Skip to content
Open
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1743,6 +1743,18 @@ export type Prepared = {
* success response was forged locally (BILI_CODEX_COMPACT=intercept +
* gate passed). forward() serves `body` without contacting upstream. */
codexForge?: { kind: "endpoint" | "trigger" | "prompt"; body: string; contentType: string };
/** #2411 Class A: set by prepareOpenai when the request IS a host-native
* compaction act (summarization template as last user message — see
* src/server/native-compact-shape.ts). The compression surface was stood
* down for this turn; preflight must skip it too — folding the same
* history the host is asking to summarize would put two compressors on
* one turn (#2432/#2373 pathology). */
nativeCompact?: boolean;
/** #2411 Stage B: set with nativeCompact when bili's own fold summaries are
* served AS the completion for the host-native compaction request — same
* zero-egress contract as codexForge; forward() serves `body` without
* contacting upstream. */
nativeCompactForge?: { body: string; contentType: string };
/** #2740: set when a Claude Code auto-mode classifier one-shot was answered
* locally (BILI_AUTO_MODE_FORGE, default on). forward() serves `body`
* without contacting upstream — zero egress, zero billing for the lane. */
Expand Down
7 changes: 5 additions & 2 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2599,8 +2599,11 @@ async function handleRequest(
}
// A locally-served codex compaction forge never reaches an
// upstream: preflight would burn summarization rounds for a
// reply that is already forged (#3008 prompt form).
if (!countTokens && !responsesCompact && !prepared.codexForge && !prepared.threadsLane) {
// reply that is already forged (#3008 prompt form). #2411 Class
// A: a host-native compaction request IS the compression act —
// folding the same history the host is asking to summarize
// would put two compressors on one turn; skip like codexForge.
if (!countTokens && !responsesCompact && !prepared.codexForge && !prepared.nativeCompact && !prepared.threadsLane) {
const outcome = await preflightCompressIfNeeded(
prepared,
runPrepare,
Expand Down
65 changes: 65 additions & 0 deletions src/server/native-compact-shape.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// #2411 Class A: detect host-native compaction requests on the OpenAI wire so
// bili can stand down its own compression surface for that one turn.
//
// Evidence (ezjbc live captures, #2411 thread, unified Trae client via
// sidecar -> bili, 2026-10-18~23 window):
// - 17/17 native auto-compaction requests carry the host's summarization
// template as the LAST user message; 38/40 session-store copies are
// byte-identical across 21 days / 9 models / 2 channels. Store original:
// 6,861 raw-LF bytes, sha256 d56eeae339bd8007… (reporter's correction —
// his first-posted e5a1804e… was the CRLF-normalized digest). The
// thread-pasted copy embedded in the test fixture lost 4 bytes (newlines)
// in markdown transit — hence anchors below instead of a full-text hash.
// - Both known variants (6861-char Trae mainstream, 6980-char legacy with an
// <analysis> block) share line 1 and the final instruction sentence. The
// Trae-only "<user_input/>" line and the <summary>/<analysis> tags are
// deliberately NOT anchors: variant-specific, and model free-form products
// never matched them anyway (#2849's phrase pair has zero hits here).
// - Secondary anchor "/compact": manual slash-command form from static
// bytecode (module 79484 QP predicate); zero occurrences in the 17 live
// samples, kept as a cheap secondary signal for manual triggers.
// - The compaction PRODUCT (re-injected head-of-history user turn such as
// "## 1. Primary Request and Intent") is deliberately NOT matched — it is
// model free-form per the template's <example>, so product-shape matching
// is fragile; instruction-shape matching is stable (40/40).
//
// Evidence-permitlist discipline (#970/#1104): this predicate gates ACP
// surface suppression on ONE wire family only. It fails open — any structural
// deviation (parts-array content, non-user last message, missing either
// anchor, unparseable body) leaves the request fully instrumented, exactly as
// before this module existed.

/** First line of both known template variants (offset 0, 40/40 hits). */
const NATIVE_COMPACT_LEAD_ANCHOR = "Your task is to create a detailed summary of the conversation so far";
/** Final instruction sentence shared by both variants (false-positive guard). */
const NATIVE_COMPACT_TAIL_ANCHOR = "Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.";
/** Manual slash-command trigger form (static bytecode evidence only). */
const NATIVE_COMPACT_SLASH_FORM = "/compact";

// Leading ACP render-tag prefix(es) the host may echo back verbatim — bili
// renders refs into outbound messages (renderTags), clients persist those
// bytes and resend them. Grammar mirrors src/server/chain-artifacts.ts
// (unescaped wire form); hex escapes per KDD #2.
const LEADING_ACP_TAGS = /^\s*(?:\x3cacp\s+tokens="\d+(?:\.\d+)?K?"\s+type="[^"]*"\s*\x3em\d{1,8}\x3c\/acp\x3e\s*)+/;

/** Strip leading ACP render-tag prefix(es) plus surrounding whitespace. */
export function stripLeadingAcpTags(text: string): string {
return text.replace(LEADING_ACP_TAGS, "").trimStart();
}

/** True when the request IS a host-native compaction act: the last user
* message is the host's summarization template (or the manual "/compact"
* form). See the module header for anchors and evidence. Fails open. */
export function looksLikeNativeCompactionRequest(parsed: unknown): boolean {
if (!parsed || typeof parsed !== "object") return false;
const messages = (parsed as { messages?: unknown }).messages;
if (!Array.isArray(messages) || messages.length === 0) return false;
const last = messages[messages.length - 1];
if (!last || typeof last !== "object") return false;
const rec = last as { role?: unknown; content?: unknown };
if (rec.role !== "user" || typeof rec.content !== "string") return false;
const t = stripLeadingAcpTags(rec.content).trimEnd();
if (t === "") return false;
if (t === NATIVE_COMPACT_SLASH_FORM) return true;
return t.startsWith(NATIVE_COMPACT_LEAD_ANCHOR) && t.includes(NATIVE_COMPACT_TAIL_ANCHOR);
}
56 changes: 56 additions & 0 deletions src/server/openai-compact-forge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { randomUUID } from "node:crypto";

// #2411 Stage B: local forge for host-native compaction requests on the openai
// lane (TRAE Code / unified Trae client). When the host fires its own auto-compact
// it sends its ~6.9KB summarization template as the LAST user message on the
// normal chat endpoint; bili intercepts that request (nativeCompact predicate,
// src/server/native-compact-shape.ts) and serves its OWN fold summaries as the
// completion — upstream never contacted (zero-egress contract, same class as
// codexForge). E2 capture (reporter, #2411 floor 36): the backend's response to
// this request shape is an ORDINARY chat completion — no private progress
// frames, no pseudo-tool events, terminal shape = final data frame with
// finish_reason:"stop" + usage followed by `data: [DONE]`. So the forge is a
// standard chat.completion / chat.completion.chunk pair, nothing more. The
// id prefix marks bili-forged completions for downstream greps, mirroring
// codex's fc_bili_ sentinel.

export const OPENAI_COMPACT_ID_PREFIX = "chatcmpl_bili_";

interface OpenaiForgeUsage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
}

function usageJson(u: OpenaiForgeUsage): { prompt_tokens: number; completion_tokens: number; total_tokens: number } {
return { prompt_tokens: u.inputTokens, completion_tokens: u.outputTokens, total_tokens: u.totalTokens };
}

export function buildOpenaiCompactForgeBody(
summaryText: string,
model: string,
usage: OpenaiForgeUsage,
stream: boolean,
): { body: string; contentType: string } {
const id = `${OPENAI_COMPACT_ID_PREFIX}${randomUUID()}`;
const created = Math.floor(Date.now() / 1000);
if (!stream) {
const body = JSON.stringify({
id,
object: "chat.completion",
created,
model,
choices: [{ index: 0, message: { role: "assistant", content: summaryText }, finish_reason: "stop" }],
usage: usageJson(usage),
});
return { body, contentType: "application/json" };
}
const frame = (obj: unknown) => `data: ${JSON.stringify(obj)}\n\n`;
const base = { id, object: "chat.completion.chunk" as const, created, model };
let body = "";
body += frame({ ...base, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] });
body += frame({ ...base, choices: [{ index: 0, delta: { content: summaryText }, finish_reason: null }] });
body += frame({ ...base, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: "stop" }], usage: usageJson(usage) });
body += "data: [DONE]\n\n";
return { body, contentType: "text/event-stream" };
}
Loading
Loading