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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ Usage:
bili update check for & install a newer version now
bili plugin install <agent> install the thin plugin into a host (pi/omp/
claude/codex/opencode; original backed up once)
(opencode: --with-mcp adds the MCP surface,
auto-discovering the live proxy origin)
bili plugin remove <agent> remove it again
bili plugin list show install status for every host
bili mcp run the bili MCP server standalone (stdio)
Expand Down Expand Up @@ -118,6 +120,7 @@ type Parsed = {
registerConversationId?: string;
pluginAction?: "install" | "remove" | "list";
pluginAgent?: PluginAgent;
pluginWithMcp?: boolean;
};

export function parseArgs(argv: string[]): Parsed {
Expand All @@ -133,6 +136,7 @@ export function parseArgs(argv: string[]): Parsed {
let exportFull = false;
let pluginAction: Parsed["pluginAction"];
let pluginAgent: Parsed["pluginAgent"];
let pluginWithMcp = false;

for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
Expand Down Expand Up @@ -178,6 +182,9 @@ export function parseArgs(argv: string[]): Parsed {
case "--full":
exportFull = true;
break;
case "--with-mcp":
pluginWithMcp = true;
break;
case "--output": {
const val = argv[++i];
if (val === undefined) {
Expand Down Expand Up @@ -278,11 +285,11 @@ export function parseArgs(argv: string[]): Parsed {
}
}

return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent };
return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent, pluginWithMcp };
}

export async function main(): Promise<void> {
const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent } = parseArgs(process.argv.slice(2));
const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent, pluginWithMcp } = parseArgs(process.argv.slice(2));
if (command === "help") {
process.stdout.write(HELP);
return;
Expand Down Expand Up @@ -333,7 +340,7 @@ export async function main(): Promise<void> {
}
if (pluginAction === "install") {
try {
console.log(pluginInstall(pluginAgent!));
console.log(pluginInstall(pluginAgent!, { withMcp: pluginWithMcp }));
} catch (error) {
console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
Expand Down
66 changes: 58 additions & 8 deletions src/plugin-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,18 +439,68 @@ function isPlainMcpObject(v: unknown): v is Record<string, unknown> {
return v !== null && typeof v === "object" && !Array.isArray(v);
}

function opencodeInstall(): string {
const file = opencodeJson();
// #926: "ours" = command loads a bili dist/mcp.js (this install or an npm
// install). Only such entries are removed/rewritten below; a hand-authored
// mcp.bili is never clobbered (§7.3).
const BILI_MCP_JS_RE = /(^|[/\\])billion-context[/\\]dist[/\\]mcp\.js$/;

function isOurOpencodeMcpEntry(entry: unknown): boolean {
if (entry === null || typeof entry !== "object") return false;
const cmd = (entry as { command?: unknown }).command;
if (!Array.isArray(cmd)) return false;
const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js");
requireDistFile(mcpJs);
return cmd.some((c) => typeof c === "string" && (c === mcpJs || BILI_MCP_JS_RE.test(c)));
}

export interface OpencodeInstallOptions {
withMcp?: boolean;
}

// #926: opencode has a native plugin API — the V2 plugin (`bili opencode`)
// already registers the bili tools natively with auto session binding, so a
// second MCP surface here is redundant and its frozen BILI_MCP_PROXY goes
// stale when the launcher's ephemeral proxy restarts. Default: write nothing
// (heal a stale generated entry away). withMcp (`--with-mcp`): write the
// surface WITHOUT freezing the origin — resolveProxyOrigin() discovers the
// live proxy; only a user-pinned BILI_MCP_PROXY env persists.

function opencodeInstall(opts: OpencodeInstallOptions = {}): string {
const file = opencodeJson();
const data = readJson(file);
if (data.mcp != null && !isPlainMcpObject(data.mcp)) return `opencode: mcp.bili skipped ("mcp" is not an object) -> ${file}`;
const mcp = (data.mcp as Record<string, unknown> | undefined) ?? {};
if ("bili" in mcp) return `opencode: already installed (${file})`;
mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: proxyOriginForInstall() }, enabled: true };
const existing = "bili" in mcp ? mcp.bili : undefined;
const ours = existing !== undefined && isOurOpencodeMcpEntry(existing);

if (!opts.withMcp) {
if (ours) {
delete mcp.bili;
if (Object.keys(mcp).length === 0) delete data.mcp;
else data.mcp = mcp;
writeJson(file, data);
return `opencode: removed stale mcp.bili from ${file} (opencode uses the built-in plugin — launch via \`bili opencode\`; pass --with-mcp to restore the MCP surface)`;
}
if (existing !== undefined) {
return `opencode: left your existing mcp.bili untouched (${file}); pass --with-mcp to manage the bili MCP surface`;
}
return `opencode: nothing to install — opencode uses the built-in plugin (launch via \`bili opencode\`); pass --with-mcp to add the MCP surface`;
}

const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js");
requireDistFile(mcpJs);
const pinned = process.env.BILI_MCP_PROXY?.trim() ?? "";
const environment: Record<string, string> = {};
if (pinned.length > 0) environment.BILI_MCP_PROXY = pinned;
const entry: Record<string, unknown> = { type: "local", command: [process.execPath, mcpJs], enabled: true };
if (Object.keys(environment).length > 0) entry.environment = environment;
if ("bili" in mcp && !ours) {
throw new Error(`${file}: mcp.bili exists but is not a bili-managed entry — refusing to overwrite it (remove it first or rename yours)`);
}
const verb = "bili" in mcp ? "refreshed" : "installed";
mcp.bili = entry;
data.mcp = mcp;
writeJson(file, data);
return `opencode: installed -> ${file} mcp.bili`;
return `opencode: ${verb} ${verb === "refreshed" ? "mcp.bili in" : "->"} ${file} mcp.bili${pinned.length > 0 ? "" : " (origin auto-discovered from the live proxy)"}`;
}

function opencodeRemove(): string {
Expand All @@ -475,8 +525,8 @@ export function isPluginAgent(value: string): value is PluginAgent {
return (PLUGIN_AGENTS as readonly string[]).includes(value);
}

export function pluginInstall(agent: PluginAgent): string {
return agent === "pi" ? piInstall() : agent === "omp" ? ompInstall() : agent === "claude" ? claudeInstall() : agent === "codex" ? codexInstall() : opencodeInstall();
export function pluginInstall(agent: PluginAgent, opts: OpencodeInstallOptions = {}): string {
return agent === "pi" ? piInstall() : agent === "omp" ? ompInstall() : agent === "claude" ? claudeInstall() : agent === "codex" ? codexInstall() : opencodeInstall(opts);
}

export function pluginRemove(agent: PluginAgent): string {
Expand Down
12 changes: 8 additions & 4 deletions tests/logger-rotation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ import {
setLogCapture,
} from "../src/logger.ts";

/** Poll until the file's size is stable across a few checks (stream flushed). */
async function settle(file: string, timeoutMs = 3000): Promise<void> {
/** Poll until the file's size is stable across a few checks (stream flushed).
* With minSize > 0 the size must also have reached it: stability alone can be
* observed mid-flush when a write stalls (loaded runner, AV scan), and the
* rotation decision in openStream() is stat-based — an incomplete flush then
* skips the rename (CI flake on windows/22, #932). */
async function settle(file: string, timeoutMs = 3000, minSize = 0): Promise<void> {
const start = Date.now();
let last = -1;
let stable = 0;
while (Date.now() - start < timeoutMs) {
const size = fs.existsSync(file) ? fs.statSync(file).size : -1;
if (size === last) {
if (size >= minSize && size === last) {
stable++;
if (stable >= 3) return;
} else {
Expand Down Expand Up @@ -98,7 +102,7 @@ test("internal 10MB rotation: post-rotation line lands in the fresh file", async
configureLogger(file);
try {
log("info", "x".repeat(11 * 1024 * 1024));
await settle(file);
await settle(file, 10000, 11 * 1024 * 1024);
log("info", "post-rotation");
await settle(file);

Expand Down
60 changes: 57 additions & 3 deletions tests/plugin-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,12 +877,20 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO
assert.match(pluginInstall("codex"), /already installed/);
assert.match(pluginRemove("codex"), /removed/);

assert.match(pluginInstall("opencode"), /installed/);
const oc = JSON.parse(fs.readFileSync(path.join(home, ".config/opencode/opencode.json"), "utf8")) as { mcp: Record<string, { command: string[]; environment?: Record<string, string> }> };
// #926: opencode default writes NO mcp.bili (the native plugin owns
// the tools); only --with-mcp adds the surface. hintEnv pins
// BILI_MCP_PROXY, so --with-mcp persists that pinned value here.
const ocFile = path.join(home, ".config/opencode/opencode.json");
fs.mkdirSync(path.dirname(ocFile), { recursive: true });
fs.writeFileSync(ocFile, "{}");
assert.match(pluginInstall("opencode"), /nothing to install/);
assert.equal((JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: unknown }).mcp, undefined);
assert.match(pluginInstall("opencode", { withMcp: true }), /installed/);
const oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp: Record<string, { command: string[]; environment?: Record<string, string> }> };
assert.equal(oc.mcp.bili.command[1]!.endsWith(path.join("dist", "mcp.js")), true);
assert.equal(oc.mcp.bili.environment?.BILI_MCP_PROXY, "http://127.0.0.1:8787");
assert.match(pluginRemove("opencode"), /removed/);
assert.equal((JSON.parse(fs.readFileSync(path.join(home, ".config/opencode/opencode.json"), "utf8")) as { mcp?: unknown }).mcp, undefined);
assert.equal((JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: unknown }).mcp, undefined);

assert.throws(() => pluginInstall("claude"), /claude: install failed/);
// The CLAUDE stub above keeps that assertion deterministic even on
Expand All @@ -897,6 +905,52 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO
fs.rmSync(home, { recursive: true, force: true });
});

test("#926: opencode install never freezes a stale origin; --with-mcp auto-discovers", async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-plugin-opencode-926-"));
const ocDir = path.join(home, ".config/opencode");
fs.mkdirSync(ocDir, { recursive: true });
const ocFile = path.join(ocDir, "opencode.json");
const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js");
try {
await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined }, async () => {
// (a) default install writes nothing and preserves unrelated config
fs.writeFileSync(ocFile, JSON.stringify({ $schema: "https://opencode.ai/config.json", theme: "dark" }));
assert.match(pluginInstall("opencode"), /nothing to install/);
const kept = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record<string, unknown>;
assert.equal(kept.$schema, "https://opencode.ai/config.json");
assert.equal(kept.theme, "dark");
assert.equal(kept.mcp, undefined);

// (b) --with-mcp without a pinned env omits the environment field entirely
assert.match(pluginInstall("opencode", { withMcp: true }), /installed/);
let oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp: { bili: { command: string[]; environment?: Record<string, string> } } };
assert.equal(oc.mcp.bili.command[1], mcpJs);
assert.equal(oc.mcp.bili.environment, undefined);
// idempotent refresh stays origin-free
assert.match(pluginInstall("opencode", { withMcp: true }), /refreshed/);
oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as typeof oc;
assert.equal(oc.mcp.bili.environment, undefined);

// (c) self-heal: a stale frozen-origin entry (dead port) is removed, siblings preserved
fs.writeFileSync(ocFile, JSON.stringify({ mcp: { foo: { type: "remote", url: "https://foo.example/sse" }, bili: { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: "http://127.0.0.1:18787" }, enabled: true } } }));
assert.match(pluginInstall("opencode"), /removed stale mcp\.bili/);
const healed = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp: Record<string, unknown> };
assert.equal(healed.mcp.bili, undefined);
assert.ok("foo" in healed.mcp);

// (d) a hand-authored (non-ours) mcp.bili is never clobbered
fs.writeFileSync(ocFile, JSON.stringify({ mcp: { bili: { type: "remote", url: "https://example.invalid/sse" } } }));
assert.match(pluginInstall("opencode"), /left your existing mcp\.bili untouched/);
const untouched = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp: { bili: { url: string } } };
assert.equal(untouched.mcp.bili.url, "https://example.invalid/sse");
// --with-mcp refuses to overwrite a foreign entry
assert.throws(() => pluginInstall("opencode", { withMcp: true }), /refusing to overwrite/);
});
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});

test("omp plugin: scoped matching, existence check, overlay redirect (issue #392)", async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-plugin-omp-"));
const root = selfPackageRoot();
Expand Down
Loading