diff --git a/README.md b/README.md index 6f25bee154..7c5e98af97 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,14 @@ Pick by your client: | **omp** | [`billion-context`](https://github.com/ranxianglei/billion-context) via `bili omp` (built-in plugin) | | **everything else** (no context hook) | [`billion-context`](https://github.com/ranxianglei/billion-context) — `bili ` (launcher, preferred) or `/bili/` prefix | -**Native mode vs standalone extensions.** The host-native plugins (`bili plugin install pi` / `opencode` — they spawn the proxy inside the host process) and the standalone in-process extensions (`billion-context-pi`, `opencode-acp`) are **mutually exclusive**: both active means double compression. The installer makes the switch (`bili plugin install pi` replaces the legacy `npm:billion-context-pi` entry). As a runtime safety net for manual installs, the native entries set `BILLION_CONTEXT_NATIVE=` synchronously at load so a standalone extension can stand down at action time — its own load-time `BILLION_CONTEXT_PROXY` check cannot see a proxy that native mode spawns asynchronously, and its `/bili/` baseUrl check never sees the fetch-layer rewrite. +**Native mode vs standalone extensions.** The host-native plugins (`bili plugin install pi` / `opencode` — they spawn the proxy inside the host process) and the standalone in-process extensions (`billion-context-pi`, `opencode-acp`) are **mutually exclusive**: both active means double compression. The installer makes the switch: `bili plugin install pi` replaces the legacy `npm:billion-context-pi` entry, and `bili plugin install opencode` strips legacy `opencode-acp` entries from the global opencode.json — bare name, `npm:` alias, versioned (`opencode-acp@stable`), or path form, array or object shape; the original config is snapshotted to `opencode.json.bili-bak`. A **project-local** install (`opencode plugin opencode-acp` writes `/.opencode/opencode.json`, not the global config) is not touched — remove it by hand; the installer note reminds you. As a runtime safety net for manual installs, the native entries set `BILLION_CONTEXT_NATIVE=` synchronously at load so a standalone extension can stand down at action time — its own load-time `BILLION_CONTEXT_PROXY` check cannot see a proxy that native mode spawns asynchronously, and its `/bili/` baseUrl check never sees the fetch-layer rewrite. + +**Legacy sessions from opencode-acp (v1 lane routing).** On OpenCode 1.x, `bili plugin install opencode` keeps pre-migration sessions WORKING: the native entry absorbs the installed `opencode-acp` package (imported directly from `node_modules` — `.opencode/node_modules`, project `node_modules`, global npm root, or opencode's config-scope modules, first hit wins) and routes per session. A session is legacy iff opencode-acp's persisted state file exists (`/opencode/storage/plugin/acp/.json`): + +- **Legacy session** — compression runs through the absorbed opencode-acp (its own `` refs and block store keep working: `compress` / `decompress` / `search_context` / `acp_status` / `acp_context_recap` all execute in it). Its model requests carry `x-bili-plugin-bypass: 1`, and the proxy forwards them VERBATIM — no wire injection, no nudge, no session binding. +- **New session** — bili owns it: tool calls forward to the proxy's plugin endpoints (plugin mode). The tool slots the model sees carry the DCP schemas (one def per name process-wide on v1), but the executor routes by session lane, so a new session's `compress` reaches the proxy while a legacy session's reaches opencode-acp. `acp_context_recap` has no proxy counterpart — on new sessions the proxy answers it with its unknown-tool message. + +`/acp` and `/dcp` route the same way. Adoption of new sessions into opencode-acp's registry is prevented by gating its transforms (system / messages / text.complete) on the legacy predicate. Degradation: when the opencode-acp package is absent or fails to import, bili runs alone and legacy sessions behave as read-only archives (old `` tags render, `decompress` returns `[Block … not found]`, new refs restart from m00001). ## Install diff --git a/README.zh-CN.md b/README.zh-CN.md index 7208e2f530..5639f55535 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -83,7 +83,14 @@ AI 编程助手的通用上下文压缩代理 | **omp** | [`billion-context`](https://github.com/ranxianglei/billion-context),`bili omp`(内置插件) | | **其余所有**(没有上下文 hook) | [`billion-context`](https://github.com/ranxianglei/billion-context) —— `bili `(启动器,优先)或 `/bili/` 前缀 | -**原生模式 vs 独立扩展。** 宿主原生插件(`bili plugin install pi` / `opencode` —— 代理在宿主进程内拉起)与独立进程内扩展(`billion-context-pi`、`opencode-acp`)**互斥**:两者同时生效意味着双重压缩。安装器负责切换(`bili plugin install pi` 会替换旧的 `npm:billion-context-pi` 条目);作为手动安装的运行期安全网,原生入口在加载时同步设置 `BILLION_CONTEXT_NATIVE=`,让独立扩展在动作时自动退出 —— 它自己的加载期 `BILLION_CONTEXT_PROXY` 检查看不见原生模式异步拉起的代理,`/bili/` baseURL 检查也看不见 fetch 层改写。 +**原生模式 vs 独立扩展。** 宿主原生插件(`bili plugin install pi` / `opencode` —— 代理在宿主进程内拉起)与独立进程内扩展(`billion-context-pi`、`opencode-acp`)**互斥**:两者同时生效意味着双重压缩。安装器负责切换:`bili plugin install pi` 会替换旧的 `npm:billion-context-pi` 条目;`bili plugin install opencode` 会从全局 opencode.json 里剔除旧的 `opencode-acp` 条目 —— 裸名、`npm:` 别名、带版本号(`opencode-acp@stable`)、路径形式都认,数组/对象两种形态都处理;原配置会快照到 `opencode.json.bili-bak`。**项目级**安装(`opencode plugin opencode-acp` 写的是 `/.opencode/opencode.json`,不是全局配置)不会被碰 —— 需手动移除,安装器输出里会提醒。作为手动安装的运行期安全网,原生入口在加载时同步设置 `BILLION_CONTEXT_NATIVE=`,让独立扩展在动作时自动退出 —— 它自己的加载期 `BILLION_CONTEXT_PROXY` 检查看不见原生模式异步拉起的代理,`/bili/` baseURL 检查也看不见 fetch 层改写。 + +**从 opencode-acp 迁移旧会话(v1 泳道路由)。** 在 OpenCode 1.x 上,`bili plugin install opencode` 让迁移前的旧会话继续可用:原生入口会吸收已安装的 `opencode-acp` 包(直接从 `node_modules` 导入 —— `.opencode/node_modules`、项目 `node_modules`、全局 npm root、opencode 配置级 modules,先到先得),并按会话路由。会话属于 legacy ⟺ opencode-acp 的持久化状态文件存在(`/opencode/storage/plugin/acp/.json`): + +- **旧会话** —— 压缩由被吸收的 opencode-acp 执行(它自己的 `` 引用号与块存储照常工作:`compress` / `decompress` / `search_context` / `acp_status` / `acp_context_recap` 全部在它里面执行)。其模型请求带 `x-bili-plugin-bypass: 1`,代理原样转发 —— 不注入 wire 工具、不注 nudge、不绑定会话。 +- **新会话** —— bili 接管:工具调用转发到代理的 plugin 端点(plugin 模式)。模型看到的工具槽位带 DCP schema(v1 进程级每个名字仅一份定义),但执行器按会话分泳道:新会话的 `compress` 发到代理,旧会话的发给 opencode-acp。`acp_context_recap` 没有代理端对应 —— 新会话调用会收到代理的 unknown-tool 消息。 + +`/acp` 与 `/dcp` 同样路由。新会话被 opencode-acp 注册表收编的可能被其 transform 门控(system / messages / text.complete 都过 legacy 谓词)阻断。退化路径:opencode-acp 包缺失或导入失败时 bili 单独运行,旧会话退化为只读存档(旧 `` 标签照常渲染、`decompress` 返回 `[Block … not found]`、新引用号从 m00001 重新开始)。 ## 安装 diff --git a/src/agent/opencode-legacy.ts b/src/agent/opencode-legacy.ts new file mode 100644 index 0000000000..51890a1d89 --- /dev/null +++ b/src/agent/opencode-legacy.ts @@ -0,0 +1,176 @@ +// opencode-acp absorption for LEGACY V1 sessions (#920). +// +// Users migrating from the standalone `opencode-acp` extension (DCP protocol, +// its own ref space + block store) to `bili plugin install opencode` still +// need their OLD sessions to work: those sessions' history is annotated with +// `` tags and their refs live in acp's store — bili's kernel +// cannot serve them. Routing requirement: legacy sessions keep running +// through opencode-acp, new sessions go through bili. +// +// Probed facts (opencode-acp 1.18.x, ~/projects/opencode-acp): +// - package exports ONLY `default server` (index.ts); `server(ctx)` returns +// `{}` immediately when BILLION_CONTEXT_PROXY is set — the env is checked +// ONLY there (index.ts:38); executors never re-check it, so calling +// `server(ctx)` with the env temporarily unset yields the armed hooks. +// - its `config` hook self-disables the whole plugin when any provider +// baseURL contains `/bili/` (findBiliProxyProviders) AND denies the tools +// via permission.deny — so we call it with `provider` hidden and merge +// back only the keys it legitimately owns (permission / command / +// experimental.primary_tools / agent snapshot side effects). +// - adoption of NEW sessions happens in messages.transform via +// registry.getOrCreate(lastUserMessage.info.sessionID) — gating that hook +// (and system.transform / text.complete) on legacy state keeps new +// sessions out of acp's registry entirely. +// - legacy session marker: acp's persisted state file at +// `/opencode/storage/plugin/acp/.json` +// (getDefaultStorageDir, lib/state/persistence.ts:67). config storagePath +// overrides are NOT probed (documented limitation). +// - tool args are kernel-compatible: compress `content: +// [{topic,startId,endId,summary}]` is the kernel's accepted object form +// (verified: parseCompressArgs maps startId/endId → ranges[].startRef/ +// endRef), decompress/search_context/acp_status args match the kernel +// shapes — so NEW-session calls can be forwarded to the proxy verbatim +// with zero translation. `acp_context_recap` has no proxy counterpart +// (rejected by /__bili/plugin/tool) — legacy-only, documented. +// - the v1 host loads tool defs from the hooks table statically; ONE def +// per name process-wide. The slots therefore carry acp's DCP schemas for +// everyone, and the WRAPPED executors route per session: legacy → acp +// executor, new → forwardTool to the proxy (plugin-mode carrier). +// +// Degradation: package not found / import fails / unexpected shape → the +// caller falls back to bili's own V1 tools (current behavior); legacy +// sessions then degrade as documented (read-only archives). + +import { existsSync, readdirSync } from "node:fs"; +import { homedir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +export interface LegacyAcpToolDef { + description?: unknown; + args?: unknown; + execute?: (args: Record, ctx: { sessionID: string; messageID?: string }) => Promise; +} + +export interface LegacyAcpModule { + /** acp's full hooks table (config/tool/hooks keys as returned by server()). */ + hooks: Record; + /** hooks.tool — the DCP tool slots (compress/decompress/search_context/acp_status/acp_context_recap). */ + tools: Record; + /** hooks.config — must be called with `provider` hidden (self-disable neutered). */ + configHook: ((cfg: Record) => Promise) | undefined; + /** hooks["command.execute.before"] — /acp + /dcp handler for legacy sessions. */ + commandHook: ((input: { command: string; sessionID: string; arguments?: string }, output?: { parts?: unknown[] }) => Promise) | undefined; + /** resolved dist/index.js path (for logs). */ + source: string; +} + +/** Candidate `opencode-acp/dist/index.js` paths, most specific first: + * project plugin scope, plain project node_modules, opencode's v1 package + * cache (`opencode plugin opencode-acp` — global AND project installs land + * in `~/.cache/opencode/packages/opencode-acp@/node_modules`; every + * version present is offered, newest first), global user npm root, and + * opencode's config-scope node_modules. */ +export function legacyAcpCandidates(cwd: string | undefined): string[] { + const dirs: string[] = []; + if (cwd !== undefined && cwd.length > 0) { + dirs.push(path.join(cwd, ".opencode", "node_modules")); + dirs.push(path.join(cwd, "node_modules")); + } + const out: string[] = []; + const pushDir = (d: string): void => { + out.push(path.join(d, "opencode-acp", "dist", "index.js")); + }; + for (const d of dirs) pushDir(d); + const cacheHome = process.env.XDG_CACHE_HOME ?? path.join(homedir(), ".cache"); + const packages = path.join(cacheHome, "opencode", "packages"); + try { + const versions = readdirSync(packages) + .filter((e) => e.startsWith("opencode-acp@")) + .sort() + .reverse(); + for (const v of versions) { + pushDir(path.join(packages, v, "node_modules")); + } + } catch { + // no package cache + } + pushDir(path.join(homedir(), ".local", "lib", "node_modules")); + pushDir(path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode", "node_modules")); + return out; +} + +/** acp's default persisted-state location for a session id. */ +export function legacyAcpStatePath(sessionId: string): string { + const dataHome = process.env.XDG_DATA_HOME ?? path.join(homedir(), ".local", "share"); + return path.join(dataHome, "opencode", "storage", "plugin", "acp", `${sessionId}.json`); +} + +/** A session is legacy iff acp has a state file for it. Ids are sanitized + * (no separators, bounded length) before touching the filesystem. */ +export function isLegacyAcpSession(sessionId: string | undefined): boolean { + if (sessionId === undefined || sessionId.length === 0 || sessionId.length > 200) return false; + if (/[/\\\s]/.test(sessionId)) return false; + try { + return existsSync(legacyAcpStatePath(sessionId)); + } catch { + return false; + } +} + +export async function loadLegacyAcp(ctx: { directory?: string; client?: unknown }, log: (msg: string) => void = () => {}): Promise { + let found: string | undefined; + for (const p of legacyAcpCandidates(ctx.directory)) { + if (existsSync(p)) { + found = p; + break; + } + } + if (found === undefined) return undefined; + // acp's server() refuses to arm when BILLION_CONTEXT_PROXY is set; the + // check runs only at entry, so it is unset strictly around the call and + // restored in finally. Concurrent readers on this event loop see either + // value only across our own awaits here. + const prev = process.env.BILLION_CONTEXT_PROXY; + try { + if (prev !== undefined) delete process.env.BILLION_CONTEXT_PROXY; + const mod = (await import(pathToFileURL(found).href)) as { default?: unknown }; + const server = mod.default; + if (typeof server !== "function") { + log(`[bili-opencode-native] legacy: ${found} exports no server function — ignored`); + return undefined; + } + const hooks = (await (server as (c: unknown) => Promise>)(ctx)) ?? {}; + if (typeof hooks !== "object") return undefined; + const toolsRaw = hooks.tool; + const tools = toolsRaw !== null && typeof toolsRaw === "object" && !Array.isArray(toolsRaw) ? (toolsRaw as Record) : {}; + if (Object.keys(tools).length === 0) { + log(`[bili-opencode-native] legacy: ${found} armed but registered no tools (acp disabled by its own config?) — ignored`); + return undefined; + } + const configHook = typeof hooks.config === "function" ? (hooks.config as LegacyAcpModule["configHook"]) : undefined; + const commandHook = typeof hooks["command.execute.before"] === "function" ? (hooks["command.execute.before"] as LegacyAcpModule["commandHook"]) : undefined; + log(`[bili-opencode-native] legacy opencode-acp absorbed from ${found} (tools: ${Object.keys(tools).join(", ")})`); + return { hooks, tools, configHook, commandHook, source: found }; + } catch (err) { + log(`[bili-opencode-native] legacy: failed to load ${found}: ${String(err)} — legacy sessions degrade to read-only`); + return undefined; + } finally { + if (prev === undefined) delete process.env.BILLION_CONTEXT_PROXY; + else process.env.BILLION_CONTEXT_PROXY = prev; + } +} + +/** Call acp's config hook without letting it see (and self-disable on) the + * /bili/-wrapped provider URLs, then merge back the top-level keys it may + * have replaced on the shadow copy (it writes via `??=`/spread-replace, so a + * reference change marks an owned write; in-place mutations already hit the + * real object). */ +export async function callLegacyAcpConfig(configHook: NonNullable, cfg: Record): Promise { + const shadow: Record = { ...cfg }; + delete shadow.provider; + await configHook(shadow); + for (const key of ["permission", "command", "experimental"] as const) { + if (shadow[key] !== cfg[key]) cfg[key] = shadow[key]; + } +} diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 11a9fcf550..eaf9b8de6e 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -69,6 +69,7 @@ import { createAcpCommandHooks } from "./opencode-acp-command.js"; import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; import { installNativeFetchIntercept, isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; +import { callLegacyAcpConfig, isLegacyAcpSession, loadLegacyAcp, type LegacyAcpModule } from "./opencode-legacy.js"; /** Decides whether the native bootstrap should run in this process. */ export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean { @@ -303,10 +304,15 @@ export interface V1Hooks { "chat.headers"?: (input: V1ChatHeadersInput, output: { headers: Record }) => Promise; "command.execute.before"?: (input: { command: string; sessionID: string; arguments?: string }, output?: { parts: unknown[] }) => Promise; tool?: Record; + event?: (input: { event?: unknown }) => Promise; + "experimental.chat.system.transform"?: (input: { sessionID?: string }, output: { system?: unknown[] }) => Promise; + "experimental.chat.messages.transform"?: (input: unknown, output: { messages?: unknown }) => Promise; + "experimental.text.complete"?: (input: { sessionID: string }, output: { text?: unknown }) => Promise; } export interface V1PluginContext { client?: import("./opencode-acp-command.js").OpencodeClient; + directory?: string; } /** JSON-schema (ACP_TOOLS_OPENAI parameters) → zod raw shape. Only the shapes @@ -398,28 +404,90 @@ export interface V1NativeDeps { z?: ZodLike; /** Tool forwarder (tests inject; runtime POSTs /__bili/plugin/tool). */ forward?: (origin: string, conversationId: string, tool: string, args: unknown) => Promise; + /** Absorbed opencode-acp for legacy sessions (#920); when present its DCP + * tool slots serve BOTH lanes (legacy → acp executor, new → forward). */ + legacy?: LegacyAcpModule; + /** Legacy-session predicate (tests inject; runtime = state file exists). */ + isLegacy?: (sessionId: string | undefined) => boolean; + log?: (msg: string) => void; } /** Build the V1 hooks for a RESOLVED proxy origin. `deps.z` present → plugin * mode (tools + header stamping); absent → proxy mode (rewrite only, the * proxy injects wire tools). Exported for tests; the `server` export below * wires the real bootstrap + zod. */ +function lastSessionFromMessages(messages: unknown): string | undefined { + if (!Array.isArray(messages)) return undefined; + for (let i = messages.length - 1; i >= 0; i--) { + const info = (messages[i] as { info?: { sessionID?: unknown } } | undefined)?.info; + if (typeof info?.sessionID === "string") return info.sessionID; + } + return undefined; +} + export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: V1NativeDeps = {}): V1Hooks { const acp = createAcpCommandHooks(() => origin, ctx); + const legacy = deps.legacy; + const isLegacy = deps.isLegacy ?? isLegacyAcpSession; + const log = deps.log ?? ((msg: string) => console.log(msg)); let windows = new Map(); const hooks: V1Hooks = { config: async (cfg) => { + if (legacy?.configHook !== undefined) { + await callLegacyAcpConfig(legacy.configHook, cfg); + } await acp.config?.(cfg); const n = rewriteV1Providers(cfg, origin); - if (n > 0) console.log(`[bili-opencode-native] v1: rewrote ${n} provider baseURL(s) -> ${origin}/bili/`); + if (n > 0) log(`[bili-opencode-native] v1: rewrote ${n} provider baseURL(s) -> ${origin}/bili/`); windows = extractV1Windows(cfg); }, - "command.execute.before": async (input, _output) => { + "command.execute.before": async (input, output) => { + if ((input.command === "acp" || input.command === "dcp") && legacy?.commandHook !== undefined && isLegacy(input.sessionID)) { + await legacy.commandHook(input, output); + return; + } await acp["command.execute.before"]?.(input); }, }; - if (deps.z !== undefined) { + if (legacy !== undefined) { + // Legacy lane (#920): route acp's own transforms to legacy sessions + // only — new sessions never enter acp's registry (no adoption). + const sys = legacy.hooks["experimental.chat.system.transform"]; + if (typeof sys === "function") { + hooks["experimental.chat.system.transform"] = async (input, output) => { + if (!isLegacy(input.sessionID)) return; + await (sys as (i: unknown, o: unknown) => Promise)(input, output); + }; + } + const msgT = legacy.hooks["experimental.chat.messages.transform"]; + if (typeof msgT === "function") { + hooks["experimental.chat.messages.transform"] = async (input, output) => { + if (!isLegacy(lastSessionFromMessages(output?.messages))) return; + await (msgT as (i: unknown, o: unknown) => Promise)(input, output); + }; + } + const textC = legacy.hooks["experimental.text.complete"]; + if (typeof textC === "function") { + hooks["experimental.text.complete"] = async (input, output) => { + if (!isLegacy(input.sessionID)) return; + await (textC as (i: unknown, o: unknown) => Promise)(input, output); + }; + } + // Event hook carries no session (acp uses it only for compress timing + // on message.part.updated) — pass through ungated, state-independent. + const evt = legacy.hooks.event; + if (typeof evt === "function") { + hooks.event = evt as V1Hooks["event"]; + } + } + if (deps.z !== undefined || legacy !== undefined) { hooks["chat.headers"] = async (input, output) => { + if (isLegacy(input.sessionID)) { + // Legacy sessions run through absorbed acp; the proxy must + // forward their traffic verbatim (no injection, no binding). + output.headers["x-bili-plugin-bypass"] = "1"; + return; + } output.headers["x-bili-plugin"] = "opencode"; output.headers["x-bili-plugin-conversation"] = input.sessionID; const model = input.model; @@ -429,18 +497,42 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: } }; const forward = deps.forward ?? ((o, conversationId, tool, args) => import("./shared.js").then((m) => m.forwardTool(o, conversationId, tool, args))); - const tools: Record = {}; - for (const t of ACP_TOOLS_OPENAI) { - const fn = t.function; - tools[fn.name] = { - description: fn.description ?? fn.name, - args: jsonSchemaToZodShape(fn.parameters, deps.z), - execute: async (args, v1ctx) => forward(origin, v1ctx.sessionID, fn.name, args), - }; + if (legacy !== undefined) { + // Tool slots carry acp's DCP schemas (kernel-parseable object form) + // for BOTH lanes; executors route per session. acp_context_recap + // has no proxy counterpart — legacy-only, forwarded calls fail + // with the endpoint's unknown-tool message (documented). + const tools: Record = {}; + for (const [name, def] of Object.entries(legacy.tools)) { + const exec = typeof def.execute === "function" ? def.execute : undefined; + tools[name] = { + description: typeof def.description === "string" ? def.description : name, + args: (def.args ?? {}) as Record, + execute: async (args, v1ctx) => { + if (exec !== undefined && isLegacy(v1ctx.sessionID)) { + return String((await exec(args, v1ctx)) ?? ""); + } + return forward(origin, v1ctx.sessionID, name, args); + }, + }; + } + hooks.tool = tools; + } else { + const tools: Record = {}; + if (deps.z !== undefined) { + for (const t of ACP_TOOLS_OPENAI) { + const fn = t.function; + tools[fn.name] = { + description: fn.description ?? fn.name, + args: jsonSchemaToZodShape(fn.parameters, deps.z), + execute: async (args, v1ctx) => forward(origin, v1ctx.sessionID, fn.name, args), + }; + } + } else { + console.error("[bili-opencode-native] v1: zod unavailable — plugin tools skipped; sessions run in proxy mode (wire-injected compress)"); + } + if (Object.keys(tools).length > 0) hooks.tool = tools; } - hooks.tool = tools; - } else { - console.error("[bili-opencode-native] v1: zod unavailable — plugin tools skipped; sessions run in proxy mode (wire-injected compress)"); } return hooks; } @@ -480,7 +572,19 @@ const server = async (ctx: V1PluginContext): Promise => { } catch { z = undefined; } - return createV1ServerHooks(origin, ctx, { z }); + // Legacy lane (#920): absorb the installed opencode-acp so pre-migration + // sessions keep their DCP machinery. Absent/failing package → undefined → + // bili-only mode (legacy sessions degrade to read-only, documented). + let legacy: LegacyAcpModule | undefined; + try { + // Pass the host's full ctx object through: V1PluginContext types only + // what bili uses (client/directory), but the runtime object may carry + // extra host fields acp's hooks need at action time. + legacy = await loadLegacyAcp(ctx, (msg) => console.log(msg)); + } catch { + legacy = undefined; + } + return createV1ServerHooks(origin, ctx, { z, legacy }); }; export default { id: "billion-context-opencode-native", setup: createOpencodeV2Setup({ route: createNativeRoute(state) }), server }; diff --git a/src/plugin-install.ts b/src/plugin-install.ts index a825ba4088..a244580d35 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -7,7 +7,8 @@ // omp ~/.omp/agent/config.yml extensions: [/dist/agent/omp.js] // claude `claude mcp add` (user scope; writes ~/.claude.json) // codex ~/.codex/config.toml [mcp_servers.bili] -// opencode ~/.config/opencode/opencode.json mcp.bili + native plugin dir + compaction.auto=false +// opencode /opencode.json{c}|config.json (highest-precedence existing; #927) +// mcp.bili + native plugin dir + compaction.auto=false // Installers throw on failure (bad/locked config, missing host CLI); the CLI // layer catches, prints `bili plugin: ` and exits 1. @@ -16,6 +17,7 @@ import path from "node:path"; import os from "node:os"; import { execFileSync } from "node:child_process"; import { fileURLToPath } from "node:url"; +import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser"; import { resolvePiHome } from "./client-config.js"; import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js"; @@ -426,12 +428,58 @@ function codexStatus(): string { // — opencode ———————————————————————————————————————————————————————————— -function opencodeJson(): string { +// #927: OpenCode reads BOTH `plugin` (1.x canonical) and `plugins` (2.x +// canonical): 2.x merges the two arrays, while 1.x hard-errors on `plugins` +// (ConfigInvalidError: unrecognized_keys). Dual-writing is off the table — +// pick ONE effective key by host major version. A failed version probe falls +// back to major 1, whose key (`plugin`) 2.x still honors as a legacy alias, +// so degradation can never write a dead config line. +export function pickPluginKey(major: number): "plugin" | "plugins" { + return major >= 2 ? "plugins" : "plugin"; +} + +const PLUGIN_KEYS = ["plugin", "plugins"] as const; + +const ocMajorCache = new Map(); + +/** Host major version via ` --version` (probe failure → 1). Same + * contract as the launcher's probe; honors the BILI_CLIENT_BIN override. */ +export function detectOpencodeMajor(): number { + const command = process.env.BILI_CLIENT_BIN?.trim() || "opencode"; + const hit = ocMajorCache.get(command); + if (hit !== undefined) return hit; + let major = 1; + try { + const out = execFileSync(command, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + const m = /(\d+)\s*\./.exec(out); + if (m) major = parseInt(m[1], 10); + } catch {} + ocMajorCache.set(command, major); + return major; +} + +function pluginEntries(data: Record, key: string): string[] { + const v = data[key]; + if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string"); + if (v !== null && typeof v === "object") return Object.keys(v as Record); + return []; +} + +// #927: write target = explicit OPENCODE_CONFIG override, else the +// highest-precedence file ALREADY PRESENT in the config dir (opencode merges +// config.json -> opencode.json -> opencode.jsonc, later wins), else create +// opencode.json. Never spawn a second file next to an existing config — that +// splits one logical config across files (#927). +export function opencodeTargetFile(): string { const raw = process.env.OPENCODE_CONFIG?.trim(); if (raw && raw.length > 0) return raw; const xdg = process.env.XDG_CONFIG_HOME?.trim(); - if (xdg && xdg.length > 0) return path.join(xdg, "opencode/opencode.json"); - return path.join(os.homedir(), ".config", "opencode", "opencode.json"); + const dir = xdg && xdg.length > 0 ? path.join(xdg, "opencode") : path.join(os.homedir(), ".config", "opencode"); + for (const name of ["opencode.jsonc", "opencode.json", "config.json"]) { + const p = path.join(dir, name); + if (fs.existsSync(p)) return p; + } + return path.join(dir, "opencode.json"); } // #820 native mode: OpenCode 2.x rejects bare FILE paths in `plugin` — the @@ -448,10 +496,133 @@ function isPlainMcpObject(v: unknown): v is Record { return v !== null && typeof v === "object" && !Array.isArray(v); } +function readOriginalText(file: string): string { + try { + return fs.readFileSync(file, "utf8"); + } catch (err) { + if ((err as { code?: string }).code === "ENOENT") return ""; + throw err; + } +} + +// JSONC-tolerant parse: the target may be an opencode.jsonc carrying comments +// (and trailing commas) — strict JSON.parse would refuse it outright, and a +// stringify round-trip would wash the comments away on write-back. Tolerance +// is bounded: ANY diagnostic beyond comments/trailing commas means the file +// is broken, and a broken config is never overwritten (§7.3). +function parseOpencodeConfig(text: string, file: string): Record { + const errors: ParseError[] = []; + const parsed = jsoncParse(text, errors, { allowTrailingComma: true }); + if (errors.length > 0 || parsed === undefined) { + const first = errors[0]; + const detail = first ? ` (offset ${first.offset})` : ""; + throw new Error(`${file}: not valid JSON${detail} — fix it or restore ${path.basename(file)}.bili-bak first; refusing to overwrite`); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`); + } + return parsed as Record; +} + +function loadOpencodeConfig(file: string): { original: string; data: Record } { + const original = readOriginalText(file); + return { original, data: original === "" ? {} : parseOpencodeConfig(original, file) }; +} + +// Write back preserving everything bili did not touch: a missing or plain-JSON +// target is serialized whole (the historical behavior); a JSONC target gets +// surgical top-level-key edits so comments and formatting elsewhere survive +// byte-for-byte (#927). A no-op run (nothing touched) leaves the file alone. +function writeOpencodeConfig(file: string, original: string, data: Record, touched: ReadonlySet): void { + if (touched.size === 0) return; + fs.mkdirSync(path.dirname(file), { recursive: true }); + backupOnce(file); + if (original === "") { + fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let strict = false; + try { + JSON.parse(original); + strict = true; + } catch {} + if (strict) { + fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n"); + return; + } + let text = original; + for (const key of touched) { + text = applyEdits(text, jsoncModify(text, [key], data[key], { formattingOptions: { tabSize: 2, insertSpaces: true } })); + } + fs.writeFileSync(file, text); +} + +// Legacy opencode-acp plugin entries — both config shapes v1 accepts: +// array: "opencode-acp" | "npm:opencode-acp" | "/opencode-acp[/index.js]" | "opencode-acp@" +// object: { "opencode-acp": "stable", ... } +// The in-process extension and the native plugin are two compression owners — +// keeping both armed means double compression / ref-space fights (#918). +// #927: strip from BOTH key spellings — a 2.x host may carry acp entries under +// `plugins`, an older v1 install under `plugin`. +function isLegacyOpencodeAcpEntry(entry: string): boolean { + if (entry === "opencode-acp" || entry.startsWith("opencode-acp@")) return true; + if (entry.startsWith("npm:")) { + const rest = entry.slice(4); + return rest === "opencode-acp" || rest.startsWith("opencode-acp@"); + } + const normalized = entry.replace(/\\/g, "/"); + const segments = normalized.split("/").filter((s) => s.length > 0); + // Any path segment naming the package identifies an acp install — covers + // dir specs, /index.js, and deeper entry paths like dist/index.js. + return segments.some((s) => s === "opencode-acp" || s.startsWith("opencode-acp@")); +} + +function stripLegacyOpencodeAcp(data: Record, notes: string[], touched: Set): void { + const removed: string[] = []; + for (const key of PLUGIN_KEYS) { + const v = data[key]; + let dropped = 0; + if (Array.isArray(v)) { + const survivors: unknown[] = []; + for (const entry of v) { + if (typeof entry === "string" && isLegacyOpencodeAcpEntry(entry)) { + removed.push(entry); + dropped++; + continue; + } + survivors.push(entry); + } + if (dropped > 0) { + if (survivors.length === 0) delete data[key]; + else data[key] = survivors; + touched.add(key); + } + } else if (v !== null && typeof v === "object") { + const map = v as Record; + for (const k of Object.keys(map)) { + if (isLegacyOpencodeAcpEntry(k)) { + delete map[k]; + removed.push(k); + dropped++; + } + } + if (dropped > 0) { + if (Object.keys(map).length === 0) delete data[key]; + touched.add(key); + } + } + } + if (removed.length > 0) { + notes.push(`replaced opencode-acp plugin entries (${removed.join(", ")}) — single compression owner; restore from the .bili-bak backup if that was intended`); + notes.push("also check /.opencode/opencode.json — a LOCAL-scope opencode-acp install (opencode plugin opencode-acp) lives there, not in this global config"); + } +} + function opencodeInstall(): string { - const file = opencodeJson(); - const data = readJson(file); + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); const notes: string[] = []; + const touched = new Set(); // MCP shell is optional: the native plugin below self-spawns a proxy, so a // missing live origin skips the shell instead of failing the install. @@ -460,13 +631,14 @@ function opencodeInstall(): string { requireDistFile(mcpJs); const rawMcp = data.mcp; if (rawMcp != null && !isPlainMcpObject(rawMcp)) { - notes.push('mcp.bili skipped (opencode.json "mcp" is not an object)'); + notes.push('mcp.bili skipped ("mcp" is not an object)'); } else { const mcp = (rawMcp as Record | undefined) ?? {}; if ("bili" in mcp) notes.push("mcp.bili present"); else { mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: proxyOriginForInstall() }, enabled: true }; data.mcp = mcp; + touched.add("mcp"); notes.push("mcp.bili written"); } } @@ -477,49 +649,70 @@ function opencodeInstall(): string { // Native plugin (#820): self-spawned proxy + http.request URL rewrite. const agentJs = path.join(selfPackageRoot(), "dist", "agent", "opencode-native.js"); requireDistFile(agentJs); + // Single compression owner FIRST: drop any opencode-acp entry before + // adding ours, so both never load armed in one host (#918). The write + // below snapshots the original config to .bili-bak (first write only). + stripLegacyOpencodeAcp(data, notes, touched); const dir = opencodePluginDir(file); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, "index.js"), `export { default } from ${JSON.stringify(agentJs)};\n`); - const plugins = Array.isArray(data.plugin) ? (data.plugin as unknown[]).filter((x): x is string => typeof x === "string") : []; - if (!plugins.includes(dir)) { - plugins.push(dir); - data.plugin = plugins; - notes.push(`plugin -> ${dir}`); + // #927: the single effective key for this host — see pickPluginKey. + const key = pickPluginKey(detectOpencodeMajor()); + const existing = pluginEntries(data, key); + if (!existing.includes(dir)) { + data[key] = [...existing, dir]; + touched.add(key); + notes.push(`${key} -> ${dir}`); } else { - notes.push("plugin present"); + notes.push(`${key} present`); } // Single compression owner: with the native plugin installed, ACP owns // compression — disable host auto-compaction (merge-preserving; the key is - // ignored on OpenCode 1.x). Restored from the pre-install backup on remove. - const existingCompaction = data.compaction; - data.compaction = { - ...(existingCompaction !== null && typeof existingCompaction === "object" && !Array.isArray(existingCompaction) ? existingCompaction as Record : {}), - auto: false, - }; - - writeJson(file, data); + // ignored on OpenCode 1.x). Restored from the pre-install backup on + // remove. #927: skip when the target already says auto:false — the user + // wrote it themselves, so one file carries the fact exactly once. + const curCompaction = data.compaction; + const curObj = curCompaction !== null && typeof curCompaction === "object" && !Array.isArray(curCompaction) ? curCompaction as Record : undefined; + if (curObj?.auto === false) { + notes.push("compaction.auto already disabled"); + } else { + data.compaction = { ...(curObj ?? {}), auto: false }; + touched.add("compaction"); + notes.push("compaction.auto set to false"); + } + + writeOpencodeConfig(file, original, data, touched); return `opencode: installed -> ${file} (${notes.join("; ")})`; } function opencodeRemove(): string { - const file = opencodeJson(); - const data = readJson(file); + const file = opencodeTargetFile(); + const { original, data } = loadOpencodeConfig(file); const notes: string[] = []; + const touched = new Set(); const mcp = data.mcp; if (isPlainMcpObject(mcp) && "bili" in mcp) { delete mcp.bili; if (Object.keys(mcp).length === 0) delete data.mcp; + touched.add("mcp"); notes.push("mcp.bili removed"); } + // #927: clean our entry out of whichever key spelling carries it. const dir = opencodePluginDir(file); - const plugins = Array.isArray(data.plugin) ? (data.plugin as unknown[]).filter((x): x is string => typeof x === "string") : []; - if (plugins.includes(dir)) { - const remaining = plugins.filter((p) => p !== dir); - if (remaining.length === 0) delete data.plugin; - else data.plugin = remaining; + let dirRemoved = false; + for (const key of PLUGIN_KEYS) { + const entries = pluginEntries(data, key); + if (!entries.includes(dir)) continue; + const remaining = entries.filter((p) => p !== dir); + if (remaining.length === 0) delete data[key]; + else data[key] = remaining; + touched.add(key); + dirRemoved = true; + } + if (dirRemoved) { fs.rmSync(dir, { recursive: true, force: true }); notes.push(`plugin dir removed (${dir})`); } @@ -530,9 +723,10 @@ function opencodeRemove(): string { const bak = `${file}.bili-bak`; if (fs.existsSync(bak)) { try { - const bakData = JSON.parse(fs.readFileSync(bak, "utf8")) as { compaction?: unknown }; + const bakData = loadOpencodeConfig(bak).data; if (bakData.compaction === undefined) delete data.compaction; else data.compaction = bakData.compaction; + touched.add("compaction"); notes.push("compaction restored from backup"); } catch { // unreadable backup — leave current settings untouched @@ -542,21 +736,23 @@ function opencodeRemove(): string { // key — dropping it restores the pre-install state exactly; with // extra keys present we can't tell user edits apart, so leave them delete data.compaction; + touched.add("compaction"); notes.push("compaction removed (no prior config)"); } } } - if (notes.length > 0) writeJson(file, data); + writeOpencodeConfig(file, original, data, touched); return notes.length > 0 ? `opencode: removed from ${file} (${notes.join("; ")})` : `opencode: not installed (${file})`; } function opencodeStatus(): string { - const file = opencodeJson(); - const data = readJson(file); + const file = opencodeTargetFile(); + const { data } = loadOpencodeConfig(file); const mcp = data.mcp; - const plugins = Array.isArray(data.plugin) ? (data.plugin as unknown[]).filter((x): x is string => typeof x === "string") : []; - return (isPlainMcpObject(mcp) && "bili" in mcp) || plugins.includes(opencodePluginDir(file)) ? "installed" : "not installed"; + const dir = opencodePluginDir(file); + const listed = PLUGIN_KEYS.some((k) => pluginEntries(data, k).includes(dir)); + return (isPlainMcpObject(mcp) && "bili" in mcp) || listed ? "installed" : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— diff --git a/src/plugin.ts b/src/plugin.ts index 9bd3864a3a..86eb776d75 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -48,6 +48,11 @@ const PROXY_VERSION = (() => { export const PLUGIN_AGENT_HEADER = "x-bili-plugin"; export const PLUGIN_CONVERSATION_HEADER = "x-bili-plugin-conversation"; +/** #920: legacy-lane marker. Set by the absorbed opencode-acp wrapper for + * sessions that still run through the legacy DCP machinery — the proxy + * forwards such requests VERBATIM (no wire injection, no session binding, + * no compress loop): the legacy extension owns compression for them. */ +export const PLUGIN_BYPASS_HEADER = "x-bili-plugin-bypass"; export const PLUGIN_CONTEXT_WINDOW_HEADER = "x-bili-plugin-context-window"; export const PLUGIN_PROTOCOL_VERSION = 1; @@ -77,6 +82,10 @@ export function pluginConversationHeader(headers: Record): string | undefined { + return headerValue(headers, PLUGIN_BYPASS_HEADER); +} + /** The plugin reports its agent's own model context window (what the agent * configured, e.g. a pinned/overridden contextWindow). It replaces the * native-window source (built-in table / models.dev registry) in the config diff --git a/src/server.ts b/src/server.ts index 32d674e1a7..1e58bc515a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -73,7 +73,7 @@ import { emitPreflightError, emitStreamError } from "./stream-error.js"; import { affinityToken, clientConversationHeader, codexTurnIdentity, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; import { flushPrefixAffinity, hydratePrefixAffinity, scheduleAffinityPersist } from "./affinity-persist.js"; -import { consumePluginRegisterFor, flushConversations, handlePluginCompact, handlePluginManifest, handlePluginRegister, handlePluginStatus, handlePluginTool, loadConversations, pipePluginChatWithStrip, pipePluginJson, pipePluginResponsesWithStrip, pluginAgentHeader, pluginConversationHeader, pluginReportedContextWindow, recordPluginSession, rememberPluginMessages, takePendingPluginRegister } from "./plugin.js"; +import { consumePluginRegisterFor, flushConversations, handlePluginCompact, handlePluginManifest, handlePluginRegister, handlePluginStatus, handlePluginTool, loadConversations, pipePluginChatWithStrip, pipePluginJson, pipePluginResponsesWithStrip, pluginAgentHeader, pluginBypassHeader, pluginConversationHeader, pluginReportedContextWindow, recordPluginSession, rememberPluginMessages, takePendingPluginRegister } from "./plugin.js"; import { setupMitm, readMitmUpstream } from "./mitm.js"; import type { BiliMessage } from "acp-kernel/wire"; import { hardenOpenaiAssistantContent, isLoopbackAddress, inspectContextOverflow, reserveOutputHeadroom, shouldReserveOutputHeadroom, systemToUser, usageTotals, type WireProtocol } from "./util.js"; @@ -1024,13 +1024,21 @@ async function handle( // requests whose upstream URL matches a provider route with // `passthrough: true` (upstreams that fingerprint the request body). const routePassthrough = !opts.passthrough && findRoute(opts.routes, route?.rewrittenUrl)?.passthrough === true; + // #920 legacy lane: an absorbed-agent request marked x-bili-plugin-bypass + // belongs to a session still running through the legacy extension's own + // machinery — verbatim forward (same treatment as #300 hopMarker / #661 + // route-passthrough: prepared stays null). + const bypassMarker = pluginBypassHeader(req.headers); + if (bypassMarker !== undefined && !opts.passthrough && !routePassthrough && hopMarker === undefined) { + log("info", `[plugin-bypass] legacy-lane session — forwarding verbatim, kernel bypassed`); + } if (routePassthrough && hopMarker === undefined && protocol && parsed) { log("info", `[route-passthrough] ${maskUrlsInText(route?.rewrittenUrl ?? "")} matches a passthrough route — forwarding verbatim, kernel bypassed`); } // #300: `hopMarker !== undefined` means an upstream bili already processed // this request — skip the whole pipeline (prepared stays null) so the // passthrough path below forwards it verbatim. - if (!opts.passthrough && !routePassthrough && hopMarker === undefined && protocol && parsed && typeof parsed === "object") { + if (!opts.passthrough && !routePassthrough && hopMarker === undefined && bypassMarker === undefined && protocol && parsed && typeof parsed === "object") { const sessionHeader = headerValue(req, opts.sessionHeader); // Plugin mode (issue #1, "内外呼应"): a cooperative agent-side plugin // announces itself with x-bili-plugin. The proxy then treats the diff --git a/tests/issue927-opencode-install.test.ts b/tests/issue927-opencode-install.test.ts new file mode 100644 index 0000000000..d3cdb243a0 --- /dev/null +++ b/tests/issue927-opencode-install.test.ts @@ -0,0 +1,256 @@ +// #927: the opencode install target must be ONE effective config file written +// under the host-generation's canonical plugin key, without duplicating facts +// the user already wrote. Covers: version-aware key, jsonc preference, comment +// preservation, compaction.auto single-source, broken-target refusal, and +// remove/status across key spellings. +import { test } from "node:test"; +import * as assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { pluginInstall, pluginRemove, pluginStatusAll, pickPluginKey, detectOpencodeMajor } from "../src/plugin-install.ts"; +import { parse as jsoncParse, type ParseError } from "jsonc-parser"; + +function readJsonc(file: string): Record { + const errors: ParseError[] = []; + const data = jsoncParse(fs.readFileSync(file, "utf8"), errors, { allowTrailingComma: true }); + assert.equal(errors.length, 0, "written config must stay valid JSONC"); + return data as Record; +} + +async function withEnv(vars: Record, fn: () => Promise): Promise { + const saved = new Map(); + for (const [k, v] of Object.entries(vars)) { + saved.set(k, process.env[k]); + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + try { + await fn(); + } finally { + for (const [k, v] of saved) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } +} + +function isolatedHome(): { home: string; cfgDir: string; env: Record } { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc927-")); + const cfgDir = path.join(home, ".config-x/opencode"); + return { + home, + cfgDir, + env: { + HOME: home, + XDG_CONFIG_HOME: path.join(home, ".config-x"), + XDG_DATA_HOME: path.join(home, ".data-x"), + XDG_STATE_HOME: path.join(home, ".state-x"), + XDG_CACHE_HOME: path.join(home, ".cache-x"), + OPENCODE_CONFIG: undefined, + BILI_CLIENT_BIN: undefined, + BILI_MCP_PROXY: "http://127.0.0.1:8787", + }, + }; +} + +function ocKeys(): { ocKey: "plugin" | "plugins"; otherKey: "plugin" | "plugins" } { + const ocKey = pickPluginKey(detectOpencodeMajor()); + return { ocKey, otherKey: ocKey === "plugin" ? "plugins" : "plugin" }; +} + +test("pickPluginKey: 2.x writes plugins, 1.x and unknowns write plugin (#927)", () => { + assert.equal(pickPluginKey(1), "plugin"); + assert.equal(pickPluginKey(2), "plugins"); + assert.equal(pickPluginKey(3), "plugins"); +}); + +test("detectOpencodeMajor: honors BILI_CLIENT_BIN, fails soft to 1 (#927)", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc927-ver-")); + try { + const v2bin = path.join(home, "fake-opencode-v2"); + fs.writeFileSync(v2bin, "#!/bin/sh\necho \"opencode 2.0.3\"\n"); + fs.chmodSync(v2bin, 0o755); + await withEnv({ BILI_CLIENT_BIN: v2bin }, async () => { + assert.equal(detectOpencodeMajor(), 2); + }); + const deadBin = path.join(home, "fake-opencode-dead"); + fs.writeFileSync(deadBin, "#!/bin/sh\nexit 3\n"); + fs.chmodSync(deadBin, 0o755); + await withEnv({ BILI_CLIENT_BIN: deadBin }, async () => { + assert.equal(detectOpencodeMajor(), 1); + }); + await withEnv({ BILI_CLIENT_BIN: path.join(home, "does-not-exist") }, async () => { + assert.equal(detectOpencodeMajor(), 1); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("install targets existing opencode.jsonc, preserves comments, keeps compaction.auto single-sourced (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const { ocKey } = ocKeys(); + const file = path.join(cfgDir, "opencode.jsonc"); + fs.mkdirSync(cfgDir, { recursive: true }); + const original = [ + "{", + ' // user comment that must survive', + ' "$schema": "https://opencode.ai/config.json",', + ' "compaction": {', + " /* hand-tuned */", + ' "auto": false,', + ' "reserve": 5000', + " },", + ' "provider": { "myprov": {} }', + "}", + "", + ].join("\n"); + fs.writeFileSync(file, original); + try { + await withEnv(env, async () => { + const msg = pluginInstall("opencode"); + assert.match(msg, /installed -> .*opencode\.jsonc/); + assert.match(msg, /mcp\.bili written/); + assert.match(msg, /compaction\.auto already disabled/); + assert.doesNotMatch(msg, /set to false/); + const dir = path.join(cfgDir, "plugins/billion-context"); + let text = fs.readFileSync(file, "utf8"); + assert.ok(text.includes("// user comment that must survive"), "line comment survived"); + assert.ok(text.includes("/* hand-tuned */"), "block comment survived"); + const data = readJsonc(file); + assert.deepEqual(data.compaction, { auto: false, reserve: 5000 }); + assert.ok(Array.isArray(data[ocKey]) && (data[ocKey] as string[]).includes(dir)); + assert.equal(fs.existsSync(path.join(cfgDir, "opencode.json")), false, "no second file spawned"); + assert.equal(fs.existsSync(path.join(cfgDir, "config.json")), false); + + // idempotent re-run: byte-identical file, presence notes only + const again = pluginInstall("opencode"); + assert.match(again, /mcp\.bili present/); + assert.match(again, new RegExp(`${ocKey} present`)); + assert.match(again, /compaction\.auto already disabled/); + assert.equal(fs.readFileSync(file, "utf8"), text, "re-run leaves the file byte-identical"); + + // remove: entries gone, compaction restored from backup, comments intact + assert.match(pluginRemove("opencode"), /removed/); + text = fs.readFileSync(file, "utf8"); + assert.ok(text.includes("// user comment that must survive")); + const after = readJsonc(file); + assert.equal(after.mcp, undefined); + assert.equal(after[ocKey], undefined); + assert.deepEqual(after.compaction, { auto: false, reserve: 5000 }); + assert.equal(fs.existsSync(dir), false); + assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "not installed"); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("fresh config dir: creates plain opencode.json, remove restores pre-install state (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const { ocKey } = ocKeys(); + const file = path.join(cfgDir, "opencode.json"); + try { + await withEnv(env, async () => { + const msg = pluginInstall("opencode"); + assert.match(msg, new RegExp(`installed -> ${file} \\(`)); + assert.match(msg, /compaction\.auto set to false/); + const data = JSON.parse(fs.readFileSync(file, "utf8")) as Record; + assert.deepEqual(data.compaction, { auto: false }); + assert.deepEqual(data[ocKey], [path.join(cfgDir, "plugins/billion-context")]); + assert.equal(fs.existsSync(`${file}.bili-bak`), false, "nothing existed to back up"); + + assert.match(pluginRemove("opencode"), /removed/); + assert.match(pluginRemove("opencode"), /not installed/); + const after = JSON.parse(fs.readFileSync(file, "utf8")) as Record; + assert.equal(after.mcp, undefined); + assert.equal(after[ocKey], undefined); + assert.equal(after.compaction, undefined); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("only config.json present: installer edits it, does not spawn opencode.json (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const { ocKey } = ocKeys(); + const file = path.join(cfgDir, "config.json"); + fs.mkdirSync(cfgDir, { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ marker: "keep" }, null, 2)); + try { + await withEnv(env, async () => { + const msg = pluginInstall("opencode"); + assert.match(msg, new RegExp(`installed -> ${file} \\(`)); + const data = JSON.parse(fs.readFileSync(file, "utf8")) as Record; + assert.equal(data.marker, "keep"); + assert.ok(Array.isArray(data[ocKey])); + assert.equal(fs.existsSync(path.join(cfgDir, "opencode.json")), false); + assert.equal(fs.existsSync(path.join(cfgDir, "opencode.jsonc")), false); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("jsonc + json both present: jsonc wins, sibling json stays byte-identical (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const { ocKey } = ocKeys(); + fs.mkdirSync(cfgDir, { recursive: true }); + const jsoncFile = path.join(cfgDir, "opencode.jsonc"); + const jsonFile = path.join(cfgDir, "opencode.json"); + fs.writeFileSync(jsoncFile, "{\n // top comment\n \"compaction\": { \"auto\": false }\n}\n"); + const siblingBytes = '{\n "marker": "json"\n}\n'; + fs.writeFileSync(jsonFile, siblingBytes); + try { + await withEnv(env, async () => { + const msg = pluginInstall("opencode"); + assert.match(msg, new RegExp(`installed -> ${jsoncFile} \\(`)); + const data = readJsonc(jsoncFile); + assert.ok(Array.isArray(data[ocKey])); + assert.equal(fs.readFileSync(jsonFile, "utf8"), siblingBytes, "sibling opencode.json untouched"); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("broken target config: refuses to overwrite, writes nothing (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const file = path.join(cfgDir, "opencode.jsonc"); + fs.mkdirSync(cfgDir, { recursive: true }); + const broken = "nope{"; + fs.writeFileSync(file, broken); + try { + await withEnv(env, async () => { + assert.throws(() => pluginInstall("opencode"), /refusing to overwrite/); + assert.equal(fs.readFileSync(file, "utf8"), broken, "broken config left byte-identical"); + assert.equal(fs.existsSync(`${file}.bili-bak`), false); + assert.equal(fs.existsSync(path.join(cfgDir, "plugins/billion-context/index.js")), false); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("status/remove recognize our entry under either key spelling (#927)", async () => { + const { home, cfgDir, env } = isolatedHome(); + const { otherKey } = ocKeys(); + const file = path.join(cfgDir, "opencode.json"); + const dir = path.join(cfgDir, "plugins/billion-context"); + fs.mkdirSync(cfgDir, { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ [otherKey]: [dir] })); + try { + await withEnv(env, async () => { + assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "installed"); + assert.match(pluginRemove("opencode"), /removed/); + const after = JSON.parse(fs.readFileSync(file, "utf8")) as Record; + assert.equal(after[otherKey], undefined); + assert.equal(fs.existsSync(dir), false); + assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "not installed"); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/opencode-native-v1.test.ts b/tests/opencode-native-v1.test.ts index fcde3371d5..705088877c 100644 --- a/tests/opencode-native-v1.test.ts +++ b/tests/opencode-native-v1.test.ts @@ -254,3 +254,172 @@ describe("createV1ServerHooks", () => { ); }); }); + +// --------------------------------------------------------------------------- +// #920 legacy lane routing: absorbed opencode-acp serves pre-migration +// sessions; new sessions go to the proxy. +// --------------------------------------------------------------------------- + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + callLegacyAcpConfig, + isLegacyAcpSession, + legacyAcpStatePath, + type LegacyAcpModule, +} from "../src/agent/opencode-legacy.js"; + +function fakeLegacyModule(events: string[]): LegacyAcpModule { + const hooks: Record = { + config: async (cfg: Record) => { + events.push(`legacy-config:${JSON.stringify(Object.keys(cfg))}`); + cfg.permission = { deny: ["dcp_*"] }; + }, + "command.execute.before": async (input: { command: string; sessionID: string }, output?: { parts?: unknown[] }) => { + events.push(`legacy-command:${input.command}:${input.sessionID}:${output === undefined ? "no-output" : "output"}`); + }, + "experimental.chat.system.transform": async (input: { sessionID: string }, output?: { system?: unknown[] }) => { + events.push(`legacy-system:${input.sessionID}:${output === undefined ? "no-output" : "output"}`); + }, + "experimental.chat.messages.transform": async (_i: unknown, output: { messages: unknown[] }) => { + const last = output.messages[output.messages.length - 1] as { info?: { sessionID?: string } }; + events.push(`legacy-messages:${last?.info?.sessionID}`); + }, + "experimental.text.complete": async (input: { sessionID: string }, output?: { text?: unknown }) => { + events.push(`legacy-text:${input.sessionID}:${output === undefined ? "no-output" : "output"}`); + }, + tool: { + compress: { + description: "legacy compress", + args: { content: { __fake: "string" } }, + execute: async (args: Record, ctx: { sessionID: string }) => { + events.push(`legacy-compress:${ctx.sessionID}`); + return "legacy-compressed"; + }, + }, + acp_status: { + description: "legacy status", + args: {}, + execute: async (_a: Record, ctx: { sessionID: string }) => { + events.push(`legacy-status:${ctx.sessionID}`); + return "legacy-status"; + }, + }, + }, + }; + return { hooks, tools: hooks.tool as LegacyAcpModule["tools"], configHook: hooks.config as LegacyAcpModule["configHook"], commandHook: hooks["command.execute.before"] as LegacyAcpModule["commandHook"], source: "/fake/opencode-acp/dist/index.js" }; +} + +describe("createV1ServerHooks legacy routing (#920)", () => { + it("routes tools, headers, command and transforms per session lane", async () => { + const events: string[] = []; + const legacy = fakeLegacyModule(events); + const forwarded: { sid: string; tool: string; args: unknown }[] = []; + const hooks = createV1ServerHooks("http://127.0.0.1:19999", {}, { + z: fakeZ, + legacy, + isLegacy: (sid) => sid === "ses_legacy", + forward: async (_o, sid, tool, args) => { + forwarded.push({ sid, tool, args }); + return "proxied"; + }, + log: () => {}, + }); + + // legacy session: tool executes via absorbed acp + const r1 = await hooks.tool?.compress.execute({ content: [] }, { sessionID: "ses_legacy" }); + assert.equal(r1, "legacy-compressed"); + assert.deepEqual(forwarded, []); + // new session: forwarded to the proxy + const r2 = await hooks.tool?.compress.execute({ content: [] }, { sessionID: "ses_new" }); + assert.equal(r2, "proxied"); + assert.deepEqual(forwarded, [{ sid: "ses_new", tool: "compress", args: { content: [] } }]); + + // headers: legacy bypasses, new stamps plugin mode + const h1: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_legacy" } as never, { headers: h1 }); + assert.equal(h1["x-bili-plugin"], undefined); + assert.equal(h1["x-bili-plugin-bypass"], "1"); + const h2: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_new" } as never, { headers: h2 }); + assert.equal(h2["x-bili-plugin"], "opencode"); + assert.equal(h2["x-bili-plugin-conversation"], "ses_new"); + assert.equal(h2["x-bili-plugin-bypass"], undefined); + + // /acp command: legacy session -> acp handler (no throw); new -> bili handler (throws __BILI_ACP_HANDLED__ after render) + // output must reach the absorbed acp handler (its handlers are two-arg (input, output)) + await hooks["command.execute.before"]?.({ command: "acp", sessionID: "ses_legacy", arguments: "" }, { parts: [] }); + assert.ok(events.includes("legacy-command:acp:ses_legacy:output")); + events.length = 0; + await assert.rejects(hooks["command.execute.before"]?.({ command: "acp", sessionID: "ses_new", arguments: "" }), /__BILI_ACP_HANDLED__/); + assert.equal(events.filter((e) => e.startsWith("legacy-command")).length, 0); + + // transforms gated to legacy sessions only; output reaches acp on the legacy lane + await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_new" }, { system: [] }); + assert.equal(events.filter((e) => e.startsWith("legacy-system:ses_new")).length, 0); + await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_legacy" }, { system: [] }); + assert.ok(events.includes("legacy-system:ses_legacy:output")); + await hooks["experimental.chat.messages.transform"]?.({}, { messages: [{ role: "user" }, { role: "assistant", info: { sessionID: "ses_new" } }] }); + assert.equal(events.filter((e) => e === "legacy-messages:ses_new").length, 0); + await hooks["experimental.chat.messages.transform"]?.({}, { messages: [{ info: { sessionID: "ses_legacy" } }] }); + assert.ok(events.includes("legacy-messages:ses_legacy")); + await hooks["experimental.text.complete"]?.({ sessionID: "ses_new" }, { text: "" }); + await hooks["experimental.text.complete"]?.({ sessionID: "ses_legacy" }, { text: "" }); + assert.equal(events.filter((e) => e.startsWith("legacy-text:ses_new")).length, 0); + assert.ok(events.includes("legacy-text:ses_legacy:output")); + }); + + it("config hook hides providers from absorbed acp and still rewrites", async () => { + const events: string[] = []; + const legacy = fakeLegacyModule(events); + const cfg: V1Config = { + provider: { testprov: { options: { baseURL: "http://127.0.0.1:19998/v1" } } }, + }; + await createV1ServerHooks("http://127.0.0.1:19999", {}, { + z: fakeZ, + legacy, + isLegacy: () => false, + forward: async () => "proxied", + log: () => {}, + }).config?.(cfg); + // legacy saw no provider key (shadow had provider: undefined) + assert.ok(events.some((e) => e.startsWith("legacy-config:") && !e.includes("provider"))); + // its permission write survived the merge + assert.deepEqual(cfg.permission, { deny: ["dcp_*"] }); + // and the rewrite still happened + assert.equal((cfg.provider.testprov?.options as V1ProviderOptions).baseURL, "http://127.0.0.1:19999/bili/http://127.0.0.1:19998/v1"); + }); +}); + +describe("legacy session state file (#920)", () => { + it("detects legacy sessions by acp state file and sanitizes ids", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-legacy-state-")); + process.env.XDG_DATA_HOME = path.join(home, "data"); + try { + fs.mkdirSync(path.dirname(legacyAcpStatePath("ses_old")), { recursive: true }); + fs.writeFileSync(legacyAcpStatePath("ses_old"), "{}"); + assert.equal(isLegacyAcpSession("ses_old"), true); + assert.equal(isLegacyAcpSession("ses_fresh"), false); + assert.equal(isLegacyAcpSession(undefined), false); + assert.equal(isLegacyAcpSession(""), false); + assert.equal(isLegacyAcpSession("../../etc"), false); + } finally { + delete process.env.XDG_DATA_HOME; + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("callLegacyAcpConfig merges only owned top-level keys", async () => { + const cfg: Record = { provider: { p: 1 }, agent: { keep: true } }; + await callLegacyAcpConfig(async (shadow) => { + assert.equal((shadow as { provider?: unknown }).provider, undefined); + shadow.experimental = { replaced: true }; // reference change → owned + (shadow as { permission?: unknown }).permission = { deny: ["x"] }; + }, cfg); + assert.equal((cfg.provider as { p?: number }).p, 1); // untouched + assert.deepEqual(cfg.agent, { keep: true }); // not an owned key + assert.deepEqual(cfg.experimental, { replaced: true }); + assert.deepEqual(cfg.permission, { deny: ["x"] }); + }); +}); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index b846053072..0682792f29 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -11,7 +11,7 @@ process.env.NODE_ENV = "test"; import { proxyBaseFromUrl, proxyBaseFromEnv, detectProxyBase, fetchManifest, forwardTool, fetchStatus } from "../src/agent/shared.ts"; import biliPlugin, { createBiliPlugin } from "../src/agent/pi.ts"; import ompPlugin from "../src/agent/omp.ts"; -import { pluginInstall, pluginRemove, pluginStatusAll, PLUGIN_AGENTS, selfPackageRoot } from "../src/plugin-install.ts"; +import { pluginInstall, pluginRemove, pluginStatusAll, PLUGIN_AGENTS, selfPackageRoot, pickPluginKey, detectOpencodeMajor } from "../src/plugin-install.ts"; import { resolveProxyOrigin, forwardTool as mcpForwardTool } from "../src/mcp.ts"; function withEnv(vars: Record, fn: () => void | Promise): Promise { @@ -882,27 +882,30 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO assert.match(pluginRemove("codex"), /removed/); // #820: pre-seed user settings — install must merge around them and remove must restore them. + // #927: seed under whichever key this host's opencode generation uses, so the + // round-trip assertions hold on both 1.x ("plugin") and 2.x ("plugins") machines. + const ocKey = pickPluginKey(detectOpencodeMajor()); const ocFile = path.join(home, ".config/opencode/opencode.json"); fs.mkdirSync(path.dirname(ocFile), { recursive: true }); - fs.writeFileSync(ocFile, JSON.stringify({ $schema: "https://opencode.ai/config.json", compaction: { auto: true, buffer: 100 }, plugin: ["some-other-plugin"] })); + fs.writeFileSync(ocFile, JSON.stringify({ $schema: "https://opencode.ai/config.json", compaction: { auto: true, buffer: 100 }, [ocKey]: ["some-other-plugin"] })); const ocPluginDir = path.join(home, ".config/opencode/plugins/billion-context"); const ocInstallMsg = pluginInstall("opencode"); assert.match(ocInstallMsg, /installed/); assert.match(ocInstallMsg, /mcp\.bili written/); - let oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: Record }>; plugin?: string[]; compaction?: Record; $schema?: string }; + let oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: Record }>; compaction?: Record; $schema?: string } & 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.deepEqual(oc.plugin, ["some-other-plugin", ocPluginDir]); + assert.deepEqual(oc[ocKey], ["some-other-plugin", ocPluginDir]); assert.match(fs.readFileSync(path.join(ocPluginDir, "index.js"), "utf8"), /agent[\\/]opencode-native\.js/); assert.deepEqual(oc.compaction, { auto: false, buffer: 100 }); const ocAgain = pluginInstall("opencode"); assert.match(ocAgain, /mcp\.bili present/); - assert.match(ocAgain, /plugin present/); + assert.match(ocAgain, new RegExp(`${ocKey} present`)); assert.match(pluginRemove("opencode"), /removed/); - oc = JSON.parse(fs.readFileSync(ocFile, "utf8")); + oc = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record; assert.equal(oc.mcp, undefined); // only the bili entry is dropped — the user's other plugin survives - assert.deepEqual(oc.plugin, ["some-other-plugin"]); + assert.deepEqual(oc[ocKey], ["some-other-plugin"]); assert.deepEqual(oc.compaction, { auto: true, buffer: 100 }); assert.equal(oc.$schema, "https://opencode.ai/config.json"); assert.equal(fs.existsSync(ocPluginDir), false); @@ -925,19 +928,20 @@ test("plugin install opencode without a live proxy: MCP shell skipped, native pl const ocFile = path.join(home, ".config/opencode/opencode.json"); try { await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + const ocKey = pickPluginKey(detectOpencodeMajor()); const msg = pluginInstall("opencode"); assert.match(msg, /installed/); assert.match(msg, /mcp\.bili skipped/); assert.match(msg, /no bili proxy origin found/); - const data = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: unknown; plugin?: string[]; compaction?: Record }; + const data = JSON.parse(fs.readFileSync(ocFile, "utf8")) as { mcp?: unknown; compaction?: Record } & Record; assert.equal(data.mcp, undefined); - assert.deepEqual(data.plugin, [path.join(home, ".config/opencode/plugins/billion-context")]); + assert.deepEqual(data[ocKey], [path.join(home, ".config/opencode/plugins/billion-context")]); assert.deepEqual(data.compaction, { auto: false }); assert.ok(fs.existsSync(path.join(home, ".config/opencode/plugins/billion-context/index.js"))); assert.match(pluginRemove("opencode"), /removed/); const after = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record; assert.equal(after.mcp, undefined); - assert.equal(after.plugin, undefined); + assert.equal(after[ocKey], undefined); assert.equal(after.compaction, undefined); }); } finally { @@ -945,22 +949,72 @@ test("plugin install opencode without a live proxy: MCP shell skipped, native pl } }); +test("plugin install opencode replaces legacy opencode-acp entries — array and object shapes (#918)", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc-acp-")); + const ocFile = path.join(home, ".config/opencode/opencode.json"); + fs.mkdirSync(path.dirname(ocFile), { recursive: true }); + try { + await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + const ocKey = pickPluginKey(detectOpencodeMajor()); + const otherKey = ocKey === "plugin" ? "plugins" : "plugin"; + const dir = path.join(home, ".config/opencode/plugins/billion-context"); + // array shape: bare name, npm: alias, path (incl. deep entry path), versioned + fs.writeFileSync(ocFile, JSON.stringify({ + [ocKey]: ["opencode-acp", "npm:opencode-acp", "/opt/other-plugin", path.join(home, "ext/opencode-acp/index.js"), path.join(home, "ext2/opencode-acp/dist/index.js"), "opencode-acp@stable"], + })); + let msg = pluginInstall("opencode"); + assert.match(msg, /replaced opencode-acp plugin entries/); + let data = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record; + assert.deepEqual(data[ocKey], ["/opt/other-plugin", dir]); + assert.ok(fs.existsSync(`${ocFile}.bili-bak`)); + pluginRemove("opencode"); + + // object shape: version-map form (defensive; normalized to keys) + fs.writeFileSync(ocFile, JSON.stringify({ [ocKey]: { "opencode-acp": "stable", "other": "1.0" } })); + msg = pluginInstall("opencode"); + assert.match(msg, /replaced opencode-acp plugin entries \(opencode-acp\)/); + data = JSON.parse(fs.readFileSync(ocFile, "utf8")); + // sibling object entries survive as bare array specs + our dir + assert.deepEqual(data[ocKey], ["other", dir]); + pluginRemove("opencode"); + + // #927: legacy entries under the OTHER spelling are stripped too + fs.writeFileSync(ocFile, JSON.stringify({ [otherKey]: ["npm:opencode-acp", "/opt/other-plugin"], [ocKey]: ["/opt/mine"] })); + msg = pluginInstall("opencode"); + assert.match(msg, /replaced opencode-acp plugin entries \(npm:opencode-acp\)/); + data = JSON.parse(fs.readFileSync(ocFile, "utf8")); + assert.deepEqual(data[otherKey], ["/opt/other-plugin"]); + assert.deepEqual(data[ocKey], ["/opt/mine", dir]); + pluginRemove("opencode"); + + // no legacy entries -> no note, plugin untouched + fs.writeFileSync(ocFile, JSON.stringify({ [ocKey]: ["/opt/other-plugin"] })); + msg = pluginInstall("opencode"); + assert.doesNotMatch(msg, /replaced opencode-acp/); + assert.equal(msg.includes("other-plugin"), false); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + test("plugin install/remove/status survive a non-object mcp in opencode.json (#809/N4)", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc-badmcp-")); const ocFile = path.join(home, ".config/opencode/opencode.json"); fs.mkdirSync(path.dirname(ocFile), { recursive: true }); try { await withEnv({ OPENCODE_CONFIG: ocFile, BILI_MCP_PROXY: undefined, XDG_STATE_HOME: path.join(home, "state") }, async () => { + const ocKey = pickPluginKey(detectOpencodeMajor()); fs.writeFileSync(ocFile, JSON.stringify({ mcp: "totally-broken-string" })); const msg = pluginInstall("opencode"); assert.match(msg, /installed/); let data = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record; - assert.deepEqual(data.plugin, [path.join(home, ".config/opencode/plugins/billion-context")]); + assert.deepEqual(data[ocKey], [path.join(home, ".config/opencode/plugins/billion-context")]); assert.deepEqual(data.compaction, { auto: false }); assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "installed"); assert.doesNotThrow(() => pluginRemove("opencode")); data = JSON.parse(fs.readFileSync(ocFile, "utf8")) as Record; - assert.equal(data.plugin, undefined); + assert.equal(data[ocKey], undefined); assert.equal(data.compaction, undefined); assert.ok(!fs.existsSync(path.join(home, ".config/opencode/plugins/billion-context/index.js"))); assert.equal(pluginStatusAll().find((r) => r.agent === "opencode")?.status, "not installed"); diff --git a/tests/plugin-bypass.test.ts b/tests/plugin-bypass.test.ts new file mode 100644 index 0000000000..1511e4c8ec --- /dev/null +++ b/tests/plugin-bypass.test.ts @@ -0,0 +1,108 @@ +// #920 legacy lane: requests marked x-bili-plugin-bypass are forwarded +// VERBATIM — no wire tool injection, no nudge, no session binding — because +// the absorbed opencode-acp owns compression for those sessions. +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer, type ProxyOptions } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; + +interface Harness { + proxyPort: number; + upstreamPort: number; + captured: { body: string; headers: Record }[]; + close(): Promise; +} + +async function startHarness(): Promise { + const captured: Harness["captured"] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + captured.push({ body: Buffer.concat(chunks).toString(), headers: { ...req.headers } }); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "msg_bypass", role: "assistant", content: [{ type: "text", text: "ok" }], usage: { input_tokens: 5, output_tokens: 1 } })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = upstream.address().port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetPluginStateForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "test-model": { context: 400_000 } } } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + compress: { injectTool: true, injectNudge: true }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = proxy.address().port; + + return { + proxyPort, + upstreamPort, + captured, + close: async () => { + proxy.close(); + upstream.close(); + await Promise.allSettled([once(proxy, "close"), once(upstream, "close")]); + }, + }; +} + +let h: Harness | undefined; + +beforeEach(async () => { + h = await startHarness(); +}); +afterEach(async () => { + await h?.close(); + h = undefined; +}); + +describe("plugin bypass header (#920)", () => { + it("bypassed requests are forwarded verbatim — no tool injection, no nudge", async () => { + const body = { model: "test-model", stream: false, messages: [{ role: "user", content: "hello legacy session" }] }; + const resp = await fetch(`http://127.0.0.1:${h!.proxyPort}/bili/http://127.0.0.1:${h!.upstreamPort}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin-bypass": "1" }, + body: JSON.stringify(body), + }); + assert.equal(resp.status, 200); + assert.equal(h!.captured.length, 1); + const seen = JSON.parse(h!.captured[0]!.body) as { tools?: unknown[]; messages: unknown[] }; + assert.equal(seen.tools, undefined); + assert.deepEqual(seen.messages, body.messages); + assert.equal(h!.captured[0]!.headers["x-bili-plugin-bypass"], "1"); + }); + + it("without the header the same request gets the plugin pipeline (tools injected)", async () => { + const body = { model: "test-model", stream: false, messages: [{ role: "user", content: "hello new session" }] }; + const resp = await fetch(`http://127.0.0.1:${h!.proxyPort}/bili/http://127.0.0.1:${h!.upstreamPort}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + assert.equal(resp.status, 200); + const seen = JSON.parse(h!.captured[0]!.body) as { tools?: { function?: { name?: string } }[] }; + const names = (seen.tools ?? []).map((t) => t.function?.name); + assert.ok(names.includes("compress"), `expected compress in ${JSON.stringify(names)}`); + }); +});