From 0f762381710b09a0e7c46f1c5864577f60b9b8c9 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Mon, 19 Oct 2026 00:30:50 +0800 Subject: [PATCH 1/6] dsh authored client compaction: answer the #1729 guard locally with the bili snapshot (#3733) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Post-#3644 the substrate concern behind the #1729 refusal is gone, but the refusal itself keeps dsh's context gauge growing and its session file ballooning unboundedly (#3723). When BILI_DSH_AUTHORED_COMPACTION=1 (env-only rollout, per-request) and the session holds an active fold block, the guard answers the compaction summarize call locally — zero egress, autoModeForge discipline — with the folded snapshot: identity header + kernel-rendered block summaries (byte-identical to what the model already reads upstream). dsh records it as its checkpoint; the file shrinks; display/context/server agree. Landing recognition is declarative (tag in the message text, #2621 carrier+novelty discipline) and flows the same #2432 rebase as a foreign checkpoint, recorded as dshAuthoredCheckpointLanded (info, not warn). Precedence: allowDshCompaction (forward native) wins; no active blocks falls through to the 422; passthrough-lane guard untouched. dshCompactionRefusedBytes high-water still recorded on authored answers (#2490 output-clamp regimes). Fixes #3733 --- CHANGELOG.md | 1 + CONFIGURATION.md | 2 + src/knobs.ts | 14 + src/server/dsh-authored-compaction.ts | 153 ++++++++++ src/server/handle.ts | 32 +- src/server/prepare-anthropic.ts | 8 +- src/server/prepare-google.ts | 8 +- src/server/prepare-openai.ts | 10 +- src/server/prepare-responses.ts | 8 +- tests/dsh-authored-compaction.test.ts | 416 ++++++++++++++++++++++++++ 10 files changed, 642 insertions(+), 10 deletions(-) create mode 100644 src/server/dsh-authored-compaction.ts create mode 100644 tests/dsh-authored-compaction.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f129729362..c6ab6dfb4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Changes +- **bili-authored dsh client compaction: the #1729 guard can now ANSWER instead of refuse (#3733, fixes #3723's growth loop).** dsh's own compaction was refused locally since #1729 because a landed dsh checkpoint durably shadows the raw history; post-#3644 that substrate concern is gone (the server snapshot is the base), but a native checkpoint is still a foreign summary and — worse — with the refusal standing, dsh's context gauge only grows while its session file balloons unboundedly (#3723: a 39.7 MB / 9001-message file choked the desktop UI). With `BILI_DSH_AUTHORED_COMPACTION=1` (env-only rollout window, read per-request), when the guard fires AND the session holds an active fold block, bili answers the compaction summarize call LOCALLY — zero egress, the autoModeForge discipline — with OUR folded snapshot as the payload: one identity header line `` plus every active block's summary in the kernel render format. dsh records that as its checkpoint, so the client file shrinks while the recorded content is byte-identical to what the upstream already reads — client display, model context and server state finally agree. The identity tag rides in the message text, so replay recognition is declarative (`carriesBiliSnapshotCheckpoint`, the #2621 carrier+novelty discipline): the #2432 rebase handles the landing exactly like a foreign checkpoint but records `dshAuthoredCheckpointLanded` and logs info instead of warn. Precedence: an explicit `allowDshCompaction` (forward natively) still wins; no active blocks → falls through to the same 422; the passthrough-lane guard (no session) is untouched. Originals stay recoverable via CCR/export/fork; `dshCompactionRefusedBytes` keeps recording the raw-ledger high-water on authored answers too, so the #2490 output-clamp regimes keep planning against the raw scale. - **Automatic upgrades now stagger across a window instead of landing within minutes; a public policy file controls the window fleet-wide (#3619).** Every bili instance that discovers a new version draws ONE random moment inside a delay window (built-in default **15 min – 48 h**), persists it, and upgrades when it arrives — restarts never re-roll. Before this, a release hit every auto-updating install within ~15–30 minutes, leaving no time to stop a bad one mid-rollout (#3401/#3600/#3394 were all shipped-too-fast incidents). The window and the emergency controls live in `auto-update-policy.json` in this repo, fetched anonymously (plain GET + ETag, zero telemetry, fail-open — an unreachable or malformed file falls back to local defaults): `hold` freezes automatic upgrades fleet-wide, `blocked` skips listed versions, `pinned` sets an upgrade ceiling, and per-version `overrides` tune the window (`{ "range": ">=0.1.200", "maxDelay": "1h" }`). Delay fields take human-readable durations — `"15m"`, `"2d"`, `"1d12h"` (units s/m/h/d/w, combinable; plain numbers still mean raw ms); malformed values are ignored with a warning, never guessed. The file steers timing/skip/pin only — it can never control what gets installed (no URLs, no commands; target versions must exist in the npm packument). Exits: manual `bili update` bypasses `hold`/stagger (still respects `blocked`/`pinned`), `update.staggerMinDelayMs: 0` + `update.staggerMaxDelayMs: 0` (or the `BILI_UPDATE_STAGGER_*_MS` twins) restore legacy immediate upgrades on one machine, `ACP_AUTO_UPDATE=0` disables auto-updates entirely. The update-driven e2e suites pin stagger 0/0 + an unroutable policy URL — they test periodic-update mechanics, not rollout timing. - **openai wire: non-array content tolerance (kernel 0.0.133, #3658 follow-up)** — the #3642 per-part rewrite iterated `messages[].content` and threw `TypeError: m.content is not iterable` on clients that emit a lone content-part object instead of an array (#2824 corpus caught it). Non-array non-string content now degrades to the legacy empty-text core (byte-compatible ids and bytes with the pre-#3642 codec) instead of throwing. Also regenerates the storage-render chat goldens for the documented one-time canonical re-key (tool-pair ids), and inverts the retired reconcile-off id-churn control into an absorption canary: with reconcile OFF, tool_call id rewrites + argument re-serialization must not disturb fold coverage (canonical ids absorb them by construction). - **protocol-stable core identity: the same logical conversation now yields byte-identical core message ids in all four dialects (#3642).** Wire codecs previously baked dialect accidents into message identity: anthropic used `"[image]"` as image text while openai deliberately kept `""` ("switching the seed would move every pre-existing shape"), tool-call ids embedded the provider's `toolCallId` bytes, raw JSON tool arguments hashed verbatim (key order = new id), and responses' empty-text reasoning cells seeded from the provider's volatile `item.id`. Switch protocols mid-session (opencode #3640: `/chat/completions` → `/v1/messages`) and ~20-68% of ids churned, tripping the fold-destroyed misdiagnosis #3641 just class-fixed. Identity now derives from a canonical form shared by all four codecs: a new `kernel/src/wire/identity.ts` (canonicalToolArgs: JSON args parsed → recursive key sort → compact stringify, verbatim for non-JSON; canonicalOpaqueSeed: provider `item.id`/`status` stripped; image marker `[image]` everywhere), the `toolCallId` slot retired from the seed (cluster suffixes disambiguate same-shape calls, deleting one sibling is local damage), and granularity normalized to one core per content part (anthropic's existing shape — its lanes take zero granularity re-keying, though tool-call/tool-result cores still re-seed since the `toolCallId` slot is retired; openai/responses/google split runs, with accumulators re-merging on rebuild so the wire stays byte-stable). The kernel first-user pin now spans the opening message's whole core run, so a multimodal opening message keeps its image bytes through folds (#781/#2607). Cross-protocol golden: text/tool/bash conversation → identical id arrays in all four dialects; canonical key-sort makes `{"file","line"}` == `{"line","file"}`. Image cells are now stamped `imagePart: true` at parse time (never text-compared — tag injection rewrites markers mid-render, which previously made image cores render as text and lose the real bytes, #767 billing fallout). Upgrade cost is one re-key of stored ids for openai/responses/google lanes; the #3641 reconcile tiers (word-bag claims, k-th image family pairing, toolCallId channel, epoch gate) absorb it without re-folding. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 4e0bb0788b..823df58ad0 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1857,7 +1857,9 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_RESUME_INHERITANCE` | Set `0` to turn OFF resume inheritance (ON by default) (#1486): when an identified client (sends its own session id, e.g. Claude Code's `x-claude-code-session-id`) resumes a conversation under a NEW session id while replaying the full transcript (`cc --resume` forks a fresh UUID), bili matches the incoming history byte-exactly against that client's tracked chains (≥8 messages, append-only tracking) and, on the resumed session's first request, inherits the parent's ref assignments — stale model citations then resolve to their ORIGINAL messages instead of mis-hitting renumbered ones — adopts the fully-present compression blocks (together with this inheritance, #1834: losing them on resume meant the folded originals came back on the wire and the upstream request ballooned; the old `forkAdoption` co-gate now applies only to anonymous forks, #629), and records the `derivedFrom` lineage. The parent is never modified and fresh messages number above the parent's ref space. A resume must strictly EXTEND the parent's history — an equal-depth byte-exact replay under another id is a duplicate, not a resume. Anonymous sessions are unaffected (they keep their own pfa-* world, #309). `"resumeInheritance": false` in the config file does the same; the env var wins. | | `BILI_STABLE_SYSTEM_ANCHOR` | Set `1` to enable stable-system anchoring (#1085) — a **best-effort wire-layer fallback** for prefix caching: the root fix belongs client-side (the client owns its history and decides how to present instruction changes), this only stops the proxy from letting a changed head invalidate the whole cached prefix. **Plain-proxy mode only**: plugin-mode agents (`x-bili-plugin`) own their context management and are never anchored, so clients that already inject cache-friendly updates (e.g. claude-code-style system reminders) are not double-processed. When enabled, bili remembers each session's first-seen head system/instructions block and keeps re-sending those exact bytes even when the client's system prompt later changes. A **localized** change (a file-style edit sharing ≥70% of lines with the version in effect so far) appends a trailing `[System context update] …` user note carrying a compact line diff (`-` removed / `+` added; each note composes sequentially onto the previous one). A **non-localized** change (structural reshuffle, tool-def churn, timestamped banners, heads over 400 lines) is adopted outright — one deliberate cache miss beats appending noise that would mislead the model about its instructions. Churn guard: more than 8 accumulated notes likewise replace the anchor with the newest text and clear the log. The anchor and note log persist with the session and survive compression/compaction (session metadata, not kernel state). Known residual limitation: client-placed `cache_control` breakpoints may still misalign after a head swap. Excluded from anchoring: title-gen micro-requests (OpenAI/Google), Responses compaction-trigger requests, auto-mode classifier requests. Clients implementing their own variant (stable prompt + in-history updates) get zero extra injection — such updates pass through as ordinary history. Default is OFF. `"stableSystemAnchor": true` in the config file does the same; the env var wins. | | `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. While the guard refuses, dsh's own context-pressure counter (its raw ledger) only grows — refused checkpoints never land — while bili's folds keep the wire payload small, so the session keeps working past the point where the client's gauge says "full", and dsh keeps re-requesting compaction (refused every time). Since #3384 the outgoing output budget is also no longer planned against that raw ledger, EXCEPT when bili's own folded view has already reached the enforced headroom target or the requested budget is >= 25% of the native window (the #2490 protection regimes) — before that fix the growing ledger silently shrank the model's output budget every turn, ending in error-free empty replies on onlyReasoning models. Scope note: on non-web profiles the shipped bundle patch (`auto: false`) still suppresses AUTO-triggering, so only manual `/compact` benefits there; on web profiles no patch layer can address the preset-nested row by id (#1772), so auto-triggering works as-is once allowed unless you apply the #2474 full-snapshot override of preset-standard from your profile's cordis.patch.yml. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | +| `BILI_DSH_AUTHORED_COMPACTION` | Set `1` to have bili itself ANSWER dsh's compaction summarize calls locally instead of refusing them (#3733). Prerequisites per call: the #1729 guard fires (marker-decisive), the session holds at least one ACTIVE fold block, and `allowDshCompaction` is NOT enabled (the explicit "forward natively" choice always wins). The reply is forged with zero egress (the autoModeForge #2740 discipline): an identity header `` plus every active block's summary in the kernel render format — exactly the bytes the model already reads upstream, so client display, upstream context and server state agree for the first time, and dsh's checkpoint file shrinks (#3723's unbounded growth loop). Originals stay recoverable via CCR/export; the landed checkpoint is recognized on replay through the same #2432 rebase as a foreign one, but recorded as `dshAuthoredCheckpointLanded` (info, not warn). Env-only for the rollout window; read per-request, no restart needed. | | `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. Scope note: with bili ON, dsh native auto-compaction is now off on every plane — the host-plane row via the shipped bundle patch (`auto: false`), and web-profile preset instances at load time via the #3354 overlay — so this switch mainly governs manual `/compact` on non-web profiles (auto-triggering stays suppressed there) and any residual auto-triggering on dsh builds where the #3354 overlay does not apply. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | +| `BILI_DSH_AUTHORED_COMPACTION` | Set `1` to have bili itself ANSWER dsh's compaction summarize calls locally instead of refusing them (#3733). Prerequisites per call: the #1729 guard fires (marker-decisive), the session holds at least one ACTIVE fold block, and `allowDshCompaction` is NOT enabled (the explicit "forward natively" choice always wins). The reply is forged with zero egress (the autoModeForge #2740 discipline): an identity header `` plus every active block's summary in the kernel render format — exactly the bytes the model already reads upstream, so client display, upstream context and server state agree for the first time, and dsh's checkpoint file shrinks (#3723's unbounded growth loop). Originals stay recoverable via CCR/export; the landed checkpoint is recognized on replay through the same #2432 rebase as a foreign one, but recorded as `dshAuthoredCheckpointLanded` (info, not warn). Env-only for the rollout window; read per-request, no restart needed. | | `BILI_NO_CACHE_CONTROL` | Set `1` to disable bili's Anthropic-lane `cache_control` breakpoint stamping (#1637, shipped in #1639). On by default: Anthropic-style upstreams cache only what is explicitly breakpointed (max 4 per request, counted across system + tools + message blocks combined), so bili marks the system block plus up to 3 cumulative message marks — a marked message stays marked (byte-stable prefix), marks die only by folding, and the last 3 stable messages carry the advancing frontier. Any client-set `cache_control` (message blocks, tools entries) suppresses bili's stamps entirely — client-managed caching wins. Marks persist with the session. This switch is the escape hatch for upstreams that reject the field or relays with their own breakpoint policy. Plain-proxy Anthropic lane only; OpenAI/Responses lanes cache implicitly and are never stamped. Config-file twin: [`compat.noCacheControl`](#compat) — the env var wins. | | `BILI_CHAIN_CONTENT` | Set `1` to turn ON the ACP-artifact / `` checkpoint **body-content** detection of bili→bili chain awareness (#1086/#1421): when an inbound request carries compression artifacts (render tags / historical `acp_status`+`search_context` tool calls) or a digest-bearing checkpoint in its BODY but neither the `x-bili-hop` header nor local compression state for its session, bili records an advisory observation and/or applies first-processor-wins passthrough. **Default is OFF** (#1683 follow-up): by default ONLY the `x-bili-hop` header drives chain recognition, because scanning the request BODY can false-positive on CCR/file-introduced text and model-echoed tags that look like real markers. Enable it only for the narrow multi-bili relay case where an intermediate box strips `x-bili-hop` and you accept that false-positive risk. `"chainContentDetection": true` in the config file does the same; the env var wins. The `x-bili-hop` signal itself is unaffected by this switch. | | `BILI_CHAIN_STAMP` | Set `1` to turn ON egress emission of the **model-visible** `` chain-integrity checkpoint carrier (#1683, default OFF): when enabled, every request THIS instance actually processes leaves with a digest-bearing stamp so a downstream bili applies first-processor-wins even when the `x-bili-hop` header was stripped in transit (#1421). The carrier lands in a slot the terminal model also reads (a trailing `user` message on OpenAI/Responses, a trailing text part on Anthropic/Google), so models treat it as phantom user input and burn tokens commenting on it — which is why it is off by default. Enable it only for the narrow multi-bili relay case where `x-bili-hop` is stripped by an intermediate box and the digest-verified body-stamp is the sole guard against double-processing. Independent of `BILI_CHAIN_CONTENT` (inbound body-detection is also default OFF) and of the `x-bili-hop` passthrough, which works either way. `"chainEgressStamp": true` in the config file does the same; the env var wins. | diff --git a/src/knobs.ts b/src/knobs.ts index 80beee71d1..c4cbc8386b 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -473,6 +473,20 @@ export function codexCompactMode(): CodexCompactMode { return loadConfigFile().codexCompact === "pass" ? "pass" : "intercept"; } +/** BILI_DSH_AUTHORED_COMPACTION — #3733 bili-authored dsh client compaction. + * Default OFF ("0"/unset): the #1729 guard keeps refusing dsh's native + * compaction summarize calls, exactly as before. "1": when the session + * holds active fold blocks, the guard site answers the call LOCALLY with + * our folded snapshot (zero egress) instead of refusing — dsh records our + * checkpoint and its file shrinks (#3733/#3723). Read per-request so a + * running proxy flips without a restart. Env-only for the rollout window; + * the #2028-style file/web toggle follows once adopted. */ +export function dshAuthoredCompactionEnabled(): boolean { + const envRaw = process.env.BILI_DSH_AUTHORED_COMPACTION; + if (envRaw !== undefined) return envRaw.trim() !== "0"; + return false; +} + /** BILI_DECOMPRESS_TMP_CAP > decompressTmpCap > 50. */ export function decompressTmpCap(): number { const v = tIntLoose("BILI_DECOMPRESS_TMP_CAP", loadConfigFile().decompressTmpCap); diff --git a/src/server/dsh-authored-compaction.ts b/src/server/dsh-authored-compaction.ts new file mode 100644 index 0000000000..8d96b7b154 --- /dev/null +++ b/src/server/dsh-authored-compaction.ts @@ -0,0 +1,153 @@ +// #3733: bili-authored dsh client compaction — the answer side of the #1729 +// guard. Post-#3644 (snapshot doctrine) a landed client checkpoint no longer +// destroys the server substrate, but a NATIVE dsh checkpoint is still a +// foreign summary: recognizable only fuzzily, and possibly inconsistent with +// what the upstream actually has. When the authored-compaction knob is on and +// the session holds active fold blocks, the guard site answers the compaction +// summarize call LOCALLY instead of refusing it — zero egress, the +// autoModeForge (#2740) discipline — with OUR folded snapshot as the payload: +// +// +// [Compressed conversation section] — … +// +// +// dsh records the response text as its checkpoint (wrapped in its own +// preamble/ framing), so the client file shrinks (fixes +// #3723's unbounded growth) while the recorded content is exactly what the +// model already sees upstream — client display, upstream context and server +// state agree for the first time. The identity header line rides in the +// message TEXT (clients resend message content verbatim), so recognition on +// replay is declarative (carriesBiliSnapshotCheckpoint below) instead of +// fuzzy; the #2432 landed-checkpoint rebase keeps handling the ACP-state side +// of the landing for ANY checkpoint, authored or foreign. +// +// Precedence at the guard site: authored (this module, knob + active blocks) +// replaces the DEFAULT refusal only — an explicit allowDshCompaction +// forward-native choice still wins over authoring, because that is the user +// asking for dsh's own behavior. The passthrough-lane copy of the guard +// (handle.ts #1117/#2709 site) has no session and therefore no snapshot to +// author; it keeps refusing. +import { renderForgedSummary, buildPromptForgeBody } from "../codex-compact.js"; + +/** Identity header prefix of an authored checkpoint. Angle brackets + * hex-escaped per KDD #2 (see dsh-compaction-guard.ts). */ +export const BILI_SNAPSHOT_TAG_PREFIX = "\x3cbili-snapshot v1 "; + +/** Renders the full checkpoint text for a session: one identity header line + * (conversation id, canonical message count, active block ids — the exact + * server-side anchors the refs map to) followed by every ACTIVE block's + * summary in the kernel render format (renderForgedSummary — the same bytes + * the model reads for a live kernel-rendered block, so a captured checkpoint + * reads identically to a live one). `seq` counts the raw messages the server + * has ingested for the session (messageRefs.byRaw keys). */ +export function renderDshAuthoredCheckpoint(session: { id: string; state: { messageRefs: { byRaw: Record }; blocks: readonly { blockId: string; active: boolean; summary: string; topic?: string }[] } }): string { + const active = session.state.blocks.filter((b) => b.active); + const seq = Object.keys(session.state.messageRefs.byRaw).length; + const header = `${BILI_SNAPSHOT_TAG_PREFIX}conv="${session.id}" seq="${seq}" blocks="${active.map((b) => b.blockId).join("+")}" />`; + if (active.length === 0) return header; + return [header, ...active.map((b) => renderForgedSummary(b))].join("\n\n"); +} + +/** Landing recognition: a freshly-landed AUTHORED checkpoint is a user-role + * plain-text message whose text contains the identity tag. Same carrier + + * novelty discipline as carriesDshLocalCompactionSummary (#2621): tool + * results, reasoning, assistant prose and OLD ids (historical quotes of the + * tag) are structurally incapable of being a fresh landing. */ +export function carriesBiliSnapshotCheckpoint( + msgs: readonly { id?: unknown; role?: unknown; contentType?: unknown; text?: unknown; content?: unknown }[], + knownIds?: ReadonlySet, +): boolean { + for (const m of msgs) { + if (m.role !== "user" || (m.contentType !== undefined && m.contentType !== "text")) continue; + if (knownIds !== undefined && typeof m.id === "string" && knownIds.has(m.id)) continue; + const text = typeof m.text === "string" && m.text !== "" ? m.text : contentText(m.content); + if (text !== "" && text.includes(BILI_SNAPSHOT_TAG_PREFIX)) return true; + } + return false; +} + +function contentText(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 { text?: unknown }).text === "string") out += (part as { text: string }).text; + } + return out; +} + +type WireProtocol = "openai" | "anthropic" | "responses"; + +/** Forged reply for a dsh compaction summarize call. `stream` honors the + * request's own flag. openai: chat.completions chunk stream (or JSON); + * anthropic: the message event order CC's parser accepts (autoModeForge + * shape); responses: the codex prompt-forge body (a plain assistant message + * item — protocol-standard, codex-specific only in name). Returns null for + * any other protocol (caller falls through to the refusal — dsh speaks no + * Google wire, and an undecidable shape must never emit a malformed + * response). */ +export function buildDshCompactionForgeBody( + protocol: WireProtocol, + text: string, + usage: { inputTokens: number; outputTokens: number }, + stream: boolean, +): { body: string; contentType: string } | null { + const total = Math.max(1, usage.inputTokens + usage.outputTokens); + if (protocol === "responses") { + return buildPromptForgeBody(text, { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, totalTokens: total }, stream); + } + if (protocol === "openai") { + const id = `chatcmpl_bili_${Date.now().toString(36)}`; + if (!stream) { + return { + body: JSON.stringify({ + id, + object: "chat.completion", + created: Math.floor(Date.now() / 1000), + model: "bili-authored-compaction", + choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], + usage: { prompt_tokens: usage.inputTokens, completion_tokens: usage.outputTokens, total_tokens: total }, + }), + contentType: "application/json", + }; + } + const frame = (o: unknown) => `data: ${JSON.stringify(o)}\n\n`; + let body = ""; + body += frame({ id, object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] }); + body += frame({ id, object: "chat.completion.chunk", choices: [{ index: 0, delta: { content: text }, finish_reason: null }] }); + body += frame({ id, object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: usage.inputTokens, completion_tokens: usage.outputTokens, total_tokens: total } }); + body += "data: [DONE]\n\n"; + return { body, contentType: "text/event-stream" }; + } + if (protocol === "anthropic") { + const id = `msg_bili_compact_${Date.now().toString(36)}`; + const inputTokens = Math.max(1, usage.inputTokens); + const outputTokens = Math.max(1, usage.outputTokens); + if (!stream) { + return { + body: JSON.stringify({ + id, + type: "message", + role: "assistant", + model: "bili-authored-compaction", + content: [{ type: "text", text }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: inputTokens, output_tokens: outputTokens }, + }), + contentType: "application/json", + }; + } + const sse = (event: string, data: Record) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; + let body = ""; + body += sse("message_start", { type: "message_start", message: { id, type: "message", role: "assistant", model: "bili-authored-compaction", content: [], usage: { input_tokens: inputTokens, output_tokens: 0 } } }); + body += sse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }); + body += sse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } }); + body += sse("content_block_stop", { type: "content_block_stop", index: 0 }); + body += sse("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: outputTokens } }); + body += sse("message_stop", { type: "message_stop" }); + return { body, contentType: "text/event-stream" }; + } + return null; +} diff --git a/src/server/handle.ts b/src/server/handle.ts index 898f4b0eeb..bf78bd0424 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -47,13 +47,14 @@ import { BILI_PASSTHROUGH_HEADER, BILI_PLUGIN_BYPASS_HEADER, isLoopbackAddress, import { checkTunnelDestination, tunnelAllowlistFromEnv } from "../tunnel-guard.js"; import { resolveCompatDropFields } from "../compat-drop.js"; import { DecompressedTooLargeError, decodeRequestBody } from "../content-encoding.js"; -import { autoModeForgeEnabled, imageRescaleEnabled, limitsDecodedBytes as knobLimitsDecodedBytes, noInjectTool as knobNoInjectTool, rawDumpDir as knobRawDumpDir } from "../knobs.js"; +import { autoModeForgeEnabled, dshAuthoredCompactionEnabled, imageRescaleEnabled, limitsDecodedBytes as knobLimitsDecodedBytes, noInjectTool as knobNoInjectTool, rawDumpDir as knobRawDumpDir } from "../knobs.js"; import { buildForgeResponse, classifierForgeVariant, estimateCjkTokens, isAutoModeClassifier, requestText, summarizeAction } from "../auto-mode-forge.js"; import { extractConversationId, isV1BackgroundSideRequest, isV1InternalRequest, unwrapV1Internal } from "../v1internal.js"; import { anthropicBetaContextWindow, BILI_HOP_HEADER, capRegistryWindowByStandard, expandedContextSuffixWindow, launcherContextWindow, launcherMaxOutput, windowSourceLogged } from "./context-window.js"; import { NO_IDENTITY_MESSAGE, safeSessionId } from "./headers.js"; import { demoteGate, hasLeakedBiliToolsOnly, isDshTitleRequest, isServerToolUtilityCall, isSideRequest, resolveSideLane, restoreOutputBudget, sideRequestGuard, stripLeakedBiliTools } from "./side-request.js"; import { DSH_COMPACTION_SHAPE_MSGS, detectPassthroughDshCompactionCall, dshCompactionRefusal, dshPassthroughGuardStats, isDshCompactionCall } from "./dsh-compaction-guard.js"; +import { buildDshCompactionForgeBody, renderDshAuthoredCheckpoint } from "./dsh-authored-compaction.js"; import { artifactSeedHit, detectAcpArtifacts } from "./chain-artifacts.js"; import { piSubagentChannelFallback } from "./pi-subagent-channel.js"; import { FORCE_TEXT_PROTOCOL } from "./inject.js"; @@ -1821,7 +1822,21 @@ async function handleRequest( // side-request lane: the compaction call is a full-budget request, so // only this guard can catch it. if (protocol !== null && opts.allowDshCompaction !== true && isDshCompactionCall(protocol, parsed)) { - if (session.metadata.dshCompactionRefused !== true) { + // #3733: AUTHORED compaction — when the knob is on and the session + // holds active fold blocks, answer the call LOCALLY with our folded + // snapshot instead of refusing: zero egress (autoModeForge #2740 + // discipline), dsh records our tagged checkpoint and its file shrinks + // (#3723), and the recorded content is exactly what the upstream + // already sees. Replaces the DEFAULT refusal only — an explicit + // allowDshCompaction (checked above) still forwards natively, because + // that is the user asking for dsh's own behavior. Undecidable shapes + // (null forge) fall through to the refusal below. + const authored = dshAuthoredCompactionEnabled() && session.state.blocks.some((b) => b.active) + ? buildDshCompactionForgeBody(protocol as "openai" | "anthropic" | "responses", renderDshAuthoredCheckpoint(session), { inputTokens: Math.max(1, Math.round(inboundBytes / 4)), outputTokens: 0 }, (parsed as { stream?: unknown }).stream === true) + : null; + if (authored !== null) { + log("info", `[${session.id}] dsh compaction call identified (final user message = COMPACTION_INSTRUCTION, ${inboundMsgs} msgs) — ANSWERED LOCALLY with the bili snapshot (#3733 authored checkpoint): upstream not contacted, dsh records our tagged checkpoint; originals stay recoverable via CCR/export`); + } else if (session.metadata.dshCompactionRefused !== true) { session.metadata.dshCompactionRefused = true; const shapeDrift = inboundMsgs !== null && inboundMsgs > DSH_COMPACTION_SHAPE_MSGS ? `, shape drifted from the ≤${DSH_COMPACTION_SHAPE_MSGS}-msg rc.1 envelope — rc.2 replays the full shadowed region (#2193)` : ""; log("warn", `[${session.id}] dsh native compaction call identified (final user message = COMPACTION_INSTRUCTION, ${inboundMsgs} msgs${shapeDrift}) — REFUSED, not forwarded: bili owns compression on this lane; a landed dsh checkpoint would durably shadow the raw history (#1729, cf. #1206/#1772)`); @@ -1838,6 +1853,19 @@ async function handleRequest( // sticky and consumes it. const prevBytes = typeof session.metadata["dshCompactionRefusedBytes"] === "number" ? session.metadata["dshCompactionRefusedBytes"] as number : 0; session.metadata["dshCompactionRefusedBytes"] = Math.max(prevBytes, inboundBytes); + if (authored !== null) { + // #3733 counters + the same raw-ledger high-water as a refusal + // (the envelope still proves the raw scale the output clamp must + // plan against); NOT counted in dshCompactionRefusals. + session.metadata["dshAuthoredCompactions"] = (typeof session.metadata["dshAuthoredCompactions"] === "number" ? session.metadata["dshAuthoredCompactions"] as number : 0) + 1; + markDirty(session); + if (!res.headersSent && !res.writableEnded && !res.destroyed) { + res.writeHead(200, { "content-type": authored.contentType }); + res.end(authored.body); + } + logRequestCost(log, session.id, inboundMsgs, inboundBytes, reqT0); + return; + } session.metadata["dshCompactionRefusals"] = (typeof session.metadata["dshCompactionRefusals"] === "number" ? session.metadata["dshCompactionRefusals"] as number : 0) + 1; markDirty(session); const refusal = dshCompactionRefusal(protocol); diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 67d84035b9..7d1c9edda1 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -14,6 +14,7 @@ import { nudgeSuppressed } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; import { applyCompactionArchive, coveredRealHistoryIds, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type PendingRetrieval, type Session } from "../session.js"; import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js"; +import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js"; import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL, RULE_TOOL, absorbToolsFor, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote } from "../compress-tool.js"; import { applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetrievals, imageRescaleToolArmed, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes } from "../store.js"; @@ -264,11 +265,14 @@ export async function prepareAnthropic( if (!anthropicTitleGen && laneDecisions.profile.compactsClientSide && session.state.blocks.some((b) => b.active)) { const coveredBeforeDshCompact = coveredRealHistoryIds(session.state.blocks); // #2627: same real-history caliber const dshGap = foldCoverage(coveredBeforeDshCompact, msgs.map((m) => m.id)); - if (dshGap && carriesDshLocalCompactionSummary(msgs)) { + if (dshGap && (carriesDshLocalCompactionSummary(msgs) || carriesBiliSnapshotCheckpoint(msgs))) { const missing = dshGap.expected - dshGap.matched; if (missing >= DSH_LOCAL_COMPACTION_MIN_MISSING && missing * 2 >= dshGap.expected) { + // #3733: our own tag = authored checkpoint. + const authored = carriesBiliSnapshotCheckpoint(msgs); + if (authored) session.metadata.dshAuthoredCheckpointLanded = true; recordConflict(session, "native-compaction", `dsh native compaction: ${missing}/${dshGap.expected} covered id(s) replaced by the compacted history; ACP state rebased (#2432)`); - log("warn", `[${sessionId}] dsh native compaction detected (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — rebasing ACP state onto the compacted history (#2432)`); + log(authored ? "info" : "warn", `[${sessionId}] dsh ${authored ? "AUTHORED checkpoint landed" : "native compaction detected"} (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — ${authored ? "rebasing ACP state onto the authored bili-snapshot checkpoint (#3733)" : "rebasing ACP state onto the compacted history (#2432)"}`); markNativeCompactionBoundary(session); dshRebased = reconcileNativeCompactionBoundary(session); } diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 4a456efd19..52812720f9 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -13,6 +13,7 @@ import { compressBreakerArmed } from "../stream.js"; import { applyCompactionArchive, coveredRealHistoryIds, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type Session } from "../session.js"; import { recordConflict } from "../conflict-watch.js"; import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js"; +import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js"; import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_GOOGLE, RULE_TOOL_GOOGLE, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, imageRescaleToolArmed, retrieveToolName } from "../store.js"; @@ -145,11 +146,14 @@ export async function prepareGoogle( if (!isTitleGen && laneDecisions.profile.compactsClientSide && session.state.blocks.some((b) => b.active)) { const coveredBeforeDshCompact = coveredRealHistoryIds(session.state.blocks); // #2627: same real-history caliber const dshGap = foldCoverage(coveredBeforeDshCompact, msgs.map((m) => m.id)); - if (dshGap && carriesDshLocalCompactionSummary(msgs)) { + if (dshGap && (carriesDshLocalCompactionSummary(msgs) || carriesBiliSnapshotCheckpoint(msgs))) { const missing = dshGap.expected - dshGap.matched; if (missing >= DSH_LOCAL_COMPACTION_MIN_MISSING && missing * 2 >= dshGap.expected) { + // #3733: our own tag = authored checkpoint. + const authored = carriesBiliSnapshotCheckpoint(msgs); + if (authored) session.metadata.dshAuthoredCheckpointLanded = true; recordConflict(session, "native-compaction", `dsh native compaction: ${missing}/${dshGap.expected} covered id(s) replaced by the compacted history; ACP state rebased (#2432)`); - log("warn", `[${sessionId}] dsh native compaction detected (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — rebasing ACP state onto the compacted history (#2432)`); + log(authored ? "info" : "warn", `[${sessionId}] dsh ${authored ? "AUTHORED checkpoint landed" : "native compaction detected"} (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — ${authored ? "rebasing ACP state onto the authored bili-snapshot checkpoint (#3733)" : "rebasing ACP state onto the compacted history (#2432)"}`); markNativeCompactionBoundary(session); reconcileNativeCompactionBoundary(session); } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 2fb81e6499..a0bd8f9afa 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -14,6 +14,7 @@ import { nudgeSuppressed } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; import { applyCompactionArchive, coveredRealHistoryIds, detectUnannouncedHistoryRewrite, foldCoverage, markCompactionBoundary, markDirty, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type PendingRetrieval, type Session } from "../session.js"; import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js"; +import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js"; import { ABSORB_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, RULE_TOOL_OPENAI, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; import { adoptContentStore, ccrEnabled, ccrLoopConfig, contentStoreOf, dropRetrievals, imageRescaleToolArmed, pruneExpiredRetrievals, reconcileReloadedRetrievals, renderRetrievalNotes, retrieveToolName, snapshotPendingRetrievals, snapshotRetrievalNotes } from "../store.js"; @@ -154,11 +155,16 @@ export async function prepareOpenai( // #2621: pass the pre-turn ref map so the framing match also demands // NOVELTY — a freshly-landed checkpoint is a NEW id, while every // historical quote/replay of the marker string hits an old id. - if (dshGap && carriesDshLocalCompactionSummary(msgs, knownRefsBefore)) { + if (dshGap && (carriesDshLocalCompactionSummary(msgs, knownRefsBefore) || carriesBiliSnapshotCheckpoint(msgs, knownRefsBefore))) { const missing = dshGap.expected - dshGap.matched; if (missing >= DSH_LOCAL_COMPACTION_MIN_MISSING && missing * 2 >= dshGap.expected) { + // #3733: a checkpoint carrying our tag is one + // WE authored (answered locally at the #1729 guard) — same rebase + // as a foreign one, but recorded + logged as the intended event. + const authored = carriesBiliSnapshotCheckpoint(msgs, knownRefsBefore); + if (authored) session.metadata.dshAuthoredCheckpointLanded = true; recordConflict(session, "native-compaction", `dsh native compaction: ${missing}/${dshGap.expected} covered id(s) replaced by the compacted history; ACP state rebased (#2432)`); - log("warn", `[${sessionId}] dsh native compaction detected (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — rebasing ACP state onto the compacted history (#2432)`); + log(authored ? "info" : "warn", `[${sessionId}] dsh ${authored ? "AUTHORED checkpoint landed" : "native compaction detected"} (${dshGap.matched}/${dshGap.expected} covered id(s) retained, checkpoint framing in resent history) — ${authored ? "rebasing ACP state onto the authored bili-snapshot checkpoint (#3733)" : "rebasing ACP state onto the compacted history (#2432)"}`); markNativeCompactionBoundary(session); dshRebased = reconcileNativeCompactionBoundary(session); } diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index b8ec042f3e..b0eb9ba066 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -16,6 +16,7 @@ import { nudgeSuppressed, pluginLaneDegraded } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; import { coveredRealHistoryIds, foldCoverage, markDirty, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, REWRITE_MIN_INCOMING_TOTAL, snapshotMessages, type Session } from "../session.js"; import { carriesDshLocalCompactionSummary, DSH_LOCAL_COMPACTION_MIN_MISSING } from "./dsh-compaction-guard.js"; +import { carriesBiliSnapshotCheckpoint } from "./dsh-authored-compaction.js"; import { recordConflict } from "../conflict-watch.js"; import { ABSORB_TOOL_NAME, BILI_ACP_READONLY_TOOLS_RESPONSES, BILI_ACP_READONLY_TOOLS_RESPONSES_NO_RANGE, BILI_ACP_TOOLS_RESPONSES, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, READ_ORIGINAL_IMAGE_TOOL_RESPONSES, RULE_TOOL_RESPONSES, absorbToolsFor, buildAbsorbSystemPrompt, buildAcpTagsOnlyPrompt, buildCompressHybridSystemPrompt, buildCompressSystemPrompt, retrieveToolsFor, withFirstSightDrain, withMarkerIntegrityNote, withSummaryBudgetNote, withProjectAttribution } from "../compress-tool.js"; import { absorbToolName, applyAbsorbView, storeEffectiveAbsorb } from "../absorb.js"; @@ -247,14 +248,17 @@ export async function prepareResponses( // checkpoint is a NEW id; historical quotes/replays hit old ids. const knownIdsBeforeLocalCompact = new Set(Object.keys(session.state.messageRefs.byRaw)); const codexHit = codexLane && carriesCodexLocalCompactionSummary(msgs); - const dshHit = dshLane && carriesDshLocalCompactionSummary(msgs, knownIdsBeforeLocalCompact); + const dshHit = dshLane && (carriesDshLocalCompactionSummary(msgs, knownIdsBeforeLocalCompact) || carriesBiliSnapshotCheckpoint(msgs, knownIdsBeforeLocalCompact)); + const dshAuthored = dshLane && carriesBiliSnapshotCheckpoint(msgs, knownIdsBeforeLocalCompact); if (localGap && (codexHit || dshHit)) { const missing = localGap.expected - localGap.matched; const minMissing = dshHit ? DSH_LOCAL_COMPACTION_MIN_MISSING : CODEX_LOCAL_COMPACTION_MIN_MISSING; if (missing >= minMissing && missing * 2 >= localGap.expected) { if (dshHit) { + // #3733: our own tag = authored checkpoint. + if (dshAuthored) session.metadata.dshAuthoredCheckpointLanded = true; recordConflict(session, "native-compaction", `dsh native compaction: ${missing}/${localGap.expected} covered id(s) replaced by the compacted history; ACP state rebased (#2432)`); - log("warn", `[${sessionId}] dsh native compaction detected (${localGap.matched}/${localGap.expected} covered id(s) retained, checkpoint framing in resent history) — rebasing ACP state onto the compacted history (#2432)`); + log(dshAuthored ? "info" : "warn", `[${sessionId}] dsh ${dshAuthored ? "AUTHORED checkpoint landed" : "native compaction detected"} (${localGap.matched}/${localGap.expected} covered id(s) retained, checkpoint framing in resent history) — ${dshAuthored ? "rebasing ACP state onto the authored bili-snapshot checkpoint (#3733)" : "rebasing ACP state onto the compacted history (#2432)"}`); } else { recordConflict(session, "native-compaction", `codex local auto-compaction: ${missing}/${localGap.expected} covered id(s) replaced by the compacted history; rebasing ACP state (#2372)`); log("warn", `[${sessionId}] codex local auto-compaction detected (${localGap.matched}/${localGap.expected} covered ids retained) — rebasing ACP state onto the compacted history (#2372)`); diff --git a/tests/dsh-authored-compaction.test.ts b/tests/dsh-authored-compaction.test.ts new file mode 100644 index 0000000000..c9f4f4f5f4 --- /dev/null +++ b/tests/dsh-authored-compaction.test.ts @@ -0,0 +1,416 @@ +// #3733: bili-authored dsh client compaction. +// +// The #1729 guard refuses dsh's native compaction summarize calls. Post-#3644 +// (snapshot doctrine) a landed client checkpoint is benign for the server +// substrate — but a NATIVE checkpoint is still a foreign summary we can only +// recognize fuzzily, and it may not match what the upstream actually sees. +// Authored compaction answers the SAME call locally (zero egress, autoModeForge +// discipline): the response we hand back is OUR folded snapshot, carrying an +// identity header line. dsh writes it into its history as the checkpoint, so +// the client file shrinks (fixes #3723's unbounded growth) while the content +// stays exactly what the model already has upstream. +// +// This file pins the contract BEFORE the implementation (打桩): unit shapes +// (header / forge bodies / detector) and the end-to-end lane (interception, +// zero upstream contact, ledger marks, knob-off fallthrough to refusal, +// no-block fallthrough, stream honoring, allow-precedence, and the landing +// recognition on the post-compaction replay). +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, _resetSessionsForTest } from "../src/session.ts"; +import { DSH_COMPACTION_INSTRUCTION_PREFIX, DSH_CHECKPOINT_OPEN_TAG, DSH_CHECKPOINT_PREAMBLE_PREFIX } from "../src/server/dsh-compaction-guard.ts"; +import { + BILI_SNAPSHOT_TAG_PREFIX, + buildDshCompactionForgeBody, + carriesBiliSnapshotCheckpoint, + renderDshAuthoredCheckpoint, +} from "../src/server/dsh-authored-compaction.ts"; +import { rmrf } from "./tmp-rm.ts"; + +// --------------------------------------------------------------------------- +// Unit: checkpoint text. + +function fakeBlock(blockId: string, summary: string, topic?: string): { blockId: string; summary: string; topic?: string; active: true } { + return { blockId, summary, topic, active: true }; +} + +test("unit: checkpoint = identity header + kernel-rendered block summaries", () => { + const session = { + id: "s-3733", + state: { + messageRefs: { byRaw: Object.fromEntries(Array.from({ length: 42 }, (_, i) => [`m${i}`, {}])) }, + blocks: [fakeBlock("b1", "setup folded", "setup"), fakeBlock("b2", "later work folded")], + }, + }; + const text = renderDshAuthoredCheckpoint(session as never); + const lines = text.split("\n"); + assert.ok(lines[0].startsWith(BILI_SNAPSHOT_TAG_PREFIX), "first line is the identity header"); + assert.match(lines[0], /conv="s-3733"/); + assert.match(lines[0], /seq="42"/); + assert.match(lines[0], /blocks="b1\+b2"/); + assert.ok(text.includes("[Compressed conversation section] — setup"), "kernel render format (topic)"); + assert.ok(text.includes("setup folded")); + assert.ok(text.includes("[Compressed conversation section]"), "kernel render format (no topic)"); + assert.ok(text.includes("later work folded")); +}); + +test("unit: inactive blocks are skipped; empty active set renders header only", () => { + const session = { + id: "s-none", + state: { messageRefs: { byRaw: {} }, blocks: [{ blockId: "b1", summary: "SECRET-INACTIVE", active: false }] }, + }; + const text = renderDshAuthoredCheckpoint(session as never); + assert.ok(text.startsWith(BILI_SNAPSHOT_TAG_PREFIX)); + assert.ok(!text.includes("SECRET-INACTIVE"), "inactive block content absent"); +}); + +// --------------------------------------------------------------------------- +// Unit: forge bodies (all three dsh wires, stream and JSON). + +const SAMPLE = ` +[Compressed conversation section] +summary body`; + +function parseSseFrames(body: string): { event?: string; data: unknown }[] { + const frames: { event?: string; data: unknown }[] = []; + for (const block of body.trim().split("\n\n")) { + let event: string | undefined; + let data = ""; + for (const line of block.split("\n")) { + if (line.startsWith("event: ")) event = line.slice(7).trim(); + else if (line.startsWith("data: ")) data += line.slice(6); + } + if (data === "[DONE]") frames.push({ event, data: "[DONE]" }); + else if (data !== "") frames.push({ event, data: JSON.parse(data) }); + } + return frames; +} + + +// Non-null wrapper: these unit cases assert the happy path; the null path is +// pinned separately (unknown protocol). +function buildDshCompactionForgeBodyOrFail(...args: Parameters) { + const out = buildDshCompactionForgeBody(...args); + if (out === null) throw new Error("forge body unexpectedly null"); + return out; +} + +test("unit: openai JSON forge body", () => { + const { body, contentType } = buildDshCompactionForgeBodyOrFail("openai", SAMPLE, { inputTokens: 100, outputTokens: 10 }, false); + assert.equal(contentType, "application/json"); + const j = JSON.parse(body); + assert.equal(j.choices[0].message.role, "assistant"); + assert.equal(j.choices[0].message.content, SAMPLE); + assert.equal(j.choices[0].finish_reason, "stop"); + assert.ok(j.usage && typeof j.usage.total_tokens === "number"); +}); + +test("unit: openai SSE forge body", () => { + const { body, contentType } = buildDshCompactionForgeBodyOrFail("openai", SAMPLE, { inputTokens: 100, outputTokens: 10 }, true); + assert.equal(contentType, "text/event-stream"); + const frames = parseSseFrames(body); + const last = frames[frames.length - 1]; + assert.equal(last.data, "[DONE]", "terminal [DONE]"); + const deltas = frames.filter((f) => (f.data as { choices?: { delta?: { content?: unknown } }[] })?.choices?.[0]?.delta?.content !== undefined); + assert.ok(deltas.length >= 1, "at least one content delta"); + const joined = deltas.map((f) => (f.data as { choices: { delta: { content: string } }[] }).choices[0].delta.content).join(""); + assert.ok(joined.includes(BILI_SNAPSHOT_TAG_PREFIX), "checkpoint text delivered"); + const finish = frames.find((f) => (f.data as { choices?: { finish_reason?: string }[] })?.choices?.[0]?.finish_reason === "stop"); + assert.ok(finish, "finish_reason stop frame"); +}); + +test("unit: anthropic JSON forge body", () => { + const { body, contentType } = buildDshCompactionForgeBodyOrFail("anthropic", SAMPLE, { inputTokens: 100, outputTokens: 10 }, false); + assert.equal(contentType, "application/json"); + const j = JSON.parse(body); + assert.equal(j.type, "message"); + assert.equal(j.role, "assistant"); + assert.equal(j.content[0].type, "text"); + assert.equal(j.content[0].text, SAMPLE); + assert.equal(j.stop_reason, "end_turn"); +}); + +test("unit: anthropic SSE forge body (event order)", () => { + const { body, contentType } = buildDshCompactionForgeBodyOrFail("anthropic", SAMPLE, { inputTokens: 100, outputTokens: 10 }, true); + assert.equal(contentType, "text/event-stream"); + const events = parseSseFrames(body).map((f) => (f.data as { type?: string }).type); + assert.equal(events[0], "message_start"); + assert.ok(events.includes("content_block_start")); + assert.ok(events.includes("content_block_delta")); + assert.ok(events.includes("content_block_stop")); + assert.ok(events.includes("message_delta")); + assert.equal(events[events.length - 1], "message_stop"); + const textDelta = parseSseFrames(body).find((f) => (f.data as { type?: string }).type === "content_block_delta"); + assert.equal((textDelta!.data as { delta: { text?: string } }).delta.text, SAMPLE); +}); + +test("unit: responses wire delegates to the codex prompt-forge shape", () => { + for (const stream of [false, true]) { + const { body, contentType } = buildDshCompactionForgeBodyOrFail("responses", SAMPLE, { inputTokens: 100, outputTokens: 10 }, stream); + if (stream) { + assert.equal(contentType, "text/event-stream"); + const frames = parseSseFrames(body); + const types = frames.map((f) => (f.data as { type?: string }).type).filter(Boolean); + assert.ok(types.includes("response.created")); + assert.ok(types.includes("response.completed")); + const delta = frames.find((f) => (f.data as { type?: string }).type === "response.output_text.delta") as { data: { delta: string } } | undefined; + assert.equal(delta?.data.delta, SAMPLE); + } else { + assert.equal(contentType, "application/json"); + const j = JSON.parse(body); + const item = j.output.find((o: { type?: string }) => o.type === "message"); + assert.equal(item.role, "assistant"); + assert.equal(item.content[0].text, SAMPLE); + } + } +}); + +test("unit: unknown protocol returns null (caller falls through to refusal)", () => { + assert.equal(buildDshCompactionForgeBody("google" as never, SAMPLE, { inputTokens: 1, outputTokens: 1 }, true), null); +}); + +// --------------------------------------------------------------------------- +// Unit: landing recognition (tag detector, #2621 carrier discipline). + +test("unit: carriesBiliSnapshotCheckpoint — carrier + novelty gates", () => { + const tagged = `${DSH_CHECKPOINT_PREAMBLE_PREFIX}: something\n\n${DSH_CHECKPOINT_OPEN_TAG}\n${SAMPLE}\n`; + assert.equal(carriesBiliSnapshotCheckpoint([{ id: "n1", role: "user", contentType: "text", text: tagged }]), true, "fresh user plain-text checkpoint matches"); + assert.equal(carriesBiliSnapshotCheckpoint([{ id: "n2", role: "assistant", text: tagged }]), false, "assistant carrier rejected"); + assert.equal(carriesBiliSnapshotCheckpoint([{ id: "n3", role: "user", contentType: "tool-result", text: tagged }]), false, "tool-result carrier rejected"); + assert.equal(carriesBiliSnapshotCheckpoint([{ id: "n4", role: "user", text: tagged }], new Set(["n4"])), false, "old id (historical quote) rejected under novelty gate"); + assert.equal(carriesBiliSnapshotCheckpoint([{ id: "n5", role: "user", text: "plain question" }]), false, "no tag no match"); +}); + +// --------------------------------------------------------------------------- +// E2E: real proxy + mock upstream on the openai wire (dsh's primary lane). + +const SUMMARY = "MAIN-SUMMARY-SETUP-CONTEXT-FOLDED-BY-COMPRESSION-LONG-ENOUGH-FOR-KERNEL-MIN-LENGTH-CHECK"; + +function sse(obj: unknown): string { + return `data: ${JSON.stringify(obj)}\n\n`; +} + +// 24 messages × ~1.5k chars (~375 tokens each): total ~9k tokens stays under +// the 15k window (no preflight); the default protection zone (preserveRecent +// 3 + 5000-token walk ≈ 14 messages) leaves the first ~10 compressible, so the +// m00001..m00008 range lands intact — 8 covered ids = DSH_LOCAL_COMPACTION_MIN_MISSING, +// enough for the #2432/#3733 landing gate to see a real region replacement. +function conversation(): { role: string; content: string }[] { + const out: { role: string; content: string }[] = []; + for (let i = 0; i < 24; i++) { + out.push({ role: i % 2 === 0 ? "user" : "assistant", content: `Message ${i} of the working session. ` + `WORK_${i}_content_`.repeat(88) }); + } + return out; +} + +type Harness = { proxy: http.Server; upstream: http.Server; bodies: string[]; url: string; sessionOf: (label: string) => { meta: { label: string }; state: { blocks: { id: string; active: boolean }[] }; metadata: Record } | undefined }; + +async function withHarness(fn: (h: Harness) => Promise, optsOverride: Partial = {}): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + bodies.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + if (bodies.length === 1) { + // First turn: the model compresses the oldest pair → active block. + const args = JSON.stringify({ content: [{ startId: "m00001", endId: "m00008", topic: "setup", summary: SUMMARY }] }); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: null, tool_calls: [{ index: 0, id: "call_p", type: "function", function: { name: "compress", arguments: args } }] } }] })); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "done compressing" } }] })); + } + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })); + res.end(); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + _resetSessionsForTest(); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: 15_000 } } } }, + modelContextLimit: 15_000, + kernelConfig: defaultConfig(15_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + passthroughSource: null, + autoUpdate: false, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: true, + releaseNotesCheck: true, + compat: { roles: {} }, + streamErrorShape: "protocol", + mitm: { enabled: false, domains: [] }, + ...optsOverride, + } as unknown as ProxyOptions); + await once(proxy, "listening"); + const port = (proxy.address() as { port: number }).port; + const h: Harness = { + proxy, + upstream, + bodies, + url: `http://127.0.0.1:${port}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`, + sessionOf: (label) => listSessions().find((x) => x.meta.label === label) as never, + }; + try { + await fn(h); + } finally { + proxy.close(); + proxy.closeIdleConnections?.(); + await once(proxy, "close"); + upstream.close(); + upstream.closeIdleConnections?.(); + await once(upstream, "close"); + delete process.env.BILI_DSH_AUTHORED_COMPACTION; + delete process.env.BILI_ALLOW_DSH_COMPACTION; + } +} + +async function turn(h: Harness, label: string, messages: unknown[], extraHeaders: Record = {}, stream = true): Promise<{ status: number; body: string; contentType: string }> { + const r = await fetch(h.url, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": label, ...extraHeaders }, + body: JSON.stringify({ model: "gpt-test", messages, stream }), + }); + return { status: r.status ?? 0, body: await r.text(), contentType: r.headers.get("content-type") ?? "" }; +} + +/** One normal turn that leaves an active block behind. */ +async function armBlock(h: Harness, label: string): Promise { + const r = await turn(h, label, conversation()); + assert.equal(r.status, 200, r.body); + const s = h.sessionOf(label); + assert.ok(s, "session exists"); + assert.ok(s!.state.blocks.some((b) => b.active), "setup created an active block"); +} + +test("e2e: authored compaction answers locally — zero egress, tagged checkpoint, ledger marks", async () => { + await withHarness(async (h) => { + await armBlock(h, "s-auth"); + const before = h.bodies.length; + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const r = await turn(h, "s-auth", [ + { role: "system", content: "sys" }, + { role: "user", content: "x".repeat(600_000) }, + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense the conversation above.` }, + ]); + assert.equal(r.status, 200, r.body); + assert.match(r.contentType, /text\/event-stream/); + assert.ok(r.body.includes(BILI_SNAPSHOT_TAG_PREFIX), "identity header in the forged stream"); + assert.ok(r.body.includes(SUMMARY), "block summary in the forged stream"); + assert.equal(h.bodies.length, before, "upstream never contacted (zero egress)"); + const s = h.sessionOf("s-auth")!; + assert.equal(s.metadata["dshAuthoredCompactions"], 1, "authored counter"); + assert.ok(typeof s.metadata["dshCompactionRefusedBytes"] === "number", "raw ledger high-water still marked"); + assert.equal(s.metadata["dshCompactionRefusals"], undefined, "not counted as a refusal"); + }); +}); + +test("e2e: stream:false honored — JSON body with the checkpoint text", async () => { + await withHarness(async (h) => { + await armBlock(h, "s-json"); + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const r = await turn(h, "s-json", [ + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense.` }, + ], {}, false); + assert.equal(r.status, 200, r.body); + assert.match(r.contentType, /application\/json/); + const j = JSON.parse(r.body); + assert.ok(j.choices[0].message.content.includes(BILI_SNAPSHOT_TAG_PREFIX)); + }); +}); + +test("e2e: knob off → the #1729 refusal still stands (status quo pinned)", async () => { + await withHarness(async (h) => { + await armBlock(h, "s-off"); + delete process.env.BILI_DSH_AUTHORED_COMPACTION; + const r = await turn(h, "s-off", [ + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense.` }, + ]); + assert.equal(r.status, 422, r.body); + assert.equal(JSON.parse(r.body).error.code, "dsh_compaction_refused"); + assert.equal(h.bodies.filter((b) => b.includes(DSH_COMPACTION_INSTRUCTION_PREFIX)).length, 0, "never forwarded"); + }); +}); + +test("e2e: no active blocks → authored mode falls through to refusal", async () => { + await withHarness(async (h) => { + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const r = await turn(h, "s-cold", [ + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense.` }, + ]); + assert.equal(r.status, 422, "nothing to checkpoint — refuse like today"); + }); +}); + +test("e2e: explicit allowDshCompaction wins over authored mode (user asked for native)", async () => { + const allowNative: (h: Harness) => Promise = async (h) => { + await armBlock(h, "s-allow"); + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const r = await turn(h, "s-allow", [ + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense.` }, + ]); + assert.equal(r.status, 200, r.body); + assert.ok(h.bodies.some((b) => b.includes(DSH_COMPACTION_INSTRUCTION_PREFIX)), "forwarded natively"); + const s = h.sessionOf("s-allow")!; + assert.equal(s.metadata["dshAuthoredCompactions"], undefined, "not authored"); + }; + await withHarness(allowNative, { allowDshCompaction: true } as Partial); +}); + +test("e2e: landed checkpoint is recognized on replay — rebase + authored-landed mark", async () => { + await withHarness(async (h) => { + await armBlock(h, "s-land"); + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const forged = await turn(h, "s-land", [ + { role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense.` }, + ]); + assert.equal(forged.status, 200); + // Extract the checkpoint text the way dsh would record it (preamble + + // tags around our payload). + const frames = forged.body.split("\n\n").filter((b) => b.startsWith("data: ") && !b.includes("[DONE]")); + const deltas = frames.map((f) => { try { return JSON.parse(f.slice(6)); } catch { return null; } }) + .map((j) => j?.choices?.[0]?.delta?.content) + .filter((c: unknown): c is string => typeof c === "string"); + const payload = deltas.join(""); + assert.ok(payload.includes(BILI_SNAPSHOT_TAG_PREFIX)); + const checkpointText = `${DSH_CHECKPOINT_PREAMBLE_PREFIX}:\n\n${DSH_CHECKPOINT_OPEN_TAG}\n${payload}\n\x3c/compacted-summary\x3e`; + // Next turn: dsh replays [checkpoint, retained tail] against the same session. + // #2432/#3733 recognition is dsh-lane scoped: the replay carries the + // dsh plugin identity so laneDecisions.profile.compactsClientSide is + // true (the guard + forge above are marker-based and lane-agnostic). + const r = await turn(h, "s-land", [ + { role: "user", content: checkpointText }, + { role: "assistant", content: "ack" }, + { role: "user", content: "continue the work" }, + ], { "x-bili-plugin": "dsh" }); + assert.equal(r.status, 200, r.body); + const s = h.sessionOf("s-land")!; + assert.equal(s.metadata["dshAuthoredCheckpointLanded"], true, "authored landing recognized"); + }); +}); From 66e6130c1b4f147e885ed28e94496df2289163c8 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Mon, 19 Oct 2026 00:34:20 +0800 Subject: [PATCH 2/6] docs: env-only seed for BILI_DSH_AUTHORED_COMPACTION (docs-coverage gate) --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 1 + website/config-reference/env-only.yaml | 8 ++++++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 823df58ad0..1e6508ad68 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -327,6 +327,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | Key | Type | Default | Env | Description | |-----|------|---------|-----|-------------| +| `BILI_DSH_AUTHORED_COMPACTION` | boolean | false | — | Let bili ANSWER dsh compaction summarize calls locally with the folded snapshot instead of refusing (#3733): identity header + kernel-rendered block summaries, zero egress; replay recognized via the #2432 rebase. | | `BILI_CONFIG_FILE` | string | unset (XDG config path) | — | Override the config file path (path relocation). | | `BILI_SESSIONS_DIR` | string | unset (XDG state path) | — | Where session records are stored (path relocation). | | `BILI_ENCRYPTION_KEY` | string | unset | — | Key material for encrypted persisted payloads (secret). | @@ -1859,7 +1860,6 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. While the guard refuses, dsh's own context-pressure counter (its raw ledger) only grows — refused checkpoints never land — while bili's folds keep the wire payload small, so the session keeps working past the point where the client's gauge says "full", and dsh keeps re-requesting compaction (refused every time). Since #3384 the outgoing output budget is also no longer planned against that raw ledger, EXCEPT when bili's own folded view has already reached the enforced headroom target or the requested budget is >= 25% of the native window (the #2490 protection regimes) — before that fix the growing ledger silently shrank the model's output budget every turn, ending in error-free empty replies on onlyReasoning models. Scope note: on non-web profiles the shipped bundle patch (`auto: false`) still suppresses AUTO-triggering, so only manual `/compact` benefits there; on web profiles no patch layer can address the preset-nested row by id (#1772), so auto-triggering works as-is once allowed unless you apply the #2474 full-snapshot override of preset-standard from your profile's cordis.patch.yml. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | | `BILI_DSH_AUTHORED_COMPACTION` | Set `1` to have bili itself ANSWER dsh's compaction summarize calls locally instead of refusing them (#3733). Prerequisites per call: the #1729 guard fires (marker-decisive), the session holds at least one ACTIVE fold block, and `allowDshCompaction` is NOT enabled (the explicit "forward natively" choice always wins). The reply is forged with zero egress (the autoModeForge #2740 discipline): an identity header `` plus every active block's summary in the kernel render format — exactly the bytes the model already reads upstream, so client display, upstream context and server state agree for the first time, and dsh's checkpoint file shrinks (#3723's unbounded growth loop). Originals stay recoverable via CCR/export; the landed checkpoint is recognized on replay through the same #2432 rebase as a foreign one, but recorded as `dshAuthoredCheckpointLanded` (info, not warn). Env-only for the rollout window; read per-request, no restart needed. | | `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. Scope note: with bili ON, dsh native auto-compaction is now off on every plane — the host-plane row via the shipped bundle patch (`auto: false`), and web-profile preset instances at load time via the #3354 overlay — so this switch mainly governs manual `/compact` on non-web profiles (auto-triggering stays suppressed there) and any residual auto-triggering on dsh builds where the #3354 overlay does not apply. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | -| `BILI_DSH_AUTHORED_COMPACTION` | Set `1` to have bili itself ANSWER dsh's compaction summarize calls locally instead of refusing them (#3733). Prerequisites per call: the #1729 guard fires (marker-decisive), the session holds at least one ACTIVE fold block, and `allowDshCompaction` is NOT enabled (the explicit "forward natively" choice always wins). The reply is forged with zero egress (the autoModeForge #2740 discipline): an identity header `` plus every active block's summary in the kernel render format — exactly the bytes the model already reads upstream, so client display, upstream context and server state agree for the first time, and dsh's checkpoint file shrinks (#3723's unbounded growth loop). Originals stay recoverable via CCR/export; the landed checkpoint is recognized on replay through the same #2432 rebase as a foreign one, but recorded as `dshAuthoredCheckpointLanded` (info, not warn). Env-only for the rollout window; read per-request, no restart needed. | | `BILI_NO_CACHE_CONTROL` | Set `1` to disable bili's Anthropic-lane `cache_control` breakpoint stamping (#1637, shipped in #1639). On by default: Anthropic-style upstreams cache only what is explicitly breakpointed (max 4 per request, counted across system + tools + message blocks combined), so bili marks the system block plus up to 3 cumulative message marks — a marked message stays marked (byte-stable prefix), marks die only by folding, and the last 3 stable messages carry the advancing frontier. Any client-set `cache_control` (message blocks, tools entries) suppresses bili's stamps entirely — client-managed caching wins. Marks persist with the session. This switch is the escape hatch for upstreams that reject the field or relays with their own breakpoint policy. Plain-proxy Anthropic lane only; OpenAI/Responses lanes cache implicitly and are never stamped. Config-file twin: [`compat.noCacheControl`](#compat) — the env var wins. | | `BILI_CHAIN_CONTENT` | Set `1` to turn ON the ACP-artifact / `` checkpoint **body-content** detection of bili→bili chain awareness (#1086/#1421): when an inbound request carries compression artifacts (render tags / historical `acp_status`+`search_context` tool calls) or a digest-bearing checkpoint in its BODY but neither the `x-bili-hop` header nor local compression state for its session, bili records an advisory observation and/or applies first-processor-wins passthrough. **Default is OFF** (#1683 follow-up): by default ONLY the `x-bili-hop` header drives chain recognition, because scanning the request BODY can false-positive on CCR/file-introduced text and model-echoed tags that look like real markers. Enable it only for the narrow multi-bili relay case where an intermediate box strips `x-bili-hop` and you accept that false-positive risk. `"chainContentDetection": true` in the config file does the same; the env var wins. The `x-bili-hop` signal itself is unaffected by this switch. | | `BILI_CHAIN_STAMP` | Set `1` to turn ON egress emission of the **model-visible** `` chain-integrity checkpoint carrier (#1683, default OFF): when enabled, every request THIS instance actually processes leaves with a digest-bearing stamp so a downstream bili applies first-processor-wins even when the `x-bili-hop` header was stripped in transit (#1421). The carrier lands in a slot the terminal model also reads (a trailing `user` message on OpenAI/Responses, a trailing text part on Anthropic/Google), so models treat it as phantom user input and burn tokens commenting on it — which is why it is off by default. Enable it only for the narrow multi-bili relay case where `x-bili-hop` is stripped by an intermediate box and the digest-verified body-stamp is the sole guard against double-processing. Independent of `BILI_CHAIN_CONTENT` (inbound body-detection is also default OFF) and of the `x-bili-hop` passthrough, which works either way. `"chainEgressStamp": true` in the config file does the same; the env var wins. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index ca3c2b11c2..2487f5d5dd 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -327,6 +327,7 @@ | Key | Type | Default | Env | Description | |-----|------|---------|-----|-------------| +| `BILI_DSH_AUTHORED_COMPACTION` | boolean | false | — | 让 bili 本地应答 dsh 压缩摘要请求(返回折叠快照而非拒绝,#3733):身份头 + 内核渲染格式的块摘要,零出口流量;重放经 #2432 再基线识别。 | | `BILI_CONFIG_FILE` | string | unset (XDG config path) | — | 覆盖配置文件路径(路径重定位)。 | | `BILI_SESSIONS_DIR` | string | unset (XDG state path) | — | 会话记录的存放目录(路径重定位)。 | | `BILI_ENCRYPTION_KEY` | string | unset | — | 加密持久化载荷的密钥材料(机密)。 | diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index f1db743913..69125481bb 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -2,6 +2,14 @@ # Edit HERE, then run: node tools/gen-config-docs.mjs generate domain: env-only entries: + - key: BILI_DSH_AUTHORED_COMPACTION + type: boolean + default: "false" + kind: env-only + audience: user + group: envonly + desc_en: "Let bili ANSWER dsh compaction summarize calls locally with the folded snapshot instead of refusing (#3733): identity header + kernel-rendered block summaries, zero egress; replay recognized via the #2432 rebase." + desc_zh: "让 bili 本地应答 dsh 压缩摘要请求(返回折叠快照而非拒绝,#3733):身份头 + 内核渲染格式的块摘要,零出口流量;重放经 #2432 再基线识别。" - key: BILI_CONFIG_FILE type: string default: "unset (XDG config path)" From 74ba7835ca850b256bbe6fafb09a147f34783855 Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 00:51:11 +0800 Subject: [PATCH 3/6] docs: merge duplicated BILI_ALLOW_DSH_COMPACTION rows in CONFIGURATION.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In-passing fix found while reviewing #3737: since the #3540 merge, master has carried two adjacent BILI_ALLOW_DSH_COMPACTION detail rows — one with the #3384/#2490 output-budget paragraph but a stale pre-#3354 scope note, one with the current #3354-overlay scope note (the overlay marks preset-nested rows at any depth, pinned by tests/issue3354-dsh-compaction-disable.test.ts). Merge them into one canonical row keeping both unique paragraphs; the new BILI_DSH_AUTHORED_COMPACTION row from #3733 now sits in a single place. --- CONFIGURATION.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1e6508ad68..411a6c729e 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1857,9 +1857,8 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_AFFINITY_SIMHASH` | Set `0` to turn OFF simhash chain-alignment adoption (#2265): anonymous requests whose exact hash chain was broken by a client-side pervasive decorative rewrite (e.g. Trae re-stamping model tags on every assistant message) re-attach the existing session with its compression state instead of minting fresh and re-folding from zero. Guards: ≥90% coverage within Hamming 10, ≥20% mutated-but-similar positions (point edits still fork, #629), ≥1 byte-identical user message, unique candidate only. Default ON. `"affinitySimhash": false` in the config file does the same; the env var wins. | | `BILI_RESUME_INHERITANCE` | Set `0` to turn OFF resume inheritance (ON by default) (#1486): when an identified client (sends its own session id, e.g. Claude Code's `x-claude-code-session-id`) resumes a conversation under a NEW session id while replaying the full transcript (`cc --resume` forks a fresh UUID), bili matches the incoming history byte-exactly against that client's tracked chains (≥8 messages, append-only tracking) and, on the resumed session's first request, inherits the parent's ref assignments — stale model citations then resolve to their ORIGINAL messages instead of mis-hitting renumbered ones — adopts the fully-present compression blocks (together with this inheritance, #1834: losing them on resume meant the folded originals came back on the wire and the upstream request ballooned; the old `forkAdoption` co-gate now applies only to anonymous forks, #629), and records the `derivedFrom` lineage. The parent is never modified and fresh messages number above the parent's ref space. A resume must strictly EXTEND the parent's history — an equal-depth byte-exact replay under another id is a duplicate, not a resume. Anonymous sessions are unaffected (they keep their own pfa-* world, #309). `"resumeInheritance": false` in the config file does the same; the env var wins. | | `BILI_STABLE_SYSTEM_ANCHOR` | Set `1` to enable stable-system anchoring (#1085) — a **best-effort wire-layer fallback** for prefix caching: the root fix belongs client-side (the client owns its history and decides how to present instruction changes), this only stops the proxy from letting a changed head invalidate the whole cached prefix. **Plain-proxy mode only**: plugin-mode agents (`x-bili-plugin`) own their context management and are never anchored, so clients that already inject cache-friendly updates (e.g. claude-code-style system reminders) are not double-processed. When enabled, bili remembers each session's first-seen head system/instructions block and keeps re-sending those exact bytes even when the client's system prompt later changes. A **localized** change (a file-style edit sharing ≥70% of lines with the version in effect so far) appends a trailing `[System context update] …` user note carrying a compact line diff (`-` removed / `+` added; each note composes sequentially onto the previous one). A **non-localized** change (structural reshuffle, tool-def churn, timestamped banners, heads over 400 lines) is adopted outright — one deliberate cache miss beats appending noise that would mislead the model about its instructions. Churn guard: more than 8 accumulated notes likewise replace the anchor with the newest text and clear the log. The anchor and note log persist with the session and survive compression/compaction (session metadata, not kernel state). Known residual limitation: client-placed `cache_control` breakpoints may still misalign after a head swap. Excluded from anchoring: title-gen micro-requests (OpenAI/Google), Responses compaction-trigger requests, auto-mode classifier requests. Clients implementing their own variant (stable prompt + in-history updates) get zero extra injection — such updates pass through as ordinary history. Default is OFF. `"stableSystemAnchor": true` in the config file does the same; the env var wins. | -| `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. While the guard refuses, dsh's own context-pressure counter (its raw ledger) only grows — refused checkpoints never land — while bili's folds keep the wire payload small, so the session keeps working past the point where the client's gauge says "full", and dsh keeps re-requesting compaction (refused every time). Since #3384 the outgoing output budget is also no longer planned against that raw ledger, EXCEPT when bili's own folded view has already reached the enforced headroom target or the requested budget is >= 25% of the native window (the #2490 protection regimes) — before that fix the growing ledger silently shrank the model's output budget every turn, ending in error-free empty replies on onlyReasoning models. Scope note: on non-web profiles the shipped bundle patch (`auto: false`) still suppresses AUTO-triggering, so only manual `/compact` benefits there; on web profiles no patch layer can address the preset-nested row by id (#1772), so auto-triggering works as-is once allowed unless you apply the #2474 full-snapshot override of preset-standard from your profile's cordis.patch.yml. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | +| `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. While the guard refuses, dsh's own context-pressure counter (its raw ledger) only grows — refused checkpoints never land — while bili's folds keep the wire payload small, so the session keeps working past the point where the client's gauge says "full", and dsh keeps re-requesting compaction (refused every time). Since #3384 the outgoing output budget is also no longer planned against that raw ledger, EXCEPT when bili's own folded view has already reached the enforced headroom target or the requested budget is >= 25% of the native window (the #2490 protection regimes) — before that fix the growing ledger silently shrank the model's output budget every turn, ending in error-free empty replies on onlyReasoning models. Scope note: with bili ON, dsh native auto-compaction is now off on every plane — the host-plane row via the shipped bundle patch (`auto: false`), and web-profile preset instances at load time via the #3354 overlay — so this switch mainly governs manual `/compact` on non-web profiles (auto-triggering stays suppressed there) and any residual auto-triggering on dsh builds where the #3354 overlay does not apply. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | | `BILI_DSH_AUTHORED_COMPACTION` | Set `1` to have bili itself ANSWER dsh's compaction summarize calls locally instead of refusing them (#3733). Prerequisites per call: the #1729 guard fires (marker-decisive), the session holds at least one ACTIVE fold block, and `allowDshCompaction` is NOT enabled (the explicit "forward natively" choice always wins). The reply is forged with zero egress (the autoModeForge #2740 discipline): an identity header `` plus every active block's summary in the kernel render format — exactly the bytes the model already reads upstream, so client display, upstream context and server state agree for the first time, and dsh's checkpoint file shrinks (#3723's unbounded growth loop). Originals stay recoverable via CCR/export; the landed checkpoint is recognized on replay through the same #2432 rebase as a foreign one, but recorded as `dshAuthoredCheckpointLanded` (info, not warn). Env-only for the rollout window; read per-request, no restart needed. | -| `BILI_ALLOW_DSH_COMPACTION` | Set `1` to let dsh's built-in auto-compaction run through bili (#2028). By default the wire-level guard (#1729) **refuses dsh native compaction calls locally** (422) on every lane bili serves — openai, anthropic, and responses (responses added by #2360; it was the lane the pre-#2360 whitelist short-circuited before the marker was ever examined, so dsh desktop's compaction calls passed silently): dsh's `compaction-basic` answers context pressure by replaying the conversation prefix plus a fixed summarization directive as the final user message, and when such a call LANDS its checkpoint durably shadows the raw history — irreversible, and it destroys the proxy's compression substrate. This switch lifts the refusal so dsh-native compaction can actually execute. Scope note: with bili ON, dsh native auto-compaction is now off on every plane — the host-plane row via the shipped bundle patch (`auto: false`), and web-profile preset instances at load time via the #3354 overlay — so this switch mainly governs manual `/compact` on non-web profiles (auto-triggering stays suppressed there) and any residual auto-triggering on dsh builds where the #3354 overlay does not apply. The web config page exposes the same switch; the env var wins over the file. Set `"dsh": { "allowDshCompaction": true }` in the config file to the same effect (a bare top-level `"allowDshCompaction"` in an older file is auto-relocated there on load). | | `BILI_NO_CACHE_CONTROL` | Set `1` to disable bili's Anthropic-lane `cache_control` breakpoint stamping (#1637, shipped in #1639). On by default: Anthropic-style upstreams cache only what is explicitly breakpointed (max 4 per request, counted across system + tools + message blocks combined), so bili marks the system block plus up to 3 cumulative message marks — a marked message stays marked (byte-stable prefix), marks die only by folding, and the last 3 stable messages carry the advancing frontier. Any client-set `cache_control` (message blocks, tools entries) suppresses bili's stamps entirely — client-managed caching wins. Marks persist with the session. This switch is the escape hatch for upstreams that reject the field or relays with their own breakpoint policy. Plain-proxy Anthropic lane only; OpenAI/Responses lanes cache implicitly and are never stamped. Config-file twin: [`compat.noCacheControl`](#compat) — the env var wins. | | `BILI_CHAIN_CONTENT` | Set `1` to turn ON the ACP-artifact / `` checkpoint **body-content** detection of bili→bili chain awareness (#1086/#1421): when an inbound request carries compression artifacts (render tags / historical `acp_status`+`search_context` tool calls) or a digest-bearing checkpoint in its BODY but neither the `x-bili-hop` header nor local compression state for its session, bili records an advisory observation and/or applies first-processor-wins passthrough. **Default is OFF** (#1683 follow-up): by default ONLY the `x-bili-hop` header drives chain recognition, because scanning the request BODY can false-positive on CCR/file-introduced text and model-echoed tags that look like real markers. Enable it only for the narrow multi-bili relay case where an intermediate box strips `x-bili-hop` and you accept that false-positive risk. `"chainContentDetection": true` in the config file does the same; the env var wins. The `x-bili-hop` signal itself is unaffected by this switch. | | `BILI_CHAIN_STAMP` | Set `1` to turn ON egress emission of the **model-visible** `` chain-integrity checkpoint carrier (#1683, default OFF): when enabled, every request THIS instance actually processes leaves with a digest-bearing stamp so a downstream bili applies first-processor-wins even when the `x-bili-hop` header was stripped in transit (#1421). The carrier lands in a slot the terminal model also reads (a trailing `user` message on OpenAI/Responses, a trailing text part on Anthropic/Google), so models treat it as phantom user input and burn tokens commenting on it — which is why it is off by default. Enable it only for the narrow multi-bili relay case where `x-bili-hop` is stripped by an intermediate box and the digest-verified body-stamp is the sole guard against double-processing. Independent of `BILI_CHAIN_CONTENT` (inbound body-detection is also default OFF) and of the `x-bili-hop` passthrough, which works either way. `"chainEgressStamp": true` in the config file does the same; the env var wins. | From e726bcb0c685e93dde62f35f157596567ded75f2 Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 01:15:11 +0800 Subject: [PATCH 4/6] docs: complete zh-CN env table (merge leftover ALLOW_DSH_COMPACTION dup row; add DSH_AUTHORED_COMPACTION long-form entry) Review follow-up on #3737: commit 74ba7835c merged the duplicated BILI_ALLOW_DSH_COMPACTION rows in CONFIGURATION.md but left the zh-CN copy with both rows still present (one carrying the #3384 output-budget sentence, the other the newer #3354 scope note). Merged them into one row mirroring the EN union, and added the missing long-form BILI_DSH_AUTHORED_COMPACTION paragraph so the zh file matches the EN coverage (summary-table row + full description). --- CONFIGURATION.zh-CN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 2487f5d5dd..15ebb79103 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -1853,8 +1853,8 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_AFFINITY_SIMHASH` | 设为 `0` 关闭 simhash 链对齐收养(#2265):匿名请求的精确哈希链被客户端侧大面积装饰性改写(如 Trae 切模型后给每条 assistant 消息重打模型标签)打断时,重新挂回既有会话并保留压缩状态,而不是每次新铸会话、从零重折。护栏:覆盖率 ≥90%(Hamming ≤10)、变异位置 ≥20%(单点编辑仍走 fork,#629)、至少一条字节相同的用户消息、双候选歧义拒猜。默认开启。配置文件中设 `"affinitySimhash": false` 效果相同;环境变量优先。 | | `BILI_RESUME_INHERITANCE` | 设为 `0` 关闭 resume 继承(默认开启)(#1486):当带自有会话 id 的客户端(如 Claude Code 的 `x-claude-code-session-id`)以**新**会话 id 重放完整历史来续接会话时(`cc --resume` 会 fork 出新 UUID),bili 通过字节级前缀匹配(≥8 条消息、append-only 跟踪)识别出它与该客户端已跟踪历史的父子关系,并在续接会话的首个请求上继承父会话的 ref 分配 —— 模型引用的旧代际 refs 因此命中**原始**消息、而不是错配到重新编号的新消息 —— 同时继承源内容完整存在的压缩块(随本继承一并生效,#1834:resume 丢块会导致被折叠原文重新回到线上、上游请求膨胀;旧的 `forkAdoption` 联动门现仅作用于匿名 fork,#629),并记录 `derivedFrom` 血缘。父会话不受影响;新消息在父会话 ref 空间之上继续编号。resume 必须**严格扩展**父历史 —— 同深度的字节级重放(不同 id)视为重复会话而非 resume。匿名会话不受影响(保留自己的 pfa-* 世界,#309)。配置文件中设 `"resumeInheritance": false` 效果相同;环境变量优先。 | | `BILI_STABLE_SYSTEM_ANCHOR` | 设为 `1` 开启稳定 system 锚定(#1085)—— **wire 层兜底(best-effort)**:根治在客户端(会话历史与指令变更的呈现方式由客户端决定),本开关只是阻止代理因头部变化而使整个已缓存前缀失效。**仅限 plain-proxy 模式**:plugin-mode agent(`x-bili-plugin`)自管上下文、永不参与锚定,避免对已自带 cache-friendly 更新注入的客户端(如 claude-code 的 system-reminder)做双重处理。开启后,bili 按会话记住客户端首次发送的头部 system/instructions 块并持续原样重发。**局部变更**(文件式编辑,与当前生效版本共享 ≥70% 行)追加末尾 `[System context update] …` user 注记,内含紧凑行级 diff(`-` 删除 / `+` 新增;每条注记顺序叠加在前一条之上)。**非局部变更**(结构性重排、tool 定义增删、带时间戳的 banner、超 400 行的头部)直接采用新文本 —— 一次有意的缓存失效好过追加会误导模型的噪声 diff。防抖保护:累积超过 8 条注记同样直接替换锚点为最新文本并清空日志。锚点与注记日志随会话持久化,不受压缩/compaction 影响(session metadata 而非 kernel state)。已知残留限制:客户端自放的 `cache_control` 断点在换头后仍可能错位。不参与锚定的请求:标题生成微请求(OpenAI/Google)、Responses compaction-trigger 请求、auto-mode classifier 请求。客户端自身已实现同类机制(稳定 prompt + 历史内更新)时零额外注入 —— 这类更新作为普通历史透传。默认关闭。配置文件中设 `"stableSystemAnchor": true` 效果相同;环境变量优先。 | -| `BILI_ALLOW_DSH_COMPACTION` | 设为 `1` 放行 dsh 内置自动压缩(#2028)。默认由 wire 级守卫(#1729)**在本地拒绝 dsh 原生压缩调用**(422),覆盖 bili 服务的全部线路——openai、anthropic、responses(responses 由 #2360 补上:此前的协议白名单在检查标记之前就把 responses 短路了,而 dsh 桌面端的压缩恰好走这条线路,调用因此静默穿过):dsh 的 `compaction-basic` 应对上下文压力时会重放会话前缀、并把固定摘要指令作为最后一条 user 消息发出,此类调用一旦落地,其 checkpoint 会永久覆盖原始历史——不可逆,且摧毁代理的压缩基底。本开关解除该拒绝,让 dsh 原生压缩真正执行。在守卫拒绝期间,dsh 自己的上下文压力计数(原始账本)只增不减——被拒的 checkpoint 永不落地——而 bili 的折叠保持 wire 体积很小,因此会话在客户端仪表显示「已满」之后仍能继续工作,dsh 会不断重新请求压缩(持续被拒)。自 #3384 起,出站输出额度也不再按该原始账本规划——除非 bili 自己的折叠视图已到达强制的 headroom 目标线,或请求的额度达到原生窗口的 25% 及以上(#2490 保护区间);修复前,增长的账本会逐轮悄悄压掉模型的输出额度,在 onlyReasoning 模型上最终表现为无报错的空回复。作用范围:非 web profile 下随附 bundle patch(`auto: false`)仍抑制**自动**触发,因此那里只有手动 `/compact` 受益;web profile 下任何 patch 层都无法按 id 直寻 preset 嵌套行(#1772),因此放行后自动触发照常工作——除非在你的 profile `cordis.patch.yml` 里按 #2474 施加对 preset-standard 的完整快照覆盖。网页配置页提供同一开关;环境变量优先于文件。在配置文件的 `"dsh"` 段下设 `"allowDshCompaction": true` 效果相同(旧文件里裸写在顶层的 `"allowDshCompaction"` 会在加载时自动迁移到该位置)。 | -| `BILI_ALLOW_DSH_COMPACTION` | 设为 `1` 放行 dsh 内置自动压缩(#2028)。默认由 wire 级守卫(#1729)**在本地拒绝 dsh 原生压缩调用**(422),覆盖 bili 服务的全部线路——openai、anthropic、responses(responses 由 #2360 补上:此前的协议白名单在检查标记之前就把 responses 短路了,而 dsh 桌面端的压缩恰好走这条线路,调用因此静默穿过):dsh 的 `compaction-basic` 应对上下文压力时会重放会话前缀、并把固定摘要指令作为最后一条 user 消息发出,此类调用一旦落地,其 checkpoint 会永久覆盖原始历史——不可逆,且摧毁代理的压缩基底。本开关解除该拒绝,让 dsh 原生压缩真正执行。作用范围:bili 开启时,dsh 原生自动压缩现已在所有平面关闭 —— 宿主平面行经随附 bundle patch(`auto: false`)、web profile 的 preset 实例经 #3354 加载期 overlay —— 因此该开关主要治理非 web profile 的手动 `/compact`(那里的自动触发仍被 `auto: false` 抑制),以及 #3354 overlay 不适用的 dsh 构建上残留的自动触发。网页配置页提供同一开关;环境变量优先于文件。在配置文件的 `"dsh"` 段下设 `"allowDshCompaction": true` 效果相同(旧文件里裸写在顶层的 `"allowDshCompaction"` 会在加载时自动迁移到该位置)。 | +| `BILI_ALLOW_DSH_COMPACTION` | 设为 `1` 放行 dsh 内置自动压缩(#2028)。默认由 wire 级守卫(#1729)**在本地拒绝 dsh 原生压缩调用**(422),覆盖 bili 服务的全部线路——openai、anthropic、responses(responses 由 #2360 补上:此前的协议白名单在检查标记之前就把 responses 短路了,而 dsh 桌面端的压缩恰好走这条线路,调用因此静默穿过):dsh 的 `compaction-basic` 应对上下文压力时会重放会话前缀、并把固定摘要指令作为最后一条 user 消息发出,此类调用一旦落地,其 checkpoint 会永久覆盖原始历史——不可逆,且摧毁代理的压缩基底。本开关解除该拒绝,让 dsh 原生压缩真正执行。在守卫拒绝期间,dsh 自己的上下文压力计数(原始账本)只增不减——被拒的 checkpoint 永不落地——而 bili 的折叠保持 wire 体积很小,因此会话在客户端仪表显示「已满」之后仍能继续工作,dsh 会不断重新请求压缩(持续被拒)。自 #3384 起,出站输出额度也不再按该原始账本规划——除非 bili 自己的折叠视图已到达强制的 headroom 目标线,或请求的额度达到原生窗口的 25% 及以上(#2490 保护区间);修复前,增长的账本会逐轮悄悄压掉模型的输出额度,在 onlyReasoning 模型上最终表现为无报错的空回复。作用范围:bili 开启时,dsh 原生自动压缩现已在所有平面关闭 —— 宿主平面行经随附 bundle patch(`auto: false`)、web profile 的 preset 实例经 #3354 加载期 overlay —— 因此该开关主要治理非 web profile 的手动 `/compact`(那里的自动触发仍被 `auto: false` 抑制),以及 #3354 overlay 不适用的 dsh 构建上残留的自动触发。网页配置页提供同一开关;环境变量优先于文件。在配置文件的 `"dsh"` 段下设 `"allowDshCompaction": true` 效果相同(旧文件里裸写在顶层的 `"allowDshCompaction"` 会在加载时自动迁移到该位置)。 | +| `BILI_DSH_AUTHORED_COMPACTION` | 设为 `1` 让 bili **本地应答** dsh 的压缩摘要调用,而不是拒绝它们(#3733)。每次调用的前置条件:#1729 守卫触发(由标记决定)、会话至少持有一个 ACTIVE 折叠块、且 `allowDshCompaction` 未启用(显式的「原生转发」选择始终优先)。应答零出口流量构造(autoModeForge #2740 纪律):一行身份头 `` 加上每个活跃块的内核渲染格式摘要——与模型在上游已读到的字节完全一致,客户端显示、上游上下文与服务端状态首次吻合,dsh 的 checkpoint 文件随之缩小(终结 #3723 的无界增长环)。原始历史随时可经 CCR/导出恢复;落地的检查点在重放时经同一 #2432 rebase 识别(与外部 checkpoint 同路径),但记为 `dshAuthoredCheckpointLanded`(info 而非 warn)。灰度窗口期 env-only(无配置文件键);每请求读取,无需重启。 | | `BILI_NO_CACHE_CONTROL` | 设为 `1` 关闭 bili 在 Anthropic 通道上的 `cache_control` 断点标注(#1637,随 #1639 落地)。默认开启:Anthropic 系上游只缓存被显式打断点的内容(每请求最多 4 个,按 system + tools + 消息块合并计数),因此 bili 会标注 system 块加上至多 3 个累积消息断点——被标注的消息保持标注(前缀字节稳定),断点只随折叠消亡,最近 3 条稳定消息承载推进前沿。客户端自设的任何 `cache_control`(消息块、tools 条目)都会完全抑制 bili 的标注——客户端自管缓存优先。断点随会话持久化。本开关是逃生阀:用于拒绝该字段的上游或有自己断点策略的中继。仅限 plain-proxy Anthropic 通道;OpenAI/Responses 通道隐式缓存,从不标注。配置文件对应项:[`compat.noCacheControl`](#compat) —— 环境变量优先。 | | `BILI_CHAIN_CONTENT` | 设为 `1` 开启 bili→bili 链感知的 ACP 产物 / `` 检查点**正文内容**检测(#1086/#1421):当入站请求的正文携带压缩产物(渲染标签 / 历史 `acp_status`+`search_context` 工具调用)或带摘要的检查点,但既无 `x-bili-hop` 头、本实例也无该会话的压缩状态时,bili 记录一次告警性观察和/或应用「首个处理器优先」透传。**默认关闭**(#1683 后续):默认下只有 `x-bili-hop` 头驱动链识别,因为扫描请求正文可能把 CCR/文件引入的文本和模型回声标签误判为真实标记。仅在中间盒子剥掉 `x-bili-hop`、且你接受该误判风险的狭窄多 bili 中继场景下才启用。配置文件中设 `"chainContentDetection": true` 效果相同;环境变量优先。`x-bili-hop` 信号本身不受此开关影响。 | | `BILI_CHAIN_STAMP` | 设为 `1` 开启**模型可见**的 `` 链完整性检查点载体的出站注入(#1683,默认关闭):开启后,本实例实际处理的每个请求都携带一个带摘要的戳,使下游 bili 即使 `x-bili-hop` 头在传输中被剥离也能应用「首个处理器优先」(first-processor-wins)(#1421)。该载体落在终端模型同样会读取的位置(OpenAI/Responses 上是一条尾部 `user` 消息,Anthropic/Google 上是尾部文本 part),因此模型会把它当作幽灵用户输入并花 token 去评论它——这正是它默认关闭的原因。仅在多 bili 中继、且中间盒子剥掉 `x-bili-hop`、带摘要校验的 body-stamp 是防止双重处理的唯一手段这一狭窄场景下才启用。与 `BILI_CHAIN_CONTENT`(入站正文检测同样默认关闭)及 `x-bili-hop` 透传相互独立(后者无论如何都生效)。配置文件中设 `"chainEgressStamp": true` 效果相同;环境变量优先。 | From 5e0ba2a53711cc5599f93fdb000411532faa6b5a Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 01:17:49 +0800 Subject: [PATCH 5/6] docs: hex-escape the snapshot tag example in the module header (KDD #2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on #3737: the module-header example rendered the identity tag with literal angle brackets, unlike every other bili-tag example in the codebase (tag-echo-filter.ts / chain-checkpoint.ts write \x3c/\x3e even inside comments) — tooling that strips well-formed tags would mangle the example. Comment-only, zero behavior change. --- src/server/dsh-authored-compaction.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/dsh-authored-compaction.ts b/src/server/dsh-authored-compaction.ts index 8d96b7b154..decb9f3127 100644 --- a/src/server/dsh-authored-compaction.ts +++ b/src/server/dsh-authored-compaction.ts @@ -7,7 +7,7 @@ // summarize call LOCALLY instead of refusing it — zero egress, the // autoModeForge (#2740) discipline — with OUR folded snapshot as the payload: // -// +// \x3cbili-snapshot v1 conv="…" seq="…" blocks="…" \x3e // [Compressed conversation section] — … // // From 4ce21964724ea040fcdb2f4a7eb825375bde09c9 Mon Sep 17 00:00:00 2001 From: awork Date: Mon, 19 Oct 2026 01:27:48 +0800 Subject: [PATCH 6/6] test: responses-wire landing lane for authored checkpoints (#3733) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewer follow-up on #3737: the landing->replay->rebase e2e covered only the openai wire, but dsh desktop's compaction actually rides /v1/responses (#2360) — an untested prepare-responses OR-branch wiring mistake (wrong knownIds space or message view) would pass CI silently. Add a self-contained responses harness (function_call SSE arm turn folding m00001..m00008) that pins: authored answer on the production wire (zero egress, identity header + kernel-format summary in the prompt-forge stream), and replay through x-bili-plugin: dsh recognized via response.output_text.done extraction -> dshAuthoredCheckpointLanded. --- tests/dsh-authored-compaction.test.ts | 134 ++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) diff --git a/tests/dsh-authored-compaction.test.ts b/tests/dsh-authored-compaction.test.ts index c9f4f4f5f4..37f0a4f952 100644 --- a/tests/dsh-authored-compaction.test.ts +++ b/tests/dsh-authored-compaction.test.ts @@ -414,3 +414,137 @@ test("e2e: landed checkpoint is recognized on replay — rebase + authored-lande assert.equal(s.metadata["dshAuthoredCheckpointLanded"], true, "authored landing recognized"); }); }); + +// --------------------------------------------------------------------------- +// E2E: real proxy + mock upstream on the RESPONSES wire — dsh desktop's actual +// compaction lane (#2360). The landing recognition must hold there too, not +// just on the openai wire above: authored answer (delegated to the codex +// prompt-forge body) + replay through x-bili-plugin: dsh rebases and marks +// dshAuthoredCheckpointLanded. + +function respSse(type: string, data: unknown): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +function respCompleted(inputTokens: number): string { + return respSse("response.completed", { response: { id: "resp_done", status: "completed", output: [], usage: { input_tokens: inputTokens, output_tokens: 5, total_tokens: inputTokens + 5 } } }); +} + +function respFcEvents(callId: string, args: string): string { + return [ + respSse("response.output_item.added", { item: { type: "function_call", id: `fc_${callId}`, call_id: callId, name: "compress" }, output_index: 0 }), + respSse("response.function_call_arguments.delta", { item_id: `fc_${callId}`, delta: args }), + respSse("response.output_item.done", { item: { type: "function_call", id: `fc_${callId}`, call_id: callId, name: "compress", arguments: args }, output_index: 0 }), + ].join(""); +} + +// Responses-shape copy of conversation(): same 24 messages / ~9k tokens, so +// m00001..m00008 fold exactly like the openai lane above. +function respConversation(): { type: string; role: string; content: string }[] { + const out: { type: string; role: string; content: string }[] = []; + for (let i = 0; i < 24; i++) { + out.push({ type: "message", role: i % 2 === 0 ? "user" : "assistant", content: `Message ${i} of the working session. ` + `WORK_${i}_content_`.repeat(88) }); + } + return out; +} + +test("e2e: responses wire — authored answer + landed checkpoint recognized on replay", async () => { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + bodies.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + if (bodies.length === 1) { + // First turn: the model compresses m00001..m00008 → active block. + const args = JSON.stringify({ content: [{ startId: "m00001", endId: "m00008", topic: "setup", summary: SUMMARY }] }); + res.write(respFcEvents("call_p", args)); + } + res.write(respCompleted(9_000)); + res.end(); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + _resetSessionsForTest(); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: 15_000 } } } }, + modelContextLimit: 15_000, + kernelConfig: defaultConfig(15_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + passthroughSource: null, + autoUpdate: false, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: true, + releaseNotesCheck: true, + compat: { roles: {} }, + streamErrorShape: "protocol", + mitm: { enabled: false, domains: [] }, + } as unknown as ProxyOptions); + await once(proxy, "listening"); + const port = (proxy.address() as { port: number }).port; + const url = `http://127.0.0.1:${port}/bili/http://127.0.0.1:${upstreamPort}/v1/responses`; + const post = (input: unknown[], extraHeaders: Record = {}): Promise => + fetch(url, { method: "POST", headers: { "content-type": "application/json", ...extraHeaders }, body: JSON.stringify({ model: "gpt-test", stream: true, session_id: "s-resp", instructions: "You are the test coding agent.", input }) }); + const sessionOf = (): { state: { blocks: { active: boolean }[] }; metadata: Record } | undefined => + listSessions().find((x) => x.meta.label === "s-resp") as never; + try { + // Arm: a normal turn where the model folds m00001..m00008 → active block. + const r0 = await post(respConversation()); + assert.equal(r0.status, 200); + await r0.text(); + assert.ok(sessionOf()?.state.blocks.some((b) => b.active), "setup created an active block"); + + // Authored compaction on dsh desktop's production wire: zero egress, forge body. + process.env.BILI_DSH_AUTHORED_COMPACTION = "1"; + const before = bodies.length; + const r1 = await post([{ type: "message", role: "user", content: `${DSH_COMPACTION_INSTRUCTION_PREFIX} Condense the conversation above.` }]); + assert.equal(r1.status, 200); + const streamText = await r1.text(); + assert.ok(streamText.includes(BILI_SNAPSHOT_TAG_PREFIX), "identity header in the forged responses stream"); + assert.ok(streamText.includes(SUMMARY), "block summary in the forged responses stream"); + assert.equal(bodies.length, before, "upstream never contacted (zero egress)"); + assert.equal(sessionOf()?.metadata["dshAuthoredCompactions"], 1, "authored counter"); + + // dsh records the last assistant message item as its checkpoint and + // replays [checkpoint, retained tail] with its plugin identity. + const done = streamText.split("\n\n") + .map((f) => { try { return f.startsWith("data: ") ? (JSON.parse(f.slice(6)) as Record) : null; } catch { return null; } }) + .find((j): j is Record & { text: string } => j !== null && j.type === "response.output_text.done" && typeof j.text === "string"); + assert.ok(done, "output_text.done frame present in the forged stream"); + const payload = done.text; + assert.ok(payload.includes(BILI_SNAPSHOT_TAG_PREFIX), "checkpoint payload extracted from the real stream"); + const checkpointText = `${DSH_CHECKPOINT_PREAMBLE_PREFIX}:\n\n${DSH_CHECKPOINT_OPEN_TAG}\n${payload}\n\x3c/compacted-summary\x3e`; + const r2 = await post([ + { type: "message", role: "user", content: checkpointText }, + { type: "message", role: "assistant", content: "ack" }, + { type: "message", role: "user", content: "continue the work" }, + ], { "x-bili-plugin": "dsh" }); + assert.equal(r2.status, 200); + await r2.text(); + assert.equal(sessionOf()?.metadata["dshAuthoredCheckpointLanded"], true, "authored landing recognized on the responses wire"); + } finally { + proxy.close(); + proxy.closeIdleConnections?.(); + await once(proxy, "close"); + upstream.close(); + upstream.closeIdleConnections?.(); + await once(upstream, "close"); + delete process.env.BILI_DSH_AUTHORED_COMPACTION; + delete process.env.BILI_ALLOW_DSH_COMPACTION; + } +});