diff --git a/CHANGELOG.md b/CHANGELOG.md index f0878e9053..3a041d8456 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,9 +12,13 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag - 暴露面:`/__bili/status` 的 `snapshotShadow` 汇总(enabled/watching/errors/worst)、web 会话列表逐会话计数(`snapshotShadow` 字段)、`snapshot-shadow` 诊断主题(GitHub 一键上报)、面板 banner(仅 error>0 时出现,附复制诊断/报 issue 按钮)。 - 配置:环境变量 `BILI_SNAPSHOT_SHADOW` 优先,配置文件 `snapshot.shadow` 布尔次之,缺省开启(`false`/`0`/`off` 关闭)。这是灰度翻转前的全舰队干跑 —— error 率连续一版本≈0 才翻 rollout。 +### Added + +- **插件车道:宿主可按请求声明实际暴露的 bili 工具(`x-bili-plugin-exposed-tools`,#3884 Step3+,owner 批准)**。可达性判定此前只有 wire 形状推断(认顶层工具名),宿主每改一次拢子工具名就静默失配一次(#3600→#3884 两起事故)。现在插件车道的宿主可在每个请求的 header 里声明本 preset 实际暴露了哪些 bili 工具:声明在场即真源,压过全部推断档位(含 profile 默认)——顶层是不认识的**新** omnibus 形态、只要声明含 `compress` 即可达(未来改名免疫);反方向同样成立——顶层是认识的 omnibus、声明说没暴露 compress,面照关(双向钉死)。header 缺省时传统名字推断逻辑逐位保持(owner 约束:没加 header 的请求行为不变,不嘎);proxy 车道结构性开面不受声明影响。这是 #3417/#3482 Step3+ 结构级真源方向的第一步,dsh 侧后续在 code-mode preset 补声明后本机制即为其服务。测试:b-class 单测(优先级规则 9 行 + 解析器)+ 矩阵 e2e 四 wire 双向行(声明救未知形态 / 声明压认识形态)。 ### 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..b0e4249684 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -260,7 +260,22 @@ 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 +// 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"). */ @@ -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.ts b/src/server.ts index fddc3bf4cd..8a1971d7bc 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2246,7 +2246,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 ?? {}; @@ -2266,7 +2266,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/headers.ts b/src/server/headers.ts index dbc56efe92..de7ea60372 100644 --- a/src/server/headers.ts +++ b/src/server/headers.ts @@ -31,6 +31,25 @@ export const UPSTREAM_HOP_HEADERS = new Set([ "upgrade", ]); +/** #3884 Step3+ (owner-approved 2026-10-20): per-request DECLARATION from a + * plugin host of which bili tools it actually exposed for THIS request + * (comma-separated tool names; present-but-empty = "exposes none"). The + * registration state lives only in the host, so where hosts adopt this the + * declaration replaces wire-shape name-guessing (#3600/#3884 fragility + * class). Absent header = undeclared host — consumers fall back to the + * legacy inference bit-for-bit; an absent header must never change behavior + * (owner constraint, #3884 thread). Precedence rules live in + * resolveLaneDecisions (#3417 lane-decisions). */ +export const EXPOSED_TOOLS_HEADER = "x-bili-plugin-exposed-tools"; + +/** Parse the declaration: undefined header → null (absent); any other value + * → trimmed, lowercased names ([] when nothing was declared). */ +export function parseExposedToolsHeader(value: string | string[] | undefined): string[] | null { + if (value === undefined) return null; + const raw = Array.isArray(value) ? value.join(",") : value; + return raw.split(",").map((s) => s.trim().toLowerCase()).filter((s) => s.length > 0); +} + // content-encoding is end-to-end (RFC 9110 §7.2), NOT hop-by-hop — but the two // directions need opposite treatment. RESPONSES: Node's fetch transparently // decodes compressed bodies, so the upstream's encoding marker must not reach diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index 4daa598ed9..2c53529671 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"; @@ -165,6 +165,13 @@ interface LaneDecisionInput { readonly parsed: unknown; /** injectTool config (`shouldInject`) — the config-level master switch. */ readonly shouldInject: boolean; + /** #3884 Step3+: parsed x-bili-plugin-exposed-tools declaration for THIS + * request — null when the header is absent (undeclared host → the legacy + * wire-shape inference below applies bit-for-bit), [] when + * present-but-empty ("exposes none"). When non-null it is ground truth: + * the declaration outranks every inference rung, profile default + * included (an explicit "not exposed" beats toolsHostScopedByDefault). */ + readonly exposedTools: string[] | null; } // ④ nudgeOn — the ONE nudge-injection gate (#3482 Step 2.5). The four // prepares used to carry four hand-copied conjunctions that drifted (#3293: @@ -225,18 +232,40 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { const declaredTools = observeDeclaredTools(input.parsed, input.protocol); // Reachability truth: in PROXY mode bili itself injects the tool // definitions into the outbound body, so the surface is structurally on. - // 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%). - const compressReachable = !input.pluginMode - || declaredTools.has("compress") - || declaredTools.has(RUN_CODE_TOOL_NAME) - || !profile.toolsHostScopedByDefault; + // In PLUGIN mode the host owns the tool table, with two evidence tiers: + // Tier 1 — DECLARATION (#3884 Step3+, owner-approved 2026-10-20): the + // host stamps x-bili-plugin-exposed-tools with what it actually exposed + // for THIS request. It IS the ground truth the name-guessing below + // approximated, so it decides alone — even against a recognized omnibus + // name (a host that says "not exposed" wins). Top-level `compress` + // stays callable-truth either way: it is in the model's tool table when + // observed, declaration or no. + // Tier 2 — WIRE-SHAPE INFERENCE (absent header; every host today): + // reach when this request declares `compress` (observed — some dsh + // profiles DO surface it, #3401) or a known code-mode omnibus sits at + // the top level (PTC presets collapse EVERY tool into one omnibus with + // SDK bindings nested inside it, so top-level absence of `compress` is + // not evidence of unreachability there) or the host exposes bili tools + // by design (profile default, #3177). 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). An absent header must keep this tier bit-for-bit — + // undeclared hosts behave exactly as before (owner constraint). + const topLevelCompress = declaredTools.has("compress"); + let compressReachable: boolean; + if (!input.pluginMode) { + compressReachable = true; + } else if (input.exposedTools !== null) { + compressReachable = topLevelCompress || input.exposedTools.includes("compress"); + } else { + compressReachable = topLevelCompress + || [...CODE_MODE_OMNIBUS_TOOL_NAMES].some((n) => declaredTools.has(n)) + || !profile.toolsHostScopedByDefault; + } const compressSurfaceOn = input.shouldInject && compressReachable; const billingBlockObserved = extractBillingAttributionBlock(systemOf(input.parsed)) !== undefined; const billingBlockWanted = profile.wantsBillingBlock || billingBlockObserved; @@ -250,6 +279,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 8ca49dfbbf..b8200adf68 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -34,7 +34,8 @@ 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 { EXPOSED_TOOLS_HEADER, parseExposedToolsHeader } from "./headers.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareAnthropic( parsed: AnthropicRequestBody, @@ -70,6 +71,7 @@ export async function prepareAnthropic( pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject: opts.compress.injectTool, + exposedTools: parseExposedToolsHeader(req.headers[EXPOSED_TOOLS_HEADER]), }); // #3222: #651's reasoning-drop plan, computed on the INBOUND history before // core.processTurn — see planReasoningDrop for why the post-turn view is too late. @@ -359,7 +361,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 0d6c60c443..9e1d798100 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -29,7 +29,8 @@ 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 { EXPOSED_TOOLS_HEADER, parseExposedToolsHeader } from "./headers.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; function appendGoogleNudge(contents: GoogleContent[], text: string): GoogleContent[] { const last = contents[contents.length - 1]; @@ -100,7 +101,7 @@ export async function prepareGoogle( const injectTools = shouldInject && !pluginMode; // #3417: surface gating lives in lane-decisions (observed reachability // overrides the dsh default, #3401); alias kept for the remaining reads. - const laneDecisions = resolveLaneDecisions({ protocol: "google", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject }); + const laneDecisions = resolveLaneDecisions({ protocol: "google", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, exposedTools: parseExposedToolsHeader(req.headers[EXPOSED_TOOLS_HEADER]) }); // #2483: this lane used to ignore renderNone entirely (hardcoded "text-only" // in processTurn, Prepared and countTokens) — the knob was dead config on /v1beta. const renderStrategy = knobRenderNone() ? "none" : "text-only"; @@ -240,7 +241,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 7c386d419f..f23664bc6e 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -32,7 +32,8 @@ 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 { EXPOSED_TOOLS_HEADER, parseExposedToolsHeader } from "./headers.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareOpenai( parsed: OpenAIRequestBody, @@ -94,7 +95,7 @@ export async function prepareOpenai( // keep it — their extensions expose the tools to the agent. // #3417: that judgement now lives in lane-decisions (observed reachability // overrides the dsh default — #3401); alias kept for the remaining reads. - const laneDecisions = resolveLaneDecisions({ protocol: "openai", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject }); + const laneDecisions = resolveLaneDecisions({ protocol: "openai", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, exposedTools: parseExposedToolsHeader(req.headers[EXPOSED_TOOLS_HEADER]) }); const markerCounts = stripRawStage(parsed, "openai"); logRawStripCounts(markerCounts, log, sessionId); @@ -256,7 +257,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 26558d8f5a..c230a4c0e5 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -37,7 +37,8 @@ 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 { EXPOSED_TOOLS_HEADER, parseExposedToolsHeader } from "./headers.js"; +import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; export async function prepareResponses( parsed: ResponsesRequestBody, @@ -122,7 +123,7 @@ export async function prepareResponses( const injectTools = shouldInject && !pluginMode; // #3417: surface gating lives in lane-decisions (observed reachability // overrides the dsh default, #3401). - const laneDecisions = resolveLaneDecisions({ protocol: "responses", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject }); + const laneDecisions = resolveLaneDecisions({ protocol: "responses", pluginMode, pluginAgent: typeof session.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] as string : undefined, parsed, shouldInject, exposedTools: parseExposedToolsHeader(req.headers[EXPOSED_TOOLS_HEADER]) }); // Effective gate for the standing prompt + nudge: DSH reads as injectTool-off so it takes the same // stable tags-only developer slot as any non-injecting session (prefix cache stays append-stable). const compressSurfaceOn = laneDecisions.compressSurfaceOn; @@ -354,7 +355,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..cb844c8bc6 100644 --- a/tests/lane-decisions-b-class.test.ts +++ b/tests/lane-decisions-b-class.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { nudgeOn, resolveLaneDecisions, resolveWireClientProfile, type NudgeGateInputs } from "../src/server/lane-decisions.js"; +import { parseExposedToolsHeader } from "../src/server/headers.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 @@ -91,7 +92,7 @@ test("nudgeOn: deliberate per-lane differences stay explicit (#3482)", () => { test("resolveLaneDecisions: billingBlockWanted = profile-declared OR wire-observed (#3482 site 1)", () => { const billingSystem = [{ type: "text", text: "x-anthropic-billing-header: acct-123" }, { type: "text", text: "You are helpful." }]; const plainSystem = [{ type: "text", text: "You are helpful." }]; - const input = (system: unknown, pluginAgent: string | undefined) => ({ protocol: "anthropic" as const, pluginMode: true, pluginAgent, parsed: { system }, shouldInject: true }); + const input = (system: unknown, pluginAgent: string | undefined) => ({ protocol: "anthropic" as const, pluginMode: true, pluginAgent, parsed: { system }, shouldInject: true, exposedTools: null }); // dsh declares it — even with no block on this wire. const dsh = resolveLaneDecisions(input(plainSystem, "dsh")); assert.equal(dsh.billingBlockWanted, true); @@ -125,3 +126,58 @@ 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, exposedTools: null }); + // 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])"); +}); + +// #3884 Step3+ (owner-approved): host declaration channel — +// x-bili-plugin-exposed-tools is ground truth when present; an ABSENT header +// keeps the legacy wire-shape inference bit-for-bit (owner constraint: a +// request without the header must not change behavior). +test("resolveLaneDecisions: exposed-tools declaration outranks wire inference (#3884 Step3+)", () => { + const dsh = (parsed: unknown, exposedTools: string[] | null) => resolveLaneDecisions({ protocol: "anthropic", pluginMode: true, pluginAgent: "dsh", parsed, shouldInject: true, exposedTools }); + // declaration rescues an UNRECOGNIZED omnibus shape — the future-rename + // case that sank #3600 and #3884 alike. + assert.equal(dsh({ tools: [{ name: "code_run2" }] }, ["compress", "decompress"]).compressSurfaceOn, true); + // declaration beats a recognized-name inference: run_code on top level but + // the host says compress is NOT exposed → off (name matching alone said on). + assert.equal(dsh({ tools: [{ name: "run_code" }] }, ["decompress"]).compressSurfaceOn, false); + // present-but-empty = "exposes none" → off even with a recognized omnibus. + assert.equal(dsh({ tools: [{ name: "code_run" }] }, []).compressSurfaceOn, false); + // absent header → legacy inference, both directions (the fallback guarantee). + assert.equal(dsh({ tools: [{ name: "code_run" }] }, null).compressSurfaceOn, true); + assert.equal(dsh({ tools: [{ name: "get_weather" }] }, null).compressSurfaceOn, false); + // top-level compress stays ground truth even against a contradicting declaration. + assert.equal(dsh({ tools: [{ name: "compress" }] }, []).compressSurfaceOn, true); + // proxy mode is structural — a stray header cannot turn it off. + const proxy = resolveLaneDecisions({ protocol: "anthropic", pluginMode: false, pluginAgent: undefined, parsed: {}, shouldInject: true, exposedTools: [] }); + assert.equal(proxy.compressSurfaceOn, true); + // declaration outranks the profile default too (pi: toolsHostScopedByDefault=false). + const pi = resolveLaneDecisions({ protocol: "anthropic", pluginMode: true, pluginAgent: "pi", parsed: {}, shouldInject: true, exposedTools: [] }); + assert.equal(pi.compressSurfaceOn, false); + // surfaceOffDetail explains a declared-off case like any other off. + assert.equal(surfaceOffDetail(dsh({ tools: [{ name: "run_code" }] }, ["decompress"]), true), "surface=off(top-level=[run_code])"); +}); + +test("parseExposedToolsHeader: absent → null, present → trimmed/lowercased names (#3884 Step3+)", () => { + assert.equal(parseExposedToolsHeader(undefined), null); + assert.deepEqual(parseExposedToolsHeader(""), []); + assert.deepEqual(parseExposedToolsHeader("compress"), ["compress"]); + assert.deepEqual(parseExposedToolsHeader("Compress, decompress ,, ACP_Status "), ["compress", "decompress", "acp_status"]); + assert.deepEqual(parseExposedToolsHeader(["compress", ""]), ["compress"]); +}); diff --git a/tests/lane-decisions-matrix.test.ts b/tests/lane-decisions-matrix.test.ts index dd2a00d76a..12fba277af 100644 --- a/tests/lane-decisions-matrix.test.ts +++ b/tests/lane-decisions-matrix.test.ts @@ -96,7 +96,7 @@ const settledClose = (srv: http.Server): Promise => { }); }; -async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool = true, teachTokens = 50_000) { +async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool = true, teachTokens = 50_000, exposedTools?: string) { // Windows CI flake class (seen on runners, not on dev VMs): listen(0) // occasionally lands in an OS-reserved/excluded port range and emits // "error" (EACCES/EADDRINUSE) instead of "listening". events.once( @@ -186,7 +186,7 @@ async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool = const send = async (texts: string[]) => { const r = await fetch(`${origin}/bili/${upstreamUrl}${endpoint}`, { method: "POST", - headers: { "content-type": "application/json", "x-acp-session": `lane-${lane}-${toolNames.join("-") || "notools"}`, ...(lane === "proxy" ? {} : { "x-bili-plugin": lane }) }, + headers: { "content-type": "application/json", "x-acp-session": `lane-${lane}-${toolNames.join("-") || "notools"}`, ...(lane === "proxy" ? {} : { "x-bili-plugin": lane }), ...(exposedTools !== undefined ? { "x-bili-plugin-exposed-tools": exposedTools } : {}) }, body: JSON.stringify(buildBody(texts)), }); const bodyText = await r.text(); @@ -246,7 +246,7 @@ function outcome(wire: Wire, sentCount: number, forwarded: Record RowOutcome }[] = [ +const ROWS: { name: string; lane: Lane; tools: string[]; injectTool?: boolean; teach?: number; /** raw x-bili-plugin-exposed-tools value; undefined = header absent */ exposedTools?: string; expect: (w: Wire) => RowOutcome }[] = [ { name: "omp control keeps the surface", lane: "omp", tools: [], expect: () => ({ nudge: true, standingPrompt: true }) }, { name: "dsh no-tools drops the surface (#3177)", lane: "dsh", tools: [], expect: () => ({ nudge: false, standingPrompt: false }) }, // #3401 FIX ROW: dsh with compress actually declared on @@ -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,12 +295,22 @@ 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 }) }, + // #3884 Step3+ declaration pair (owner-approved 2026-10-20): the host's + // x-bili-plugin-exposed-tools is ground truth when present. Positive: an + // UNRECOGNIZED omnibus shape that name-matching still misses becomes + // reachable once the host declares what it exposed — the future-rename + // case that sank #3600/#3884 alike. Reverse: a recognized omnibus on top + // level stays SUPPRESSED when the host says compress is not among what it + // exposed (declaration outranks inference in BOTH directions). + { name: "dsh declared-exposed compress rescues unrecognized omnibus shape (#3884 Step3+)", lane: "dsh", tools: ["code_run2"], exposedTools: "compress,decompress", expect: () => ({ nudge: true, standingPrompt: true }) }, + { name: "dsh declared-not-exposed suppresses despite recognized omnibus (#3884 Step3+ reverse)", lane: "dsh", tools: ["run_code"], exposedTools: "", expect: () => ({ nudge: false, standingPrompt: false }) }, ]; for (const wire of ["anthropic", "openai", "responses", "google"] as const) { for (const row of ROWS) { test(`lane matrix [${wire}] ${row.name}`, { timeout: 60_000 }, async () => { - const h = await harness(wire, row.lane, row.tools, row.injectTool, row.teach); + const h = await harness(wire, row.lane, row.tools, row.injectTool, row.teach, row.exposedTools); try { await h.send(["hello"]); // teach usage 50k / 64k = 78% await h.send(historyTexts()); // arm the nudge 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 } {