Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1566,7 +1566,18 @@ async function handle(
// so a foreign session leaves no trace in this instance.
if (artifactSeed) {
const artifactKind = detectAcpArtifacts(bodyBuffer, parsed);
if (artifactKind !== null && !hasProcessedState(sessionId, { protocol })) {
// #1197: a cooperative plugin announces itself with x-bili-plugin —
// its protocol RE-SENDS bili's compression artifacts (the compress
// tool call + result live in the agent's own re-sent history by
// design), so content-shape evidence can never outrank that
// announcement. The #1086 fallback guards NON-cooperative clients
// chained behind a header-stripping middlebox; a plugin client that
// is ALSO double-chained through another bili AND had the hop header
// stripped is contrived, and weighing it against silently losing
// compression + /acp for every resumed plugin session (the #1197
// incident) says: process.
const pluginAnnounced = pluginAgentHeader(req.headers) !== undefined;
if (artifactKind !== null && !pluginAnnounced && !hasProcessedState(sessionId, { protocol })) {
if (!warnedChainSessions.has(sessionId)) {
warnedChainSessions.add(sessionId);
if (warnedChainSessions.size > WARNED_CHAIN_SESSION_CAP) {
Expand Down
60 changes: 58 additions & 2 deletions src/server/chain-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,72 @@ export function artifactSeedHit(body: Buffer): boolean {

/** Verify which ACP artifact family is actually present in the request.
* `parsed` is the already-parsed body (null when unparseable — then only
* the tag check can fire). Returns null when neither family is present. */
* the legacy whole-buffer tag check can fire). Returns null when neither
* family is present.
*
* #1197: the tags family scans HISTORY message content only. bili's
* compression artifacts (render tags, the re-voiced acp_summary, plugin
* compress tool results) always live in history items — never in the
* system/developer/instructions section. Tag-shaped text there is
* client-authored context (AGENTS.md/CLAUDE.md/README quoting the wire
* format — the billion-context repo itself carries literal examples) and
* is not chain evidence. */
export function detectAcpArtifacts(body: Buffer, parsed: unknown): AcpArtifactKind | null {
if (body.includes("\x3cacp ") && ACP_TAG_RE.test(body.toString("utf8"))) return "tags";
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
// ACP_TAG_RE matches the JSON-escaped form (tokens=\"…\") because it
// was born scanning the raw wire buffer; re-encode the parsed history
// text so both paths share one regex.
const encoded = JSON.stringify(historyTextOf(parsed as Record<string, unknown>));
if (encoded.includes("\x3cacp ") && ACP_TAG_RE.test(encoded)) return "tags";
} else if (body.includes("\x3cacp ") && ACP_TAG_RE.test(body.toString("utf8"))) {
return "tags";
}
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const names = historyToolCallNames(parsed as Record<string, unknown>);
if (names.has("acp_status") && names.has("search_context")) return "tool-history";
}
return null;
}

/** Text of HISTORY items only (messages/input/contents), excluding
* system/developer-role messages; the top-level system / instructions
* fields are never visited. Mirrors the container walk of
* historyToolCallNames. */
function historyTextOf(parsed: Record<string, unknown>): string {
const parts: string[] = [];
const container = Array.isArray(parsed.messages) ? parsed.messages
: Array.isArray(parsed.input) ? parsed.input
: Array.isArray(parsed.contents) ? parsed.contents
: null;
if (container) {
for (const item of container) collectHistoryText(item, parts);
}
return parts.join("\n");
}

function collectHistoryText(item: unknown, out: string[]): void {
if (!item || typeof item !== "object" || Array.isArray(item)) return;
const it = item as Record<string, unknown>;
if (it.role === "system" || it.role === "developer") return;
const content = it.content;
if (typeof content === "string") out.push(content);
else if (Array.isArray(content)) {
for (const block of content) {
if (block && typeof block === "object" && !Array.isArray(block) && typeof (block as Record<string, unknown>).text === "string") {
out.push((block as Record<string, unknown>).text as string);
}
}
}
const parts = it.parts;
if (Array.isArray(parts)) {
for (const part of parts) {
if (part && typeof part === "object" && !Array.isArray(part) && typeof (part as Record<string, unknown>).text === "string") {
out.push((part as Record<string, unknown>).text as string);
}
}
}
}

/** Collect tool names invoked in HISTORY items only: OpenAI
* messages[].tool_calls[].function.name, Anthropic content blocks
* {type:"tool_use",name}, Responses input[] {type:"function_call",name},
Expand Down
198 changes: 198 additions & 0 deletions tests/issue1086-chain-self-exemption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -656,3 +656,201 @@ test("#1101 T9: BILI_CHAIN_CONTENT env parse — default ON, 0 disables, env win
rmSync(root, { recursive: true, force: true });
}
});

// #1197: tag-shaped text in the SYSTEM section is client-authored context
// (AGENTS.md/CLAUDE.md/README quoting the wire format — the billion-context
// repo itself carries literal examples), never bili compression output:
// render tags and the re-voiced acp_summary always live in HISTORY items.
test("#1197 detector: tags in system/developer/instructions are NOT artifacts", () => {
const realTag = "\x3cacp tokens=\"59\" type=\"text\"\x3em00001\x3c/acp\x3e";

const openaiSystem = { model: MODEL, messages: [
{ role: "system", content: `Project rules — refs look like ${realTag}` },
{ role: "user", content: "reply 1234" },
] };
assert.ok(artifactSeedHit(Buffer.from(JSON.stringify(openaiSystem))), "byte pre-filter still hits");
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(openaiSystem)), openaiSystem), null, "openai system-role tags must not read as chain evidence");

const developer = { model: MODEL, messages: [
{ role: "developer", content: `wire examples: ${realTag}` },
{ role: "user", content: "hi" },
] };
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(developer)), developer), null, "developer-role tags are context, not artifacts");

const anthropicSystem = { model: MODEL, system: [{ type: "text", text: `docs quote ${realTag}` }], messages: [{ role: "user", content: "hi" }] };
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(anthropicSystem)), anthropicSystem), null, "anthropic top-level system is never scanned");

const responsesInstructions = { model: MODEL, instructions: `format: ${realTag}`, input: [{ type: "message", role: "user", content: "hi" }] };
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(responsesInstructions)), responsesInstructions), null, "responses instructions is never scanned");
});

test("#1197 detector: tags in HISTORY still are artifacts (tool results, user messages)", () => {
const realTag = "\x3cacp tokens=\"1.2K\" type=\"text\"\x3em00042\x3c/acp\x3e";
const toolResult = { model: MODEL, messages: [
{ role: "user", content: "compress please" },
{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "compress", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "c1", content: `blocks folded ${realTag}` },
] };
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(toolResult)), toolResult), "tags", "tool-result tags (plugin compress replay) remain detectable");

const userMsg = { model: MODEL, messages: [{ role: "user", content: `folded ${realTag}` }] };
assert.equal(detectAcpArtifacts(Buffer.from(JSON.stringify(userMsg)), userMsg), "tags", "history-message tags remain detectable");
});

// The exact #1197 incident: a fresh session whose system prompt carries literal
// tag examples from the project's AGENTS.md (cwd = a billion-context checkout)
// used to be verdict-ed into permanent passthrough — /acp stuck on armed-idle
// and the whole session ran uncompressed.
test("#1197 T10: system-prompt tags on a fresh plain-client session are processed, not judged a chain", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-chain-t10-"));
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 = makeUpstream(captured);
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 realTag = "\x3cacp tokens=\"59\" type=\"text\"\x3em00001\x3c/acp\x3e";
const raw = JSON.stringify({
model: MODEL,
stream: false,
messages: [
{ role: "system", content: `# Project docs\nRef anchors ${realTag} in summaries.` },
{ role: "user", content: "reply with exactly: 1234" },
],
});
const resp = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/v1/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", "x-acp-session": "ctx-1" },
body: raw,
});
assert.equal(resp.status, 200);
await resp.text();
assert.equal(captured.length, 1);
assert.notEqual(sha(captured[0]!.body), sha(raw), "#1197: context-file tags must go through the kernel, not raw passthrough");
assert.equal(chainWarns(logs, "ctx-1").length, 0, "no chain warning for client-authored system content");
assert.equal(peekSession("ctx-1")?.stats.requests, 1, "session must be created and processed");
} finally {
setLogCapture(null);
proxy.closeAllConnections?.();
await close(proxy);
upstream.closeAllConnections?.();
await close(upstream);
store.cancelAll();
rmSync(dir, { recursive: true, force: true });
}
});

// A cooperative plugin's protocol re-sends its compression artifacts (compress
// tool call + result in history) by design; the announcement header outranks
// content-shape evidence, so a resumed plugin session is processed even when
// this instance holds no state for it.
test("#1197 T11: plugin-announced request with history artifacts is processed, not judged a chain", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-chain-t11-"));
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 = makeUpstream(captured);
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 raw = incidentBody();
const resp = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/v1/chat/completions`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-acp-session": "plug-1",
"x-bili-plugin": "pi",
"x-bili-plugin-conversation": "plug-1",
},
body: raw,
});
assert.equal(resp.status, 200);
await resp.text();
assert.equal(captured.length, 1);
assert.notEqual(sha(captured[0]!.body), sha(raw), "#1197: plugin-announced replay must be rebuilt by the kernel, not passed through");
assert.equal(chainWarns(logs, "plug-1").length, 0, "no chain warning for a cooperative plugin's own replay");
assert.equal(peekSession("plug-1")?.stats.requests, 1, "session must be created (plugin binding) and processed");
} finally {
setLogCapture(null);
proxy.closeAllConnections?.();
await close(proxy);
upstream.closeAllConnections?.();
await close(upstream);
store.cancelAll();
rmSync(dir, { recursive: true, force: true });
}
});

// 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 () => {
const dir = mkdtempSync(join(tmpdir(), "bili-chain-t12-"));
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 = makeUpstream(captured);
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 {
// 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 raw = JSON.stringify({
model: MODEL,
stream: false,
messages: [
{ role: "system", content: "You are a test assistant." },
{ role: "user", content: `earlier context folded ${realTag} continue` },
],
});
for (let i = 0; i < 2; i++) {
const resp = await fetch(`http://127.0.0.1:${(proxy.address() as { port: number }).port}/v1/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", "x-acp-session": "foreign-tags-1" },
body: raw,
});
assert.equal(resp.status, 200);
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);
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");
} finally {
setLogCapture(null);
proxy.closeAllConnections?.();
await close(proxy);
upstream.closeAllConnections?.();
await close(upstream);
store.cancelAll();
rmSync(dir, { recursive: true, force: true });
}
});
Loading