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
20 changes: 19 additions & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1492,7 +1492,25 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t
- **Type:** `string` (pack name, e.g. `"lean"`)
- **Default:** `default` *(unset is equivalent — identity surface, kernel defaults everywhere)*
- **Status:** ACTIVE
- **Description:** Select a named prompt pack — a curated surface preset covering tool descriptions, compress system-prompt sections, and nudge sections — resolved from the host's pack chain: **project** `./.billion-context/packs/<name>.json` → **user** `<configDir>/packs/<name>.json` → **shipped** (`chat`) → **builtin** (`default`, `lean`). Built-in `lean` swaps the four ACP tool descriptions for one-liners (no snippet/guideline chrome) while keeping the compression rules default. Built-in `chat` (#5319) rewrites only the compress philosophy and how-to-compress prose for long-term companionship / multi-session memory use; every other surface piece stays at the host defaults, and a same-name user or project file overrides it. Unknown names fall back to the identity surface with a one-time warning. Same three-level merge as the other fields; pack-surface sections (tool/section overrides) apply directly, without the `acknowledgePromptsRisk` gate — that gate governs only inline `compress.prompts` rule-text overrides. Note a pack's `prompts` block is ignored by this proxy: rule-text overrides are possible only via inline `compress.prompts`. Requires `acp-kernel` >= 0.0.66.
- **Description:** Select a named prompt pack — a curated surface preset covering tool descriptions, compress system-prompt sections, and nudge sections — resolved from the host's pack chain: **project** `./.billion-context/packs/<name>.json` → **user** `<configDir>/packs/<name>.json` → **shipped** (`chat`) → **builtin** (`default`, `lean`). Built-in `lean` swaps the four ACP tool descriptions for one-liners (no snippet/guideline chrome) while keeping the compression rules default. Built-in `chat` (#5319) rewrites only the compress philosophy and how-to-compress prose for long-term companionship / multi-session memory use; every other surface piece stays at the host defaults, and a same-name user or project file overrides it. Unknown names fall back to the identity surface with a one-time warning. Same three-level merge as the other fields; pack-surface sections (tool/section overrides) apply directly, without the `acknowledgePromptsRisk` gate — that gate governs only inline `compress.prompts` rule-text overrides. Note a pack's `prompts` block is ignored by this proxy: rule-text overrides are possible only via inline `compress.prompts`. Requires `acp-kernel` >= 0.0.66. The settings panel can manage the user-dir files directly — New/Edit/Delete for packs under `<configDir>/packs/` (the picker knows each entry's provenance; builtins and shipped packs stay read-only there, override them with a same-named user pack instead).

**Pack file format.** Each `<dir>/<name>.json` holds one pack object. Unknown fields are dropped by the same sanitizer used on every load path (`sanitizePackSurface`), so extra metadata is harmless:

```json
{
"name": "my-pack", // optional — defaults to the file name without .json
"version": "1.0.0", // optional — shown by `bili pack list` and the panel
"description": "…", // optional
"promptSections": {
"philosophy": "…", // replace a whole system-prompt section; JSON null keeps the default
"howToCompress": "…" // start from the tuned texts in src/chat-pack.ts
}
}
```

Optional surface blocks: `prompts` (inline rule-text overrides), `nudgeSections`, `toolPrompts`, and `adapters` (host-specific extras, e.g. `"pi": { "promptSections": { … } }`). At least one recognized field must survive sanitizing or the file is refused when written.

**Installing other people's packs.** Any npm package whose root contains a `bili-pack.json` (the pack object above) is installable: `bili pack install <pkg>` — also accepts `name@version`, scoped names, git URLs and `.tgz` paths (it delegates to your local `npm`, so registry auth behaves normally). Files land in `<configDir>/packs/` by default (`--project` targets `./.billion-context/packs/`; `--force` replaces an existing pack instead of refusing). Afterwards manage them from the settings panel, or via `bili pack remove <name>` / `bili pack list`.

#### `reconcile`

Expand Down
20 changes: 19 additions & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1483,7 +1483,25 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报
- **类型:** `string`(包名,如 `"lean"`)
- **默认值:** `default`(未设置等同——恒等表面,全部使用内核默认值)
- **状态:** ACTIVE
- **说明:** 选择一个具名 prompt pack —— 一套策划好的表面预设,覆盖工具描述、压缩系统提示词段落、nudge 段落 —— 从宿主侧的包解析链解析:**项目** `./.billion-context/packs/<name>.json` → **用户** `<configDir>/packs/<name>.json` → **随包附带**(`chat`)→ **内核内置**(`default`、`lean`)。内置 `lean` 把四个 ACP 工具描述换成单行版(无 snippet/guideline 包装),压缩规则保持默认。内置 `chat`(#5319)只替换压缩哲学段与 how-to-compress 规则段,面向长期陪伴 / 多会话记忆场景;其余表面全部保持宿主默认,同名的用户/项目文件会覆盖它。未知包名回退到恒等表面并记录一次警告。与其他字段一样三级级联合并;包的表面覆盖(工具/段落)直接生效,不经 `acknowledgePromptsRisk` 门控——该门控只管内联 `compress.prompts` 的规则文本覆盖。注意:包文件里的 `prompts` 块会被本代理忽略,规则文本只能经内联 `compress.prompts` 设置。需要 `acp-kernel` >= 0.0.66。
- **说明:** 选择一个具名 prompt pack —— 一套策划好的表面预设,覆盖工具描述、压缩系统提示词段落、nudge 段落 —— 从宿主侧的包解析链解析:**项目** `./.billion-context/packs/<name>.json` → **用户** `<configDir>/packs/<name>.json` → **随包附带**(`chat`)→ **内核内置**(`default`、`lean`)。内置 `lean` 把四个 ACP 工具描述换成单行版(无 snippet/guideline 包装),压缩规则保持默认。内置 `chat`(#5319)只替换压缩哲学段与 how-to-compress 规则段,面向长期陪伴 / 多会话记忆场景;其余表面全部保持宿主默认,同名的用户/项目文件会覆盖它。未知包名回退到恒等表面并记录一次警告。与其他字段一样三级级联合并;包的表面覆盖(工具/段落)直接生效,不经 `acknowledgePromptsRisk` 门控——该门控只管内联 `compress.prompts` 的规则文本覆盖。注意:包文件里的 `prompts` 块会被本代理忽略,规则文本只能经内联 `compress.prompts` 设置。需要 `acp-kernel` >= 0.0.66。设置面板可以直接管理用户目录里的包文件——对 `<configDir>/packs/` 下的包 新建/编辑/删除(选择器知道每个条目的来源;内置与 shipped 包在那里只读,要用同名用户包覆盖)。

**包文件格式。** 每个 `<dir>/<name>.json` 是一个 pack 对象。未识别的字段会被与所有加载路径相同的 sanitize 器丢弃(`sanitizePackSurface`),所以多写元数据无害:

```json
{
"name": "my-pack", // 可选 —— 缺省用文件名(去 .json)
"version": "1.0.0", // 可选 —— `bili pack list` 与面板会显示
"description": "……", // 可选
"promptSections": {
"philosophy": "……", // 替换整段系统提示词;JSON null = 保留默认文本
"howToCompress": "……" // 可直接从 src/chat-pack.ts 里调好的全文起步
}
}
```

可选的表面块:`prompts`(内联规则文本覆盖)、`nudgeSections`、`toolPrompts`、`adapters`(宿主专属附加,如 `"pi": { "promptSections": { … } }`)。至少一个字段在 sanitize 后存活,否则写入时会被拒绝。

**安装别人的包。** 任何根目录带 `bili-pack.json`(即上面的 pack 对象)的 npm 包都可安装:`bili pack install <pkg>`——也接受 `name@version`、带 scope 名、git URL、`.tgz` 路径(底层委托本机 `npm`,所以 registry 鉴权行为与普通 npm 一致)。默认落到 `<configDir>/packs/`(`--project` 指向 `./.billion-context/packs/`;已存在同名包时默认拒绝,`--force` 才替换)。之后可用设置面板管理,或 `bili pack remove <name>` / `bili pack list`。

#### `reconcile`

Expand Down
64 changes: 61 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* bili acp-cache diff <dir> attribute cache breaks from ACP_DUMP_BODY dumps
* bili sessions ls|rm|archive|restore [id] manage persisted sessions
* bili storage gc [--days N] run the storage sweep now (--dry-run plans only)
* bili pack install <spec> install a custom compress prompt pack from npm (#5319)
* bili test pi non-polluting pi smoke test
* bili --version
* bili --help
Expand All @@ -42,6 +43,8 @@ import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatus
import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launcher.js";
import { exportSession } from "./export.js";
import { runSessionsCommand, runStorageGcCommand } from "./storage-maintenance.js";
import { installPackFromNpm, removePackFile } from "./pack-install.js";
import { listResolvedPacks } from "./compress-settings.js";
import { renderJson, renderText, runDiff } from "./acp-cache-diff.js";
import { fixDshLedgers, renderDoctorReport, renderLedgerFixReport, runDoctor } from "./doctor.js";
import { VERSION, PACKAGE_NAME, BUILD_COMMIT } from "./version.js";
Expand Down Expand Up @@ -94,6 +97,10 @@ Usage:
release unreferenced content, shrink index.db
(--days N overrides the age; --vacuum full|incremental;
prints the sweep plan first, --dry-run stops there)
bili pack install <npm-spec> npm-install a custom compress prompt pack
bili pack list / remove <name> list resolvable packs / delete a local pack file
(--project targets ./.billion-context/packs/ instead;
install also accepts --force to replace an existing pack)
bili acp-cache diff <dir> offline prefix-diff attribution over ACP_DUMP_BODY
dumps: pairs adjacent requests per session and classifies
each (pure-append / mid-stream-rewrite / prefix-stable-miss);
Expand Down Expand Up @@ -183,7 +190,7 @@ Docs: https://github.com/ranxianglei/billion-context
`;

type Parsed = {
command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage";
command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage" | "pack";
client?: ClientName;
clientArgs: string[];
mitmDomains: string[];
Expand All @@ -196,6 +203,10 @@ type Parsed = {
pluginAction?: "install" | "remove" | "update" | "list";
pluginAgent?: PluginAgent;
pluginWithMcp?: boolean;
packAction?: "install" | "remove" | "list";
packSpec?: string;
packProject?: boolean;
packForce?: boolean;
acpCacheDir?: string;
acpCacheLog?: string;
acpCacheNoLog?: boolean;
Expand Down Expand Up @@ -226,6 +237,10 @@ export function parseArgs(argv: string[]): Parsed {
let pluginAction: Parsed["pluginAction"];
let pluginAgent: Parsed["pluginAgent"];
let pluginWithMcp = false;
let packAction: Parsed["packAction"];
let packSpec: string | undefined;
let packProject = false;
let packForce = false;
let acpCacheDir: string | undefined;
let acpCacheLog: string | undefined;
let acpCacheNoLog = false;
Expand Down Expand Up @@ -302,6 +317,12 @@ export function parseArgs(argv: string[]): Parsed {
case "--with-mcp":
pluginWithMcp = true;
break;
case "--project":
packProject = true;
break;
case "--force":
packForce = true;
break;
case "--json":
jsonOutput = true;
doctorJson = true;
Expand Down Expand Up @@ -476,6 +497,20 @@ export function parseArgs(argv: string[]): Parsed {
console.error(`bili sessions: unknown action "${sub ?? ""}" (try "bili sessions ls|rm|archive|restore")`);
process.exit(2);
}
} else if (cmd === "pack" || cmd === "packs") {
command = "pack";
const action = positional[1];
if (action !== "install" && action !== "remove" && action !== "list") {
console.error(`bili pack: unknown action "${action ?? ""}" (try "bili pack install <npm-spec> | remove <name> | list")`);
process.exit(2);
}
packAction = action;
const arg = positional[2];
if (packAction !== "list" && arg === undefined) {
console.error(`bili pack ${packAction}: <${packAction === "install" ? "npm-spec" : "name"}> is required`);
process.exit(2);
}
packSpec = arg;
} else if (cmd === "storage") {
command = "storage";
if (positional[1] !== "gc") {
Expand All @@ -488,11 +523,11 @@ export function parseArgs(argv: string[]): Parsed {
}
}

return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix };
return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce };
}

export async function main(): Promise<void> {
const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix } = parseArgs(process.argv.slice(2));
const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2));
if (command === "help") {
process.stdout.write(HELP);
return;
Expand Down Expand Up @@ -605,6 +640,29 @@ export async function main(): Promise<void> {
return;
}
}
if (command === "pack") {
try {
if (packAction === "list") {
for (const p of listResolvedPacks()) {
console.log(`${p.name}\t${p.version ?? "-"}\t${p.source}${p.description ? ` ${p.description}` : ""}`);
}
return;
}
if (packAction === "install") {
const r = installPackFromNpm(packSpec!, { project: packProject, force: packForce });
console.log(`installed pack "${r.name}"${r.version ? ` v${r.version}` : ""} -> ${r.file}`);
return;
}
if (packAction === "remove") {
console.log(`removed ${removePackFile(packSpec!, packProject)}`);
return;
}
} catch (error) {
console.error(`bili pack: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
return;
}
if (command === "export") {
try {
const text = await exportSession(exportSelector, { output: exportOutput, full: exportFull, jsonl: exportJsonl });
Expand Down
36 changes: 25 additions & 11 deletions src/compress-settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DEFAULT_ABSORB_CONFIG, DEFAULT_CCR_CONFIG, defaultPrompts, resolvePrompts, createPackResolver, builtinSource, createDirPackSource, isValidPackName, type AbsorbConfig, type Config, type CcrConfig, type PackSurface, type Prompts } from "acp-kernel";
import { DEFAULT_ABSORB_CONFIG, DEFAULT_CCR_CONFIG, defaultPrompts, resolvePrompts, createPackResolver, builtinSource, createDirPackSource, isValidPackName, type AbsorbConfig, type Config, type CcrConfig, type Pack, type PackSurface, type Prompts } from "acp-kernel";
import * as path from "node:path";
import { findRoute, type CompressSettings, type NamedProviderRecipe, type ProviderRoutes } from "./config.js";
import { configDir } from "./paths.js";
Expand Down Expand Up @@ -167,6 +167,21 @@ interface SurfaceResolution {
packVersion?: string;
}

function packResolver(
dirs?: { projectDir?: string; userDirs?: readonly string[] },
): ReturnType<typeof createPackResolver> {
// #5319: host-shipped packs sit between the user dirs and the kernel
// builtin registry — same-name user/project files still win, and the
// kernel registry itself stays untouched (Kernel Boundary: adding a pack
// must not require a kernel/** change).
return createPackResolver([
createDirPackSource("project", dirs?.projectDir ?? path.join(process.cwd(), ".billion-context", "packs")),
...(dirs?.userDirs ?? [path.join(configDir(), "packs")]).map((dir) => createDirPackSource("user", dir)),
shippedPacksSource,
builtinSource,
]);
}

/** Resolve the pack surface for one request: `promptPack` names a pack in the
* host's resolver chain [project `./.billion-context/packs` > user
* `<configDir>/packs` > shipped host-bundled packs (`chat`, #5319) > kernel
Expand All @@ -180,16 +195,7 @@ export function resolveCompressSurfaceDetailed(
): SurfaceResolution {
const name = s.promptPack;
if (typeof name !== "string" || name === "default" || !isValidPackName(name)) return { surface: {}, packName: "default" };
// #5319: host-shipped packs sit between the user dirs and the kernel
// builtin registry — same-name user/project files still win, and the
// kernel registry itself stays untouched (Kernel Boundary: adding a pack
// must not require a kernel/** change).
const resolver = createPackResolver([
createDirPackSource("project", dirs?.projectDir ?? path.join(process.cwd(), ".billion-context", "packs")),
...(dirs?.userDirs ?? [path.join(configDir(), "packs")]).map((dir) => createDirPackSource("user", dir)),
shippedPacksSource,
builtinSource,
]);
const resolver = packResolver(dirs);
const pack = resolver.resolve(name);
if (!pack) {
if (!warnedUnknownPack.has(name)) {
Expand All @@ -201,6 +207,14 @@ export function resolveCompressSurfaceDetailed(
return { surface: pack.surface, packName: name, packVersion: pack.version };
}

/** Every pack resolvable by name right now (first-wins per name) — the panel
* picker's inventory (#5319 web half). Same chain as per-request resolution. */
export function listResolvedPacks(
dirs?: { projectDir?: string; userDirs?: readonly string[] },
): Pack[] {
return packResolver(dirs).listPacks();
}

export function resolveCompressSurface(
s: CompressSettings,
dirs?: { projectDir?: string; userDirs?: readonly string[] },
Expand Down
Loading
Loading