From 40409f3bc28e1b1f0d5d2102e9023256da53bbc2 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 02:13:33 +0800 Subject: [PATCH 1/3] fix: downgrade ACP body-artifact detection to advisory (#1357) A fresh proxy session whose history carried ACP-shaped content (render tags or ACP tool-name invocations) with no local state was judged a foreign bili chain and forwarded byte-identical (prepared=null), once per session, with NO session record created. Because that content persists in the client's re-sent history, the session was locked into passthrough forever -- compression never engaged for any conversation containing literal ACP tags (e.g. an AGENTS.md example), even though those tags are just user-authored text. Phase 1 of #1357: make ACP *body* artifact detection advisory-only. When such artifacts appear without x-bili-hop and without local compression state, log one observation per session and let the request enter processTurn so the session establishes its own state. The x-bili-hop header remains authoritative verbatim passthrough (unchanged). The /acp diagnostics surface is repurposed from chain-passthrough to chain-advisory. Behavior change (old -> new): content-detected fresh session went from byte-identical passthrough / no session record / permanent lock-in, to processed normally (session owns its own state) with one advisory warn and real /acp activity. Tradeoff: a header-stripping bili->bili relay may now double-process until signed chain proof ships (Phases 2/3, out of scope). Tests: T3/T8/T12/#1218 updated to the advisory contract; added Responses-wire and Anthropic-wire regression tests; the regression fixture uses the verbatim AGENTS.md tag shape inline plus inside a fenced code block. Fixes #1357 --- src/config.ts | 10 +- src/plugin.ts | 26 +-- src/server.ts | 33 +-- tests/anthropic-pck-verbatim.test.ts | 22 +- tests/issue1086-chain-self-exemption.test.ts | 202 +++++++++++++++---- 5 files changed, 218 insertions(+), 75 deletions(-) diff --git a/src/config.ts b/src/config.ts index 329414907a..f8208b6cd3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -590,10 +590,11 @@ export type ProxyOptions = { * fully-present compression blocks instead of restarting at zero. * Enable with `forkAdoption: true` or env BILI_FORK_ADOPTION=1. */ forkAdoption?: boolean; - /** Content fallback of the bili→bili chain detection: when an inbound + /** Content detection of the bili→bili chain awareness: when an inbound * request carries ACP artifacts (render tags / ACP tool-call history) * but no x-bili-hop header and no local compression state for the - * session, pass it through verbatim instead of processing (#1086). + * session, record one advisory observation and process normally (#1086, + * advisory-only since #1357) — never verbatim passthrough. * Default ON; escape valve via env BILI_CHAIN_CONTENT=0 or * `chainContentDetection: false` in the config file (env wins). The * x-bili-hop signal is unaffected by this switch. */ @@ -937,8 +938,9 @@ type FileConfig = { * zero compression state. Default false; env BILI_FORK_ADOPTION=1/0 * wins over the file. */ forkAdoption?: boolean; - /** Set `false` to disable the ACP-artifact content fallback of the - * bili→bili chain detection (#1086); x-bili-hop stays active either way. + /** Set `false` to disable the ACP-artifact content detection of the + * bili→bili chain awareness (#1086, advisory-only since #1357); + * x-bili-hop stays active either way. * Env BILI_CHAIN_CONTENT=0 wins over the file. */ chainContentDetection?: boolean; /** Set `true` to enable the sticky head-system anchor (#1085, default diff --git a/src/plugin.ts b/src/plugin.ts index 440af59ad7..f32003096f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -686,12 +686,14 @@ export function _chainVerdictMapForTest(): Map { return chainVerdicts; } -/** #1218: the /acp panel rendered when a conversation is being passed through - * unprocessed. Every /acp surface (pi / dsh / opencode) displays `panel` - * verbatim, so the server renders the verdict once and all clients show it - * without agent-side changes. */ -function chainPassthroughPanel(v: ChainVerdict): string { - return `⚠️ billion-context: this conversation is being PASSED THROUGH UNPROCESSED — judged an external bili chain by the content fallback (evidence: ${v.kind}, protocol ${v.protocol}). No local compression session exists, so compression is silently disabled for this conversation. Last passthrough: ${new Date(v.at).toISOString()}. If this is your own client, disable the content fallback (chainContentDetection=false, env BILI_CHAIN_CONTENT=0); see the [chain] warn in the bili log.`; +/** #1357 Phase 1: the /acp panel rendered when a conversation carried + * historical ACP content with no prior local state. That content is now + * ADVISORY-only — observed but NOT treated as a foreign chain, so the request + * was processed normally and the conversation owns its own compression session. + * Every /acp surface (pi / dsh / opencode) displays `panel` verbatim, so the + * server renders it once and all clients show it without agent-side changes. */ +function chainAdvisoryPanel(v: ChainVerdict): string { + return `ℹ️ billion-context: this conversation carried ACP-shaped content (evidence: ${v.kind}, protocol ${v.protocol}) with no prior local compression state. Historical ACP content is advisory-only (#1357) — it was NOT treated as a foreign bili chain, so the request was processed normally and this conversation owns its own compression session. Last observation: ${new Date(v.at).toISOString()}. See the [chain] warn in the bili log.`; } export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false): void { @@ -716,15 +718,15 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt } } if (!session) { - // #1218: a chain/content-fallback verdict for THIS conversation means - // requests ARE arriving — passed through unprocessed — so the - // armed-idle notice would mislead ("no model request yet" is false). - // Answer 200 with a renderable panel; `phase` exposes the state for - // programmatic consumers. + // #1357 Phase 1: a content-fallback verdict for THIS conversation means + // requests ARE arriving and carried historical ACP content — now an + // ADVISORY observation (processed normally), so the armed-idle notice + // would mislead ("no model request yet" is false). Answer 200 with a + // renderable panel; `phase` exposes the state for programmatic consumers. const verdict = chainVerdictFor(conversationId); if (verdict !== undefined) { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, conversationId, phase: "chain-passthrough", chain: verdict, panel: chainPassthroughPanel(verdict) })); + res.end(JSON.stringify({ ok: true, conversationId, phase: "chain-advisory", chain: verdict, panel: chainAdvisoryPanel(verdict) })); return; } // Runtime-info protocol (#955): no session exists yet, but the client diff --git a/src/server.ts b/src/server.ts index 0d12b57e69..ec76af4b5b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1686,20 +1686,27 @@ async function handle( // incident) says: process. const pluginAnnounced = pluginAgentHeader(req.headers) !== undefined; if (artifactKind !== null && !pluginAnnounced && !hasProcessedState(sessionId, { protocol })) { - // #1218: record the verdict under the session id AND the - // client's own conversation value when they differ — /acp - // status probes arrive keyed by the client's value (the same - // key space resolveConversation uses), and the session-bound - // id alone would be invisible to the client. + // #1357 Phase 1: historical ACP content is ADVISORY, never + // decisive. It can be user-authored (AGENTS.md / docs / CCR + // lossless originals / pastes), so judging it a foreign chain + // and forwarding verbatim here permanently locked FRESH sessions + // into passthrough — the decision returned before any session was + // created, so no ownership state ever existed to clear the next + // request. Record the observation for /acp diagnostics and fall + // through to processTurn so this session establishes ownership. + // Decisive passthrough stays reserved for the authenticated + // x-bili-hop header (above + at the passthrough tail). Trade-off: + // a bili→bili relay that STRIPS x-bili-hop now double-processes + // until signed request-bound chain proof ships (#1357 Phase 2/3). + // #1218: recorded under the session id AND the client's own + // conversation value when they differ (same key space /acp + // status probes use) so the observation is visible to the client. const firstVerdict = recordChainVerdict(sessionId, artifactKind, protocol); if (clientConv !== undefined && clientConv !== sessionId) recordChainVerdict(clientConv, artifactKind, protocol); if (firstVerdict) { - log("warn", `[chain] inbound ${protocol} request carries ACP compression artifacts (${artifactKind}) but neither ${BILI_HOP_HEADER} nor local compression state for session ${sessionId} — likely a bili→bili chain whose headers were stripped. Passing through without processing; if this is your own client, disable the content fallback with chainContentDetection=false (env BILI_CHAIN_CONTENT=0).`); + log("warn", `[chain] inbound ${protocol} request carries ACP compression artifacts (${artifactKind}) but neither ${BILI_HOP_HEADER} nor local compression state for session ${sessionId}. Historical ACP content is advisory-only — continuing to processTurn so this session establishes ownership (#1357); a header-stripping bili→bili relay may now double-process until signed chain proof lands.`); } - await forward(req, res, opts, scrubAnthropicPck(protocol, bodyBuffer, log), null, core, config, log, route, instanceId, undefined); - return; - } - if (artifactKind !== null) { + } else if (artifactKind !== null) { log("debug", `[chain] ACP artifacts (${artifactKind}) belong to this instance's own session ${sessionId} — self-produced, processing normally (#1086)`); } } @@ -2637,9 +2644,9 @@ function effectiveTokenCount(session: Session, msgs: CoreMessage[], inboundImage // #1403: top-level prompt_cache_key is NOT part of the Anthropic Messages API. // It is the omp plugin's session id stamped for the proxy's identity chain // (#268); the fully-processed path strips it (prepareAnthropic), but every -// VERBATIM forward branch (side-request passthrough #388, chain verdict #1086, -// bypass/passthrough marks, route/global passthrough #661, decode-fail -// fallback) used to ship the raw buffer through — strict-schema upstreams +// VERBATIM forward branch (side-request passthrough #388, hop-marker chain +// passthrough, bypass/passthrough marks, route/global passthrough #661, +// decode-fail fallback) used to ship the raw buffer through — strict-schema upstreams // (opencode zen: "prompt_cache_key: Extra inputs are not permitted") 400'd // the request. Strip on those branches too. A body WITHOUT the field passes // back byte-identical, so #661's fingerprinting contract is untouched in the diff --git a/tests/anthropic-pck-verbatim.test.ts b/tests/anthropic-pck-verbatim.test.ts index 32ed8bb4c7..5cb9bce7d0 100644 --- a/tests/anthropic-pck-verbatim.test.ts +++ b/tests/anthropic-pck-verbatim.test.ts @@ -17,7 +17,8 @@ import { _setForTest as setRegistryForTest } from "../src/registry.ts"; // #1403 wire invariant: the omp plugin stamps prompt_cache_key into the body // as its session id (#268); that field is NOT part of the Anthropic Messages // API, so EVERY anthropic forward path must ship it stripped — side requests -// (#388), chain verdicts (#1086), passthrough marks (#1117/#920), the +// (#388), chain advisories (#1086/#1357: advisory processing since #1357, the +// rebuild never forwards stamped fields), passthrough marks (#1117/#920), the // non-conversation relay (#1284), global/route passthrough (#661). The fake // upstream below enforces zen's strict schema: top-level prompt_cache_key ⇒ // the exact production 400. @@ -177,7 +178,7 @@ test("#1403 T1: side request (max_tokens<=200) verbatim forward strips stamped p } }); -test("#1403 T2: chain-verdict raw forward (foreign ACP artifacts, no local state) strips stamped prompt_cache_key", async () => { +test("#1403/#1357 T2: advisory processing of foreign ACP artifacts strips stamped prompt_cache_key", async () => { const dir = mkdtempSync(path.join(tmpdir(), "bili-pck-chain-")); const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); _setStoreForTest(store); @@ -197,15 +198,18 @@ test("#1403 T2: chain-verdict raw forward (foreign ACP artifacts, no local state const out = await post(pport, `/bili/http://127.0.0.1:${uport}/v1/messages`, anthropicBody(sid, 1024, `keep ${tag}`), { "x-acp-session": sid }); assert.equal(out.status, 200, `strict upstream must never see prompt_cache_key; got ${out.status}: ${out.body.slice(0, 200)}`); assert.equal(captured.length, 1); - assert.ok(!captured[0]!.body.includes("prompt_cache_key"), "chain-verdict forward must strip the stamped field"); - // Compare the PARSED message text, not raw JSON bytes: quotes inside - // the tag are escaped on the wire, and a kernel re-render (wrong path) - // would renumber the ref — only the verbatim chain forward keeps it. + assert.ok(!captured[0]!.body.includes("prompt_cache_key"), "advisory processing must still strip the stamped field"); + // #1357: historical ACP content is advisory — the request is PROCESSED + // (kernel re-render adds its own tag header), not verbatim-forwarded. + // Compare the PARSED message text: the user's literal tag must survive + // byte-intact inside the rebuilt body. const sentText = (JSON.parse(captured[0]!.body) as { messages: { content: { type: string; text: string }[] }[] }).messages[0]!.content[0]!.text; - assert.equal(sentText, `keep ${tag}`, "the rest of the body must arrive untouched"); + assert.notEqual(sentText, `keep ${tag}`, "#1357: foreign ACP literal is advisory — processed, not verbatim chain forward"); + assert.ok(sentText.includes(`keep ${tag}`), "user text and literal tag survive processing intact"); const warns = logs.filter((l) => l.level === "warn" && l.msg.includes("[chain]") && l.msg.includes(sid)); - assert.equal(warns.length, 1, "expected exactly one [chain] verdict warn for the foreign session"); - assert.equal(peekSession(sid), undefined, "chain passthrough must not create local state"); + assert.equal(warns.length, 1, "expected exactly one [chain] advisory warn for the foreign session"); + assert.ok(warns[0]!.msg.includes("#1357"), "warn cites the #1357 advisory downgrade"); + assert.notEqual(peekSession(sid), undefined, "advisory processing establishes local session state (#1357)"); }); } finally { setLogCapture(null); diff --git a/tests/issue1086-chain-self-exemption.test.ts b/tests/issue1086-chain-self-exemption.test.ts index b48eb29985..e7bab7a0ea 100644 --- a/tests/issue1086-chain-self-exemption.test.ts +++ b/tests/issue1086-chain-self-exemption.test.ts @@ -24,8 +24,9 @@ import { artifactSeedHit, detectAcpArtifacts } from "../src/server/chain-artifac // artifacts; historical tool calls are; real tags are; placeholders aren't). // 2. self-state exemption — artifacts + local processed state ⇒ processed. // 3. fresh plugin-mode session (declarations only) ⇒ processed, no warn. -// 4. foreign artifacts without local state ⇒ byte-identical passthrough, -// exactly one warn per session, no session record created. +// 4. #1357 Phase 1: foreign artifacts without local state are ADVISORY — +// processed normally so the session owns itself; one advisory warn, and +// only x-bili-hop remains decisive verbatim passthrough. // 5. escape valve chainContentDetection=false disables the fallback. // 6. liveness guard — a plain-client chat-wire session still compresses // as it grows (the #1086 failure mode was silent non-compression). @@ -153,6 +154,19 @@ function makeUpstream(captured: Captured[]): http.Server { }); } +function makeJsonUpstream(captured: Captured[], respond: () => unknown): http.Server { + return http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + captured.push({ url: req.url ?? "", headers: req.headers, body }); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(respond())); + }); + }); +} + type LogRec = { level: string; msg: string }; const chainWarns = (logs: LogRec[], sessionId?: string): LogRec[] => logs.filter((l) => l.level === "warn" && l.msg.includes("[chain]") && (!sessionId || l.msg.includes(sessionId))); @@ -256,7 +270,7 @@ test("#1086 T2: fresh plugin-mode session (declarations only) is processed, not } }); -test("#1086 T3: foreign artifacts without local state pass through byte-identical, one warn, no state", async () => { +test("#1086/#1357 T3: foreign artifacts without local state are ADVISORY — processed, owned, one warn", async () => { // #1100: "no local state ⇒ foreign" holds only when persistence proves ownership // across a restart, so T3 runs an ENABLED store over an empty temp dir (truly // foreign). Disabled-store variant is ambiguous (own session after restart) → T6. @@ -286,12 +300,13 @@ test("#1086 T3: foreign artifacts without local state pass through byte-identica await resp.text(); } assert.equal(captured.length, 2); - assert.equal(captured[0]!.body, raw, "foreign payload must reach the LLM byte-identical (no kernel processing)"); - assert.equal(captured[1]!.body, raw); + assert.notEqual(captured[0]!.body, raw, "historical ACP content is advisory — processed, not passed through verbatim (#1357)"); + assert.notEqual(captured[1]!.body, raw, "second request also processed (no permanent passthrough)"); const warns = chainWarns(logs, "foreign-1"); - assert.equal(warns.length, 1, `exactly one warn per session (got ${warns.length}: ${JSON.stringify(warns)})`); - assert.ok(warns[0]!.msg.includes("chainContentDetection=false"), "warning must point at the escape valve"); - assert.equal(peekSession("foreign-1"), undefined, "foreign sessions must leave no trace in this instance"); + assert.equal(warns.length, 1, `exactly one advisory warn per session (got ${warns.length}: ${JSON.stringify(warns)})`); + assert.ok(warns[0]!.msg.includes("#1357"), "warn cites the #1357 advisory downgrade"); + assert.ok(warns[0]!.msg.includes("advisory"), "warn states historical ACP content is advisory-only"); + assert.ok(peekSession("foreign-1") !== undefined, "the advisory session establishes local ownership (no longer left trace-less)"); } finally { setLogCapture(null); proxy.closeAllConnections?.(); @@ -303,11 +318,12 @@ test("#1086 T3: foreign artifacts without local state pass through byte-identica } }); -test("#1218: /acp explains chain passthrough instead of the armed-idle notice", async () => { - // Same shape as T3: a session whose requests are judged an external chain - // is passed through with NO local state. /acp (plugin status) must surface - // WHY there is no session — the user sees "PASSED THROUGH" with the escape - // valve, not "no model request yet" (#1218 repro). +test("#1218/#1357: a content-detected conversation owns a real session; /acp shows real activity", async () => { + // #1357 Phase 1: body-artifact detection is advisory-only, so a conversation + // whose history carries ACP-shaped content is PROCESSED and owns its own state. + // Pre-#1357 symptom (#1218): such requests passed through with NO session, so + // /acp showed a misleading armed-idle "no model request yet". Now /acp reflects + // the real session — requests served, panel built; never armed-idle or passthrough. const dir = mkdtempSync(join(tmpdir(), "bili-chain-1218-")); const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); _setStoreForTest(store); @@ -328,19 +344,16 @@ test("#1218: /acp explains chain passthrough instead of the armed-idle notice", }); assert.equal(resp.status, 200); await resp.text(); - assert.equal(peekSession("chain-exp-1"), undefined, "passthrough leaves no session"); + assert.ok(peekSession("chain-exp-1") !== undefined, "advisory content establishes a real local session (#1357)"); const probe = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/__bili/plugin/status?conversationId=chain-exp-1`); const probeBody = await probe.text(); assert.equal(probe.status, 200, `status probe failed: ${probeBody.slice(0, 200)}`); - const status = JSON.parse(probeBody) as { ok: boolean; conversationId: string; phase: string; chain: { at: number; kind: string; protocol: string }; panel: string }; + const status = JSON.parse(probeBody) as { ok: boolean; conversationId: string; phase?: string; requests?: number; panel?: string }; assert.equal(status.ok, true); assert.equal(status.conversationId, "chain-exp-1"); - assert.equal(status.phase, "chain-passthrough"); - assert.equal(typeof status.chain.kind, "string"); - assert.ok(status.chain.kind.length > 0, "verdict carries the evidence kind"); - assert.equal(status.chain.protocol, "openai"); - assert.ok(status.panel.includes("PASSED THROUGH UNPROCESSED"), `panel explains the passthrough (got: ${status.panel.slice(0, 120)}…)`); - assert.ok(status.panel.includes("chainContentDetection=false"), "panel points at the escape valve"); + assert.notEqual(status.phase, "chain-passthrough", "content is advisory, not a decisive chain verdict"); + assert.ok((status.requests ?? 0) >= 1, `/acp reflects the served request (got requests=${status.requests})`); + assert.equal(typeof status.panel, "string", "/acp renders a real session panel, not the armed-idle notice"); // A conversation with NO verdict keeps the pre-#1218 answer shape — // the new branch must not hijack unrelated probes. const clean = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/__bili/plugin/status?conversationId=never-seen`); @@ -679,7 +692,7 @@ test("#1101 T8: warn-set FIFO evicts the oldest session once past the cap", asyn }); assert.equal(resp.status, 200); await resp.text(); - assert.equal(captured[0]!.body, raw, "foreign payload still passes through byte-identical"); + assert.notEqual(captured[0]!.body, raw, "#1357: foreign historical content is advisory — processed, not byte-identical"); assert.ok(warnSet.has("fifo-evict"), "newly warned session must be tracked"); assert.ok(!warnSet.has("pad-0"), "oldest entry must be FIFO-evicted once past the cap"); assert.ok(warnSet.has("pad-1"), "only the single oldest entry is evicted per add"); @@ -854,12 +867,12 @@ test("#1197 T11: plugin-announced request with history artifacts is processed, n } }); -// Review of #1213: T3 pins the #1086 fallback for the TOOL-HISTORY family at -// server level, but nothing pinned it for the TAGS family — the exact family -// this PR re-scopes. A non-cooperative client whose HISTORY carries real -// render tags must still be judged a chain when this instance holds no state -// for it: byte-identical passthrough, one warn, no session record. -test("#1197 T12: foreign client with tags in HISTORY passes through byte-identical, one warn, no state", async () => { +// #1357 Phase 1 regression (TAGS family, primary fixture): ACP tag literals in +// ordinary HISTORY are advisory-only. The literal below mirrors the AGENTS.md +// example VERBATIM and appears BOTH inlined AND inside a fenced code block — the +// exact real-world trigger. Pre-#1357 this forced byte-identical passthrough +// forever; now it is processed normally, the session owns itself, one advisory warn. +test("#1357 T12: ACP tag literals in history are advisory — processed, owned, one warn (not passthrough)", async () => { const dir = mkdtempSync(join(tmpdir(), "bili-chain-t12-")); const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); _setStoreForTest(store); @@ -875,15 +888,25 @@ test("#1197 T12: foreign client with tags in HISTORY passes through byte-identic const proxy = await startServer(makeOpts(`http://127.0.0.1:${(upstream.address() as { port: number }).port}`)); await listen(proxy); try { - // Proxy-mode chain shape: the re-voiced acp_summary lands as a user - // message whose content carries the render tags. - const realTag = "\x3cacp tokens=\"1.2K\" type=\"text\"\x3em00042\x3c/acp\x3e"; + const acpExample = "\x3cacp tokens=\"2\" type=\"text\"\x3em00001\x3c/acp\x3e"; + const userText = [ + "Here is how compression tags look:", + "", + acpExample, + "", + "And inside a code fence:", + "```", + acpExample, + "```", + "", + "Please continue from here.", + ].join("\n"); const raw = JSON.stringify({ model: MODEL, stream: false, messages: [ { role: "system", content: "You are a test assistant." }, - { role: "user", content: `earlier context folded ${realTag} continue` }, + { role: "user", content: userText }, ], }); for (let i = 0; i < 2; i++) { @@ -896,12 +919,117 @@ test("#1197 T12: foreign client with tags in HISTORY passes through byte-identic await resp.text(); } assert.equal(captured.length, 2); - assert.equal(captured[0]!.body, raw, "foreign payload with history tags must reach the LLM byte-identical (no kernel processing)"); - assert.equal(captured[1]!.body, raw); + assert.notEqual(captured[0]!.body, raw, "ACP literals in history are advisory — processed, not passed through verbatim (#1357)"); + assert.notEqual(captured[1]!.body, raw, "second request also processed (no permanent passthrough)"); const warns = chainWarns(logs, "foreign-tags-1"); - assert.equal(warns.length, 1, `exactly one warn per session (got ${warns.length}: ${JSON.stringify(warns)})`); - assert.ok(warns[0]!.msg.includes("chainContentDetection=false"), "warning must point at the escape valve"); - assert.equal(peekSession("foreign-tags-1"), undefined, "foreign sessions must leave no trace in this instance"); + assert.equal(warns.length, 1, `exactly one advisory warn per session (got ${warns.length}: ${JSON.stringify(warns)})`); + assert.ok(warns[0]!.msg.includes("#1357"), "warn cites the #1357 advisory downgrade"); + assert.ok(warns[0]!.msg.includes("advisory"), "inline + fenced ACP examples are advisory-only, not decisive"); + assert.ok(peekSession("foreign-tags-1") !== undefined, "the session establishes local ownership instead of leaving no trace"); + } finally { + setLogCapture(null); + proxy.closeAllConnections?.(); + await close(proxy); + upstream.closeAllConnections?.(); + await close(upstream); + store.cancelAll(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#1357 T13: Responses wire — ACP tag literal in history is advisory, processed, owned", async () => { + const dir = mkdtempSync(join(tmpdir(), "bili-chain-resp-")); + const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); + _setStoreForTest(store); + _resetSessionsForTest(); + _resetChainWarningsForTest(); + setRegistryForTest({}); + const logs: LogRec[] = []; + setLogCapture((level, msg) => logs.push({ level, msg })); + const captured: Captured[] = []; + const upstream = makeJsonUpstream(captured, () => ({ + id: "resp-test", status: "completed", + output: [{ type: "message", role: "assistant", content: [{ type: "output_text", text: "ok" }] }], + usage: { input_tokens: 10, output_tokens: 5 }, + })); + upstream.listen(0, "127.0.0.1"); + await listen(upstream); + const proxy = await startServer(makeOpts(`http://127.0.0.1:${(upstream.address() as { port: number }).port}`)); + await listen(proxy); + try { + const acpExample = "\x3cacp tokens=\"2\" type=\"text\"\x3em00001\x3c/acp\x3e"; + const raw = JSON.stringify({ + model: MODEL, + stream: false, + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: `earlier folded ${acpExample}\ncontinue please` }] }, + ], + }); + const resp = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/v1/responses`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "resp-advisory-1" }, + body: raw, + }); + assert.equal(resp.status, 200); + await resp.text(); + assert.equal(captured.length, 1); + assert.notEqual(captured[0]!.body, raw, "Responses ACP literal is advisory — processed, not passed through verbatim (#1357)"); + const warns = chainWarns(logs, "resp-advisory-1"); + assert.equal(warns.length, 1, `exactly one advisory warn (got ${warns.length})`); + assert.ok(warns[0]!.msg.includes("#1357"), "warn cites #1357"); + assert.ok(peekSession("resp-advisory-1") !== undefined, "Responses session establishes local ownership"); + } finally { + setLogCapture(null); + proxy.closeAllConnections?.(); + await close(proxy); + upstream.closeAllConnections?.(); + await close(upstream); + store.cancelAll(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#1357 T14: Anthropic wire — ACP tag literal in history is advisory, processed, owned", async () => { + const dir = mkdtempSync(join(tmpdir(), "bili-chain-anth-")); + const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); + _setStoreForTest(store); + _resetSessionsForTest(); + _resetChainWarningsForTest(); + setRegistryForTest({}); + const logs: LogRec[] = []; + setLogCapture((level, msg) => logs.push({ level, msg })); + const captured: Captured[] = []; + const upstream = makeJsonUpstream(captured, () => ({ + id: "msg-test", type: "message", role: "assistant", model: MODEL, + content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", + usage: { input_tokens: 10, output_tokens: 5 }, + })); + upstream.listen(0, "127.0.0.1"); + await listen(upstream); + const proxy = await startServer(makeOpts(`http://127.0.0.1:${(upstream.address() as { port: number }).port}`)); + await listen(proxy); + try { + const acpExample = "\x3cacp tokens=\"2\" type=\"text\"\x3em00001\x3c/acp\x3e"; + const raw = JSON.stringify({ + model: MODEL, + max_tokens: 1024, + messages: [ + { role: "user", content: [{ type: "text", text: `earlier folded ${acpExample}\ncontinue please` }] }, + ], + }); + const resp = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/v1/messages`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "anthropic-advisory-1" }, + body: raw, + }); + assert.equal(resp.status, 200); + await resp.text(); + assert.equal(captured.length, 1); + assert.notEqual(captured[0]!.body, raw, "Anthropic ACP literal is advisory — processed, not passed through verbatim (#1357)"); + const warns = chainWarns(logs, "anthropic-advisory-1"); + assert.equal(warns.length, 1, `exactly one advisory warn (got ${warns.length})`); + assert.ok(warns[0]!.msg.includes("#1357"), "warn cites #1357"); + assert.ok(peekSession("anthropic-advisory-1") !== undefined, "Anthropic session establishes local ownership"); } finally { setLogCapture(null); proxy.closeAllConnections?.(); From 9834eaaeba78eed8b6465008bea8a9d46e080ef8 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 02:33:45 +0800 Subject: [PATCH 2/3] docs(server): refresh stale chain-fallback comment for #1357 advisory behavior --- src/server.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/server.ts b/src/server.ts index ec76af4b5b..74b4410f16 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1665,13 +1665,14 @@ async function handle( } } const sessionId = anonAffinity ? anonAffinity.sessionId : conversation; - // #1086: content-fallback chain verdict, now that identity is known. + // #1086/#1357: content-fallback chain observation, now that identity is known. // Artifacts + processed local state ⇒ self-produced: process normally. - // Artifacts + NO local state ⇒ an upstream bili already compressed - // this payload and its headers were stripped: forward verbatim and - // create no session state (same contract as the hop-marker path). - // Returning before getSession also skips note()/register consumption, - // so a foreign session leaves no trace in this instance. + // Artifacts + NO local state ⇒ ADVISORY observation (#1357 Phase 1): the + // content may be user-authored (AGENTS.md examples, docs, pastes), so it + // no longer forces byte-identical passthrough — record one observation for + // /acp diagnostics and fall through to processTurn so this session + // establishes its own ownership state. Decisive verbatim passthrough + // stays reserved for the x-bili-hop header (above). if (artifactSeed) { const artifactKind = detectAcpArtifacts(bodyBuffer, parsed); // #1197: a cooperative plugin announces itself with x-bili-plugin — From 6588fb0c2f809a536428ed8af770c7385a6c4b08 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 02:33:45 +0800 Subject: [PATCH 3/3] docs: BILI_CHAIN_CONTENT row now describes #1357 advisory semantics (zh/en) --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 190b86cdd8..ea7219dc1b 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -615,7 +615,7 @@ Environment variables take precedence over the config file. They are useful for | `BILI_SUBAGENT_SPLIT` | Set `0` to turn OFF Claude Code subagent session splitting (#970): by default, anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair (background subagents) get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. Default is ON. `"subagentSplit": false` in the config file does the same; the env var wins. | | `BILI_FORK_ADOPTION` | Set `1` to turn ON fork block-adoption (#629): when an anonymous (prefix-affinity) client forks its history mid-conversation (edit-and-resend / regenerate an earlier turn), the new session inherits the parent's compression blocks whose source content is fully present in the forked request — instead of restarting with zero compression state and re-folding the shared prefix from scratch. Default is OFF. `"forkAdoption": true` in the config file does the same; the env var wins. The adoptable inventory is logged on every anonymous fork even while disabled, so you can size the win before flipping it on. | | `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_CHAIN_CONTENT` | Set `0` to turn OFF the ACP-artifact content fallback of bili→bili chain detection (#1086): when an inbound request carries compression artifacts (render tags / historical `acp_status`+`search_context` tool calls) but neither the `x-bili-hop` header nor local compression state for its session, it is passed through verbatim instead of being processed again (a middlebox may have stripped the hop header from a chained request). Default is ON. `"chainContentDetection": false` in the config file does the same; the env var wins. The `x-bili-hop` signal itself is unaffected by this switch. | +| `BILI_CHAIN_CONTENT` | Set `0` to turn OFF the ACP-artifact content detection of bili→bili chain awareness (#1086, advisory-only since #1357): when an inbound request carries compression artifacts (render tags / historical `acp_status`+`search_context` tool calls) but neither the `x-bili-hop` header nor local compression state for its session, bili records ONE advisory observation (a single `[chain]` warn, visible in `/acp`) and processes the request normally — the session establishes its own state. Historical ACP-shaped content is user-authored text (AGENTS.md examples, docs, pastes) far more often than a stripped-header relay, so it is no longer decisive; only the `x-bili-hop` header still forces byte-identical passthrough. Trade-off: a bili→bili relay that strips `x-bili-hop` may now double-process until signed request-bound chain proof lands (#1357 Phase 2/3). Set `0` to disable the detection itself (no observation, no warn). Default is ON. `"chainContentDetection": false` in the config file does the same; the env var wins. The `x-bili-hop` signal itself is unaffected by this switch. | | `BILI_CHAIN_MAX_FUTURE_SKEW_MS` | Maximum future skew (ms) tolerated when validating a chain checkpoint's `issued-at` timestamp (#1395 step 2): a checkpoint stamped more than this far into the future is judged `stale` (replay / clock skew) even when its digest verifies. Default `120000` (2 min); non-numeric or non-positive values fall back to the default. Step 2 is shadow-only — these knobs tune verdict logging, never forwarding. | | `BILI_CHAIN_RECENT_WINDOW_MS` | Recency window (ms) for chain-checkpoint validation (#1395 step 2): a checkpoint older than this is judged `stale`. Default `600000` (10 min); non-numeric or non-positive values fall back to the default. Step 2 is shadow-only — these knobs tune verdict logging, never forwarding. | | `BILI_CONFLICT_SCAN` | Set `0` to disable third-party compression plugin detection (#1206). On by default: bili scans the client's own plugin/extension registries — opencode global + project `plugin` arrays, pi global + project `.pi/settings.json` `packages`, omp `config.yml` `extensions`, claude settings `enabledPlugins`/`plugins` + its plugins dir, kimi `plugins/installed.json`, hermes plugins dir, dsh profile dependencies — for another compressor co-resident with bili. Two tiers: **known conflicts** (`opencode-acp`, legacy `billion-context-pi`) and **keyword-suspected** entries (names matching compress / compact / acp / summar* / context*; bili's own entries are always skipped, and non-compression tools like `context7` do not match). Findings surface as launcher stderr lines before client start, a one-time proxy warn log on each session's first request, and the session's conflict ledger — visible in `acp_status`'s `COMPRESSION CONFLICTS` section, aggregated at `GET /__bili/stats` → `conflicts`, and shown as a web-UI banner. Runtime interference evidence (unannounced history rewrites #1001, orphan-block deactivations) feeds the same ledger. The scan is read-only, best-effort, 5-minute cached, and never blocks or modifies client config. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 84d07ddcca..627e12f01c 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -611,7 +611,7 @@ | `BILI_SUBAGENT_SPLIT` | 设为 `0` 关闭 Claude Code subagent 会话分流(#970):默认情况下,anthropic 线路上同时携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 头的请求(后台 subagent)会获得独立的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 不再排在主会话的锁后面。默认开启。配置文件中设 `"subagentSplit": false` 效果相同;环境变量优先。 | | `BILI_FORK_ADOPTION` | 设为 `1` 开启 fork 块继承(#629):匿名(prefix-affinity)客户端在会话中途分叉历史(编辑重发 / 从更早轮次重新生成)时,新会话直接继承父会话中"源内容在分叉请求里完整存在"的压缩块 —— 而不是从零开始、把共享前缀重新折叠一遍。默认关闭。配置文件中设 `"forkAdoption": true` 效果相同;环境变量优先。无论开关如何,匿名 fork 发生时日志都会记录可继承的块清单,便于先评估收益再开启。 | | `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_CHAIN_CONTENT` | 设为 `0` 关闭 bili→bili 链检测的 ACP 产物内容回退(#1086):当入站请求携带压缩产物(渲染标签 / 历史 `acp_status`+`search_context` 工具调用)但既无 `x-bili-hop` 头、本实例也无该会话的压缩状态时,请求被原样透传而不再次处理(中间设备可能已剥掉链路上的 hop 头)。默认开启。配置文件中设 `"chainContentDetection": false` 效果相同;环境变量优先。`x-bili-hop` 信号本身不受此开关影响。 | +| `BILI_CHAIN_CONTENT` | 设为 `0` 关闭 bili→bili 链感知的 ACP 产物内容检测(#1086,#1357 起为仅告警):当入站请求携带压缩产物(渲染标签 / 历史 `acp_status`+`search_context` 工具调用)但既无 `x-bili-hop` 头、本实例也无该会话的压缩状态时,bili 只记录一次告警性观察(单条 `[chain]` warn,可在 `/acp` 查看)并正常处理请求——该会话建立自己的状态。历史中的 ACP 形内容绝大多数是用户自撰文本(AGENTS.md 示例、文档、粘贴),而非被剥头的中继,因此不再作为决定性依据;只有 `x-bili-hop` 头仍强制字节级原样透传。代价:剥掉 `x-bili-hop` 的 bili→bili 中继在签名的请求绑定链证明落地前(#1357 Phase 2/3)可能被双重处理。设为 `0` 则关闭检测本身(不观察、不告警)。默认开启。配置文件中设 `"chainContentDetection": false` 效果相同;环境变量优先。`x-bili-hop` 信号本身不受此开关影响。 | | `BILI_CHAIN_MAX_FUTURE_SKEW_MS` | 校验链检查点 `issued-at` 时间戳时容忍的最大未来偏斜(毫秒)(#1395 step 2):戳在比当前时间未来超过此值的检查点会被判为 `stale`(重放 / 时钟偏斜),即使其摘要校验通过。默认 `120000`(2 分钟);非数字或非正值回退到默认值。Step 2 仅影子模式——这些旋钮只调判定日志,绝不影响转发。 | | `BILI_CHAIN_RECENT_WINDOW_MS` | 链检查点校验的近期窗口(毫秒)(#1395 step 2):早于此窗口的检查点被判为 `stale`。默认 `600000`(10 分钟);非数字或非正值回退到默认值。Step 2 仅影子模式——这些旋钮只调判定日志,绝不影响转发。 | | `BILI_CONFLICT_SCAN` | 设为 `0` 关闭第三方压缩插件检测(#1206)。默认开启:bili 会扫描客户端自身的插件/扩展注册表 —— opencode 全局 + 项目配置的 `plugin` 数组、pi 全局 + 项目 `.pi/settings.json` 的 `packages`、omp `config.yml` 的 `extensions`、claude 设置的 `enabledPlugins`/`plugins` 及其插件目录、kimi `plugins/installed.json`、hermes 插件目录、dsh profile 依赖 —— 查找与 bili 并存的另一个压缩器。两个层级:**已知冲突**(`opencode-acp`、遗留 `billion-context-pi`,确定性判定)和**关键词疑似**条目(名称匹配 compress / compact / acp / summar* / context*;bili 自身条目永远跳过,`context7` 这类非压缩工具不会误报)。发现结果出现在:客户端启动前的 launcher stderr、每个会话首个请求的一次性代理 warn 日志、以及会话冲突台账 —— `acp_status` 的 `COMPRESSION CONFLICTS` 段、`GET /__bili/stats` → `conflicts`、Web UI 横幅。运行时干扰证据(未宣告的历史改写 #1001、孤儿块废弃)记入同一台账。「扫描只读、尽力而为、5 分钟缓存,绝不阻塞或改动客户端配置。」 |