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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag
- **`bili kiro`:Kiro CLI(AWS)启动器车道 / launcher lane for Kiro CLI.** Kiro 的模型调用是 `runtime.<region>.kiro.dev/v1/responses` 上的 Responses wire,每轮重放完整历史、bearer 鉴权、遵守 `HTTPS_PROXY`——现有 responses 管线即可压缩,只需处理两处网关差异:①网关只收 `user`/`assistant` 项,注入的 `developer` 压缩提示会被 400(`param: input[0]`)拒绝 → 对 Kiro 流量内置 `developer`/`system`→`user` 角色映射(最低优先级,`compat.roles` 与学到的角色仍按键覆盖;判官按原角色看待注入提示,不误报 I1);②Kiro 首项跨进程不字节稳定,`--resume` 会新建会话 → 提升 `metadata["kiro:conversation_id"]` 为会话 id(`kiro-<id>`,只覆盖内容指纹)。车道只 MITM 四个 `runtime.*.kiro.dev` 网关,合并 CA 同时写 `SSL_CERT_FILE`(Rust 外壳)与 `NODE_EXTRA_CA_CERTS`(Node 代理服务),回环走 `NO_PROXY`。实测(kiro-cli 2.37,真实账号):0 次 400,14 次独立启动(13 次 --resume)始终同一会话,折叠 16.4K token 后口令仍可召回,判官 clean fold verdict。新文件 `src/kiro.ts`,测试 `tests/kiro.test.ts` + `tests/launcher.test.ts`(runLaunch kiro);文档 CLIENTS.md / CLIENTS.zh-CN.md「Kiro CLI(AWS)」节、README 表格与启动器列表。
- **消息时间戳渲染默认开启(#4313 后续)**:此前 `compress.messageTimestamps` 为可选特性(默认关,线上字节与特性前逐字节一致)。生产会话的缓存审计(同会话开关前后命中率均 95.0%、无一条时间戳导致的前缀重写 miss、全部异常可归因上游 TTL 驱逐)证实存戳渲染跨轮逐字节稳定,故默认翻转为**开**:`time=` 压缩标签属性、回执指纹行 `[起 – 止]` 覆盖跨度、摘要 Occurred 行对所有人默认可见(每条消息首次出现时铸一次不可变墙钟戳,渲染只读存戳不读墙钟)。关闭方式不变:文件 `compress.messageTimestamps: false` 或 `BILI_MESSAGE_TIMESTAMPS=0`,关闭后每个出站字节与 pre-#4313 master 一致。升级用户的一次性代价:标志首次解析为开的那个重启后,每个活跃会话付一次冻结前缀缓存重写(旧消息补上 time= 属性 + 提示词变体切换),之后稳定。测试基线:tests/preload-test-env.mjs 整套件 pin 显示门控关,字节对比型金标保持特性前形态;issue4313 toggle 套件按新契约翻转并新增 message-timestamps-default-on.test.ts 钉住生产默认路径。


### Storage — bun 运行时原生支持(`bun:sqlite`)

- **在 bun 上跑 bili 不再退回 legacy**:引擎阶梯加了第 0 步 `bun:sqlite`(src/storage/driver.ts,只有 `process.versions.bun` 存在时才 require —— bun 里 `node:sqlite` 根本不存在,而 better-sqlite3 的 N-API 预编译在 bun 下必定 "Could not load the default exports from better-sqlite3",阶梯三步全落空只会得到 legacy-only)。bun 内置引擎与 better-sqlite3 同形(`Database`、同步 `run/get/all`、`.transaction()`),适配层只补三处实测差异:命名参数按 SQL 里书写的记号绑定(`:a`/`@b`/`$c`,而库内 SQL 是 better-sqlite3 风格、传裸键 `{ a: 1 }`)——按语句把裸键复制成该语句真正用到的记号形态(字面量先抹平,故字符串里的 `:name` 不会被误认);BLOB 列回裸 `Uint8Array` → 归一成 Buffer(媒体/载荷读取端按 Buffer 契约写);`run()` 的 `changes`/`lastInsertRowid` 是 BigInt → 收成 number,并补 bun 没有的 `.open` 旗标。写事务走 `.immediate()`、只读走 `.deferred()`(#2690 的写锁拓扑:延迟事务中途升级为写锁会撞 busy_timeout 救不回的 SQLITE_BUSY_SNAPSHOT),`close()` 幂等。
- **自举与状态文案不再指错运行时**:bun 上自举直接 `not-needed`(给 bun 下载 N-API 预编译纯属浪费带宽且必加载失败);`nodeSqliteUpgradeHint` 与降级横幅在 bun 上讲 `bun:sqlite`,不再让运维去升 Node;整史后台完整性 worker 是自包含源串、不复用阶梯,也按 `process.versions.bun` 选引擎(bun 的只读选项名是 `readonly`,不是 Node 的 `readOnly`)。
- **测试钉住契约**:tests/storage-bun-sqlite.test.ts —— 假 Database 那几组经测试缝 `setBunDatabaseFactoryForTests` 在 Node CI 上同样可跑(记号双写、字面量外只重写一次、BigInt/Uint8Array/null 归一、事务必须 `.immediate()`、阶梯第 0 步优先、被钉的 `{builtin, host}` 探针袋视为 Node 主机);真内置那几组仅在 bun 下跑(真 BEGIN 与回滚、嵌套事务不提前提交、写完锁立刻交还,以及真 UnifiedStore 端到端:开库跑 PRAGMA 阶梯 + quick_check + 迁移、命名参数插入、读回、close 触发 WAL checkpoint 后重开仍在)。
- **既有存储套件在 bun 下实测**:7 处写死 `openSqliteDatabase(path, "node:sqlite")` 的裸句柄改为随动自动探测后,block-bounds 1/0、fork-clone-media 3/0、issue4982 18/0、unified-remap 3/0 全绿;storage-unified 从 4 通过/13 失败变成 14 通过/4 跳过/0 失败(三条只驱动 `node:sqlite` 的 leg 现按驱动探针跳过);storage-ingest-watermark 15/1、bounded-load 4/1、engine-proofs 7/5、plugin-fork 51/5、engine-bootstrap 维持 43/1。与改动前同机基线相比:多通过 24 条,零回归。剩余失败与存储引擎无关:bun 的 node:test 垫片没有 `t.mock`(oven-sh/bun#5090)、Node 专用套件顶层静态 `import("node:sqlite")`、以及子进程 harness 在 bun 下的 ERR_SERVER_NOT_RUNNING。

### #5079 — `prompt_cache_key` 自注入默认关闭,`promptCache.routing` 一个开关管住两条 wire

- **行为变更(旧→新)**:此前 bili 在插件车道对一切目的地默认给请求体盖 `prompt_cache_key=<会话 id>`(#2218/#2649 定案,Responses wire 仅对 `api.openai.com` 注入)。由于大量服务见到该字段会直接拒绝、且这类服务无法枚举,**默认反转为关闭**:`promptCache.routing` 缺省值从 `"auto"` 变为 `"disabled"`(无法识别的值同样落到 `"disabled"`)。客户端自带的 key 不受影响:任何模式下都原样转发(A/B 探测记忆对已证实拒收的 origin+model 组合照常撤键)。
Expand Down
190 changes: 183 additions & 7 deletions src/storage/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@
* Minimal SQLite driver seam for the unified storage layer (#2671).
*
* Engine resolution order (#2833, owner-approved 2026-10-12):
* 0. bun builtin — bun:sqlite (bun's own built-in synchronous SQLite). Only
* ever available when the host runtime IS bun, where
* node:sqlite does NOT exist; without this step a bun-run
* bili falls through to the N-API better-sqlite3 path, whose
* prebuilt binding cannot be loaded by bun ("Could not load
* the default exports from better-sqlite3"), so the unified
* store cannot open at all. Same zero-native-dependency
* invariant as step 1.
* 1. builtin — node:sqlite (DatabaseSync; unflagged on recent Node 22.x,
* stable lineage since Node 23.4). Zero native dependency,
* zero build scripts — preferred wherever it exists.
Expand Down Expand Up @@ -74,7 +82,22 @@ import { createRequire } from "node:module";

const require = createRequire(import.meta.url);

export type SqliteEngineName = "better-sqlite3" | "node:sqlite";
// Specifier through a constant: `bun:sqlite` is bun's own builtin and is NOT in
// module.builtinModules, so a quoted-literal require reads as an external npm
// package to scripts/check-dist-external.mjs (the same indirection that
// SQLITE_SPEC in src/storage/integrity-check.ts uses for node:sqlite). It is
// required lazily, and only when isBunRuntime() says this process IS bun, so a
// thin Node install never evaluates it.
const BUN_SQLITE_SPEC = "bun:sqlite";

export type SqliteEngineName = "better-sqlite3" | "node:sqlite" | "bun:sqlite";

/** True when the host runtime is bun (aliased `node` installs included). bun
* implements `bun:sqlite` and NOT `node:sqlite`, so the ladder must tell them
* apart; on real Node this is false and the ladder below is unchanged. */
export function isBunRuntime(): boolean {
return typeof process !== "undefined" && process.versions?.bun !== undefined;
}

interface OpenedDatabase {
readonly db: SqliteDatabase;
Expand Down Expand Up @@ -210,21 +233,166 @@ function adaptNodeSqliteStatement(stmt: NodeSqliteStatement): SqliteStatement {
};
}

interface BunSqliteStatement {
run(...args: unknown[]): { changes?: number | bigint; lastInsertRowid?: number | bigint } | undefined;
get(...args: unknown[]): unknown;
all(...args: unknown[]): unknown[];
}

export interface BunSqliteDatabase {
exec(sql: string): unknown;
prepare(sql: string): BunSqliteStatement;
/** bun mirrors better-sqlite3's shape: wraps fn and returns the callable
* wrapper with immediate/deferred/exclusive lock-mode variants attached. */
transaction<T>(fn: () => T): (() => T) & { immediate(): T; deferred(): T; exclusive(): T };
close(): void;
}

type BunSqliteCtor = new (path: string) => BunSqliteDatabase;

let bunDatabaseFactoryForTests: ((path: string) => BunSqliteDatabase) | null = null;

/** Test seam: substitute how the bun:sqlite emulation obtains its database
* handle, so the bun adapter can be pinned on a Node CI runner where
* `bun:sqlite` cannot load. Null = the real builtin bun:sqlite module. */
export function setBunDatabaseFactoryForTests(factory: ((path: string) => BunSqliteDatabase) | null): void {
bunDatabaseFactoryForTests = factory;
}

/** bun binds named parameters by the exact sigil written in the SQL (`:a`, `@a`,
* `$a`), while the store's SQL is better-sqlite3 style and passes plain
* `{ name: value }` objects. Collect the sigil forms a statement actually uses
* (literals blanked first) so the adapter can offer bun both spellings. */
type BunNamedParamForms = Map<string, string[]>;

function bunNamedParamForms(sql: string): BunNamedParamForms | undefined {
const forms: BunNamedParamForms = new Map();
for (const m of sql.replace(/'[^']*'/g, "''").matchAll(/(?:^|[^:@$])([:@$])([A-Za-z_][A-Za-z0-9_]*)/g)) {
const bare = m[2];
const full = m[1] + bare;
const list = forms.get(bare) ?? [];
if (!list.includes(full)) list.push(full);
forms.set(bare, list);
}
return forms.size > 0 ? forms : undefined;
}

/** Duplicate each named key into the sigil form(s) the statement uses, keeping
* the bare key too (bun accepts it). A positional / array / binary / Date first
* argument is not a named-parameter bag and passes through untouched. */
function bunParamArgs(args: unknown[], forms: BunNamedParamForms | undefined): unknown[] {
if (forms === undefined || args.length === 0) return args;
const first = args[0];
if (first === null || typeof first !== "object" || Array.isArray(first) || ArrayBuffer.isView(first) || first instanceof Date) return args;
const src = first as Record<string, unknown>;
const out = Object.assign({}, src) as Record<string, unknown>;
for (const key of Object.keys(src)) {
for (const form of forms.get(key) ?? []) out[form] = src[key];
}
return [out, ...args.slice(1)];
}

/** bun hands back a bare `Uint8Array` for BLOB columns where better-sqlite3 and
* node:sqlite hand back a Buffer; the store's media/payload readers expect a
* Buffer, so normalize on the way out. `null` rows collapse to `undefined`,
* matching the node:sqlite adapter's no-row contract. */
function bunRow(row: unknown): unknown {
if (row === null) return undefined;
if (row === undefined || typeof row !== "object") return row;
const src = row as Record<string, unknown>;
let mapped: Record<string, unknown> | undefined;
for (const key of Object.keys(src)) {
const v = src[key];
if (v instanceof Uint8Array && !Buffer.isBuffer(v)) {
if (mapped === undefined) mapped = Object.assign({}, src);
mapped[key] = Buffer.from(v);
}
}
return mapped ?? row;
}

function adaptBunSqliteStatement(stmt: BunSqliteStatement, forms: BunNamedParamForms | undefined): SqliteStatement {
return {
run: (...args: unknown[]) => {
const res = stmt.run(...bunParamArgs(args, forms));
return {
changes: Number(res?.changes ?? 0),
lastInsertRowid: Number(res?.lastInsertRowid ?? 0),
};
},
get: (...args: unknown[]) => bunRow(stmt.get(...bunParamArgs(args, forms))),
all: (...args: unknown[]) => stmt.all(...bunParamArgs(args, forms)).map((row) => bunRow(row)),
};
}

function openBunSqlite(path: string): SqliteDatabase {
// bun:sqlite is synchronous like better-sqlite3, and already carries a
// .transaction() helper — only the parameter spelling, the BLOB type and
// the missing `.open` flag differ from what the store expects.
const db = bunDatabaseFactoryForTests
? bunDatabaseFactoryForTests(path)
: (() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { Database } = require(BUN_SQLITE_SPEC) as { Database: BunSqliteCtor };
return new Database(path);
})();
let closed = false;
const mode = <T>(fn: () => T, variant: "immediate" | "deferred"): T => {
const t = db.transaction(fn);
// BEGIN IMMEDIATE for writes, deferred for reads — the same #2690
// reasoning as wrapBetterSqlite3: a deferred read-then-write
// transaction upgrades mid-flight to a write lock (SQLITE_BUSY_SNAPSHOT,
// which busy_timeout cannot resolve), so writers take the lock up front.
return t[variant] ? t[variant]() : t();
};
return {
exec: (sql) => void db.exec(sql),
prepare: (sql) => adaptBunSqliteStatement(db.prepare(sql), bunNamedParamForms(sql)),
transaction: (fn) => mode(fn, "immediate"),
readTransaction: (fn) => mode(fn, "deferred"),
close: () => {
if (closed) return;
closed = true;
db.close();
},
get open() {
return !closed;
},
};
}

export type SqliteEngineSource = "builtin" | "host" | "self-downloaded";

interface ResolvedEngine {
readonly name: SqliteEngineName;
readonly source: SqliteEngineSource;
}

let probeOverridesForTests: { builtin?: boolean; host?: boolean } | null = null;
let probeOverridesForTests: { bun?: boolean; builtin?: boolean; host?: boolean } | null = null;

/** Test seam: override engine availability probes (null = real probes). Lets
* resolution-order tests run deterministically on any CI Node version. */
export function setSqliteProbeOverridesForTests(o: { builtin?: boolean; host?: boolean } | null): void {
* resolution-order tests run deterministically on any CI Node version. A bag
* that names only `builtin`/`host` simulates a NODE host: bun stays off unless
* the caller opts in with `bun: true`, so the #2833 ladder remains testable on
* a machine whose runtime happens to be bun (where `node` is aliased to bun). */
export function setSqliteProbeOverridesForTests(o: { bun?: boolean; builtin?: boolean; host?: boolean } | null): void {
probeOverridesForTests = o;
}

/** bun:sqlite presence probe: bun's builtin synchronous SQLite. False on real
* Node (there is no `bun:sqlite` module to require) and false whenever a test
* pins a Node-host bag, so the #2833 ladder below stays authoritative there. */
export function probeBunSqlite(): boolean {
if (probeOverridesForTests?.bun !== undefined) return probeOverridesForTests.bun;
if (probeOverridesForTests) return false; // a pinned bag = simulated Node host
if (!isBunRuntime()) return false;
try {
return (require(BUN_SQLITE_SPEC) as { Database?: unknown }).Database !== undefined;
} catch {
return false;
}
}

/** node:sqlite presence probe (#2833 step 1). Absent on Node <= 21 and early
* 22.x minors that still gate it behind --experimental-sqlite. */
export function probeBuiltinSqlite(): boolean {
Expand Down Expand Up @@ -275,7 +443,8 @@ export function resolvedSqliteEngineInfo(): ResolvedEngine | null {

function detectEngine(): ResolvedEngine {
if (cachedEngine) return cachedEngine;
if (probeBuiltinSqlite()) cachedEngine = { name: "node:sqlite", source: "builtin" };
if (probeBunSqlite()) cachedEngine = { name: "bun:sqlite", source: "builtin" };
else if (probeBuiltinSqlite()) cachedEngine = { name: "node:sqlite", source: "builtin" };
else if (probeHostBetterSqlite3()) cachedEngine = { name: "better-sqlite3", source: "host" };
else if (selfDownloadedLoader) cachedEngine = { name: "better-sqlite3", source: "self-downloaded" };
else throw new SqliteDriverError("no SQLite engine available", "node:sqlite");
Expand All @@ -284,7 +453,7 @@ function detectEngine(): ResolvedEngine {

/** Test seam: forces the engine for the next open (does not affect open handles). */
export function setPreferredSqliteEngineForTests(engine: SqliteEngineName | null): void {
cachedEngine = engine ? { name: engine, source: engine === "node:sqlite" ? "builtin" : "host" } : null;
cachedEngine = engine ? { name: engine, source: engine === "node:sqlite" || engine === "bun:sqlite" ? "builtin" : "host" } : null;
}

let enginesUnavailableForTests = false;
Expand All @@ -305,7 +474,14 @@ export function openSqliteDatabase(path: string, engine?: SqliteEngineName): Ope
if (enginesUnavailableForTests) {
throw new SqliteDriverError("no SQLite engine available", "node:sqlite");
}
const resolved = engine ? { name: engine, source: (engine === "node:sqlite" ? "builtin" : "host") as SqliteEngineSource } : detectEngine();
const resolved = engine ? { name: engine, source: (engine === "node:sqlite" || engine === "bun:sqlite" ? "builtin" : "host") as SqliteEngineSource } : detectEngine();
if (resolved.name === "bun:sqlite") {
try {
return { db: openBunSqlite(path), engine: resolved.name, source: resolved.source };
} catch (err) {
throw new SqliteDriverError(String(err), resolved.name);
}
}
if (resolved.name === "better-sqlite3") {
try {
const ctor = resolved.source === "self-downloaded" ? selfDownloadedLoader!() : loadHostBetterSqlite3();
Expand Down
Loading
Loading