From 8c706c388265487017b698e1a92ebf9b852f2437 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Sat, 19 Sep 2026 19:46:04 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20single-writer=20plugin=20guard=20?= =?UTF-8?q?=E2=80=94=20never=20overwrite=20host-managed=20copies,=20add=20?= =?UTF-8?q?bili=20plugin=20update?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/update.ts: hostManagedInstall() classifies install dirs (pnpm .pnpm virtual store, pi/opencode/dsh/kimi/omp host homes); checkForUpdate skips them, installViaTarball refuses them structurally (#991) - dsh bundles: self-update re-runs dsh's plugin channel per profile instead of copying over a pnpm store - bili plugin update [client]: drives each lane through its own owner, prints per-lane update path; bili plugin list shows the same channel info - tests: update-host-guard (classification + refusal), plugin-update lanes - docs: single-writer principle in README + AGENTS.md Key Design Decisions Fixes #991 --- AGENTS.md | 1 + README.md | 25 ++++++ src/cli.ts | 50 +++++++++-- src/plugin-install.ts | 107 +++++++++++++++++++++-- src/update.ts | 88 +++++++++++++++++++ tests/plugin-update.test.ts | 68 +++++++++++++++ tests/update-host-guard.test.ts | 146 ++++++++++++++++++++++++++++++++ 7 files changed, 474 insertions(+), 11 deletions(-) create mode 100644 tests/plugin-update.test.ts create mode 100644 tests/update-host-guard.test.ts diff --git a/AGENTS.md b/AGENTS.md index a4e1c7c74a..155fb5d0d7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,6 +81,7 @@ billion-context/ 3. **Auto-update**: checks npm registry every 3 min (`CHECK_INTERVAL_MS = 3*60*1000`), first check per process ignores throttle 4. **Tee logger**: all proxy logs go through `src/logger.ts` (file + stderr). Do NOT use `console.error` in server-side modules — use `loggerLog()`. 5. **acp-kernel MUST be pinned to an exact version** (e.g. `"acp-kernel": "0.0.17"`, NEVER `"^0.0.17"`). Because acp-kernel is a build-time dependency that tsup bundles inline into `dist`, a caret range makes the resolved version drift if `package-lock.json` is regenerated or absent, breaking reproducible builds. When bumping acp-kernel: set the exact version in `package.json`, run `npm install` to refresh the lockfile, then rebuild. The `package-lock.json` is committed and kept in sync. +6. **Single-writer plugin copies (#991)** — every bili presence has exactly one writer. Host-managed copies (pi's npm entry, opencode's plugin dir, dsh profile bundles in pnpm's store) are NEVER overwritten in place by bili: `src/update.ts` → `hostManagedInstall()` detects pnpm virtual-store (`.pnpm`) and host-home trees (pi/opencode/dsh/kimi/omp) and the self-updater skips them; `installViaTarball` refuses them structurally. Reference lanes (omp/claude/codex/kimi) point at the global install and update with it. `bili plugin update [agent]` drives each lane through its own owner. Mixing user commands is fine (they share channels); mixing writers is what the guard forbids. 6. **Two compression modes with different summary carriers** — `pluginMode` (the `x-bili-plugin` header / registered agent, e.g. `bili pi`) means the ACP-native agent OWNS compression: it executes `compress` locally, the call+result live in its own re-sent history, and the summary carrier on the wire is the **tool call** (the proxy suppresses tool + nudge injection; the agent's view never renders the kernel's `acp_summary`). Proxy mode (plain client, no header) means the proxy executes `compress` server-side: the tool call is ephemeral (never enters the client's history) and preflight blocks have none, so the summary carrier is the **`acp_summary` message**, which the kernel renders as role `system` but `systemToUser` (`src/util.ts`) re-voices as a **`user` message** (leaving it at its anchor) so strict backends (SGLang: exactly one system at index 0, #377) accept it and the head system message stays byte-stable for the prefix cache. The mode is decided per request and bound per session (`session.metadata.pluginAgent`, sticky, upgrade-only). See README "Two compression modes". ### Kernel Contract: Message Ids Are Never Reused diff --git a/README.md b/README.md index 7e2598201b..2bb88add2b 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,7 @@ bili plugin install opencode # registers the plugin in opencode's real config bili plugin install dsh # runs 'dsh plugin --profile add billion-context' for every existing profile bili plugin install kimi # writes $KIMI_CODE_HOME/plugins/managed/billion-context/kimi.plugin.json (+ installed.json record); per-session routing block lands in config.toml on first start (Kimi Code >= 2.0.0) bili plugin remove # undo (dsh removes through the same channel; config snapshots go to .bili-bak) +bili plugin update [client] # bring every lane's bili presence up to date, each through its own owner (see below) ``` Where a client has its own plugin channel you can also install natively, @@ -216,6 +217,30 @@ For pi / omp / kimi / claude there is no client-side channel — `bili plugin install ` writes their config entries for you (kimi's declarative `kimi.plugin.json` + registry record, claude's managed settings block, …). +#### Single-writer: who owns which copy (#991) + +Every bili presence on a machine has exactly **one writer** — the thing +that installed it is the thing that updates it, and nothing else ever +overwrites that copy in place: + +| Lane | Copy lives in | Updated by | +|------|---------------|------------| +| global `bili` | npm global (`npm i -g billion-context`) | `bili update` / background auto-update | +| **pi** | pi's package manager (npm form) | **`pi update`** — bili never overwrites it | +| **opencode** | opencode's plugin dir | **opencode's plugin manager** — bili never overwrites it | +| **dsh** | each profile's pnpm store | global bili self-update re-runs dsh's plugin channel per profile (or `dsh plugin add billion-context@latest`); pnpm's hardlinked store must never be copied over in place | +| omp / claude / codex / kimi | no copy — entries point at the global bili install | they update together with the global copy | + +This is enforced in code, not just convention: the self-updater +(`src/update.ts` → `hostManagedInstall`) detects install dirs under a pnpm +virtual store (`.pnpm`) or a host agent tree (pi / opencode / dsh / kimi / +omp homes) and **skips** them; `installViaTarball` refuses them structurally +so direct callers cannot corrupt a store either. Mixing *commands* is fine +(`dsh plugin add` ≡ `bili plugin install dsh` — same channel, same records); +mixing *writers* is what the guard forbids. `bili plugin update [client]` +is the one command that drives every lane through its own owner and prints +the per-lane update path (`bili plugin list` shows the same per-lane channel). + At load the plugin **spawns its own proxy** (or attaches to a healthy running one — a parent-pid watchdog tears it down when the client exits), rewrites model traffic to `/bili/`, registers diff --git a/src/cli.ts b/src/cli.ts index d2380e38cf..0f6454b8f5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -26,7 +26,7 @@ import { configFile as defaultConfigFile } from "./paths.js"; import { checkForUpdate, startAutoUpdate } from "./update.js"; import { resolveProxy } from "./upstream-proxy.js"; import { runMcpStdio } from "./mcp.js"; -import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, type PluginAgent } from "./plugin-install.js"; +import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, type PluginAgent } from "./plugin-install.js"; import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launcher.js"; import { exportSession } from "./export.js"; import { VERSION, PACKAGE_NAME } from "./version.js"; @@ -57,6 +57,11 @@ Usage: --with-mcp (opencode only) also adds the mcp.bili MCP face; default is the native plugin tools only bili plugin remove remove it again + bili plugin update [agent] update each lane's bili presence through its + own owner (#991): reference lanes follow the + global install, dsh bundles refresh through + dsh's channel, host-owned copies are pointed + at their host's updater — never overwritten bili plugin list show install status for every host bili mcp run the bili MCP server standalone (stdio) bili plugin-register pre-bind a conversation to the plugin mode @@ -118,7 +123,7 @@ type Parsed = { exportOutput?: string; exportFull?: boolean; registerConversationId?: string; - pluginAction?: "install" | "remove" | "list"; + pluginAction?: "install" | "remove" | "update" | "list"; pluginAgent?: PluginAgent; pluginWithMcp?: boolean; }; @@ -252,10 +257,10 @@ export function parseArgs(argv: string[]): Parsed { } else if (cmd === "plugin") { command = "plugin"; const action = positional[1]; - if (action === "install" || action === "remove" || action === "list") { + if (action === "install" || action === "remove" || action === "update" || action === "list") { pluginAction = action; } else { - console.error(`bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|list ")`); + console.error(`bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|update|list ")`); process.exit(2); } const agent = positional[2]; @@ -266,7 +271,7 @@ export function parseArgs(argv: string[]): Parsed { } pluginAgent = agent; } - if (pluginAction !== "list" && pluginAgent === undefined) { + if (pluginAction !== "list" && pluginAction !== "update" && pluginAgent === undefined) { console.error(`bili plugin ${pluginAction}: agent is required (try one of: ${PLUGIN_AGENTS.join(", ")})`); process.exit(2); } @@ -334,7 +339,40 @@ export async function main(): Promise { if (overrides.BILI_MCP_PROXY !== undefined) process.env.BILI_MCP_PROXY = overrides.BILI_MCP_PROXY; if (pluginAction === "list") { for (const row of pluginStatusAll()) { - console.log(`${row.agent.padEnd(10)} ${row.status}`); + const channel = row.status === "not installed" || row.status.startsWith("error") ? "" : ` | updates via ${row.channel}`; + console.log(`${row.agent.padEnd(10)} ${row.status}${channel}`); + } + return; + } + if (pluginAction === "update") { + // Same updater egress/channel wiring as `bili update` (#609): the + // dsh lane resolves the latest registry version and the global + // check downloads through the same proxy decision as model + // traffic. + for (const [k, v] of Object.entries(overrides)) { + if (v !== undefined) process.env[k] = v; + } + let updaterResolveProxy: ((url: string) => string | undefined) | undefined; + let updateTag: string | undefined; + try { + const o = loadOptions(); + updaterResolveProxy = (url) => resolveProxy(o.routes, o.proxy, url, o.proxyFallback); + updateTag = o.updateTag; + } catch { + // config unloadable — updater egress goes direct + } + try { + const lines = await pluginUpdate(pluginAgent ? [pluginAgent] : undefined, { + packageName: PACKAGE_NAME, + resolveProxy: updaterResolveProxy, + updateTag, + globalCheck: () => checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true, resolveProxy: updaterResolveProxy, updateTag }, true), + log: (_level, msg) => console.log(msg), + }); + for (const line of lines) console.log(line); + } catch (error) { + console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); } return; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 407bc96db3..791aa2cd8d 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -30,7 +30,8 @@ import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError import { resolveDshHome, resolveKimiHome, resolvePiHome } from "./client-config.js"; import { clearClaudeNativePort, resolveClaudeNativePort, saveClaudeNativePort } from "./config.js"; import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js"; -import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDirs, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js"; +import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDirs, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js"; +import { fetchRegistryVersion } from "./update.js"; import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js"; /** #403: never freeze a dead or unverifiable origin into a client's @@ -1337,8 +1338,8 @@ export function pluginRemove(agent: PluginAgent): string { return agent === "pi" ? piRemove() : agent === "omp" ? ompRemove() : agent === "claude" ? claudeRemove() : agent === "codex" ? codexRemove() : agent === "dsh" ? dshRemove() : agent === "kimi" ? kimiRemove() : opencodeRemove(); } -export function pluginStatusAll(): Array<{ agent: string; status: string }> { - const checks: Array<[string, () => string]> = [ +export function pluginStatusAll(): Array<{ agent: string; status: string; channel: string }> { + const checks: Array<[PluginAgent, () => string]> = [ ["pi", piStatus], ["omp", ompStatus], ["claude", claudeStatus], @@ -1349,9 +1350,105 @@ export function pluginStatusAll(): Array<{ agent: string; status: string }> { ]; return checks.map(([agent, check]) => { try { - return { agent, status: check() }; + return { agent, status: check(), channel: UPDATE_CHANNEL[agent] }; } catch (err) { - return { agent, status: `error: ${err instanceof Error ? err.message : String(err)}` }; + return { agent, status: `error: ${err instanceof Error ? err.message : String(err)}`, channel: UPDATE_CHANNEL[agent] }; } }); } + +// #991 single-writer: every lane's update path, user-facing. Host-managed +// copies (pi's npm entry, opencode's plugin dir) are only ever updated by +// their host; dsh profile bundles track the global version; reference lanes +// (omp/claude/codex/kimi) follow the global bili install itself. +const UPDATE_CHANNEL: Record = { + pi: "pi update (pi owns the npm:billion-context copy)", + omp: "the global bili install (entry points at it)", + claude: "the global bili install (hook/MCP point at it)", + codex: "the global bili install (the mcp launcher shells out to it)", + opencode: "opencode's own plugin manager (opencode owns the copy)", + dsh: "the global bili self-update (profile bundles track it)", + kimi: "the global bili install (plugin points at its dist)", +}; + +export interface PluginUpdateOpts { + packageName: string; + resolveProxy?: (url: string) => string | undefined; + updateTag?: string; + /** Runs the global self-update check before per-lane reports. The CLI + * wires this to checkForUpdate(force); tests omit it to stay offline. */ + globalCheck?: () => Promise; + log?: (level: "info" | "warn", msg: string) => void; +} + +/** `bili plugin update [agent]` — bring every lane's bili presence up to + * date, each through its OWN owner (#991 single-writer): + * - reference lanes (omp/claude/codex/kimi) need nothing per-lane: they + * point at the global install, so only the global copy updates; + * - host-managed copies (pi npm entry, opencode plugin entry) are never + * overwritten by bili — the report says which host command upgrades + * them; + * - dsh profile bundles are re-resolved to the latest registry version + * through dsh's own plugin channel. + * Returns user-facing lines. Network is only touched when a dsh profile + * actually depends on bili (version lookup) or globalCheck is provided. */ +export async function pluginUpdate(agents: readonly PluginAgent[] | undefined, opts: PluginUpdateOpts): Promise { + const log = opts.log ?? (() => {}); + const lines: string[] = []; + if (opts.globalCheck) { + await opts.globalCheck(); + lines.push("global bili copy: update check ran (see log above; it skips copies owned by a host)"); + } + for (const agent of agents ?? PLUGIN_AGENTS) { + try { + lines.push(...await updateLane(agent as PluginAgent, opts, log)); + } catch (err) { + lines.push(`${agent}: update failed — ${err instanceof Error ? err.message : String(err)}`); + } + } + return lines; +} + +async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (level: "info" | "warn", msg: string) => void): Promise { + if (agent === "pi") { + const packages = readJson(piSettingsFile()).packages; + const list = Array.isArray(packages) ? (packages as unknown[]).map(String) : []; + const root = selfPackageRoot(); + if (list.some((p) => p === PI_NPM_ENTRY)) { + return ["pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)"]; + } + if (list.some((p) => isPiEntry(p, root))) { + return ["pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; + } + return ["pi: not installed"]; + } + if (agent === "opencode") { + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); + const dir = opencodePluginDir(file); + if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY))) { + return ["opencode: the plugin copy is opencode-managed — upgrade/reload it via opencode's plugin manager; bili never overwrites it (#991)"]; + } + if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir))) { + return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; + } + return ["opencode: not installed"]; + } + if (agent === "dsh") { + let dirs: string[]; + try { + dirs = dshProfileDirs(); + } catch { + return ["dsh: never initialized on this machine — nothing to update"]; + } + const targets = dirs.filter((dir) => dshProfileDependsOnBili(dir)); + if (targets.length === 0) return ["dsh: no profile depends on billion-context — nothing to update"]; + const latest = await fetchRegistryVersion(opts, opts.packageName); + if (!latest) return ["dsh: could not resolve the latest version from npm — leaving profile bundles alone"]; + const before = targets.length; + await refreshDshProfileBundles(latest, log); + return [`dsh: refreshing ${before} profile bundle(s) to ${latest} through dsh's plugin channel (see log for per-profile results)`]; + } + const via = UPDATE_CHANNEL[agent]; + return [`${agent}: the plugin entry follows the global bili install — it updates together with it (${via})`]; +} diff --git a/src/update.ts b/src/update.ts index 0ff0e11ca0..01dcd90c75 100644 --- a/src/update.ts +++ b/src/update.ts @@ -22,13 +22,16 @@ */ import { readFile, writeFile, mkdir, access, constants, rm, cp, unlink } from "node:fs/promises"; import { execFile } from "node:child_process"; +import { realpathSync } from "node:fs"; import crypto from "node:crypto"; import * as tar from "tar"; import path from "node:path"; +import os from "node:os"; import { fileURLToPath } from "node:url"; import { cacheDir } from "./paths.js"; import { log as loggerLog, type Logger } from "./logger.js"; import { refreshDshProfileBundles } from "./dsh-channel.js"; +import { resolveDshHome, resolveKimiHome, resolveOmpHome, resolvePiHome } from "./client-config.js"; import { proxyDispatcher } from "./upstream-proxy.js"; import type { FetchOptions } from "./fetch-util.js"; @@ -201,6 +204,56 @@ export async function isGitWorkingTree(dir: string): Promise { } } +export interface HostManagedInstall { + /** Who owns and updates this copy: "pnpm", "pi", "opencode", "dsh". */ + owner: string; + /** User-facing instruction for updating this copy through its owner. */ + channel: string; +} + +/** #991 single-writer rule: detect install directories that are OWNED by a + * host's package manager — a pnpm virtual store (dsh profile bundles, pnpm + * global) or a host agent's data tree (pi's package dir, opencode's plugin + * dir, dsh/kimi homes). An in-place tarball copy over such a directory + * corrupts the owner's bookkeeping (npm/pnpm metadata drift, #953) or, for + * pnpm, the hardlinked content files shared across every install in the + * store. Returns the owner + its update channel, or undefined when the copy + * is bili-owned (npm global, manual install) and may be updated in place. + * Exported for tests. */ +export function hostManagedInstall(installDir: string, env: NodeJS.ProcessEnv = process.env): HostManagedInstall | undefined { + let real = installDir; + try { + real = realpathSync(installDir); + } catch { + // nonexistent or unreadable — evaluate the literal path + } + for (const dir of [installDir, real]) { + if (dir.split(path.sep).some((seg) => seg === ".pnpm")) { + return { + owner: "pnpm", + channel: "dsh profiles refresh automatically on the next global bili self-update; a pnpm-global install upgrades via `pnpm add -g billion-context@latest`", + }; + } + } + const xdgData = env.XDG_DATA_HOME && env.XDG_DATA_HOME.trim().length > 0 ? env.XDG_DATA_HOME : path.join(os.homedir(), ".local", "share"); + const homes: Array<[string, string, string]> = [ + ["pi", resolvePiHome(env), "`pi update` (pi installs and upgrades the npm:billion-context entry itself)"], + ["opencode", path.join(xdgData, "opencode"), "opencode's own plugin manager (reload/reinstall the billion-context plugin)"], + ["dsh", resolveDshHome(env), "the dsh plugin channel (global bili self-update refreshes profiles; or `dsh plugin add billion-context@latest`)"], + ["kimi", resolveKimiHome(env), "`bili plugin install kimi` after updating the global bili install"], + ["omp", resolveOmpHome(env), "the global bili install (the extensions entry points at it)"], + ]; + for (const [owner, home, channel] of homes) { + if (!home) continue; + for (const dir of [installDir, real]) { + if (dir === home || dir.startsWith(home + path.sep)) { + return { owner, channel }; + } + } + } + return undefined; +} + /** Read the version from the on-disk package.json (not the startup constant). */ async function readDiskVersion(installDir: string): Promise { try { @@ -429,6 +482,24 @@ function fetchWithEgress(url: string, init: FetchOptions): Promise { return fetch(url, init as RequestInit); } +/** Resolve the current version of `packageName` on the configured dist-tag + * channel. Shared by the self-updater and `bili plugin update` (dsh profile + * refresh). Returns undefined on any failure — callers treat "unknown" as + * "do nothing". (#991) */ +export async function fetchRegistryVersion(opts: Pick, packageName: string): Promise { + const tag = normalizeUpdateTag(opts.updateTag); + const url = registryUrlFor(packageName, tag); + const dispatcher = egressDispatcher(opts, url); + const res = await fetchWithEgress(url, { + signal: AbortSignal.timeout(5000), + headers: { Accept: "application/json" }, + ...(dispatcher ? { dispatcher } : {}), + }); + if (!res.ok) return undefined; + const data = (await res.json()) as { version?: string }; + return data.version; +} + /** Run a single check (throttled unless `force`). Safe to call frequently. */ export async function checkForUpdate(opts: UpdateOptions, force = false): Promise { if (!opts.autoUpdate && !force) return; @@ -457,6 +528,16 @@ export async function checkForUpdate(opts: UpdateOptions, force = false): Promis return; } + // #991 single-writer: when this install dir belongs to a host (pnpm + // store, pi/opencode/dsh/kimi/omp trees), the copy must only be + // updated through its owner — never overwritten in place by the + // global self-updater. + const managed = installDir ? hostManagedInstall(installDir) : undefined; + if (managed) { + loggerLog("info", `[update] install dir is managed by ${managed.owner} (${installDir}) \u2014 skipping in-place self-update; update it via ${managed.channel} (#991)`); + return; + } + loggerLog("info", `[update] checking npm registry for ${opts.packageName}${sinceLastSec < 0 ? " (startup check)" : sinceLastSec === 0 ? "" : ` (last check ${sinceLastSec}s ago)`}\u2026`); // Follow the configured dist-tag channel (default "latest"): an @@ -589,6 +670,13 @@ export async function installViaTarball( return { ok: false, error: `install dir is a git working tree (${installDir}) \u2014 refusing to overwrite a source checkout (use npm install -g)` }; } + // #991 single-writer: refuse to overwrite a host-managed copy (pnpm + // store, host agent data trees) — only its owner may update it. + const managed = hostManagedInstall(installDir); + if (managed) { + return { ok: false, error: `install dir is managed by ${managed.owner} (${installDir}) \u2014 refusing in-place overwrite (single-writer); update via ${managed.channel}` }; + } + // Download tarball. Stream into memory with a hard size cap so a corrupt // or malicious tarball cannot exhaust memory. const MAX_TARBALL_BYTES = 100 * 1024 * 1024; diff --git a/tests/plugin-update.test.ts b/tests/plugin-update.test.ts new file mode 100644 index 0000000000..193e4a29b5 --- /dev/null +++ b/tests/plugin-update.test.ts @@ -0,0 +1,68 @@ +// #991 single-writer: `bili plugin update` reports each lane through its own +// owner — reference lanes follow the global install, host-managed copies are +// pointed at their host's updater (never overwritten), dsh bundles refresh +// through dsh's plugin channel. These tests run fully offline: no globalCheck +// is injected, and the dsh lane short-circuits before any registry fetch +// (no profiles on a scratch DSH_HOME). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pluginUpdate } from "../src/plugin-install.ts"; + +function scratchHome(): { home: string; cleanup(): void } { + const home = mkdtempSync(path.join(tmpdir(), "bc-plugin-update-")); + return { home, cleanup: () => rmSync(home, { recursive: true, force: true }) }; +} + +const OPTS = { packageName: "billion-context" }; + +test("pluginUpdate: reference lanes point at the global install", async () => { + const lines = await pluginUpdate(["omp", "claude", "codex", "kimi"], OPTS); + assert.equal(lines.length, 4); + for (const line of lines) assert.match(line, /global bili install/); +}); + +test("pluginUpdate: global check runs once when injected", async () => { + let ran = 0; + const lines = await pluginUpdate(["omp"], { ...OPTS, globalCheck: async () => { ran += 1; } }); + assert.equal(ran, 1); + assert.match(lines[0], /global bili copy: update check ran/); + assert.match(lines[1], /omp: /); +}); + +test("pluginUpdate: pi lane reports its owner by entry form", async () => { + const { home, cleanup } = scratchHome(); + process.env.PI_HOME = path.join(home, "agent"); + try { + // no settings file → not installed + let lines = await pluginUpdate(["pi"], OPTS); + assert.match(lines[0], /pi: not installed/); + + // npm entry → host-managed, bili never overwrites + const settings = path.join(home, "agent", "settings.json"); + mkdirSync(path.join(home, "agent"), { recursive: true }); + writeFileSync(settings, JSON.stringify({ packages: ["npm:billion-context"] })); + lines = await pluginUpdate(["pi"], OPTS); + assert.match(lines[0], /pi-managed/); + assert.match(lines[0], /pi update/); + assert.match(lines[0], /#991/); + } finally { + delete process.env.PI_HOME; + cleanup(); + } +}); + +test("pluginUpdate: dsh lane short-circuits offline when dsh is not initialized", async () => { + const { home, cleanup } = scratchHome(); + process.env.DSH_HOME = path.join(home, "dsh"); + try { + const lines = await pluginUpdate(["dsh"], OPTS); + assert.match(lines[0], /never initialized|nothing to update/); + } finally { + delete process.env.DSH_HOME; + cleanup(); + } +}); diff --git a/tests/update-host-guard.test.ts b/tests/update-host-guard.test.ts new file mode 100644 index 0000000000..9215e0be5d --- /dev/null +++ b/tests/update-host-guard.test.ts @@ -0,0 +1,146 @@ +// #991 single-writer: the global self-updater must never overwrite a copy +// owned by a host package manager or a host agent tree (pnpm virtual store, +// pi / opencode / dsh / kimi / omp homes). hostManagedInstall() classifies an +// install dir; checkForUpdate skips such dirs; installViaTarball refuses +// them structurally so direct callers cannot corrupt a store either. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import * as tar from "tar"; +import { hostManagedInstall, installViaTarball } from "../src/update.ts"; + +function integrityField(buf: Buffer, alg = "sha512"): string { + return `${alg}-${crypto.createHash(alg).update(buf).digest("base64")}`; +} + +test("hostManagedInstall: pnpm virtual-store paths are pnpm-owned", () => { + const base = mkdtempSync(path.join(tmpdir(), "bc-host-guard-")); + try { + // dsh profile bundle layout (dsh's pnpm forwarder) + const dshBundle = path.join(base, ".dsh", "profiles", "default", "node_modules", ".pnpm", "billion-context@0.1.121", "node_modules", "billion-context"); + assert.equal(hostManagedInstall(dshBundle)?.owner, "pnpm"); + // pnpm global layout + const pnpmGlobal = path.join(base, "pnpm", "global", "5", ".pnpm", "billion-context@0.1.121", "node_modules", "billion-context"); + assert.equal(hostManagedInstall(pnpmGlobal)?.owner, "pnpm"); + assert.match(hostManagedInstall(dshBundle)!.channel, /dsh profiles refresh/); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +test("hostManagedInstall: host agent homes own their trees", () => { + const base = mkdtempSync(path.join(tmpdir(), "bc-host-guard-")); + try { + const piDir = path.join(base, "pi-root", "node_modules", "billion-context"); + assert.equal(hostManagedInstall(piDir, { PI_HOME: path.join(base, "pi-root") })?.owner, "pi"); + assert.match(hostManagedInstall(piDir, { PI_HOME: path.join(base, "pi-root") })!.channel, /pi update/); + + const ocDir = path.join(base, "xdg", "opencode", "node_modules", "billion-context"); + assert.equal(hostManagedInstall(ocDir, { XDG_DATA_HOME: path.join(base, "xdg") })?.owner, "opencode"); + + const dshDir = path.join(base, "dsh-root", "plugins", "billion-context"); + assert.equal(hostManagedInstall(dshDir, { DSH_HOME: path.join(base, "dsh-root") })?.owner, "dsh"); + + const kimiDir = path.join(base, "kimi-root", "plugins", "managed", "billion-context"); + assert.equal(hostManagedInstall(kimiDir, { KIMI_CODE_HOME: path.join(base, "kimi-root") })?.owner, "kimi"); + + // PI_CODING_AGENT_DIR relocates BOTH the pi and omp homes (omp is a + // pi fork and shares the env) — either owner is correct; what matters + // is the guard fires on that tree. + const ompDir = path.join(base, "omp-root", "node_modules", "billion-context"); + const ompOwner = hostManagedInstall(ompDir, { PI_CODING_AGENT_DIR: path.join(base, "omp-root") })?.owner; + assert.ok(ompOwner === "pi" || ompOwner === "omp", `unexpected owner ${ompOwner}`); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +test("hostManagedInstall: bili-owned dirs (npm global layout, scratch) stay updatable", () => { + const base = mkdtempSync(path.join(tmpdir(), "bc-host-guard-")); + try { + assert.equal(hostManagedInstall(path.join(base, "install")), undefined); + // plain npm global layout: /.local/lib/node_modules/billion-context + // must NOT be classified as opencode-owned even though both live under + // the same XDG-ish tree root. + assert.equal(hostManagedInstall(path.join(base, "home", ".local", "lib", "node_modules", "billion-context"), { HOME: path.join(base, "home") }), undefined); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +interface Fixture { + root: string; + installDir: string; + cacheDir: string; + cleanup(): void; +} + +/** A running install at 1.2.3 under `relInstall`, plus scratch cache. */ +function makeFixture(relInstall: string): Fixture { + const root = mkdtempSync(path.join(tmpdir(), "bc-update-guard-")); + const installDir = path.join(root, relInstall); + const cacheDir = path.join(root, "cache"); + mkdirSync(path.join(installDir, "dist"), { recursive: true }); + writeFileSync( + path.join(installDir, "package.json"), + JSON.stringify({ name: "billion-context", version: "1.2.3", type: "module", main: "dist/index.js", bin: { bili: "./dist/index.js" } }), + ); + writeFileSync(path.join(installDir, "dist", "index.js"), "export const loaded = '1.2.3';\n"); + return { root, installDir, cacheDir, cleanup: () => rmSync(root, { recursive: true, force: true }) }; +} + +function makeTarball(root: string, version: string): { tgz: Buffer; integrity: string } { + const src = path.join(root, "pkg"); + mkdirSync(path.join(src, "package", "dist"), { recursive: true }); + writeFileSync(path.join(src, "package", "package.json"), JSON.stringify({ name: "billion-context", version, type: "module", main: "dist/index.js", bin: { bili: "./dist/index.js" } })); + writeFileSync(path.join(src, "package", "dist", "index.js"), `export const loaded = '${version}';\n`); + const tgzPath = path.join(root, "pkg.tgz"); + tar.c({ cwd: src, file: tgzPath, gzip: true, sync: true }, ["package"]); + const tgz = readFileSync(tgzPath); + return { tgz, integrity: integrityField(tgz) }; +} + +async function withTarballFetch(tgz: Buffer, fn: () => Promise): Promise { + const original = globalThis.fetch; + globalThis.fetch = (() => Promise.resolve(new Response(tgz))) as unknown as typeof fetch; + return fn().finally(() => { + globalThis.fetch = original; + }); +} + +test("installViaTarball: refuses a pnpm-store install dir and leaves it untouched", { timeout: 30_000 }, async () => { + const fx = makeFixture(path.join("node_modules", ".pnpm", "billion-context@1.2.3", "node_modules", "billion-context")); + process.env.XDG_CACHE_HOME = fx.cacheDir; + try { + const { tgz, integrity } = makeTarball(fx.root, "2.0.0"); + const r = await withTarballFetch(tgz, () => installViaTarball("2.0.0", "https://registry.test/x.tgz", fx.installDir, integrity)); + assert.equal(r.ok, false); + assert.match(r.error ?? "", /pnpm/); + assert.match(r.error ?? "", /single-writer/); + assert.equal(JSON.parse(readFileSync(path.join(fx.installDir, "package.json"), "utf-8")).version, "1.2.3", "store copy untouched"); + } finally { + delete process.env.XDG_CACHE_HOME; + fx.cleanup(); + } +}); + +test("installViaTarball: refuses a pi-owned install dir", { timeout: 30_000 }, async () => { + const fx = makeFixture(path.join(".pi", "agent", "node_modules", "billion-context")); + process.env.XDG_CACHE_HOME = fx.cacheDir; + process.env.PI_HOME = path.join(fx.root, ".pi", "agent"); + try { + const { tgz, integrity } = makeTarball(fx.root, "2.0.0"); + const r = await withTarballFetch(tgz, () => installViaTarball("2.0.0", "https://registry.test/x.tgz", fx.installDir, integrity)); + assert.equal(r.ok, false); + assert.match(r.error ?? "", /pi/); + assert.equal(JSON.parse(readFileSync(path.join(fx.installDir, "package.json"), "utf-8")).version, "1.2.3", "pi copy untouched"); + } finally { + delete process.env.XDG_CACHE_HOME; + delete process.env.PI_HOME; + fx.cleanup(); + } +}); From 79db64fe7ad3cae0dd9c958dfb2e44c10cb13dcd Mon Sep 17 00:00:00 2001 From: ework-daemon Date: Sat, 19 Sep 2026 20:27:51 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20re-apply=20review=20nits=20lost=20in?= =?UTF-8?q?=20rebase=20=E2=80=94=20trailing=20whitespace,=20AGENTS.md=20de?= =?UTF-8?q?cision-list=20numbering=20(#995)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- src/plugin-install.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 155fb5d0d7..0b6f2b800c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,7 @@ billion-context/ 4. **Tee logger**: all proxy logs go through `src/logger.ts` (file + stderr). Do NOT use `console.error` in server-side modules — use `loggerLog()`. 5. **acp-kernel MUST be pinned to an exact version** (e.g. `"acp-kernel": "0.0.17"`, NEVER `"^0.0.17"`). Because acp-kernel is a build-time dependency that tsup bundles inline into `dist`, a caret range makes the resolved version drift if `package-lock.json` is regenerated or absent, breaking reproducible builds. When bumping acp-kernel: set the exact version in `package.json`, run `npm install` to refresh the lockfile, then rebuild. The `package-lock.json` is committed and kept in sync. 6. **Single-writer plugin copies (#991)** — every bili presence has exactly one writer. Host-managed copies (pi's npm entry, opencode's plugin dir, dsh profile bundles in pnpm's store) are NEVER overwritten in place by bili: `src/update.ts` → `hostManagedInstall()` detects pnpm virtual-store (`.pnpm`) and host-home trees (pi/opencode/dsh/kimi/omp) and the self-updater skips them; `installViaTarball` refuses them structurally. Reference lanes (omp/claude/codex/kimi) point at the global install and update with it. `bili plugin update [agent]` drives each lane through its own owner. Mixing user commands is fine (they share channels); mixing writers is what the guard forbids. -6. **Two compression modes with different summary carriers** — `pluginMode` (the `x-bili-plugin` header / registered agent, e.g. `bili pi`) means the ACP-native agent OWNS compression: it executes `compress` locally, the call+result live in its own re-sent history, and the summary carrier on the wire is the **tool call** (the proxy suppresses tool + nudge injection; the agent's view never renders the kernel's `acp_summary`). Proxy mode (plain client, no header) means the proxy executes `compress` server-side: the tool call is ephemeral (never enters the client's history) and preflight blocks have none, so the summary carrier is the **`acp_summary` message**, which the kernel renders as role `system` but `systemToUser` (`src/util.ts`) re-voices as a **`user` message** (leaving it at its anchor) so strict backends (SGLang: exactly one system at index 0, #377) accept it and the head system message stays byte-stable for the prefix cache. The mode is decided per request and bound per session (`session.metadata.pluginAgent`, sticky, upgrade-only). See README "Two compression modes". +7. **Two compression modes with different summary carriers** — `pluginMode` (the `x-bili-plugin` header / registered agent, e.g. `bili pi`) means the ACP-native agent OWNS compression: it executes `compress` locally, the call+result live in its own re-sent history, and the summary carrier on the wire is the **tool call** (the proxy suppresses tool + nudge injection; the agent's view never renders the kernel's `acp_summary`). Proxy mode (plain client, no header) means the proxy executes `compress` server-side: the tool call is ephemeral (never enters the client's history) and preflight blocks have none, so the summary carrier is the **`acp_summary` message**, which the kernel renders as role `system` but `systemToUser` (`src/util.ts`) re-voices as a **`user` message** (leaving it at its anchor) so strict backends (SGLang: exactly one system at index 0, #377) accept it and the head system message stays byte-stable for the prefix cache. The mode is decided per request and bound per session (`session.metadata.pluginAgent`, sticky, upgrade-only). See README "Two compression modes". ### Kernel Contract: Message Ids Are Never Reused diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 791aa2cd8d..bc4e37d386 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -1418,7 +1418,7 @@ async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (leve return ["pi: the plugin copy is pi-managed (npm:billion-context) — `pi update` upgrades it; bili never overwrites it (#991)"]; } if (list.some((p) => isPiEntry(p, root))) { - return ["pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; + return ["pi: entry points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; } return ["pi: not installed"]; } @@ -1427,10 +1427,10 @@ async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (leve const { data } = loadOpencodeConfig(file); const dir = opencodePluginDir(file); if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === OPENCODE_NPM_ENTRY))) { - return ["opencode: the plugin copy is opencode-managed — upgrade/reload it via opencode's plugin manager; bili never overwrites it (#991)"]; + return ["opencode: the plugin copy is opencode-managed — upgrade/reload it via opencode's plugin manager; bili never overwrites it (#991)"]; } if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir))) { - return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; + return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; } return ["opencode: not installed"]; }