From 9e4141921bfd117851e8aee218f07b72e8b1d9d0 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 11 Sep 2026 21:07:34 +0800 Subject: [PATCH 01/29] =?UTF-8?q?feat(pi):=20native=20plugin=20mode=20?= =?UTF-8?q?=E2=80=94=20self-bootstrapping=20proxy=20+=20fetch=20intercepti?= =?UTF-8?q?on=20(#519)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bare pi (package installed via pi's package manager or bili plugin install pi) now gets full plugin-mode compression with no launcher: - dist/agent/pi-native.js (new tsup entry, now the pi manifest target): at extension load it spawns the package's own proxy via ensureProxyRunning (ephemeral port, parent-pid watchdog = the pi process; attaches to a healthy compatible instance instead of doubling), sets BILLION_CONTEXT_PROXY, and exports the existing createBiliPlugin factory so tools/headers//acp/compaction-cancel reuse launcher-mode paths. - src/agent/native-intercept.ts: globalThis.fetch patch verified against pi 0.83.6 (SDK fetch resolves from the global at first-request client construction). Rewrites ONLY model-API URL shapes to /bili/; never touches the proxy's own paths or non-HTTP(S); waits for bootstrap (15s) then degrades to direct with a one-time warning; TypeError triggers one respawn+retry (parent watchdog fires when the owning pi exits while later sessions ride it). - ensureProxyRunning: deps.scriptPath override (process.argv[1] is the host's script inside pi). - Gating: skipped under bili launch (BILLION_CONTEXT_PROXY / BILI_PROVIDER_REWRITES) and node:test (NODE_TEST_CONTEXT); opt-out BILI_NATIVE_PI=0. bili pi keeps -e dist/agent/pi.js unchanged. Known limitation: legacy billion-context-pi self-disables via the /bili/ baseUrl prefix native mode does not rewrite — tracked in #513. --- CHANGELOG.md | 3 + package.json | 2 +- src/agent/native-intercept.ts | 143 ++++++++++++++++++++++++++++++ src/agent/pi-native.ts | 73 +++++++++++++++ src/launcher.ts | 6 +- tests/native-intercept.test.ts | 157 +++++++++++++++++++++++++++++++++ tests/pi-native.test.ts | 49 ++++++++++ tsup.config.ts | 2 +- 8 files changed, 432 insertions(+), 3 deletions(-) create mode 100644 src/agent/native-intercept.ts create mode 100644 src/agent/pi-native.ts create mode 100644 tests/native-intercept.test.ts create mode 100644 tests/pi-native.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 19bf0905e6..4d7b6c9747 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] +### Features + +- **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Known limitation: the legacy `billion-context-pi` adapter package detects the proxy via a `/bili/` baseUrl prefix, which native mode does not rewrite — users with BOTH installed get double compression; `bili plugin install pi` already removes the legacy entry, a detection warning for pi-package-manager installs is tracked in #513. ### Fixes - **DeepSeek thinking mode 400 fixed: turns are atomic, reasoning-drop self-disables on strict-echo upstreams (#684)**: two paths could ship a rebuilt request whose assistant `tool_calls` turn lost its `reasoning_content` — (1) the proxy's recent-zone carve kept the last tool-call of a multi-call turn visible while its reasoning run folded into the block (kernel boundary logic only pulled the FIRST companion message after reasoning), and (2) #651's reasoning-drop stripped reasoning from a closed compress turn even on upstreams that document thinking-mode `reasoning_content` as mandatory round-trip. DeepSeek rejects both with 400 (`The \`reasoning_content\` in the thinking mode must be passed back to the API`) and the turn dies. Fixes: the kernel now computes atomic turn groups (reasoning run + its full assistant burst + every result paired by `toolCallId` — all fold together or none do; a range that would split a turn is withdrawn with a warning, or rejected with an explanatory error when nothing else remains), the forward boundary pull covers the whole burst, and the reasoning-drop never fires when the session is known strict-echo — statically for `deepseek` upstreams, or learned from the first 400 whose body mentions `reasoning_content` (persisted on the session, self-healing like #552). Three wire-level exit sentinels (`[reasoning-pair-violated]` on chat/completions and Responses, `[thinking-pair-violated]` on Anthropic) log loudly if any future path reintroduces a split turn. diff --git a/package.json b/package.json index 7191a87bc8..8198ccb4b0 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "pi": { "image": "https://raw.githubusercontent.com/ranxianglei/billion-context/master/docs/logo.png", "extensions": [ - "./dist/agent/pi.js" + "./dist/agent/pi-native.js" ] }, "publishConfig": { diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts new file mode 100644 index 0000000000..2181bfb10b --- /dev/null +++ b/src/agent/native-intercept.ts @@ -0,0 +1,143 @@ +// Native-mode fetch interception (#519): a globalThis.fetch patch that +// silently routes model-API requests through a bili proxy that the extension +// itself spawned (see pi-native.ts). Verified end-to-end on pi 0.83.6: pi's +// provider stack (pi-stable-ai → Anthropic/OpenAI SDKs) resolves its fetch +// from the global at FIRST-request client construction, so a patch installed +// at extension load always wins. The patch is surgical — it rewrites ONLY +// model-API shaped URLs and leaves every other request untouched. + +export interface NativeInterceptState { + /** Proxy origin ("http://127.0.0.1:PORT") once the bootstrap resolved. + * Written by the owner (pi-native.ts); read synchronously on each call. */ + origin: string | undefined; + /** Resolves to the proxy origin once healthy, or undefined on failure. */ + ready: Promise; + /** Owner hook: re-run the bootstrap (proxy died → respawn). */ + respawn?: () => Promise; + /** How long a pre-ready model request waits for the bootstrap before + * falling back to a direct (uncompressed) send. */ + readyTimeoutMs?: number; + /** Test/observability hook: every dispatched decision. */ + onDispatch?: (url: string, action: "rewrite" | "direct" | "self" | "retry") => void; +} + +const INTERCEPT_FLAG = "__biliNativeFetchIntercept"; + +// Model-API endpoint suffixes across the wires bili proxies: Anthropic +// `/v1/messages`, OpenAI chat `/v1/chat/completions` (and legacy +// `/v1/completions`), Responses `/v1/responses`, Mistral +// `/v1/chat/completions`|`/v1/conversations`. Version segment is optional +// and unpinned (zhipuai uses `/v4/chat/completions`, bailian mounts +// `/apps/anthropic/v1/messages`), so match on the trailing shape only. +const MODEL_API_SUFFIX = /(?:^|\/)(?:v\d+\/)?(?:messages|chat\/completions|completions|responses|conversations)\/?$/; + +/** True when the URL points at a model-API endpoint worth proxying. Never + * true for bili's own proxy paths (`/bili/…`, `/__bili/…`) or non-HTTP(S). */ +export function isModelApiUrl(url: string): boolean { + if (!/^https?:\/\//i.test(url)) return false; + if (url.includes("/__bili/") || url.includes("/__acp/")) return false; + try { + const u = new URL(url); + const segments = u.pathname.split("/").filter((s) => s.length > 0); + if (segments[0] === "bili") return false; + const pathname = u.pathname.replace(/\/+$/, ""); + return MODEL_API_SUFFIX.test(pathname); + } catch { + return false; + } +} + +function fetchUrlOf(input: string | URL | Request): string | undefined { + try { + if (typeof input === "string") return input; + if (input instanceof URL) return input.href; + if (input !== null && typeof input === "object" && typeof (input as Request).url === "string") { + return (input as Request).url; + } + } catch { + // fallthrough + } + return undefined; +} + +async function withTimeout(p: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), ms); + }); + try { + return await Promise.race([p, timeout]); + } catch { + return undefined; + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + +async function readyOrigin(state: NativeInterceptState): Promise { + if (state.origin !== undefined) return state.origin; + return withTimeout(state.ready, state.readyTimeoutMs ?? 15000); +} + +/** Install the global fetch patch. Idempotent: a second call is a no-op + * (returns false) so double-loading the entry cannot double-wrap. */ +export function installNativeFetchIntercept(state: NativeInterceptState): boolean { + const g = globalThis as Record; + if (g[INTERCEPT_FLAG] === true) return false; + const orig = globalThis.fetch; + let warned = false; + + const patched = async (input: string | URL | Request, init?: RequestInit): Promise => { + const url = fetchUrlOf(input); + if (url === undefined || !isModelApiUrl(url)) return orig(input, init); + + const dispatch = (target: string, action: "rewrite" | "self" | "retry"): ReturnType => { + state.onDispatch?.(target, action); + if (typeof input === "string" || input instanceof URL) return orig(target, init); + return orig(new Request(target, input), init); + }; + + const origin = await readyOrigin(state); + if (origin === undefined) { + // Bootstrap failed or timed out — NEVER break the agent: send + // direct (uncompressed) and say so once. + if (!warned) { + warned = true; + console.error(`bili-native: proxy not ready — model request goes direct (uncompressed): ${url}`); + } + state.onDispatch?.(url, "direct"); + return orig(input, init); + } + if (url.startsWith(`${origin}/`)) { + state.onDispatch?.(url, "self"); + return orig(input, init); + } + try { + return await dispatch(`${origin}/bili/${url}`, "rewrite"); + } catch (err) { + // The spawned proxy can die mid-session (its parent watchdog + // fires when the FIRST owning pi exits while later sessions + // still ride it). A network-level failure (undici throws + // TypeError) triggers one respawn + one retry. + if (err instanceof TypeError && state.respawn !== undefined) { + state.origin = undefined; + state.ready = state.respawn(); + const again = await readyOrigin(state); + if (again !== undefined) return dispatch(`${again}/bili/${url}`, "retry"); + state.onDispatch?.(url, "direct"); + } + throw err; + } + }; + + globalThis.fetch = patched as typeof globalThis.fetch; + g[INTERCEPT_FLAG] = true; + return true; +} + +/** Test-only: drop the patch guard so a suite can install again. The + * caller owns restoring globalThis.fetch. */ +export function _resetForTest(): void { + const g = globalThis as Record; + delete g[INTERCEPT_FLAG]; +} diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts new file mode 100644 index 0000000000..3173131ff8 --- /dev/null +++ b/src/agent/pi-native.ts @@ -0,0 +1,73 @@ +// Native pi mode (#519): the package-installed pi extension bootstraps its +// own proxy — bare `pi` (with this package installed via pi's package +// manager or `bili plugin install pi`) gets full plugin-mode compression +// with NO launcher. Flow at extension load: +// 1. spawn the package's own proxy (`dist/index.js start`, ephemeral +// port, parent-pid watchdog = this pi process) via ensureProxyRunning — +// a healthy compatible instance is ATTACHED, not doubled; +// 2. patch globalThis.fetch (native-intercept.ts) so model-API requests +// are rewritten to `/bili/`; +// 3. set BILLION_CONTEXT_PROXY so the shared plugin (pi.ts) detects the +// proxy through its existing env fallback — tools, headers, /acp and +// the compaction cancel all reuse the launcher-mode code paths. +// Skipped when a proxy is already managed (BILLION_CONTEXT_PROXY set by a +// `bili` MITM launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ +// launch) or opted out (BILI_NATIVE_PI=0). + +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createBiliPlugin } from "./pi.js"; +import { installNativeFetchIntercept, type NativeInterceptState } from "./native-intercept.js"; +import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; + +/** dist/agent/pi-native.js → dist/index.js (the package bin). Resolved at + * runtime so the artifact works from any install root. */ +export function nativeProxyScriptPath(fromUrl: string = import.meta.url): string { + return path.resolve(path.dirname(fileURLToPath(fromUrl)), "..", "index.js"); +} + +/** Decides whether the native bootstrap should run in this process. */ +export function shouldBootstrapNative(env: NodeJS.ProcessEnv): boolean { + if (env.BILLION_CONTEXT_PLUGIN === "0") return false; + if (env.BILI_NATIVE_PI === "0") return false; + // A `bili` launch already owns a proxy — attach to its mode instead of + // spawning a second one (MITM transparent sets BILLION_CONTEXT_PROXY; + // /bili/ rewrite mode sets BILI_PROVIDER_REWRITES). + if (env.BILLION_CONTEXT_PROXY !== undefined && env.BILLION_CONTEXT_PROXY.trim().length > 0) return false; + if (env.BILI_PROVIDER_REWRITES !== undefined) return false; + return true; +} + +function errMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined) }; + +async function bootstrap(): Promise { + try { + const handle = await ensureProxyRunning( + { host: LAUNCHER_DEFAULT_HOST, port: 0, passthrough: false, debug: false }, + { scriptPath: nativeProxyScriptPath() }, + ); + const origin = handle.origin; + state.origin = origin; + process.env.BILLION_CONTEXT_PROXY = origin; + return origin; + } catch (err) { + console.error(`bili-native: proxy bootstrap failed — model traffic goes direct (uncompressed): ${errMessage(err)}`); + return undefined; + } +} + +// node:test imports this module for shouldBootstrapNative/nativeProxyScriptPath — +// never bootstrap a real proxy from inside a test run. +if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNative(process.env)) { + state.respawn = bootstrap; + state.ready = bootstrap(); + installNativeFetchIntercept(state); +} + +export default createBiliPlugin(); + +export { fetchStatus } from "./pi.js"; diff --git a/src/launcher.ts b/src/launcher.ts index 8eb31df617..6de72f39aa 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -148,6 +148,10 @@ export interface LauncherDeps { spawnImpl?: SpawnFn; now?: () => number; sleep?: (ms: number) => Promise; + /** #519 native mode: the proxy entry script to spawn. The launcher + * default (process.argv[1]) is WRONG inside a host process like pi — + * pi-native.ts passes its own package's dist/index.js instead. */ + scriptPath?: string; } export function isLaunchClient(value: string): value is ClientName { @@ -1744,7 +1748,7 @@ export async function ensureProxyRunning( // pointed there only ever reach an explicitly-started `bili start`. // The child's EADDRINUSE retry covers the pick/spawn race. const port = opts.port > 0 ? opts.port : await pickEphemeralPort(opts.host); - const script = process.argv[1]; + const script = deps.scriptPath ?? process.argv[1]; if (!script) throw new Error("bili: cannot resolve launcher script path"); const logPath = path.join(os.tmpdir(), `bili-proxy-${port}.log`); const logFd = fs.openSync(logPath, "a"); diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts new file mode 100644 index 0000000000..ffb08513f6 --- /dev/null +++ b/tests/native-intercept.test.ts @@ -0,0 +1,157 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { installNativeFetchIntercept, isModelApiUrl, _resetForTest, type NativeInterceptState } from "../src/agent/native-intercept.ts"; + +test("isModelApiUrl: matches model-API endpoint shapes", () => { + assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/messages"), true); + assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/chat/completions"), true); + assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/completions"), true); + assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/responses"), true); + assert.equal(isModelApiUrl("https://coding.dashscope.aliyuncs.com/apps/anthropic/v1/messages"), true); + assert.equal(isModelApiUrl("https://open.bigmodel.cn/api/coding/paas/v4/chat/completions"), true); + assert.equal(isModelApiUrl("https://api.anthropic.com/v1/messages?beta=true"), true); + assert.equal(isModelApiUrl("http://localhost:9123/v1/messages/"), true); +}); + +test("isModelApiUrl: rejects non-model URLs, proxy paths, non-HTTP", () => { + assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/models"), false); + assert.equal(isModelApiUrl("http://127.0.0.1:36485/__bili/plugin/manifest"), false); + assert.equal(isModelApiUrl("http://127.0.0.1:36485/bili/http://127.0.0.1:8199/v1/messages"), false); + assert.equal(isModelApiUrl("https://registry.npmjs.org/billion-context"), false); + assert.equal(isModelApiUrl("https://example.com/v1/messages/count_tokens"), false); + assert.equal(isModelApiUrl("file:///tmp/v1/messages"), false); + assert.equal(isModelApiUrl("not a url"), false); + assert.equal(isModelApiUrl("https://api.anthropic.com/v1/messages/count_tokens"), false); +}); + +function fakeFetch(sink: string[]) { + return (async (input: RequestInfo | URL, _init?: RequestInit) => { + sink.push(typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url); + return new Response("{}", { status: 200 }); + }) as typeof fetch; +} + +async function withPatch(state: NativeInterceptState, fn: (fetch: typeof globalThis.fetch) => Promise): Promise<{ sink: string[]; result: T }> { + const saved = globalThis.fetch; + _resetForTest(); + const sink: string[] = []; + globalThis.fetch = fakeFetch(sink); + try { + assert.equal(installNativeFetchIntercept(state), true); + const result = await fn(globalThis.fetch); + return { sink, result }; + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +} + +test("install: rewrites model URLs once ready", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("http://127.0.0.1:8199/v1/messages", { method: "POST" }); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); +}); + +test("install: waits for a not-yet-ready proxy before rewriting", async () => { + let release: (v: string | undefined) => void = () => {}; + const ready = new Promise((r) => { + release = r; + }); + const state: NativeInterceptState = { origin: undefined, ready, readyTimeoutMs: 5000 }; + const { sink } = await withPatch(state, async (fetch) => { + const pending = fetch("http://127.0.0.1:8199/v1/messages"); + await new Promise((r) => setTimeout(r, 20)); + release("http://127.0.0.1:40002"); + const res = await pending; + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40002/bili/http://127.0.0.1:8199/v1/messages"]); +}); + +test("install: falls back to direct when the bootstrap fails/times out", async () => { + const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined), readyTimeoutMs: 50 }; + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:8199/v1/messages"]); +}); + +test("install: leaves non-model URLs untouched", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const { sink } = await withPatch(state, async (fetch) => { + await fetch("https://registry.npmjs.org/billion-context"); + await fetch("http://127.0.0.1:40001/__bili/plugin/manifest"); + }); + assert.deepEqual(sink, ["https://registry.npmjs.org/billion-context", "http://127.0.0.1:40001/__bili/plugin/manifest"]); +}); + +test("install: proxy-origin URLs are never re-proxied (self guard)", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const { sink } = await withPatch(state, async (fetch) => { + await fetch("http://127.0.0.1:40001/v1/messages"); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/v1/messages"]); +}); + +test("install: TypeError triggers one respawn + retry", async () => { + const calls: string[] = []; + const saved = globalThis.fetch; + _resetForTest(); + let failNext = true; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url; + calls.push(url); + if (failNext) { + failNext = false; + throw new TypeError("fetch failed"); + } + return new Response("{}", { status: 200 }); + }) as typeof fetch; + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), respawn: undefined }; + try { + assert.equal(installNativeFetchIntercept(state), true); + state.respawn = () => { + state.origin = "http://127.0.0.1:40009"; + state.ready = Promise.resolve("http://127.0.0.1:40009"); + return Promise.resolve("http://127.0.0.1:40009"); + }; + const res = await globalThis.fetch("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + assert.deepEqual(calls, [ + "http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages", + "http://127.0.0.1:40009/bili/http://127.0.0.1:8199/v1/messages", + ]); + assert.equal(state.origin, "http://127.0.0.1:40009"); + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +}); + +test("install: second install is a no-op while active", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const saved = globalThis.fetch; + _resetForTest(); + globalThis.fetch = fakeFetch([]); + try { + assert.equal(installNativeFetchIntercept(state), true); + assert.equal(installNativeFetchIntercept(state), false); + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +}); + +test("install: Request-object input is re-dispatched with the rewritten URL", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const { sink } = await withPatch(state, async (fetch) => { + const req = new Request("http://127.0.0.1:8199/v1/messages", { method: "POST", body: "{}" }); + const res = await fetch(req); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); +}); diff --git a/tests/pi-native.test.ts b/tests/pi-native.test.ts new file mode 100644 index 0000000000..07e8f9edce --- /dev/null +++ b/tests/pi-native.test.ts @@ -0,0 +1,49 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { shouldBootstrapNative, nativeProxyScriptPath } from "../src/agent/pi-native.ts"; +import { ensureProxyRunning, type SpawnChild, type SpawnFn } from "../src/launcher.ts"; + +test("shouldBootstrapNative: true in a bare host with no bili env", () => { + assert.equal(shouldBootstrapNative({}), true); +}); + +test("shouldBootstrapNative: false when the plugin or native mode is opted out", () => { + assert.equal(shouldBootstrapNative({ BILLION_CONTEXT_PLUGIN: "0" }), false); + assert.equal(shouldBootstrapNative({ BILI_NATIVE_PI: "0" }), false); +}); + +test("shouldBootstrapNative: false when a bili launch already owns a proxy", () => { + assert.equal(shouldBootstrapNative({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), false); + assert.equal(shouldBootstrapNative({ BILLION_CONTEXT_PROXY: " " }), true); + assert.equal(shouldBootstrapNative({ BILI_PROVIDER_REWRITES: '{"vllm":"http://127.0.0.1:1/bili/http://x"}' }), false); +}); + +test("nativeProxyScriptPath: dist/agent/pi-native.js resolves to the package bin", () => { + const resolved = nativeProxyScriptPath("file:///opt/pkg/dist/agent/pi-native.js"); + assert.equal(resolved, path.resolve("/opt/pkg/dist/index.js")); +}); + +function makeFakeChild(pid: number): SpawnChild { + return { + pid, + unref() {}, + kill() { + return true; + }, + on() {}, + }; +} + +test("ensureProxyRunning: deps.scriptPath overrides process.argv[1] for the spawned proxy (#519)", async () => { + let spawnScriptArg = ""; + const spawnImpl: SpawnFn = (_command, args) => { + spawnScriptArg = args[0]; + return makeFakeChild(42431); + }; + await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { fetchImpl: async () => ({ ok: true }), spawnImpl, readInstanceFile: () => undefined, scriptPath: "/opt/pkg/dist/index.js" }, + ); + assert.equal(spawnScriptArg, "/opt/pkg/dist/index.js"); +}); diff --git a/tsup.config.ts b/tsup.config.ts index d84f50e191..b87ca8f13d 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from "tsup"; export default defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/agent/pi.ts", "src/agent/omp.ts", "src/agent/opencode.ts", "src/agent/dsh-acp.ts"], + entry: ["src/index.ts", "src/mcp.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/opencode.ts", "src/agent/dsh-acp.ts"], format: ["esm"], target: "node20", platform: "node", From 3cb0331fb95be8663f31385d16aa091ee0ec50b1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 11 Sep 2026 21:25:06 +0800 Subject: [PATCH 02/29] fix(pi): arm compaction-cancel at event time; dedup concurrent native respawns (#519) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for the native plugin mode: - pi.ts: the session_before_compact cancel was gated on BILLION_CONTEXT_PROXY at factory (load) time. In native mode the proxy origin only lands in env AFTER the async bootstrap finishes, so the cancel was disarmed for the whole session and pi's native threshold/ overflow compaction could fire alongside ACP compression (destroying the ACP-tagged context). Decide ownership at EVENT time via detectProxyBase instead: a failed bootstrap or a plain no-proxy run still degrades to fully native, and a manual /bili/ baseUrl routing now arms the cancel too. - pi-native.ts: wrap the bootstrap in singleFlight() — a burst of TypeErrors (proxy died mid-session) used to call ensureProxyRunning once per failing request, which has no in-flight dedup and would spawn one orphaned proxy per request. --- src/agent/pi-native.ts | 20 ++++++++++++++++++-- src/agent/pi.ts | 18 ++++++++++++------ tests/pi-native.test.ts | 18 +++++++++++++++++- tests/plugin-agent.test.ts | 15 +++++++++++++-- 4 files changed, 60 insertions(+), 11 deletions(-) diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts index 3173131ff8..25335df233 100644 --- a/src/agent/pi-native.ts +++ b/src/agent/pi-native.ts @@ -60,11 +60,27 @@ async function bootstrap(): Promise { } } +/** Concurrent callers share one in-flight bootstrap — a burst of TypeErrors + * (the proxy died mid-session) must not spawn one proxy per failing request: + * ensureProxyRunning has no in-flight dedup of its own. */ +export function singleFlight(fn: () => Promise): () => Promise { + let inFlight: Promise | undefined; + return (): Promise => { + if (inFlight === undefined) { + inFlight = fn().finally(() => { + inFlight = undefined; + }); + } + return inFlight; + }; +} + // node:test imports this module for shouldBootstrapNative/nativeProxyScriptPath — // never bootstrap a real proxy from inside a test run. if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNative(process.env)) { - state.respawn = bootstrap; - state.ready = bootstrap(); + const start = singleFlight(bootstrap); + state.respawn = start; + state.ready = start(); installNativeFetchIntercept(state); } diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 6c65b6336b..bf4cb214a7 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -59,8 +59,8 @@ function agentName(override: string | undefined): string { return process.env.BILLION_CONTEXT_PLUGIN_AGENT === "omp" ? "omp" : "pi"; } -function proxyBaseForCtx(ctx: Ctx): string | undefined { - return detectProxyBase(ctx.model?.baseUrl); +function proxyBaseForCtx(ctx: Ctx | undefined): string | undefined { + return detectProxyBase(ctx?.model?.baseUrl); } function sessionIdOf(ctx: Ctx): string | undefined { @@ -281,10 +281,16 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM // cancels ALL compaction — under bili, manual native /compact is // equally harmful (the native summarizer would destroy the // ACP-tagged context), the host shows "Compaction cancelled", and - // the user should reach for /acp instead. Only armed under `bili` - // launch: plain pi/omp with the plugin installed stays fully native. - if ((agent === "pi" || agent === "omp") && process.env.BILLION_CONTEXT_PROXY !== undefined) { - pi.on("session_before_compact", (event) => { + // the user should reach for /acp instead. Whether we own compression + // is decided at EVENT time, not load time: in native mode (#519) the + // proxy origin lands in BILLION_CONTEXT_PROXY only after the async + // bootstrap finishes, so a load-time check would leave the cancel + // disarmed for the whole session. Plain pi/omp with the plugin + // installed but NO reachable proxy (incl. a failed bootstrap) stays + // fully native. + if (agent === "pi" || agent === "omp") { + pi.on("session_before_compact", (event, ctx) => { + if (proxyBaseForCtx(ctx) === undefined) return undefined; if (agent === "pi") { const reason = (event as unknown as { reason?: unknown }).reason; if (reason === "threshold" || reason === "overflow") return { cancel: true }; diff --git a/tests/pi-native.test.ts b/tests/pi-native.test.ts index 07e8f9edce..36226da7fa 100644 --- a/tests/pi-native.test.ts +++ b/tests/pi-native.test.ts @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; -import { shouldBootstrapNative, nativeProxyScriptPath } from "../src/agent/pi-native.ts"; +import { shouldBootstrapNative, nativeProxyScriptPath, singleFlight } from "../src/agent/pi-native.ts"; import { ensureProxyRunning, type SpawnChild, type SpawnFn } from "../src/launcher.ts"; test("shouldBootstrapNative: true in a bare host with no bili env", () => { @@ -35,6 +35,22 @@ function makeFakeChild(pid: number): SpawnChild { }; } +test("singleFlight: concurrent callers share one in-flight run, then re-arm", async () => { + let runs = 0; + const start = singleFlight(async () => { + runs++; + await new Promise((r) => setTimeout(r, 20)); + return "http://127.0.0.1:40001"; + }); + const [a, b, c] = await Promise.all([start(), start(), start()]); + assert.equal(runs, 1, "three concurrent callers → one bootstrap"); + assert.deepEqual([a, b, c], ["http://127.0.0.1:40001", "http://127.0.0.1:40001", "http://127.0.0.1:40001"]); + // after settling, the next call starts fresh (a later respawn is allowed) + const d = await start(); + assert.equal(runs, 2); + assert.equal(d, "http://127.0.0.1:40001"); +}); + test("ensureProxyRunning: deps.scriptPath overrides process.argv[1] for the spawned proxy (#519)", async () => { let spawnScriptArg = ""; const spawnImpl: SpawnFn = (_command, args) => { diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 55be3151ec..91c616c140 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -287,13 +287,24 @@ test("#535: session_before_compact cancels only pi auto compaction under bili la } }); -test("#535: plain pi (no BILLION_CONTEXT_PROXY) → no compaction cancel handler", () => { +test("#535/#519: no proxy at factory time → cancel inert until a proxy appears", () => { const prevProxy = process.env.BILLION_CONTEXT_PROXY; delete process.env.BILLION_CONTEXT_PROXY; try { const pi = makeFakePi(); createBiliPlugin("pi")(pi as never); - assert.equal(pi.events.get("session_before_compact"), undefined, "native run stays fully native"); + const handler = pi.events.get("session_before_compact"); + assert.ok(handler, "handler registered; arming decided at event time"); + assert.equal(handler({ reason: "threshold" }, undefined), undefined, "no proxy → native compaction untouched"); + // native mode (#519): BILLION_CONTEXT_PROXY lands only AFTER the factory ran + process.env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:8787"; + assert.deepEqual(handler({ reason: "threshold" }, undefined), { cancel: true }); + assert.deepEqual(handler({ reason: "overflow" }, undefined), { cancel: true }); + assert.equal(handler({ reason: "manual" }, undefined), undefined, "manual /compact stays user-owned"); + // /bili/ baseUrl routing (no env at all) arms the cancel too + delete process.env.BILLION_CONTEXT_PROXY; + const biliCtx = { model: { baseUrl: "http://127.0.0.1:8787/bili/https://api.example.com/v1" } }; + assert.deepEqual(handler({ reason: "threshold" }, biliCtx), { cancel: true }); } finally { if (prevProxy === undefined) delete process.env.BILLION_CONTEXT_PROXY; else process.env.BILLION_CONTEXT_PROXY = prevProxy; From 05b78b4ff2033ada91e8b96b3982da17e5277847 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 11 Sep 2026 21:42:10 +0800 Subject: [PATCH 03/29] =?UTF-8?q?fix(test):=20platform-native=20absolute?= =?UTF-8?q?=20path=20in=20nativeProxyScriptPath=20test=20=E2=80=94=20a=20h?= =?UTF-8?q?ardcoded=20file:///opt=20URL=20throws=20ERR=5FINVALID=5FFILE=5F?= =?UTF-8?q?URL=5FPATH=20on=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/pi-native.test.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/pi-native.test.ts b/tests/pi-native.test.ts index 36226da7fa..bd21b0c131 100644 --- a/tests/pi-native.test.ts +++ b/tests/pi-native.test.ts @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; +import { pathToFileURL } from "node:url"; import { shouldBootstrapNative, nativeProxyScriptPath, singleFlight } from "../src/agent/pi-native.ts"; import { ensureProxyRunning, type SpawnChild, type SpawnFn } from "../src/launcher.ts"; @@ -20,8 +21,12 @@ test("shouldBootstrapNative: false when a bili launch already owns a proxy", () }); test("nativeProxyScriptPath: dist/agent/pi-native.js resolves to the package bin", () => { - const resolved = nativeProxyScriptPath("file:///opt/pkg/dist/agent/pi-native.js"); - assert.equal(resolved, path.resolve("/opt/pkg/dist/index.js")); + // Build the from-URL from a platform-native absolute path: a hardcoded + // file:///opt/... URL is invalid on Windows (no drive letter — + // fileURLToPath throws ERR_INVALID_FILE_URL_PATH). + const agentFile = path.resolve(path.sep, "opt", "pkg", "dist", "agent", "pi-native.js"); + const resolved = nativeProxyScriptPath(pathToFileURL(agentFile).href); + assert.equal(resolved, path.resolve(path.sep, "opt", "pkg", "dist", "index.js")); }); function makeFakeChild(pid: number): SpawnChild { From ddbbf2092add7c2b8e9509e2955d0d37661ddde7 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 15 Sep 2026 22:26:29 +0800 Subject: [PATCH 04/29] fix(pi-native): degrade to direct sends when respawn fails; don't misclassify request-construction errors (#513 audit) --- CHANGELOG.md | 1 + src/agent/native-intercept.ts | 35 ++++++++++++++---- src/agent/pi-native.ts | 8 +++++ tests/native-intercept.test.ts | 66 ++++++++++++++++++++++++++++++++++ 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d7b6c9747..153f411aae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag - **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Known limitation: the legacy `billion-context-pi` adapter package detects the proxy via a `/bili/` baseUrl prefix, which native mode does not rewrite — users with BOTH installed get double compression; `bili plugin install pi` already removes the legacy entry, a detection warning for pi-package-manager installs is tracked in #513. ### Fixes +- **pi native mode: a failed mid-session respawn degrades to direct sends instead of rethrowing the proxy's network error (#513 audit)**: when the spawned proxy died and the one-shot respawn also failed, the interceptor logged an `onDispatch(url, "direct")` but then re-threw the original `TypeError` — the model call died instead of degrading, and `BILLION_CONTEXT_PROXY` stayed set, so the event-time `session_before_compact` cancel kept cancelling native compaction while all traffic went direct (context grows uncompressed, forever). The give-up path now sends the request direct (same contract as bootstrap failure, one-time warning) and fires a new `onGiveUp` hook; pi-native uses it to clear the env so event-time ownership checks disarm together with the traffic. Also: rebuilding a Request-object input against the rewritten target no longer routes caller-side defects (already-consumed or locked body) into the proxy-death branch — they surface as-is instead of respawning an orphaned proxy. - **DeepSeek thinking mode 400 fixed: turns are atomic, reasoning-drop self-disables on strict-echo upstreams (#684)**: two paths could ship a rebuilt request whose assistant `tool_calls` turn lost its `reasoning_content` — (1) the proxy's recent-zone carve kept the last tool-call of a multi-call turn visible while its reasoning run folded into the block (kernel boundary logic only pulled the FIRST companion message after reasoning), and (2) #651's reasoning-drop stripped reasoning from a closed compress turn even on upstreams that document thinking-mode `reasoning_content` as mandatory round-trip. DeepSeek rejects both with 400 (`The \`reasoning_content\` in the thinking mode must be passed back to the API`) and the turn dies. Fixes: the kernel now computes atomic turn groups (reasoning run + its full assistant burst + every result paired by `toolCallId` — all fold together or none do; a range that would split a turn is withdrawn with a warning, or rejected with an explanatory error when nothing else remains), the forward boundary pull covers the whole burst, and the reasoning-drop never fires when the session is known strict-echo — statically for `deepseek` upstreams, or learned from the first 400 whose body mentions `reasoning_content` (persisted on the session, self-healing like #552). Three wire-level exit sentinels (`[reasoning-pair-violated]` on chat/completions and Responses, `[thinking-pair-violated]` on Anthropic) log loudly if any future path reintroduces a split turn. - **Windows: spaced client/extension paths no longer break launched clients or silently drop extensions (#679, PR #682)**: `runClient` spawned clients with `shell: true` and no per-token quoting, so on Windows cmd.exe re-split the joined line at the first space — a client binary under a spaced path (`C:\Users\John Doe\...`) died with `'C:\Users\John' is not recognized`, and a surviving client whose `-e ` path was split launched WITHOUT the bili extension (compression silently never activates). Spawning is now routed by executable class: real `.exe`/node binaries spawn directly (the OS quotes argv, spaces intact), npm `.cmd`/`.bat`/extensionless shims go through an explicit `comspec /d /s /c "…"` line with correct per-token quoting (`windowsVerbatimArguments`); `shell: true` is gone (also silences Node's DEP0190 warning). Known edge: `BILI_CLIENT_BIN` pointing at a `.js` file now fails loudly instead of relying on file association via the old shell path. - **Windows: codex MCP server delivered via CODEX_HOME overlay, not inline `-c` (#681, PR #683)**: cmd.exe cannot transmit a literal `"` to a child, but every valid TOML string needs one — so the inline `-c mcp_servers.bili.command="C:\\Program Files\\nodejs\\node.exe"` arg arrived at codex as an unquoted, space-split, invalid TOML value for ANY absolute Windows path (spaced stock install just the common case), the bili MCP server never registered, and plugin-mode compression silently never activated. On `win32` the launcher now writes `[mcp_servers.bili]` (command/args/env.BILI_MCP_PROXY/env.BILI_CONVERSATION_ID) into a persistent `-bili` overlay's merged `config.toml` — sharing every other real-home entry (auth.json, sessions, model settings) — and points the spawned codex at it via `CODEX_HOME`. POSIX keeps the working inline `-c` path byte-identical; if the overlay can't be built the launch degrades to wire mode (server-side compression still active) with a warning. Real-Windows end-to-end verification tracked in #686. diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index 2181bfb10b..82c90ec86a 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -14,6 +14,11 @@ export interface NativeInterceptState { ready: Promise; /** Owner hook: re-run the bootstrap (proxy died → respawn). */ respawn?: () => Promise; + /** Owner hook: fired once when a respawn attempt fails and the session + * degrades to direct sends for good — clear proxy-owned state (e.g. the + * BILLION_CONTEXT_PROXY env) so event-time ownership checks disarm with + * the traffic. */ + onGiveUp?: () => void; /** How long a pre-ready model request waits for the bootstrap before * falling back to a direct (uncompressed) send. */ readyTimeoutMs?: number; @@ -91,11 +96,12 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea const url = fetchUrlOf(input); if (url === undefined || !isModelApiUrl(url)) return orig(input, init); - const dispatch = (target: string, action: "rewrite" | "self" | "retry"): ReturnType => { - state.onDispatch?.(target, action); - if (typeof input === "string" || input instanceof URL) return orig(target, init); - return orig(new Request(target, input), init); - }; + // Rebuild a Request-object input against the rewritten target. A + // caller-side defect here (already-consumed or locked body) must not + // reach the proxy-death branch below — respawning would orphan a + // fresh proxy for a request that can never be sent. + const makeTarget = (target: string): string | URL | Request => + typeof input === "string" || input instanceof URL ? target : new Request(target, input); const origin = await readyOrigin(state); if (origin === undefined) { @@ -112,8 +118,10 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea state.onDispatch?.(url, "self"); return orig(input, init); } + const first = makeTarget(`${origin}/bili/${url}`); + state.onDispatch?.(`${origin}/bili/${url}`, "rewrite"); try { - return await dispatch(`${origin}/bili/${url}`, "rewrite"); + return await orig(first, init); } catch (err) { // The spawned proxy can die mid-session (its parent watchdog // fires when the FIRST owning pi exits while later sessions @@ -123,8 +131,21 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea state.origin = undefined; state.ready = state.respawn(); const again = await readyOrigin(state); - if (again !== undefined) return dispatch(`${again}/bili/${url}`, "retry"); + if (again !== undefined) { + const retried = makeTarget(`${again}/bili/${url}`); + state.onDispatch?.(`${again}/bili/${url}`, "retry"); + return await orig(retried, init); + } + // Respawn failed — this session runs direct for its lifetime. + // Degrade exactly like a bootstrap failure: actually send the + // request direct, then let the owner clear proxy-owned state. + state.onGiveUp?.(); + if (!warned) { + warned = true; + console.error(`bili-native: proxy respawn failed — model requests go direct (uncompressed): ${url}`); + } state.onDispatch?.(url, "direct"); + return orig(input, init); } throw err; } diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts index 25335df233..400c769732 100644 --- a/src/agent/pi-native.ts +++ b/src/agent/pi-native.ts @@ -80,6 +80,14 @@ export function singleFlight(fn: () => Promise): () => Promi if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNative(process.env)) { const start = singleFlight(bootstrap); state.respawn = start; + state.onGiveUp = () => { + // We wrote BILLION_CONTEXT_PROXY at successful bootstrap. If the proxy + // dies mid-session and the respawn fails, traffic goes direct — clear + // the env so event-time ownership checks (session_before_compact + // cancel, header stamping) stop claiming compression ownership and + // native compaction comes back with the direct traffic. + delete process.env.BILLION_CONTEXT_PROXY; + }; state.ready = start(); installNativeFetchIntercept(state); } diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts index ffb08513f6..34aef16132 100644 --- a/tests/native-intercept.test.ts +++ b/tests/native-intercept.test.ts @@ -155,3 +155,69 @@ test("install: Request-object input is re-dispatched with the rewritten URL", as }); assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); }); + +test("install: failed respawn degrades to a direct send and fires onGiveUp", async () => { + const calls: string[] = []; + const dispatches: string[] = []; + const saved = globalThis.fetch; + _resetForTest(); + let failNext = true; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url; + calls.push(url); + if (failNext) { + failNext = false; + throw new TypeError("fetch failed"); + } + return new Response("{}", { status: 200 }); + }) as typeof fetch; + const state: NativeInterceptState = { + origin: "http://127.0.0.1:40001", + ready: Promise.resolve("http://127.0.0.1:40001"), + respawn: () => Promise.resolve(undefined), + onDispatch: (_url, action) => dispatches.push(action), + }; + try { + assert.equal(installNativeFetchIntercept(state), true); + const res = await globalThis.fetch("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + assert.deepEqual(calls, [ + "http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages", + "http://127.0.0.1:8199/v1/messages", + ]); + assert.deepEqual(dispatches, ["rewrite", "direct"]); + assert.equal(state.origin, undefined); + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +}); + +test("install: a consumed-body Request throws without triggering a respawn", async () => { + const saved = globalThis.fetch; + _resetForTest(); + let respawnCalls = 0; + globalThis.fetch = (async () => new Response("{}", { status: 200 })) as typeof fetch; + const state: NativeInterceptState = { + origin: "http://127.0.0.1:40001", + ready: Promise.resolve("http://127.0.0.1:40001"), + respawn: () => { + respawnCalls += 1; + return Promise.resolve("http://127.0.0.1:40001"); + }, + }; + try { + assert.equal(installNativeFetchIntercept(state), true); + const req = new Request("http://127.0.0.1:8199/v1/messages", { + method: "POST", + body: ReadableStream.from([new TextEncoder().encode("{}")]), + duplex: "half", + } as RequestInit & { duplex?: string }); + await req.arrayBuffer(); + await assert.rejects(() => globalThis.fetch(req), TypeError); + assert.equal(respawnCalls, 0); + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +}); From 314d03c1dd765f81c2d37bfa3f69cf577c240588 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 15 Sep 2026 22:55:09 +0800 Subject: [PATCH 05/29] test(pi-native): assert onGiveUp fires and the degrade stays permanent (#513 audit) --- tests/native-intercept.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts index 34aef16132..8d0c67b8c6 100644 --- a/tests/native-intercept.test.ts +++ b/tests/native-intercept.test.ts @@ -162,6 +162,8 @@ test("install: failed respawn degrades to a direct send and fires onGiveUp", asy const saved = globalThis.fetch; _resetForTest(); let failNext = true; + let respawns = 0; + let giveUps = 0; globalThis.fetch = (async (input: RequestInfo | URL) => { const url = typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url; calls.push(url); @@ -174,7 +176,13 @@ test("install: failed respawn degrades to a direct send and fires onGiveUp", asy const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), - respawn: () => Promise.resolve(undefined), + respawn: () => { + respawns += 1; + return Promise.resolve(undefined); + }, + onGiveUp: () => { + giveUps += 1; + }, onDispatch: (_url, action) => dispatches.push(action), }; try { @@ -187,6 +195,16 @@ test("install: failed respawn degrades to a direct send and fires onGiveUp", asy ]); assert.deepEqual(dispatches, ["rewrite", "direct"]); assert.equal(state.origin, undefined); + assert.equal(respawns, 1); + assert.equal(giveUps, 1); + // The degrade is permanent for the session: later model requests go + // direct without re-entering the respawn path. + const res2 = await globalThis.fetch("http://127.0.0.1:8199/v1/messages"); + assert.equal(res2.status, 200); + assert.equal(calls[2], "http://127.0.0.1:8199/v1/messages"); + assert.deepEqual(dispatches, ["rewrite", "direct", "direct"]); + assert.equal(respawns, 1); + assert.equal(giveUps, 1); } finally { globalThis.fetch = saved; _resetForTest(); From 9409d3bf80212195bc100da862d656ae096042c9 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 00:39:01 +0800 Subject: [PATCH 06/29] =?UTF-8?q?feat(opencode):=20native=20plugin=20mode?= =?UTF-8?q?=20for=20OpenCode=202.x=20(#820)=20=E2=80=94=20self-spawning=20?= =?UTF-8?q?proxy=20in=20the=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follows the pi-native pattern (#706) so both hosts share one bootstrap core. - src/agent/native-bootstrap.ts: side-effect-free helpers shared by pi-native and opencode-native (nativeProxyScriptPath / nativeBootstrapGate / singleFlight); importing it never spawns a proxy. - src/agent/opencode-v2.ts: V2 factory createOpencodeV2Setup() extracted from opencode.ts (tool registration, context-window refresh, compaction-boundary reporting, header stamping), parameterized by an optional per-request route(e, state) hook. - src/agent/opencode-native.ts: native entry billion-context-opencode-native. Bootstraps a proxy via ensureProxyRunning on load (no bili daemon needed); its http.request hook rewrites model-API URLs to /bili/ by replacing the request reference (Request.url is readonly, #810). Liveness is probed against GET /__bili/health before every send; a dead proxy respawns with a 15s cooldown, and failed respawn degrades to direct sends with one warning, auto-recovering on later requests. - src/launcher.ts: resolveNodeRuntime() fixes #819 — ensureProxyRunning no longer spawns process.execPath blindly, which breaks when the host process is not Node itself. Resolution: live node -> BILLION_CONTEXT_NODE override -> PATH search -> actionable error. - src/plugin-install.ts: bili plugin install opencode also installs the native plugin as wrapper dir /plugins/billion-context/index.js re-exporting dist/agent/opencode-native.js (OpenCode 2.x requires directory-form plugin entries, #754), disables compaction.auto with merge preservation (.bili-bak restore on remove), and makes the MCP shell optional (missing live proxy origin skips it with a note instead of failing). - tests: new tests/opencode-native.test.ts (gate, route rewrite, respawn/degrade, setup integration, kill switch); launcher.test.ts gains resolveNodeRuntime units + spawn-runtime wiring; plugin-agent.test.ts roundtrip extended for plugin dir / compaction merge+restore plus a no-proxy case. Also repairs the dsh phase-4 launch test finally block referencing an undeclared prevNoProxy (pre-existing ReferenceError; DSH_HOME leak fixed too). - docs: README OpenCode 2.0 Native bullet; CHANGELOG entry. --- CHANGELOG.md | 1 + README.md | 17 ++- src/agent/native-bootstrap.ts | 41 ++++++ src/agent/native-intercept.ts | 2 +- src/agent/opencode-native.ts | 168 +++++++++++++++++++++++ src/agent/opencode-v2.ts | 224 +++++++++++++++++++++++++++++++ src/agent/opencode.ts | 210 ++--------------------------- src/agent/pi-native.ts | 38 +----- src/launcher.ts | 33 ++++- src/plugin-install.ts | 114 +++++++++++++--- tests/launcher.test.ts | 53 ++++++++ tests/opencode-native.test.ts | 242 ++++++++++++++++++++++++++++++++++ tests/plugin-agent.test.ts | 54 +++++++- tsup.config.ts | 2 +- 14 files changed, 941 insertions(+), 258 deletions(-) create mode 100644 src/agent/native-bootstrap.ts create mode 100644 src/agent/opencode-native.ts create mode 100644 src/agent/opencode-v2.ts create mode 100644 tests/opencode-native.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f19772761e..89adca234d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Features +- **opencode 2.x native mode: package-installed opencode gets plugin-mode compression with no launcher (#820, npm-package design #809)**: `bili plugin install opencode` now installs, alongside the MCP shell (kept, but optional — a missing live proxy origin skips it instead of failing the install), a self-spawning native plugin: a stable wrapper directory `/plugins/billion-context/index.js` re-exporting `dist/agent/opencode-native.js` (OpenCode 2.x rejects bare FILE paths in `plugin` — the directory's index.js is the entrypoint, #754 probe) plus `compaction.auto=false` (single compression owner; merge-preserving, restored from the `.bili-bak` backup on remove). At plugin load the same gate as pi-native applies (`BILI_NATIVE_OPENCODE=0` opt-out; skipped entirely under a `bili` launch) and the package's own proxy is bootstrapped through `ensureProxyRunning` (attach-or-spawn, ephemeral port, parent-pid watchdog, `deps.scriptPath`). OpenCode plugins have no fetch seam to patch, so egress interception uses the `http.request` hook, replacing the outgoing fetch Request REFERENCE with `new Request("/bili/", old)` carrying method/headers/body (WHATWG Request.url is read-only at runtime — verified live, #810). Header stamping, native tools and compaction-boundary reporting reuse the shared V2 setup factory (`src/agent/opencode-v2.ts`, extracted from opencode.ts so launcher mode and native mode share ONE protocol implementation). Because an http.request hook cannot observe send failures (the host swallows them), every request liveness-probes `/__bili/health` of the current origin before routing — one respawn if the proxy died mid-session, direct send + one-time warning when no origin can be made healthy (auto-recovering: each request re-verifies, unlike pi's lifetime latch). Also fixes #819: `ensureProxyRunning` resolves the Node executable for spawning via `resolveNodeRuntime()` (live Node wins → `BILLION_CONTEXT_NODE` override → PATH search) instead of blind `process.execPath`, which inside a host binary (opencode/pi native) is the HOST executable — the spawned proxy died at spawn. - **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Known limitation: the legacy `billion-context-pi` adapter package detects the proxy via a `/bili/` baseUrl prefix, which native mode does not rewrite — users with BOTH installed get double compression; `bili plugin install pi` already removes the legacy entry, a detection warning for pi-package-manager installs is tracked in #513. ### Fixes diff --git a/README.md b/README.md index 7cf25e146e..a235128c8f 100644 --- a/README.md +++ b/README.md @@ -264,8 +264,21 @@ contract: plain proxy mode (wire-level tool injection) instead of breaking — observed on two adjacent `dev` builds (2026-09-13 / 2026-09-14) whose API surfaces differ from each other (#754 review probes); conversely verified end-to-end - on `@opencode/cli` 2.0.3 (native `acp_status` executed through the plugin - endpoint, zero wire-level injection). + on `@opencode/cli` 2.0.3 (native `acp_status` executed through the plugin + endpoint, zero wire-level injection). +- **Native (no launcher):** with the package installed from npm, run + `bili plugin install opencode` — it writes a self-spawning plugin into your + real opencode config (`/plugins/billion-context/index.js` → + `dist/agent/opencode-native.js`) and sets `compaction.auto: false`, after + which plain `opencode` works as-is. At load the plugin bootstraps its own + proxy (attaches to a healthy instance instead of doubling; parent-pid + watchdog kills it when opencode exits), routes model-API traffic through the + `http.request` hook to `/bili/`, and exposes the same + native bili tools as launcher mode — no fixed port, no env var, no launcher. + Opt-out: `BILI_NATIVE_OPENCODE=0`. If no proxy can be made healthy, requests + go direct (uncompressed) with a one-time warning and recover automatically. + Under a `bili opencode` launch this entry is skipped entirely (the launcher + owns the proxy). - **Pure proxy:** point the provider baseURL at the proxy like any other client: diff --git a/src/agent/native-bootstrap.ts b/src/agent/native-bootstrap.ts new file mode 100644 index 0000000000..7c63706560 --- /dev/null +++ b/src/agent/native-bootstrap.ts @@ -0,0 +1,41 @@ +// Shared native-mode bootstrap plumbing (#519 pi pattern, reused by every +// host-native entry — opencode 2.x per #820). Kept free of host-specific side +// effects: importing this module must NEVER spawn a proxy or patch anything — +// the host entries (pi-native.ts / opencode-native.ts) own their module-level +// bootstrap blocks. + +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +/** dist/agent/.js → dist/index.js (the package bin). Resolved at + * runtime so the artifact works from any install root. */ +export function nativeProxyScriptPath(fromUrl: string = import.meta.url): string { + return path.resolve(path.dirname(fileURLToPath(fromUrl)), "..", "index.js"); +} + +/** Common gate for host-native bootstraps: off when the global plugin kill + * switch or the per-host opt-out key is set, or when a `bili` launch already + * owns a proxy (MITM transparent sets BILLION_CONTEXT_PROXY; /bili/ rewrite + * mode sets BILI_PROVIDER_REWRITES). */ +export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string): boolean { + if (env.BILLION_CONTEXT_PLUGIN === "0") return false; + if (env[optOutKey] === "0") return false; + if (env.BILLION_CONTEXT_PROXY !== undefined && env.BILLION_CONTEXT_PROXY.trim().length > 0) return false; + if (env.BILI_PROVIDER_REWRITES !== undefined) return false; + return true; +} + +/** Concurrent callers share one in-flight bootstrap — a burst of failures + * (the proxy died mid-session) must not spawn one proxy per failing request: + * ensureProxyRunning has no in-flight dedup of its own. */ +export function singleFlight(fn: () => Promise): () => Promise { + let inFlight: Promise | undefined; + return (): Promise => { + if (inFlight === undefined) { + inFlight = fn().finally(() => { + inFlight = undefined; + }); + } + return inFlight; + }; +} diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index 82c90ec86a..d77901aa0c 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -79,7 +79,7 @@ async function withTimeout(p: Promise, ms: number): Promise< } } -async function readyOrigin(state: NativeInterceptState): Promise { +export async function readyOrigin(state: NativeInterceptState): Promise { if (state.origin !== undefined) return state.origin; return withTimeout(state.ready, state.readyTimeoutMs ?? 15000); } diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts new file mode 100644 index 0000000000..e590d0886a --- /dev/null +++ b/src/agent/opencode-native.ts @@ -0,0 +1,168 @@ +// Native opencode mode (#820 opencode line; npm-package design tracked in +// #809): the package-installed OpenCode 2.x plugin bootstraps its own proxy — +// the pi pattern (#519/#706), adapted to opencode's egress seam. Flow at +// plugin load: +// 1. spawn the package's own proxy (`dist/index.js start`, ephemeral port, +// parent-pid watchdog = this opencode process) via ensureProxyRunning — +// a healthy compatible instance is ATTACHED, not doubled; +// 2. register an http.request hook that rewrites model-API URLs to +// `/bili/` and stamps nothing else — header +// stamping / tools / compaction reporting all reuse the shared V2 setup +// (opencode-v2.ts), which detects the proxy through the env var set in +// step 1; +// 3. set BILLION_CONTEXT_PROXY after bootstrap so tool execute() and the +// compaction reporter find the proxy through their existing env path. +// +// Why URL rewrite instead of pi's global fetch patch: opencode's plugins have +// no fetch seam they can patch — the only observed egress hook is http.request +// with the outgoing fetch Request at e.request. WHATWG Request.url is +// read-only at runtime (verified live on 2.0.x, #810), so the request REFERENCE +// is replaced with a new Request to `/bili/` carrying the same +// method/headers/body. +// +// Liveness gate (differs from pi by design): an http.request hook CANNOT +// observe send failures (the host swallows them; #809 verification list), so +// unlike pi's post-failure respawn, every outgoing request first probes +// `/__bili/health` (bounded) of the current origin and respawns if dead. If +// no origin can be made healthy the request goes DIRECT (uncompressed) and a +// one-time stderr warning fires — recovery is automatic once a proxy is +// healthy again (no permanent latch; each request re-verifies). Bootstrap +// retries are rate-limited to one attempt per RESPAWN_COOLDOWN_MS so a +// persistently failing spawn does not become a per-request spawn storm. +// +// Skipped when a proxy is already managed (BILLION_CONTEXT_PROXY set by a +// `bili` launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ launch) or +// opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0). +// +// Deployment: OpenCode 2.x `plugin` entries must be DIRECTORIES whose index.js +// is the entrypoint (bare file paths are rejected, #754 probe) — `bili plugin +// install opencode` writes /plugins/billion-context/index.js +// re-exporting this entry (same wrapper shape the launcher builds, +// src/launcher.ts prepareOpencodeHttpRewrite). + +import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; +import { nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; +import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; + +/** Decides whether the native bootstrap should run in this process. */ +export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean { + return nativeBootstrapGate(env, "BILI_NATIVE_OPENCODE"); +} + +const HEALTH_TIMEOUT_MS = 1500; +const RESPAWN_COOLDOWN_MS = 15_000; + +async function probeHealth(origin: string): Promise { + try { + const res = await fetch(`${origin}/__bili/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) }); + return res.ok; + } catch { + return false; + } +} + +export interface OpencodeNativeRouteDeps { + probe?: (origin: string) => Promise; + /** Bootstrap retry interval when no live origin is held (tests shrink it). */ + respawnCooldownMs?: number; +} + +/** Build the native-mode route callback consumed by createOpencodeV2Setup. + * The probe is injectable for tests; the default does a bounded GET of + * /__bili/health. */ +export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNativeRouteDeps = {}): (e: V2HttpRequestEvent, s: V2State) => Promise { + const probe = deps.probe ?? probeHealth; + const respawnCooldownMs = deps.respawnCooldownMs ?? RESPAWN_COOLDOWN_MS; + let warned = false; + let lastRespawn = 0; + + const healthyOrigin = async (): Promise => { + let ownedThenLost = false; + if (state.origin !== undefined) { + if (await probe(state.origin)) return state.origin; + // Proxy died mid-session. Clearing origin first makes concurrent + // callers share the same state.ready (dedup). + ownedThenLost = true; + state.origin = undefined; + } + // Retry bootstrap whenever no live origin is held — either just lost + // it or the load-time bootstrap failed (the hook cannot observe send + // failures, so nothing else would retry). Cooldown bounds attempts to + // one per interval instead of one per request. + if (state.respawn !== undefined && (ownedThenLost || Date.now() - lastRespawn >= respawnCooldownMs)) { + lastRespawn = Date.now(); + state.ready = state.respawn(); + } + const o = await readyOrigin(state); + if (o !== undefined && (await probe(o))) return o; + if (ownedThenLost) state.onGiveUp?.(); + return undefined; + }; + + return async (e, s) => { + const url = typeof e.request?.url === "string" ? e.request.url : undefined; + if (url === undefined) return; + if (!isModelApiUrl(url)) return; + const target = await healthyOrigin(); + if (target === undefined) { + if (!warned) { + warned = true; + console.error("bili-native-opencode: proxy unavailable — model requests go direct (uncompressed)"); + } + return; + } + warned = false; + s.proxyBase = target; + try { + e.request = new Request(`${target}/bili/${url}`, e.request as unknown as Request); + } catch { + // undici refuses to copy a body-bearing Request without explicit + // duplex — reconstruct with the body stream passed explicitly. + const old = e.request as unknown as { method?: unknown; headers?: Iterable | null; body?: ReadableStream | null }; + try { + const init: RequestInit & { duplex?: "half" } = { method: typeof old.method === "string" ? old.method : "GET" }; + const pairs: [string, string][] = []; + try { + for (const pair of old.headers ?? []) pairs.push([pair[0], pair[1]]); + } catch {} + if (pairs.length > 0) init.headers = pairs; + if (old.body != null) { + init.body = old.body as RequestInit["body"]; + init.duplex = "half"; + } + e.request = new Request(`${target}/bili/${url}`, init); + } catch { + // replacement impossible (exotic body) — request goes direct + } + } + }; +} + +const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined) }; + +async function bootstrap(): Promise { + try { + const handle = await ensureProxyRunning( + { host: LAUNCHER_DEFAULT_HOST, port: 0, passthrough: false, debug: false }, + { scriptPath: nativeProxyScriptPath() }, + ); + state.origin = handle.origin; + process.env.BILLION_CONTEXT_PROXY = handle.origin; + return handle.origin; + } catch (err) { + console.error(`bili-native-opencode: proxy bootstrap failed — model traffic goes direct (uncompressed): ${err instanceof Error ? err.message : String(err)}`); + return undefined; + } +} + +if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNativeOpencode(process.env)) { + const start = singleFlight(bootstrap); + state.respawn = start; + state.onGiveUp = () => { + delete process.env.BILLION_CONTEXT_PROXY; + }; + state.ready = start(); +} + +export default { id: "billion-context-opencode-native", setup: createOpencodeV2Setup({ route: createNativeRoute(state) }) }; diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts new file mode 100644 index 0000000000..821efe0b85 --- /dev/null +++ b/src/agent/opencode-v2.ts @@ -0,0 +1,224 @@ +// Shared OpenCode 2.x (V2 plugin API) setup factory — one implementation of +// tool registration / header stamping / context-window refresh / compaction +// boundary reporting used by BOTH deployment modes: +// - launcher mode: src/agent/opencode.ts (proxy pointed at by config/env) +// - native mode: src/agent/opencode-native.ts (self-spawned proxy) +// Keeping the protocol logic here means the two modes cannot drift apart. +// +// No acp-kernel, no compression logic — the proxy is the single compression +// authority. Structural types only (no @opencode/plugin import) so this file +// stays loadable under both host generations via the object exports above it +// (V2 validates `{ id, setup }`; V1 >= 1.18.29 calls `.server()`). +// +// Runtime API facts — VERSION-SPECIFIC (the 2.x plugin surface changes between +// builds; do not generalize beyond the build named): +// - next-17444 pre-release (probed live by the author): model.request registers +// but NEVER FIRES; http.request fires per outgoing provider request with a +// fetch Request at e.request (mutating e.request.headers reaches the wire); +// NO ctx.tool.reload(); command editor list/get/update/remove only (no ADD — +// hence no /acp under V2; acp_status tool is the in-host equivalent). +// - @opencode/cli 2.0.x stable (provenance confirmed during #754 review; +// probed live on 2.0.1 + 2.0.3): setup() is chosen over server(); BOTH +// model.request and http.request hooks fire (e.request mutation reaches the +// wire); ctx.tool = {reload, transform, hook} (reload EXISTS here); +// ctx.command.transform(editor.add) CAN add commands (TUI invocation needs +// Tab+Enter completion accept; `run` mode dispatches no slash commands at +// all); configured `plugin` entries must be DIRECTORIES (file paths are +// rejected with WARN "configured plugin path must be a directory"; the +// directory's index.js is the entrypoint) — the launcher wraps this single +// file accordingly (src/launcher.ts opencodeMajorVersion). End-to-end +// verified on 2.0.3: true plugin mode, native tools via the plugin tool +// endpoint, zero wire-level injection. +// - npm dev builds 2026-09-13 / 2026-09-14 (probed live during #754 review): +// first loads plugins via V1 server() only; second exposes setup() but has +// no ctx.session / ctx.tool at all. Adjacent dev builds disagree with each +// other and with both of the above. +// Consequence: every registration below uses optional chaining so the plugin +// is inert-safe on any surface; when no seam fires, sessions transparently run +// in proxy mode (wire-level tool injection) instead of failing. Tools stay +// registered synchronously from bundled schemas (exact parity with the proxy's +// openai tool list, src/compress-tool.ts) because reload-based refresh is not +// available on all observed surfaces. + +import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; +import { forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; + +type V2Registration = { dispose?: () => void | Promise }; + +interface V2Headers { + set(name: string, value: string): void; +} + +export interface V2HttpRequestEvent { + sessionID?: unknown; + model?: { providerID?: unknown; id?: unknown }; + request?: { url?: unknown; headers?: V2Headers | null }; +} + +interface V2ToolEditor { + add(tool: { + name: string; + description?: string; + input: unknown; + options?: { namespace?: string; permission?: string; codemode?: boolean; pinned?: boolean }; + execute: (input: Record, ctx: { sessionID: string }) => Promise<{ content: string }>; + }): void; +} + +interface V2CatalogModelEntry { + providerID?: unknown; + id?: unknown; + limit?: { context?: unknown }; +} + +export interface V2PluginContext { + session?: { + hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; + }; + tool?: { + transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; + }; + event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record }> | undefined }; + catalog?: { model?: { list?: () => Promise<{ data?: V2CatalogModelEntry[] }> | undefined } | undefined }; +} + +const WINDOW_REFRESH_MS = 60000; + +// Kill switch = fully inert (same semantics as detectProxyBase): gates header stamping, tool forwarding, compaction reporting. +const pluginDisabled = (): boolean => process.env.BILLION_CONTEXT_PLUGIN === "0"; + +const V2_BILI_TOOLS = [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI].map((t) => ({ + name: t.function.name, + description: t.function.description, + input: t.function.parameters, +})); + +export interface V2State { + proxyBase?: string; + windows?: Map; + windowsAt?: number; +} + +function refreshWindows(ctx: V2PluginContext, state: V2State): void { + const now = Date.now(); + if (state.windows && state.windowsAt !== undefined && now - state.windowsAt < WINDOW_REFRESH_MS) return; + state.windowsAt = now; + void (async () => { + try { + const res = await ctx.catalog?.model?.list?.(); + const map = new Map(); + for (const m of res?.data ?? []) { + const pid = typeof m.providerID === "string" ? m.providerID : ""; + const id = typeof m.id === "string" ? m.id : ""; + const c = m.limit?.context; + if (pid && id && typeof c === "number" && Number.isFinite(c) && c > 0) map.set(`${pid}/${id}`, Math.floor(c)); + } + if (map.size > 0) state.windows = map; + } catch { + // catalog unavailable — window header simply goes unstamped + } + })(); +} + +export interface OpencodeV2SetupOptions { + /** Native mode only: called for EVERY outgoing provider request before + * stamping. Owns proxy discovery and URL rewriting to the self-spawned + * proxy (idempotent on already-routed URLs) and sets state.proxyBase + * when traffic is routed. Absent in launcher mode (no routing). */ + route?: (e: V2HttpRequestEvent, state: V2State) => void | Promise; +} + +export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ctx: V2PluginContext) => Promise<() => void> { + return async (ctx: V2PluginContext): Promise<() => void> => { + const ac = new AbortController(); + const state: V2State = {}; + const registrations: V2Registration[] = []; + + const stampHeaders = (e: V2HttpRequestEvent): void => { + const headers = e.request?.headers; + const sid = typeof e.sessionID === "string" ? e.sessionID : ""; + if (!headers || typeof headers.set !== "function" || !sid || !state.proxyBase) return; + headers.set("x-bili-plugin-conversation", sid); + headers.set("x-bili-plugin", "opencode"); + const model = e.model; + if (model && typeof model.providerID === "string" && typeof model.id === "string") { + const window = state.windows?.get(`${model.providerID}/${model.id}`); + if (window !== undefined) headers.set("x-bili-plugin-context-window", String(window)); + } + }; + + const httpRequestHook = async (e: V2HttpRequestEvent): Promise => { + if (pluginDisabled()) return; + const url = e.request?.url; + if (typeof url !== "string") return; + if (options.route !== undefined) { + // Native mode: route owns discovery + rewriting (it is called + // per request even once state.proxyBase is known, because the + // URL rewrite must happen per request and env detection alone + // would skip it after bootstrap). + await options.route(e, state); + } else if (!state.proxyBase) { + state.proxyBase = proxyBaseFromUrl(url) ?? proxyBaseFromEnv(); + } + if (!state.proxyBase) return; + refreshWindows(ctx, state); + stampHeaders(e); + }; + + const hookReg = await ctx.session?.hook?.("http.request", httpRequestHook); + if (hookReg) registrations.push(hookReg); + + const toolReg = await ctx.tool?.transform?.((editor) => { + for (const t of V2_BILI_TOOLS) { + editor.add({ + name: t.name, + description: t.description, + input: t.input, + options: { codemode: false, permission: "allow" }, + execute: async (args, tctx) => { + if (pluginDisabled()) return { content: "bili: disabled (BILLION_CONTEXT_PLUGIN=0)" }; + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!base) return { content: "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)" }; + try { + const result = await forwardTool(base, tctx.sessionID, t.name, args); + return { content: result }; + } catch (err) { + return { content: err instanceof Error ? err.message : String(err) }; + } + }, + }); + } + }); + if (toolReg) registrations.push(toolReg); + + const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); + if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { + void (async () => { + try { + for await (const evt of subscription) { + if (evt?.type !== "session.compaction.ended" || pluginDisabled()) continue; + const data = evt.data; + const cid = data && typeof data.sessionID === "string" ? data.sessionID : ""; + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!cid || !base) continue; + reportCompactionBoundary(base, cid).catch(() => {}); + } + } catch { + // subscription closed (abort on cleanup) + } + })(); + } + + return () => { + ac.abort(); + for (const r of registrations) { + try { + void r.dispose?.(); + } catch {} + } + state.proxyBase = undefined; + state.windows = undefined; + state.windowsAt = undefined; + }; + }; +} diff --git a/src/agent/opencode.ts b/src/agent/opencode.ts index 58926ef8f4..998578ed23 100644 --- a/src/agent/opencode.ts +++ b/src/agent/opencode.ts @@ -7,9 +7,14 @@ // - binds the opencode session id to the proxy session via the // pending-register queue (POST /__bili/plugin/register on session.created) // - renders the proxy's buildStatusPanel via an ignored chat message +// +// OpenCode 2.x (V2 plugin API) loads `{ id, setup }` instead of `.server()` — +// setup comes from the shared factory src/agent/opencode-v2.ts, which the +// native npm entry (opencode-native.ts) reuses so both deployment modes share +// one protocol implementation. The V2 runtime-API facts live in that file. -import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; -import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +import { createOpencodeV2Setup } from "./opencode-v2.js"; +import { fetchProxyVersion } from "./shared.js"; interface OpencodeCommandConfig { template: string; @@ -127,206 +132,7 @@ const server = async (ctx: OpencodePluginContext): Promise => { }; }; -// --------------------------------------------------------------------------- -// OpenCode 2.0 (V2 plugin API). Same protocol-client contract as V1 above: no -// acp-kernel, no compression logic — the proxy is the single compression -// authority. Structural types only (no @opencode/plugin import) so this file -// stays loadable under both host generations via the object export below -// (V2 validates `{ id, setup }`; V1 >= 1.18.29 calls `.server()`). -// -// Runtime API facts — VERSION-SPECIFIC (the 2.x plugin surface changes between -// builds; do not generalize beyond the build named): -// - next-17444 pre-release (probed live by the author): model.request registers -// but NEVER FIRES; http.request fires per outgoing provider request with a -// fetch Request at e.request (mutating e.request.headers reaches the wire); -// NO ctx.tool.reload(); command editor list/get/update/remove only (no ADD — -// hence no /acp under V2; acp_status tool is the in-host equivalent). -// - @opencode/cli 2.0.x stable (provenance confirmed during #754 review; -// probed live on 2.0.1 + 2.0.3): setup() is chosen over server(); BOTH -// model.request and http.request hooks fire (e.request mutation reaches the -// wire); ctx.tool = {reload, transform, hook} (reload EXISTS here); -// ctx.command.transform(editor.add) CAN add commands (TUI invocation needs -// Tab+Enter completion accept; `run` mode dispatches no slash commands at -// all); configured `plugin` entries must be DIRECTORIES (file paths are -// rejected with WARN "configured plugin path must be a directory"; the -// directory's index.js is the entrypoint) — the launcher wraps this single -// file accordingly (src/launcher.ts opencodeMajorVersion). End-to-end -// verified on 2.0.3: true plugin mode, native tools via the plugin tool -// endpoint, zero wire-level injection. -// - npm dev builds 2026-09-13 / 2026-09-14 (probed live during #754 review): -// first loads plugins via V1 server() only; second exposes setup() but has -// no ctx.session / ctx.tool at all. Adjacent dev builds disagree with each -// other and with both of the above. -// Consequence: every registration below uses optional chaining so the plugin -// is inert-safe on any surface; when no seam fires, sessions transparently run -// in proxy mode (wire-level tool injection) instead of failing. Tools stay -// registered synchronously from bundled schemas (exact parity with the proxy's -// openai tool list, src/compress-tool.ts) because reload-based refresh is not -// available on all observed surfaces. -// --------------------------------------------------------------------------- - -type V2Registration = { dispose?: () => void | Promise }; - -interface V2Headers { - set(name: string, value: string): void; -} - -interface V2HttpRequestEvent { - sessionID?: unknown; - model?: { providerID?: unknown; id?: unknown }; - request?: { url?: unknown; headers?: V2Headers | null }; -} - -interface V2ToolEditor { - add(tool: { - name: string; - description?: string; - input: unknown; - options?: { namespace?: string; permission?: string; codemode?: boolean; pinned?: boolean }; - execute: (input: Record, ctx: { sessionID: string }) => Promise<{ content: string }>; - }): void; -} - -interface V2CatalogModelEntry { - providerID?: unknown; - id?: unknown; - limit?: { context?: unknown }; -} - -interface V2PluginContext { - session?: { - hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; - }; - tool?: { - transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; - }; - event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record }> | undefined }; - catalog?: { model?: { list?: () => Promise<{ data?: V2CatalogModelEntry[] }> | undefined } | undefined }; -} - -const WINDOW_REFRESH_MS = 60000; - -// Kill switch = fully inert (same semantics as detectProxyBase): gates header stamping, tool forwarding, compaction reporting. -const pluginDisabled = (): boolean => process.env.BILLION_CONTEXT_PLUGIN === "0"; - -const V2_BILI_TOOLS = [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI].map((t) => ({ - name: t.function.name, - description: t.function.description, - input: t.function.parameters, -})); - -interface V2State { - proxyBase?: string; - windows?: Map; - windowsAt?: number; -} - -function refreshWindows(ctx: V2PluginContext, state: V2State): void { - const now = Date.now(); - if (state.windows && state.windowsAt !== undefined && now - state.windowsAt < WINDOW_REFRESH_MS) return; - state.windowsAt = now; - void (async () => { - try { - const res = await ctx.catalog?.model?.list?.(); - const map = new Map(); - for (const m of res?.data ?? []) { - const pid = typeof m.providerID === "string" ? m.providerID : ""; - const id = typeof m.id === "string" ? m.id : ""; - const c = m.limit?.context; - if (pid && id && typeof c === "number" && Number.isFinite(c) && c > 0) map.set(`${pid}/${id}`, Math.floor(c)); - } - if (map.size > 0) state.windows = map; - } catch { - // catalog unavailable — window header simply goes unstamped - } - })(); -} - -const setup = async (ctx: V2PluginContext): Promise<() => void> => { - const ac = new AbortController(); - const state: V2State = {}; - const registrations: V2Registration[] = []; - - const stampHeaders = (e: V2HttpRequestEvent): void => { - const headers = e.request?.headers; - const sid = typeof e.sessionID === "string" ? e.sessionID : ""; - if (!headers || typeof headers.set !== "function" || !sid || !state.proxyBase) return; - headers.set("x-bili-plugin-conversation", sid); - headers.set("x-bili-plugin", "opencode"); - const model = e.model; - if (model && typeof model.providerID === "string" && typeof model.id === "string") { - const window = state.windows?.get(`${model.providerID}/${model.id}`); - if (window !== undefined) headers.set("x-bili-plugin-context-window", String(window)); - } - }; - - const httpRequestHook = async (e: V2HttpRequestEvent): Promise => { - if (pluginDisabled()) return; - const url = e.request?.url; - if (typeof url !== "string") return; - if (!state.proxyBase) { - state.proxyBase = proxyBaseFromUrl(url) ?? proxyBaseFromEnv(); - } - if (!state.proxyBase) return; - refreshWindows(ctx, state); - stampHeaders(e); - }; - - const hookReg = await ctx.session?.hook?.("http.request", httpRequestHook); - if (hookReg) registrations.push(hookReg); - - const toolReg = await ctx.tool?.transform?.((editor) => { - for (const t of V2_BILI_TOOLS) { - editor.add({ - name: t.name, - description: t.description, - input: t.input, - options: { codemode: false, permission: "allow" }, - execute: async (args, tctx) => { - if (pluginDisabled()) return { content: "bili: disabled (BILLION_CONTEXT_PLUGIN=0)" }; - const base = state.proxyBase ?? proxyBaseFromEnv(); - if (!base) return { content: "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)" }; - try { - const result = await forwardTool(base, tctx.sessionID, t.name, args); - return { content: result }; - } catch (err) { - return { content: err instanceof Error ? err.message : String(err) }; - } - }, - }); - } - }); - if (toolReg) registrations.push(toolReg); - - const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); - if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { - void (async () => { - try { - for await (const evt of subscription) { - if (evt?.type !== "session.compaction.ended" || pluginDisabled()) continue; - const data = evt.data; - const cid = data && typeof data.sessionID === "string" ? data.sessionID : ""; - const base = state.proxyBase ?? proxyBaseFromEnv(); - if (!cid || !base) continue; - reportCompactionBoundary(base, cid).catch(() => {}); - } - } catch { - // subscription closed (abort on cleanup) - } - })(); - } - return () => { - ac.abort(); - for (const r of registrations) { - try { - void r.dispose?.(); - } catch {} - } - state.proxyBase = undefined; - state.windows = undefined; - state.windowsAt = undefined; - }; -}; +const setup = createOpencodeV2Setup(); export default { id: "billion-context-opencode", setup, server }; diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts index 400c769732..7d4703878e 100644 --- a/src/agent/pi-native.ts +++ b/src/agent/pi-native.ts @@ -14,28 +14,19 @@ // `bili` MITM launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ // launch) or opted out (BILI_NATIVE_PI=0). -import path from "node:path"; -import { fileURLToPath } from "node:url"; +import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; import { createBiliPlugin } from "./pi.js"; +import { nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; import { installNativeFetchIntercept, type NativeInterceptState } from "./native-intercept.js"; -import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; +import { fetchStatus } from "./shared.js"; -/** dist/agent/pi-native.js → dist/index.js (the package bin). Resolved at - * runtime so the artifact works from any install root. */ -export function nativeProxyScriptPath(fromUrl: string = import.meta.url): string { - return path.resolve(path.dirname(fileURLToPath(fromUrl)), "..", "index.js"); -} +// Shared plumbing lives in native-bootstrap.ts (side-effect-free — importing +// pi-native.ts from another host entry must not run pi's bootstrap). +export { nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; /** Decides whether the native bootstrap should run in this process. */ export function shouldBootstrapNative(env: NodeJS.ProcessEnv): boolean { - if (env.BILLION_CONTEXT_PLUGIN === "0") return false; - if (env.BILI_NATIVE_PI === "0") return false; - // A `bili` launch already owns a proxy — attach to its mode instead of - // spawning a second one (MITM transparent sets BILLION_CONTEXT_PROXY; - // /bili/ rewrite mode sets BILI_PROVIDER_REWRITES). - if (env.BILLION_CONTEXT_PROXY !== undefined && env.BILLION_CONTEXT_PROXY.trim().length > 0) return false; - if (env.BILI_PROVIDER_REWRITES !== undefined) return false; - return true; + return nativeBootstrapGate(env, "BILI_NATIVE_PI"); } function errMessage(err: unknown): string { @@ -60,21 +51,6 @@ async function bootstrap(): Promise { } } -/** Concurrent callers share one in-flight bootstrap — a burst of TypeErrors - * (the proxy died mid-session) must not spawn one proxy per failing request: - * ensureProxyRunning has no in-flight dedup of its own. */ -export function singleFlight(fn: () => Promise): () => Promise { - let inFlight: Promise | undefined; - return (): Promise => { - if (inFlight === undefined) { - inFlight = fn().finally(() => { - inFlight = undefined; - }); - } - return inFlight; - }; -} - // node:test imports this module for shouldBootstrapNative/nativeProxyScriptPath — // never bootstrap a real proxy from inside a test run. if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNative(process.env)) { diff --git a/src/launcher.ts b/src/launcher.ts index ff89e4d0ab..5e1601cb35 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -175,6 +175,10 @@ export interface LauncherDeps { * default (process.argv[1]) is WRONG inside a host process like pi — * pi-native.ts passes its own package's dist/index.js instead. */ scriptPath?: string; + /** #819: explicit Node executable for spawning the proxy. Inside a host + * process (opencode/pi native binary) process.execPath is NOT Node; + * defaults to resolveNodeRuntime(). */ + nodeRuntime?: string; } export function isLaunchClient(value: string): value is ClientName { @@ -1885,6 +1889,33 @@ function proxyStartArgs(opts: LaunchOptions): string[] { return args; } +/** #819: resolve the executable that runs the proxy entry script. In a plain + * Node CLI, process.execPath is correct; inside a host process (the opencode + * or pi native binary) it is the HOST executable — spawning it with a .js + * argv passes the script to the wrong program. A live Node always wins, then + * an explicit BILLION_CONTEXT_NODE override, then a PATH search. */ +export function resolveNodeRuntime( + execPath: string = process.execPath, + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, + existsImpl: (p: string) => boolean = fs.existsSync, +): string { + const base = path.basename(execPath).toLowerCase(); + if (base === "node" || base === "node.exe") return execPath; + const override = typeof env.BILLION_CONTEXT_NODE === "string" ? env.BILLION_CONTEXT_NODE.trim() : ""; + if (override.length > 0 && existsImpl(override)) return override; + const sep = platform === "win32" ? ";" : ":"; + const names = platform === "win32" ? ["node.exe"] : ["node"]; + for (const dir of (env.PATH ?? "").split(sep)) { + if (!dir) continue; + for (const name of names) { + const candidate = path.join(dir, name); + if (existsImpl(candidate)) return candidate; + } + } + throw new Error("bili: cannot find a Node runtime to spawn the proxy (this process is not Node) — set BILLION_CONTEXT_NODE"); +} + export async function ensureProxyRunning( opts: LaunchOptions, deps: LauncherDeps = {}, @@ -1974,7 +2005,7 @@ export async function ensureProxyRunning( let child: SpawnChild; try { child = spawnImpl( - process.execPath, + deps.nodeRuntime ?? resolveNodeRuntime(), [script, ...proxyStartArgs({ ...opts, port })], { detached: true, diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 6dca5c2d87..00b3fb2710 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -7,7 +7,7 @@ // 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 +// opencode ~/.config/opencode/opencode.json 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. @@ -434,33 +434,117 @@ function opencodeJson(): string { return path.join(os.homedir(), ".config", "opencode", "opencode.json"); } +// #820 native mode: OpenCode 2.x rejects bare FILE paths in `plugin` — the +// entry must be a DIRECTORY whose index.js is the entrypoint (#754 probe). The +// wrapper directory lives next to the config so it survives config moves. +function opencodePluginDir(configFile: string): string { + return path.join(path.dirname(configFile), "plugins", "billion-context"); +} + function opencodeInstall(): string { const file = opencodeJson(); - const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); - requireDistFile(mcpJs); const data = readJson(file); - const mcp = (data.mcp as Record | undefined) ?? {}; - if ("bili" in mcp) return `opencode: already installed (${file})`; - mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: proxyOriginForInstall() }, enabled: true }; - data.mcp = mcp; + const notes: string[] = []; + + // 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. + try { + const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); + requireDistFile(mcpJs); + const mcp = (data.mcp 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; + notes.push("mcp.bili written"); + } + } catch (err) { + notes.push(`mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`); + } + + // Native plugin (#820): self-spawned proxy + http.request URL rewrite. + const agentJs = path.join(selfPackageRoot(), "dist", "agent", "opencode-native.js"); + requireDistFile(agentJs); + 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}`); + } else { + notes.push("plugin 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); - return `opencode: installed -> ${file} mcp.bili`; + return `opencode: installed -> ${file} (${notes.join("; ")})`; } function opencodeRemove(): string { const file = opencodeJson(); const data = readJson(file); + const notes: string[] = []; + const mcp = data.mcp as Record | undefined; - if (!mcp || !("bili" in mcp)) return `opencode: not installed (${file})`; - delete mcp.bili; - if (Object.keys(mcp).length === 0) delete data.mcp; - writeJson(file, data); - return `opencode: removed from ${file}`; + if (mcp && "bili" in mcp) { + delete mcp.bili; + if (Object.keys(mcp).length === 0) delete data.mcp; + notes.push("mcp.bili removed"); + } + + 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; + fs.rmSync(dir, { recursive: true, force: true }); + notes.push(`plugin dir removed (${dir})`); + } + + if (notes.length > 0) { + const cur = data.compaction as Record | undefined; + if (cur && cur.auto === false) { + const bak = `${file}.bili-bak`; + if (fs.existsSync(bak)) { + try { + const bakData = JSON.parse(fs.readFileSync(bak, "utf8")) as { compaction?: unknown }; + if (bakData.compaction === undefined) delete data.compaction; + else data.compaction = bakData.compaction; + notes.push("compaction restored from backup"); + } catch { + // unreadable backup — leave current settings untouched + } + } else if (Object.keys(cur).length === 1) { + // no pre-install config existed, so our {auto:false} is the entire + // 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; + notes.push("compaction removed (no prior config)"); + } + } + } + + if (notes.length > 0) writeJson(file, data); + return notes.length > 0 ? `opencode: removed from ${file} (${notes.join("; ")})` : `opencode: not installed (${file})`; } function opencodeStatus(): string { - const mcp = readJson(opencodeJson()).mcp as Record | undefined; - return mcp && "bili" in mcp ? "installed" : "not installed"; + const file = opencodeJson(); + const data = readJson(file); + const mcp = data.mcp as Record | undefined; + const plugins = Array.isArray(data.plugin) ? (data.plugin as unknown[]).filter((x): x is string => typeof x === "string") : []; + return (mcp !== undefined && "bili" in mcp) || plugins.includes(opencodePluginDir(file)) ? "installed" : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index ed562b71c9..fa4568ffd3 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -66,6 +66,7 @@ import { resolveOpencodeConfigFile, findFreePort, ensureProxyRunning, + resolveNodeRuntime, stopProxy, resolveLauncherWindow, resolveCodexBudgetArgs, @@ -2531,6 +2532,58 @@ test("runLaunch dsh: no loopback custom providers — no DSH_HOME overlay (#535 } }); +test("resolveNodeRuntime: a live Node executable wins without consulting PATH (#819)", () => { + assert.equal(resolveNodeRuntime("/usr/local/bin/node", { PATH: "" }, "linux", () => false), "/usr/local/bin/node"); + assert.equal(resolveNodeRuntime("C:/nodejs/node.exe", {}, "win32", () => false), "C:/nodejs/node.exe"); +}); + +test("resolveNodeRuntime: non-Node host uses the BILLION_CONTEXT_NODE override when it exists", () => { + const exists = (p: string): boolean => p === "/opt/runtimes/node"; + assert.equal( + resolveNodeRuntime("/usr/bin/opencode", { BILLION_CONTEXT_NODE: " /opt/runtimes/node ", PATH: "" }, "linux", exists), + "/opt/runtimes/node", + ); + // an override pointing at a missing file is ignored — the PATH search still runs + assert.equal( + resolveNodeRuntime("/usr/bin/opencode", { BILLION_CONTEXT_NODE: "/missing/node", PATH: "/usr/local/bin" }, "linux", (p) => p === "/usr/local/bin/node"), + "/usr/local/bin/node", + ); +}); + +test("resolveNodeRuntime: PATH search finds node for non-Node hosts (posix + win32 shapes)", () => { + const posixExists = (p: string): boolean => p === "/opt/host/bin/node"; + assert.equal( + resolveNodeRuntime("/snap/opencode/current/usr/bin/opencode", { PATH: "/nonexistent:/opt/host/bin" }, "linux", posixExists), + "/opt/host/bin/node", + ); + // forward-slash fake paths keep the join platform-independent on any CI host + const winExists = (p: string): boolean => p === "C:/Program Files/nodejs/node.exe"; + assert.equal( + resolveNodeRuntime("C:/opencode/opencode.exe", { PATH: "C:/nope;C:/Program Files/nodejs" }, "win32", winExists), + "C:/Program Files/nodejs/node.exe", + ); +}); + +test("resolveNodeRuntime: throws with the actionable message when nothing resolves", () => { + assert.throws( + () => resolveNodeRuntime("/usr/bin/opencode", { PATH: "/nonexistent" }, "linux", () => false), + /BILLION_CONTEXT_NODE/, + ); +}); + +test("ensureProxyRunning: spawns the resolved Node runtime, not blind process.execPath (#819)", async () => { + let spawnedCmd: string | null = null; + const spawnImpl: SpawnFn = (cmd) => { + spawnedCmd = cmd as string; + return makeFakeChild(42425); + }; + await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { fetchImpl: async () => ({ ok: true }), spawnImpl, readInstanceFile: () => undefined, nodeRuntime: "/custom/node" }, + ); + assert.equal(spawnedCmd, "/custom/node"); +}); + test("runLaunch omp: launcher hands per-model windows to the spawned proxy", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-mw-")); const prevHome = process.env.HOME; diff --git a/tests/opencode-native.test.ts b/tests/opencode-native.test.ts new file mode 100644 index 0000000000..7c4f375ba1 --- /dev/null +++ b/tests/opencode-native.test.ts @@ -0,0 +1,242 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +// The module-level guard reads NODE_TEST_CONTEXT while the module EVALUATES, +// and static imports hoist above any assignment — so the value must be set +// first and the module loaded dynamically. +process.env.NODE_TEST_CONTEXT = "1"; + +import type { NativeInterceptState } from "../src/agent/native-intercept.ts"; +import type { V2HttpRequestEvent, V2PluginContext, V2State } from "../src/agent/opencode-v2.ts"; +import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../src/compress-tool.ts"; + +const { shouldBootstrapNativeOpencode, createNativeRoute } = await import("../src/agent/opencode-native.ts"); +const { createOpencodeV2Setup } = await import("../src/agent/opencode-v2.ts"); +const nativeDefault = (await import("../src/agent/opencode-native.ts")).default; + +const EXPECTED_TOOLS = [...ACP_TOOLS_OPENAI.map((t) => t.function.name), ABSORB_TOOL_OPENAI.function.name]; +const MODEL_URL = "https://api.anthropic.com/v1/messages"; +const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); + +test("shouldBootstrapNativeOpencode: true in a bare host with no bili env", () => { + assert.equal(shouldBootstrapNativeOpencode({}), true); +}); + +test("shouldBootstrapNativeOpencode: false when the plugin or native mode is opted out", () => { + assert.equal(shouldBootstrapNativeOpencode({ BILLION_CONTEXT_PLUGIN: "0" }), false); + assert.equal(shouldBootstrapNativeOpencode({ BILI_NATIVE_OPENCODE: "0" }), false); +}); + +test("shouldBootstrapNativeOpencode: false when a bili launch already owns a proxy", () => { + assert.equal(shouldBootstrapNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), false); + assert.equal(shouldBootstrapNativeOpencode({ BILLION_CONTEXT_PROXY: " " }), true); + assert.equal(shouldBootstrapNativeOpencode({ BILI_PROVIDER_REWRITES: '{"vllm":"http://127.0.0.1:1/bili/http://x"}' }), false); +}); + +test("native entry exports an OpenCode 2.x plugin object", () => { + assert.equal(nativeDefault.id, "billion-context-opencode-native"); + assert.equal(typeof nativeDefault.setup, "function"); +}); + +test("route: healthy origin rewrites the request reference and records proxyBase", async () => { + const origin = "http://127.0.0.1:9999"; + const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) }; + const route = createNativeRoute(state, { probe: async () => true }); + const s: V2State = {}; + const body = JSON.stringify({ messages: [] }); + const e: V2HttpRequestEvent = { + sessionID: "ses_1", + request: new Request(MODEL_URL, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer x" }, body }), + }; + await route(e, s); + const out = e.request as Request; + assert.equal(out.url, `${origin}/bili/${MODEL_URL}`); + assert.equal(out.method, "POST"); + assert.equal(out.headers.get("authorization"), "Bearer x"); + assert.equal(await out.text(), body); + assert.equal(s.proxyBase, origin); +}); + +test("route: non-model-API and already-routed URLs are left untouched", async () => { + const origin = "http://127.0.0.1:9999"; + const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) }; + const route = createNativeRoute(state, { probe: async () => true }); + const s: V2State = {}; + const plain = new Request("https://github.com/repos"); + const e1: V2HttpRequestEvent = { request: plain }; + await route(e1, s); + assert.equal(e1.request, plain); + const routed = new Request(`${origin}/bili/${MODEL_URL}`); + const e2: V2HttpRequestEvent = { request: routed }; + await route(e2, s); + assert.equal(e2.request, routed); + assert.equal(s.proxyBase, undefined); +}); + +test("route: waits for a pending bootstrap before routing", async () => { + let release!: (o: string) => void; + const state: NativeInterceptState = { origin: undefined, ready: new Promise((r) => (release = r)) }; + const route = createNativeRoute(state, { probe: async () => true }); + const s: V2State = {}; + const e: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + const pending = route(e, s); + release("http://127.0.0.1:4321"); + await pending; + assert.equal((e.request as Request).url, `http://127.0.0.1:4321/bili/${MODEL_URL}`); +}); + +test("route: failed bootstrap sends direct with a single warning (no respawn wired)", async () => { + const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined) }; + const route = createNativeRoute(state, { probe: async () => true }); + const s: V2State = {}; + const origError = console.error; + const warnings: string[] = []; + console.error = (...args: unknown[]) => { + warnings.push(args.join(" ")); + }; + try { + const e1: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e1, s); + assert.equal((e1.request as Request).url, MODEL_URL); + const e2: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e2, s); + assert.equal((e2.request as Request).url, MODEL_URL); + assert.equal(s.proxyBase, undefined); + assert.equal(warnings.filter((w) => w.includes("bili-native-opencode")).length, 1); + } finally { + console.error = origError; + } +}); + +test("route: dead origin respawns once and routes to the replacement", async () => { + const dead = "http://127.0.0.1:1111"; + const live = "http://127.0.0.1:2222"; + const state: NativeInterceptState = { + origin: dead, + ready: Promise.resolve(dead), + respawn: async () => { + state.origin = live; + return live; + }, + }; + const route = createNativeRoute(state, { probe: async (o) => o === live }); + const s: V2State = {}; + const e: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e, s); + assert.equal((e.request as Request).url, `${live}/bili/${MODEL_URL}`); + assert.equal(s.proxyBase, live); +}); + +test("route: failed respawn fires onGiveUp once and holds direct (cooldown suppresses re-spawn)", async () => { + const dead = "http://127.0.0.1:1111"; + let gaveUp = 0; + let respawns = 0; + const state: NativeInterceptState = { + origin: dead, + ready: Promise.resolve(dead), + respawn: async () => { + respawns++; + return undefined; + }, + onGiveUp: () => { + gaveUp++; + }, + }; + const route = createNativeRoute(state, { probe: async () => false }); + const s: V2State = {}; + const e1: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e1, s); + assert.equal((e1.request as Request).url, MODEL_URL); + assert.equal(gaveUp, 1); + assert.equal(respawns, 1); + const e2: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e2, s); + assert.equal(gaveUp, 1); + assert.equal(respawns, 1); +}); + +test("route: load-time bootstrap failure retries after the cooldown only", async () => { + let respawns = 0; + const state: NativeInterceptState = { + origin: undefined, + ready: Promise.resolve(undefined), + respawn: async () => { + respawns++; + return undefined; + }, + }; + const route = createNativeRoute(state, { probe: async () => true, respawnCooldownMs: 10 }); + const s: V2State = {}; + const e1: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e1, s); + assert.equal(respawns, 1); + const e2: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e2, s); + assert.equal(respawns, 1); + await sleep(15); + const e3: V2HttpRequestEvent = { request: new Request(MODEL_URL) }; + await route(e3, s); + assert.equal(respawns, 2); +}); + +test("setup(route): header stamping applies to the REPLACED request, tools register natively", async () => { + const origin = "http://127.0.0.1:9999"; + const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) }; + const hooks: Array<{ name: string; cb: (e: V2HttpRequestEvent) => void | Promise }> = []; + const tools: string[] = []; + const ctx: V2PluginContext = { + session: { + hook: (name, cb) => { + hooks.push({ name, cb }); + return { dispose() {} }; + }, + }, + tool: { + transform: (add) => { + add({ add: (t) => tools.push(t.name) }); + return { dispose() {} }; + }, + }, + }; + const setup = createOpencodeV2Setup({ route: createNativeRoute(state, { probe: async () => true }) }); + const cleanup = await setup(ctx); + assert.deepEqual(hooks.map((h) => h.name), ["http.request"]); + assert.deepEqual(tools.sort(), [...EXPECTED_TOOLS].sort()); + const e: V2HttpRequestEvent = { + sessionID: "ses_abc", + model: { providerID: "anthropic", id: "claude-x" }, + request: new Request(MODEL_URL, { method: "POST" }), + }; + await hooks[0].cb(e); + const out = e.request as Request; + assert.equal(out.url, `${origin}/bili/${MODEL_URL}`); + assert.equal(out.headers.get("x-bili-plugin-conversation"), "ses_abc"); + assert.equal(out.headers.get("x-bili-plugin"), "opencode"); + cleanup(); +}); + +test("setup(route): kill switch keeps the hook fully inert", async () => { + const origin = "http://127.0.0.1:9999"; + const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) }; + const hooks: Array<(e: V2HttpRequestEvent) => void | Promise> = []; + const ctx: V2PluginContext = { + session: { + hook: (_name, cb) => { + hooks.push(cb); + return { dispose() {} }; + }, + }, + }; + const setup = createOpencodeV2Setup({ route: createNativeRoute(state, { probe: async () => true }) }); + const cleanup = await setup(ctx); + process.env.BILLION_CONTEXT_PLUGIN = "0"; + try { + const req = new Request(MODEL_URL); + const e: V2HttpRequestEvent = { sessionID: "ses_x", request: req }; + await hooks[0](e); + assert.equal(e.request, req); + } finally { + delete process.env.BILLION_CONTEXT_PLUGIN; + cleanup(); + } +}); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index da795580ba..1cf87a2b55 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -881,12 +881,31 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO assert.match(pluginInstall("codex"), /already installed/); assert.match(pluginRemove("codex"), /removed/); - assert.match(pluginInstall("opencode"), /installed/); - const oc = JSON.parse(fs.readFileSync(path.join(home, ".config/opencode/opencode.json"), "utf8")) as { mcp: Record }> }; - 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"); + // #820: pre-seed user settings — install must merge around them and remove must restore them. + 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"] })); + 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 }; + 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.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(pluginRemove("opencode"), /removed/); - assert.equal((JSON.parse(fs.readFileSync(path.join(home, ".config/opencode/opencode.json"), "utf8")) as { mcp?: unknown }).mcp, undefined); + oc = JSON.parse(fs.readFileSync(ocFile, "utf8")); + 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.compaction, { auto: true, buffer: 100 }); + assert.equal(oc.$schema, "https://opencode.ai/config.json"); + assert.equal(fs.existsSync(ocPluginDir), false); assert.throws(() => pluginInstall("claude"), /claude: install failed/); // The CLAUDE stub above keeps that assertion deterministic even on @@ -901,6 +920,31 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO fs.rmSync(home, { recursive: true, force: true }); }); +test("plugin install opencode without a live proxy: MCP shell skipped, native plugin still installed (#820)", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc-noproxy-")); + 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 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 }; + assert.equal(data.mcp, undefined); + assert.deepEqual(data.plugin, [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.compaction, undefined); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + test("omp plugin: scoped matching, existence check, overlay redirect (issue #392)", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-plugin-omp-")); const root = selfPackageRoot(); diff --git a/tsup.config.ts b/tsup.config.ts index 1683082ee4..91e76068d9 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from "tsup"; export default defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/opencode.ts", "src/agent/dsh-acp.ts"], + entry: ["src/index.ts", "src/mcp.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts"], format: ["esm"], target: "node20", platform: "node", From 385db4f96c814f5576539203c22d8ecf2d850bc1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 00:50:56 +0800 Subject: [PATCH 07/29] =?UTF-8?q?docs:=20README=20=E2=80=94=20fix=203-spac?= =?UTF-8?q?e=20continuation=20drift;=20table=20row=20covers=20native=20plu?= =?UTF-8?q?gin=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a235128c8f..66a5a62578 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ Pick by your client: |---|---| | **pi** | [`billion-context-pi`](https://github.com/ranxianglei/billion-context-pi) (in-process extension) | | **opencode 1.x** | [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) (in-process extension, V1 plugin API) or `bili opencode` | -| **opencode 2.0+** | `bili opencode` (built-in V2 plugin — native tools, no separate package) | +| **opencode 2.0+** | `bili opencode` (built-in V2 plugin — native tools, no separate package) or `bili plugin install opencode` (self-spawning native plugin, no launcher) | | **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 | @@ -263,7 +263,7 @@ contract: never fires, the plugin stays inert and the session transparently runs in plain proxy mode (wire-level tool injection) instead of breaking — observed on two adjacent `dev` builds (2026-09-13 / 2026-09-14) whose API surfaces - differ from each other (#754 review probes); conversely verified end-to-end + differ from each other (#754 review probes); conversely verified end-to-end on `@opencode/cli` 2.0.3 (native `acp_status` executed through the plugin endpoint, zero wire-level injection). - **Native (no launcher):** with the package installed from npm, run From 42c178202b22ca59ba332d9bc1d59d4076952a7d Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 10:39:48 +0800 Subject: [PATCH 08/29] =?UTF-8?q?feat(agent):=20BILLION=5FCONTEXT=5FNATIVE?= =?UTF-8?q?=20coexistence=20marker=20=E2=80=94=20standalone=20extensions?= =?UTF-8?q?=20can=20back=20off=20under=20native=20mode=20(#820)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verified against billion-context-pi and opencode-acp sources that their existing auto-disable does not cover native mode: both check BILLION_CONTEXT_PROXY only at extension-load time (native bootstrap writes it asynchronously after the proxy is up) and detect /bili/ in the configured baseUrl (native rewrites at the fetch layer, invisible to config). Launcher mode and manual wiring keep working as before. - native-bootstrap.ts: markNativeHost() — synchronous, first writer wins - pi-native.ts / opencode-native.ts: set BILLION_CONTEXT_NATIVE= at module evaluation, gated on the same shouldBootstrap*() condition as the bootstrap itself (opt-outs and launcher-managed launches leave it unset) - README 'Which do I need?': mutual-exclusion note; CHANGELOG entries - tests: marker assertions in pi-native/opencode-native files + units --- CHANGELOG.md | 3 ++- README.md | 2 ++ src/agent/native-bootstrap.ts | 15 +++++++++++++++ src/agent/opencode-native.ts | 7 +++++-- src/agent/pi-native.ts | 7 +++++-- tests/opencode-native.test.ts | 19 +++++++++++++++++++ tests/pi-native.test.ts | 7 +++++++ 7 files changed, 55 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89adca234d..1cdb542fed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,9 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Features +- **Coexistence marker for standalone extensions (#820)**: the pi-native and opencode-native entries now set `BILLION_CONTEXT_NATIVE=` synchronously at module evaluation (gated on their own bootstrap gate, first writer wins — `markNativeHost()` in `src/agent/native-bootstrap.ts`), so the standalone `billion-context-pi` / `opencode-acp` extensions can stand down at action time when running alongside a native entry. Verified against both sibling repos that the pre-existing auto-disable does NOT cover native mode: they check `BILLION_CONTEXT_PROXY` only at extension-load time (native bootstrap writes it asynchronously, after the proxy is up) and detect `/bili/` in the configured baseUrl (native rewrites at the fetch layer, invisible to config); launcher mode and manual wiring keep working as before. Standalone-side adoption of the marker is tracked in each repo's issue tracker. - **opencode 2.x native mode: package-installed opencode gets plugin-mode compression with no launcher (#820, npm-package design #809)**: `bili plugin install opencode` now installs, alongside the MCP shell (kept, but optional — a missing live proxy origin skips it instead of failing the install), a self-spawning native plugin: a stable wrapper directory `/plugins/billion-context/index.js` re-exporting `dist/agent/opencode-native.js` (OpenCode 2.x rejects bare FILE paths in `plugin` — the directory's index.js is the entrypoint, #754 probe) plus `compaction.auto=false` (single compression owner; merge-preserving, restored from the `.bili-bak` backup on remove). At plugin load the same gate as pi-native applies (`BILI_NATIVE_OPENCODE=0` opt-out; skipped entirely under a `bili` launch) and the package's own proxy is bootstrapped through `ensureProxyRunning` (attach-or-spawn, ephemeral port, parent-pid watchdog, `deps.scriptPath`). OpenCode plugins have no fetch seam to patch, so egress interception uses the `http.request` hook, replacing the outgoing fetch Request REFERENCE with `new Request("/bili/", old)` carrying method/headers/body (WHATWG Request.url is read-only at runtime — verified live, #810). Header stamping, native tools and compaction-boundary reporting reuse the shared V2 setup factory (`src/agent/opencode-v2.ts`, extracted from opencode.ts so launcher mode and native mode share ONE protocol implementation). Because an http.request hook cannot observe send failures (the host swallows them), every request liveness-probes `/__bili/health` of the current origin before routing — one respawn if the proxy died mid-session, direct send + one-time warning when no origin can be made healthy (auto-recovering: each request re-verifies, unlike pi's lifetime latch). Also fixes #819: `ensureProxyRunning` resolves the Node executable for spawning via `resolveNodeRuntime()` (live Node wins → `BILLION_CONTEXT_NODE` override → PATH search) instead of blind `process.execPath`, which inside a host binary (opencode/pi native) is the HOST executable — the spawned proxy died at spawn. -- **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Known limitation: the legacy `billion-context-pi` adapter package detects the proxy via a `/bili/` baseUrl prefix, which native mode does not rewrite — users with BOTH installed get double compression; `bili plugin install pi` already removes the legacy entry, a detection warning for pi-package-manager installs is tracked in #513. +- **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `/bili/` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Coexistence: the legacy `billion-context-pi` adapter detects the proxy via a `/bili/` baseUrl prefix or `BILLION_CONTEXT_PROXY`, both invisible under native mode (fetch-layer rewrite; env written asynchronously) — so BOTH installed used to mean double compression. `bili plugin install pi` removes the legacy entry, and the synchronous `BILLION_CONTEXT_NATIVE=pi` marker (see above) lets the standalone extension stand down at action time once it adopts the check. ### Fixes - **pi native mode: a failed mid-session respawn degrades to direct sends instead of rethrowing the proxy's network error (#513 audit)**: when the spawned proxy died and the one-shot respawn also failed, the interceptor logged an `onDispatch(url, "direct")` but then re-threw the original `TypeError` — the model call died instead of degrading, and `BILLION_CONTEXT_PROXY` stayed set, so the event-time `session_before_compact` cancel kept cancelling native compaction while all traffic went direct (context grows uncompressed, forever). The give-up path now sends the request direct (same contract as bootstrap failure, one-time warning) and fires a new `onGiveUp` hook; pi-native uses it to clear the env so event-time ownership checks disarm together with the traffic. Also: rebuilding a Request-object input against the rewritten target no longer routes caller-side defects (already-consumed or locked body) into the proxy-death branch — they surface as-is instead of respawning an orphaned proxy. diff --git a/README.md b/README.md index 66a5a62578..6faefab8dc 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,8 @@ 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. + ## Install ```bash diff --git a/src/agent/native-bootstrap.ts b/src/agent/native-bootstrap.ts index 7c63706560..acff49e57d 100644 --- a/src/agent/native-bootstrap.ts +++ b/src/agent/native-bootstrap.ts @@ -25,6 +25,21 @@ export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string): return true; } +/** Coexistence marker (#820): tells standalone in-process bili extensions + * (billion-context-pi / opencode-acp) that a host-native entry owns THIS + * process so they back off instead of double-compressing. Set synchronously + * at module evaluation — before any await — because those extensions check + * BILLION_CONTEXT_PROXY at load time (our bootstrap writes it only after the + * proxy is up) and their /bili/ baseUrl check never sees our fetch-layer + * rewrite. First writer wins: one process hosts one native entry. Callers + * gate on their own shouldBootstrap*() so opt-outs and launches where a bili + * launcher already manages the proxy leave the marker unset. */ +export function markNativeHost(env: NodeJS.ProcessEnv, host: string): void { + if (env.BILLION_CONTEXT_NATIVE === undefined || env.BILLION_CONTEXT_NATIVE.length === 0) { + env.BILLION_CONTEXT_NATIVE = host; + } +} + /** Concurrent callers share one in-flight bootstrap — a burst of failures * (the proxy died mid-session) must not spawn one proxy per failing request: * ensureProxyRunning has no in-flight dedup of its own. */ diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index e590d0886a..0c60e8a486 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -41,7 +41,7 @@ // src/launcher.ts prepareOpencodeHttpRewrite). import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; -import { nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { markNativeHost, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; @@ -156,7 +156,10 @@ async function bootstrap(): Promise { } } -if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNativeOpencode(process.env)) { +const nativeActive = shouldBootstrapNativeOpencode(process.env); +if (nativeActive) markNativeHost(process.env, "opencode"); + +if (process.env.NODE_TEST_CONTEXT === undefined && nativeActive) { const start = singleFlight(bootstrap); state.respawn = start; state.onGiveUp = () => { diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts index 7d4703878e..0359c86488 100644 --- a/src/agent/pi-native.ts +++ b/src/agent/pi-native.ts @@ -16,7 +16,7 @@ import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; import { createBiliPlugin } from "./pi.js"; -import { nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { markNativeHost, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; import { installNativeFetchIntercept, type NativeInterceptState } from "./native-intercept.js"; import { fetchStatus } from "./shared.js"; @@ -51,9 +51,12 @@ async function bootstrap(): Promise { } } +const nativeActive = shouldBootstrapNative(process.env); +if (nativeActive) markNativeHost(process.env, "pi"); + // node:test imports this module for shouldBootstrapNative/nativeProxyScriptPath — // never bootstrap a real proxy from inside a test run. -if (process.env.NODE_TEST_CONTEXT === undefined && shouldBootstrapNative(process.env)) { +if (process.env.NODE_TEST_CONTEXT === undefined && nativeActive) { const start = singleFlight(bootstrap); state.respawn = start; state.onGiveUp = () => { diff --git a/tests/opencode-native.test.ts b/tests/opencode-native.test.ts index 7c4f375ba1..5817dce63d 100644 --- a/tests/opencode-native.test.ts +++ b/tests/opencode-native.test.ts @@ -12,6 +12,7 @@ import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../src/compress-tool.ts"; const { shouldBootstrapNativeOpencode, createNativeRoute } = await import("../src/agent/opencode-native.ts"); const { createOpencodeV2Setup } = await import("../src/agent/opencode-v2.ts"); +const { markNativeHost } = await import("../src/agent/native-bootstrap.ts"); const nativeDefault = (await import("../src/agent/opencode-native.ts")).default; const EXPECTED_TOOLS = [...ACP_TOOLS_OPENAI.map((t) => t.function.name), ABSORB_TOOL_OPENAI.function.name]; @@ -38,6 +39,24 @@ test("native entry exports an OpenCode 2.x plugin object", () => { assert.equal(typeof nativeDefault.setup, "function"); }); +// #820 coexistence: the standalone opencode-acp extension must see this marker +// at its action-time check even though our bootstrap writes BILLION_CONTEXT_PROXY +// only later (async) and its /bili/ baseUrl check never sees our rewrite. +test("module evaluation marks the process as a native opencode host", () => { + assert.equal(process.env.BILLION_CONTEXT_NATIVE, "opencode"); +}); + +test("markNativeHost: sets when unset, first writer wins", () => { + const env: NodeJS.ProcessEnv = {}; + markNativeHost(env, "pi"); + assert.equal(env.BILLION_CONTEXT_NATIVE, "pi"); + markNativeHost(env, "opencode"); + assert.equal(env.BILLION_CONTEXT_NATIVE, "pi"); + const blank: NodeJS.ProcessEnv = { BILLION_CONTEXT_NATIVE: "" }; + markNativeHost(blank, "omp"); + assert.equal(blank.BILLION_CONTEXT_NATIVE, "omp"); +}); + test("route: healthy origin rewrites the request reference and records proxyBase", async () => { const origin = "http://127.0.0.1:9999"; const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) }; diff --git a/tests/pi-native.test.ts b/tests/pi-native.test.ts index bd21b0c131..bab59ca16e 100644 --- a/tests/pi-native.test.ts +++ b/tests/pi-native.test.ts @@ -5,6 +5,13 @@ import { pathToFileURL } from "node:url"; import { shouldBootstrapNative, nativeProxyScriptPath, singleFlight } from "../src/agent/pi-native.ts"; import { ensureProxyRunning, type SpawnChild, type SpawnFn } from "../src/launcher.ts"; +// #820 coexistence: standalone billion-context-pi checks env at load time, so +// the marker must be set synchronously during module evaluation (before our +// async bootstrap writes BILLION_CONTEXT_PROXY) for its action-time back-off. +test("module evaluation marks the process as a native pi host", () => { + assert.equal(process.env.BILLION_CONTEXT_NATIVE, "pi"); +}); + test("shouldBootstrapNative: true in a bare host with no bili env", () => { assert.equal(shouldBootstrapNative({}), true); }); From 54f8fb2560bdddd9aad4c539128a501e41da0c15 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 14:13:26 +0800 Subject: [PATCH 09/29] fix(launcher,plugin-install): async spawn error + non-object mcp guards (#809 D/N4) Two safety defects found while hands-on testing #824 (reported in #809). D - ensureProxyRunning registered only child.on("exit"), not "error". An async spawn failure (EACCES/ENOENT on the resolved runtime) emits "error", so with no listener it became an uncaughtException that killed the host process, while the poll loop misreported "did not become healthy" after burning SPAWN_WAIT_MS. Register an "error" handler, break the poll on it, and reject with the cause. N4 - opencode.json may carry a non-object "mcp" (e.g. a bare string); `"bili" in ` throws TypeError. Install tolerated it via its catch ("skipped"), but remove had no guard and crashed, leaving an irreconcilable half-installed state; status returned "error:". Guard all three sites with isPlainMcpObject: install defaults absent->{} and skips present-non-object, while remove/status degrade gracefully so remove always cleans up (reversibility). Regression tests: launcher.test.ts (child "error" handler registered + rejects "spawn failed"); plugin-agent.test.ts (install/remove/status survive a string mcp). Full suite green: 1652 pass / 0 fail / 2 pre-existing skip. --- src/launcher.ts | 13 ++++++++++++- src/plugin-install.ts | 32 ++++++++++++++++++++++---------- tests/launcher.test.ts | 29 +++++++++++++++++++++++++++++ tests/plugin-agent.test.ts | 25 +++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 11 deletions(-) diff --git a/src/launcher.ts b/src/launcher.ts index 5e1601cb35..42178ab577 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -2036,16 +2036,23 @@ export async function ensureProxyRunning( // healthy — otherwise a startup crash (bad config, missing upstream, …) // burns the whole SPAWN_WAIT_MS poll window before erroring. let childExit: { code: number | null; signal: string | null } | undefined; + // #809/D: an async spawn failure (EACCES/ENOENT on the resolved runtime) + // emits 'error', not 'exit'. Unhandled, it becomes an uncaughtException + // that kills the host process; capture it so we fail fast with the cause. + let childError: unknown; child.on?.("exit", (...rest: unknown[]) => { childExit = { code: typeof rest[0] === "number" ? rest[0] : null, signal: typeof rest[1] === "string" ? rest[1] : null, }; }); + child.on?.("error", (...rest: unknown[]) => { + childError = rest[0]; + }); const deadline = now() + SPAWN_WAIT_MS; while (now() < deadline) { - if (childExit) break; + if (childExit || childError !== undefined) break; await sleepImpl(HEALTH_POLL_INTERVAL_MS); const inst = readInstance(); if (isProxyInstanceFile(inst) && inst.launchToken === launchToken) { @@ -2064,6 +2071,10 @@ export async function ensureProxyRunning( return { origin: proxyOrigin(opts.host, port), port, child, logPath }; } } + if (childError !== undefined) { + const detail = childError instanceof Error ? childError.message : String(childError); + throw new Error(`bili: proxy spawn failed (${detail}) (log: ${logPath})`); + } if (childExit) { const detail = childExit.code !== null ? `code ${childExit.code}` diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 00b3fb2710..a825ba4088 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -441,6 +441,13 @@ function opencodePluginDir(configFile: string): string { return path.join(path.dirname(configFile), "plugins", "billion-context"); } +// #809/N4: opencode.json may carry a non-object `mcp` (e.g. a bare string); +// `"bili" in ` throws TypeError. Guard so install/remove/status +// degrade gracefully instead of crashing (a crashing remove leaves no cleanup). +function isPlainMcpObject(v: unknown): v is Record { + return v !== null && typeof v === "object" && !Array.isArray(v); +} + function opencodeInstall(): string { const file = opencodeJson(); const data = readJson(file); @@ -451,12 +458,17 @@ function opencodeInstall(): string { try { const mcpJs = path.join(selfPackageRoot(), "dist", "mcp.js"); requireDistFile(mcpJs); - const mcp = (data.mcp 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; - notes.push("mcp.bili written"); + const rawMcp = data.mcp; + if (rawMcp != null && !isPlainMcpObject(rawMcp)) { + notes.push('mcp.bili skipped (opencode.json "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; + notes.push("mcp.bili written"); + } } } catch (err) { notes.push(`mcp.bili skipped (${err instanceof Error ? err.message : String(err)})`); @@ -495,8 +507,8 @@ function opencodeRemove(): string { const data = readJson(file); const notes: string[] = []; - const mcp = data.mcp as Record | undefined; - if (mcp && "bili" in mcp) { + const mcp = data.mcp; + if (isPlainMcpObject(mcp) && "bili" in mcp) { delete mcp.bili; if (Object.keys(mcp).length === 0) delete data.mcp; notes.push("mcp.bili removed"); @@ -542,9 +554,9 @@ function opencodeRemove(): string { function opencodeStatus(): string { const file = opencodeJson(); const data = readJson(file); - const mcp = data.mcp as Record | undefined; + const mcp = data.mcp; const plugins = Array.isArray(data.plugin) ? (data.plugin as unknown[]).filter((x): x is string => typeof x === "string") : []; - return (mcp !== undefined && "bili" in mcp) || plugins.includes(opencodePluginDir(file)) ? "installed" : "not installed"; + return (isPlainMcpObject(mcp) && "bili" in mcp) || plugins.includes(opencodePluginDir(file)) ? "installed" : "not installed"; } // — dispatch ———————————————————————————————————————————————————————————— diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index fa4568ffd3..023af4c179 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -906,6 +906,35 @@ test("ensureProxyRunning: throws when never healthy within deadline", async () = ); }); +test("ensureProxyRunning: registers a child 'error' handler so an async spawn failure rejects cleanly (#809/D)", async () => { + const subscribed: string[] = []; + const child: SpawnChild = { + pid: 42420, + unref() {}, + kill() { + return true; + }, + on(event, listener) { + subscribed.push(event); + if (event === "error") setImmediate(() => listener(new Error("spawn /bad/node EACCES"))); + }, + }; + await assert.rejects( + ensureProxyRunning( + { host: "127.0.0.1", port: 8791, passthrough: false, debug: false }, + { + spawnImpl: () => child, + fetchImpl: async () => ({ ok: false }), + readInstanceFile: () => undefined, + sleep: () => new Promise((r) => setTimeout(r, 0)), + }, + ), + /spawn failed/, + ); + assert.ok(subscribed.includes("exit")); + assert.ok(subscribed.includes("error"), "an 'error' handler was registered on the spawned proxy child"); +}); + function recordedInstance(over: Partial = {}): InstanceFile { return { origin: "http://127.0.0.1:8787", diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 1cf87a2b55..b846053072 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -945,6 +945,31 @@ test("plugin install opencode without a live proxy: MCP shell skipped, native pl } }); +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 () => { + 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.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.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"); + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + test("omp plugin: scoped matching, existence check, overlay redirect (issue #392)", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-plugin-omp-")); const root = selfPackageRoot(); From 1d4f38cbb7fc20b53a08f15876d19df263485208 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 15:48:21 +0800 Subject: [PATCH 10/29] feat(agent): opencode native attach-to-external-proxy mode (#809) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add an attach sub-mode to the opencode native entry (#824 vehicle): when BILLION_CONTEXT_ATTACH= is set, model traffic routes through that pre-existing proxy instead of spawning one — no ownership, no respawn. Per owner decision (#809): an explicitly-specified external proxy fails CLOSED on death (always rewrite toward the target, never fall back to direct, plus one loud diagnostic); unset defaults to the self-spawn watchdog (attach off by default). Precedence off > attach > spawn — a launcher-owned proxy or opt-out stands down even over an explicit attach. - native-bootstrap.ts: nativeAttachOrigin() env resolver (http(s)-only, trailing-slash normalized). - native-intercept.ts: NativeInterceptState.attach flag. - opencode-native.ts: planNativeOpencode() three-way posture decision; the route gains an attach branch sharing the extracted rewriteToProxy helper (self-spawn path unchanged). - tests/opencode-native.test.ts: resolution, precedence, and fail-closed route behavior (7 cases). typecheck clean; 1652 pass / 0 fail / 2 skip (win32-only); build OK. Refs #809. --- src/agent/native-bootstrap.ts | 18 ++++++ src/agent/native-intercept.ts | 4 ++ src/agent/opencode-native.ts | 103 +++++++++++++++++++++++++--------- tests/opencode-native.test.ts | 95 ++++++++++++++++++++++++++++++- 4 files changed, 190 insertions(+), 30 deletions(-) diff --git a/src/agent/native-bootstrap.ts b/src/agent/native-bootstrap.ts index acff49e57d..d519b2ef17 100644 --- a/src/agent/native-bootstrap.ts +++ b/src/agent/native-bootstrap.ts @@ -25,6 +25,24 @@ export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string): return true; } +/** External-proxy attach signal (#809): when BILLION_CONTEXT_ATTACH holds a + * valid http(s) origin, a host-native entry routes model traffic THROUGH that + * pre-existing proxy instead of spawning its own — no ownership, no respawn, + * fail-closed on its death. Returns the normalized origin (trailing slash + * stripped) or undefined when unset/blank/malformed/non-http(s). */ +export function nativeAttachOrigin(env: NodeJS.ProcessEnv): string | undefined { + const raw = env.BILLION_CONTEXT_ATTACH; + if (raw === undefined) return undefined; + const url = raw.trim(); + if (url.length === 0 || !/^https?:\/\//i.test(url)) return undefined; + try { + new URL(url); + } catch { + return undefined; + } + return url.replace(/\/+$/, ""); +} + /** Coexistence marker (#820): tells standalone in-process bili extensions * (billion-context-pi / opencode-acp) that a host-native entry owns THIS * process so they back off instead of double-compressing. Set synchronously diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index d77901aa0c..c39efb3edf 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -19,6 +19,10 @@ export interface NativeInterceptState { * BILLION_CONTEXT_PROXY env) so event-time ownership checks disarm with * the traffic. */ onGiveUp?: () => void; + /** Attach mode (#809): route through a user-supplied external proxy at + * state.origin instead of a spawned one — no respawn, fail-closed on + * death. Set by the host entry when BILLION_CONTEXT_ATTACH is present. */ + attach?: boolean; /** How long a pre-ready model request waits for the bootstrap before * falling back to a direct (uncompressed) send. */ readyTimeoutMs?: number; diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 0c60e8a486..41903d7a64 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -41,7 +41,7 @@ // src/launcher.ts prepareOpencodeHttpRewrite). import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; -import { markNativeHost, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; @@ -50,6 +50,17 @@ export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean { return nativeBootstrapGate(env, "BILI_NATIVE_OPENCODE"); } +/** Decide this process's native posture (#809). Precedence off > attach > + * spawn: a launcher-owned proxy or an opt-out stands us down entirely (even + * over an explicit attach); otherwise attach to BILLION_CONTEXT_ATTACH when + * given, else spawn our own watchdog proxy. */ +export function planNativeOpencode(env: NodeJS.ProcessEnv): { mode: "off" | "attach" | "spawn"; attachOrigin?: string } { + if (!shouldBootstrapNativeOpencode(env)) return { mode: "off" }; + const attachOrigin = nativeAttachOrigin(env); + if (attachOrigin !== undefined) return { mode: "attach", attachOrigin }; + return { mode: "spawn" }; +} + const HEALTH_TIMEOUT_MS = 1500; const RESPAWN_COOLDOWN_MS = 15_000; @@ -75,6 +86,7 @@ export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNat const probe = deps.probe ?? probeHealth; const respawnCooldownMs = deps.respawnCooldownMs ?? RESPAWN_COOLDOWN_MS; let warned = false; + let attachWarned = false; let lastRespawn = 0; const healthyOrigin = async (): Promise => { @@ -100,26 +112,13 @@ export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNat return undefined; }; - return async (e, s) => { - const url = typeof e.request?.url === "string" ? e.request.url : undefined; - if (url === undefined) return; - if (!isModelApiUrl(url)) return; - const target = await healthyOrigin(); - if (target === undefined) { - if (!warned) { - warned = true; - console.error("bili-native-opencode: proxy unavailable — model requests go direct (uncompressed)"); - } - return; - } - warned = false; - s.proxyBase = target; + const rewriteToProxy = (ev: V2HttpRequestEvent, target: string, url: string): void => { try { - e.request = new Request(`${target}/bili/${url}`, e.request as unknown as Request); + ev.request = new Request(`${target}/bili/${url}`, ev.request as unknown as Request); } catch { // undici refuses to copy a body-bearing Request without explicit // duplex — reconstruct with the body stream passed explicitly. - const old = e.request as unknown as { method?: unknown; headers?: Iterable | null; body?: ReadableStream | null }; + const old = ev.request as unknown as { method?: unknown; headers?: Iterable | null; body?: ReadableStream | null }; try { const init: RequestInit & { duplex?: "half" } = { method: typeof old.method === "string" ? old.method : "GET" }; const pairs: [string, string][] = []; @@ -131,12 +130,50 @@ export function createNativeRoute(state: NativeInterceptState, deps: OpencodeNat init.body = old.body as RequestInit["body"]; init.duplex = "half"; } - e.request = new Request(`${target}/bili/${url}`, init); + ev.request = new Request(`${target}/bili/${url}`, init); } catch { // replacement impossible (exotic body) — request goes direct } } }; + + return async (e, s) => { + const url = typeof e.request?.url === "string" ? e.request.url : undefined; + if (url === undefined) return; + if (!isModelApiUrl(url)) return; + + // Attach mode (#809): route through the user's external proxy. We do + // NOT own it — no spawn, no respawn. Fail-closed by construction: we + // always rewrite toward the target and never fall back to direct, so a + // dead target surfaces as a client-visible connection error (plus one + // loud diagnostic), never as silent uncompressed traffic. + if (state.attach) { + const target = state.origin; + if (target === undefined) return; + const up = await probe(target); + if (!up && !attachWarned) { + attachWarned = true; + console.error(`bili-native-opencode: external proxy ${target} unreachable — model requests will fail (compression unavailable)`); + } else if (up) { + attachWarned = false; + } + s.proxyBase = target; + rewriteToProxy(e, target, url); + return; + } + + const target = await healthyOrigin(); + if (target === undefined) { + if (!warned) { + warned = true; + console.error("bili-native-opencode: proxy unavailable — model requests go direct (uncompressed)"); + } + return; + } + warned = false; + s.proxyBase = target; + rewriteToProxy(e, target, url); + }; } const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined) }; @@ -156,16 +193,26 @@ async function bootstrap(): Promise { } } -const nativeActive = shouldBootstrapNativeOpencode(process.env); -if (nativeActive) markNativeHost(process.env, "opencode"); - -if (process.env.NODE_TEST_CONTEXT === undefined && nativeActive) { - const start = singleFlight(bootstrap); - state.respawn = start; - state.onGiveUp = () => { - delete process.env.BILLION_CONTEXT_PROXY; - }; - state.ready = start(); +const plan = planNativeOpencode(process.env); +if (plan.mode !== "off") { + markNativeHost(process.env, "opencode"); + if (process.env.NODE_TEST_CONTEXT === undefined) { + if (plan.mode === "attach") { + state.attach = true; + state.origin = plan.attachOrigin; + // Tools / compaction discover the proxy through this env path, as + // in self-spawn; no respawn/onGiveUp — the external proxy isn't + // ours to restart or clean up. + process.env.BILLION_CONTEXT_PROXY = plan.attachOrigin; + } else { + const start = singleFlight(bootstrap); + state.respawn = start; + state.onGiveUp = () => { + delete process.env.BILLION_CONTEXT_PROXY; + }; + state.ready = start(); + } + } } export default { id: "billion-context-opencode-native", setup: createOpencodeV2Setup({ route: createNativeRoute(state) }) }; diff --git a/tests/opencode-native.test.ts b/tests/opencode-native.test.ts index 5817dce63d..74fb4e3ef7 100644 --- a/tests/opencode-native.test.ts +++ b/tests/opencode-native.test.ts @@ -10,9 +10,9 @@ import type { NativeInterceptState } from "../src/agent/native-intercept.ts"; import type { V2HttpRequestEvent, V2PluginContext, V2State } from "../src/agent/opencode-v2.ts"; import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../src/compress-tool.ts"; -const { shouldBootstrapNativeOpencode, createNativeRoute } = await import("../src/agent/opencode-native.ts"); +const { shouldBootstrapNativeOpencode, createNativeRoute, planNativeOpencode } = await import("../src/agent/opencode-native.ts"); const { createOpencodeV2Setup } = await import("../src/agent/opencode-v2.ts"); -const { markNativeHost } = await import("../src/agent/native-bootstrap.ts"); +const { markNativeHost, nativeAttachOrigin } = await import("../src/agent/native-bootstrap.ts"); const nativeDefault = (await import("../src/agent/opencode-native.ts")).default; const EXPECTED_TOOLS = [...ACP_TOOLS_OPENAI.map((t) => t.function.name), ABSORB_TOOL_OPENAI.function.name]; @@ -259,3 +259,94 @@ test("setup(route): kill switch keeps the hook fully inert", async () => { cleanup(); } }); + +test("nativeAttachOrigin: unset/blank/malformed/non-http(s) all resolve to undefined", () => { + assert.equal(nativeAttachOrigin({}), undefined); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: "" }), undefined); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: " " }), undefined); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: "not a url" }), undefined); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: "ftp://127.0.0.1:21" }), undefined); +}); + +test("nativeAttachOrigin: normalizes a valid http(s) origin (trailing slash stripped)", () => { + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: "http://127.0.0.1:8787" }), "http://127.0.0.1:8787"); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: "http://127.0.0.1:8787///" }), "http://127.0.0.1:8787"); + assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: " https://proxy.example.com/ " }), "https://proxy.example.com"); +}); + +test("planNativeOpencode: default is spawn; opt-out and launcher-owned are off", () => { + assert.deepEqual(planNativeOpencode({}), { mode: "spawn" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILI_NATIVE_OPENCODE: "0" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), { mode: "off" }); +}); + +test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy", () => { + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_ATTACH: "http://10.0.0.5:9000/" }), + { mode: "attach", attachOrigin: "http://10.0.0.5:9000" }, + ); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_ATTACH: "garbage" }), { mode: "spawn" }); +}); + +test("planNativeOpencode: a launcher-owned proxy stands down even over an explicit attach", () => { + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_ATTACH: "http://10.0.0.5:9000" }), + { mode: "off" }, + ); +}); + +test("native route: attach mode routes model traffic through the external proxy", async () => { + const origin = "http://10.0.0.5:9000"; + let respawnCalls = 0; + const state: NativeInterceptState = { + attach: true, + origin, + ready: Promise.resolve(origin), + respawn: async () => { + respawnCalls++; + return undefined; + }, + }; + const s: V2State = {}; + const route = createNativeRoute(state, { probe: async () => true }); + const e: V2HttpRequestEvent = { sessionID: "ses_a", request: new Request(MODEL_URL, { method: "POST" }) }; + await route(e, s); + assert.equal((e.request as Request).url, `${origin}/bili/${MODEL_URL}`); + assert.equal(s.proxyBase, origin); + assert.equal(respawnCalls, 0); +}); + +test("native route: attach mode FAILS CLOSED when the external proxy is down", async () => { + const origin = "http://10.0.0.5:9000"; + const state: NativeInterceptState = { attach: true, origin, ready: Promise.resolve(origin) }; + const s: V2State = {}; + const warns: string[] = []; + const origErr = console.error; + console.error = (...a: unknown[]) => { + warns.push(a.join(" ")); + }; + try { + const route = createNativeRoute(state, { probe: async () => false }); + await route({ sessionID: "ses_b", request: new Request(MODEL_URL, { method: "POST" }) }, s); + const second: V2HttpRequestEvent = { sessionID: "ses_b", request: new Request(MODEL_URL, { method: "POST" }) }; + await route(second, s); + assert.equal((second.request as Request).url, `${origin}/bili/${MODEL_URL}`); + assert.ok(warns.some((w) => w.includes("unreachable")), "expected an unreachable diagnostic"); + assert.ok(warns.filter((w) => w.includes("unreachable")).length === 1, "expected exactly one warning"); + } finally { + console.error = origErr; + } +}); + +test("native route: attach mode leaves non-model requests untouched", async () => { + const origin = "http://10.0.0.5:9000"; + const state: NativeInterceptState = { attach: true, origin, ready: Promise.resolve(origin) }; + const s: V2State = {}; + const route = createNativeRoute(state, { probe: async () => true }); + const req = new Request("https://api.anthropic.com/v1/models", { method: "GET" }); + const e: V2HttpRequestEvent = { sessionID: "ses_c", request: req }; + await route(e, s); + assert.equal(e.request, req); + assert.equal(s.proxyBase, undefined); +}); From 11a82d79e757d12029b2cc19d30610aaf14647fc Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 18:25:44 +0800 Subject: [PATCH 11/29] feat(agent): register /acp command under OpenCode V2 (#809) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The /acp status command was implemented only against the legacy .server() plugin API and orphaned by the V2 migration — OpenCode 2.x loads `{id, setup}` and never calls `.server()`, so /acp never registered (native mode looked "inactive"). Register /acp in the shared createOpencodeV2Setup factory so BOTH launcher and native modes surface it. API verified against @opencode/cli v2.0.3 source: - ctx.command.transform(editor.add({name, description, execute})) — commands carry an execute(input) handler (input.sessionID is provided). - ctx.session.synthetic({sessionID, text}) — inserts a synthetic message that does NOT trigger a model turn (the V2 replacement for the legacy ignored no-reply prompt). /acp fetches /__bili/plugin/status?conversationId=&fallback=latest and renders the panel (or idle/error notice) via synthetic. Inert-safe on surfaces without ctx.command; TUI-only (`run` dispatches no slash commands). - src/agent/opencode-v2.ts: add command seam to V2PluginContext + V2CommandEditor types; register /acp after tool registration. - tests/opencode-v2.test.ts: fake ctx gains command.transform + session.synthetic; fake proxy serves /status; 2 new tests (panel render, no-proxy notice). typecheck clean; full suite 1654 pass / 0 fail / 2 skip (win32-only); build OK; dist markers confirmed in both agent entries. Refs #809. --- src/agent/opencode-v2.ts | 71 ++++++++++++++++++++++++++++++++++++++- tests/opencode-v2.test.ts | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 821efe0b85..07b66190fe 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -41,7 +41,7 @@ // available on all observed surfaces. import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; -import { forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; type V2Registration = { dispose?: () => void | Promise }; @@ -65,6 +65,19 @@ interface V2ToolEditor { }): void; } +interface V2CommandInvocation { + sessionID?: unknown; + [key: string]: unknown; +} + +interface V2CommandEditor { + add(def: { + name: string; + description?: string; + execute: (input: V2CommandInvocation) => Promise; + }): void; +} + interface V2CatalogModelEntry { providerID?: unknown; id?: unknown; @@ -74,10 +87,14 @@ interface V2CatalogModelEntry { export interface V2PluginContext { session?: { hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; + synthetic?: (input: { sessionID: string; text: string }) => Promise; }; tool?: { transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; }; + command?: { + transform?: (cb: (editor: V2CommandEditor) => void) => void | Promise; + }; event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record }> | undefined }; catalog?: { model?: { list?: () => Promise<{ data?: V2CatalogModelEntry[] }> | undefined } | undefined }; } @@ -191,6 +208,58 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct }); if (toolReg) registrations.push(toolReg); + // /acp status command (#809): registered via the V2 command editor where + // supported (2.0.x stable; inert-safe otherwise) and rendered as a + // synthetic non-model-turn message; TUI-only (`run` dispatches no slash cmds). + const commandReg = await ctx.command?.transform?.((editor) => { + editor.add({ + name: "acp", + description: "Show ACP status (billion-context proxy)", + execute: async (input) => { + const sid = typeof input.sessionID === "string" ? input.sessionID : ""; + let text: string; + if (pluginDisabled()) { + text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; + } else if (!sid) { + return; + } else { + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!base) { + text = "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)"; + } else { + try { + const res = await fetch(`${base}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); + const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; + if (typeof status.panel === "string" && status.panel.length > 0) { + text = status.panel; + } else if (status.ok === false) { + let version: string | undefined; + try { + version = await fetchProxyVersion(base); + } catch { + version = undefined; + } + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else { + text = "bili: proxy returned no status panel"; + } + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; + } + } + } + try { + await ctx.session?.synthetic?.({ sessionID: sid, text }); + } catch (err) { + console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); + } + }, + }); + }); + if (commandReg) registrations.push(commandReg); + const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { void (async () => { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 3023b6327a..ebdc814566 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -42,6 +42,11 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver }); return; } + if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, panel: "ACP-PANEL-OK" })); + return; + } res.writeHead(404); res.end("{}"); }); @@ -62,12 +67,20 @@ interface FakeAddedTool { execute: (input: Record, ctx: { sessionID: string }) => Promise<{ content: string }>; } +interface FakeAddedCommand { + name: string; + description?: string; + execute: (input: Record) => Promise; +} + function makeFakeCtx() { const eventQueue: Array<{ type?: unknown; data?: Record }> = []; let wake: (() => void) | undefined; let closed = false; let signal: AbortSignal | undefined; const addedTools: FakeAddedTool[] = []; + const addedCommands: FakeAddedCommand[] = []; + const syntheticCalls: Array<{ sessionID: string; text: string }> = []; let modelRequestCb: ((e: Record) => void | Promise) | undefined; const disposed: number[] = []; @@ -78,6 +91,10 @@ function makeFakeCtx() { modelRequestCb = cb; return { dispose: () => { disposed.push(1); } }; }, + synthetic: async (input: { sessionID: string; text: string }) => { + syntheticCalls.push(input); + return {}; + }, }, tool: { transform: async (cb: (editor: { add: (t: FakeAddedTool) => void }) => void) => { @@ -85,6 +102,12 @@ function makeFakeCtx() { return { dispose: () => { disposed.push(2); } }; }, }, + command: { + transform: async (cb: (editor: { add: (c: FakeAddedCommand) => void }) => void) => { + cb({ add: (c) => addedCommands.push(c) }); + return { dispose: () => { disposed.push(3); } }; + }, + }, event: { subscribe: (opts?: { signal?: AbortSignal }) => { signal = opts?.signal; @@ -126,6 +149,8 @@ function makeFakeCtx() { }, pushEvent: (evt: { type?: unknown; data?: Record }) => { eventQueue.push(evt); wake?.(); }, get addedTools() { return addedTools; }, + get addedCommands() { return addedCommands; }, + get syntheticCalls() { return syntheticCalls; }, get disposed() { return disposed; }, }; } @@ -316,6 +341,44 @@ test("v2 setup: cleanup aborts event subscription and disposes registrations", a } }); +test("v2 setup: /acp command registered and renders proxy status panel via synthetic", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp"); + assert.ok(acp, "/acp command registered"); + assert.equal(typeof acp!.execute, "function"); + await acp!.execute({ sessionID: "ses_acp_1" }); + await until(() => fake.syntheticCalls.length === 1); + assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); + assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", async () => { + const fake = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "s_nopx" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + } finally { + cleanup(); + } + }); +}); + test("fetchManifest openai format maps parameters to inputSchema", async () => { const MANIFEST_OPENAI = [ { name: "compress", description: "Compress a range", parameters: { type: "object", properties: { content: { type: "array" } }, required: ["content"] } }, From f857ff1666dfd3854e114dea5a24b210579cc807 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 16 Sep 2026 21:57:07 +0800 Subject: [PATCH 12/29] fix(agent): harden /acp under OpenCode V2 (guard order, status timeout, inert-safe registration) F1: check empty-sessionID guard before the disabled branch so a missing id never reaches ctx.session.synthetic with an empty id. F2: read status via shared fetchStatus (5s STATUS_TIMEOUT_MS soft-fail) instead of a bare unbounded fetch. F3: surface status.error in the no-panel fall-through. F4: wrap command registration in its own try/catch so an unsupported editor.add degrades to no-/acp instead of rejecting setup. F5: console.warn on the no-sessionID path so a broken host contract surfaces instead of dead silence. --- src/agent/opencode-v2.ts | 94 +++++++++++++++++++---------------- tests/opencode-v2.test.ts | 100 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 43 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 07b66190fe..b84a5c47a7 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -41,7 +41,7 @@ // available on all observed surfaces. import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; -import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +import { fetchProxyVersion, fetchStatus, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; type V2Registration = { dispose?: () => void | Promise }; @@ -211,54 +211,62 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct // /acp status command (#809): registered via the V2 command editor where // supported (2.0.x stable; inert-safe otherwise) and rendered as a // synthetic non-model-turn message; TUI-only (`run` dispatches no slash cmds). - const commandReg = await ctx.command?.transform?.((editor) => { - editor.add({ - name: "acp", - description: "Show ACP status (billion-context proxy)", - execute: async (input) => { - const sid = typeof input.sessionID === "string" ? input.sessionID : ""; - let text: string; - if (pluginDisabled()) { - text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; - } else if (!sid) { - return; - } else { - const base = state.proxyBase ?? proxyBaseFromEnv(); - if (!base) { - text = "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)"; + try { + const commandReg = await ctx.command?.transform?.((editor) => { + editor.add({ + name: "acp", + description: "Show ACP status (billion-context proxy)", + execute: async (input) => { + const sid = typeof input.sessionID === "string" ? input.sessionID : ""; + if (!sid) { + console.warn("[bili-opencode] /acp invoked without a sessionID; cannot render ACP status"); + return; + } + let text: string; + if (pluginDisabled()) { + text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)"; } else { - try { - const res = await fetch(`${base}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); - const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; - if (typeof status.panel === "string" && status.panel.length > 0) { - text = status.panel; - } else if (status.ok === false) { - let version: string | undefined; - try { - version = await fetchProxyVersion(base); - } catch { - version = undefined; + const base = state.proxyBase ?? proxyBaseFromEnv(); + if (!base) { + text = "bili: no proxy detected (set BILLION_CONTEXT_PROXY or point the provider at the proxy's /bili/ URL, then run /acp again)"; + } else { + try { + const status = await fetchStatus(base, sid); + if (status && typeof status.panel === "string" && status.panel.length > 0) { + text = status.panel; + } else if (status && status.ok === false) { + let version: string | undefined; + try { + version = await fetchProxyVersion(base); + } catch { + version = undefined; + } + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else { + const errText = status?.error; + text = typeof errText === "string" && errText.length > 0 + ? `bili: proxy returned no status panel (${errText})` + : "bili: proxy returned no status panel"; } - text = version !== undefined - ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` - : "bili: no ACP session yet (send a model request first, then run /acp)"; - } else { - text = "bili: proxy returned no status panel"; + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; } - } catch (err) { - text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; } } - } - try { - await ctx.session?.synthetic?.({ sessionID: sid, text }); - } catch (err) { - console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); - } - }, + try { + await ctx.session?.synthetic?.({ sessionID: sid, text }); + } catch (err) { + console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); + } + }, + }); }); - }); - if (commandReg) registrations.push(commandReg); + if (commandReg) registrations.push(commandReg); + } catch (err) { + console.warn(`[bili-opencode] /acp command registration unavailable; continuing without it: ${err instanceof Error ? err.message : String(err)}`); + } const subscription = ctx.event?.subscribe?.({ signal: ac.signal }); if (subscription && typeof subscription[Symbol.asyncIterator] === "function") { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index ebdc814566..c3b3c7de35 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -379,6 +379,106 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 /acp: host omits sessionID → warn once, render nothing (never an empty-id synthetic)", async () => { + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (msg?: unknown) => { warns.push(String(msg)); }; + try { + for (const plugin of ["0", undefined]) { + const f = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: plugin }, async () => { + const cleanup = await biliOpencodePlugin.setup(f.ctx as never); + try { + const acp = f.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({}); + await new Promise((r) => setTimeout(r, 20)); + assert.equal(f.syntheticCalls.length, 0, `no synthetic for missing sessionID (BILLION_CONTEXT_PLUGIN=${String(plugin)})`); + } finally { + cleanup(); + } + }); + } + assert.equal(warns.filter((w) => w.includes("sessionID")).length, 2, "one warning per no-sessionID invocation"); + } finally { + console.warn = origWarn; + } +}); + +test("v2 /acp: disabled + valid session still renders the 'disabled' notice", async () => { + const fake = makeFakeCtx(); + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: "0" }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_dis" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /disabled/); + assert.equal(fake.syntheticCalls[0].sessionID, "ses_dis"); + } finally { + cleanup(); + } + }); +}); + +test("v2 /acp: surfaces status.error when the proxy returns no panel", async () => { + const server = http.createServer((req, res) => { + if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, error: "backend-busy" })); + return; + } + res.writeHead(404); + res.end("{}"); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_err" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].text, /no status panel/); + assert.match(fake.syntheticCalls[0].text, /backend-busy/); + } finally { + cleanup(); + } + }); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("v2 /acp: a throwing command editor degrades to no-/acp without killing setup", async () => { + const fake = makeFakeCtx(); + const ctxObj = fake.ctx as unknown as { command?: unknown }; + ctxObj.command = { + transform: async (cb: (editor: { add: (c: unknown) => void }) => void) => { + cb({ add: () => { throw new Error("command editor has no add"); } }); + return { dispose: () => {} }; + }, + }; + const warns: string[] = []; + const origWarn = console.warn; + console.warn = (msg?: unknown) => { warns.push(String(msg)); }; + try { + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + assert.ok(typeof cleanup === "function", "setup resolved despite the command editor throwing"); + } finally { + cleanup(); + } + }); + assert.ok(warns.some((w) => w.includes("/acp")), "degradation logged"); + } finally { + console.warn = origWarn; + } +}); + test("fetchManifest openai format maps parameters to inputSchema", async () => { const MANIFEST_OPENAI = [ { name: "compress", description: "Compress a range", parameters: { type: "object", properties: { content: { type: "array" } }, required: ["content"] } }, From d6d60f8d3e55fece71d0764611d41361941bbad6 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 10:11:27 +0800 Subject: [PATCH 13/29] fix(agent): /acp must not wake the model under OpenCode V2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenCode V2's session.synthetic defaults to delivery="steer" and, unless resume:false, calls execution.wake(sessionID) — every /acp invocation started a model turn on behalf of a status query. Observed live in TUI: the model answered its own injected status panel with an unprompted assistant message. Pass resume:false so rendering stays inert. --- src/agent/opencode-v2.ts | 6 ++++-- tests/opencode-v2.test.ts | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index b84a5c47a7..d40508cf08 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -87,7 +87,7 @@ interface V2CatalogModelEntry { export interface V2PluginContext { session?: { hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise) => void | Promise; - synthetic?: (input: { sessionID: string; text: string }) => Promise; + synthetic?: (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => Promise; }; tool?: { transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise; @@ -256,7 +256,9 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct } } try { - await ctx.session?.synthetic?.({ sessionID: sid, text }); + // resume:false — OpenCode V2 defaults to delivery "steer" + execution.wake(), which would + // start a model turn on every /acp invocation with no user input (spurious empty turns). + await ctx.session?.synthetic?.({ sessionID: sid, text, resume: false }); } catch (err) { console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index c3b3c7de35..a38b920088 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -80,7 +80,7 @@ function makeFakeCtx() { let signal: AbortSignal | undefined; const addedTools: FakeAddedTool[] = []; const addedCommands: FakeAddedCommand[] = []; - const syntheticCalls: Array<{ sessionID: string; text: string }> = []; + const syntheticCalls: Array<{ sessionID: string; text: string; description?: string; resume?: boolean }> = []; let modelRequestCb: ((e: Record) => void | Promise) | undefined; const disposed: number[] = []; @@ -91,7 +91,7 @@ function makeFakeCtx() { modelRequestCb = cb; return { dispose: () => { disposed.push(1); } }; }, - synthetic: async (input: { sessionID: string; text: string }) => { + synthetic: async (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => { syntheticCalls.push(input); return {}; }, @@ -355,6 +355,7 @@ test("v2 setup: /acp command registered and renders proxy status panel via synth await until(() => fake.syntheticCalls.length === 1); assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); } @@ -373,6 +374,7 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy await acp.execute({ sessionID: "s_nopx" }); await until(() => fake.syntheticCalls.length === 1); assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); } From 304110ad3fa0b93403a349dc2381a474174ef0ef Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 10:25:25 +0800 Subject: [PATCH 14/29] fix(agent): make opencode v2 /acp status panel visible in the TUI The /acp panel was carried only in the synthetic message's text. OpenCode V2's TUI renders a synthetic message as a Notice row only when its display text fits the timeline cap (~1KB; message-timeline.tsx canRenderImmediately), so real panels were silently dropped: users saw nothing after /acp. The panel now goes to description (verbatim under 1024 chars, leading lines + [panel truncated] above) and the model-facing body is an inert one-line note (V2_SYNTHETIC_TEXT) so the model context never repeats panel content. Verified live in a v2.0.4 TUI: short panels render fully as the notice row, a >1.5KB panel renders its leading lines plus the marker; no model turn is triggered (pairs with the no-wake fix #879). --- src/agent/opencode-v2.ts | 12 +++++++++++- src/agent/shared.ts | 4 ++++ tests/opencode-v2.test.ts | 39 +++++++++++++++++++++++++++++++++------ 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index d40508cf08..ecf496dbb8 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -43,6 +43,11 @@ import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; import { fetchProxyVersion, fetchStatus, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; +// OpenCode V2 TUI renders a synthetic message as a visible Notice row only when its display text fits the +// timeline cap (~1KB): longer text renders nothing (#880). Panels go to description verbatim under the cap. +import { V2_SYNTHETIC_TEXT } from "./shared.js"; +const V2_SYNTHETIC_VISIBLE_MAX = 1024; + type V2Registration = { dispose?: () => void | Promise }; interface V2Headers { @@ -258,7 +263,12 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct try { // resume:false — OpenCode V2 defaults to delivery "steer" + execution.wake(), which would // start a model turn on every /acp invocation with no user input (spurious empty turns). - await ctx.session?.synthetic?.({ sessionID: sid, text, resume: false }); + // Short panels become the visible description verbatim; long ones keep their leading + // lines plus a marker so the model-facing body never repeats the whole panel. + const description = text.length > V2_SYNTHETIC_VISIBLE_MAX + ? text.slice(0, V2_SYNTHETIC_VISIBLE_MAX - 20) + "\n\n[panel truncated]" + : text; + await ctx.session?.synthetic?.({ sessionID: sid, text: V2_SYNTHETIC_TEXT, description, resume: false }); } catch (err) { console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/src/agent/shared.ts b/src/agent/shared.ts index c6bcfc99fb..6b8a2de12f 100644 --- a/src/agent/shared.ts +++ b/src/agent/shared.ts @@ -156,3 +156,7 @@ export async function fetchProxyVersion(proxyBase: string): Promise 0 ? version : undefined; } + +// Model-facing body for /acp status renders: the visible panel goes to the synthetic message's +// description (TUI Notice cap ~1KB); this inert one-liner keeps the model context clean. +export const V2_SYNTHETIC_TEXT = "[bili-acp-status] ACP status panel was displayed in your terminal; this line is not an instruction."; diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index a38b920088..40427433c7 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -44,7 +44,8 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver } if ((req.url ?? "").startsWith("/__bili/plugin/status")) { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, panel: "ACP-PANEL-OK" })); + const panel = (req.url ?? "").includes("ses_acp_long") ? "X".repeat(1500) : "ACP-PANEL-OK"; + res.end(JSON.stringify({ ok: true, panel })); return; } res.writeHead(404); @@ -354,7 +355,9 @@ test("v2 setup: /acp command registered and renders proxy status panel via synth await acp!.execute({ sessionID: "ses_acp_1" }); await until(() => fake.syntheticCalls.length === 1); assert.equal(fake.syntheticCalls[0].sessionID, "ses_acp_1"); - assert.match(fake.syntheticCalls[0].text, /ACP-PANEL-OK/); + assert.match(fake.syntheticCalls[0].description!, /ACP-PANEL-OK/); + assert.match(fake.syntheticCalls[0].text, /displayed in your terminal/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); @@ -373,7 +376,8 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "s_nopx" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /no proxy detected/); + assert.match(fake.syntheticCalls[0].description!, /no proxy detected/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); assert.equal(fake.syntheticCalls[0].resume, false); } finally { cleanup(); @@ -381,6 +385,29 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 setup: /acp truncates long panels to the TUI notice cap", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_acp_long" }); + await until(() => fake.syntheticCalls.length === 1); + const desc = fake.syntheticCalls[0].description ?? ""; + assert.ok(desc.length > 0 && desc.length <= 1024); + assert.match(desc, /\[panel truncated\]$/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + test("v2 /acp: host omits sessionID → warn once, render nothing (never an empty-id synthetic)", async () => { const warns: string[] = []; const origWarn = console.warn; @@ -414,7 +441,7 @@ test("v2 /acp: disabled + valid session still renders the 'disabled' notice", as const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "ses_dis" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /disabled/); + assert.match(fake.syntheticCalls[0].description!, /disabled/); assert.equal(fake.syntheticCalls[0].sessionID, "ses_dis"); } finally { cleanup(); @@ -443,8 +470,8 @@ test("v2 /acp: surfaces status.error when the proxy returns no panel", async () const acp = fake.addedCommands.find((c) => c.name === "acp")!; await acp.execute({ sessionID: "ses_err" }); await until(() => fake.syntheticCalls.length === 1); - assert.match(fake.syntheticCalls[0].text, /no status panel/); - assert.match(fake.syntheticCalls[0].text, /backend-busy/); + assert.match(fake.syntheticCalls[0].description!, /no status panel/); + assert.match(fake.syntheticCalls[0].description!, /backend-busy/); } finally { cleanup(); } From 6d79228fc111c7298ae2629c051cd54fcd828682 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 12:13:32 +0800 Subject: [PATCH 15/29] fix(agent): show the idle notice on first opencode v2 /acp before any model request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before the conversation's first model request the proxy knows no ACP session; handlePluginStatus answers that with HTTP 404 {ok:false}. shared.fetchStatus() soft-fails every non-2xx into undefined, so the v2 renderer fell through both the panel and the ok===false branches and printed 'proxy returned no status panel' instead of the friendly idle line. Handle the undefined result explicitly: probe the manifest, and when it answers render 'billion-context@ — proxy connected, no ACP session yet…'; when nothing answers, say the proxy is unreachable. Second-and-later calls were already correct (panel or ok:false path). Same soft-fail contract as v1's inline fetch, without changing the endpoint's wire semantics. --- src/agent/opencode-v2.ts | 8 ++++++++ tests/opencode-v2.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index ecf496dbb8..7ae0ed6bb8 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -249,6 +249,14 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct text = version !== undefined ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else if (!status) { + // fetchStatus soft-fails to undefined both when the proxy 404s an absent or + // never-seen conversation and when the proxy is unreachable. Probe the + // manifest to claim "connected" only when it answers. + const version = await fetchProxyVersion(base).catch(() => undefined); + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: cannot reach the bili proxy (run `bili start`, then run /acp again)"; } else { const errText = status?.error; text = typeof errText === "string" && errText.length > 0 diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 40427433c7..3661ac5c06 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -43,11 +43,21 @@ function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conver return; } if ((req.url ?? "").startsWith("/__bili/plugin/status")) { + if ((req.url ?? "").includes("ses_acp_idle")) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation" })); + return; + } res.writeHead(200, { "content-type": "application/json" }); const panel = (req.url ?? "").includes("ses_acp_long") ? "X".repeat(1500) : "ACP-PANEL-OK"; res.end(JSON.stringify({ ok: true, panel })); return; } + if ((req.url ?? "") === "/__bili/plugin/manifest") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ version: "9.9.9-test" })); + return; + } res.writeHead(404); res.end("{}"); }); @@ -385,6 +395,29 @@ test("v2 setup: /acp reports no proxy detected via synthetic when no proxy", asy }); }); +test("v2 setup: first /acp before any model request shows the idle notice (proxy 404s the conversation)", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const acp = fake.addedCommands.find((c) => c.name === "acp")!; + await acp.execute({ sessionID: "ses_acp_idle" }); + await until(() => fake.syntheticCalls.length === 1); + assert.match(fake.syntheticCalls[0].description!, /billion-context@9\.9\.9-test \u2014 proxy connected, no ACP session yet/); + assert.match(fake.syntheticCalls[0].text, /not an instruction/); + assert.equal(fake.syntheticCalls[0].resume, false); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + + test("v2 setup: /acp truncates long panels to the TUI notice cap", async () => { const proxy = await startFakeProxyV2(); const fake = makeFakeCtx(); From 202e8116a91a30a3facc9a893544484c1c031d2b Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 13:39:56 +0800 Subject: [PATCH 16/29] fix(agent): preset BILLION_CONTEXT_PROXY attaches the opencode v2 native plugin instead of standing down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pseudo-attach hole: presetting BILLION_CONTEXT_PROXY and running bare opencode disarmed the native bootstrap entirely (no spawn, no attach) while tools still discovered the proxy through the env — model traffic silently went direct, the proxy never saw the session, and every tool forward 404'd ("unknown plugin conversation"). planNativeOpencode now treats the preset value as an external attach target (probe + rewrite + stamp, same semantics as BILLION_CONTEXT_ATTACH; explicit ATTACH wins when both are set). Kill switches (BILLION_CONTEXT_PLUGIN=0, BILI_NATIVE_OPENCODE=0) and /bili/ launches (BILI_PROVIDER_REWRITES) still stand down; a garbage preset falls back to spawn. Also: the opencode v2 plugin tool forward now returns guided text when the proxy reports the conversation was never registered, instead of surfacing the raw 404 that sent the model down a "refresh/restart" tangent. Verified in-container end-to-end (real qwen upstream) across all four postures: proxy (baseURL), launcher (bili opencode), native spawn (bare opencode + plugin), and preset-env attach — session registration, live conversation, acp_status real execution, /acp panel render. --- src/agent/native-bootstrap.ts | 16 ++++++++++++++++ src/agent/opencode-native.ts | 28 ++++++++++++++++++---------- src/agent/opencode-v2.ts | 6 +++++- tests/opencode-native.test.ts | 25 +++++++++++++++++++++---- 4 files changed, 60 insertions(+), 15 deletions(-) diff --git a/src/agent/native-bootstrap.ts b/src/agent/native-bootstrap.ts index d519b2ef17..6d0a456e5b 100644 --- a/src/agent/native-bootstrap.ts +++ b/src/agent/native-bootstrap.ts @@ -25,6 +25,22 @@ export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string): return true; } +/** Normalize a preset BILLION_CONTEXT_PROXY value (http/https, trailing + * slashes stripped) for attach-style routing. Returns undefined when unset, + * blank, or not a valid http(s) origin. */ +export function proxyEnvOrigin(env: NodeJS.ProcessEnv): string | undefined { + const raw = env.BILLION_CONTEXT_PROXY; + if (raw === undefined) return undefined; + const url = raw.trim(); + if (url.length === 0 || !/^https?:\/\//i.test(url)) return undefined; + try { + new URL(url); + } catch { + return undefined; + } + return url.replace(/\/+$/, ""); +} + /** External-proxy attach signal (#809): when BILLION_CONTEXT_ATTACH holds a * valid http(s) origin, a host-native entry routes model traffic THROUGH that * pre-existing proxy instead of spawning its own — no ownership, no respawn, diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 41903d7a64..b28ef4bbe4 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -30,9 +30,10 @@ // retries are rate-limited to one attempt per RESPAWN_COOLDOWN_MS so a // persistently failing spawn does not become a per-request spawn storm. // -// Skipped when a proxy is already managed (BILLION_CONTEXT_PROXY set by a -// `bili` launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ launch) or -// opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0). +// Skipped when opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0) +// or when a `bili` /bili/ launch owns routing (BILI_PROVIDER_REWRITES). A +// preset BILLION_CONTEXT_PROXY is treated as an EXTERNAL attach target +// (probe + rewrite + stamp) instead of a stand-down — see planNativeOpencode. // // Deployment: OpenCode 2.x `plugin` entries must be DIRECTORIES whose index.js // is the entrypoint (bare file paths are rejected, #754 probe) — `bili plugin @@ -41,7 +42,7 @@ // src/launcher.ts prepareOpencodeHttpRewrite). import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; -import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js"; +import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; @@ -50,13 +51,20 @@ export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean { return nativeBootstrapGate(env, "BILI_NATIVE_OPENCODE"); } -/** Decide this process's native posture (#809). Precedence off > attach > - * spawn: a launcher-owned proxy or an opt-out stands us down entirely (even - * over an explicit attach); otherwise attach to BILLION_CONTEXT_ATTACH when - * given, else spawn our own watchdog proxy. */ +/** Decide this process's native posture (#809). Precedence kill-switch > + * /bili/ rewrite launch > attach > spawn. A preset BILLION_CONTEXT_PROXY is + * an ATTACH target, not a stand-down: the pseudo-attach hole (preset env + + * bare opencode) used to disarm routing entirely while tools still found the + * proxy through the env — model traffic went direct, the proxy never saw the + * session, and every tool forward 404'd. Attach keeps the user's intent + * ("route through THIS proxy") and matches BILLION_CONTEXT_ATTACH semantics + * (probe + rewrite + stamp); explicit BILLION_CONTEXT_ATTACH wins when both + * are set. A /bili/ launch (BILI_PROVIDER_REWRITES) still stands us down — + * its URLs are already proxy-shaped and isModelApiUrl skips them. */ export function planNativeOpencode(env: NodeJS.ProcessEnv): { mode: "off" | "attach" | "spawn"; attachOrigin?: string } { - if (!shouldBootstrapNativeOpencode(env)) return { mode: "off" }; - const attachOrigin = nativeAttachOrigin(env); + if (env.BILLION_CONTEXT_PLUGIN === "0" || env.BILI_NATIVE_OPENCODE === "0") return { mode: "off" }; + if (env.BILI_PROVIDER_REWRITES !== undefined) return { mode: "off" }; + const attachOrigin = nativeAttachOrigin(env) ?? proxyEnvOrigin(env); if (attachOrigin !== undefined) return { mode: "attach", attachOrigin }; return { mode: "spawn" }; } diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 7ae0ed6bb8..3559b3ea95 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -205,7 +205,11 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct const result = await forwardTool(base, tctx.sessionID, t.name, args); return { content: result }; } catch (err) { - return { content: err instanceof Error ? err.message : String(err) }; + const msg = err instanceof Error ? err.message : String(err); + if (msg.includes("no model request has arrived with this conversation id yet")) { + return { content: "bili: no ACP state for this session yet — no model request has been routed through the proxy. Tell the user to send one normal message first; ACP activates automatically once model traffic flows through the proxy (verify the provider baseURL goes through bili, or launch via `bili opencode` / the installed plugin)." }; + } + return { content: msg }; } }, }); diff --git a/tests/opencode-native.test.ts b/tests/opencode-native.test.ts index 74fb4e3ef7..df1641dd14 100644 --- a/tests/opencode-native.test.ts +++ b/tests/opencode-native.test.ts @@ -274,11 +274,28 @@ test("nativeAttachOrigin: normalizes a valid http(s) origin (trailing slash stri assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: " https://proxy.example.com/ " }), "https://proxy.example.com"); }); -test("planNativeOpencode: default is spawn; opt-out and launcher-owned are off", () => { +test("planNativeOpencode: default is spawn; opt-out and /bili/ launches are off", () => { assert.deepEqual(planNativeOpencode({}), { mode: "spawn" }); assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" }); assert.deepEqual(planNativeOpencode({ BILI_NATIVE_OPENCODE: "0" }), { mode: "off" }); - assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILI_PROVIDER_REWRITES: '{"vllm":"http://127.0.0.1:1/bili/http://x"}' }), { mode: "off" }); +}); + +test("planNativeOpencode: a preset BILLION_CONTEXT_PROXY is an attach target, not a stand-down", () => { + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), + { mode: "attach", attachOrigin: "http://127.0.0.1:36485" }, + ); + assert.deepEqual( + planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485/" }), + { mode: "attach", attachOrigin: "http://127.0.0.1:36485" }, + ); + // kill switches and a /bili/ launch still win over the preset + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILI_PROVIDER_REWRITES: "{}" }), { mode: "off" }); + // a garbage preset falls back to spawn (self-managed) rather than dead-off + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "garbage" }), { mode: "spawn" }); + assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: " " }), { mode: "spawn" }); }); test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy", () => { @@ -289,10 +306,10 @@ test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_ATTACH: "garbage" }), { mode: "spawn" }); }); -test("planNativeOpencode: a launcher-owned proxy stands down even over an explicit attach", () => { +test("planNativeOpencode: explicit BILLION_CONTEXT_ATTACH wins over the env preset", () => { assert.deepEqual( planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_ATTACH: "http://10.0.0.5:9000" }), - { mode: "off" }, + { mode: "attach", attachOrigin: "http://10.0.0.5:9000" }, ); }); From 96368b24d8a412fefd9106a9a51651af64fe84bc Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Thu, 17 Sep 2026 22:42:14 +0800 Subject: [PATCH 17/29] fix(agent): opencode v2 acp_status renders the status panel (panel-first) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forwarded kernel acp_status returns the legacy flat report while the /acp command shows the rich status panel — tool and command disagreed. acp_status is read-only, so the plugin now reads the panel from the proxy's status endpoint first and falls back to forwardTool when no panel is served (older proxy, unknown conversation). Fixes #911 --- src/agent/opencode-v2.ts | 12 ++++++++++++ tests/opencode-v2.test.ts | 9 ++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/agent/opencode-v2.ts b/src/agent/opencode-v2.ts index 3559b3ea95..0ff03994a6 100644 --- a/src/agent/opencode-v2.ts +++ b/src/agent/opencode-v2.ts @@ -202,6 +202,18 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct const base = state.proxyBase ?? proxyBaseFromEnv(); if (!base) return { content: "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)" }; try { + // Panel-first for acp_status: the proxy's status + // endpoint renders the same rich panel the /acp + // command shows; the forwarded kernel tool returns + // the legacy flat report. acp_status is read-only, + // so reading the panel changes no state. Fall back + // to the tool call when no panel comes back (older + // proxy, unknown conversation). + if (t.name === "acp_status") { + const status = await fetchStatus(base, tctx.sessionID); + const panel = status?.["panel"]; + if (typeof panel === "string" && panel.length > 0) return { content: panel }; + } const result = await forwardTool(base, tctx.sessionID, t.name, args); return { content: result }; } catch (err) { diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts index 3661ac5c06..493ebd3f51 100644 --- a/tests/opencode-v2.test.ts +++ b/tests/opencode-v2.test.ts @@ -285,8 +285,15 @@ test("v2 setup: activates from /bili/ baseURL on round 1, stamps headers, forwar assert.equal(proxy.toolCalls.at(-1)?.conversationId, "ses_v2_1"); assert.equal(proxy.toolCalls.at(-1)?.tool, "compress"); - const statusOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_other" }); + // Panel-first: acp_status returns the status panel when the + // proxy serves one for this conversation (ses_other gets the + // generic "ACP-PANEL-OK"), and falls back to the forwarded + // kernel tool when the status endpoint 404s (ses_acp_idle). + const panelOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_other" }); + assert.equal(panelOut.content, "ACP-PANEL-OK"); + const statusOut = await fake.addedTools.find((t) => t.name === "acp_status")!.execute({}, { sessionID: "ses_acp_idle" }); assert.equal(statusOut.content, "STATUS-RESULT"); + assert.equal(proxy.toolCalls.at(-1)?.tool, "acp_status"); } finally { cleanup(); } From 086e80a270f905428fea1049b491153e8fd3a2b6 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 00:38:21 +0800 Subject: [PATCH 18/29] =?UTF-8?q?feat:=20OpenCode=201.x=20native=20support?= =?UTF-8?q?=20=E2=80=94=20V1=20.server()=20hooks=20on=20the=20standard=20i?= =?UTF-8?q?nstall=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/agent/opencode-native.ts: V1 plugin surface — config hook rewrites provider baseURLs to /bili/ on the shared in-process config object (idempotent, unwraps stale wraps), chat.headers stamps the plugin headers, tool registers the bili tool set with real zod shapes, /acp command renders the same status panel. Reuses the self-spawn/attach bootstrap; degrades to plain proxy mode when zod is unresolvable. - src/agent/opencode-acp-command.ts: /acp hooks extracted from the launcher plugin, shared by V1 (.server) and V2 (setup) entries. - src/agent/opencode.ts: launcher plugin now consumes the shared factory. - zod 4.1.8 (exact, matches the opencode host's zod) added as the only runtime dependency; dist/index.js stays zod-free. - tests/opencode-native-v1.test.ts: 11 tests (schema->zod mapping incl. cross-instance interop, provider rewrite idempotency, hooks + degrade). - E2E verified in-container on opencode-ai 1.14.46 and 1.18.31 via 'bili plugin install opencode': providers rewritten, plugin-mode headers, native acp_status round-trip, /acp panel render, tag-echo guard. --- AGENTS.md | 6 +- README.md | 19 ++- package-lock.json | 12 ++ package.json | 3 + src/agent/opencode-acp-command.ts | 114 ++++++++++++++++ src/agent/opencode-native.ts | 209 +++++++++++++++++++++++++++++- src/agent/opencode.ts | 105 +++------------ tests/opencode-native-v1.test.ts | 195 ++++++++++++++++++++++++++++ 8 files changed, 566 insertions(+), 97 deletions(-) create mode 100644 src/agent/opencode-acp-command.ts create mode 100644 tests/opencode-native-v1.test.ts diff --git a/AGENTS.md b/AGENTS.md index dc8bfc4ab9..a9453f3b5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ | Language | TypeScript (strict, ESM) | | Build | tsup (bundling, inlines acp-kernel) | | Test | Node.js built-in: `node --import tsx --test tests/*.test.ts` | -| Runtime Dep | `acp-kernel` (bundled at build time, zero runtime deps in dist) | +| Runtime Dep | `acp-kernel` (bundled at build time) + `zod` (external, only used by `dist/agent/opencode-native.js` V1 tools; `dist/index.js` stays dependency-free) | ### Repository Info @@ -65,7 +65,7 @@ billion-context/ │ ├── compress-tool.ts # compress tool parsing (kernel parseCompressArgs) │ ├── decompress-shared.ts # Shared decompress logic │ ├── orphan-gc.ts # Orphaned block cleanup -│ ├── agent/ # Thin agent-side plugins (pi/omp/opencode) +│ ├── agent/ # Thin agent-side plugins (pi/omp/opencode; opencode-acp-command.ts = shared /acp hooks V1+V2, opencode-native.ts = self-spawn native, V1 `.server()` + V2 `setup`) │ ├── web/ # Web UI (config + context windows) │ ├── fetch-util.ts # HTTP fetch with timeout │ └── util.ts # Misc utilities @@ -76,7 +76,7 @@ billion-context/ ### Key Design Decisions -1. **acp-kernel is bundled inline** — tsup does NOT list it in `external`, so `dist/index.js` is self-contained (zero runtime deps) +1. **acp-kernel is bundled inline** — tsup does NOT list it in `external`, so `dist/index.js` is self-contained. Exception: `zod` (exact `4.1.8`, matching the opencode host's own zod so V1 plugin-tool shapes interoperate) is a real dependency and stays external — only `dist/agent/opencode-native.js` imports it (lazily, at plugin-tool registration); `dist/index.js` and every other entry remain zod-free. When zod cannot be resolved at runtime the V1 plugin degrades to plain proxy mode instead of failing. 2. **Tags use XML format** `m00001` — written with hex escapes (`\x3c`, `\x3e`) to avoid Write/Edit tool stripping 3. **Auto-update**: checks npm registry every 3 min (`CHECK_INTERVAL_MS = 3*60*1000`), first check per process ignores throttle 4. **Tee logger**: all proxy logs go through `src/logger.ts` (file + stderr). Do NOT use `console.error` in server-side modules — use `loggerLog()`. diff --git a/README.md b/README.md index 6f007518d2..7efc059539 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ Pick by your client: | Client | Use | |---|---| | **pi** | [`billion-context-pi`](https://github.com/ranxianglei/billion-context-pi) (in-process extension) | -| **opencode 1.x** | [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) (in-process extension, V1 plugin API) or `bili opencode` | +| **opencode 1.x** | `bili plugin install opencode` (V1 `.server()` hooks — same wrapper as 2.x) or `bili opencode` (launcher) or [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) (in-process extension) | | **opencode 2.0+** | `bili opencode` (built-in V2 plugin — native tools, no separate package) or `bili plugin install opencode` (self-spawning native plugin, no launcher) | | **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 | @@ -274,13 +274,24 @@ contract: `dist/agent/opencode-native.js`) and sets `compaction.auto: false`, after which plain `opencode` works as-is. At load the plugin bootstraps its own proxy (attaches to a healthy instance instead of doubling; parent-pid - watchdog kills it when opencode exits), routes model-API traffic through the - `http.request` hook to `/bili/`, and exposes the same - native bili tools as launcher mode — no fixed port, no env var, no launcher. + watchdog kills it when opencode exits), routes model-API traffic to + `/bili/`, and exposes the same native bili tools as + launcher mode — no fixed port, no env var, no launcher. Opt-out: `BILI_NATIVE_OPENCODE=0`. If no proxy can be made healthy, requests go direct (uncompressed) with a one-time warning and recover automatically. Under a `bili opencode` launch this entry is skipped entirely (the launcher owns the proxy). + + The same wrapper serves **OpenCode 1.x** through the V1 `.server()` hooks + (verified on 1.14.46 and 1.18.31): the `config` hook mutates the shared + config object in-process to rewrite every provider `options.baseURL` to + `/bili/…` and sets `compaction.auto: false`; `chat.headers` stamps + the plugin headers per request; `tool` registers the bili tools with real + zod shapes (zod is a runtime dependency — when it cannot be resolved the + plugin degrades to plain proxy mode: rewrite only, wire-injected tools); + the `/acp` command renders the same status panel. V1 has no request-level + URL hook, so providers **without** an explicit `baseURL` (SDK defaults) + keep going direct — set a baseURL to be proxied. - **Pure proxy:** point the provider baseURL at the proxy like any other client: diff --git a/package-lock.json b/package-lock.json index a0d48046ac..0c8116f570 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "billion-context", "version": "0.1.115", "license": "MIT", + "dependencies": { + "zod": "4.1.8" + }, "bin": { "bili": "dist/index.js", "bili-proxy": "dist/index.js" @@ -2165,6 +2168,15 @@ "engines": { "node": ">=18" } + }, + "node_modules/zod": { + "version": "4.1.8", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.8.tgz", + "integrity": "sha512-5R1P+WwQqmmMIEACyzSvo4JXHY5WiAFHRMg+zBZKgKS+Q1viRa0C1hmUKtHltoIFKtIdki3pRxkmpP74jnNYHQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 1d675d9623..1501bd5dd6 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,9 @@ "bugs": { "url": "https://github.com/ranxianglei/billion-context/issues" }, + "dependencies": { + "zod": "4.1.8" + }, "devDependencies": { "@types/node": "^22.0.0", "@types/node-forge": "^1.3.14", diff --git a/src/agent/opencode-acp-command.ts b/src/agent/opencode-acp-command.ts new file mode 100644 index 0000000000..8e3613a411 --- /dev/null +++ b/src/agent/opencode-acp-command.ts @@ -0,0 +1,114 @@ +// Shared /acp command hooks for the OpenCode 1.x plugin surface (V1 `.server()` +// hooks). Extracted from src/agent/opencode.ts so both deployments register +// the identical command: the launcher-gated plugin (BILLION_CONTEXT_PROXY set +// by `bili opencode`) and the native V1 entry (src/agent/opencode-native.ts, +// self-spawned/attached proxy whose origin resolves asynchronously). +// +// The proxy base is read through a getter because the native entry learns its +// origin only after bootstrap; the launcher variant captures the env value at +// module load and serves it verbatim. + +import { fetchProxyVersion } from "./shared.js"; + +export interface OpencodeCommandConfig { + template: string; + description?: string; +} + +export interface OpencodeConfig { + command?: Record; + [key: string]: unknown; +} + +export interface OpencodePromptPart { + type: string; + text: string; + ignored?: boolean; +} + +export interface OpencodeClient { + session?: { + prompt?: (args: { + path: { id: string }; + body: { noReply: boolean; parts: OpencodePromptPart[] }; + }) => Promise; + }; +} + +export interface OpencodeCommandInput { + command: string; + sessionID: string; + arguments?: string; +} + +export interface OpencodeAcpHooks { + config?: (input: OpencodeConfig) => Promise; + "command.execute.before"?: (input: OpencodeCommandInput) => Promise; +} + +export async function showAcpText(ctx: { client?: OpencodeClient }, sid: string, text: string): Promise { + // Direct method call — `const p = ctx.client.session.prompt; p(...)` loses `this` (this._client) and throws. + const session = ctx.client?.session; + if (!session || typeof session.prompt !== "function") { + console.error("[bili-opencode] /acp render failed: session.prompt unavailable"); + return; + } + try { + await session.prompt({ + path: { id: sid }, + body: { noReply: true, parts: [{ type: "text", text, ignored: true }] }, + }); + } catch (err) { + console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); + } +} + +/** The /acp command hooks (registration + render). `getProxyBase` returns the + * proxy origin or undefined when unavailable — an undefined base renders a + * diagnostic instead of failing silently. The config hook ONLY registers the + * command; callers layer provider rewriting on top. */ +export function createAcpCommandHooks(getProxyBase: () => string | undefined, ctx: { client?: OpencodeClient }): OpencodeAcpHooks { + return { + config: async (opencodeConfig) => { + opencodeConfig.command ??= {}; + opencodeConfig.command["acp"] = { + template: "", + description: "Show ACP status (billion-context proxy)", + }; + }, + "command.execute.before": async (input) => { + if (input.command !== "acp") return; + const sid = input.sessionID; + const proxyBase = getProxyBase(); + let text: string; + if (proxyBase === undefined || proxyBase.length === 0) { + text = "bili: proxy not running (native bootstrap failed) — model traffic goes direct"; + } else { + try { + const res = await fetch(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); + const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; + if (typeof status.panel === "string" && status.panel.length > 0) { + text = status.panel; + } else if (status.ok === false) { + // zero sessions on the proxy (fresh launch) — friendly idle notice + let version: string | undefined; + try { + version = await fetchProxyVersion(proxyBase); + } catch { + version = undefined; + } + text = version !== undefined + ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` + : "bili: no ACP session yet (send a model request first, then run /acp)"; + } else { + text = "bili: proxy returned no status panel"; + } + } catch (err) { + text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; + } + } + await showAcpText(ctx, sid, text); + throw new Error("__BILI_ACP_HANDLED__"); + }, + }; +} diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index b28ef4bbe4..e2b6a08767 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -40,8 +40,31 @@ // install opencode` writes /plugins/billion-context/index.js // re-exporting this entry (same wrapper shape the launcher builds, // src/launcher.ts prepareOpencodeHttpRewrite). +// +// OpenCode 1.x loads the SAME entry through `.server(ctx)` (hooks object). +// V1 runtime facts (probed on 1.14.46, ~/projects/opencode-stable): +// - config hook: receives the SHARED cached config object (Config.get → +// InstanceState.use) — mutating provider..options.baseURL persists +// for the process lifetime, no file writes needed. Providers WITHOUT an +// explicit baseURL (SDK defaults) cannot be caught this way — documented. +// - "chat.headers": per-LLM-request header mutation — the V1 equivalent of +// V2's stampHeaders (x-bili-plugin + conversation id). +// - tool: { [name]: { description, args, execute } } registers native tools; +// args must be REAL zod fields (registry wraps them with its own +// z.object(...).safeParse) — hence zod is a runtime dependency, lazily +// imported below. Same tool set/schemas as V2 (ACP_TOOLS_OPENAI), +// converted JSON-schema → zod. When zod cannot be resolved (dist copied +// without node_modules) the plugin degrades to proxy mode: no headers, no +// tools — the proxy injects wire tools, compression still works. +// - command.execute.before + ctx.client.session.prompt: /acp command +// (shared factory opencode-acp-command.ts). +// - "experimental.session.compacting" exists but config compaction.auto=false +// (written by the config hook, same as the launcher/installer) is the +// owner-switch; no compaction-prompt surgery needed. -import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; +import { ACP_TOOLS_OPENAI } from "../compress-tool.js"; +import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST, unwrapUpstream, wrapUpstream } from "../launcher.js"; +import { createAcpCommandHooks } from "./opencode-acp-command.js"; import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; @@ -223,4 +246,186 @@ if (plan.mode !== "off") { } } -export default { id: "billion-context-opencode-native", setup: createOpencodeV2Setup({ route: createNativeRoute(state) }) }; +// ———— OpenCode 1.x native surface (V1 `.server()`) ———————————————————— + +type ZodLike = typeof import("zod"); + +interface V1ToolContext { + sessionID: string; + messageID?: string; + agent?: string; + abort?: AbortSignal; +} + +interface V1Tool { + description: string; + args: Record; + execute: (args: Record, ctx: V1ToolContext) => Promise; +} + +export interface V1ProviderOptions { + baseURL?: unknown; + [key: string]: unknown; +} + +export interface V1Config { + provider?: Record | undefined; + command?: Record; + compaction?: unknown; + [key: string]: unknown; +} + +export interface V1ChatHeadersInput { + sessionID: string; + agent?: string; + model?: { providerID?: unknown; id?: unknown }; +} + +export interface V1Hooks { + config?: (input: V1Config) => Promise; + "chat.headers"?: (input: V1ChatHeadersInput, output: { headers: Record }) => Promise; + "command.execute.before"?: (input: { command: string; sessionID: string; arguments?: string }, output?: { parts: unknown[] }) => Promise; + tool?: Record; +} + +export interface V1PluginContext { + client?: import("./opencode-acp-command.js").OpencodeClient; +} + +/** JSON-schema (ACP_TOOLS_OPENAI parameters) → zod raw shape. Only the shapes + * our own tools use; anything exotic degrades to z.any() — the proxy + * re-validates server-side anyway (parseCompressArgs), client zod is just + * the host's parameter gate. */ +export function jsonSchemaToZodShape(schema: unknown, z: ZodLike): Record { + if (schema === null || typeof schema !== "object" || Array.isArray(schema)) return {}; + const props = (schema as { properties?: unknown }).properties; + if (props === null || typeof props !== "object" || Array.isArray(props)) return {}; + const out: Record = {}; + for (const [key, raw] of Object.entries(props as Record)) { + out[key] = jsonSchemaFieldToZod(raw, z); + } + return out; +} + +function jsonSchemaFieldToZod(raw: unknown, z: ZodLike): unknown { + if (raw === null || typeof raw !== "object") return z.any(); + const spec = raw as { type?: unknown; enum?: unknown; items?: unknown; anyOf?: unknown; description?: unknown }; + if (Array.isArray(spec.enum) && spec.enum.length > 0 && spec.enum.every((v) => typeof v === "string")) { + return z.enum(spec.enum as [string, ...string[]]); + } + switch (spec.type) { + case "string": + return typeof spec.description === "string" ? z.string().describe(spec.description) : z.string(); + case "number": + return z.number(); + case "boolean": + return z.boolean(); + case "array": { + const item = jsonSchemaFieldToZod(spec.items, z); + return item === undefined ? z.array(z.any()) : z.array(item as never); + } + default: + // object / anyOf / unknown — accept anything; the proxy validates + return z.any(); + } +} + +/** Rewrite provider baseURLs to `/bili/` (idempotent) and flip + * compaction.auto off. Providers without an explicit baseURL keep their SDK + * default (traffic goes direct) — V1 has no request seam to catch those. */ +export function rewriteV1Providers(cfg: V1Config, origin: string): number { + const providers = cfg.provider; + if (providers === null || typeof providers !== "object") return 0; + let rewritten = 0; + for (const entry of Object.values(providers)) { + const options = entry?.options; + if (options === null || typeof options !== "object") continue; + const base = options.baseURL; + if (typeof base !== "string" || base.trim().length === 0) continue; + if (!/^https?:\/\//i.test(base)) continue; + // unwrapUpstream strips ANY existing `<…>/bili/` prefix (stale wrap + // from another proxy origin included), wrapUpstream re-adds ours. + const next = wrapUpstream(origin, unwrapUpstream(base)); + if (next === base) continue; + options.baseURL = next; + rewritten++; + } + const compaction = cfg.compaction; + cfg.compaction = { + ...(compaction !== null && typeof compaction === "object" && !Array.isArray(compaction) ? (compaction as Record) : {}), + auto: false, + }; + return rewritten; +} + +export interface V1NativeDeps { + /** zod module (tests inject; runtime lazy-imports "zod"). */ + z?: ZodLike; + /** Tool forwarder (tests inject; runtime POSTs /__bili/plugin/tool). */ + forward?: (origin: string, conversationId: string, tool: string, args: unknown) => Promise; +} + +/** 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. */ +export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: V1NativeDeps = {}): V1Hooks { + const acp = createAcpCommandHooks(() => origin, ctx); + const hooks: V1Hooks = { + config: async (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/`); + }, + "command.execute.before": async (input, _output) => { + await acp["command.execute.before"]?.(input); + }, + }; + if (deps.z !== undefined) { + hooks["chat.headers"] = async (input, output) => { + output.headers["x-bili-plugin"] = "opencode"; + output.headers["x-bili-plugin-conversation"] = input.sessionID; + }; + 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), + }; + } + 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; +} + +async function resolveV1Origin(): Promise { + try { + return await readyOrigin(state); + } catch { + return undefined; + } +} + +const server = async (ctx: V1PluginContext): Promise => { + if (plan.mode === "off") return {}; + const origin = await resolveV1Origin(); + if (origin === undefined) { + console.error("[bili-opencode-native] v1: proxy bootstrap failed — model traffic goes direct (uncompressed)"); + return {}; + } + console.log(`[bili-opencode-native] v1 active (proxy ${origin})`); + let z: ZodLike | undefined; + try { + z = (await import("zod")) as ZodLike; + } catch { + z = undefined; + } + return createV1ServerHooks(origin, ctx, { z }); +}; + +export default { id: "billion-context-opencode-native", setup: createOpencodeV2Setup({ route: createNativeRoute(state) }), server }; diff --git a/src/agent/opencode.ts b/src/agent/opencode.ts index 998578ed23..65a57c1527 100644 --- a/src/agent/opencode.ts +++ b/src/agent/opencode.ts @@ -12,19 +12,22 @@ // setup comes from the shared factory src/agent/opencode-v2.ts, which the // native npm entry (opencode-native.ts) reuses so both deployment modes share // one protocol implementation. The V2 runtime-API facts live in that file. +// +// The /acp command hooks themselves live in src/agent/opencode-acp-command.ts +// and are shared with the native V1 entry (opencode-native.ts). +import { createAcpCommandHooks } from "./opencode-acp-command.js"; import { createOpencodeV2Setup } from "./opencode-v2.js"; -import { fetchProxyVersion } from "./shared.js"; - -interface OpencodeCommandConfig { - template: string; - description?: string; -} -interface OpencodeConfig { - command?: Record; - [key: string]: unknown; -} +export { showAcpText } from "./opencode-acp-command.js"; +export type { + OpencodeCommandConfig, + OpencodeConfig, + OpencodePromptPart, + OpencodeClient, + OpencodeCommandInput, + OpencodeAcpHooks, +} from "./opencode-acp-command.js"; interface OpencodeSessionInfo { id?: unknown; @@ -39,100 +42,26 @@ interface OpencodeEventInput { event?: OpencodeEvent; } -interface OpencodeCommandInput { - command: string; - sessionID: string; - arguments?: string; -} - -interface OpencodePromptPart { - type: string; - text: string; - ignored?: boolean; -} - -interface OpencodeClient { - session?: { - prompt?: (args: { - path: { id: string }; - body: { noReply: boolean; parts: OpencodePromptPart[] }; - }) => Promise; - }; -} - interface OpencodePluginContext { - client?: OpencodeClient; + client?: import("./opencode-acp-command.js").OpencodeClient; } interface OpencodeHooks { - config?: (input: OpencodeConfig) => Promise; + config?: (input: import("./opencode-acp-command.js").OpencodeConfig) => Promise; event?: (input: OpencodeEventInput) => Promise; - "command.execute.before"?: (input: OpencodeCommandInput, output: { parts: unknown[] }) => Promise; + "command.execute.before"?: (input: import("./opencode-acp-command.js").OpencodeCommandInput, output: { parts: unknown[] }) => Promise; } const proxyBase = process.env.BILLION_CONTEXT_PROXY ?? ""; -async function showText(ctx: OpencodePluginContext, sid: string, text: string): Promise { - // Direct method call — `const p = ctx.client.session.prompt; p(...)` loses `this` (this._client) and throws. - const session = ctx.client?.session; - if (!session || typeof session.prompt !== "function") { - console.error("[bili-opencode] /acp render failed: session.prompt unavailable"); - return; - } - try { - await session.prompt({ - path: { id: sid }, - body: { noReply: true, parts: [{ type: "text", text, ignored: true }] }, - }); - } catch (err) { - console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`); - } -} - const server = async (ctx: OpencodePluginContext): Promise => { if (!proxyBase) return {}; console.log("[bili-opencode] plugin active (proxy " + proxyBase + ")"); return { - config: async (opencodeConfig) => { - opencodeConfig.command ??= {}; - opencodeConfig.command["acp"] = { - template: "", - description: "Show ACP status (billion-context proxy)", - }; - }, - "command.execute.before": async (input) => { - if (input.command !== "acp") return; - const sid = input.sessionID; - let text: string; - try { - const res = await fetch(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(sid)}&fallback=latest`); - const status = (await res.json()) as { ok?: boolean; panel?: string; error?: string }; - if (typeof status.panel === "string" && status.panel.length > 0) { - text = status.panel; - } else if (status.ok === false) { - // zero sessions on the proxy (fresh launch) — friendly idle notice - let version: string | undefined; - try { - version = await fetchProxyVersion(proxyBase); - } catch { - version = undefined; - } - text = version !== undefined - ? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.` - : "bili: no ACP session yet (send a model request first, then run /acp)"; - } else { - text = "bili: proxy returned no status panel"; - } - } catch (err) { - text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`; - } - await showText(ctx, sid, text); - throw new Error("__BILI_ACP_HANDLED__"); - }, + ...createAcpCommandHooks(() => proxyBase, ctx), }; }; - const setup = createOpencodeV2Setup(); export default { id: "billion-context-opencode", setup, server }; diff --git a/tests/opencode-native-v1.test.ts b/tests/opencode-native-v1.test.ts new file mode 100644 index 0000000000..7c1099e512 --- /dev/null +++ b/tests/opencode-native-v1.test.ts @@ -0,0 +1,195 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import type { z } from "zod"; + +import { + createV1ServerHooks, + jsonSchemaToZodShape, + rewriteV1Providers, + type V1Config, + type V1ProviderOptions, +} from "../src/agent/opencode-native.js"; + +// Minimal structural stand-in for the host's zod module: only the builders +// jsonSchemaToZodShape touches. Real zod (4.1.8) is exercised implicitly by +// the shape assertions below via the actual import. +const fakeZ = { + any: () => ({ __fake: "any" }), + string: () => ({ __fake: "string", describe: (d: string) => ({ __fake: "string", desc: d }) }), + number: () => ({ __fake: "number" }), + boolean: () => ({ __fake: "boolean" }), + array: (item: unknown) => ({ __fake: "array", item }), + enum: (values: [string, ...string[]]) => ({ __fake: "enum", values }), +} as unknown as typeof z; + +describe("jsonSchemaToZodShape", () => { + it("maps primitive, enum, array and unknown fields", () => { + const shape = jsonSchemaToZodShape( + { + type: "object", + properties: { + range: { type: "string", description: "refs" }, + limit: { type: "number" }, + force: { type: "boolean" }, + mode: { type: "string", enum: ["auto", "manual"] }, + keep: { type: "array", items: { type: "string" } }, + nested: { type: "object", properties: { x: { type: "string" } } }, + weird: { anyOf: [{ type: "string" }, { type: "number" }] }, + }, + }, + fakeZ, + ); + assert.equal((shape.range as { __fake: string }).__fake, "string"); + assert.equal((shape.limit as { __fake: string }).__fake, "number"); + assert.equal((shape.force as { __fake: string }).__fake, "boolean"); + assert.deepEqual((shape.mode as { values: string[] }).values, ["auto", "manual"]); + assert.equal((shape.keep as { item: { __fake: string } }).item.__fake, "string"); + assert.equal((shape.nested as { __fake: string }).__fake, "any"); + assert.equal((shape.weird as { __fake: string }).__fake, "any"); + }); + + it("tolerates non-object schemas", () => { + assert.deepEqual(jsonSchemaToZodShape(undefined, fakeZ), {}); + assert.deepEqual(jsonSchemaToZodShape({ type: "string" }, fakeZ), {}); + assert.deepEqual(jsonSchemaToZodShape({ properties: "nope" }, fakeZ), {}); + }); + + it("produces fields the real host zod accepts in z.object()", async () => { + // The v1 registry wraps our shape with the HOST's zod: simulate with + // the real zod dependency (4.1.8) to prove cross-instance interop. + const real = (await import("zod")) as typeof z; + const shape = jsonSchemaToZodShape( + { type: "object", properties: { range: { type: "string" }, limit: { type: "number" } } }, + real, + ); + const parsed = real.object(shape).safeParse({ range: "m1-m5", limit: 3 }); + assert.equal(parsed.success, true); + const bad = real.object(shape).safeParse({ range: 7, limit: 3 }); + assert.equal(bad.success, false); + }); +}); + +describe("rewriteV1Providers", () => { + const origin = "http://127.0.0.1:19199"; + + it("rewrites http(s) baseURLs and preserves provider entries", () => { + const cfg: V1Config = { + provider: { + openai: { options: { baseURL: "https://api.openai.com/v1", apiKey: "sk-x" } }, + local: { options: { baseURL: "http://127.0.0.1:8199/v1" } }, + }, + }; + const n = rewriteV1Providers(cfg, origin); + assert.equal(n, 2); + const openai = (cfg.provider?.openai?.options ?? {}) as V1ProviderOptions; + const local = (cfg.provider?.local?.options ?? {}) as V1ProviderOptions; + assert.equal(openai.baseURL, `${origin}/bili/https://api.openai.com/v1`); + assert.equal(local.baseURL, `${origin}/bili/http://127.0.0.1:8199/v1`); + // untouched sibling keys + assert.equal(openai.apiKey, "sk-x"); + }); + + it("is idempotent for already-wrapped URLs", () => { + const cfg: V1Config = { + provider: { wrapped: { options: { baseURL: `${origin}/bili/https://api.openai.com/v1` } } }, + }; + assert.equal(rewriteV1Providers(cfg, origin), 0); + assert.equal(cfg.provider?.wrapped?.options?.baseURL, `${origin}/bili/https://api.openai.com/v1`); + }); + + it("skips non-http and missing baseURLs, handles absent provider table", () => { + const cfg: V1Config = { + provider: { + weird: { options: { baseURL: "file:///nope" } }, + none: { options: {} }, + empty: { options: { baseURL: " " } }, + }, + }; + assert.equal(rewriteV1Providers(cfg, origin), 0); + assert.deepEqual(rewriteV1Providers({}, origin), 0); + const broken: V1Config = { provider: "not-a-table" }; + assert.equal(rewriteV1Providers(broken, origin), 0); + }); + + it("unwraps double-wrapped upstreams instead of nesting", () => { + const cfg: V1Config = { + provider: { x: { options: { baseURL: `http://other:1/bili/https://api.anthropic.com` } } }, + }; + const n = rewriteV1Providers(cfg, origin); + assert.equal(n, 1); + assert.equal(cfg.provider?.x?.options?.baseURL, `${origin}/bili/https://api.anthropic.com`); + }); + + it("disables compaction.auto while merging existing settings", () => { + const cfg: V1Config = { + provider: { x: { options: { baseURL: "https://api.openai.com/v1" } } }, + compaction: { threshold: 0.8 }, + }; + rewriteV1Providers(cfg, origin); + assert.deepEqual(cfg.compaction, { threshold: 0.8, auto: false }); + }); +}); + +describe("createV1ServerHooks", () => { + const origin = "http://127.0.0.1:19199"; + + function makeDeps() { + const forwarded: Array<{ conversationId: string; tool: string; args: unknown }> = []; + return { + z: fakeZ, + forward: async (o: string, conversationId: string, tool: string, args: unknown) => { + forwarded.push({ conversationId, tool, args }); + assert.equal(o, origin); + return `panel:${tool}`; + }, + forwarded, + }; + } + + it("registers /acp command, rewrites providers, stamps headers and tools when zod present", async () => { + const deps = makeDeps(); + const hooks = createV1ServerHooks(origin, {}, deps); + assert.ok(hooks.config); + assert.ok(hooks["chat.headers"]); + assert.ok(hooks["command.execute.before"]); + const names = Object.keys(hooks.tool ?? {}); + assert.ok(names.includes("compress"), `tools include compress, got ${names.join(",")}`); + + const cfg: V1Config = { provider: { o: { options: { baseURL: "https://api.openai.com/v1" } } } }; + await hooks.config?.(cfg); + assert.equal(cfg.provider?.o?.options?.baseURL, `${origin}/bili/https://api.openai.com/v1`); + assert.ok(cfg.command?.acp); + + const headers: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_1" }, { headers }); + assert.equal(headers["x-bili-plugin"], "opencode"); + assert.equal(headers["x-bili-plugin-conversation"], "ses_1"); + + const compress = hooks.tool?.compress; + assert.ok(compress); + const out = await compress.execute({ range: "m1-m2" }, { sessionID: "ses_1" }); + assert.equal(out, "panel:compress"); + assert.deepEqual(deps.forwarded, [{ conversationId: "ses_1", tool: "compress", args: { range: "m1-m2" } }]); + }); + + it("degrades to proxy mode (no headers, no tools) when zod is unavailable", async () => { + const hooks = createV1ServerHooks(origin, {}, {}); + assert.equal(hooks["chat.headers"], undefined); + assert.equal(hooks.tool, undefined); + assert.ok(hooks.config); + const cfg: V1Config = { provider: { o: { options: { baseURL: "https://api.openai.com/v1" } } } }; + await hooks.config?.(cfg); + assert.equal(cfg.provider?.o?.options?.baseURL, `${origin}/bili/https://api.openai.com/v1`); + }); + + it("command.execute.before only reacts to /acp", async () => { + const deps = makeDeps(); + const hooks = createV1ServerHooks(origin, {}, deps); + await hooks["command.execute.before"]?.({ command: "other", sessionID: "s" }); + // /acp path throws the sentinel after rendering — assert the sentinel shape + await assert.rejects( + hooks["command.execute.before"]?.({ command: "acp", sessionID: "ses_x" }), + /__BILI_ACP_HANDLED__/, + ); + }); +}); From eeb08deb0f352051a06c74281d0cd85d94923620 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 18 Sep 2026 01:40:13 +0800 Subject: [PATCH 19/29] feat: OpenCode V1 stamps x-bili-plugin-context-window from config-declared limits Completes V1<->V2 header parity flagged during #919 review. The V1 .server() path reads provider..models..limit.context from the shared config object (V1 exposes no catalog API like V2's ctx.catalog.model.list()) into a provider/model map rebuilt on each config reload, then chat.headers stamps x-bili-plugin-context-window only when the requested model carries a finite, positive declared limit -- byte-compatible with the V2/pi stamping guard. When absent (common for registry-discovered models) nothing is stamped, so the proxy falls back to its models.dev registry window as before; never fabricates a threshold. Adds extractV1Windows (+4 unit tests incl. end-to-end stamping). Local pre-flight: typecheck + build + full suite green (1696 pass). --- src/agent/opencode-native.ts | 43 +++++++++++++++++++++- tests/opencode-native-v1.test.ts | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index e2b6a08767..db4cacaa1b 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -268,8 +268,24 @@ export interface V1ProviderOptions { [key: string]: unknown; } +export interface V1ModelLimit { + context?: unknown; + [key: string]: unknown; +} + +export interface V1ModelDef { + limit?: V1ModelLimit | undefined; + [key: string]: unknown; +} + +export interface V1ProviderDef { + options?: V1ProviderOptions | undefined; + models?: Record | undefined; + [key: string]: unknown; +} + export interface V1Config { - provider?: Record | undefined; + provider?: Record | undefined; command?: Record; compaction?: unknown; [key: string]: unknown; @@ -358,6 +374,24 @@ export function rewriteV1Providers(cfg: V1Config, origin: string): number { return rewritten; } +/** Provider-declared model windows (`provider..models..limit.context`) as a `${id}/${m}` map. + * V1 has no catalog seam (cf. V2 `ctx.catalog.model.list()`), so config is the only window source; + * non-finite/non-positive values are dropped so a partial table stays unstamped rather than fabricated. */ +export function extractV1Windows(cfg: V1Config): Map { + const map = new Map(); + const providers = cfg.provider; + if (providers === null || typeof providers !== "object") return map; + for (const [pid, entry] of Object.entries(providers)) { + const models = entry?.models; + if (models === null || typeof models !== "object") continue; + for (const [mid, model] of Object.entries(models)) { + const c = model?.limit?.context; + if (typeof c === "number" && Number.isFinite(c) && c > 0) map.set(`${pid}/${mid}`, Math.floor(c)); + } + } + return map; +} + export interface V1NativeDeps { /** zod module (tests inject; runtime lazy-imports "zod"). */ z?: ZodLike; @@ -371,11 +405,13 @@ export interface V1NativeDeps { * wires the real bootstrap + zod. */ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: V1NativeDeps = {}): V1Hooks { const acp = createAcpCommandHooks(() => origin, ctx); + let windows = new Map(); const hooks: V1Hooks = { config: async (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/`); + windows = extractV1Windows(cfg); }, "command.execute.before": async (input, _output) => { await acp["command.execute.before"]?.(input); @@ -385,6 +421,11 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: hooks["chat.headers"] = async (input, output) => { output.headers["x-bili-plugin"] = "opencode"; output.headers["x-bili-plugin-conversation"] = input.sessionID; + const model = input.model; + if (model && typeof model.providerID === "string" && typeof model.id === "string") { + const w = windows.get(`${model.providerID}/${model.id}`); + if (w !== undefined) output.headers["x-bili-plugin-context-window"] = String(w); + } }; const forward = deps.forward ?? ((o, conversationId, tool, args) => import("./shared.js").then((m) => m.forwardTool(o, conversationId, tool, args))); const tools: Record = {}; diff --git a/tests/opencode-native-v1.test.ts b/tests/opencode-native-v1.test.ts index 7c1099e512..fcde3371d5 100644 --- a/tests/opencode-native-v1.test.ts +++ b/tests/opencode-native-v1.test.ts @@ -4,6 +4,7 @@ import type { z } from "zod"; import { createV1ServerHooks, + extractV1Windows, jsonSchemaToZodShape, rewriteV1Providers, type V1Config, @@ -130,6 +131,45 @@ describe("rewriteV1Providers", () => { }); }); +describe("extractV1Windows", () => { + it("collects finite positive limits keyed by provider/model and floors them", () => { + const cfg: V1Config = { + provider: { + openai: { models: { gpt: { limit: { context: 128_000.9 } } } }, + anthropic: { models: { claude: { limit: { context: 200_000 } } } }, + }, + }; + const m = extractV1Windows(cfg); + assert.equal(m.get("openai/gpt"), 128000); + assert.equal(m.get("anthropic/claude"), 200000); + }); + + it("drops non-finite, non-positive and non-numeric limits", () => { + const cfg: V1Config = { + provider: { + p: { + models: { + zero: { limit: { context: 0 } }, + neg: { limit: { context: -5 } }, + nan: { limit: { context: Number.NaN } }, + str: { limit: { context: "big" } }, + empty: { limit: {} }, + nolimit: {}, + }, + }, + }, + }; + assert.deepEqual(extractV1Windows(cfg), new Map()); + }); + + it("returns an empty map for missing or broken provider tables", () => { + assert.deepEqual(extractV1Windows({}), new Map()); + assert.deepEqual(extractV1Windows({ provider: "nope" }), new Map()); + assert.deepEqual(extractV1Windows({ provider: { p: {} } }), new Map()); + assert.deepEqual(extractV1Windows({ provider: { p: { models: "nope" } } }), new Map()); + }); +}); + describe("createV1ServerHooks", () => { const origin = "http://127.0.0.1:19199"; @@ -182,6 +222,27 @@ describe("createV1ServerHooks", () => { assert.equal(cfg.provider?.o?.options?.baseURL, `${origin}/bili/https://api.openai.com/v1`); }); + it("stamps x-bili-plugin-context-window from config-declared model limits (omits when absent)", async () => { + const deps = makeDeps(); + const hooks = createV1ServerHooks(origin, {}, deps); + assert.ok(hooks["chat.headers"]); + const cfg: V1Config = { + provider: { + openai: { options: { baseURL: "https://api.openai.com/v1" }, models: { gpt: { limit: { context: 128_000.9 } } } }, + }, + }; + await hooks.config?.(cfg); + const h1: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_w", model: { providerID: "openai", id: "gpt" } }, { headers: h1 }); + assert.equal(h1["x-bili-plugin-context-window"], "128000"); + const h2: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_w", model: { providerID: "openai", id: "other" } }, { headers: h2 }); + assert.equal(h2["x-bili-plugin-context-window"], undefined); + const h3: Record = {}; + await hooks["chat.headers"]?.({ sessionID: "ses_w" }, { headers: h3 }); + assert.equal(h3["x-bili-plugin-context-window"], undefined); + }); + it("command.execute.before only reacts to /acp", async () => { const deps = makeDeps(); const hooks = createV1ServerHooks(origin, {}, deps); From 29a5966f19bd68bee6c64a89f09d6458fe179f58 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 08:46:56 +0800 Subject: [PATCH 20/29] fix: v1 catches SDK-default provider baseURLs via global fetch patch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The V1 config-hook rewrite only reaches providers with an explicit options.baseURL; providers relying on the SDK default (e.g. bare @ai-sdk/openai -> api.openai.com) silently bypassed the proxy. Install the shared native fetch intercept (pi-native's mechanism) in both the native V1 server() and the launcher plugin server() — v1's provider stack resolves fetch per-request, so a global patch catches those calls. Verified end-to-end on opencode-ai 1.18.31 (container, hosts-redirect api.openai.com -> local https shim -> sglang): leaktest provider with no baseURL produced proxy log 'forward POST -> https://api.openai.com/v1/ responses' with x-bili-plugin headers — the request was captured, /bili/-wrapped, and answered. --- README.md | 10 +++++++--- src/agent/opencode-native.ts | 18 ++++++++++++++++-- src/agent/opencode.ts | 9 +++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7efc059539..6f25bee154 100644 --- a/README.md +++ b/README.md @@ -289,9 +289,13 @@ contract: the plugin headers per request; `tool` registers the bili tools with real zod shapes (zod is a runtime dependency — when it cannot be resolved the plugin degrades to plain proxy mode: rewrite only, wire-injected tools); - the `/acp` command renders the same status panel. V1 has no request-level - URL hook, so providers **without** an explicit `baseURL` (SDK defaults) - keep going direct — set a baseURL to be proxied. + the `/acp` command renders the same status panel. Providers **without** + an explicit `baseURL` (SDK defaults, e.g. bare `@ai-sdk/openai` → + api.openai.com) are caught by a global `fetch` patch (the pi-native + mechanism) that reroutes model-API calls to the proxy — verified end-to-end + on 1.14.46 and 1.18.31 (log: `v1: fetch patch installed`), including the + OpenAI Responses endpoint. The patch is idempotent and passes + `/bili/`-wrapped URLs through untouched. - **Pure proxy:** point the provider baseURL at the proxy like any other client: diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index db4cacaa1b..11a9fcf550 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -46,7 +46,8 @@ // - config hook: receives the SHARED cached config object (Config.get → // InstanceState.use) — mutating provider..options.baseURL persists // for the process lifetime, no file writes needed. Providers WITHOUT an -// explicit baseURL (SDK defaults) cannot be caught this way — documented. +// explicit baseURL (SDK defaults) are caught by the global fetch patch +// installed in server() (see installNativeFetchIntercept below). // - "chat.headers": per-LLM-request header mutation — the V1 equivalent of // V2's stampHeaders (x-bili-plugin + conversation id). // - tool: { [name]: { description, args, execute } } registers native tools; @@ -66,7 +67,7 @@ import { ACP_TOOLS_OPENAI } from "../compress-tool.js"; import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST, unwrapUpstream, wrapUpstream } from "../launcher.js"; import { createAcpCommandHooks } from "./opencode-acp-command.js"; import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; -import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; +import { installNativeFetchIntercept, isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js"; /** Decides whether the native bootstrap should run in this process. */ @@ -460,6 +461,19 @@ const server = async (ctx: V1PluginContext): Promise => { return {}; } console.log(`[bili-opencode-native] v1 active (proxy ${origin})`); + // Global fetch patch (pi-native's mechanism): the config-hook rewrite can + // only catch providers with an EXPLICIT baseURL — V1 has no request-level + // hook, and providers relying on the SDK default (e.g. bare + // `@ai-sdk/openai` → api.openai.com) would silently bypass the proxy. + // v1's provider stack resolves `fetch` late (`customFetch ?? fetch` inside + // the per-request wrapper, provider.ts), so a global patch catches those + // requests too. Idempotent (flag-guarded) and disjoint from the config + // rewrite: isModelApiUrl passes `/bili/`-prefixed URLs straight through, + // so already-rewritten providers never double-wrap. Proxy-death respawn / + // degrade-to-direct semantics come with the shared state. + if (installNativeFetchIntercept(state)) { + console.log("[bili-opencode-native] v1: fetch patch installed (catches providers without an explicit baseURL)"); + } let z: ZodLike | undefined; try { z = (await import("zod")) as ZodLike; diff --git a/src/agent/opencode.ts b/src/agent/opencode.ts index 65a57c1527..225fffb9d6 100644 --- a/src/agent/opencode.ts +++ b/src/agent/opencode.ts @@ -18,6 +18,7 @@ import { createAcpCommandHooks } from "./opencode-acp-command.js"; import { createOpencodeV2Setup } from "./opencode-v2.js"; +import { installNativeFetchIntercept, type NativeInterceptState } from "./native-intercept.js"; export { showAcpText } from "./opencode-acp-command.js"; export type { @@ -57,6 +58,14 @@ const proxyBase = process.env.BILLION_CONTEXT_PROXY ?? ""; const server = async (ctx: OpencodePluginContext): Promise => { if (!proxyBase) return {}; console.log("[bili-opencode] plugin active (proxy " + proxyBase + ")"); + // V1 host: same SDK-default-baseURL gap as the native entry — the + // launcher's config-file rewrite only catches explicit baseURLs. Global + // fetch patch catches the rest; `origin` is already resolved (the + // launcher owns the proxy lifecycle, no respawn hooks needed). + const intercept: NativeInterceptState = { origin: proxyBase, ready: Promise.resolve(proxyBase) }; + if (installNativeFetchIntercept(intercept)) { + console.log("[bili-opencode] v1: fetch patch installed (catches providers without an explicit baseURL)"); + } return { ...createAcpCommandHooks(() => proxyBase, ctx), }; From 9b3bd46f1d39fef86855fcf8cc247e371fbe894e Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 09:13:45 +0800 Subject: [PATCH 21/29] docs: sync README.zh-CN opencode coverage with the English README Adds the 1.x/2.x client-table rows, the native-vs-standalone mutual exclusion note, the 2.x launcher bullet, and a condensed Chinese counterpart of the OpenCode-specific section (launcher / native install / V1 .server() details incl. the SDK-default fetch patch). --- README.zh-CN.md | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/README.zh-CN.md b/README.zh-CN.md index 0388469440..7208e2f530 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -78,10 +78,13 @@ AI 编程助手的通用上下文压缩代理 | 客户端 | 用这个 | |---|---| | **pi** | [`billion-context-pi`](https://github.com/ranxianglei/billion-context-pi)(进程内扩展) | -| **opencode** | [`opencode-acp`](https://github.com/ranxianglei/opencode-acp)(进程内扩展) | +| **opencode 1.x** | [`billion-context`](https://github.com/ranxianglei/billion-context) —— `bili plugin install opencode`(V1 `.server()` 钩子,与 2.x 同一个包装器)或 `bili opencode`(启动器);[`opencode-acp`](https://github.com/ranxianglei/opencode-acp)(进程内扩展)仍可用 | +| **opencode 2.0+** | `bili opencode`(内置 V2 插件 —— 原生工具,无需另装包)或 `bili plugin install opencode`(自拉起原生插件,免启动器) | | **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 层改写。 + ## 安装 ```bash @@ -112,7 +115,7 @@ bili pi # 拉起 pi,走代理 —— file-free(#53 bili codex # 拉起 codex bili claude # 拉起 claude bili omp # pi 同款,file-free(#535):环境变量 + 扩展 registerProvider + 压缩取消,真实 ~/.omp 不动 -bili opencode # HTTPS 走 MITM + 临时 opencode.json(HTTP 走 /bili/)+ 轻量 /acp 插件 +bili opencode # HTTPS 走 MITM + 临时 opencode.json(HTTP 走 /bili/)+ 轻量 /acp 插件;OpenCode 2.0+:内置 V2 插件带原生 bili 工具,自动关掉原生 auto-compaction。详见下方「OpenCode 专属说明」 bili hermes # file-free(#535):hermes 代理环境变量(HTTPS_PROXY + HERMES_CA_BUNDLE)—— https 走 CONNECT MITM,http 走绝对形式转发;真实 ~/.hermes 不动 bili dsh # deepseek-harness:非回环上游走代理 env(https MITM、http absolute-form),回环上游保留 overlay DSH_HOME(~/.dsh-bili)改写(#535),内置 deepseek 路由走 DEEPSEEK_BASE_URL,经 --patch 注入原生 /acp 命令 bili codebuddy # Tencent CodeBuddy Code CLI:CODEBUDDY_BASE_URL /bili/ 重写(OpenAI chat completions wire),预算对齐走 CODEBUDDY_AUTO_COMPACT_WINDOW;真实 ~/.codebuddy 不动 @@ -159,6 +162,34 @@ curl -s http://localhost:8787/__bili/stats 同时也打到 stderr)。每个请求应该看到一行 `processTurn`,等对话变长后 会出现 `[acp-usage] round N input=X cached=Y (cache hit Z%)` + `compress` 事件。 +### OpenCode 专属说明 + +OpenCode 2.0 换了新插件 API(`@opencode/plugin`);独立扩展 `opencode-acp` 仅支持 V1,在 2.0 下不加载。bili 的两种模式在 2.0 都能用。2.x 插件 API 面在不同 build 间仍在变动(相邻的 npm `dev` 构建 `ctx` 形状不同),下面列的钩子/工具细节是针对具体版本的观察,不是稳定契约: + +- **启动器:** `bili opencode` 用法不变。在 2.x 宿主上,它把内置 V2 插件(`dist/agent/opencode.js`)以临时包装目录的形式注入临时配置(目录入口 `index.js` 再 re-export 插件文件 —— 2.x 拒绝配置 `plugin` 数组里的裸文件路径;1.x 宿主用裸文件路径)。宿主代次用 `--version` 探测(探测失败默认 1.x 形状)。V2 插件在宿主内原生注册 bili 工具 —— compress / decompress / search_context / acp_status(另加 absorb),JSON-Schema 入参 —— 并在每个 provider 请求上盖章代理头,压缩走插件模式,不做 wire 级工具注入;原生 auto-compaction 自动关闭(`compaction.auto: false`)。所有注册都是防御式的(可选链):任一 2.x build 上接缝缺失或未触发时,插件保持情性,会话透明回退纯代理模式(wire 级注入)而不是报错 —— 在两个相邻 `dev` build(2026-09-13 / 2026-09-14)上观察到过 API 面不同(#754 评审探针);反之在 `@opencode/cli` 2.0.3 上端到端验证过(原生 `acp_status` 经插件端点执行,零 wire 注入)。 +- **原生(免启动器):** npm 装好包后跑 `bili plugin install opencode` —— 它往真实 opencode 配置写一个自拉起插件(`/plugins/billion-context/index.js` → `dist/agent/opencode-native.js`)并设 `compaction.auto: false`,之后直接跑 `opencode` 即可。加载时插件自拉起自己的代理(健康的已有实例直接复用不重复起;父进程 pid 看门狗在 opencode 退出时收掉它),把模型流量路由到 `/bili/`,并暴露与启动器模式相同的原生 bili 工具 —— 无固定端口、无环境变量、免启动器。退出:`BILI_NATIVE_OPENCODE=0`。若没有任何代理能拉到健康状态,请求直连(不压缩)并给一次性告警,之后自动恢复。在 `bili opencode` 启动下该入口整体跳过(代理归启动器管)。 + + 同一个包装器也服务 **OpenCode 1.x**(V1 `.server()` 钩子;在 1.14.46 和 1.18.31 上验证):`config` 钩子在进程内直接改共享配置对象,把每个 provider 的 `options.baseURL` 改写为 `/bili/…` 并设 `compaction.auto: false`;`chat.headers` 每次请求盖章插件头;`tool` 用真实 zod 形状注册 bili 工具(zod 是运行时依赖 —— 解析不到时插件降级纯代理模式:只改写、wire 注入工具);`/acp` 命令渲染同一张状态面板。**没有显式 `baseURL`** 的 provider(SDK 默认值,如裸 `@ai-sdk/openai` → api.openai.com)由全局 `fetch` 补丁(pi-native 同机制)兑住 —— 模型 API 调用重路由到代理(日志:`v1: fetch patch installed`),在 1.14.46 / 1.18.31 上含 OpenAI Responses 端点端到端验证;补丁幂等,`/bili/` 包装过的 URL 原样直通。 +- **纯代理:** 与其它客户端一样,把 provider baseURL 指向代理: + + ```json + { + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://localhost:8787/bili/http://upstream.example/v1", + "apiKey": "sk-any" + } + } + } + } + ``` + + 注意:2.0 AI-SDK provider 即使本地端点从不校验也要求 `apiKey` 字段 —— 随便填个非空值。 + +注意事项:2.x 系列以 npm 包 `@opencode/cli` 发布。命令支持随 build 而定:某个预发布版只暴露 list/get/update/remove,而 2.0.x 稳定版允许插件经 `ctx.command.transform((editor) => editor.add(...))` 新增命令 —— TUI 里接受斜杠菜单补全(Tab + Enter)即可调用;注意 `opencode run` 模式完全不派发斜杠命令(它们会透传给模型)。内置插件在两种形状上都刻意不注册命令。 + ## 运行代理 ### 命令行参数 From 288eca87e8b73992d882a614fca65416209afdf2 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 09:23:59 +0800 Subject: [PATCH 22/29] fix(install): strip legacy opencode-acp entries on bili plugin install opencode (#918) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two compression owners in one host = double compression / ref-space fights. The installer now removes opencode-acp entries from the global opencode.json (bare / npm: / versioned / path specs, array or object shape; original snapshotted to .bili-bak) and warns about project-local installs it cannot touch. Object-shaped plugin maps are normalized to their keys so sibling entries survive. Docs (EN+zh) document the strip and the old-session migration semantics: old refs live in opencode-acp's own store, decompress returns not-found, numbering restarts — treat pre-migration sessions as read-only archives. --- README.md | 4 ++- README.zh-CN.md | 4 ++- src/plugin-install.ts | 63 ++++++++++++++++++++++++++++++++++++++ tests/plugin-agent.test.ts | 37 ++++++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6f25bee154..5d00291129 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,9 @@ 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. + +**Migrating existing sessions from opencode-acp.** Old sessions keep their `` tags, but the ref space lives in opencode-acp's own store; billion-context starts a fresh one per conversation. Consequences: `decompress` of an old ref returns `[Block … not found]`, and new refs restart numbering from m00001 — the same number in old history and in new output can denote different messages. Nothing corrupts on disk, but treat pre-migration sessions as read-only archives and start new sessions after switching. ## Install diff --git a/README.zh-CN.md b/README.zh-CN.md index 7208e2f530..2e4a381b2e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -83,7 +83,9 @@ 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 迁移旧会话。** 旧会话保留其 `` 标签,但引用号空间存在 opencode-acp 自己的存储里;billion-context 对每个会话从零开始。后果:对旧 ref 调 `decompress` 返回 `[Block … not found]`,新 ref 从 m00001 重新编号 —— 旧历史和新输出里同一个号可能指不同消息。磁盘上不会损坏任何东西,但切换后请把迁移前的会话当只读存档,新开会话干活。 ## 安装 diff --git a/src/plugin-install.ts b/src/plugin-install.ts index a825ba4088..a378d54cd7 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -448,6 +448,60 @@ function isPlainMcpObject(v: unknown): v is Record { return v !== null && typeof v === "object" && !Array.isArray(v); } +// 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). +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); + const last = segments[segments.length - 1]; + const parent = segments[segments.length - 2]; + if (last === undefined) return false; + if (last.startsWith("opencode-acp@")) return true; + if (last === "opencode-acp") return true; + return last === "index.js" && parent !== undefined && parent.startsWith("opencode-acp"); +} + +function stripLegacyOpencodeAcp(data: Record, notes: string[]): void { + const removed: string[] = []; + const plugin = data.plugin; + if (Array.isArray(plugin)) { + const kept = plugin.filter((x): x is string => typeof x === "string"); + const survivors: string[] = []; + for (const entry of kept) { + if (isLegacyOpencodeAcpEntry(entry)) removed.push(entry); + else survivors.push(entry); + } + if (removed.length > 0) { + if (survivors.length === 0) delete data.plugin; + else data.plugin = survivors; + } + } else if (plugin !== null && typeof plugin === "object") { + const map = { ...(plugin as Record) }; + for (const key of Object.keys(map)) { + if (isLegacyOpencodeAcpEntry(key)) { + delete map[key]; + removed.push(key); + } + } + if (removed.length > 0) { + if (Object.keys(map).length === 0) delete data.plugin; + else data.plugin = map; + } + } + 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); @@ -477,6 +531,15 @@ 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 writeJson + // below snapshots the original config to .bili-bak (first write only). + // Object-shaped plugin maps (defensive; v1 disk form is an array) are + // normalized to their keys so sibling entries survive the append below. + if (data.plugin !== null && typeof data.plugin === "object" && !Array.isArray(data.plugin)) { + data.plugin = Object.keys(data.plugin as Record); + } + stripLegacyOpencodeAcp(data, notes); const dir = opencodePluginDir(file); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, "index.js"), `export { default } from ${JSON.stringify(agentJs)};\n`); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index b846053072..bedf35fd9c 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -945,6 +945,43 @@ 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 () => { + // array shape: bare name, npm: alias, path, versioned + fs.writeFileSync(ocFile, JSON.stringify({ + plugin: ["opencode-acp", "npm:opencode-acp", "/opt/other-plugin", path.join(home, "ext/opencode-acp/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 { plugin: string[] }; + assert.deepEqual(data.plugin, ["/opt/other-plugin", path.join(home, ".config/opencode/plugins/billion-context")]); + assert.ok(fs.existsSync(`${ocFile}.bili-bak`)); + pluginRemove("opencode"); + + // object shape: version-map form (defensive; normalized to keys) + fs.writeFileSync(ocFile, JSON.stringify({ plugin: { "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")) as { plugin: string[] }; + // sibling object entries survive as bare array specs + our dir + assert.deepEqual(data.plugin, ["other", path.join(home, ".config/opencode/plugins/billion-context")]); + + // no legacy entries -> no note, plugin untouched + pluginRemove("opencode"); + fs.writeFileSync(ocFile, JSON.stringify({ plugin: ["/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"); From 8d79c08ee4ebd8d44025fdc71fb8c9160f6b0199 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 10:05:50 +0800 Subject: [PATCH 23/29] =?UTF-8?q?feat:=20v1=20legacy-lane=20routing=20?= =?UTF-8?q?=E2=80=94=20absorbed=20opencode-acp=20serves=20old=20sessions,?= =?UTF-8?q?=20bili=20owns=20new=20ones=20(#920)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenCode 1.x hosts migrating from opencode-acp keep their pre-migration sessions WORKING. The V1 native entry absorbs the installed opencode-acp package (loadLegacyAcp: .opencode/node_modules > project node_modules > global npm root > config-scope modules) by importing its server() with BILLION_CONTEXT_PROXY unset strictly around the call (its only env check is at entry), then routes per session: - legacy session (acp state file exists in /opencode/storage/plugin/acp/.json) — compression runs INSIDE the absorbed acp (its dcp refs, block store, all five tools). Model requests carry x-bili-plugin-bypass: 1; the proxy forwards them verbatim (no injection/nudge/binding). - new session — tool executors forward to the proxy plugin endpoints (plugin mode). Tool slots carry the DCP schemas for both lanes (v1 registers one def per name process-wide); the executor picks the lane. acp's transforms (system/messages/text.complete) are gated on the legacy predicate so new sessions never enter its registry; its config hook runs on a provider-hidden shadow (its /bili/ self-disable is neutered) and owned keys are merged back. /acp and /dcp route per lane. Degradation: package absent/import-failed -> bili alone, legacy sessions read-only (documented). Also: cherry-picked 74701fb (installer strips legacy opencode-acp entries, #918) — it was pushed to the already-merged #919 branch and orphaned. --- README.md | 7 +- README.zh-CN.md | 7 +- src/agent/opencode-legacy.ts | 155 ++++++++++++++++++++++++++++ src/agent/opencode-native.ts | 129 +++++++++++++++++++++--- src/plugin.ts | 9 ++ src/server.ts | 12 ++- tests/opencode-native-v1.test.ts | 168 +++++++++++++++++++++++++++++++ tests/plugin-bypass.test.ts | 108 ++++++++++++++++++++ 8 files changed, 577 insertions(+), 18 deletions(-) create mode 100644 src/agent/opencode-legacy.ts create mode 100644 tests/plugin-bypass.test.ts diff --git a/README.md b/README.md index 5d00291129..7c5e98af97 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,12 @@ Pick by your client: **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. -**Migrating existing sessions from opencode-acp.** Old sessions keep their `` tags, but the ref space lives in opencode-acp's own store; billion-context starts a fresh one per conversation. Consequences: `decompress` of an old ref returns `[Block … not found]`, and new refs restart numbering from m00001 — the same number in old history and in new output can denote different messages. Nothing corrupts on disk, but treat pre-migration sessions as read-only archives and start new sessions after switching. +**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 2e4a381b2e..5639f55535 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -85,7 +85,12 @@ AI 编程助手的通用上下文压缩代理 **原生模式 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 迁移旧会话。** 旧会话保留其 `` 标签,但引用号空间存在 opencode-acp 自己的存储里;billion-context 对每个会话从零开始。后果:对旧 ref 调 `decompress` 返回 `[Block … not found]`,新 ref 从 m00001 重新编号 —— 旧历史和新输出里同一个号可能指不同消息。磁盘上不会损坏任何东西,但切换后请把迁移前的会话当只读存档,新开会话干活。 +**从 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..d6db1d0e86 --- /dev/null +++ b/src/agent/opencode-legacy.ts @@ -0,0 +1,155 @@ +// 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 } 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 (v1 `opencode plugin opencode-acp`), plain project + * node_modules, global user npm root, 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")); + } + dirs.push(path.join(homedir(), ".local", "lib", "node_modules")); + dirs.push(path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode", "node_modules")); + return dirs.map((d) => path.join(d, "opencode-acp", "dist", "index.js")); +} + +/** 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..1493ef3899 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 }) => Promise; + "experimental.chat.messages.transform"?: (input: unknown, output: { messages?: unknown }) => Promise; + "experimental.text.complete"?: (input: { sessionID: string }) => 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) => { + if ((input.command === "acp" || input.command === "dcp") && legacy?.commandHook !== undefined && isLegacy(input.sessionID)) { + await legacy.commandHook(input); + 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) => { + if (!isLegacy(input.sessionID)) return; + await (sys as (i: unknown) => Promise)(input); + }; + } + 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) => { + if (!isLegacy(input.sessionID)) return; + await (textC as (i: unknown) => Promise)(input); + }; + } + // 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,16 @@ 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 { + legacy = await loadLegacyAcp({ directory: ctx.directory, client: ctx.client }); + } 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.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/opencode-native-v1.test.ts b/tests/opencode-native-v1.test.ts index fcde3371d5..3b0dc6c366 100644 --- a/tests/opencode-native-v1.test.ts +++ b/tests/opencode-native-v1.test.ts @@ -254,3 +254,171 @@ 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 }) => { + events.push(`legacy-command:${input.command}:${input.sessionID}`); + }, + "experimental.chat.system.transform": async (input: { sessionID: string }) => { + events.push(`legacy-system:${input.sessionID}`); + }, + "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 }) => { + events.push(`legacy-text:${input.sessionID}`); + }, + 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) + await hooks["command.execute.before"]?.({ command: "acp", sessionID: "ses_legacy", arguments: "" }); + assert.ok(events.includes("legacy-command:acp:ses_legacy")); + 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 + await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_new" }); + assert.equal(events.filter((e) => e === "legacy-system:ses_new").length, 0); + await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_legacy" }); + assert.ok(events.includes("legacy-system:ses_legacy")); + 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" }); + await hooks["experimental.text.complete"]?.({ sessionID: "ses_legacy" }); + assert.equal(events.filter((e) => e === "legacy-text:ses_new").length, 0); + assert.ok(events.includes("legacy-text:ses_legacy")); + }); + + 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-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)}`); + }); +}); From 49b290f6e30536d4b341aec2752e746c08ca259d Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 18 Sep 2026 10:14:49 +0800 Subject: [PATCH 24/29] fix: pass host ctx through to absorbed acp; match acp path entries by any segment (#920 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review hardening fixes: - loadLegacyAcp now receives the host's full ctx object instead of a {directory, client} projection. V1PluginContext types only the fields bili uses, but the runtime object may carry extra host fields that acp's hooks need at action time (the projection would drop them). - isLegacyOpencodeAcpEntry matches path entries by ANY segment naming opencode-acp instead of only last/parent — deep entry paths like /opencode-acp/dist/index.js were missed, leaving both compression owners armed (the double-compression case #918 exists to prevent). Test fixture extended with the dist/index.js form. --- src/agent/opencode-native.ts | 5 ++++- src/plugin-install.ts | 9 +++------ tests/plugin-agent.test.ts | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 1493ef3899..e5a82e4be4 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -577,7 +577,10 @@ const server = async (ctx: V1PluginContext): Promise => { // bili-only mode (legacy sessions degrade to read-only, documented). let legacy: LegacyAcpModule | undefined; try { - legacy = await loadLegacyAcp({ directory: ctx.directory, client: ctx.client }); + // 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); } catch { legacy = undefined; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index a378d54cd7..c68ae77357 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -461,12 +461,9 @@ function isLegacyOpencodeAcpEntry(entry: string): boolean { } const normalized = entry.replace(/\\/g, "/"); const segments = normalized.split("/").filter((s) => s.length > 0); - const last = segments[segments.length - 1]; - const parent = segments[segments.length - 2]; - if (last === undefined) return false; - if (last.startsWith("opencode-acp@")) return true; - if (last === "opencode-acp") return true; - return last === "index.js" && parent !== undefined && parent.startsWith("opencode-acp"); + // 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[]): void { diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index bedf35fd9c..a42f79da6f 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -951,9 +951,9 @@ test("plugin install opencode replaces legacy opencode-acp entries — array and 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 () => { - // array shape: bare name, npm: alias, path, versioned + // array shape: bare name, npm: alias, path (incl. deep entry path), versioned fs.writeFileSync(ocFile, JSON.stringify({ - plugin: ["opencode-acp", "npm:opencode-acp", "/opt/other-plugin", path.join(home, "ext/opencode-acp/index.js"), "opencode-acp@stable"], + plugin: ["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/); From 72234689b8614b06e2f04510cc79e9944a162f78 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 11:11:06 +0800 Subject: [PATCH 25/29] fix: legacy lane hardening from docker E2E (#920) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pass output param through all absorbed-acp wrappers (system.transform / text.complete / command.execute.before crashed with 'output is undefined' — acp hooks are (input, output) two-arg) - legacyAcpCandidates: include v1 package cache ~/.cache/opencode/packages/opencode-acp@/node_modules (every version, newest first) — that is where 'opencode plugin opencode-acp' actually installs; project/global node_modules rarely see it - wire loadLegacyAcp log through from .server() (absorption was silent) Verified in container: legacy session ses_f4d9 — b1 decompress restores phase-1 facts, model-created b2 block via absorbed acp, model requests bypass-forwarded verbatim ([plugin-bypass] in proxy log); new session ses_f4d821 — tools forward to proxy, session bound (plugin mode). --- src/agent/opencode-legacy.ts | 33 +++++++++++++++++++++++++++------ src/agent/opencode-native.ts | 18 +++++++++--------- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/src/agent/opencode-legacy.ts b/src/agent/opencode-legacy.ts index d6db1d0e86..51890a1d89 100644 --- a/src/agent/opencode-legacy.ts +++ b/src/agent/opencode-legacy.ts @@ -41,7 +41,7 @@ // caller falls back to bili's own V1 tools (current behavior); legacy // sessions then degrade as documented (read-only archives). -import { existsSync } from "node:fs"; +import { existsSync, readdirSync } from "node:fs"; import { homedir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; @@ -66,17 +66,38 @@ export interface LegacyAcpModule { } /** Candidate `opencode-acp/dist/index.js` paths, most specific first: - * project plugin scope (v1 `opencode plugin opencode-acp`), plain project - * node_modules, global user npm root, opencode's config-scope node_modules. */ + * 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")); } - dirs.push(path.join(homedir(), ".local", "lib", "node_modules")); - dirs.push(path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "opencode", "node_modules")); - return dirs.map((d) => path.join(d, "opencode-acp", "dist", "index.js")); + 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. */ diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index e5a82e4be4..eaf9b8de6e 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -305,9 +305,9 @@ export interface V1Hooks { "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 }) => 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 }) => Promise; + "experimental.text.complete"?: (input: { sessionID: string }, output: { text?: unknown }) => Promise; } export interface V1PluginContext { @@ -441,9 +441,9 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: 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); + await legacy.commandHook(input, output); return; } await acp["command.execute.before"]?.(input); @@ -454,9 +454,9 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: // 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) => { + hooks["experimental.chat.system.transform"] = async (input, output) => { if (!isLegacy(input.sessionID)) return; - await (sys as (i: unknown) => Promise)(input); + await (sys as (i: unknown, o: unknown) => Promise)(input, output); }; } const msgT = legacy.hooks["experimental.chat.messages.transform"]; @@ -468,9 +468,9 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps: } const textC = legacy.hooks["experimental.text.complete"]; if (typeof textC === "function") { - hooks["experimental.text.complete"] = async (input) => { + hooks["experimental.text.complete"] = async (input, output) => { if (!isLegacy(input.sessionID)) return; - await (textC as (i: unknown) => Promise)(input); + await (textC as (i: unknown, o: unknown) => Promise)(input, output); }; } // Event hook carries no session (acp uses it only for compress timing @@ -580,7 +580,7 @@ const server = async (ctx: V1PluginContext): Promise => { // 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); + legacy = await loadLegacyAcp(ctx, (msg) => console.log(msg)); } catch { legacy = undefined; } From a63fa66c78b549325dc54e14319f5bcd4143327b Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 18 Sep 2026 12:06:30 +0800 Subject: [PATCH 26/29] test: pin two-arg (input, output) contract on absorbed-acp wrappers (#920 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7223468 fixed real 'output is undefined' crashes in acp's system.transform / text.complete / command.execute.before handlers, but the lane-routing test still called those hooks one-arg with fakes that ignore the second parameter — so a regression of exactly this class would not have been caught (tests are outside tsconfig.build.json, so typecheck does not cover them either). Fakes now record whether output reached them (:output/:no-output marker) and the assertions require it on the legacy lane. Mutation-verified: reverting the wrapper to a one-arg call fails the suite. --- tests/opencode-native-v1.test.ts | 35 ++++++++++++++++---------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/tests/opencode-native-v1.test.ts b/tests/opencode-native-v1.test.ts index 3b0dc6c366..705088877c 100644 --- a/tests/opencode-native-v1.test.ts +++ b/tests/opencode-native-v1.test.ts @@ -276,18 +276,18 @@ function fakeLegacyModule(events: string[]): LegacyAcpModule { events.push(`legacy-config:${JSON.stringify(Object.keys(cfg))}`); cfg.permission = { deny: ["dcp_*"] }; }, - "command.execute.before": async (input: { command: string; sessionID: string }) => { - events.push(`legacy-command:${input.command}:${input.sessionID}`); + "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 }) => { - events.push(`legacy-system:${input.sessionID}`); + "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 }) => { - events.push(`legacy-text:${input.sessionID}`); + "experimental.text.complete": async (input: { sessionID: string }, output?: { text?: unknown }) => { + events.push(`legacy-text:${input.sessionID}:${output === undefined ? "no-output" : "output"}`); }, tool: { compress: { @@ -348,25 +348,26 @@ describe("createV1ServerHooks legacy routing (#920)", () => { 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) - await hooks["command.execute.before"]?.({ command: "acp", sessionID: "ses_legacy", arguments: "" }); - assert.ok(events.includes("legacy-command:acp:ses_legacy")); + // 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 - await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_new" }); - assert.equal(events.filter((e) => e === "legacy-system:ses_new").length, 0); - await hooks["experimental.chat.system.transform"]?.({ sessionID: "ses_legacy" }); - assert.ok(events.includes("legacy-system:ses_legacy")); + // 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" }); - await hooks["experimental.text.complete"]?.({ sessionID: "ses_legacy" }); - assert.equal(events.filter((e) => e === "legacy-text:ses_new").length, 0); - assert.ok(events.includes("legacy-text: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 () => { From 85c9dbf1f5059bdb9e23154b11d87d52a9a6d57b Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 18 Sep 2026 12:23:20 +0800 Subject: [PATCH 27/29] fix(install): version-aware plugin key + jsonc-first target for opencode install (#927) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pick ONE effective plugin key by host major version (>=2 -> plugins, 1.x/probe-failure -> plugin): 1.x hard-errors on 'plugins', 2.x merges both keys, so dual-writing is impossible and the probe fallback can never write a dead line - write target = OPENCODE_CONFIG override, else highest-precedence file already present (opencode.jsonc > opencode.json > config.json), else create opencode.json — no more second file next to an existing config - JSONC targets get surgical top-level-key edits (jsonc-parser), so user comments/formatting survive byte-for-byte; plain JSON keeps the historical full re-serialize; broken targets are refused, never overwritten - compaction.auto is set to false only when the target does not already say auto:false (single source of truth); remove/status now recognize our entry under either key spelling and strip legacy acp entries from both --- src/plugin-install.ts | 264 ++++++++++++++++++------ tests/issue927-opencode-install.test.ts | 256 +++++++++++++++++++++++ tests/plugin-agent.test.ts | 57 +++-- 3 files changed, 493 insertions(+), 84 deletions(-) create mode 100644 tests/issue927-opencode-install.test.ts diff --git a/src/plugin-install.ts b/src/plugin-install.ts index c68ae77357..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,11 +496,74 @@ 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:")) { @@ -466,31 +577,39 @@ function isLegacyOpencodeAcpEntry(entry: string): boolean { return segments.some((s) => s === "opencode-acp" || s.startsWith("opencode-acp@")); } -function stripLegacyOpencodeAcp(data: Record, notes: string[]): void { +function stripLegacyOpencodeAcp(data: Record, notes: string[], touched: Set): void { const removed: string[] = []; - const plugin = data.plugin; - if (Array.isArray(plugin)) { - const kept = plugin.filter((x): x is string => typeof x === "string"); - const survivors: string[] = []; - for (const entry of kept) { - if (isLegacyOpencodeAcpEntry(entry)) removed.push(entry); - else survivors.push(entry); - } - if (removed.length > 0) { - if (survivors.length === 0) delete data.plugin; - else data.plugin = survivors; - } - } else if (plugin !== null && typeof plugin === "object") { - const map = { ...(plugin as Record) }; - for (const key of Object.keys(map)) { - if (isLegacyOpencodeAcpEntry(key)) { - delete map[key]; - removed.push(key); + 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) { - if (Object.keys(map).length === 0) delete data.plugin; - else data.plugin = map; } } if (removed.length > 0) { @@ -500,9 +619,10 @@ function stripLegacyOpencodeAcp(data: Record, notes: string[]): } 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. @@ -511,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"); } } @@ -529,57 +650,69 @@ function opencodeInstall(): string { 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 writeJson + // adding ours, so both never load armed in one host (#918). The write // below snapshots the original config to .bili-bak (first write only). - // Object-shaped plugin maps (defensive; v1 disk form is an array) are - // normalized to their keys so sibling entries survive the append below. - if (data.plugin !== null && typeof data.plugin === "object" && !Array.isArray(data.plugin)) { - data.plugin = Object.keys(data.plugin as Record); - } - stripLegacyOpencodeAcp(data, notes); + 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})`); } @@ -590,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 @@ -602,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/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/plugin-agent.test.ts b/tests/plugin-agent.test.ts index a42f79da6f..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 { @@ -951,28 +955,40 @@ test("plugin install opencode replaces legacy opencode-acp entries — array and 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({ - plugin: ["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"], + [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 { plugin: string[] }; - assert.deepEqual(data.plugin, ["/opt/other-plugin", path.join(home, ".config/opencode/plugins/billion-context")]); + 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({ plugin: { "opencode-acp": "stable", "other": "1.0" } })); + 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")) as { plugin: string[] }; + data = JSON.parse(fs.readFileSync(ocFile, "utf8")); // sibling object entries survive as bare array specs + our dir - assert.deepEqual(data.plugin, ["other", path.join(home, ".config/opencode/plugins/billion-context")]); + assert.deepEqual(data[ocKey], ["other", dir]); + pluginRemove("opencode"); - // no legacy entries -> no note, plugin untouched + // #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"); - fs.writeFileSync(ocFile, JSON.stringify({ plugin: ["/opt/other-plugin"] })); + + // 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); @@ -988,16 +1004,17 @@ test("plugin install/remove/status survive a non-object mcp in opencode.json (#8 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"); From 4bbc4638bc8e2d3830ea1c087b159a1248c24822 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 15:32:51 +0800 Subject: [PATCH 28/29] fix: windows portability of the opencode major-version probe (#927) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI on windows-latest failed twice in tests/issue927-opencode-install.test.ts: - detectOpencodeMajor execFileSync'd BILI_CLIENT_BIN directly — Windows npm global shims are .cmd/.bat, which execFileSync cannot spawn (EINVAL), so every probe failed soft to 1 and the v2 'plugins' key was never chosen. Route .cmd/.bat through the shell with explicit quoting on win32; plain exes and POSIX shebang scripts still go straight through. - the test's fake bins were #!/bin/sh scripts (unspawnable on win32) — now .cmd fakes on Windows, matching the real-world BILI_CLIENT_BIN shape. - 'installed -> ' assertions built RegExp from raw paths — win32 backslash paths are regex metacharacters; switched to includes(). Verified: typecheck clean, 1829 tests (1827 pass / 2 E2E-gated skip), build ok. --- src/plugin-install.ts | 8 +++++++- tests/issue927-opencode-install.test.ts | 27 ++++++++++++++++--------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 7644287836..ffcf375fbf 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -451,7 +451,13 @@ export function detectOpencodeMajor(): number { if (hit !== undefined) return hit; let major = 1; try { - const out = execFileSync(command, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + // Windows: npm global shims are .cmd/.bat — execFileSync cannot spawn + // those directly (EINVAL), so route through the shell with explicit + // quoting. Plain exes and POSIX shebang scripts go straight through. + const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); + const out = viaShell + ? execFileSync(`"${command}" --version`, { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) + : 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 {} diff --git a/tests/issue927-opencode-install.test.ts b/tests/issue927-opencode-install.test.ts index d3cdb243a0..45b8861acb 100644 --- a/tests/issue927-opencode-install.test.ts +++ b/tests/issue927-opencode-install.test.ts @@ -67,16 +67,21 @@ test("pickPluginKey: 2.x writes plugins, 1.x and unknowns write plugin (#927)", test("detectOpencodeMajor: honors BILI_CLIENT_BIN, fails soft to 1 (#927)", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-oc927-ver-")); + const isWin = process.platform === "win32"; try { - const v2bin = path.join(home, "fake-opencode-v2"); - fs.writeFileSync(v2bin, "#!/bin/sh\necho \"opencode 2.0.3\"\n"); - fs.chmodSync(v2bin, 0o755); + // Windows: execFileSync cannot spawn shebang scripts — fake the npm + // global shim shape (.cmd) there, matching what BILI_CLIENT_BIN points + // at in the wild. + const ext = isWin ? ".cmd" : ""; + const v2bin = path.join(home, `fake-opencode-v2${ext}`); + fs.writeFileSync(v2bin, isWin ? "@echo opencode 2.0.3\r\n" : "#!/bin/sh\necho \"opencode 2.0.3\"\n"); + if (!isWin) 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); + const deadBin = path.join(home, `fake-opencode-dead${ext}`); + fs.writeFileSync(deadBin, isWin ? "@exit /b 3\r\n" : "#!/bin/sh\nexit 3\n"); + if (!isWin) fs.chmodSync(deadBin, 0o755); await withEnv({ BILI_CLIENT_BIN: deadBin }, async () => { assert.equal(detectOpencodeMajor(), 1); }); @@ -154,7 +159,9 @@ test("fresh config dir: creates plain opencode.json, remove restores pre-install try { await withEnv(env, async () => { const msg = pluginInstall("opencode"); - assert.match(msg, new RegExp(`installed -> ${file} \\(`)); + // plain includes(): `file` on win32 is a backslash path that must + // not be fed to a regex + assert.ok(msg.includes(`installed -> ${file} (`), msg); assert.match(msg, /compaction\.auto set to false/); const data = JSON.parse(fs.readFileSync(file, "utf8")) as Record; assert.deepEqual(data.compaction, { auto: false }); @@ -182,7 +189,9 @@ test("only config.json present: installer edits it, does not spawn opencode.json try { await withEnv(env, async () => { const msg = pluginInstall("opencode"); - assert.match(msg, new RegExp(`installed -> ${file} \\(`)); + // plain includes(): `file` on win32 is a backslash path that must + // not be fed to a regex + assert.ok(msg.includes(`installed -> ${file} (`), msg); const data = JSON.parse(fs.readFileSync(file, "utf8")) as Record; assert.equal(data.marker, "keep"); assert.ok(Array.isArray(data[ocKey])); @@ -206,7 +215,7 @@ test("jsonc + json both present: jsonc wins, sibling json stays byte-identical ( try { await withEnv(env, async () => { const msg = pluginInstall("opencode"); - assert.match(msg, new RegExp(`installed -> ${jsoncFile} \\(`)); + assert.ok(msg.includes(`installed -> ${jsoncFile} (`), msg); const data = readJsonc(jsoncFile); assert.ok(Array.isArray(data[ocKey])); assert.equal(fs.readFileSync(jsonFile, "utf8"), siblingBytes, "sibling opencode.json untouched"); From a627201706e50cce6dbf64c6fd74e3ca3bebd70b Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Fri, 18 Sep 2026 15:50:52 +0800 Subject: [PATCH 29/29] =?UTF-8?q?fix:=20windows=20CI=20=E2=80=94=20shell-m?= =?UTF-8?q?ode=20.cmd=20probe,=20separator-preserving=20PATH=20join=20(#92?= =?UTF-8?q?7=20follow-up)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four windows-latest failures remained after 7a15acc: - detectOpencodeMajor passed the quoted command STRING to execFileSync without shell:true — node treats the whole string as one executable path, ENOENT, probe fails soft to 1. Add shell:true to the .cmd/.bat branch. - resolveNodeRuntime joined PATH candidates through the HOST path module: a posix-style entry on a win32 host gets rewritten to backslashes (and vice versa), so the probe misses runtimes the PATH actually contains. Concatenate separator-preserving instead — win32 accepts forward slashes, and the candidate keeps the exact bytes existsImpl can match. - plugin-entry assertion grepped the raw index.js bytes where the path is JSON-escaped (doubled backslashes on win32) — normalize separators before matching. Verified: typecheck clean, 1829 tests (1827 pass / 2 E2E-gated skip), build ok. --- src/launcher.ts | 9 ++++++++- src/plugin-install.ts | 2 +- tests/plugin-agent.test.ts | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/launcher.ts b/src/launcher.ts index 58bdb954af..3463d21faf 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -2010,12 +2010,19 @@ export function resolveNodeRuntime( if (base === "node" || base === "node.exe") return execPath; const override = typeof env.BILLION_CONTEXT_NODE === "string" ? env.BILLION_CONTEXT_NODE.trim() : ""; if (override.length > 0 && existsImpl(override)) return override; + // join with the SIMULATED platform's separators: a posix-style PATH on + // win32 (and vice versa) must not be normalized through the host's + // path.join, or the candidates no longer match what existsImpl expects. const sep = platform === "win32" ? ";" : ":"; const names = platform === "win32" ? ["node.exe"] : ["node"]; for (const dir of (env.PATH ?? "").split(sep)) { if (!dir) continue; for (const name of names) { - const candidate = path.join(dir, name); + // separator-preserving concatenation: never normalize — win32 + // accepts forward slashes, and normalizing through path.join + // would rewrite a posix-style entry on a win32 host (or the + // reverse), missing the file existsImpl would find. + const candidate = dir.endsWith("/") || dir.endsWith("\\") ? dir + name : dir + "/" + name; if (existsImpl(candidate)) return candidate; } } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index ffcf375fbf..a53753f6b7 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -456,7 +456,7 @@ export function detectOpencodeMajor(): number { // quoting. Plain exes and POSIX shebang scripts go straight through. const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); const out = viaShell - ? execFileSync(`"${command}" --version`, { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) + ? execFileSync(`"${command}" --version`, { shell: true, timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) : execFileSync(command, ["--version"], { timeout: 5000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); const m = /(\d+)\s*\./.exec(out); if (m) major = parseInt(m[1], 10); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index d70ff16d67..b3adfa3726 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -903,7 +903,7 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO 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[ocKey], ["some-other-plugin", ocPluginDir]); - assert.match(fs.readFileSync(path.join(ocPluginDir, "index.js"), "utf8"), /agent[\\/]opencode-native\.js/); + assert.match(fs.readFileSync(path.join(ocPluginDir, "index.js"), "utf8").replace(/\\+/g, "/"), /agent\/opencode-native\.js/); assert.deepEqual(oc.compaction, { auto: false, buffer: 100 }); const ocAgain = pluginInstall("opencode"); assert.match(ocAgain, /mcp\.bili present/);