From 38e281857780de3b77eba143140adfbc113fa669 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 15:40:15 +0800 Subject: [PATCH 1/3] session self-heal: zombie plugin lanes degrade to proxy tools, idle nudges suppress, 524 summaries learn streaming (#2155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/session-self-heal.ts: per-request detector (SELF_HEAL_WINDOW=5). D2 zombie plugin lane (plugin removed, session still bound: headerless + no bili tools on the wire + no reduction across 5 nudged rounds) degrades to proxy mode — one pluginMode flip re-injects the ACP tools wire-side, keeps the nudge; falls back to suppress-nudge when injectTool is off. pluginLaneRestore() runs BEFORE the pluginMode flip so the first header-bearing request is already plugin mode (the sticky pluginAgent must not be the restore signal). D1 nudge-idle (5 nudged rounds, zero reduction) suppresses the nudge at all four willInjectNudge gates until a reduction/tool-use resumes. - preflight: a non-streaming summary killed by HTTP 524/504 stops burning in-place retries — first hit learns metadata.preflightStreamSummary and re-requests as SSE (#2133 lane, auto-armed). - observability: metadata.selfHeal {detected, action, since} in /__bili/sessions + web UI heal badge + one [self-heal] log line per transition; bili plugin remove best-effort warns about live sessions of that client seen in the last 10 minutes (2.5s timeout, silent on failure). - tests/issue2155-self-heal.test.ts: 12 tests (state machine unit + zombie degrade/recover e2e + nudge-idle e2e + 524 learn e2e + CLI warn). - docs: CLIENTS.md en/zh (zcode open sessions after removal), TECHNICAL-NOTES.md en/zh (detector constants + remedies). --- CLIENTS.md | 12 + CLIENTS.zh-CN.md | 1 + TECHNICAL-NOTES.md | 40 +++ TECHNICAL-NOTES.zh-CN.md | 10 + src/cli.ts | 7 +- src/plugin-install.ts | 30 +- src/preflight.ts | 25 +- src/server.ts | 43 ++- src/session-self-heal.ts | 255 ++++++++++++++++ src/web/client.ts | 2 + src/web/i18n.ts | 10 + src/web/sessions-data.ts | 10 + tests/issue2155-self-heal.test.ts | 473 ++++++++++++++++++++++++++++++ 13 files changed, 908 insertions(+), 10 deletions(-) create mode 100644 src/session-self-heal.ts create mode 100644 tests/issue2155-self-heal.test.ts diff --git a/CLIENTS.md b/CLIENTS.md index d7b7762293..9b3d830a5f 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -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 diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index ed6202e71a..af02512878 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -92,6 +92,7 @@ fork 继承同一面;Antigravity 自带用户插件系统 —— `plugins/ 三种对齐模式:`/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 /dist/zcode/bootstrap-hook.js`)、注册 stdio MCP server `mcp.servers.bili`(`node /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:/bili/<上游>`(你设的自定义 baseURL 原样保留在包装之内)。两代 store 都处理:legacy `~/.zcode/v2/config.json`(`provider..options.baseURL`)与 v3.14+ personal store `~/.zcode/v2/provider_config.json`(`config.providerConfigRules.providerRules[].config.api.baseUrl`)—— 两者并存时以新 store 为准(其中哪些条目路由、哪些被跳过见下方路由范围)。原始文件按每次用户编辑快照到 `.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 账号。无法安全包装的条目会被跳过并记录原因,而非静默丢弃: diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 73693f1bf3..4890a274fe 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -298,3 +298,43 @@ 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. + +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 ` 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**. diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index a7caff6087..fdd6c3302f 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -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)同一学习存储,自动武装。 + +可观测:`session.metadata.selfHeal = { detected, action, since }` 进 `/__bili/sessions`、web UI 挂"自愈"徽标、每次转换一行 `[self-heal]` 日志(检测+恢复)。`bili plugin remove ` 尽力查询活代理(instance 文件 → `GET /__bili/sessions`,2.5 秒超时,失败静默),该客户端近 **10 分钟**内有活跃会话时打印提示。 diff --git a/src/cli.ts b/src/cli.ts index d099f93ef1..02cdc809a8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -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"; @@ -486,7 +486,10 @@ export async function main(): Promise { } 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); diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 1749d37d18..ce39c2bf72 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -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"; @@ -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 ` + * 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 { + 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> }; + 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], diff --git a/src/preflight.ts b/src/preflight.ts index 49731e4de0..034dee89e4 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -740,6 +740,17 @@ async function summarizeRange(deps: PreflightDeps, content: string, startRef: st try { return await requestSummary(deps, system, content, stream, includeMaxOutputTokens); } catch (err) { + if (err instanceof UpstreamHttpError && !stream && (err.status === 524 || err.status === 504)) { + // #2155 D3: first-hit learn — the non-streaming summary call + // timed out at the gateway. Flip this session to SSE summaries + // (persisted, same slot as the #626/#2133 learn) and retry once; + // the streaming attempt itself keeps normal transient retry + // semantics inside requestSummaryBody. + deps.session.metadata.preflightStreamSummary = true; + stream = true; + deps.log("info", `[preflight] non-streaming summary timed out at the gateway (HTTP ${err.status}); retrying with SSE (learned for this session, #2155)`); + continue; + } if (err instanceof UpstreamHttpError && err.status === 400) { let adapted = false; if (!stream && STREAM_REQUIRED_RE.test(err.body)) { @@ -803,7 +814,7 @@ class SummaryTransportError extends Error { } } -async function requestSummaryBody(deps: PreflightDeps, body: string): Promise { +async function requestSummaryBody(deps: PreflightDeps, body: string, stream: boolean): Promise { const maxAttempts = replayMaxAttempts(); for (let attempt = 1; ; attempt++) { deps.signal?.throwIfAborted(); @@ -826,6 +837,16 @@ async function requestSummaryBody(deps: PreflightDeps, body: string): Promise { - const text = await requestSummaryBody(deps, JSON.stringify(summaryPayload(deps.protocol, deps.model, system, content, stream, includeMaxOutputTokens, safeHost(deps.url), deps.config.modelContextLimit, deps.billingBlock))); + const text = await requestSummaryBody(deps, JSON.stringify(summaryPayload(deps.protocol, deps.model, system, content, stream, includeMaxOutputTokens, safeHost(deps.url), deps.config.modelContextLimit, deps.billingBlock)), stream); let json: unknown; try { json = JSON.parse(text); diff --git a/src/server.ts b/src/server.ts index 9b7e236ece..883103e446 100644 --- a/src/server.ts +++ b/src/server.ts @@ -50,6 +50,7 @@ import { } from "acp-kernel/wire"; import { responsesToCoreWithToolImages as responsesToCore, patchResponsesInputWithToolImages as patchResponsesInput, mergeAdjacentConfigurationUpdates } from "./responses-tool-output.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "./fold-reconcile.js"; +import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js"; import { diagnoseSuccessWithoutUsage, getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, withSessionLock, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, snapshotMessages, applyCompactionArchive, detectUnannouncedHistoryRewrite, markCompactionBoundary, storeEffectiveConfig, foldCoverage, splitSessionWarnings, REWRITE_MIN_INCOMING_TOTAL } from "./session.js"; import { detectStaleInstall } from "./update.js"; import { getAdvisoryState, cannotResolveTarget } from "./advisory.js"; @@ -2753,7 +2754,19 @@ async function handle( // a USER message (leaving it at its anchor) so strict backends (SGLang: // exactly one system at index 0, #377) accept it and the head system // message stays byte-stable for the prefix cache. - const pluginMode = pluginAgent !== undefined; + // + // #2155 self-heal degrade: a plugin-bound session whose live plugin + // lane died (plugin removed, MCP subprocess gone) is flipped here + // back to proxy mode — the proxy re-injects the ACP tools wire-side + // and owns compression again, instead of nudging a session whose + // tools are gone. The binding (metadata.pluginAgent) is kept so the + // session can be restored when the lane returns. + // NOTE: the restore signal is the LIVE HEADER, not pluginAgent — the + // sticky binding keeps pluginAgent defined on headerless zombie + // requests, and restoring on that would clear the degrade one round + // after arming it (the session never actually degraded). + if (pluginAgent !== undefined) pluginLaneRestore(session, pluginAgentHeader(req.headers) !== undefined, log); + const pluginMode = pluginAgent !== undefined && !pluginLaneDegraded(session); // [#1097/#1271] Stamp the resolved CCR policy. acp_retrieve needs a tool // channel that can round-trip the full original, so CCR arms only where // that channel exists and is resolvable: proxy mode always (the proxy @@ -3147,6 +3160,9 @@ async function handle( // retry path) suppresses the fail-fast response — forward() answers // with the original upstream 400 instead, preserving today's // client-visible contract when the payload cannot be rescued. + // #2155: self-heal evaluates once per HTTP request — the refold + // re-runs prepare below but must not double-count a round. + let selfHealRoundDone = false; const runPreparedPipeline = async ( respondFailFast: boolean, overflowWindow?: number, @@ -3235,6 +3251,21 @@ async function handle( return { body: forwardBody, prepared: null }; } prepared = await runPrepare(); + // #2155 self-heal round: one evaluation per request, on the + // nudge-carrying prepared result (bypass lanes have nudge + // undefined and the hook no-ops inside). Side requests + // (title-gen etc.) never carry a nudge, so they cannot burn + // zombie credit either. + if (!selfHealRoundDone && prepared.nudge !== undefined) { + selfHealRoundDone = true; + evaluateSelfHealRound(session, { + pluginHeaderPresent: pluginAgentHeader(req.headers) !== undefined, + biliToolsDeclared: biliToolsDeclaredOnWire(parsed, protocol), + nudgeActive: opts.compress.injectNudge && !nudgeSuppressed(session) && (prepared.nudge.shouldInject || emergencyNudge(prepared.nudge)), + biliToolUses: countBiliToolUses(prepared.processedMessages), + degradeAvailable: opts.compress.injectTool && !knobNoInjectTool(), + }, log); + } if (!countTokens && !responsesCompact) { const outcome = await preflightCompressIfNeeded( prepared, @@ -4063,7 +4094,9 @@ async function prepareAnthropic( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); + // #2155: a self-heal-suppressed session (nudge idle / zombie fallback) + // stops nagging — including the emergency path, per session. + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && !nudgeSuppressed(session) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = stripReasoning(stripKernelSummaries(turn.messages, turn.state)); // #1001: a silent client history rewrite takes the same archive+prune path @@ -4308,7 +4341,7 @@ async function prepareOpenai( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && !nudgeSuppressed(session) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = stripReasoning(stripKernelSummaries(turn.messages, turn.state)); // #1001: a silent client history rewrite takes the same archive+prune path @@ -4574,7 +4607,7 @@ async function prepareGoogle( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && !nudgeSuppressed(session) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, model, willInjectNudge)); processedMessages = stripKernelSummaries(turn.messages, turn.state); applyCompactionArchive(session, activeBefore, new Set(msgs.map((m) => m.id)), log); @@ -4881,7 +4914,7 @@ async function prepareResponses( if (t) session.meta.title = t; } log("info", diagTagSummary(turn.messages, sessionId, "text-only")); - const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && !isCompactionTrigger && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); + const willInjectNudge = opts.compress.injectNudge && !!turn.nudge && shouldInject && !isCompactionTrigger && !nudgeSuppressed(session) && (turn.nudge.shouldInject || emergencyNudge(turn.nudge)); log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge)); processedMessages = repairResponsesAssistantOrdering(stripReasoning(stripKernelSummaries(turn.messages, turn.state)), originalMessages); reapOrphansLogged(session, msgs, log, sessionId); diff --git a/src/session-self-heal.ts b/src/session-self-heal.ts new file mode 100644 index 0000000000..b3dc724c72 --- /dev/null +++ b/src/session-self-heal.ts @@ -0,0 +1,255 @@ +import type { CoreMessage } from "acp-kernel"; +import { PROXY_TOOL_NAMES } from "./compress-tool.js"; +import type { Session } from "./session.js"; + +/** + * #2155 session self-heal: a stuck session must not spin forever. + * + * Two degradation shapes, both detected on the request path (per prepared + * round, evaluated once per HTTP request — the prepare pipeline can re-run + * for overflow refold, see runPreparedPipeline): + * + * D2 — zombie plugin session. The client was plugin-bound + * (session.metadata.pluginAgent, sticky by design: #1426) but the + * plugin lane has since died (e.g. `bili plugin remove zcode` while a + * client window stays open — the client's MCP subprocess is gone, so + * requests keep arriving with the session header but WITHOUT the + * live plugin markers: no x-bili-plugin header and no bili tool + * declarations in the request's tools array). The proxy still nudges + * (~89% usage every 30-60s) but the model's compression tools are + * gone (plugin mode suppresses wire injection), so the model spins on + * dead mcp__bili__* tools and nothing ever shrinks. + * Remedy of first resort: DEGRADE the session to proxy mode — flip + * pluginMode off, the proxy re-injects the ACP tools wire-side and + * owns compression server-side again. The session keeps working + * instead of being silenced. When wire injection is globally off + * (compress.injectTool=false) the degrade is unavailable and the + * fallback remedy is nudge suppression. + * + * D1 — nudge idle loop (any mode). The proxy keeps injecting the + * compression nudge but no reduction ever lands (no new block, no + * lastCompress change, no bili tool use in the re-sent history). + * After SELF_HEAL_WINDOW consecutive idle rounds the session is + * telling us the nudge will not be acted on — stop injecting it + * (per-session, incl. the emergency path; equivalent to + * compress.injectNudge=false for this session only). Any later + * reduction lifts the suppression automatically. + * + * Recovery is evidence-based: the degrade lifts only when the live plugin + * lane comes back (header or declared tools), the suppression lifts only + * when compression actually resumes (reduction or bili tool use). State is + * carried in session.metadata.selfHeal = { detected, action, since } so it + * survives proxy restarts with the session snapshot (#499) and is visible + * on /__bili/sessions. + */ + +/** Consecutive idle/zombie rounds before a remedy arms. Constant by design + * (#2155: no new config knobs); recorded in TECHNICAL-NOTES.md. */ +export const SELF_HEAL_WINDOW = 5; + +export type SelfHealAction = "degrade-to-proxy" | "suppress-nudge"; + +export type SelfHealState = { + /** "plugin-lane-gone" (D2) | "nudge-idle" (D1) */ + detected: "plugin-lane-gone" | "nudge-idle"; + action: SelfHealAction; + since: number; +}; + +export type SelfHealStateView = { detected: string; action: string; since: number }; + +type SelfHealCounters = { + /** last observed reduction fingerprint (nextBlockId:lastCompress.at) */ + lastReductionKey: string | undefined; + zombieStreak: number; + idleStreak: number; +}; + +const counters = new WeakMap(); + +export function selfHealOf(session: Session): SelfHealStateView | undefined { + const raw = session.metadata["selfHeal"]; + if (raw === null || typeof raw !== "object") return undefined; + const rec = raw as Record; + if (typeof rec["detected"] !== "string" || typeof rec["action"] !== "string" || typeof rec["since"] !== "number") return undefined; + return { detected: rec["detected"], action: rec["action"], since: rec["since"] }; +} + +/** True when this session's nudge injection is suppressed (D1 remedy, or the + * D2 fallback when the degrade is unavailable). Gates every willInjectNudge + * site so both the regular and the emergency path go quiet together. */ +export function nudgeSuppressed(session: Session): boolean { + return selfHealOf(session)?.action === "suppress-nudge"; +} + +/** True when a zombie plugin session has been degraded back to proxy mode + * (tools re-injected wire-side, the proxy owns compression again). */ +export function pluginLaneDegraded(session: Session): boolean { + return selfHealOf(session)?.action === "degrade-to-proxy"; +} + +/** Restore a degraded session to plugin mode the moment the plugin header + * reappears (the client re-registered). Called BEFORE the pluginMode flip so + * the very first header-bearing request is already served in plugin mode — + * otherwise the degrade would lag one round (pluginMode is computed before + * the round's evaluation hook runs). */ +export function pluginLaneRestore(session: Session, headerPresent: boolean, log: LogFn): boolean { + if (!headerPresent || selfHealOf(session)?.action !== "degrade-to-proxy") return false; + clearSelfHeal(session); + const st = counters.get(session); + if (st) { + st.zombieStreak = 0; + st.idleStreak = 0; + } + log("info", `[${session.id}] [self-heal] plugin lane is back (plugin header) — session restored to plugin mode`); + return true; +} + +function clearSelfHeal(session: Session): void { + delete session.metadata["selfHeal"]; +} + +function armSelfHeal(session: Session, detected: "plugin-lane-gone" | "nudge-idle", action: SelfHealAction): void { + session.metadata["selfHeal"] = { detected, action, since: Date.now() }; +} + +function reductionKey(session: Session): string { + return `${session.state.nextBlockId}:${session.lastCompress?.at ?? 0}`; +} + +/** A bili-owned tool name as it can appear on the wire: the proxy-injected + * bare ACP names (compress/…, also used by pi/omp extensions) or the + * MCP-prefixed form (mcp__bili__compress, zcode/claude-code lanes). */ +export function isBiliToolName(name: string): boolean { + return name.startsWith("mcp__bili__") || PROXY_TOOL_NAMES.has(name); +} + +export function countBiliToolUses(messages: CoreMessage[]): number { + let n = 0; + for (const m of messages) if (m.toolName !== undefined && isBiliToolName(m.toolName)) n += 1; + return n; +} + +export type SelfHealRoundInputs = { + /** x-bili-plugin header present on this request */ + pluginHeaderPresent: boolean; + /** the request's own tools array declares bili tools (live MCP lane) */ + biliToolsDeclared: boolean; + /** a nudge was actually injected into this round's payload */ + nudgeActive: boolean; + /** bili tool_use entries in the re-sent history (plugin-mode evidence the agent is still compressing) */ + biliToolUses: number; + /** wire tool injection is available for the degrade remedy */ + degradeAvailable: boolean; +}; + +type LogFn = (level: "info" | "warn", message: string) => void; + +/** Evaluate one prepared round. Pure w.r.t. inputs; mutates only the WeakMap + * counters and (on transitions) session.metadata.selfHeal. Called once per + * HTTP request after prepare (nudge-carrying rounds only — bypass lanes + * never reach it). */ +export function evaluateSelfHealRound(session: Session, inputs: SelfHealRoundInputs, log: LogFn): void { + const st = counters.get(session) ?? { lastReductionKey: undefined, zombieStreak: 0, idleStreak: 0 }; + counters.set(session, st); + const key = reductionKey(session); + const reduction = st.lastReductionKey !== undefined && key !== st.lastReductionKey; + st.lastReductionKey = key; + + const active = selfHealOf(session); + // Recovery: evidence first, detection second — a recovered session can + // re-arm later if it goes idle again (streaks restart from this round). + if (active !== undefined) { + if (active.action === "degrade-to-proxy" && inputs.pluginHeaderPresent) { + // NOTE: biliToolsDeclared is deliberately NOT a recovery signal + // here — after degrading, OUR OWN wire injection puts the ACP tools + // on every request, so "tools on the wire" would clear the degrade + // on the first degraded round and the session would oscillate + // (degrade -> clear -> zombie streak -> degrade). Only the plugin + // header (the client actually re-registered) restores plugin mode. + clearSelfHeal(session); + st.zombieStreak = 0; + st.idleStreak = 0; + log("info", `[${session.id}] [self-heal] plugin lane is back (live marker on request) — session restored to plugin mode`); + } else if (active.action === "suppress-nudge" && (reduction || inputs.biliToolUses > 0)) { + clearSelfHeal(session); + st.zombieStreak = 0; + st.idleStreak = 0; + log("info", `[${session.id}] [self-heal] compression resumed — nudge suppression lifted`); + } + } + + const pluginBound = typeof session.metadata["pluginAgent"] === "string"; + // Streaks advance only on rounds that actually carried a nudge — an idle + // session (no traffic, side requests) must not accumulate zombie credit, + // and a reduction or an agent-side tool use always resets both streaks. + if (inputs.nudgeActive) { + const zombieSignal = pluginBound && !inputs.pluginHeaderPresent && !inputs.biliToolsDeclared; + if (reduction || inputs.biliToolUses > 0) { + st.zombieStreak = 0; + st.idleStreak = 0; + } else { + st.idleStreak += 1; + st.zombieStreak = zombieSignal ? st.zombieStreak + 1 : 0; + } + } + + if (selfHealOf(session) !== undefined) return; + if (pluginBound && st.zombieStreak >= SELF_HEAL_WINDOW) { + if (inputs.degradeAvailable) { + armSelfHeal(session, "plugin-lane-gone", "degrade-to-proxy"); + log("warn", `[${session.id}] [self-heal] plugin lane gone for ${st.zombieStreak} nudged rounds (no x-bili-plugin header, no bili tools declared) — session degraded to proxy mode: ACP tools re-injected wire-side, nudge kept`); + } else { + armSelfHeal(session, "plugin-lane-gone", "suppress-nudge"); + log("warn", `[${session.id}] [self-heal] plugin lane gone for ${st.zombieStreak} nudged rounds — wire injection unavailable (compress.injectTool=false), nudge suppressed for this session`); + } + st.zombieStreak = 0; + st.idleStreak = 0; + return; + } + if (st.idleStreak >= SELF_HEAL_WINDOW) { + armSelfHeal(session, "nudge-idle", "suppress-nudge"); + log("warn", `[${session.id}] [self-heal] nudge idle for ${st.idleStreak} rounds (injected but nothing ever compressed) — nudge suppressed for this session until compression resumes`); + st.idleStreak = 0; + st.zombieStreak = 0; + } +} + +/** Live-lane evidence on the request's own tool declarations. In plugin mode + * the CLIENT declares the bili tools (MCP-registered: mcp__bili__* for + * zcode/claude-code lanes, bare ACP names for pi/omp extensions) — a healthy + * bound session re-declares them on every main request, while a zombie (the + * MCP subprocess removed mid-session) stops declaring them. Tolerant by + * design: unknown shapes answer false and the header signal still carries + * the healthy-plugin case. */ +export function biliToolsDeclaredOnWire(parsed: unknown, protocol: string): boolean { + if (parsed === null || typeof parsed !== "object") return false; + const body = parsed as Record; + const tools = body["tools"]; + if (!Array.isArray(tools)) return false; + for (const t of tools) { + if (t === null || typeof t !== "object") continue; + const rec = t as Record; + // anthropic / responses: flat { name }. + const flat = typeof rec["name"] === "string" ? (rec["name"] as string) : undefined; + if (flat !== undefined && isBiliToolName(flat)) return true; + // openai chat: { function: { name } }. + const fn = rec["function"]; + if (fn !== null && typeof fn === "object") { + const inner = (fn as Record)["name"]; + if (typeof inner === "string" && isBiliToolName(inner)) return true; + } + // google: { functionDeclarations: [{ name }] }. + const decls = rec["functionDeclarations"]; + if (Array.isArray(decls)) { + for (const d of decls) { + if (d !== null && typeof d === "object") { + const n = (d as Record)["name"]; + if (typeof n === "string" && isBiliToolName(n)) return true; + } + } + } + } + void protocol; + return false; +} diff --git a/src/web/client.ts b/src/web/client.ts index 5ff6e9bece..412ac7c077 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -232,6 +232,7 @@ export const WEB_CLIENT = `(function () { const href = "#/session/" + encodeURIComponent(s.id); return '' + escapeHtml(name) + "" + (live ? ' ' + t("common.live") + "" : "") + + (s.selfHeal ? ' ' + t("det.self_heal_short") + "" : "") + '' + escapeHtml(s.id) + ""; } // SAVED column prefers ledger-derived net savings; pre-tagging sessions fall back @@ -865,6 +866,7 @@ export const WEB_CLIENT = `(function () { if (d.label && d.label !== d.id) kv(parts, t("common.label"), d.label); kv(parts, t("common.protocol"), d.protocol || null, true); kv(parts, t("det.client_hint"), d.clientHint || null, true); + if (d.selfHeal) kv(parts, t("det.self_heal"), (d.selfHeal.action === "degrade-to-proxy" ? t("det.self_heal_degrade_to_proxy") : t("det.self_heal_suppress_nudge")) + " · " + d.selfHeal.detected + " · " + timeAgo(d.selfHeal.since), true); kv(parts, t("common.upstream"), hostOf(d.upstreamOrigin) || null, true); kv(parts, t("det.version"), d.biliVersion || null, true); kv(parts, t("det.active_pack"), d.activePack || null, true); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index ea384792fa..d7a60cc32f 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -212,6 +212,11 @@ export const MESSAGES: Record> = { "det.fold_h": "折叠后命中率", "det.fold_t": "累计回补 T", "det.client_hint": "客户端", + "det.self_heal": "自愈状态", + "det.self_heal_tip": "会话卡死自愈已接管:详见会话详情(#2155)", + "det.self_heal_short": "自愈", + "det.self_heal_degrade_to_proxy": "插件车道已死 → 已降级代理模式(工具已回注)", + "det.self_heal_suppress_nudge": "压缩提醒空转 → 已静默(恢复压缩自动解除)", "det.legend_base": "系统提示词基线(实测 · 不可压缩)", "det.legend_base_est": "基线估算(系统提示词与工具等不可压缩部分)", "det.blocks_title": "压缩块", @@ -566,6 +571,11 @@ export const MESSAGES: Record> = { "det.fold_h": "post-fold hit %", "det.fold_t": "cumulative repay T", "det.client_hint": "client", + "det.self_heal": "Self-heal", + "det.self_heal_tip": "Stuck-session self-heal has taken over — see session detail (#2155)", + "det.self_heal_short": "heal", + "det.self_heal_degrade_to_proxy": "plugin lane gone → degraded to proxy mode (tools re-injected)", + "det.self_heal_suppress_nudge": "nudge idle loop → suppressed (lifts when compression resumes)", "det.legend_base": "system prompt baseline (measured, not compressible)", "det.legend_base_est": "baseline est. (system prompt & tools, not compressible)", "det.blocks_title": "Compression blocks", diff --git a/src/web/sessions-data.ts b/src/web/sessions-data.ts index 4b21d7f958..f51c103a1b 100644 --- a/src/web/sessions-data.ts +++ b/src/web/sessions-data.ts @@ -510,6 +510,15 @@ function summaryOf(s: SummarySource, live: boolean): WebSessionSummary { } // #1426: which client this session came from (plugin stamp wins, then sniff/UA hint). const metaRec = s.metadata as Record; + // #2155: active self-heal state (zombie plugin degrade / nudge + // suppression) — surface it so the web list can badge the session. + const shRaw = metaRec["selfHeal"]; + const selfHeal = shRaw !== null && typeof shRaw === "object" + && typeof (shRaw as Record)["detected"] === "string" + && typeof (shRaw as Record)["action"] === "string" + && typeof (shRaw as Record)["since"] === "number" + ? { detected: (shRaw as Record)["detected"] as string, action: (shRaw as Record)["action"] as string, since: (shRaw as Record)["since"] as number } + : undefined; const clientHint = typeof metaRec["pluginAgent"] === "string" && metaRec["pluginAgent"] ? metaRec["pluginAgent"] as string : typeof metaRec["clientHint"] === "string" && metaRec["clientHint"] ? metaRec["clientHint"] as string : ""; @@ -534,6 +543,7 @@ function summaryOf(s: SummarySource, live: boolean): WebSessionSummary { cacheHitPct: hitPct(inputTokens, cachedTokens), blocks: s.state.blocks.length, ...(typeof s.metadata.effectiveContextLimit === "number" ? { contextWindow: s.metadata.effectiveContextLimit } : {}), + ...(selfHeal ? { selfHeal } : {}), lastSeen: new Date(s.lastSeen).toISOString(), ...(s.restored ? { restored: true } : {}), ...(hasLedger ? { hasLedger: true } : {}), diff --git a/tests/issue2155-self-heal.test.ts b/tests/issue2155-self-heal.test.ts new file mode 100644 index 0000000000..f0e4a59d45 --- /dev/null +++ b/tests/issue2155-self-heal.test.ts @@ -0,0 +1,473 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import type { CoreMessage } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, type Session } from "../src/session.ts"; +import { + SELF_HEAL_WINDOW, + biliToolsDeclaredOnWire, + countBiliToolUses, + evaluateSelfHealRound, + nudgeSuppressed, + pluginLaneDegraded, +} from "../src/session-self-heal.ts"; +import { warnActivePluginSessions } from "../src/plugin-install.ts"; + +// #2155: stuck-session self-heal. +// D2 zombie plugin lane — the plugin was uninstalled but already-open client +// windows keep the session plugin-bound (sticky metadata) and headerless: +// nudges keep firing against a model that no longer has the bili tools, the +// model loops calling a gone MCP tool. Detection = 5 consecutive nudged +// rounds with no plugin header, no bili tools on the wire, no reduction. +// Remedies: degrade-to-proxy (give the wire-injected tools back, primary) +// or suppress-nudge (when injection is unavailable). +// D1 nudge idle — same loop shape without a plugin binding: suppress the +// nudge until a compression reduction proves it useful again. +// D3 — a non-streaming preflight summary dying at a Cloudflare 524 burns +// 100s per retry; learn stream-once on FIRST 524/504 (#2133 lane, auto). + +const noop = () => {}; + +function mkSession(): Session { + return { + id: "s1", + metadata: {}, + state: { nextBlockId: 1 }, + lastCompress: undefined, + } as unknown as Session; +} + +function mkCoreMessages(toolNames: string[]): CoreMessage[] { + return toolNames.map((toolName) => ({ role: "assistant", toolName }) as CoreMessage); +} + +// ---- unit: state machine ---------------------------------------------------- + +test("unit: zombie plugin lane arms degrade-to-proxy after the window", () => { + const s = mkSession(); + s.metadata.pluginAgent = "zcode"; + const logs: string[] = []; + for (let i = 0; i < SELF_HEAL_WINDOW - 1; i++) { + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: true }, + noop, + ); + assert.equal(pluginLaneDegraded(s), false, `round ${i + 1}: not yet`); + } + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: true }, + (level: string, msg: string) => logs.push(`${level}:${msg}`), + ); + assert.equal(pluginLaneDegraded(s), true, "armed at exactly the window"); + assert.equal(nudgeSuppressed(s), false, "degrade keeps the nudge — the tools are back"); + const sh = s.metadata.selfHeal as { detected: string; action: string }; + assert.equal(sh.detected, "plugin-lane-gone"); + assert.equal(sh.action, "degrade-to-proxy"); + assert.ok(logs.some((l) => l.includes("plugin lane gone")), "detection is logged"); +}); + +test("unit: degrade unavailable falls back to suppress-nudge", () => { + const s = mkSession(); + s.metadata.pluginAgent = "zcode"; + for (let i = 0; i < SELF_HEAL_WINDOW; i++) { + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: false }, + noop, + ); + } + assert.equal(pluginLaneDegraded(s), false, "no degrade when injectTool is off"); + assert.equal(nudgeSuppressed(s), true, "falls back to suppression"); + assert.equal((s.metadata.selfHeal as { action: string }).action, "suppress-nudge"); +}); + +test("unit: healthy plugin lane (header present) never arms", () => { + const s = mkSession(); + s.metadata.pluginAgent = "zcode"; + for (let i = 0; i < SELF_HEAL_WINDOW + 4; i++) { + evaluateSelfHealRound( + s, + { pluginHeaderPresent: true, biliToolsDeclared: true, nudgeActive: true, biliToolUses: 1, degradeAvailable: true }, + noop, + ); + } + assert.equal(s.metadata.selfHeal, undefined); +}); + +test("unit: bili tool uses reset the streaks — no arm on intermittent health", () => { + const s = mkSession(); + s.metadata.pluginAgent = "zcode"; + for (let i = 0; i < SELF_HEAL_WINDOW - 1; i++) { + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: true }, + noop, + ); + } + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: true, nudgeActive: true, biliToolUses: 2, degradeAvailable: true }, + noop, + ); + evaluateSelfHealRound( + s, + { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: true }, + noop, + ); + assert.equal(pluginLaneDegraded(s), false, "streak restarted after the healthy round"); +}); + +test("unit: suppress-nudge lifts when a compression reduction resumes", () => { + const s = mkSession(); + for (let i = 0; i < SELF_HEAL_WINDOW; i++) { + evaluateSelfHealRound(s, { pluginHeaderPresent: false, biliToolsDeclared: true, nudgeActive: true, biliToolUses: 0, degradeAvailable: false }, noop); + } + assert.equal(nudgeSuppressed(s), true); + s.state.nextBlockId = 2; // a fold happened + const logs: string[] = []; + evaluateSelfHealRound(s, { pluginHeaderPresent: false, biliToolsDeclared: true, nudgeActive: true, biliToolUses: 0, degradeAvailable: false }, (l: string, m: string) => logs.push(`${l}:${m}`)); + assert.equal(nudgeSuppressed(s), false, "suppression lifted by the reduction"); + assert.equal(s.metadata.selfHeal, undefined, "state cleared"); + assert.ok(logs.some((x) => x.includes("suppression lifted")), "recovery is logged"); +}); + +test("unit: degrade-to-proxy clears when the plugin header comes back", () => { + const s = mkSession(); + s.metadata.pluginAgent = "zcode"; + for (let i = 0; i < SELF_HEAL_WINDOW; i++) { + evaluateSelfHealRound(s, { pluginHeaderPresent: false, biliToolsDeclared: false, nudgeActive: true, biliToolUses: 0, degradeAvailable: true }, noop); + } + assert.equal(pluginLaneDegraded(s), true); + const logs: string[] = []; + evaluateSelfHealRound(s, { pluginHeaderPresent: true, biliToolsDeclared: true, nudgeActive: true, biliToolUses: 1, degradeAvailable: true }, (l: string, m: string) => logs.push(`${l}:${m}`)); + assert.equal(pluginLaneDegraded(s), false, "plugin mode restored"); + assert.equal(s.metadata.selfHeal, undefined); + assert.ok(logs.some((x) => x.includes("plugin lane is back")), "recovery is logged"); +}); + +test("unit: countBiliToolUses counts mcp-prefixed and bare ACP tool names", () => { + const msgs = mkCoreMessages(["mcp__bili__compress", "compress", "web_search", "mcp__other__thing"]); + assert.equal(countBiliToolUses(msgs), 2); + assert.equal(countBiliToolUses([]), 0); +}); + +test("unit: biliToolsDeclaredOnWire sees every protocol's tool shape", () => { + assert.equal(biliToolsDeclaredOnWire({ tools: [{ name: "mcp__bili__compress" }] }, "anthropic"), true); + assert.equal(biliToolsDeclaredOnWire({ tools: [{ name: "web_search" }] }, "anthropic"), false); + assert.equal(biliToolsDeclaredOnWire({ tools: [{ type: "function", function: { name: "compress" } }] }, "openai"), true); + assert.equal(biliToolsDeclaredOnWire({ tools: [{ type: "function", function: { name: "bash" } }] }, "openai"), false); + assert.equal( + biliToolsDeclaredOnWire({ tools: [{ functionDeclarations: [{ name: "mcp__bili__compress" }] }] }, "google"), + true, + ); + assert.equal(biliToolsDeclaredOnWire({}, "openai"), false); +}); + +// ---- integration: zombie degrade (openai wire) ------------------------------- + +function okJson(promptTokens: number): string { + return JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: promptTokens, completion_tokens: 3, total_tokens: promptTokens + 3 }, + }); +} + +function turn2Compressible(): Record[] { + const longText = "y".repeat(20_000); + const filler: { role: "user" | "assistant"; content: string }[] = []; + for (let i = 1; i <= 12; i++) { + filler.push({ role: "user", content: `q${i} ` + "f".repeat(997) }); + filler.push({ role: "assistant", content: `a${i} ` + "e".repeat(997) }); + } + return [ + { role: "user", content: "hello" }, + { role: "assistant", content: "ok" }, + { role: "user", content: "continue" }, + { role: "assistant", content: longText }, + ...filler, + { role: "user", content: "now summarize" }, + ]; +} + +async function startProxyUpstream(window: number, sessionId: string, respond: (raw: string, parsed: Record, res: http.ServerResponse) => void) { + const received: Record[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let parsed: Record = {}; + try { + parsed = JSON.parse(raw) as Record; + } catch { + parsed = {}; + } + received.push(parsed); + respond(raw, parsed, res); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, host: "127.0.0.1", upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upPort}`]: { models: { m: { context: window } } } }, + modelContextLimit: window, kernelConfig: defaultConfig(window), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", + log: false, debug: false, passthrough: false, autoUpdate: false, + mitm: { enabled: false, domains: [] }, + compat: { roles: {} }, streamErrorShape: "protocol", passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", advisoryCheck: false, releaseNotesCheck: false, + } as ProxyOptions); + await once(proxy, "listening"); + const pPort = (proxy.address() as { port: number }).port; + const send = async (headers: Record, body: Record) => { + const url = `http://127.0.0.1:${pPort}/bili/http://127.0.0.1:${upPort}/v1/chat/completions`; + const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-acp-session": sessionId, ...headers }, body: JSON.stringify(body) }); + await r.text(); + return r.status; + }; + return { received, proxy, upstream, send }; +} + +test("integration: zombie plugin session degrades to proxy tool injection, then recovers when the header returns", async () => { + const WINDOW = 100_000; + const { received, proxy, upstream, send } = await startProxyUpstream(WINDOW, "zomb-d2", (_raw, _parsed, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(okJson(57_600)); // 72% of the 80k reserved window -> emergency nudge every round + }); + try { + const body = { model: "m", max_tokens: 20_000, messages: turn2Compressible() }; + // r1 binds the plugin lane (header present -> plugin mode, tools stay client-side). + await send({ "x-bili-plugin": "zcode" }, body); + // r2..r6: headerless, no tools on the wire — the zombie shape. + for (let i = 0; i < SELF_HEAL_WINDOW; i++) { + const status = await send({}, body); + assert.equal(status, 200); + } + const bound = listSessions().find((x) => x.id === "zomb-d2"); + assert.ok(bound, "session exists"); + assert.equal(bound!.metadata.pluginAgent, "zcode", "sticky binding survives the uninstalled plugin"); + assert.ok(bound!.metadata.selfHeal, "self-heal state recorded on the session"); + assert.equal((bound!.metadata.selfHeal as { action: string }).action, "degrade-to-proxy"); + // r7: degraded — the wire injection is back. + await send({}, body); + const toolNames = ((received[received.length - 1]!.tools as { function?: { name?: string } }[]) ?? []).map((t) => t.function?.name); + assert.ok(toolNames!.includes("compress"), `degraded session gets the ACP tools on the wire (got ${JSON.stringify(toolNames)})`); + // r8: the plugin reappears (client reinstalled) — plugin mode wins again, + // restored on the very first header-bearing request (#2155 restore hook). + await send({ "x-bili-plugin": "zcode" }, body); + const lastTools = received[received.length - 1]!.tools; + assert.equal(lastTools, undefined, "header back -> plugin mode, no wire injection"); + const healed = listSessions().find((x) => x.id === "zomb-d2"); + assert.equal(healed!.metadata.selfHeal, undefined, "self-heal cleared on recovery"); + } finally { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + } +}); + +test("integration: nudge-idle loop (non-plugin) suppresses the nudge after the window", async () => { + const WINDOW = 100_000; + const sessionId = "idle-d1"; + const { received, proxy, upstream, send } = await startProxyUpstream(WINDOW, sessionId, (_raw, _parsed, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(okJson(57_600)); + }); + try { + const body = { model: "m", max_tokens: 20_000, messages: turn2Compressible() }; + await send({}, body); // r1 baseline — usage lands only after its own response (no nudge yet, no idle credit) + for (let i = 0; i < SELF_HEAL_WINDOW - 2; i++) await send({}, body); // r2..r4 — nudged, idle credit 3 + await send({}, body); // r5 — nudged, idle credit 4 + const before = ((received[received.length - 1]!.messages as unknown[]) ?? []).length; // nudged count + const sh = listSessions().find((x) => x.id === sessionId)!.metadata.selfHeal; + assert.equal(sh, undefined, "not yet armed at window-1 idle rounds"); + await send({}, body); // r6 — the 5th nudged idle round arms AFTER its own nudge went out + const armed = listSessions().find((x) => x.id === sessionId)!.metadata.selfHeal as { action: string }; + assert.equal(armed.action, "suppress-nudge"); + await send({}, body); // r7 runs suppressed + const suppressed = ((received[received.length - 1]!.messages as unknown[]) ?? []).length; + const nudged = ((received[received.length - 2]!.messages as unknown[]) ?? []).length; + assert.ok(nudged === before + 1 - 1, "the arming round was still nudged (baseline round carried no nudge)"); + assert.ok(suppressed === before - 1, "nudge message gone once suppression armed (back to the un-nudged count)"); + } finally { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + } +}); + +// ---- integration: D3 — 524 learns streaming summaries (#2133 lane, auto) ---- + +const STATED_OVERFLOW_BODY_128K = JSON.stringify({ + type: "error", + error: { type: "invalid_request_error", message: "prompt is too long: 130000 tokens > 128000 maximum" }, +}); + +const SUMMARY_TEXT = + "PREFLIGHT SUMMARY: the segment covered a multi-step debugging session. Key decisions: chose the preflight approach over lossy truncation because the payload must stay coherent. Files touched: src/a.ts:10, src/b.ts:20. Outcome: fixed and verified by tests."; + +function okSse(): string { + return ( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: 5000 } } })}\n\n` + + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } })}\n\n` + + `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } })}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +function summarySse(): string { + return ( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: { id: "s1", role: "assistant", usage: { input_tokens: 10 } } })}\n\n` + + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: SUMMARY_TEXT } })}\n\n` + + `event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: 0 })}\n\n` + + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 40 } })}\n\n` + + `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n` + ); +} + +function bigConversation(): Array<{ role: string; content: string }> { + const msgs: Array<{ role: string; content: string }> = []; + for (let i = 0; i < 12; i++) { + const role = i % 2 === 0 ? "user" : "assistant"; + msgs.push({ role, content: `Message ${i} of the long conversation. ` + `MARKER_${i}_content_`.repeat(250) }); + } + return msgs; +} + +test("integration: a 524 on the non-streaming summary flips the session to streaming on the first hit", async () => { + let summary524 = 0; + let streamingCall = 0; + const summaryBodies: Record[] = []; + const forwarded: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let parsed: { stream?: boolean } = {}; + try { + parsed = JSON.parse(raw) as { stream?: boolean }; + } catch { + parsed = {}; + } + if (raw.includes("must be compressed because")) { + summaryBodies.push(JSON.parse(raw) as Record); + if (parsed.stream === false) { + summary524 += 1; + res.writeHead(524, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "gateway timeout" })); + return; + } + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(summarySse()); + return; + } + forwarded.push(raw); + if (streamingCall === 0) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(STATED_OVERFLOW_BODY_128K); + } else { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(okSse()); + } + streamingCall += 1; + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, host: "127.0.0.1", upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "claude-test": { context: 400_000 } } } }, + modelContextLimit: 400_000, kernelConfig: defaultConfig(400_000), + compress: { injectTool: true, injectNudge: true }, + compat: { roles: {} }, streamErrorShape: "protocol", passthroughSource: null, autoRestartOnUpdate: false, updateTag: "latest", + advisoryCheck: false, releaseNotesCheck: false, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", + log: false, debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + try { + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`; + const body = JSON.stringify({ model: "claude-test", max_tokens: 1024, stream: true, messages: bigConversation() }); + const headers = { "content-type": "application/json", "x-acp-session": "d3-sess" }; + const r1 = await fetch(url, { method: "POST", headers, body }); + assert.equal(r1.status, 200, "the turn is rescued despite the 524"); + assert.equal(r1.headers.get("content-type"), "text/event-stream"); + await r1.text(); + assert.equal(summary524, 1, "exactly one 524 — no internal non-streaming retries burned"); + assert.equal(summaryBodies.length, 2, "one non-streaming attempt, one streaming retry"); + assert.equal(summaryBodies[0]!.stream, false); + assert.equal(summaryBodies[1]!.stream, true, "the retry goes out as SSE"); + const s = listSessions().find((x) => x.id === "d3-sess"); + assert.ok(s, "session exists"); + assert.equal(s!.metadata.preflightStreamSummary, true, "learned for the session (#2133 lane, auto)"); + const lastForward = forwarded[forwarded.length - 1]!; + assert.ok(lastForward.includes(SUMMARY_TEXT), "the fold summary made it into the rescued body"); + } finally { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + } +}); + +// ---- unit: CLI remove warn --------------------------------------------------- + +test("unit: warnActivePluginSessions reports recent live sessions and stays silent on query failure", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bilixdg-")); + const prev = process.env.XDG_STATE_HOME; + const upstream = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ sessions: [{ id: "a", clientHint: "zcode", lastSeen: new Date().toISOString() }, { id: "b", clientHint: "zcode", lastSeen: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString() }] })); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const port = (upstream.address() as { port: number }).port; + try { + process.env.XDG_STATE_HOME = dir; + fs.mkdirSync(path.join(dir, "billion-context"), { recursive: true }); + fs.writeFileSync(path.join(dir, "billion-context", "proxy-origin"), JSON.stringify({ origin: `http://127.0.0.1:${port}` })); + const note = await warnActivePluginSessions("zcode"); + assert.ok(note.includes("1 active zcode session"), `names the recent session only (got: ${note})`); + // Dead proxy: the note degrades to silence. + fs.writeFileSync(path.join(dir, "billion-context", "proxy-origin"), JSON.stringify({ origin: "http://127.0.0.1:1" })); + const silent = await warnActivePluginSessions("zcode"); + assert.equal(silent, ""); + } finally { + if (prev === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prev; + upstream.close(); + await once(upstream, "close"); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); From d9ed351e155cf588179d6899ef821a660f47fac8 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 15:52:14 +0800 Subject: [PATCH 2/3] =?UTF-8?q?preflight:=20honor=20explicit=20streamSumma?= =?UTF-8?q?ry=3Dfalse=20across=20both=20learn=20paths=20(#2155=20D3=20?= =?UTF-8?q?=C3=97=20#2133)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first-hit 524/504 SSE learn flipped the UNSET default, but #2133's explicit cascade FALSE must stay the operator's 'never stream summaries' opt-out: streamSummaryOff (PreflightDeps) blocks the 400 'stream required' learn, the new 524/504 first-hit learn, and ignores an already-armed flag. The two #2133 e2e tests now pin the explicit-OFF contract (unset routes auto-learn — covered by issue2155-self-heal tests). --- TECHNICAL-NOTES.md | 4 ++++ TECHNICAL-NOTES.zh-CN.md | 2 +- src/preflight.ts | 14 +++++++----- src/server.ts | 5 +++++ tests/preflight-stream-summary-config.test.ts | 22 +++++++++++-------- 5 files changed, 32 insertions(+), 15 deletions(-) diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 4890a274fe..55b3798c4c 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -331,6 +331,10 @@ bypass and side lanes never earn credit): 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 diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index fdd6c3302f..411459a06c 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -102,6 +102,6 @@ bili 永不拥有用户数据:每个被启动的客户端都跑在**真实 home* - **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)同一学习存储,自动武装。 +- **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 ` 尽力查询活代理(instance 文件 → `GET /__bili/sessions`,2.5 秒超时,失败静默),该客户端近 **10 分钟**内有活跃会话时打印提示。 diff --git a/src/preflight.ts b/src/preflight.ts index 034dee89e4..ef3c501d5b 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -147,6 +147,8 @@ export interface PreflightDeps { upstreamOrigin?: string; /** #2133: compress.streamSummary resolved true for this request (three-level cascade). The self-learn flag only sees 400 "stream required" rejections, so gateways that time out long non-streaming completions (Cloudflare 524) can never self-heal — this forces SSE from the first attempt instead. */ forceStreamSummary?: boolean; + /** #2155: compress.streamSummary resolved FALSE for this request (explicit operator opt-out anywhere in the cascade). Neither learn path (400 "stream required" nor the 524/504 gateway-timeout first-hit learn) may arm, and an already-armed session flag is ignored — the operator said this upstream must never stream summaries. */ + streamSummaryOff?: boolean; /** #2189: the client's billing-attribution block from the INBOUND anthropic system (extractBillingAttributionBlock). Carried into every summary call as system[0]; absent → legacy string system unchanged. */ billingBlock?: { type: "text"; text: string }; } @@ -733,14 +735,16 @@ async function summarizeRange(deps: PreflightDeps, content: string, startRef: st // at most one extra attempt per capability, in either rejection order. // #2133: compress.streamSummary forces SSE from the first attempt — the // learn path above only sees 400 "stream required" rejections, which a - // gateway timeout (524) never produces. - let stream = deps.session.metadata.preflightStreamSummary === true || deps.forceStreamSummary === true; + // gateway timeout (524) never produces. #2155: an explicit cascade FALSE + // (streamSummaryOff) opts the request out of SSE summaries entirely — both + // learn paths stay disarmed and a stale learned flag is ignored. + let stream = !deps.streamSummaryOff && (deps.session.metadata.preflightStreamSummary === true || deps.forceStreamSummary === true); let includeMaxOutputTokens = !(deps.protocol === "responses" && hasLearnedNoMaxOutputTokens(deps)); for (;;) { try { return await requestSummary(deps, system, content, stream, includeMaxOutputTokens); } catch (err) { - if (err instanceof UpstreamHttpError && !stream && (err.status === 524 || err.status === 504)) { + if (err instanceof UpstreamHttpError && !stream && !deps.streamSummaryOff && (err.status === 524 || err.status === 504)) { // #2155 D3: first-hit learn — the non-streaming summary call // timed out at the gateway. Flip this session to SSE summaries // (persisted, same slot as the #626/#2133 learn) and retry once; @@ -753,7 +757,7 @@ async function summarizeRange(deps: PreflightDeps, content: string, startRef: st } if (err instanceof UpstreamHttpError && err.status === 400) { let adapted = false; - if (!stream && STREAM_REQUIRED_RE.test(err.body)) { + if (!stream && !deps.streamSummaryOff && STREAM_REQUIRED_RE.test(err.body)) { deps.session.metadata.preflightStreamSummary = true; stream = true; adapted = true; @@ -844,7 +848,7 @@ async function requestSummaryBody(deps: PreflightDeps, body: string, stream: boo // retries once with stream:true (the #2133 self-learn semantics, // extended beyond the 400 "stream required" shape). Streaming // attempts keep the normal transient replay below. - if (failure instanceof UpstreamHttpError && !stream && (failure.status === 524 || failure.status === 504)) { + if (failure instanceof UpstreamHttpError && !stream && !deps.streamSummaryOff && (failure.status === 524 || failure.status === 504)) { throw failure; } // #2189: retrying the identical shape cannot succeed — name it and fail fast. diff --git a/src/server.ts b/src/server.ts index 883103e446..d885ea793b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -6095,6 +6095,10 @@ async function preflightCompressIfNeeded( // learn path can't see gateway timeouts (524/503), so operators behind such // gateways need a deterministic escape hatch. const forceStreamSummary = resolveCompress(opts.routes, route?.rewrittenUrl, model, opts.compress).streamSummary === true; + // #2155: the same cascade resolved FALSE is an explicit operator opt-out — + // neither learn path (400 "stream required" nor the 524/504 first-hit + // learn) may arm streaming summaries for this request's session lane. + const streamSummaryOff = resolveCompress(opts.routes, route?.rewrittenUrl, model, opts.compress).streamSummary === false; let result: PreflightResult; try { result = await preflightCompress( @@ -6118,6 +6122,7 @@ async function preflightCompressIfNeeded( unknownBaseline, upstreamOrigin: currentOrigin, forceStreamSummary, + streamSummaryOff, }, prepared.originalMessages, ); diff --git a/tests/preflight-stream-summary-config.test.ts b/tests/preflight-stream-summary-config.test.ts index e024e889c0..fcd6f1eab8 100644 --- a/tests/preflight-stream-summary-config.test.ts +++ b/tests/preflight-stream-summary-config.test.ts @@ -185,7 +185,7 @@ test("e2e #2133 (global config ON): 524 gateway → SSE forced first-shot, fold } }); -test("e2e #2133 (config OFF, default): 524 gateway → non-stream first-shot, no self-heal, fail-fast 502", async () => { +test("e2e #2133/#2155 (explicit OFF): 524 gateway → legacy non-stream retries, no learn, fail-fast 502", async () => { const calls: Call[] = []; const forwardBodies: string[] = []; const upstream = makeCloudflareUpstream(calls, forwardBodies); @@ -193,19 +193,23 @@ test("e2e #2133 (config OFF, default): 524 gateway → non-stream first-shot, no await once(upstream, "listening"); const upstreamPort = (upstream.address() as { port: number }).port; + // #2155 flipped the UNSET default to first-hit SSE learn on 524/504; an + // explicit cascade FALSE is now the operator's "never stream summaries" + // opt-out and must keep the legacy behavior: no learn path arms, every + // attempt stays non-stream, preflight fails fast. const proxy = await startProxy( { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-6-astra": { context: 10_000 } } } }, - {}, + { streamSummary: false }, ); await once(proxy, "listening"); const proxyPort = (proxy.address() as { port: number }).port; try { const r = await driveResponsesPreflight(proxyPort, upstreamPort, "s2133-off-1"); - // Pins the UNCHANGED default behavior: without the knob the gateway - // timeout never arms the learn path, so preflight fails fast instead - // of folding (the exact symptom reported in #2133). - assert.equal(r.status, 502, `default behavior must still fail fast behind the 524 gateway, got ${r.status}`); + // Pins the explicit-OFF behavior (#2155): the operator opted this + // route out of streaming summaries, so the gateway timeout must not + // arm the 524 learn path — preflight fails fast instead of folding. + assert.equal(r.status, 502, `explicit OFF must still fail fast behind the 524 gateway, got ${r.status}`); const body = await r.json() as { error?: { code?: string; retryable?: boolean } }; assert.equal(body.error?.code, "preflight_compress_failed"); assert.equal(body.error?.retryable, true); @@ -214,7 +218,7 @@ test("e2e #2133 (config OFF, default): 524 gateway → non-stream first-shot, no assert.ok(summaries.length >= 1, "a summary call must have been made"); assert.ok( summaries.every((c) => !c.stream), - `without the knob every summary attempt stays non-stream (the 524 never matches the learn regex), got ${JSON.stringify(calls)}`, + `explicit OFF keeps every summary attempt non-stream (no learn path arms), got ${JSON.stringify(calls)}`, ); assert.equal(forwardBodies.length, 0, "nothing was forwarded — the payload could not be brought under the window"); } finally { @@ -243,7 +247,7 @@ test("e2e #2133 (per-provider scope): only the route carrying compress.streamSum const proxy = await startProxy( { [`http://127.0.0.1:${portA}`]: { models: { "gpt-6-astra": { context: 10_000 } }, compress: { streamSummary: true } }, - [`http://127.0.0.1:${portB}`]: { models: { "gpt-6-astra": { context: 10_000 } } }, + [`http://127.0.0.1:${portB}`]: { models: { "gpt-6-astra": { context: 10_000 } }, compress: { streamSummary: false } }, }, {}, ); @@ -257,7 +261,7 @@ test("e2e #2133 (per-provider scope): only the route carrying compress.streamSum assert.ok(sumsA.length >= 1 && sumsA.every((c) => c.stream), `route A summaries must all be stream, got ${JSON.stringify(callsA)}`); const rB = await driveResponsesPreflight(proxyPort, portB, "s2133-scope-b"); - assert.equal(rB.status, 502, "route B has no knob and keeps the legacy non-stream-first behavior"); + assert.equal(rB.status, 502, "route B carries the explicit OFF knob and keeps the legacy non-stream-first behavior"); const sumsB = callsB.filter((c) => c.summary); assert.ok(sumsB.length >= 1 && sumsB.every((c) => !c.stream), `route B summaries must stay non-stream, got ${JSON.stringify(callsB)}`); assert.equal(bodiesB.length, 0, "route B forwarded nothing (its preflight failed)"); From 04e027ce6c74ceeedd7bf92a8fdafda1083c499f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 6 Oct 2026 16:03:21 +0800 Subject: [PATCH 3/3] test: pin the stale-learned-flag clause of explicit streamSummary=false (#2155 x #2133) --- tests/preflight-stream-summary-config.test.ts | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/tests/preflight-stream-summary-config.test.ts b/tests/preflight-stream-summary-config.test.ts index fcd6f1eab8..84f81ff869 100644 --- a/tests/preflight-stream-summary-config.test.ts +++ b/tests/preflight-stream-summary-config.test.ts @@ -269,3 +269,55 @@ test("e2e #2133 (per-provider scope): only the route carrying compress.streamSum await closeAll([proxy, upstreamA, upstreamB]); } }); + +test("e2e #2155/#2133 (stale learned flag): explicit OFF ignores a flag learned under the unset default", async () => { + // The disclosed opt-out contract has a third clause beyond the two learn + // paths: an ALREADY-learned metadata.preflightStreamSummary (acquired under + // the #2155 first-hit default while the cascade was unset) must be inert + // once the operator sets an explicit streamSummary:false on the route. The + // flag is seeded directly on the live session to simulate that prior + // learning; a failed preflight would arm the #726 dead-end cooldown for + // identical bodies, so the session is warmed with an in-window request + // instead of a failed long one. + const calls: Call[] = []; + const forwardBodies: string[] = []; + const upstream = makeCloudflareUpstream(calls, forwardBodies); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + const proxy = await startProxy( + { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-6-astra": { context: 10_000 } }, compress: { streamSummary: false } } }, + {}, + ); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + + try { + const warm = await fetch(`http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/responses`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "s2155-stale-flag" }, + body: JSON.stringify({ model: "gpt-6-astra", stream: true, input: [{ type: "message", role: "user", content: "warmup" }] }), + }); + assert.equal(warm.status, 200, `warmup must pass through, got ${warm.status}`); + const forwardedAfterWarmup = forwardBodies.length; + + const sess = listSessions().find((s) => s.id.includes("s2155-stale-flag")); + assert.ok(sess, "session recorded by the warmup"); + assert.equal(sess?.metadata?.preflightStreamSummary, undefined, "no flag before seeding"); + sess!.metadata.preflightStreamSummary = true; + + const r = await driveResponsesPreflight(proxyPort, upstreamPort, "s2155-stale-flag"); + assert.equal(r.status, 502, `explicit OFF must ignore the stale flag and fail fast, got ${r.status}; calls=${JSON.stringify(calls)}`); + const summaries = calls.filter((c) => c.summary); + assert.ok(summaries.length >= 1, "a summary call must have been made"); + assert.ok( + summaries.every((c) => !c.stream), + `explicit OFF keeps every attempt non-stream even with a learned flag, got ${JSON.stringify(calls)}`, + ); + assert.equal(forwardBodies.length, forwardedAfterWarmup, "the over-window payload was never forwarded (its preflight failed)"); + assert.equal(sess?.metadata?.preflightStreamSummary, true, "the opt-out leaves the stale flag set but inert"); + } finally { + await closeAll([proxy, upstream]); + } +});