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
78 changes: 75 additions & 3 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, isResponsesServerToolSingleShot, isServerToolUtilityCall, isSideRequest, isStructuredOutputCall, resolveSideLane, restoreOutputBudget, sideRequestGuard, stripLeakedBiliTools } from "./side-request.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 { 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 @@ -322,6 +322,17 @@ function memProbe(debug: boolean, log: (level: string, msg: string) => void, ses
log("debug", `[${sessionId}] mem-probe ${stage}: heap=${mi(mu.heapUsed)} external=${mi(mu.external)} rss=${mi(mu.rss)}${payloadBytes !== undefined ? ` payload=${payloadBytes}B` : ""}`);
}

// #6884: non-empty header presence, proto-agnostically over Node's header map
// (string values, string[] tolerated for folded multi-values; anything else
// counts as absent). Lane evidence for the wire-client sidecar clauses in
// handleRequest — same trust tier as the verbatim session-id roster
// (src/session-id.ts): the header is client-stamped, not bili-derived.
function hasNonEmptyHeader(h: Record<string, unknown>, name: string): boolean {
const v = h[name];
if (typeof v === "string") return v.length > 0;
if (Array.isArray(v)) return v.some((x) => typeof x === "string" && x.length > 0);
return false;
}
async function handleRequest(
req: http.IncomingMessage,
res: http.ServerResponse,
Expand Down Expand Up @@ -1267,6 +1278,58 @@ async function handleRequest(
// small maxTokens and no tools must enter the kernel pipeline.
const declaredPiMainTurn = rawDeclaredPurpose === PLUGIN_PURPOSE_CONVERSATION
&& pluginAgentHeader(req.headers) === "pi";
// #6884 wire-client legs (the cross-agent session-identity audit;
// follow-on to #7077): every client on the verbatim roster
// (src/session-id.ts) mints ONE id per logical conversation and
// source review confirmed the lifecycles are healthy — but each fires
// auxiliary LLM calls (titles, compaction, suggestions, memory,
// naming) UNDER THE SAME id, and those shapes defeat isSideRequest,
// so they enter the main session's kernel pipeline as conversation
// turns. Each clause is gated on the client's OWN wire signal (its
// session header / its compaction header / its constant User-Agent) —
// the same trust tier as the roster itself; no clause identifies a
// client from body shape alone. Upstream evidence per client:
// - grok-shell: main turns ALWAYS stamp x-grok-turn-idx
// (turn.rs:3002-3003); every auxiliary path (/btw, compaction,
// title refresh, recap, memory, ...) stamps x-grok-session-id
// WITHOUT the turn index — grok's own test-support contract
// (README:32): "a non empty x-grok-turn-idx makes it foreground,
// else a non empty x-grok-req-id makes it auxiliary". One header
// clause covers every present AND future auxiliary path.
// - mcode: title-gen's entire tool surface is the single
// submit_session_title tool; the prompt suggestion (default on,
// every accepted answer) and the Goal evaluator are tool-less,
// budget-less single user messages reusing the main turn's
// headers (prompt-suggestion-service.ts:655-692).
// - goose: every auxiliary (naming, compaction, tool-pair summaries,
// labels, adversarial review, apps, summarize) is the dsh
// single-shot shape — no tools + exactly one user + a system
// carrier holding the context — so isDshSingleShotSidecar covers
// it as-is; the lane evidence is the roster header
// agent-session-id. Residual, accepted: the permission judge
// carries one tool (#546 main rung) and a user who configures
// zero tools loses the first turn only (#5687 class).
// - CodeBuddy: the compaction request itself carries x-compaction
// on the wire (identity-codebuddy.ts) — consume it. Deliberately
// NOT x-context-compacted: that marks "context already compacted"
// and appears on ordinary POST-compaction MAIN turns; consuming
// it would demote the real mainline.
// - opencode: the built-in title agent fires concurrently with the
// first main turn of every root session, under the root's own id,
// no tools, no budget, single user framed by a fixed template
// (session/title.ts:37-41); the User-Agent (app.ts:22 constant
// format) is the lane evidence and the template text the shape.
const grokAuxSidecar = hasNonEmptyHeader(req.headers, "x-grok-session-id")
&& !hasNonEmptyHeader(req.headers, "x-grok-turn-idx");
const mcodeLane = hasNonEmptyHeader(req.headers, "x-mavis-session-id");
const mcodeTitleSidecar = mcodeLane && isMcodeTitleRequest(parsed);
const mcodeOneShotSidecar = mcodeLane && isMcodeOneShotAuxRequest(protocol, parsed);
const gooseSingleShotSidecar = hasNonEmptyHeader(req.headers, "agent-session-id")
&& isDshSingleShotSidecar(protocol, parsed);
const codebuddyCompactionSidecar = hasNonEmptyHeader(req.headers, "x-compaction");
const opencodeTitleSidecar = isOpencodeTitleRequest(protocol, parsed)
&& (typeof req.headers["user-agent"] === "string"
&& req.headers["user-agent"].startsWith("opencode/"));
const sideRequestLike = !countTokens && !responsesCompact && protocol !== null
&& (isSideRequest(parsed, declaredPiMainTurn ? "main" : sideAgent, declaredPurpose)
// #2503: dsh title sidecar — its output budget grew past the
Expand Down Expand Up @@ -1297,6 +1360,14 @@ async function handleRequest(
// #5135: the claude code title sidecar stays off the raw-key
// anchor claim and off the kernel pipeline entirely.
|| ccTitleSidecar
// #6884: the wire-client auxiliary sidecars (clause evidence
// above) — same raw-key/anchor discipline as ccTitleSidecar:
// verbatim passthrough, kernel state untouched, no |sub: fork.
|| grokAuxSidecar
|| mcodeTitleSidecar || mcodeOneShotSidecar
|| gooseSingleShotSidecar
|| codebuddyCompactionSidecar
|| opencodeTitleSidecar
|| (pluginAgentHeader(req.headers) !== undefined && sideAgent !== "main"
&& req.headers["x-bili-ws-lane"] === undefined
&& hasLeakedBiliToolsOnly(parsed)
Expand Down Expand Up @@ -2689,7 +2760,8 @@ async function handleRequest(
// #5135: ccTitleSidecar joins the intent set so the title call rides
// the #388 passthrough (kernel state untouched) like every other
// recognized side request.
const sideIntent = isSideRequest(parsed, declaredPiMainTurn ? "main" : requestAgent, declaredPurpose) || dshTitleSidecar || dshReviewSidecar || dshSingleShotSidecar || ccTitleSidecar;
const sideIntent = isSideRequest(parsed, declaredPiMainTurn ? "main" : requestAgent, declaredPurpose) || dshTitleSidecar || dshReviewSidecar || dshSingleShotSidecar || ccTitleSidecar
|| grokAuxSidecar || mcodeTitleSidecar || mcodeOneShotSidecar || gooseSingleShotSidecar || codebuddyCompactionSidecar || opencodeTitleSidecar;
// #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 @@ -2713,7 +2785,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)" : 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)" : 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
130 changes: 130 additions & 0 deletions src/server/side-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,136 @@ export function isClaudeCodeTitleRequest(protocol: string | null, parsed: unknow
return text.trimStart().startsWith(CLAUDE_CODE_TITLE_SESSION_TAG);
}

// #6884 (wire-client legs of the cross-agent session-identity audit; follow-on
// to the pi purpose declaration in #7077): every client on the verbatim
// session-id roster (src/session-id.ts — grok-shell, mcode, goose, CodeBuddy,
// opencode) mints ONE id per logical conversation and per-client source review
// confirmed the lifecycle is healthy (forks/subagents mint fresh ids with a
// parent pointer). The exposure is elsewhere: each fires auxiliary LLM calls
// (titles, compaction, suggestions, memory, naming) UNDER THE SAME id, and
// their body shapes defeat isSideRequest (no tools plus a missing, small or
// large budget), so they would enter the main session's kernel pipeline as
// conversation turns. Each predicate below is a SHAPE only — the caller must
// gate it on the client's own wire signal (its session header / compaction
// header / constant User-Agent), the same trust tier as the roster itself.

// mcode's title sidecar calls the model with EXACTLY ONE tool —
// `submit_session_title` (session-title-model-adapter.ts:17, pinned budget
// TITLE_MAX_TOKENS=1000) — under the main conversation's mvs_ id. A main turn
// never matches: it carries mcode's full tool surface beside the title tool,
// so the length-1 bar rejects every real turn. Name is read proto-
// agnostically (openai `{function:{name}}` and flat `{name}`).
export const MCODE_TITLE_TOOL = "submit_session_title";
export function isMcodeTitleRequest(parsed: unknown): boolean {
if (!parsed || typeof parsed !== "object") return false;
const tools = (parsed as Record<string, unknown>).tools;
if (!Array.isArray(tools) || tools.length !== 1) return false;
const t = tools[0];
if (t === null || typeof t !== "object") return false;
const o = t as Record<string, unknown>;
if (o.name === MCODE_TITLE_TOOL) return true;
const fn = o.function;
return fn !== null && typeof fn === "object" && (fn as Record<string, unknown>).name === MCODE_TITLE_TOOL;
}

// mcode's prompt suggestion (default ON — fired after every accepted answer)
// and its Goal evaluator send a tool-less, BUDGET-LESS single user message
// reusing the main turn's resolved headers, including x-mavis-session-id
// (prompt-suggestion-service.ts:655-692; the evaluator's 32k budget variant
// keeps the same shape). Budget-less defeats the <=200 rung and no-tools
// defeats the #546 main rung, so isSideRequest can never see them — hence
// this dedicated clause. A real mcode main turn vetoes at every bar: it
// carries the full tool surface, and turn 2+ replays assistant/tool history
// (the role loop below rejects any non-user entry). Residual, accepted (same
// class as #5687): a tool-less FIRST main turn under a zero-tools config rides
// the side lane for that one turn; the next turn replays history and rejoins
// the full pipeline. No system carrier is required (the suggestion sends
// none) — that is the difference from isDshSingleShotSidecar.
export function isMcodeOneShotAuxRequest(protocol: string | null, parsed: unknown): boolean {
if (protocol === null || !parsed || typeof parsed !== "object") return false;
const p = parsed as Record<string, unknown>;
// Same no-tools veto as isSideRequest/isDshTitleRequest: any action surface
// marks an agent turn.
if (Array.isArray(p.tools) && p.tools.length > 0) return false;
const entries = protocol === "responses" ? p.input : protocol === "google" ? p.contents : p.messages;
if (!Array.isArray(entries)) return false;
let users = 0;
let userHasContent = false;
for (const entry of entries) {
if (entry === null || typeof entry !== "object") continue;
const rec = entry as Record<string, unknown>;
const role = rec.role;
if (role === "system" || role === "developer") continue;
// The replay veto: ANY assistant/tool turn is a history resend, not a
// one-shot auxiliary call.
if (role !== "user") return false;
if (rec.type !== undefined && rec.type !== "message") return false;
users += 1;
const c = rec.content ?? rec.parts;
if (typeof c === "string") {
if (c.length > 0) userHasContent = true;
} else if (Array.isArray(c) && c.length > 0) {
userHasContent = true;
}
}
return users === 1 && userHasContent;
}

// opencode's built-in title agent (on by default) fires CONCURRENTLY with the
// first main turn of every root session, under the root session's OWN id
// (runner/llm.ts:202): a single user message framed by a fixed wire template
// (session/title.ts:37-41), no tools, and NO output budget (kind==="title" →
// options {} — see the #1699 note at the top of this file). The #1699 defense
// covers only PLUGIN installs (x-bili-plugin-agent: title); the caller gates
// this clause on the opencode User-Agent (app.ts:22 — a constant format
// "opencode/<channel>/<version>/<name>", not a plugin signal), so this closes
// the pure-proxy gap. Both frame variants are pinned: the first-turn call and
// the regeneration call (≤8000 chars of history, same framing).
export const OPENCODE_TITLE_FRAME_PREFIXES: readonly string[] = [
"Here is the first message of the conversation:",
"Here is the conversation so far:",
];
export function isOpencodeTitleRequest(protocol: string | null, parsed: unknown): boolean {
if (protocol === null || !parsed || typeof parsed !== "object") return false;
const p = parsed as Record<string, unknown>;
// No-tools veto (same discipline as every clause above).
if (Array.isArray(p.tools) && p.tools.length > 0) return false;
// Budget-LESS is part of the pinned shape (kind==="title" sends options {}):
// a budgeted single-user request is not the title agent's wire form.
if (outputBudgetField(p) !== null) return false;
// ONE user entry total: on the chat wires the system prompt rides INSIDE
// messages[] (so the entry count cannot be the bar — that is the #3149
// class of bug); any assistant/tool row is a replayed history and vetoes,
// and a second user entry does too.
const entries = protocol === "responses" ? p.input : protocol === "google" ? p.contents : p.messages;
if (!Array.isArray(entries)) return false;
let userText: string | null = null;
for (const entry of entries) {
if (entry === null || typeof entry !== "object") continue;
const rec = entry as Record<string, unknown>;
const role = rec.role;
if (role === "system" || role === "developer") continue;
if (role !== "user") return false;
if (rec.type !== undefined && rec.type !== "message") return false;
if (userText !== null) return false;
const c = rec.content ?? rec.parts;
let text = "";
if (typeof c === "string") {
text = c;
} else if (Array.isArray(c)) {
for (const b of c) {
if (b !== null && typeof b === "object" && typeof (b as Record<string, unknown>).text === "string") {
text += (b as Record<string, unknown>).text as string;
}
}
}
userText = text;
}
if (userText === null) return false;
const t = userText.trimStart();
return OPENCODE_TITLE_FRAME_PREFIXES.some((prefix) => t.startsWith(prefix));
}

// #2170 measure 1: the two lane gates extracted from src/server.ts so they have
// ONE home and an exhaustive truth-table test. They are PURE — the two effects
// that guard demotion (detectAcpArtifacts' full-history re-encode and the
Expand Down
7 changes: 5 additions & 2 deletions src/session-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,11 @@ export function conversationHeaderSource(headers: Record<string, string | string
// unchanged below.
// x-grok-session-id next: grok-shell (xAI's CLI) stamps its per-session
// UUID on every model request (verified against grok-shell 1.0.34; the
// parallel x-grok-conv-id carries the same value and stays as a
// fallback). Client-specific name — same trust class as the claude
// parallel x-grok-conv-id carries the same value on the main conversation
// and stays as a fallback — but the #6884 source audit found that on the
// Responses-backend auxiliary paths it instead carries a TAGGED value
// (recap-<uuid> / btw-<uuid>), so the session id is the only trustworthy
// one there). Client-specific name — same trust class as the claude
// header above: without it the request is anonymous and falls to
// prefix-affinity, which forks every turn because grok-shell reorders
// its replayed history head between turns.
Expand Down
Loading
Loading