Skip to content
Open
23 changes: 18 additions & 5 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ import { buildForgeResponse, classifierForgeVariant, estimateCjkTokens, isAutoMo
import { extractConversationId, isV1BackgroundSideRequest, isV1InternalRequest, unwrapV1Internal } from "../v1internal.js";
import { anthropicBetaContextWindow, anthropicBetaMessageThreads, BILI_HOP_HEADER, capRegistryWindowByStandard, expandedContextSuffixWindow, launcherContextWindow, launcherMaxOutput, noteUnresolvedModelSession, UNRESOLVED_MODEL_SESSION_THRESHOLD, windowSourceLogged } from "./context-window.js";
import { NO_IDENTITY_MESSAGE, safeSessionId } from "./headers.js";
import { demoteGate, hasLeakedBiliToolsOnly, hasSingleShotBudget, isAudioOutputCall, isClaudeCodeTitleRequest, isDshAutoReviewRequest, isDshSingleShotSidecar, isDshTitleRequest, isMcodeOneShotAuxRequest, isMcodeTitleRequest, isOpencodeTitleRequest, isResponsesServerToolSingleShot, isServerToolUtilityCall, isSideRequest, isStructuredOutputCall, resolveSideLane, restoreOutputBudget, sideRequestGuard, stripLeakedBiliTools } from "./side-request.js";
import { demoteGate, hasLeakedBiliToolsOnly, hasSingleShotBudget, isAudioOutputCall, isClaudeCodeTitleRequest, isClaudeNotificationRequest, isDshAutoReviewRequest, isDshSingleShotSidecar, isDshTitleRequest, isMcodeOneShotAuxRequest, isMcodeTitleRequest, isOpencodeTitleRequest, isResponsesServerToolSingleShot, isServerToolUtilityCall, isSideRequest, isStructuredOutputCall, resolveSideLane, restoreOutputBudget, sideRequestGuard, stripLeakedBiliTools } from "./side-request.js";
import { DSH_COMPACTION_SHAPE_MSGS, DSH_REFUSAL_STORM_LOG_EVERY, detectPassthroughDshCompactionCall, dshCompactionRefusal, dshPassthroughGuardStats, isDshCompactionCall } from "./dsh-compaction-guard.js";
import { buildDshCompactionForgeBody, renderDshAuthoredCheckpoint } from "./dsh-authored-compaction.js";
import { artifactSeedHit, detectAcpArtifacts } from "./chain-artifacts.js";
Expand Down Expand Up @@ -1252,6 +1252,12 @@ async function handleRequest(
// proxy-mode traffic never reaches it because the plugin header gate
// fails first).
const sideAgent = pluginRequestAgentHeader(req.headers);
// #4840: Claude Desktop's Code-tab notification classifier — see
// isClaudeNotificationRequest. Computed once here so all four consumers
// (persona keying below, restoreOutputBudget and the lane decisions further
// down) share one verdict; explicit main intent vetoes it, like the
// dsh-title/review clauses do.
const claudeNotificationSidecar = sideAgent !== "main" && isClaudeNotificationRequest(parsed);
// #5135: claude code session-title sidecar (proxy mode, header-less):
// fires ~1ms ahead of the first main turn under the SAME
// x-claude-code-session-id. Recognize it by shape so it neither claims
Expand Down Expand Up @@ -1382,7 +1388,10 @@ async function handleRequest(
|| (pluginAgentHeader(req.headers) !== undefined && sideAgent !== "main"
&& req.headers["x-bili-ws-lane"] === undefined
&& hasLeakedBiliToolsOnly(parsed)
&& detectAcpArtifacts(bodyBuffer, parsed) === null));
&& detectAcpArtifacts(bodyBuffer, parsed) === null)
// #4840: the notification classifier resolves verbatim too — a request
// taking the #388 passthrough never participates in persona keying.
|| claudeNotificationSidecar);
// #1916/#1307/#1314: the dsh persona fingerprint — dsh stamps ONE
// conversation id on every model request of a session, INCLUDING the
// auto-review classifyRisk() calls (fixed REVIEW_POLICY system + a
Expand Down Expand Up @@ -2576,7 +2585,10 @@ async function handleRequest(
// outputBudgetHighWater from it would poison the first starved restore
// (title requests arrive FIRST, at session start). Starved all-bili requests
// never reach here demoted: stripLeakedBiliTools vetoes them per #546.
if (!demotedSide && !serverToolUtility && !structuredOutputUtility && !audioOutputUtility) {
// #4840: the Claude Desktop notification classifier is skipped too — its 3072
// max_tokens sizes a one-shot side call, not a main turn, so seeding the
// high-water from it would poison the first starved restore of the main lane.
if (!demotedSide && !serverToolUtility && !structuredOutputUtility && !audioOutputUtility && !claudeNotificationSidecar) {
// #3438: the dsh host contract (pi-ai buildBaseOptions) stamps the model-declared
// maxTokens on every main turn, so on this lane a below-ceiling tool-carrying
// budget is a raw-history collapse, not intent — arm the mid-band rescue.
Expand Down Expand Up @@ -2772,7 +2784,8 @@ async function handleRequest(
// the #388 passthrough (kernel state untouched) like every other
// recognized side request.
const sideIntent = isSideRequest(parsed, declaredPiMainTurn ? "main" : requestAgent, declaredPurpose) || dshTitleSidecar || dshReviewSidecar || dshSingleShotSidecar || ccTitleSidecar
|| grokAuxSidecar || mcodeTitleSidecar || mcodeOneShotSidecar || gooseSingleShotSidecar || codebuddyCompactionSidecar || opencodeTitleSidecar;
|| grokAuxSidecar || mcodeTitleSidecar || mcodeOneShotSidecar || gooseSingleShotSidecar || codebuddyCompactionSidecar || opencodeTitleSidecar
|| claudeNotificationSidecar;
// #388/#2157 follow-up: side requests must not touch kernel state under
// a public-fork receipt either. The receipt's first-request check above
// has already accepted this request (inherited prefix matched, or live
Expand All @@ -2796,7 +2809,7 @@ async function handleRequest(
// #2500 server-tool utility shape) diverts under a receipt.
// #2170 measure 1: the decision itself is resolveSideLane() (pure,
// truth-table-tested); demotedSide ⊆ lane==="side" by construction.
const sideLane = resolveSideLane({ countTokens, responsesCompact, protocol, stripApplied: demotedSide, sideIntent, requestAgent, sideLabel: declaredPurpose !== undefined ? `declared purpose=${declaredPurpose} (#6880)` : serverToolUtility ? "server-tool utility call (#2500)" : structuredOutputUtility ? "structured-output utility call (#5073)" : audioOutputUtility ? "audio-output utility call (#6636)" : dshTitleSidecar ? "dsh title-gen sidecar (#2503)" : dshReviewSidecar ? "dsh auto-review sidecar (#4438)" : dshSingleShotSidecar ? "dsh single-shot sidecar (#5656)" : ccTitleSidecar ? "claude-code title-gen sidecar (#5135)" : grokAuxSidecar ? "grok auxiliary sidecar (#6884)" : mcodeTitleSidecar ? "mcode title sidecar (#6884)" : mcodeOneShotSidecar ? "mcode one-shot aux sidecar (#6884)" : gooseSingleShotSidecar ? "goose single-shot sidecar (#6884)" : codebuddyCompactionSidecar ? "codebuddy compaction sidecar (#6884)" : opencodeTitleSidecar ? "opencode title-gen sidecar (#6884)" : undefined });
const sideLane = resolveSideLane({ countTokens, responsesCompact, protocol, stripApplied: demotedSide, sideIntent, requestAgent, sideLabel: declaredPurpose !== undefined ? `declared purpose=${declaredPurpose} (#6880)` : serverToolUtility ? "server-tool utility call (#2500)" : structuredOutputUtility ? "structured-output utility call (#5073)" : audioOutputUtility ? "audio-output utility call (#6636)" : dshTitleSidecar ? "dsh title-gen sidecar (#2503)" : dshReviewSidecar ? "dsh auto-review sidecar (#4438)" : dshSingleShotSidecar ? "dsh single-shot sidecar (#5656)" : ccTitleSidecar ? "claude-code title-gen sidecar (#5135)" : grokAuxSidecar ? "grok auxiliary sidecar (#6884)" : mcodeTitleSidecar ? "mcode title sidecar (#6884)" : mcodeOneShotSidecar ? "mcode one-shot aux sidecar (#6884)" : gooseSingleShotSidecar ? "goose single-shot sidecar (#6884)" : codebuddyCompactionSidecar ? "codebuddy compaction sidecar (#6884)" : opencodeTitleSidecar ? "opencode title-gen sidecar (#6884)" : claudeNotificationSidecar ? "claude notification classifier sidecar (#4840)" : undefined });
if (sideLane.lane === "side") {
// #554: the passthrough below skips EVERY input-side guard by design
// (#388) — a full-history side request over the window is a
Expand Down
85 changes: 85 additions & 0 deletions src/server/side-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,91 @@ export function hasSingleShotBudget(parsed: unknown): boolean {
return typeof budget === "number" && budget > 0 && budget <= SINGLE_SHOT_SIDECAR_MAX_BUDGET;
}

// #4840: Claude Desktop's Code-tab notification classifier fires a side call under
// the MAIN conversation id: a FIXED system sentence + exactly ONE freshly-built
// user blob carrying four ordered status labels (Current state / Tool calls so far
// / User's most recent ask / Assistant message tail), NO tools, max_tokens=3072 —
// above the <=200 budget gate, so pre-fix none of the signals saw it. It rode the
// FULL pipeline as a main turn: its usage sample replaced the main baseline, its
// model (Haiku) became the session's last model, and its single-message payload
// clobbered the persisted snapshot + ledger. Identified by shape alone (the #4438
// auto-review discipline): the fixed system + the four ordered labels carry their
// own client evidence, and a real main turn can NEVER match — it carries a tools
// surface and multi-turn history, and never carries these classifier labels. The
// last label's "(last N chars)" count is DYNAMIC (observed 913, varies per call):
// matched by shape, never hardcoded.
export const CLAUDE_NOTIFICATION_SYSTEM_PREFIX = "A user kicked off a Claude Code agent to do a coding task and walked away.";

// The three fixed status labels that must precede the dynamic tail label, in order.
const CLAUDE_NOTIFICATION_LABELS = ["Current state:", "Tool calls so far:", "User's most recent ask:"] as const;
// The fourth label's tail length varies per call (#4840: observed 913) — regex, not literal.
const CLAUDE_NOTIFICATION_TAIL_LABEL = /Assistant message tail \(last \d+ chars\):/;

export function isClaudeNotificationRequest(parsed: unknown): boolean {
if (!parsed || typeof parsed !== "object") return false;
const p = parsed as Record<string, unknown>;
// Same no-tools veto as isSideRequest/isDshTitleRequest/isDshAutoReviewRequest:
// any action surface marks an agent turn, not the classifier's one-shot call.
if (Array.isArray(p.tools) && p.tools.length > 0) return false;
// The fixed classifier policy on ANY wire's system carrier (top-level system,
// instructions, systemInstruction.parts, or a role:system entry in
// messages[]/input[]) — systemCarrierTexts reads them all (#3149 lesson).
if (!systemCarrierTexts(p).some((t) => t.trimStart().startsWith(CLAUDE_NOTIFICATION_SYSTEM_PREFIX))) return false;
const entries = firstPresentArray(p.messages, p.input, p.contents);
if (!entries) return false;
let users = 0;
let content: string | null = null;
for (const entry of entries) {
if (entry === null || typeof entry !== "object") continue;
const rec = entry as Record<string, unknown>;
if (rec.role === "system" || rec.role === "developer") continue;
// Responses-side typed items that are not plain messages (reasoning,
// function_call, …) can only appear in a real model round-trip.
if (rec.type !== undefined && rec.type !== "message") return false;
users += 1;
if (content !== null) return false;
content = plainTextContent(rec.content ?? rec.parts);
if (content === null) return false;
}
// Exactly ONE non-system message whose content is plain text carrying the four
// ordered labels: the freshly-built classification snapshot. A replayed history
// (any assistant/tool turn or a second user message) vetoes, as does any
// non-text block — see the comment above the constant.
return users === 1 && content !== null && hasOrderedLabels(content);
}

function firstPresentArray(...arrays: unknown[]): unknown[] | null {
for (const a of arrays) if (Array.isArray(a)) return a;
return null;
}

function plainTextContent(c: unknown): string | null {
if (typeof c === "string") return c;
if (Array.isArray(c)) {
let out = "";
for (const b of c) {
if (typeof b === "string") { out += b; continue; }
if (b && typeof b === "object") {
const o = b as Record<string, unknown>;
if (o.type === "text" && typeof o.text === "string") { out += o.text; continue; }
}
return null;
}
return out;
}
return null;
}

function hasOrderedLabels(s: string): boolean {
let pos = 0;
for (const label of CLAUDE_NOTIFICATION_LABELS) {
const i = s.indexOf(label, pos);
if (i < 0) return false;
pos = i + label.length;
}
return CLAUDE_NOTIFICATION_TAIL_LABEL.test(s.slice(pos));
}

// #5656/#5584: dsh's per-feature sidecar pins above (title #2503, auto-review
// #4438) are whack-a-mole — every NEW one-shot sidecar dsh ships around the
// main conversation (prompt-enhance in #5656: "请重写以下提示词…" rewrites the
Expand Down
Loading
Loading