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
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ 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. **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".
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.
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

Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ bili plugin install opencode # registers the plugin in opencode's real config
bili plugin install dsh # runs 'dsh plugin --profile <name> 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 <client> # 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,
Expand All @@ -216,6 +217,30 @@ For pi / omp / kimi / claude there is no client-side channel — `bili plugin
install <client>` 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 `<proxy>/bili/<upstream-url>`, registers
Expand Down
50 changes: 44 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 <agent> 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 <id> pre-bind a conversation to the plugin mode
Expand Down Expand Up @@ -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;
};
Expand Down Expand Up @@ -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 <agent>")`);
console.error(`bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|update|list <agent>")`);
process.exit(2);
}
const agent = positional[2];
Expand All @@ -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);
}
Expand Down Expand Up @@ -334,7 +339,40 @@ export async function main(): Promise<void> {
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;
}
Expand Down
107 changes: 102 additions & 5 deletions src/plugin-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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],
Expand All @@ -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<PluginAgent, string> = {
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<void>;
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<string[]> {
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<string[]> {
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})`];
}
Loading
Loading