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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,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
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 @@ -2249,7 +2249,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 @@ -2269,7 +2269,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
34 changes: 27 additions & 7 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 @@ -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;
Expand All @@ -250,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<Record<string, unknown>> | undefined {
if (parsed === null || typeof parsed !== "object") return undefined;
const system = (parsed as Record<string, unknown>)["system"];
Expand Down
4 changes: 2 additions & 2 deletions src/server/prepare-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -359,7 +359,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
4 changes: 2 additions & 2 deletions src/server/prepare-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -240,7 +240,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
Expand Down
4 changes: 2 additions & 2 deletions src/server/prepare-openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -256,7 +256,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
Expand Down
4 changes: 2 additions & 2 deletions src/server/prepare-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { imageRescaleMaxDim, keepResponseId as knobKeepResponseId, noCompressPro
import { applyImageRescaleItems } from "../image-rescale.js";
import { clampOutgoingOutput, countLoadedToolTokens, countSystemAndToolsTokens, dshLedgerFloorTokens, emergencyNudge, emergencyNudgeArmed, modelVisibleTools, responsesSysDevItemText } 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,
Expand Down Expand Up @@ -365,7 +365,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);
Expand Down
20 changes: 19 additions & 1 deletion tests/lane-decisions-b-class.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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])");
});
Loading
Loading