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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 19 additions & 3 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = 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"). */
Expand Down Expand Up @@ -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<string | undefined>): 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";
}

Expand Down
8 changes: 6 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number> } | 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<string, number> } | 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 ?? {};
Expand All @@ -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
Expand Down
19 changes: 19 additions & 0 deletions src/server/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 57 additions & 13 deletions src/server/lane-decisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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;
Expand All @@ -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<Record<string, unknown>> | undefined {
if (parsed === null || typeof parsed !== "object") return undefined;
const system = (parsed as Record<string, unknown>)["system"];
Expand Down
6 changes: 4 additions & 2 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading