From 8da4c62d37a7b52c65facf4e9a2ea07c0a662b91 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 07:03:08 +0800 Subject: [PATCH 1/4] fix: dsh 0.2.x code-mode omnibus `code_run` reads as compress-reachable (#3884) #3603's single-literal gate (RUN_CODE_TOOL_NAME = "run_code") went stale when DSH 0.2.x moved Code Mode into the dsh-codemode plugin, whose transport is named `code_run` (the reserved name `run_code` belongs to dsh-tools, so the plugin registers its own). On every DSH 0.2.x code-mode session the reachability conjunct failed and the compress surface stayed off forever: nudge ARMED-SUPPRESSED at 42% usage with pendingT1 10x over threshold, zero INJECT, fully silent (#3884). - collect the known omnibus shapes in CODE_MODE_OMNIBUS_TOOL_NAMES (run_code / code_run), provenance-commented per shape; both detection sites match the set - lane-decisions reachability (the reported miss) and ptcNoteMode (proxy-lane exempt note, same-mechanism second site) - matrix: dsh code_run row -> surface on + EMERGENCY twin; existing precision rows (get_weather / acp_status) stay the negative direction - ptc-runcode-tools: code_run -> exempt note on all four wires; bash-only rows pin the negative direction (#3617 bidirectional discipline) Targeted green: typecheck clean; lane-decisions-matrix 66/66; ptc-runcode-tools 16/16; e2e-ptc-runcode-shape 8/8. Full suite = CI. --- CHANGELOG.md | 1 + src/compress-tool.ts | 20 ++++++++++-- src/server/lane-decisions.ts | 19 +++++++----- tests/lane-decisions-matrix.test.ts | 9 ++++++ tests/ptc-runcode-tools.test.ts | 47 ++++++++++++++++++++++++++--- 5 files changed, 83 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c30988878e..0ff603b998 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Fixed +- **DSH 0.2.x Code Mode 会话恢复压缩面(#3884,#3603 修复在 DSH 0.2.x 形态上的复发)**:#3603 的可达性门只认 `run_code`(dsh-tools 内置名);DSH 0.2.x 把 Code Mode 移入 dsh-codemode 插件后 transport 改名为 `code_run`(保留名 `run_code` 归 dsh-tools,插件不能注册),判据整体失配——所有 DSH 0.2.x code-mode/PTC 会话的压缩面被**永久静默关闭**(issue 实测:usage 仅 42%、pendingT1 达门槛 10 倍仍 12× ARMED-SUPPRESSED / 0 INJECT,上下文涨到 63% 靠人工兜底)。修法:omnibus 已知形态收敛为集合 `CODE_MODE_OMNIBUS_TOOL_NAMES`(`run_code` / `code_run`,注释逐条列形态与出处),两处检测点共用——lane-decisions 可达性(主缺陷)与 proxy 车道的 `ptcNoteMode` exempt 注记(同族第二检测点,此前 code_run 客户端拿不到「直接调用」豁免注记)。真阴性精度不放松:裸单一非 omnibus 工具(get_weather/acp_status/bash)仍关面,矩阵新增 `code_run`→开面行(含 EMERGENCY 对偶行)、四 wire 双向断言。后续宿主变体按流量证据向集合追加;结构级真源(宿主 manifest 注册状态)仍在 #3417/#3482 Step3+ 路线上。 - **快照渲染接缝加固(#3812)**:身份签名没有 id 分量,重复短文本("继续"/yes/1)会让单次签名命中伪装成接缝,静默截断两点之间的全部历史。现在接缝要求至少 2 条连续匹配(`MIN_SEAM_RUN`,fold-reconcile `MIN_RESYNC_RUN` 同款纪律),单次命中一律降级走 legacy(`seam-too-short`),绝不猜测;同时容忍接缝中恰好一条未观测消息(上一轮回复的观察滞后——重发/重试轮的常态),第二条未命中即断链。块覆盖的签名传播被整体移除:它无法区分升级孪生与真实重复消息,会把未折叠的同文消息静默并入覆盖集(丢真消息);折叠期 id 在视图中完全失锚的块现在降级(`block-unanchored`)而不是把摘要锚点放在裸历史顶端。插件车道整体旁路(插件契约本就客户端权威)。影响面:灰度 0% 下零暴露,属开闸前必修。 ### Changes diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 6b7b3dbb1e..08e6743f3d 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -262,6 +262,21 @@ export const BILI_ACP_READONLY_TOOLS_RESPONSES = ACP_READONLY_TOOLS_RESPONSES.ma // only-run_code rule for exactly these tools. export const RUN_CODE_TOOL_NAME = "run_code"; +// #3884: known code-mode/PTC omnibus tool names, one entry per OBSERVED host +// shape — a code-mode harness collapses every registered tool behind ONE +// directly callable omnibus whose NAME is host-chosen, so both detection +// sites (lane-decisions reachability, ptcNoteMode below) match this set +// instead of a single literal (#3603's single-literal gate went stale when +// DSH 0.2.x swapped transports and silently suppressed the whole compress +// surface of every code-mode session): +// - "run_code" — dsh-tools built-in; DSH 0.1.x PTC preset (#3600/#3252); +// - "code_run" — dsh-codemode plugin transport; DSH 0.2.x (the reserved +// name "run_code" belongs to dsh-tools, so the plugin registers its own). +// A future host variant adds ITS observed name here with traffic evidence; +// the structural home for this judgment (host manifest registry state as the +// reachability truth, wire shape only a proxy signal) is #3417/#3482 Step3+. +export const CODE_MODE_OMNIBUS_TOOL_NAMES: ReadonlySet = new Set([RUN_CODE_TOOL_NAME, "code_run"]); + /** Calling-convention note mode for one request (internal to this module — * inject.ts/plugin.ts pick the mode via ptcNoteMode()/the literal "binding"). */ type AcpNoteMode = "binding" | "exempt" | "none"; @@ -330,9 +345,10 @@ export function withProjectAttribution(prompt: string): string { } /** Note mode for one request: the harness is code-mode-shaped when the - * client's own tools array carries a tool literally named run_code. */ + * client's own tools array carries a tool named like a known code-mode + * omnibus (run_code / code_run — see CODE_MODE_OMNIBUS_TOOL_NAMES, #3884). */ export function ptcNoteMode(names: Iterable): AcpNoteMode { - for (const n of names) if (n === RUN_CODE_TOOL_NAME) return "exempt"; + for (const n of names) if (typeof n === "string" && CODE_MODE_OMNIBUS_TOOL_NAMES.has(n)) return "exempt"; return "none"; } diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index 4daa598ed9..ab9d240a0c 100644 --- a/src/server/lane-decisions.ts +++ b/src/server/lane-decisions.ts @@ -25,7 +25,7 @@ import { biliToolsDeclaredOnWire } from "../session-self-heal.js"; import { extractBillingAttributionBlock } from "../preflight.js"; import { ANONYMOUS, hostProfileFor, type HostProfile } from "../host-profiles.js"; -import { RUN_CODE_TOOL_NAME } from "../compress-tool.js"; +import { CODE_MODE_OMNIBUS_TOOL_NAMES } from "../compress-tool.js"; type LaneProtocol = "anthropic" | "openai" | "google" | "responses"; @@ -228,14 +228,19 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { // In PLUGIN mode the host owns the tool table: reach when this request // declares `compress` (observed — some dsh profiles DO surface it, #3401) // or the host exposes bili tools to the model by design (profile default, - // #3177). PTC presets collapse EVERY tool into a single `run_code` - // omnibus (SDK bindings nested inside it), so top-level absence of - // `compress` is not evidence of unreachability there — an omnibus - // declaration reads as reachable (#3600: released 0.1.198 suppressed the - // surface on every dsh PTC session until the window hit 100%). + // #3177). PTC presets collapse EVERY tool into a single omnibus (SDK + // bindings nested inside it), so top-level absence of `compress` is not + // evidence of unreachability there — ANY known omnibus name reads as + // reachable. Known shapes live in CODE_MODE_OMNIBUS_TOOL_NAMES (run_code + // = dsh-tools built-in, DSH 0.1.x; code_run = dsh-codemode transport, + // DSH 0.2.x): #3600's miss was released 0.1.198 suppressing the surface + // on every dsh PTC session until the window hit 100%, and #3884's miss + // was that same single-literal gate going stale when DSH 0.2.x renamed + // the transport (12× ARMED-SUPPRESSED at 42% usage, pendingT1 10× over + // threshold, fully silent). const compressReachable = !input.pluginMode || declaredTools.has("compress") - || declaredTools.has(RUN_CODE_TOOL_NAME) + || [...CODE_MODE_OMNIBUS_TOOL_NAMES].some((n) => declaredTools.has(n)) || !profile.toolsHostScopedByDefault; const compressSurfaceOn = input.shouldInject && compressReachable; const billingBlockObserved = extractBillingAttributionBlock(systemOf(input.parsed)) !== undefined; diff --git a/tests/lane-decisions-matrix.test.ts b/tests/lane-decisions-matrix.test.ts index dd2a00d76a..b16d0c2401 100644 --- a/tests/lane-decisions-matrix.test.ts +++ b/tests/lane-decisions-matrix.test.ts @@ -260,6 +260,14 @@ const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; t // 100% window (89× ARMED-SUPPRESSED, output clamped) — the omnibus reads // as reachable now. { name: "dsh run_code omnibus keeps the surface (#3600 PTC shape)", lane: "dsh", tools: ["run_code"], expect: () => ({ nudge: true, standingPrompt: true }) }, + // #3884 FIX ROW: DSH 0.2.x moved Code Mode into the dsh-codemode plugin, + // whose transport is named `code_run` (the reserved name `run_code` belongs + // to dsh-tools) — the #3603 single-literal gate missed this renamed shape + // and suppressed the surface forever (issue log: 12× ARMED-SUPPRESSED at + // 42% usage with pendingT1=504985 vs the 50000 threshold, 0 INJECT). The + // omnibus-name set reads it reachable now; the precision rows below are + // the negative direction of the same pair. + { name: "dsh code_run omnibus keeps the surface (#3884 DSH 0.2.x shape)", lane: "dsh", tools: ["code_run"], expect: () => ({ nudge: true, standingPrompt: true }) }, // Named-tool precision must survive the #3600 fix: a bare single tool // that is NOT the omnibus and NOT compress stays a true negative // (#3177 preset-standard shape keeps its suppression). @@ -287,6 +295,7 @@ const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; t { name: "EMERGENCY override injects where the kernel declined cadence (#3461 guard)", lane: "omp", tools: [], teach: 45_000, expect: () => ({ nudge: true, standingPrompt: true }) }, { name: "EMERGENCY cannot punch through an unreachable dsh tool table (reverse guard)", lane: "dsh", tools: [], teach: 45_000, expect: () => ({ nudge: false, standingPrompt: false }) }, { name: "EMERGENCY override fires on the PTC run_code shape too", lane: "dsh", tools: ["run_code"], teach: 45_000, expect: () => ({ nudge: true, standingPrompt: true }) }, + { name: "EMERGENCY override fires on the PTC code_run shape too (#3884)", lane: "dsh", tools: ["code_run"], teach: 45_000, expect: () => ({ nudge: true, standingPrompt: true }) }, ]; for (const wire of ["anthropic", "openai", "responses", "google"] as const) { diff --git a/tests/ptc-runcode-tools.test.ts b/tests/ptc-runcode-tools.test.ts index a48491dcfe..8ea67e61cc 100644 --- a/tests/ptc-runcode-tools.test.ts +++ b/tests/ptc-runcode-tools.test.ts @@ -3,10 +3,11 @@ // The two serving sites answer with description-side notes so the model never // has to rediscover the calling convention by trial and error: // - proxy lane (injectTool & co): when the client's own tools array carries -// run_code, the injected ACP entries get PTC_EXEMPT_NOTE ("this tool is the -// exception — call it DIRECTLY; the proxy executes it server-side"), -// because bili's tools have no run_code SDK binding and the proxy tool loop -// executes direct calls upstream of the harness. +// a known code-mode omnibus (run_code / code_run — #3884), the injected +// ACP entries get PTC_EXEMPT_NOTE ("this tool is the exception — call it +// DIRECTLY; the proxy executes it server-side"), because bili's tools have +// no omnibus SDK binding and the proxy tool loop executes direct calls +// upstream of the harness. // - plugin lane (handlePluginManifest): every wire gets PTC_BINDING_NOTE (the // conditional both-conventions sentence) since one manifest serves native // and code-mode hosts alike. @@ -111,6 +112,44 @@ test("injectGoogleTool: no run_code → no exempt note", () => { assert.ok((decls.get("compress") ?? "").includes(PROJECT_URL_NOTE)); }); +// #3884: DSH 0.2.x code-mode transport is named `code_run` (dsh-codemode +// plugin; the reserved name `run_code` belongs to dsh-tools). ptcNoteMode must +// read it code-mode-shaped too, or proxy-lane injections for such clients lose +// the exempt note and the model may refuse direct bili calls under the +// harness's only-omnibus rule — silent compression failure, same family as the +// lane-decisions miss. Positive rows below; the negative direction is pinned by +// the bash-only rows above (#3617 bidirectional discipline). +const CODE_RUN = { name: "code_run", description: "Run a program in the sandbox." }; + +test("injectTool: code_run client → exempt note on ACP entries (#3884)", () => { + const out = flat(injectTool([CODE_RUN, BASH] as unknown[])); + assert.equal(out.get("code_run"), CODE_RUN.description, "client entry untouched"); + for (const name of ["compress", "decompress", "search_context", "acp_status", "acp_cache"]) { + assert.ok((out.get(name) ?? "").includes(PTC_EXEMPT_NOTE), `${name} carries the exempt note`); + } +}); + +test("injectOpenaiTool: code_run client → exempt note under function.description (#3884)", () => { + const out = openaiShape(injectOpenaiTool([ + { type: "function", function: { name: "code_run", description: "prog", parameters: { type: "object" } } }, + ]) as { function: { name?: string; description?: string } }[]); + assert.ok((out.get("compress") ?? "").includes(PTC_EXEMPT_NOTE)); + assert.ok((out.get("acp_status") ?? "").includes(PTC_EXEMPT_NOTE)); +}); + +test("injectResponsesTool: code_run client → exempt note, flat shape (#3884)", () => { + const out = flat(injectResponsesTool([CODE_RUN] as unknown[])); + assert.ok((out.get("decompress") ?? "").includes(PTC_EXEMPT_NOTE)); + assert.ok((out.get("compress") ?? "").includes(PROJECT_URL_NOTE)); +}); + +test("injectGoogleTool: code_run declaration → exempt note on appended declarations (#3884)", () => { + const out = injectGoogleTool([{ functionDeclarations: [{ name: "code_run", description: "prog" }] }] as never); + const decls = new Map(out.flatMap((t) => (t.functionDeclarations ?? []).map((d) => [d.name, d.description] as const)) as [string, string][]); + assert.ok((decls.get("compress") ?? "").includes(PTC_EXEMPT_NOTE)); + assert.equal(decls.get("code_run"), "prog", "client declaration untouched"); +}); + // — plugin lane: manifest always carries the binding note (no per-request signal) — function readManifestTools(): { anthropic: Map; openai: Map; responses: Map } { From 14eec04b2970bacfa056b782ba66abb6c15887d6 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 08:56:33 +0800 Subject: [PATCH 2/4] fix: name observed top-level tools when reachability keeps the compress surface off (#3884) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Observability hardening for the allowlist fragility class: when an armed nudge stays ARMED-SUPPRESSED because the lane surface is off for reachability (not user config), the diag line now carries surface=off(no-tools) or surface=off(top-level=[names]) — the next host omnibus rename shows up in bili.log next to the suppression label instead of requiring user archaeology (#3600 and #3884 were both diagnosed from user-reported dumps). No behavior change beyond log text. --- src/server.ts | 8 ++++++-- src/server/lane-decisions.ts | 15 +++++++++++++++ src/server/prepare-anthropic.ts | 4 ++-- src/server/prepare-google.ts | 4 ++-- src/server/prepare-openai.ts | 4 ++-- src/server/prepare-responses.ts | 4 ++-- tests/lane-decisions-b-class.test.ts | 20 +++++++++++++++++++- 7 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/server.ts b/src/server.ts index 6af516e531..5dc6852b29 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2241,7 +2241,7 @@ export function diagTagSummary(messages: CoreMessage[], sessionId: string, strat return `[${sessionId}] processTurn: ${messages.length} msgs, renderTags=${strategy}, ${textTagged} text tagged, ${toolTagged} tool tagged (should be 0 with text-only)`; } -export function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: string; contextUsage: number; tier: number | null; breakdown?: Record } | null }, sessionId: string, tokenCount: number, limit: number, model: string | undefined, willInject: boolean, decidePending = false): string { +export function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: string; contextUsage: number; tier: number | null; breakdown?: Record } | null }, sessionId: string, tokenCount: number, limit: number, model: string | undefined, willInject: boolean, decidePending = false, surfaceOff?: string): string { const n = turn.nudge; if (!n) return `[${sessionId}] nudge: unavailable`; const b = n.breakdown ?? {}; @@ -2261,7 +2261,11 @@ export function diagNudge(turn: { nudge?: { shouldInject: boolean; reason: strin ? (decidePending ? `INJECT-PENDING T${n.tier ?? "?"}` : (n.shouldInject ? `INJECT T${n.tier ?? "?"}` : `INJECT-ESC T${n.tier ?? "?"}`)) : (n.shouldInject ? `ARMED-SUPPRESSED T${n.tier ?? "?"}` : "idle"); const modelTag = model ? ` model=${model}` : ""; - return `[${sessionId}] nudge ${inject}: usage=${pct} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}, reason="${n.reason.slice(0, 120)}"`; + // #3884: why an armed nudge stayed suppressed — reachability-off lanes name + // the observed top-level tools so the next omnibus rename is greppable here + // (`surface=off(top-level=[...])`) instead of arriving as a user incident. + const offTag = surfaceOff ? `, ${surfaceOff}` : ""; + return `[${sessionId}] nudge ${inject}: usage=${pct} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}${offTag}, reason="${n.reason.slice(0, 120)}"`; } // Zero-baseline sessions are judged conservatively ONLY when they arrived diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index ab9d240a0c..9d0b0fd2fe 100644 --- a/src/server/lane-decisions.ts +++ b/src/server/lane-decisions.ts @@ -255,6 +255,21 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { }); } +/** #3884 owner follow-up: make a reachability miss LOUD instead of silent. + * When an armed nudge stays suppressed because the lane surface is OFF for + * reachability (not the user's own injectTool=false choice), name what was + * actually observed on the top-level tool table: the next host omnibus rename + * then shows up in bili.log next to the ARMED-SUPPRESSED label as + * `surface=off(top-level=[new_name])` instead of requiring user archaeology + * (#3600 and #3884 were both diagnosed from user-reported log dumps). Returns + * undefined when there is nothing to explain: surface on, or off by user + * config. */ +export function surfaceOffDetail(d: LaneDecisions, shouldInject: boolean): string | undefined { + if (d.compressSurfaceOn || !shouldInject) return undefined; + const declared = [...d.observed.declaredTools]; + return declared.length === 0 ? "surface=off(no-tools)" : `surface=off(top-level=[${declared.join(",")}])`; +} + function systemOf(parsed: unknown): string | Array> | undefined { if (parsed === null || typeof parsed !== "object") return undefined; const system = (parsed as Record)["system"]; diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index ac6b01eec3..6519028219 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -34,7 +34,7 @@ import { isAutoModeClassifier } from "../auto-mode-forge.js"; import { countSystemAndToolsTokens, emergencyNudge, emergencyNudgeArmed, projectThinkingMass } from "./budget.js"; import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectSystem, injectTool } from "./inject.js"; -import { nudgeOn, resolveLaneDecisions } from "./lane-decisions.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareAnthropic( parsed: AnthropicRequestBody, @@ -358,7 +358,7 @@ export async function prepareAnthropic( growthFoldingArmed: growthFoldingArmed(loopConfig), modelWantsIt: turn.nudge !== undefined && (turn.nudge.shouldInject || emergencyNudgeArmed(session, turn.nudge, loopConfig.compress.minCompressRange, tokenCount, loopConfig.nudge.growthFloor)), }); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, resolvedModel ?? parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, resolvedModel ?? parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride, surfaceOffDetail(laneDecisions, opts.compress.injectTool))); processedMessages = applyReasoningDrop(stripKernelSummaries(turn.messages, turn.state), reasoningPlan, log, sessionId); // #1001: a silent client history rewrite takes the same archive+prune path // as an announced /compact boundary — syncBlocks above has already diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 6b82f367e8..fd4a4f9af9 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -29,7 +29,7 @@ import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, e import { estimateCoreMessages } from "../preflight.js"; import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectGoogleTool, injectTool } from "./inject.js"; -import { nudgeOn, resolveLaneDecisions } from "./lane-decisions.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; function appendGoogleNudge(contents: GoogleContent[], text: string): GoogleContent[] { const last = contents[contents.length - 1]; @@ -239,7 +239,7 @@ export async function prepareGoogle( growthFoldingArmed: growthFoldingArmed(loopConfig), modelWantsIt: turn.nudge !== undefined && (turn.nudge.shouldInject || emergencyNudgeArmed(session, turn.nudge, loopConfig.compress.minCompressRange, tokenCount, loopConfig.nudge.growthFloor)), }); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, model, willInjectNudge, decideTier1Arm && !decideFallbackOverride, surfaceOffDetail(laneDecisions, opts.compress.injectTool))); processedMessages = stripKernelSummaries(turn.messages, turn.state); // #1001: a silent client history rewrite takes the same archive+prune path // as an announced /compact boundary — syncBlocks above has already diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 0c87179d9d..0a04f7c5e7 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -32,7 +32,7 @@ import { applyImageRescalePass } from "../image-rescale.js"; import { clampOutgoingOutput, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed } from "./budget.js"; import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectOpenaiTool, injectTool } from "./inject.js"; -import { nudgeOn, resolveLaneDecisions } from "./lane-decisions.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareOpenai( parsed: OpenAIRequestBody, @@ -255,7 +255,7 @@ export async function prepareOpenai( growthFoldingArmed: growthFoldingArmed(loopConfig), modelWantsIt: turn.nudge !== undefined && (turn.nudge.shouldInject || emergencyNudgeArmed(session, turn.nudge, loopConfig.compress.minCompressRange, tokenCount, loopConfig.nudge.growthFloor)), }); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride, surfaceOffDetail(laneDecisions, opts.compress.injectTool))); processedMessages = applyReasoningDrop(stripKernelSummaries(turn.messages, turn.state), reasoningPlan, log, sessionId); // #1001: a silent client history rewrite takes the same archive+prune path // as an announced /compact boundary — syncBlocks above has already diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index cdef95ef9d..f7c6e6aa08 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -37,7 +37,7 @@ import { imageRescaleMaxDim, keepResponseId as knobKeepResponseId, noCompressPro import { applyImageRescaleItems } from "../image-rescale.js"; import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed, modelVisibleTools } from "./budget.js"; import { FORCE_TEXT_PROTOCOL, injectResponsesTool, injectTool } from "./inject.js"; -import { nudgeOn, resolveLaneDecisions } from "./lane-decisions.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareResponses( parsed: ResponsesRequestBody, @@ -353,7 +353,7 @@ export async function prepareResponses( growthFoldingArmed: growthFoldingArmed(loopConfig, codexLane && codexCompactMode() === "intercept" ? loopConfig.modelContextLimit * CODEX_COMPACT_HEALTH_RATIO : undefined), modelWantsIt: turn.nudge !== undefined && (turn.nudge.shouldInject || emergencyNudgeArmed(session, turn.nudge, loopConfig.compress.minCompressRange, tokenCount, loopConfig.nudge.growthFloor)), }); - log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride)); + log("info", diagNudge(turn, sessionId, tokenCount, config.modelContextLimit, parsed.model, willInjectNudge, decideTier1Arm && !decideFallbackOverride, surfaceOffDetail(laneDecisions, opts.compress.injectTool))); processedMessages = repairResponsesAssistantOrdering(applyReasoningDrop(stripKernelSummaries(turn.messages, turn.state), reasoningPlan, log, sessionId), originalMessages); reapOrphansLogged(session, msgs, log, sessionId); rebuiltInput = patchResponsesInput(projection, processedMessages); diff --git a/tests/lane-decisions-b-class.test.ts b/tests/lane-decisions-b-class.test.ts index 2852357089..ebde8e37c5 100644 --- a/tests/lane-decisions-b-class.test.ts +++ b/tests/lane-decisions-b-class.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { nudgeOn, resolveLaneDecisions, resolveWireClientProfile, type NudgeGateInputs } from "../src/server/lane-decisions.js"; +import { nudgeOn, resolveLaneDecisions, resolveWireClientProfile, surfaceOffDetail, type NudgeGateInputs } from "../src/server/lane-decisions.js"; import { instructionsFingerprintApplies } from "../src/session-id.js"; // #3482 Step 2.5 equivalence proof: the single nudgeOn() gate must reproduce @@ -125,3 +125,21 @@ test("wire-client registry: instructionsFingerprintKeyed by observed signals (#3 assert.equal(instructionsFingerprintApplies({ "x-claude-code-session-id": " " }), false); // blank ≠ signal assert.equal(instructionsFingerprintApplies({ "x-acp-session": "abc" }), false); }); + +// #3884 owner follow-up: a reachability miss must be greppable in bili.log — +// the next omnibus rename shows up as `surface=off(top-level=[...])` next to +// ARMED-SUPPRESSED instead of two more incidents of user archaeology. +test("surfaceOffDetail: names observed tools on reachability-off, silent otherwise (#3884)", () => { + const dsh = (parsed: unknown, shouldInject: boolean) => resolveLaneDecisions({ protocol: "anthropic", pluginMode: true, pluginAgent: "dsh", parsed, shouldInject }); + // surface ON (compress declared top-level) → nothing to explain + assert.equal(surfaceOffDetail(dsh({ tools: [{ name: "compress" }] }, true), true), undefined); + // recognized omnibus → reachable → nothing to explain (negative direction) + assert.equal(surfaceOffDetail(dsh({ tools: [{ name: "run_code" }] }, true), true), undefined); + assert.equal(surfaceOffDetail(dsh({ tools: [{ name: "code_run" }] }, true), true), undefined); + // off by USER CONFIG (injectTool=false) → no explanation demanded + assert.equal(surfaceOffDetail(dsh({}, false), false), undefined); + // scoped lane, no tools at all → honest no-tools shape + assert.equal(surfaceOffDetail(dsh({}, true), true), "surface=off(no-tools)"); + // scoped lane with unrecognized names → the future-rename signal + assert.equal(surfaceOffDetail(dsh({ tools: [{ name: "get_weather" }, { name: "code_run2" }] }, true), true), "surface=off(top-level=[get_weather,code_run2])"); +}); From 077dca3743b926fdf7555f50e116e9e0f88730e5 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 09:06:15 +0800 Subject: [PATCH 3/4] fix: un-export two internal-only symbols flagged by the unused-exports gate RUN_CODE_TOOL_NAME (src/compress-tool.ts) and maskUrlForPublish (src/log-mask.ts) are each used only within their own module and imported nowhere; the unused-exports gate classifies both INTERNAL_ONLY. Drop the redundant leading `export` so the gate passes; both stay module-local and behavior is unchanged. Clears the unused-exports check on #3885. --- src/compress-tool.ts | 2 +- src/log-mask.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 08e6743f3d..b0e4249684 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -260,7 +260,7 @@ export const BILI_ACP_READONLY_TOOLS_RESPONSES = ACP_READONLY_TOOLS_RESPONSES.ma // reaches the harness at all (the proxy tool loop executes it // server-side), so the exempt note tells the model to ignore the harness's // only-run_code rule for exactly these tools. -export const RUN_CODE_TOOL_NAME = "run_code"; +const RUN_CODE_TOOL_NAME = "run_code"; // #3884: known code-mode/PTC omnibus tool names, one entry per OBSERVED host // shape — a code-mode harness collapses every registered tool behind ONE diff --git a/src/log-mask.ts b/src/log-mask.ts index ac2440b279..d34a619b1b 100644 --- a/src/log-mask.ts +++ b/src/log-mask.ts @@ -118,7 +118,7 @@ export function maskUrlsInText(text: string): string { * preference must not weaken the publish boundary (same stance as * redactSecretsInText, which is never gated by the switch). Userinfo, query * and hash are dropped exactly as in maskUrlForLog; the path is kept. */ -export function maskUrlForPublish(url: string): string { +function maskUrlForPublish(url: string): string { let u: URL; try { u = new URL(url); From 1e629d88764410412157f43ac98540faaa1da2d7 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 09:06:15 +0800 Subject: [PATCH 4/4] docs: regenerate config reference to drop stale duplicate storage rows CONFIGURATION.md/.zh-CN.md carried two stale duplicate rows left behind by #3818 (storage.unified shadow->full flip kept the old shadow row) and #3788 (sqliteAutoDownload cooldown text added a new row but kept the old one). The config-docs generator (source of truth: website/config-reference/*.yaml) emits only the current rows, so docs-sync failed on the merge. Regenerated from seeds; removes 2 stale rows per language file. No config-surface or behavior change. Pre-existing on master, surfaced via #3885's merge. --- CONFIGURATION.md | 2 -- CONFIGURATION.zh-CN.md | 2 -- 2 files changed, 4 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 09e953c4c5..d59b7e9cc6 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -174,8 +174,6 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | Repeat interval for the EPERM alert; 0 logs it once. | | `storage` | object | {} (all defaults) | — | Unified SQLite storage sidecar settings (#2671). | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to FULL (#3818 flip - the shadow dry-run reconciled cleanly since #2815, so the index is the load path; JSON envelopes keep being written, and legacy remains the one-line escape hatch). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to shadow (JSON stays the sole source of truth; the index is digest-reconciled telemetry - set legacy to opt out). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). A failed download arms a 6-hour retry cooldown persisted as a marker file under the cache dir (billion-context/sqlite/.bootstrap-failed.json); the storage diagnostics blob shows the marker's absolute expiry time and path - delete that file and restart bili to force an immediate retry instead of waiting out the whole window (#3788). | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 envelope switch (#2960): off stops writing the legacy JSON session envelope while storage.unified is full - the SQLite index becomes the only persistent copy (reads are already unified-first; boot enumerates the index union, so index-only sessions load normally). Only honored in effective-full mode: under shadow/legacy (or with encryption active) the request is ignored with a one-time warning because the JSON file remains the sole source of truth. Env tier 0/false/off = off and 1/true/on = on wins over the strict file spellings. Fail-safe: if the sidecar disables itself mid-run, envelope writes resume on the next save. Rollback: unset the knob - writing resumes, index-only sessions keep loading via the boot union, and replicas/restore re-materialize portable JSON envelopes. Downgrading the binary (or losing the SQLite engine) makes index-only sessions invisible to v0.1.196 and older until a >=v0.1.197 binary runs again - the data stays intact in index.db, it is just not read by the older code. The per-session content-store sidecar keeps being written either way. A jsonWriter=off lane must be the SOLE writer of its sessions directory: an off lane reads unified-first and never falls back to the file, so any peer instance running legacy/shadow against the same directory diverges silently (its JSON copy stops receiving updates, and the off lane never sees the peer's writes). | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | WAL reclamation cap for index.db-wal (#3250), in bytes: every completed checkpoint truncates the WAL file back to this size, bounding disk use and crash-recovery replay in long-lived processes. NOT a per-session data quota - data lands in index.db as it is written and the WAL only stages frames between checkpoints, so session count/size does not scale this; a large burst can overshoot temporarily until the next completed checkpoint truncates back. Higher = rarer truncate IO but more steady disk use and a longer crash-replay tail. Env tier (positive integer) wins over the file tier; a garbage or non-positive env value falls through to the file/default tier instead of failing boot. Applied when the store opens at lane boot - hot edits need a restart. The effective value appears on the unified-enable log line and in the storage diagnostics blob. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 758505a848..457bc4cbb3 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -174,8 +174,6 @@ | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | EPERM 告警的重复间隔;0 只记录一次。 | | `storage` | object | {} (all defaults) | — | 统一 SQLite 存储边车设置(#2671)。 | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 full(#3818 翻转 —— shadow 干跑自 #2815 起对账一直干净,索引因此成为默认加载路径;JSON 信封照写,legacy 仍是一行逃生口)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。 | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 shadow(JSON 仍是唯一事实源,索引只做对账遥测 —— 设 legacy 可退出)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。下载失败会置一个 6 小时的重试冷却,以标记文件形式持久化在缓存目录下(billion-context/sqlite/.bootstrap-failed.json);storage 诊断块会显示该标记的绝对到期时间与路径 —— 删除该文件并重启 bili 即可强制立即重试,不必等完整个冷却窗口(#3788)。 | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 信封开关(#2960):off 时若 storage.unified 为 full 则不再写 legacy JSON 会话信封 —— SQLite 索引成为唯一持久化副本(读路径本就 unified-first;boot 枚举索引并集,纯索引会话可正常加载)。仅在有效 full 模式下生效:shadow/legacy(或加密激活)下请求会被忽略并警告一次,因为 JSON 文件仍是唯一事实源。环境变量层 0/false/off = off、1/true/on = on,优先于严格拼写的文件层。失败安全:若边车运行中自禁用,下次保存即恢复信封写入。回滚:去掉该开关 —— 写入恢复,纯索引会话经 boot 并集继续可加载,replicas/restore 可重新物化可移植的 JSON 信封。降级二进制(或丢失 SQLite 引擎)会让纯索引会话在 v0.1.196 及更早版本上不可见,直到重新运行 >=v0.1.197 —— 数据在 index.db 中完好无损,只是旧代码不读它。每会话的 content-store 边车无论开关如何都照写。jsonWriter=off 的 lane 必须是其会话目录的唯一写者:off lane 读路径 unified-first、永不回退到文件,因此同一目录上跑 legacy/shadow 的对等实例会静默分叉(它的 JSON 副本收不到更新,off lane 也看不到对等实例的写入)。 | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | index.db-wal 的 WAL 回收上限(#3250),单位字节:每次完成的 checkpoint 把 WAL 文件截回该大小,约束长驻进程的磁盘占用与崩溃恢复重放。不是每会话数据配额 —— 数据写入时就已落进 index.db,WAL 只是两次 checkpoint 之间的帧暂存区,会话数量/大小不会放大它;大 burst 可能暂时超出,直到下一次完成的 checkpoint 截回。调大 = truncate IO 更稀疏,但稳态磁盘占用更多、崩溃恢复重放尾更长。环境变量层(正整数)优先于配置文件层;env 值非法或非正数时静默落到文件/默认层,boot 不崩。lane 启动、store open 时生效 —— 热改动需重启。实际取值会出现在 unified-enable 日志行与 storage 诊断块中。 |