diff --git a/src/cli.ts b/src/cli.ts index b7ca2b87ce..5dcd1cc592 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -54,6 +54,8 @@ Usage: bili update check for & install a newer version now bili plugin install 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 remove it again bili plugin list show install status for every host bili mcp run the bili MCP server standalone (stdio) @@ -118,6 +120,7 @@ type Parsed = { registerConversationId?: string; pluginAction?: "install" | "remove" | "list"; pluginAgent?: PluginAgent; + pluginWithMcp?: boolean; }; export function parseArgs(argv: string[]): Parsed { @@ -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]!; @@ -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) { @@ -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 { - 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; @@ -333,7 +340,7 @@ export async function main(): Promise { } 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); diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 8855fea617..b1b20aeb99 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -439,18 +439,68 @@ function isPlainMcpObject(v: unknown): v is Record { 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 | 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 = {}; + if (pinned.length > 0) environment.BILI_MCP_PROXY = pinned; + const entry: Record = { 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 { @@ -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 { diff --git a/tests/logger-rotation.test.ts b/tests/logger-rotation.test.ts index bb5e4513df..16acd5b862 100644 --- a/tests/logger-rotation.test.ts +++ b/tests/logger-rotation.test.ts @@ -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 { +/** 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 { 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 { @@ -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); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 64136b77bd..9ada1b6c68 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -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 }> }; + // #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 }> }; 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 @@ -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; + 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 } } }; + 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 }; + 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();