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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,7 @@ Security boundary: the file controls ONLY *when* to upgrade and *which published
- **Type:** `{ dumpBody?: boolean; dumpReq?: boolean; rawDumpDir?: string; dump4xx?: boolean; dump4xxMaxBytes?: number; maxTotalBytes?: number; maxAgeDays?: number; renderNone?: boolean; noInjectTool?: boolean; noCompressPrompt?: boolean; countTokensPassthrough?: boolean; compressProtocol?: "tools" | "text" }`
- **Default:** `{ dumpBody: false, dumpReq: true, rawDumpDir: <state dir>/raw, dump4xx: false, dump4xxMaxBytes: 2097152, maxTotalBytes: null, maxAgeDays: null, renderNone: false, noInjectTool: false, noCompressPrompt: false, countTokensPassthrough: false, compressProtocol: "tools" }`
- **Status:** ACTIVE
- **Description:** Debug/diagnostic toggles that used to be env-only (`ACP_DUMP_BODY`, `ACP_DUMP_REQ`, `ACP_RAW_DUMP_DIR`, `BILI_DUMP_4XX`, `BILI_DUMP_4XX_MAX_BYTES`, `ACP_RENDER_NONE`, `ACP_NO_INJECT_TOOL`, `ACP_NO_COMPRESS_PROMPT`, `ACP_COUNT_TOKENS_PASSTHROUGH`, `ACP_COMPRESS_PROTOCOL`). Mostly read live per request (no restart needed), except `compressProtocol` which resolves once at boot like the env var did. `renderNone` stops the `mNNNNN` render tags from being injected into outgoing history — disable only if your workflow doesn't need ref-based compression (#933). Retention bounds (#2412): dump dirs are write-only with no rotation by default — active body/SSE capture measured at ~63 GB/day can fill a disk in days. Set `maxTotalBytes` and/or `maxAgeDays` to bound them (oldest-first deletion, `err-*`/`summary-err-*` incident dumps protected, deletions logged at warn level); leave both unset for unbounded retention. Details in the [env table](#config-file-keys-for-environment-knobs-2030).
- **Description:** Debug/diagnostic toggles that used to be env-only (`ACP_DUMP_BODY`, `ACP_DUMP_REQ`, `ACP_RAW_DUMP_DIR`, `BILI_DUMP_4XX`, `BILI_DUMP_4XX_MAX_BYTES`, `ACP_RENDER_NONE`, `ACP_NO_INJECT_TOOL`, `ACP_NO_COMPRESS_PROMPT`, `ACP_COUNT_TOKENS_PASSTHROUGH`, `ACP_COMPRESS_PROTOCOL`). Mostly read live per request (no restart needed), except `compressProtocol` which resolves once at boot like the env var did. `renderNone` stops the `mNNNNN` render tags from being injected into outgoing history — disable only if your workflow doesn't need ref-based compression (#933). Retention bounds (#2412): dump dirs are write-only with no rotation by default — active body/SSE capture measured at ~63 GB/day can fill a disk in days. Set `maxTotalBytes` and/or `maxAgeDays` to bound them (oldest-first deletion, `err-*`/`summary-err-*` incident dumps protected, deletions logged at warn level); leave both unset for unbounded retention. Visibility (#3851): when any capture channel is on with neither bound set, bili logs a one-time WARN at startup naming each dump dir and its current size, and `bili doctor` lists every dump dir with its size and the retention state (`UNBOUNDED` marker). Details in the [env table](#config-file-keys-for-environment-knobs-2030).

### `fakeCompletion`

Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,7 @@
- **类型:** `{ dumpBody?: boolean; dumpReq?: boolean; rawDumpDir?: string; dump4xx?: boolean; dump4xxMaxBytes?: number; maxTotalBytes?: number; maxAgeDays?: number; renderNone?: boolean; noInjectTool?: boolean; noCompressPrompt?: boolean; countTokensPassthrough?: boolean; compressProtocol?: "tools" | "text" }`
- **默认:** `{ dumpBody: false, dumpReq: true, rawDumpDir: <state dir>/raw, dump4xx: false, dump4xxMaxBytes: 2097152, maxTotalBytes: null, maxAgeDays: null, renderNone: false, noInjectTool: false, noCompressPrompt: false, countTokensPassthrough: false, compressProtocol: "tools" }`
- **状态:** ACTIVE
- **说明:** 此前仅有环境变量形态的调试/诊断开关(`ACP_DUMP_BODY`、`ACP_DUMP_REQ`、`ACP_RAW_DUMP_DIR`、`BILI_DUMP_4XX`、`BILI_DUMP_4XX_MAX_BYTES`、`ACP_RENDER_NONE`、`ACP_NO_INJECT_TOOL`、`ACP_NO_COMPRESS_PROMPT`、`ACP_COUNT_TOKENS_PASSTHROUGH`、`ACP_COMPRESS_PROTOCOL`)。除 `compressProtocol` 在启动时一次性解析(同旧环境变量行为)外,其余均按请求实时读取,无需重启。`renderNone` 停止向外发历史注入 `mNNNNN` 渲染标签 —— 仅当你的工作流不需要基于 ref 的压缩时才关闭(#933)。保留期限约束(#2412):转储目录只写不删、默认无轮转 —— 实测持续开启 body/SSE 捕获约 63 GB/天,数天内即可写满磁盘。设置 `maxTotalBytes` 和/或 `maxAgeDays` 可为其设限(最旧优先删除,`err-*`/`summary-err-*` 事故证据文件受保护不删,删除动作以 warn 级别记录日志);两者都不设置则保持无限期保留。详见[环境变量表](#环境变量的配置键对照-2030)。
- **说明:** 此前仅有环境变量形态的调试/诊断开关(`ACP_DUMP_BODY`、`ACP_DUMP_REQ`、`ACP_RAW_DUMP_DIR`、`BILI_DUMP_4XX`、`BILI_DUMP_4XX_MAX_BYTES`、`ACP_RENDER_NONE`、`ACP_NO_INJECT_TOOL`、`ACP_NO_COMPRESS_PROMPT`、`ACP_COUNT_TOKENS_PASSTHROUGH`、`ACP_COMPRESS_PROTOCOL`)。除 `compressProtocol` 在启动时一次性解析(同旧环境变量行为)外,其余均按请求实时读取,无需重启。`renderNone` 停止向外发历史注入 `mNNNNN` 渲染标签 —— 仅当你的工作流不需要基于 ref 的压缩时才关闭(#933)。保留期限约束(#2412):转储目录只写不删、默认无轮转 —— 实测持续开启 body/SSE 捕获约 63 GB/天,数天内即可写满磁盘。设置 `maxTotalBytes` 和/或 `maxAgeDays` 可为其设限(最旧优先删除,`err-*`/`summary-err-*` 事故证据文件受保护不删,删除动作以 warn 级别记录日志);两者都不设置则保持无限期保留。可见性(#3851):任一捕获通道开启且两个上限都未设置时,bili 启动时会打一条一次性 WARN,列出各转储目录路径与当前大小;`bili doctor` 也会列出每个转储目录的大小与保留状态(`UNBOUNDED` 标记)。详见[环境变量表](#环境变量的配置键对照-2030)。

### `fakeCompletion`

Expand Down
30 changes: 28 additions & 2 deletions src/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import { isPidAlive, listInstances, procMainScript } from "./instance.js";
import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresence, type PluginAgent } from "./plugin-install.js";
import { findInstallDir, fetchRegistryVersion, hostManagedInstall, isGitWorkingTree, isVersionNewer, lastUpdateCheckTime, normalizeUpdateTag, staleInstallStatus } from "./update.js";
import { describeAdvisory, evaluateAdvisories, type AdvisoryEvaluation } from "./advisory.js";
import { claudeRoutingWarningFile } from "./paths.js";
import { claudeRoutingWarningFile, dumpsDir } from "./paths.js";
import { rawDumpDir, sseDumpDir } from "./knobs.js";
import { dumpRetentionState, fmtBytes, measureDumpDir, type DumpDirStat, type DumpRetentionState } from "./state-gc.js";
import { dshProfileDirs } from "./dsh-channel.js";
import { convergeDshLedger, dshProfileLedgerFindings, readDshLedgerState, type LedgerChangeDetail, type LedgerFinding } from "./dsh-ledger.js";

Expand Down Expand Up @@ -77,6 +79,9 @@ export interface DoctorReport {
global: DoctorGlobalInfo;
lanes: DoctorLane[];
processes: DoctorProcess[];
/** #3851: debug dump dirs — current size + retention bounds. Always present
* so data left behind by a since-disabled capture stays visible. */
dumps: { retention: DumpRetentionState; dirs: DumpDirStat[] };
/** #3496: set only when `--fix` ran — what the repair pass changed per profile. */
ledgerFixes?: DshLedgerFixRow[];
}
Expand Down Expand Up @@ -210,7 +215,14 @@ export async function runDoctor(opts: DoctorOpts): Promise<DoctorReport> {
};
});

return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes };
// #3851: dump-dir visibility. Measure every dir the current config can write
// PLUS the default dirs, so leftover data from a since-disabled capture still
// shows up (the 51.9 GB case: capture stayed on, but the same applies in reverse).
const retention = dumpRetentionState();
const dumpCandidates = [dumpsDir(), rawDumpDir(), sseDumpDir()].filter((d): d is string => d !== undefined);
const dumpDirs = await Promise.all([...new Set(dumpCandidates)].map(measureDumpDir));

return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes, dumps: { retention, dirs: dumpDirs } };
}

/** #3496: the explicit repair pass behind `bili doctor --fix`. Converges every
Expand Down Expand Up @@ -361,6 +373,20 @@ export function renderDoctorReport(report: DoctorReport): string {
if (p.runningFrom !== undefined) lines.push(` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`);
}
}
lines.push("");
lines.push("dump dirs");
const ret = report.dumps.retention;
const capParts = [
ret.maxTotalBytes != null ? `maxTotalBytes=${fmtBytes(ret.maxTotalBytes)}` : "",
ret.maxAgeDays != null ? `maxAgeDays=${Number.isInteger(ret.maxAgeDays) ? String(ret.maxAgeDays) : ret.maxAgeDays.toFixed(1)}` : "",
].filter(Boolean).join(", ");
if (ret.channels.length === 0) lines.push(` retention off (no capture enabled)`);
else if (ret.unbounded) lines.push(` retention UNBOUNDED — capture on (${ret.channels.join("+")}) with no maxTotalBytes/maxAgeDays set: dirs grow forever until the disk fills (#3851)`);
else lines.push(` retention bounded — capture on (${ret.channels.join("+")}): ${capParts}`);
for (const d of report.dumps.dirs) {
const size = d.exists ? `${fmtBytes(d.bytes)} (${d.files.toLocaleString("en-US")} ${d.files === 1 ? "file" : "files"})` : "(absent)";
lines.push(` ${path.basename(d.dir).padEnd(16)} ${size.padEnd(24)} ${d.dir}`);
}
const counts: Record<LaneVerdict, number> = { ok: 0, stale: 0, frozen: 0, broken: 0, absent: 0 };
for (const l of report.lanes) counts[l.verdict]++;
const zombies = report.processes.filter((p) => !p.alive).length;
Expand Down
10 changes: 10 additions & 0 deletions src/knobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,16 @@ export function rawDumpDir(): string {
return path.join(stateDir(), "raw");
}

/** ACP_DUMP_SSE > top-level dumpSse > off (undefined). Directory for raw SSE
* stream captures; part of the #3851 retention-audit surface. */
export function sseDumpDir(): string | undefined {
const envRaw = process.env.ACP_DUMP_SSE;
if (envRaw && envRaw.length > 0) return envRaw;
const f = loadConfigFile().dumpSse;
if (typeof f === "string" && f.trim().length > 0) return f;
return undefined;
}

/** BILI_DUMP_4XX > diagnostics.dump4xx > false. */
export function dump4xxEnabled(): boolean {
const envRaw = process.env.BILI_DUMP_4XX;
Expand Down
16 changes: 16 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import { buildSessionCacheReport, handleAcpCache, learnedImageReserve, noteClien
import { extractBillingAttributionBlock, extractSummaryFromSse, preflightCompress, estimateCoreMessages, estimateCoreMessagesUpper, estimateCoreMessagesUpperBytes, estimateRawBodyTokens, type PreflightResult } from "./preflight.js";
import { buildDecisionPrompt, buildDirectiveText, consumeFallback, DEFAULT_DECIDE_MAX_TOKENS, DECIDE_TIMEOUT_MS, extractDecisionText, ladderMode, parseDecision, recordDecision, resolveDecisionRange, type DecideConfig, type DecisionOutcome } from "./nudge-decide.js";
import { gcConfigFromEnv, gcSessionFiles } from "./session-gc.js";
import { activeDumpDirs, dumpRetentionState, formatUnboundedDumpWarning, measureDumpDir, type DumpDirStat } from "./state-gc.js";
import { countImagesInParsedBody, countImagesInRawBody, imageTokensInRawBody, imageTokensInParsedBody, resolveImageBilling, upstreamHost, type ResolvedImageBilling } from "./image-tokens.js";
import { APIG_RESIGN_HEADER, APIG_RESIGN_CREDENTIAL_HEADER, APIG_RESIGN_SCHEME, KNOWN_SIGNATURE_SCHEMES, clearSignedRefusal, decodeApigCredential, inboundSignedScheme, readPendingRefusals, recordSignedRefusal, resignApig, signedRefusal, unresolvedRefusals, type ApigCredential } from "./apig-resign.js";
import { renderUI, handleConfigGet, handleConfigPut, handleSummaryCredentialPut, buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, hiddenEmptyCount } from "./web/index.js";
Expand Down Expand Up @@ -1231,6 +1232,21 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
`[security] bound to ${opts.host} — proxy endpoints (/bili/, CONNECT for whitelisted model hosts) are reachable from the network with NO authentication; /__bili/ management endpoints stay loopback-only. Restrict access with a firewall on untrusted networks. Remote agents: point baseURL at http://<this-host>:${actualPort}/bili/`,
);
}
// #3851: capture without retention bounds grows silently until the disk
// fills — say so once per boot. Async: measuring a large dir must not
// delay ready, and the warn still fires when the scan itself fails.
const dumpRet = dumpRetentionState();
if (dumpRet.unbounded) {
void (async (): Promise<void> => {
let stats: DumpDirStat[] = [];
try {
stats = await Promise.all(activeDumpDirs().map(measureDumpDir));
} catch {
// measurement failed — warn anyway, sizes omitted
}
log("warn", formatUnboundedDumpWarning(dumpRet, stats));
})();
}
if (opts.debug) {
log("info", `[debug] build features: raw-HTTP-capture(${bodyDumpEnabled() ? "on" : "off"}) | remote_compaction_v2-strip(on) | cert-MITM-launcher(on) | strip-acp-summary(on) — seeing this line confirms the launcher build (not registry 0.1.34)`);
}
Expand Down
100 changes: 99 additions & 1 deletion src/state-gc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { readdirSync, statSync, unlinkSync } from "node:fs";
import { readdir, stat } from "node:fs/promises";
import path from "node:path";
import { log as loggerLog } from "./logger.js";
import { dumpGcMaxTotalBytes, dumpGcMaxAgeMs } from "./knobs.js";
import { bodyDumpEnabled, dump4xxEnabled, dumpGcMaxAgeMs, dumpGcMaxTotalBytes, rawDumpDir, sseDumpDir } from "./knobs.js";
import { configFile, dumpsDir } from "./paths.js";

/**
* #2412: retention GC for the debug dump directories (`dumps/`, `raw/`, the
Expand Down Expand Up @@ -127,3 +129,99 @@ export function gcDumpDirIfConfigured(dir: string): void {
if (maxBytes == null && maxAgeMs == null) return;
gcDebugDir(dir, { maxBytes, maxAgeMs });
}

// --- #3851: retention visibility -------------------------------------------------
// The bounds above are opt-in and default OFF by design ("leave both unset for
// unbounded retention", CONFIGURATION.md). The gap #3851 reports: once capture
// is turned on per the docs, nothing says the dirs are unbounded or how big they
// already are — 51.9 GB over 10 days before anyone noticed. This block is that
// signpost: read-only measurement + message building only. No new config keys,
// no deletion, no change to any write path.

export interface DumpDirStat {
dir: string;
exists: boolean;
bytes: number;
files: number;
}

export interface DumpRetentionState {
/** Capture channels writing dumps right now: "body" (dumps/ + raw/),
* "4xx" (err-* incident dumps in dumps/), "sse" (raw SSE stream dir). */
channels: string[];
maxTotalBytes: number | null;
maxAgeDays: number | null;
/** Capture on with NEITHER bound set — dirs grow forever. */
unbounded: boolean;
}

/** Live retention posture for the debug dump dirs. Resolves the same knobs as
* the GC itself (env > file > default-off), so what is reported is what runs. */
export function dumpRetentionState(): DumpRetentionState {
const channels: string[] = [];
if (bodyDumpEnabled()) channels.push("body");
if (dump4xxEnabled()) channels.push("4xx");
if (sseDumpDir() !== undefined) channels.push("sse");
const maxBytes = dumpGcMaxTotalBytes();
const maxAgeMs = dumpGcMaxAgeMs();
return {
channels,
maxTotalBytes: maxBytes,
maxAgeDays: maxAgeMs == null ? null : maxAgeMs / 86_400_000,
unbounded: channels.length > 0 && maxBytes == null && maxAgeMs == null,
};
}

/** Every dump dir the current config can write (deduped — a custom rawDumpDir
* may coincide with dumpsDir). Order: dumps/, raw/, SSE dir. */
export function activeDumpDirs(): string[] {
const st = dumpRetentionState();
const dirs: string[] = [];
if (st.channels.includes("body") || st.channels.includes("4xx")) dirs.push(dumpsDir());
if (st.channels.includes("body")) dirs.push(rawDumpDir());
if (st.channels.includes("sse")) dirs.push(sseDumpDir()!);
return [...new Set(dirs)];
}

/** Total size + file count of one dump dir. Best-effort: a missing/unreadable
* dir reports exists:false instead of throwing. Flat-file assumption matches
* gcDebugDir — all bili dump dirs are flat. */
export async function measureDumpDir(dir: string): Promise<DumpDirStat> {
let names: string[];
try {
names = await readdir(dir);
} catch {
return { dir, exists: false, bytes: 0, files: 0 };
}
let bytes = 0;
let files = 0;
for (const name of names) {
try {
const st = await stat(path.join(dir, name));
if (st.isFile()) {
bytes += st.size;
files += 1;
}
} catch {
// vanished between readdir and stat
}
}
return { dir, exists: true, bytes, files };
}

/** Human-readable byte count for logs/doctor (binary units, one decimal). */
export function fmtBytes(n: number): string {
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(1)} GiB`;
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
if (n >= 1024) return `${(n / 1024).toFixed(1)} KiB`;
return `${n} B`;
}

/** One-shot boot warning text (#3851). Pure builder so the exact wording is
* unit-tested; empty `stats` = measurement failed, sizes omitted. */
export function formatUnboundedDumpWarning(state: DumpRetentionState, stats: DumpDirStat[]): string {
const sizes = stats.length === 0
? "size measurement unavailable"
: stats.map((s) => `${s.dir}=${s.exists ? `${fmtBytes(s.bytes)} (${s.files} file${s.files === 1 ? "" : "s"})` : "(not created yet)"}`).join(", ");
return `[dump] UNBOUNDED retention: capture is ON (${state.channels.join("+")}) but diagnostics.maxTotalBytes and diagnostics.maxAgeDays are both unset — these dirs are write-only and grow forever (~GB/day measured under active sessions, #2412). Current: ${sizes}. Set diagnostics.maxTotalBytes (total bytes) and/or diagnostics.maxAgeDays in ${configFile()} to bound them, or turn capture off (diagnostics.dumpBody=false) when you no longer need it.`;
}
1 change: 1 addition & 0 deletions tests/doctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ function syntheticReport(overrides?: { lanes?: DoctorLane[]; processes?: DoctorP
global: { installDir: "/x/node_modules/billion-context", form: "npm", diskVersion: "0.1.143", runningVersion: "0.1.143", registryVersion: "0.1.143", updateTag: "latest", lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), verdict: "ok" },
lanes: overrides?.lanes ?? [],
processes: overrides?.processes ?? [],
dumps: { retention: { channels: [], maxTotalBytes: null, maxAgeDays: null, unbounded: false }, dirs: [] },
};
}

Expand Down
Loading
Loading