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
23 changes: 23 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ import { bodyDumpEnabled, getUnrecognizedPathStats, isModelDiscoveryPath, logDum
import { BILI_HOP_HEADER, anthropicBetaContextWindow, capRegistryWindowByStandard, expandedContextSuffixWindow, LAUNCHER_MODEL_WINDOWS, LAUNCHER_MODEL_MAX_OUTPUTS, launcherContextWindow, launcherMaxOutput, parseLauncherModelWindows, windowSourceLogged } from "./server/context-window.js";
import { buildForwardHeaders, connectionNamedHeaders, NO_IDENTITY_MESSAGE, RESPONSE_ONLY_STRIP_HEADERS, safeSessionId, UPSTREAM_HOP_HEADERS } from "./server/headers.js";
import { isSideRequest, outputBudgetField, restoreOutputBudget, SIDE_REQUEST_MAX_TOKENS, sideRequestGuard } from "./server/side-request.js";
import { dshCompactionRefusal, isDshCompactionCall } from "./server/dsh-compaction-guard.js";
import { clampOutgoingOutput, countSystemAndToolsTokens, emergencyNudge, estimateInputTokens, estimateWireOverhead, projectThinkingMass } from "./server/budget.js";
import { awaitDrain, bufferToStream, dumpStreamToFile, pipeThrough, readStreamToBuffer } from "./server/stream-io.js";
import { artifactSeedHit, detectAcpArtifacts } from "./server/chain-artifacts.js";
Expand Down Expand Up @@ -2400,6 +2401,28 @@ async function handle(
// Resolved once here so the side-request guard below AND the main-path
// reservation measure against the SAME capped window.
const headroomCap = resolveOutputHeadroomCap(resolveCompress(opts.routes, route?.rewrittenUrl, (parsed as { model?: string }).model, opts.compress).outputHeadroomMaxPct);
// #1729: dsh native compaction guard β€” a compaction summarize call
// (replayed prefix + COMPACTION_INSTRUCTION as the final user message,
// ≀4 messages) is refused BEFORE any pipeline work: not forwarded, kernel
// state untouched. Unconditional by design β€” auto pressure, overflow
// recovery, and manual /compact share one envelope, and a landed
// checkpoint durably shadows the raw history (irreversible), while every
// cost of refusing is dsh-side, caught, and recoverable. Runs before the
// #388 side-request lane: the compaction call is a full-budget request,
// so only this guard can catch it.
if (protocol !== null && isDshCompactionCall(protocol, parsed, inboundMsgs)) {
if (session.metadata.dshCompactionRefused !== true) {
session.metadata.dshCompactionRefused = true;
log("warn", `[${session.id}] dsh native compaction call identified (final user message = COMPACTION_INSTRUCTION, ${inboundMsgs} msgs) β€” REFUSED, not forwarded: bili owns compression on this lane; a landed dsh checkpoint would durably shadow the raw history (#1729, cf. #1206/#1772)`);
}
const refusal = dshCompactionRefusal(protocol);
if (!res.headersSent && !res.writableEnded && !res.destroyed) {
res.writeHead(refusal.status, { "content-type": "application/json" });
res.end(JSON.stringify(refusal.body));
}
logRequestCost(log, session.id, inboundMsgs, inboundBytes, reqT0);
return;
}
// #388: side requests (title-gen etc.) share the main session key but
// must not touch kernel state (processTurn/snapshot/usage would pollute
// the main view). Forward with a minimal prepared marked sidePassthrough:
Expand Down
119 changes: 119 additions & 0 deletions src/server/dsh-compaction-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* #1729: dsh native compaction-call guard.
*
* dsh's `dsh-compaction-basic` answers context pressure by replaying the whole
* conversation prefix and appending a fixed summarization directive
* (COMPACTION_INSTRUCTION, dsh-compaction-basic/lib/index.js) as the FINAL
* user message, reusing the same session id so the provider's KV prefix cache
* stays warm. In the desktop lane those calls ride bili under the main
* conversation id β€” the second producer of #1729's deadlock β€” and when one
* LANDS, dsh durably shadows the replayed surface range: the original
* messages never ride a future request again, which destroys the proxy's
* compression substrate (irreversible, unlike every cost of refusing).
*
* This guard identifies the call at the traffic level and refuses it locally:
* never forwarded, kernel state untouched. Two-signal AND, per the
* claudeSubagentSplit (#970) discipline β€” both signals must agree, and the
* failure direction is "stop intercepting" (a reworded template degrades to
* today's behavior; a normal turn can never match: multi-turn requests carry
* far more messages than DSH_COMPACTION_MAX_MESSAGES):
* 1. MARKER β€” the final user message STARTS with the versioned instruction
* prefix (machine-appended by the summarizer, never user-chosen);
* 2. SHAPE β€” the whole request is ≀ DSH_COMPACTION_MAX_MESSAGES messages
* (replayed prefix collapsed + directive; observed live: 2 msgs at
* ~152K tokens in the #1729/#1727 logs).
*
* Deliberately unconditional (auto pressure, context-overflow recovery, and
* manual /compact all send the same envelope β€” the traffic layer cannot tell
* which trigger fired, and a landed checkpoint is equally destructive from
* any of them). Not gated on the dsh plugin marker: a dsh host routed through
* a global bili proxy without the plugin bundle must be covered too. Refusal
* message text intentionally rides into dsh's own warn line
* ("step compaction failed: <message>; continuing the turn").
*/

/** Stable opening sentence of dsh's COMPACTION_INSTRUCTION template
* (verbatim from @deepseek-ai/dsh-compaction-basic, tracked per dsh release
* like MAIN_SYSTEM_PREFIXES tracks Claude Code's system prompts, #970). */
export const DSH_COMPACTION_INSTRUCTION_PREFIX =
"You are now acting as a compaction engine for this AI coding assistant";

/** The compaction call is a replayed prefix + directive: observed as 2
* messages (~152K tokens) in the #1727 production logs. A normal turn β€”
* including a user pasting the template into an existing conversation β€”
* carries the full multi-message history and cannot fit under this bar. */
export const DSH_COMPACTION_MAX_MESSAGES = 4;

type Rec = Record<string, unknown>;

/** Concatenate a wire content field (string | parts array) into plain text. */
function textOfContent(content: unknown): string {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
let out = "";
for (const part of content) {
if (typeof part === "string") out += part;
else if (part !== null && typeof part === "object" && typeof (part as Rec).text === "string") {
out += (part as Rec).text;
}
}
return out;
}

/** Text of the LAST role=user message for the messages-shaped protocols
* (openai chat/completions, anthropic messages). Google's contents/parts
* shape and the Responses input items are out of scope for v1 β€” dsh's
* desktop lane speaks OpenAI-compatible chat. */
function lastUserMessageText(protocol: string, parsed: unknown): string | undefined {
if (parsed === null || typeof parsed !== "object") return undefined;
const messages = (parsed as Rec).messages;
if (!Array.isArray(messages)) return undefined;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m === null || typeof m !== "object") continue;
if ((m as Rec).role !== "user") continue;
return textOfContent((m as Rec).content);
}
return undefined;
}

/** Two-signal test: marker in the final user message AND a compact
* message count. `messageCount` is the wire messages-array length the
* caller already computed (server.ts inboundMsgs). */
export function isDshCompactionCall(protocol: string | null, parsed: unknown, messageCount: number | null): boolean {
if (protocol !== "openai" && protocol !== "anthropic") return false;
if (messageCount === null || messageCount > DSH_COMPACTION_MAX_MESSAGES) return false;
const finalUser = lastUserMessageText(protocol, parsed);
if (finalUser === undefined) return false;
return finalUser.trimStart().startsWith(DSH_COMPACTION_INSTRUCTION_PREFIX);
}

export type Refusal = { status: number; body: unknown };

const REFUSAL_MESSAGE =
`dsh native compaction call refused by billion-context: bili owns compression on this lane (#1729, cf. #1772/#1206). ` +
`A landed dsh compaction checkpoint durably shadows the raw conversation history, which destroys the proxy's compression substrate. ` +
`Disable dsh auto-compaction (bili preset 'standard-bili-auto-off') or remove the co-resident dsh compaction plugin.`;

/** Protocol-shaped refusal body (mirrors the #554 side-request guard shape so
* clients render it natively). 403: a policy refusal, not a malformed
* request β€” the caller's own retry logic must not treat it as transient. */
export function dshCompactionRefusal(protocol: string): Refusal {
if (protocol === "anthropic") {
return {
status: 403,
body: { type: "error", error: { type: "invalid_request_error", message: REFUSAL_MESSAGE } },
};
}
return {
status: 403,
body: {
error: {
type: "server_error",
code: "dsh_compaction_refused",
message: REFUSAL_MESSAGE,
retryable: false,
},
},
};
}
107 changes: 107 additions & 0 deletions tests/dsh-compaction-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
DSH_COMPACTION_INSTRUCTION_PREFIX,
DSH_COMPACTION_MAX_MESSAGES,
dshCompactionRefusal,
isDshCompactionCall,
} from "../src/server/dsh-compaction-guard.ts";

// #1729: the guard must recognize dsh-compaction-basic's summarize envelope
// (replayed prefix + COMPACTION_INSTRUCTION as the final user message) and
// refuse it, while a normal multi-message turn β€” even one QUOTING the
// template β€” must pass untouched.

/** First line of the real COMPACTION_INSTRUCTION, verbatim from
* @deepseek-ai/dsh-compaction-basic (tracked per dsh release). */
const INSTRUCTION =
"You are now acting as a compaction engine for this AI coding assistant. Condense the conversation ABOVE into a structured checkpoint that lets another model resume the work with no loss of essential context.";

function openaiBody(messages: unknown[]) {
return { model: "qwen-3.8-27b", messages, stream: true };
}

const giantPrefix = "x".repeat(600_000); // ~150K tokens of replayed prefix

test("identifies the observed production shape: 2-msg openai replay + directive", () => {
const body = openaiBody([
{ role: "system", content: "you are dsh" },
{ role: "user", content: giantPrefix },
{ role: "user", content: INSTRUCTION },
]);
assert.equal(isDshCompactionCall("openai", body, 3), true);
});

test("identifies the collapsed shape: system + directive only", () => {
const body = openaiBody([
{ role: "system", content: "you are dsh" },
{ role: "user", content: INSTRUCTION },
]);
assert.equal(isDshCompactionCall("openai", body, 2), true);
});

test("directive as content-parts array still matches", () => {
const body = openaiBody([
{ role: "user", content: giantPrefix },
{ role: "user", content: [{ type: "text", text: " " + INSTRUCTION }] },
]);
assert.equal(isDshCompactionCall("openai", body, 2), true);
});

test("multi-message turn quoting the template mid-history is NOT intercepted", () => {
const msgs = Array.from({ length: 107 }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: `msg ${i}` }));
msgs.push({ role: "user", content: INSTRUCTION });
const body = openaiBody(msgs);
assert.equal(isDshCompactionCall("openai", body, msgs.length), false);
});

test("message count above the shape bar is never intercepted", () => {
const body = openaiBody([
{ role: "user", content: "a" },
{ role: "assistant", content: "b" },
{ role: "user", content: "c" },
{ role: "assistant", content: "d" },
{ role: "user", content: INSTRUCTION },
]);
assert.equal(isDshCompactionCall("openai", body, 5), false);
assert.ok(5 > DSH_COMPACTION_MAX_MESSAGES);
});

test("directive text NOT at the head of the final user message is not intercepted", () => {
const body = openaiBody([
{ role: "user", content: giantPrefix },
{ role: "user", content: `What does this template mean?\n\n${INSTRUCTION}` },
]);
assert.equal(isDshCompactionCall("openai", body, 2), false);
});

test("anthropic messages shape is covered", () => {
const body = { model: "m", system: "s", max_tokens: 8192, messages: [
{ role: "user", content: giantPrefix },
{ role: "user", content: [{ type: "text", text: INSTRUCTION }] },
] };
assert.equal(isDshCompactionCall("anthropic", body, 2), true);
});

test("out-of-scope protocols and missing shapes never intercept", () => {
const body = openaiBody([{ role: "user", content: INSTRUCTION }]);
assert.equal(isDshCompactionCall("google", body, 1), false);
assert.equal(isDshCompactionCall("responses", body, 1), false);
assert.equal(isDshCompactionCall(null, body, 1), false);
assert.equal(isDshCompactionCall("openai", { input: [{ type: "message", role: "user", content: INSTRUCTION }] }, null), false);
assert.equal(isDshCompactionCall("openai", null, 1), false);
});

test("refusal bodies carry the marker reason and are non-retryable", () => {
const openai = dshCompactionRefusal("openai") as { status: number; body: { error: { retryable: boolean; message: string } } };
assert.equal(openai.status, 403);
assert.equal(openai.body.error.retryable, false);
assert.match(openai.body.error.message, /#1729/);
const anthropic = dshCompactionRefusal("anthropic") as { status: number; body: { error: { message: string } } };
assert.equal(anthropic.status, 403);
assert.match(anthropic.body.error.message, /durably/);
});

test("the versioned marker prefix matches the live dsh template", () => {
assert.ok(INSTRUCTION.startsWith(DSH_COMPACTION_INSTRUCTION_PREFIX));
});
Loading