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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite
- **proxy mode** (plain client, no header): the proxy executes `compress` server-side; the tool call is ephemeral (never enters the client's history) and preflight blocks have none, so the carrier is the **`acp_summary` message** — the kernel renders it role `system`, but `systemToUser` (`src/util.ts`) re-voices it as a **`user` message** (leaving it at its anchor) so strict backends (SGLang: exactly one system at index 0, #377) accept it and the head system message stays byte-stable for the prefix cache.
- The mode is decided per request and bound per session (`session.metadata.pluginAgent`, sticky, upgrade-only). See TECHNICAL-NOTES.md "Two compression modes".
8. **Nudge cadence is flat 50K by design (kernel contract)** — acp-kernel pins the growth interval at 50000 for every window size (`nudge.growthFloor == nudge.growthCap == 50000`; window-percentage scaling was deliberately removed — #379/#380 settled "growth-driven, no usage/count proxy gates"). Do NOT re-scale the interval with the context window or reintroduce percentage gates; a 1M-window session folding every 50K of growth is intended lean-context behavior. User escape hatch: `compress.nudgeGrowthTokens` (flattens `growthFloor`+`growthCap` to a fixed step) — big-window users who want a lazier cadence set it explicitly. Prompt wording is kernel-owned (`src/nudge-text.ts`).
9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `<id>|sub:<fp>` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`.
9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `<id>|sub:<fp>` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim); SIDE REQUESTS never claim the anchor either — dsh's title-gen sidecar fires at session start before/concurrent with the first main turn, and claiming it would fork the whole main conversation onto `|sub:<fp>` while every host-stamped ACP management call (compress/decompress/acp_status) routes into the ghost's empty session and fails forever (#2156/#2160; the `sideRequestLike` gate in `src/server.ts` mirrors the #388 passthrough predicate). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`.

10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only.

Expand Down
45 changes: 37 additions & 8 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ import { buildForwardHeaders, connectionNamedHeaders, NO_IDENTITY_MESSAGE, RESPO
import { installWebSocketBridge } from "./ws-bridge.js";
import { codexResponsesCodec, responsesCodec } from "./responses-ws.js";
import { currentFetchTransport } from "./fetch-transport.js";
import { isSideRequest, outputBudgetField, restoreOutputBudget, SIDE_REQUEST_MAX_TOKENS, sideRequestGuard, stripLeakedBiliTools } from "./server/side-request.js";
import { hasLeakedBiliToolsOnly, isSideRequest, outputBudgetField, restoreOutputBudget, SIDE_REQUEST_MAX_TOKENS, sideRequestGuard, stripLeakedBiliTools } 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";
Expand Down Expand Up @@ -2172,6 +2172,33 @@ async function handle(
clientProvided: !!convHeader,
}
: undefined;
// #2156: a request that will ride the #388 side passthrough further
// down must NEVER participate in persona namespace resolution.
// subagentNamespace's first-seen-system anchor is mutable process
// state: whichever request arrives first under an identity claims the
// raw key. A side request carries kernel-no-touch status, yet anchoring
// it lets its utility system claim the raw key and fork every real
// main turn onto `|sub:<fp>` — the host-stamped bare id then finds
// zero refs and compress fails permanently (this issue). Side requests
// therefore resolve VERBATIM: they neither read nor write the anchor
// and share the main session key per the #388 contract (before the
// fix, once any main turn had anchored, they instead rode junk
// `|sub:<fp(side)>` sessions). Mirrors the #388 lane condition below
// minus publicForkPrefix, which needs the session resolved AFTER this
// point: a public-fork child arrives under a FRESH childConversationId
// where first-seen anchoring returns the raw key anyway, so omitting
// the veto cannot move any key. detectAcpArtifacts stays last — it
// re-encodes the whole history and must only run for the all-bili
// subset (same short-circuit discipline as the demotedSide gate below;
// proxy-mode traffic never reaches it because the plugin header gate
// fails first).
const sideAgent = pluginRequestAgentHeader(req.headers);
const sideRequestLike = !countTokens && !responsesCompact && protocol !== null
&& (isSideRequest(parsed, sideAgent)
|| (pluginAgentHeader(req.headers) !== undefined && sideAgent !== "main"
&& req.headers["x-bili-ws-lane"] === undefined
&& hasLeakedBiliToolsOnly(parsed)
&& detectAcpArtifacts(bodyBuffer, parsed) === null));
// #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 @@ -2206,11 +2233,11 @@ async function handle(
// across main and subagent sessions.
(claudeSub !== undefined && opts.subagentSplit !== false
? claudeSubagentSplit(anthropicIdentity?.value ?? anthropicSignal, req.headers, systemTextsForSplit)
: dshPersona
: dshPersona && !sideRequestLike
? subagentNamespace(anthropicIdentity?.value ?? anthropicSignal, personaSystemText)
: anthropicIdentity?.value ?? anthropicSignal)
: protocol === "openai"
? (dshPersona
? (dshPersona && !sideRequestLike
? subagentNamespace(openaiIdentity?.value ?? openaiSignal, personaSystemText)
: openaiIdentity?.value ?? openaiSignal)
: codexTurn
Expand Down Expand Up @@ -2241,11 +2268,13 @@ async function handle(
// conversation evolved (upgrade / plugin / AGENTS.md),
// not a new persona. See instructionsFingerprintApplies
// in src/session-id.ts.
? subagentNamespace(
responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader),
(parsed as ResponsesRequestBody).instructions,
)
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader));
? (!sideRequestLike
? subagentNamespace(
responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader),
(parsed as ResponsesRequestBody).instructions,
)
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader)))
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader));
// #1916/#1307: true when the dsh persona fingerprint actually split
// this request onto a suffixed session key (kernel anchor mismatch).
// Used by the recordPluginSession branch below so the fork records
Expand Down
13 changes: 11 additions & 2 deletions src/server/side-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ function biliToolNamesIn(parsed: Record<string, unknown>): string[] | null {
* starved tool-carrying request is the death-spiral rescue path —
* restoreOutputBudget must run so the model regains the output room to emit
* compress — so such requests stay main turns even when every tool is bili's. */
export function stripLeakedBiliTools(parsed: unknown): boolean {
/** #2156: READ-ONLY structural twin of stripLeakedBiliTools — same verdict,
* no mutation. Lets callers (the persona-anchor bypass in server.ts) ask
* "would this request be demoted via #1897?" before any decision point that
* must not pay the mutation or re-run the check. */
export function hasLeakedBiliToolsOnly(parsed: unknown): boolean {
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
const p = parsed as Record<string, unknown>;
const names = biliToolNamesIn(p);
Expand All @@ -102,7 +106,12 @@ export function stripLeakedBiliTools(parsed: unknown): boolean {
const raw = readOutputBudget(p, field);
if (typeof raw === "number" && raw > 0 && raw <= SIDE_REQUEST_MAX_TOKENS) return false;
}
delete p.tools;
return true;
}

export function stripLeakedBiliTools(parsed: unknown): boolean {
if (!hasLeakedBiliToolsOnly(parsed)) return false;
delete (parsed as Record<string, unknown>).tools;
return true;
}

Expand Down
Loading
Loading