From 831b645804a84ab100d3ab94648ab04d852ff1e0 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 9 Nov 2026 10:49:01 +0800 Subject: [PATCH 1/2] fix(ci): register tests/issue5955-wedged-same-lane-takeover.test.ts in LIVE_FILES Converged master-red fix (sentinel ci-fixes lane): #5989 merged the spawning suite without registering it, so the #1248 SPAWN_RE tripwire kills all 11 core-matrix test shards before any test runs on every PR head. Hunk is byte-identical to open PR #5990 (which carries the same registration plus a test-tolerance change to master). --- scripts/live-files.mjs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/scripts/live-files.mjs b/scripts/live-files.mjs index 21faf81617..cf260c49ba 100644 --- a/scripts/live-files.mjs +++ b/scripts/live-files.mjs @@ -117,6 +117,13 @@ export const LIVE_FILES = [ // network I/O and binds no port, so no zone band is needed — the entry is for // the tripwire alone, like #3890/#5114 "tests/cache-keepalive.test.ts", + // #5955: the only real child is ONE bare `node -e ""` spawned purely to + // hand back an already-reaped pid (win32 taskkill-then-SIGKILL silence); + // the takeover ladder itself runs on INJECTED deps — no proxy is started, + // no port is bound, no shutdown/kill signal ever reaches the OS. Fixed + // fake origins only, so no zone band is needed — the entry is for the + // tripwire alone, like #3890/#5114/#5666 + "tests/issue5955-wedged-same-lane-takeover.test.ts", ]; /** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry; From 09bda5609420d718aff2a41aea5b76928720459d Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 12:24:45 +0800 Subject: [PATCH 2/2] fix: opencode 2.x native install writes the shim dir instead of the bare package name (#3976) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenCode 2.x resolves a bare plugin package name through the package main field (dist/index.js, the CLI — no default export), so the entry form the installer wrote for 2.x hosts ("billion-context" under the plugins key) never loads: Plugin must export a default definition / on 2.2.5 a TypeError at /reload. Verified against the real @opencode/cli 2.1.0 binary (Linux): plural+bare does load there, but both field reports are Windows and the dir-shim form is proven on all four combinations (Linux/Windows x 2.1.0/2.2.5), so the installer now writes the shim dir (/plugins/billion-context/index.js re-exporting this install dist/agent/opencode-native.js) for every 2.x host and any dev build; 1.x npm installs keep the portable bare name. Legacy bare entries in a 2.x config migrate automatically; a stale shim is regenerated to point at the current root; update messages read the shim target to tell npm-root installs from checkouts. README en/zh + clients docs en/zh: manual-install instructions split by host generation. --- README.md | 32 ++++++-- README.zh-CN.md | 15 +++- docs/clients.md | 23 ++++-- docs/clients.zh-CN.md | 4 +- src/plugin-install.ts | 64 ++++++++++++---- tests/plugin-install-opencode.test.ts | 101 +++++++++++++++++++++++++- 6 files changed, 203 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 3d7e3296b0..6121125154 100644 --- a/README.md +++ b/README.md @@ -201,13 +201,31 @@ skipping bili commands entirely: without `dist/` and the bundle never loads) — same end state either way (pnpm into the profile, bundled patch layer mounted by dsh itself); remove through the same channel. See the dsh section below. -- **opencode:** add the bare npm name to your real config's plugin list — - `"plugin": ["billion-context"]` (npm form only; a git checkout has no - published entry). The package publishes `exports["./server"]` → - `dist/agent/opencode-native.js`, so opencode loads it through its own - Npm.add machinery and the plugin self-spawns exactly like the - bili-installed form. Do the two things the bili installer would have done - for you too: set `"compaction": { "auto": false }` in the same config +- **opencode:** easiest is `bili plugin install opencode` (it picks the + right entry form for your host version). Hand-install without bili (npm + form only; a git checkout has no published entry): + - **OpenCode 1.x** — add the bare npm name to your real config's plugin + list: `"plugin": ["billion-context"]`. The package publishes + `exports["./server"]` → `dist/agent/opencode-native.js`, so opencode + loads it through its own Npm.add machinery and the plugin self-spawns + exactly like the bili-installed form. + - **OpenCode 2.x** — the bare name does NOT work: 2.x resolves it through + the package `main` field (`dist/index.js`, the CLI — no plugin + definition), so the module load fails (#3976). Instead, put a one-line + re-export in a directory and point the config's `plugins` list at that + directory: + + ```js + // /index.js + export { default } from "/dist/agent/opencode-native.js"; + ``` + + ```json + { "plugins": [""] } + ``` + + Either generation: do the two things the bili installer would have done + for you too — set `"compaction": { "auto": false }` in the same config (otherwise OpenCode's native auto-compaction double-compresses) and keep a manual backup of the file first. - **claude:** this repository doubles as a Claude Code plugin marketplace — diff --git a/README.zh-CN.md b/README.zh-CN.md index dc1a47d577..7f782120d3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -169,7 +169,20 @@ bili plugin remove # 卸载(dsh 经同一通道移除;配置快照 客户端有自己的插件通道时,也可以原生安装、完全不用 bili 命令: - **dsh:** `dsh plugin --profile add billion-context` 正是 `bili plugin install dsh` 按 profile 驱动的那条命令(仅 npm 形态;git checkout 没有已发布入口 —— 直接填 GitHub 地址装到的是没有 `dist/` 的源码,bundle 永远加载不出来)—— 两种走法终态一致(pnpm 装进 profile、patch 层由 dsh 自己挂载);经同一通道卸载。见下文 dsh 段。 -- **opencode:** 把裸 npm 包名直接写进你真实配置的插件列表 —— `"plugin": ["billion-context"]`(仅 npm 形态;git checkout 没有已发布入口)。包通过 `exports["./server"]` → `dist/agent/opencode-native.js` 暴露插件入口,opencode 用自己的 Npm.add 机制加载,插件自拉起的行为与 bili 安装的形态完全一致。另外要做两件 bili 安装器会替你做的事:在同一份配置里设 `"compaction": { "auto": false }`(否则 OpenCode 的原生自动压缩会双重压缩),并先手工备份该配置文件。 +- **opencode:** 最省事是 `bili plugin install opencode`(它会按宿主版本选对入口形态)。不用 bili 手工安装(仅 npm 形态;git checkout 没有已发布入口): + - **OpenCode 1.x** —— 把裸 npm 包名直接写进你真实配置的插件列表:`"plugin": ["billion-context"]`。包通过 `exports["./server"]` → `dist/agent/opencode-native.js` 暴露插件入口,opencode 用自己的 Npm.add 机制加载,插件自拉起的行为与 bili 安装的形态完全一致。 + - **OpenCode 2.x** —— 裸包名**不行**:2.x 走包的 `main` 字段(`dist/index.js`,是 CLI、没有插件定义)解析,模块加载失败(#3976)。正确写法是在一个目录里放一行重导出,再把配置的 `plugins` 列表指向这个目录: + + ```js + // /index.js + export { default } from "<全局安装的绝对路径>/dist/agent/opencode-native.js"; + ``` + + ```json + { "plugins": [""] } + ``` + + 两个版本都要做两件 bili 安装器会替你做的事:在同一份配置里设 `"compaction": { "auto": false }`(否则 OpenCode 的原生自动压缩会双重压缩),并先手工备份该配置文件。 - **claude:** 本仓库同时是一个 Claude Code 插件市场 —— `/plugin marketplace add ranxianglei/billion-context`,再 `/plugin install billion-context@billion-context`,然后运行 `/billion-context:bili-setup`(它会替你驱动 `bili plugin install claude` 并提示重启)。终态与 bili 安装器一致;插件自身不携带 hooks 或 MCP 条目,不会双重注册。 pi / omp / kimi / claude 没有客户端侧通道 —— 它们的配置条目由 `bili plugin install ` 代写(kimi 的声明式 `kimi.plugin.json` + 注册记录、claude 的受管 settings 块等)。 diff --git a/docs/clients.md b/docs/clients.md index 36e45a899e..f6b89c695b 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -882,7 +882,7 @@ the V1 shape and 2.x hosts load the V2 `setup()`. The standalone [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) extension is V1-only and does **not** load under 2.x — for OpenCode 2.x, billion-context is the recommended context manager. Everything below is verified end-to-end -on `@opencode/cli` 2.0.3 (V1 lane: 1.14.46 and 1.18.31). +on `@opencode/cli` 2.1.0 (V1 lane: 1.14.46 and 1.18.31). | Path | Command | When | |---|---|---| @@ -935,13 +935,20 @@ Registers a self-spawning plugin in your real opencode config and sets face is added by default (the native plugin already provides the bili tools, session-bound); pass `--with-mcp` to add one — the entry then carries no origin pin, so it survives the plugin's ephemeral-port proxy restarts (#926). -Entry form depends on how THIS bili was installed: an **npm install** writes -the bare package name (`"plugin": ["billion-context"]`) — the package -publishes `exports["./server"]` → `dist/agent/opencode-native.js`, so -opencode loads it through its own Npm.add machinery; zero absolute paths, portable. (That exact bare-name entry doubles as a hand-install without bili — see README Quickstart Option 1.) A **git checkout / dev build** falls back to a local shim dir -(`/plugins/billion-context/index.js` → this checkout's -`dist/agent/opencode-native.js`) — machine-local by construction; re-running -install from an npm install migrates the entry back to the bare name. +Entry form depends on the host generation AND how THIS bili was installed. +An **OpenCode 1.x npm install** writes the bare package name +(`"plugin": ["billion-context"]`) — the package publishes +`exports["./server"]` → `dist/agent/opencode-native.js`, so opencode loads +it through its own Npm.add machinery; zero absolute paths, portable. (That +exact bare-name entry doubles as a hand-install without bili — see README +Quickstart Option 1.) On an **OpenCode 2.x host** — and for any **git +checkout / dev build** — the installer writes a local shim dir instead +(`/plugins/billion-context/index.js` → this install's +`dist/agent/opencode-native.js`): 2.x resolves a bare package name through +the package `main` field (`dist/index.js`, the CLI — no plugin definition), +so the bare name never loads there (#3976); re-running install (or a reinstall +to a new path) regenerates the shim to point at the current root, and a +legacy bare-name entry in a 2.x config is migrated to the shim automatically. At load the plugin bootstraps its own proxy (attaches to a healthy instance instead of doubling; parent-pid watchdog kills it when opencode exits), diff --git a/docs/clients.zh-CN.md b/docs/clients.zh-CN.md index 6b1fc8c5e9..5638c7288a 100644 --- a/docs/clients.zh-CN.md +++ b/docs/clients.zh-CN.md @@ -284,7 +284,7 @@ bili 只压缩路径匹配已知 wire 协议(`/chat/completions`、`/llm_raw_cha ## OpenCode -同一个内置插件同时服务两代 OpenCode:agent 文件同时保留 V1 `server()` 与 V2 `setup()` 导出 —— ≥ 1.18.29 的 1.x 宿主加载 V1 形状,2.x 宿主加载 V2 `setup()`。独立扩展 [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) 仅支持 V1,在 2.x 下**不加载** —— 对 OpenCode 2.x,**billion-context 是推荐的上下文管理方案**。以下均在 `@opencode/cli` 2.0.3 上端到端验证过(V1 泳道:1.14.46 与 1.18.31)。 +同一个内置插件同时服务两代 OpenCode:agent 文件同时保留 V1 `server()` 与 V2 `setup()` 导出 —— ≥ 1.18.29 的 1.x 宿主加载 V1 形状,2.x 宿主加载 V2 `setup()`。独立扩展 [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) 仅支持 V1,在 2.x 下**不加载** —— 对 OpenCode 2.x,**billion-context 是推荐的上下文管理方案**。以下均在 `@opencode/cli` 2.1.0 上端到端验证过(V1 泳道:1.14.46 与 1.18.31)。 | 路径 | 命令 | 适用 | |---|---|---| @@ -304,7 +304,7 @@ HTTPS 走证书 MITM,HTTP 走临时 `opencode.json` 副本(`/bili/` 改写;JSONC ### 原生(免启动器)—— `bili plugin install opencode` -在真实 opencode 配置里注册一个自拉起插件并设 `compaction.auto: false`,之后直接跑 `opencode` 即可。默认不加 MCP 面(原生插件已提供会话绑定的 bili 工具);需要就传 `--with-mcp` —— 该条目不带 origin 钉扎,能扛过插件临时端口的代理重启(#926)。条目形态取决于**本 bili 自身的安装来源**:**npm 安装**写裸包名(`"plugin": ["billion-context"]`)—— 包经 `exports["./server"]` → `dist/agent/opencode-native.js` 暴露插件入口,opencode 用自己的 Npm.add 机制加载、自行管理安装与升级;零绝对路径、可跨机。(这个裸包名条目也可以不经 bili 直接手写进配置 —— 见 README 快速上手 方式 1。)**git checkout / 开发构建**回退到本机 shim 目录(`/plugins/billion-context/index.js` → 该 checkout 的 `dist/agent/opencode-native.js`)—— 按构造即机器本地;之后改用 npm 安装再跑一次 install 会把条目迁回裸包名。 +在真实 opencode 配置里注册一个自拉起插件并设 `compaction.auto: false`,之后直接跑 `opencode` 即可。默认不加 MCP 面(原生插件已提供会话绑定的 bili 工具);需要就传 `--with-mcp` —— 该条目不带 origin 钉扎,能扛过插件临时端口的代理重启(#926)。条目形态取决于**宿主代次**和**本 bili 自身的安装来源**。**OpenCode 1.x + npm 安装**写裸包名(`"plugin": ["billion-context"]`)—— 包经 `exports["./server"]` → `dist/agent/opencode-native.js` 暴露插件入口,opencode 用自己的 Npm.add 机制加载、自行管理安装与升级;零绝对路径、可跨机。(这个裸包名条目也可以不经 bili 直接手写进配置 —— 见 README 快速上手 方式 1。)在 **OpenCode 2.x 宿主**上 —— 以及任何 **git checkout / 开发构建** —— 改写本机 shim 目录(`/plugins/billion-context/index.js` → 本次安装的 `dist/agent/opencode-native.js`):2.x 按包的 `main` 字段(`dist/index.js`,是 CLI、没有插件定义)解析裸包名,所以裸包名在那里永远加载不出来(#3976);重跑 install(或重装到新路径)会重新生成指向当前根的 shim,2.x 配置里遗留的裸包名条目也会被自动迁移为 shim。 加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `/bili/`,暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该条目整体跳过(代理归启动器管)。 diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 46e3ac3978..3e46c60eed 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -1378,10 +1378,13 @@ function stripLegacyOpencodeAcp(data: Record, notes: string[], // #925: how THIS bili was installed decides which plugin entry install can // publish. An npm-form install (package root under node_modules — npm/pnpm/ -// yarn, both path-separator styles) ships its entry through package.json -// exports["./server"], so opencode loads the bare package name via its own -// Npm.add machinery (host-managed install + upgrade, portable config). Any -// other form (git checkout / dev build) has no published entry — local shim dir. +// yarn, both path-separator styles) CAN ship its entry through package.json +// exports["./server"] as the bare package name (host-managed install + +// upgrade, portable config) — but ONLY on OpenCode 1.x hosts. On 2.x hosts +// the bare name resolves to the package MAIN field on some platforms +// (Windows: dist/index.js — the CLI, no default export → LoadError, #3976), +// so every 2.x install writes the local shim dir instead. Any non-npm form +// (git checkout / dev build) has no published entry — local shim dir too. export function isNpmInstallForm(root: string): boolean { return /(^|[/\\])node_modules[/\\]/.test(root); } @@ -1390,6 +1393,8 @@ export const OPENCODE_NPM_ENTRY = "billion-context"; const DEV_FORM_NOTE = "dev form: machine-local shim, not portable across machines — an npm install writes the bare package name instead"; +const V2_NPM_SHIM_NOTE = "OpenCode 2.x host: machine-local shim dir instead of the bare package name — 2.x loads bare names via the package main field, which is not the plugin (#3976)"; + // #925: pick + apply the plugin entry for this install form. Replaces any // existing entry of either form (single owner), returns note(s). #927: the // entry lands in the host's effective key (`plugin` on OpenCode 1.x, @@ -1400,13 +1405,21 @@ const DEV_FORM_NOTE = "dev form: machine-local shim, not portable across machine // scalars) are preserved verbatim in form and position. A strings-only // projection must never be written back, and "plugin present" must mean // the key was left untouched (no rewrite of the surrounding file either). +// #3976: the ENTRY FORM is decided by install form AND host major version — +// the `plugins` key is written only for 2.x hosts (#927 pickPluginKey), so +// key === "plugins" is the 2.x gate: every 2.x install (npm or dev form) +// writes the shim dir, because a bare package name resolves to the package +// main field (dist/index.js — the CLI, no default export) on 2.x hosts such +// as Windows and loads no plugin at all. 1.x keeps the portable bare name +// for npm-form installs; dev form always shims (no published entry). export function applyOpencodePluginEntry(args: { data: Record; root: string; shimDir: string; agentJs: string; key?: "plugin" | "plugins"; touched?: Set }): string[] { const { data, root, shimDir, agentJs } = args; const key = args.key ?? "plugin"; const touched = args.touched ?? new Set(); const ours = [OPENCODE_NPM_ENTRY, shimDir]; const npmForm = isNpmInstallForm(root); - const entry = npmForm ? OPENCODE_NPM_ENTRY : shimDir; + const useShim = !npmForm || key === "plugins"; + const entry = useShim ? shimDir : OPENCODE_NPM_ENTRY; const isOurs = (x: unknown): boolean => typeof x === "string" && ours.includes(x); const raw = data[key]; const oursIn = (): string[] => { @@ -1415,10 +1428,15 @@ export function applyOpencodePluginEntry(args: { data: Record; return []; }; const replaced = oursIn(); - if (npmForm && replaced.includes(shimDir)) fs.rmSync(shimDir, { recursive: true, force: true }); - if (!npmForm) { + if (!useShim && replaced.includes(shimDir)) fs.rmSync(shimDir, { recursive: true, force: true }); + if (useShim) { fs.mkdirSync(shimDir, { recursive: true }); - fs.writeFileSync(path.join(shimDir, "index.js"), `export { default } from ${JSON.stringify(agentJs)};\n`); + // Rewrite whenever the content drifts from THIS root (a reinstall to + // a new path must heal a stale shim even when the config entry is + // already present and left untouched below). + const idx = path.join(shimDir, "index.js"); + const want = `export { default } from ${JSON.stringify(agentJs)};\n`; + if (!fs.existsSync(idx) || fs.readFileSync(idx, "utf8") !== want) fs.writeFileSync(idx, want); } // Exactly our one entry, already the right form — nothing to migrate: // leave the key (and the file) untouched. @@ -1434,12 +1452,13 @@ export function applyOpencodePluginEntry(args: { data: Record; data[key] = [entry]; } touched.add(key); - if (npmForm) { - if (replaced.length === 0) return [`plugin -> ${OPENCODE_NPM_ENTRY}`]; - return [`plugin -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`]; + if (!useShim) { + if (replaced.length === 0) return [`${key} -> ${OPENCODE_NPM_ENTRY}`]; + return [`${key} -> ${OPENCODE_NPM_ENTRY} (replaced ${replaced.join(", ")})`]; } - if (replaced.length === 0) return [`plugin -> ${shimDir}`, DEV_FORM_NOTE]; - return [`plugin -> ${shimDir} (replaced ${replaced.join(", ")})`, DEV_FORM_NOTE]; + const note = npmForm ? V2_NPM_SHIM_NOTE : DEV_FORM_NOTE; + if (replaced.length === 0) return [`${key} -> ${shimDir}`, note]; + return [`${key} -> ${shimDir} (replaced ${replaced.join(", ")})`, note]; } function opencodeInstall(withMcp = false): string { @@ -1501,9 +1520,10 @@ function opencodeInstall(withMcp = false): string { } } - // Native plugin (#820/#925): self-spawned proxy + http.request URL rewrite. - // Entry form depends on how THIS bili was installed — npm → bare package - // name (exports["./server"], host-managed), checkout/dev → local shim dir. + // Native plugin (#820/#925/#3976): self-spawned proxy + http.request URL + // rewrite. Entry form: OpenCode 1.x + npm install → bare package name + // (host-managed, portable); every 2.x install and any dev-form install → + // local shim dir (bare names do not load under 2.x hosts, #3976). const root = selfPackageRoot(); const agentJs = path.join(root, "dist", "agent", "opencode-native.js"); requireDistFile(agentJs); @@ -2635,6 +2655,18 @@ async function updateLane(agent: PluginAgent, opts: PluginUpdateOpts, log: (leve return [`opencode: the cache copy is bili-owned and self-updates in place through its own proxy${where}${v} (#1234) — this command does NOT run opencode's upgrade; OpenCode v2 'plugin update' is an extra manual channel, and reload/restart OpenCode after a disk update to activate it`]; } if (PLUGIN_KEYS.some((k) => pluginEntries(data, k).some((p) => p === dir))) { + // #3976: on 2.x hosts even npm installs use the shim — tell the + // user which root the shim re-exports before prescribing a fix. + let target: string | undefined; + try { + const m = /from\s+"([^"]+)"/.exec(fs.readFileSync(path.join(dir, "index.js"), "utf8")); + if (m) target = m[1]; + } catch {} + if (target !== undefined && isNpmInstallForm(target)) { + const ver = pkgVersionAt(path.dirname(path.dirname(path.dirname(target)))); + const v = ver !== undefined ? ` v${ver}` : ""; + return [`opencode: the shim points at the npm install${v} (#3976) — it self-updates in place through its own proxy; reload/restart OpenCode after a disk update to activate it`]; + } return ["opencode: plugin points at this checkout — rebuild the checkout (`npm run build`) to pick up changes"]; } return ["opencode: not installed"]; diff --git a/tests/plugin-install-opencode.test.ts b/tests/plugin-install-opencode.test.ts index 5daa73f79b..7379188a64 100644 --- a/tests/plugin-install-opencode.test.ts +++ b/tests/plugin-install-opencode.test.ts @@ -63,6 +63,48 @@ test("applyOpencodePluginEntry: npm form is idempotent", () => { assert.deepEqual(args.data.plugin, [OPENCODE_NPM_ENTRY]); }); +test("applyOpencodePluginEntry: 2.x host (plugins key) writes the shim dir even for npm form (#3976)", () => { + const args = entryArgs(NPM_ROOT, tempDir("bili-oc-v2npm-")); + const notes = applyOpencodePluginEntry({ ...args, key: "plugins" }); + assert.deepEqual(args.data.plugins, [args.shimDir]); + assert.equal(notes[0], `plugins -> ${args.shimDir}`); + assert.match(notes[1], /#3976/); + const shim = fs.readFileSync(path.join(args.shimDir, "index.js"), "utf8"); + assert.equal(shim, `export { default } from ${JSON.stringify(args.agentJs)};\n`); +}); + +test("applyOpencodePluginEntry: 2.x host migrates a legacy bare-name entry to the shim dir (#3976)", () => { + const args = entryArgs(NPM_ROOT, tempDir("bili-oc-v2migrate-")); + args.data.plugins = ["other-pkg", OPENCODE_NPM_ENTRY]; + const notes = applyOpencodePluginEntry({ ...args, key: "plugins" }); + assert.deepEqual(args.data.plugins, ["other-pkg", args.shimDir]); + assert.equal(notes[0], `plugins -> ${args.shimDir} (replaced ${OPENCODE_NPM_ENTRY})`); + assert.match(notes[1], /#3976/); + assert.ok(fs.existsSync(path.join(args.shimDir, "index.js")), "shim written"); +}); + +test("applyOpencodePluginEntry: 2.x shim entry is idempotent", () => { + const args = entryArgs(NPM_ROOT, tempDir("bili-oc-v2idem-")); + args.data.plugins = [args.shimDir]; + fs.mkdirSync(args.shimDir, { recursive: true }); + fs.writeFileSync(path.join(args.shimDir, "index.js"), `export { default } from ${JSON.stringify(args.agentJs)};\n`); + const touched = new Set(); + assert.deepEqual(applyOpencodePluginEntry({ ...args, key: "plugins", touched }), ["plugins present"]); + assert.equal(touched.size, 0, "no key touched — no rewrite"); +}); + +test("applyOpencodePluginEntry: a stale shim is healed even when the config entry is already present", () => { + const base = tempDir("bili-oc-stale-"); + const args = entryArgs(NPM_ROOT, base); + const staleAgentJs = "/opt/old-bili/dist/agent/opencode-native.js"; + fs.mkdirSync(args.shimDir, { recursive: true }); + fs.writeFileSync(path.join(args.shimDir, "index.js"), `export { default } from ${JSON.stringify(staleAgentJs)};\n`); + args.data.plugins = [args.shimDir]; + assert.deepEqual(applyOpencodePluginEntry({ ...args, key: "plugins" }), ["plugins present"]); + const shim = fs.readFileSync(path.join(args.shimDir, "index.js"), "utf8"); + assert.equal(shim, `export { default } from ${JSON.stringify(args.agentJs)};\n`, "shim re-export follows the current root"); +}); + test("applyOpencodePluginEntry: dev form writes a local shim and warns it is not portable", () => { const args = entryArgs("/opt/checkout-bili", tempDir("bili-oc-dev-")); const notes = applyOpencodePluginEntry(args); @@ -106,11 +148,13 @@ test("applyOpencodePluginEntry: map-form plugins keep foreign options and stay a const args = entryArgs(NPM_ROOT, tempDir("bili-oc-map-")); args.data.plugins = { "@org/x": { options: { z: 1 } }, "plain-y": true }; applyOpencodePluginEntry({ ...args, key: "plugins" }); - assert.deepEqual(args.data.plugins, { "@org/x": { options: { z: 1 } }, "plain-y": true, [OPENCODE_NPM_ENTRY]: true }); + // #3976: the `plugins` key means a 2.x host — even an npm-form install + // lands as the shim dir there, so the map carries the dir, not the name. + assert.deepEqual(args.data.plugins, { "@org/x": { options: { z: 1 } }, "plain-y": true, [args.shimDir]: true }); assert.ok(!Array.isArray(args.data.plugins), "map form preserved"); }); -type OcCfg = { plugin?: unknown; compaction?: { auto?: boolean } & Record; mcp?: unknown }; +type OcCfg = { plugin?: unknown; plugins?: unknown; compaction?: { auto?: boolean } & Record; mcp?: unknown }; test("pluginInstall/remove/status opencode end-to-end (dev form under tsx)", (t) => { const prevXdg = process.env.XDG_CONFIG_HOME; @@ -181,6 +225,59 @@ test("pluginInstall/remove/status opencode end-to-end (dev form under tsx)", (t) assert.match(pluginRemove("opencode"), /not installed/); }); +test("pluginInstall opencode under a 2.x host writes the plugins key + shim dir (#3976)", (t) => { + if (process.platform === "win32") { + t.skip("probe stub is a POSIX shell script"); + return; + } + const prevXdg = process.env.XDG_CONFIG_HOME; + const prevState = process.env.XDG_STATE_HOME; + const prevOpen = process.env.OPENCODE_CONFIG; + const prevBin = process.env.BILI_CLIENT_BIN; + delete process.env.OPENCODE_CONFIG; + const xdg = tempDir("bili-oc-v2xdg-"); + const state = tempDir("bili-oc-v2state-"); + process.env.XDG_CONFIG_HOME = xdg; + process.env.XDG_STATE_HOME = state; + const bin = path.join(xdg, "fake-opencode"); + fs.writeFileSync(bin, "#!/bin/sh\necho 'opencode 2.1.0'\n"); + fs.chmodSync(bin, 0o755); + process.env.BILI_CLIENT_BIN = bin; + t.after(() => { + if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME; + else process.env.XDG_CONFIG_HOME = prevXdg; + if (prevState === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prevState; + if (prevOpen === undefined) delete process.env.OPENCODE_CONFIG; + else process.env.OPENCODE_CONFIG = prevOpen; + if (prevBin === undefined) delete process.env.BILI_CLIENT_BIN; + else process.env.BILI_CLIENT_BIN = prevBin; + rmrf(xdg); + rmrf(state); + }); + + const file = path.join(xdg, "opencode", "opencode.json"); + const shimDir = path.join(xdg, "opencode", "plugins", "billion-context"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ model: "anthropic/claude" }, null, 2)); + + const out = pluginInstall("opencode"); + assert.ok(out.startsWith(`opencode: installed -> ${file}`), out); + assert.match(out, /plugins -> .+plugins[\\/]billion-context/); + const cfg = JSON.parse(fs.readFileSync(file, "utf8")) as OcCfg; + assert.deepEqual(cfg.plugins, [shimDir]); + assert.equal(cfg.plugin, undefined, "no singular-key entry on a 2.x host"); + assert.equal(cfg.compaction?.auto, false); + assert.ok(fs.existsSync(path.join(shimDir, "index.js")), "shim written"); + assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "installed"); + + const rem = pluginRemove("opencode"); + assert.match(rem, /plugin removed \(/); + const after = JSON.parse(fs.readFileSync(file, "utf8")) as OcCfg; + assert.equal(after.plugins, undefined); + assert.equal(fs.existsSync(shimDir), false); +}); + const MCP_PINNED = { type: "local", command: ["/usr/bin/node", "/opt/old/dist/mcp.js"], environment: { BILI_MCP_PROXY: "http://127.0.0.1:18787" }, enabled: true }; type OcMcpCfg = { plugin?: unknown; mcp?: { bili?: Record } & Record };