diff --git a/README.md b/README.md index b5daa721c5..bc825a4899 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,8 @@ Pick by your client: | Client | Use | |---|---| | **pi** | [`billion-context-pi`](https://github.com/ranxianglei/billion-context-pi) (in-process extension) | -| **opencode** | [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) (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) | | **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 | @@ -202,7 +203,7 @@ bili pi # launch pi through the proxy — file-fre bili codex # launch codex through the proxy bili claude # launch claude through the proxy bili omp # pi-style, file-free (#535): env + extension registerProvider + compaction cancel, real ~/.omp untouched -bili opencode # MITM for HTTPS + temp opencode.json (/bili/ for HTTP) + thin /acp plugin +bili opencode # MITM for HTTPS + temp opencode.json (/bili/ for HTTP) + thin /acp plugin; OpenCode 2.0+: built-in V2 plugin with native bili tools, native compaction auto-disabled bili hermes # file-free (#535): hermes proxy env (HTTPS_PROXY + HERMES_CA_BUNDLE) — https via CONNECT MITM, http via absolute-form forward proxy; real ~/.hermes untouched bili dsh # deepseek-harness: non-loopback upstreams ride proxy envs (https MITM, http absolute-form), loopback keeps the overlay DSH_HOME (~/.dsh-bili) rewrite (#535), built-in deepseek route via DEEPSEEK_BASE_URL, native /acp command injected via --patch bili codebuddy # Tencent CodeBuddy Code CLI: CODEBUDDY_BASE_URL /bili/ rewrite (OpenAI chat completions wire), budget aligned via CODEBUDDY_AUTO_COMPACT_WINDOW; real ~/.codebuddy untouched @@ -238,6 +239,68 @@ automatically. For per-client configuration examples (OpenCode, Codex, Pi, login-client MITM, …) see the web UI guide at [http://localhost:8787](http://localhost:8787). +### OpenCode 2.0 + +OpenCode 2.0 ships a new plugin API (`@opencode/plugin`); the standalone +`opencode-acp` extension is V1-only and does not load under 2.0. Both bili +modes work on 2.0. The 2.x plugin API surface is still moving between builds +(adjacent npm `dev`-channel builds expose different `ctx` shapes), so the +hook/tool details below are version-specific observations, not a stable +contract: + +- **Launcher:** `bili opencode` works unchanged. On a 2.x host it injects the + built-in V2 plugin (`dist/agent/opencode.js`) into the temp config as a temp + wrapper directory whose `index.js` re-exports the plugin file — 2.x rejects + bare file paths in the config `plugin` array (directory entries use + `index.js` as entrypoint); 1.x hosts get the bare file path. Host generation + is detected with a `--version` probe (a failed probe defaults to the 1.x + shape). The V2 plugin registers the bili tools natively in-host — compress / + decompress / search_context / acp_status (+ absorb), JSON-Schema inputs — and + stamps the proxy headers on every outgoing provider request, so compression + runs in plugin mode with no wire-level tool injection. Native auto-compaction + is disabled automatically (`compaction.auto: false`). Every registration is + defensive (optional chaining): on any 2.x build where a seam is missing or + 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 + on `@opencode/cli` 2.0.3 (native `acp_status` executed through the plugin + endpoint, zero wire-level injection). +- **Pure proxy:** point the provider baseURL at the proxy like any other + client: + + ```json + { + "provider": { + "myprovider": { + "npm": "@ai-sdk/openai-compatible", + "options": { + "baseURL": "http://localhost:8787/bili/http://upstream.example/v1", + "apiKey": "sk-any" + } + } + } + } + ``` + + Note: 2.0 AI-SDK providers require an `apiKey` field even for local + endpoints that never check it — set any non-empty value. + +Caveats: the 2.x line publishes as npm package `@opencode/cli`. Command +support is build-dependent: one pre-release exposed only +list/get/update/remove, while 2.0.x stable lets plugins ADD commands via +`ctx.command.transform((editor) => editor.add(...))` — invocable in the TUI by +accepting the slash-menu completion (Tab + Enter); note `opencode run` mode +dispatches no slash commands at all (they pass through to the model). The +bundled plugin deliberately registers no commands on either shape — call the +`acp_status` tool instead of an `/acp` command. The bundled agent file keeps +the V1 `server()` export alongside the V2 `setup()`, so the same artifact also +loads on hosts ≥ 1.18.29 that support dual-shape plugins. Design note: the V2 plugin is a thin protocol client (no +acp-kernel inside) because the proxy stays the single compression authority, +which eliminates kernel-version drift between agent and proxy — it does not +rely on the plugin API being unable to mutate context (that capability varies +by 2.x build). + ### Verify With the proxy running and your config saved, check it answers and that your diff --git a/devlog/2026-09-13_opencode-v2/DESIGN.md b/devlog/2026-09-13_opencode-v2/DESIGN.md new file mode 100644 index 0000000000..122c3e9388 --- /dev/null +++ b/devlog/2026-09-13_opencode-v2/DESIGN.md @@ -0,0 +1,133 @@ +# DESIGN — OpenCode 2.0 launcher mode + +## Module shape: dual-shape default export + +`src/agent/opencode.ts` keeps the existing V1 `server()` function and adds a +V2 `setup(ctx)`. The default export becomes: + +``` +{ id: "billion-context-opencode", setup, server } +``` + +Hosts ≥ 1.18.29 accept an object that is both a V1 plugin (`server`) and a +V2 plugin definition (`id` + `setup`); older hosts ignore the extra keys. One +artifact serves both generations — no separate package or entry point. + +## Why static tool registration + +`ctx.tool.transform(editor => editor.add(...))` must be synchronous, cheap, +and replayable; the probed 2.0 runtime has no `ctx.tool.reload()`, so tools +cannot be registered lazily after an async manifest fetch. Instead the tool +list is built at module load from the **same bundled schemas** the proxy +serves in its OpenAI manifest (`ACP_TOOLS_OPENAI` + `ABSORB_TOOL_OPENAI` from +`src/compress-tool.ts`). Parity between host-registered tools and wire-injected +tools cannot drift because both sides are the same const. + +## Interception point: `http.request`, not `model.request` + +Probed against the real 2.0 pre-release binary: `session.hook("model.request")` +registers successfully but never fires. `session.hook("http.request")` fires +per outgoing provider request with `e = { sessionID, agent, model, request }` +where `request` is a standard fetch `Request`; mutating `request.headers` +reaches the wire (probe-verified). The hook therefore: + +1. kill-switch check (`BILLION_CONTEXT_PLUGIN === "0"`); +2. lazy proxy-base detection from `request.url` (`proxyBaseFromUrl`) falling + back to `BILLION_CONTEXT_PROXY`; +3. refreshes the context-window map (60s throttle) from + `ctx.catalog.model.list()`; +4. stamps `x-bili-plugin: opencode`, `x-bili-plugin-conversation: `, + and — when known — `x-bili-plugin-context-window`. + +Lazy detection means the same artifact works for launcher mode (baseURL +already `/bili/-wrapped`) and any manual pure-proxy setup without env vars. + +## Tool execution path + +Native tool `execute(input)` → `forwardTool(proxyBase, sessionID, name, args)` +→ `POST /__bili/plugin/tool` on the proxy. The proxy executes via the kernel +and returns the result text; the agent returns `{ content }`. Because the +header marks the session plugin-mode, the proxy suppresses wire-level ACP tool +injection for these sessions (existing behavior, no change) — the model sees +exactly one copy of each tool, the native one. The kill switch +(`BILLION_CONTEXT_PLUGIN=0`) gates `execute` too, alongside header stamping +and compaction reporting — fully inert, matching `detectProxyBase` semantics. + +## Native compaction boundary + +`ctx.event.subscribe({ signal })` async iterator; on +`session.compaction.ended` the plugin POSTs the conversation id to +`/__bili/plugin/compact` so the proxy archives its blocks at the boundary +(#421 path). Errors are swallowed — a missed report degrades to the existing +orphan-GC behavior, never breaks the host session. Cleanup aborts the signal +and disposes every registration. + +## Launcher change + +`prepareOpencodeHttpRewrite` merges `compaction.auto: false` into the temp +config (preserving any user-set sibling keys). Verified tolerant on V1 1.14.46 +(unknown top-level key ignored), so no version detection is needed. + +## Addendum 2026-09-14 — API-surface drift (PR #754 review) + +External report (@jensenojs, #754 thread, with repro script `v2probe.sh`): on +**2.0.1 stable** all four "runtime facts" above from the next-17444 +pre-release invert or shift — `model.request` fires; `ctx.tool = {reload, +transform, hook}`; `ctx.command = {list, transform, reload}`; and `context` +mutation reaches the wire. Provenance of that binary is not on any public +channel checked (npm `opencode-ai` has no 2.x versions under any package name; +GitHub releases ≤ v1.18.30) — exact re-probe pending an artifact identifier. + +Independent probes during review (local LLM upstream, hermetic HOME): + +| build | plugin entry | ctx.session | ctx.tool | hooks fired | bili outcome | +|---|---|---|---|---|---| +| next-17444 pre-release (author) | setup() | yes | no reload | http.request only | plugin mode (author's Live ②) | +| npm dev 2026-09-13 (`0.0.0-dev-202609132139`) | V1 server() only | n/a | n/a | n/a | proxy-mode fallback (zero `[plugin]`, one `[acp-loop]`) | +| npm dev 2026-09-14 (`0.0.0-dev-202609140717`) | setup() | **absent** (ctx = options,agent,aisdk,catalog,command,integration,plugin,reference,skill) | absent | none (cannot register) | proxy-mode fallback (same log signature) | + +Consequences applied: + +1. README + this file now state the facts as version-specific observations, + not general V2 behavior. +2. The thin-shell rationale was re-based: single compression authority + + kernel-version-drift elimination, NOT "plugins cannot mutate context" + (that capability varies by build). +3. No code change required — every registration already uses optional + chaining (inert-safe); new test pins `setup({})` resolving cleanly. The + graceful-degradation path (no seam → transparent proxy mode) is now + empirically verified on two adjacent builds. +4. `/acp` conclusion survives: no observed 2.x build exposes an add-command + entry point (both list/get/update/remove and list/transform/reload shapes + lack one). + +## Addendum 2 (2026-09-14, later) — @opencode/cli 2.0.x stable verification + launcher fix + +Provenance resolved: the 2.x line publishes on npm as `@opencode/cli` +(bins `opencode`/`opencode2`; platform packages like +`@opencode/cli-linux-x64`). `opencode-ai` / `opencode` / `@opencode-ai/cli` +are the 1.x line. Verified live on 2.0.1 and 2.0.3 in the same hermetic +setup. + +| build | plugin entry | ctx.session | ctx.tool | hooks fired | bili outcome | +|---|---|---|---|---|---| +| @opencode/cli 2.0.1 | setup() | yes (hook/create/get/…) | {reload,transform,hook} | model.request + http.request | seam probe green | +| @opencode/cli 2.0.3 | setup() | yes | {reload,transform,hook} | model.request + http.request | **true plugin mode end-to-end** (`[plugin] tool acp_status executed via plugin`, zero `[acp-loop]`) | + +Command-fact correction (supersedes Addendum item 4): on 2.0.x stable +`ctx.command.transform(editor => editor.add(definition))` WORKS — the +editor's only key is `add`; added commands appear in the slash menu and are +invocable in the TUI by accepting the completion (Tab + Enter); `opencode +run` mode dispatches NO slash commands at all (they pass through to the +model). The bundled plugin still registers no commands — `acp_status` +remains the in-host equivalent. + +Launcher bug found + fixed (this addendum): OC 2.0.x rejects FILE paths in +the config `plugin` array (WARN "configured plugin path must be a directory"; +a directory entry's `index.js` is the entrypoint), so `bili opencode` was +silently degrading every 2.x launch to proxy mode. Fix: `opencodeMajorVersion` +(`--version` probe, cached per path, failure defaults to 1) gates a new +`pluginDirMode` on `prepareOpencodeHttpRewrite`, which injects a temp wrapper +dir whose `index.js` re-exports `dist/agent/opencode.js`. Verified end-to-end +through the real launcher on 2.0.3 (captured temp config shows the directory +entry; log shows true plugin mode as above). diff --git a/devlog/2026-09-13_opencode-v2/REQ.md b/devlog/2026-09-13_opencode-v2/REQ.md new file mode 100644 index 0000000000..4aaefa70e9 --- /dev/null +++ b/devlog/2026-09-13_opencode-v2/REQ.md @@ -0,0 +1,52 @@ +# REQ — OpenCode 2.0 support (pure-proxy verification + V2 launcher mode) + +Source: issue #735 (transferred from ranxianglei/opencode-acp#395). + +## Problem + +OpenCode 2.0 ships a new plugin API (`@opencode/plugin`, `Plugin.define({ id, +setup })`). The official migration guide states V1 plugins do not run under V2, +so `opencode-acp` (V1, npm latest 1.18.0) is unusable on OpenCode 2.0. Per the +decision in opencode-acp#395, V2 support lands in billion-context instead of +porting the standalone V1 implementation (which would perpetuate a second fork +of the kernel logic): + +1. **Pure proxy mode** — provider baseURL pointed at `/bili/`. Wire-level, + independent of the host plugin API version; needs live verification on 2.0. +2. **New OpenCode V2 launcher mode** — counterpart of `bili pi` / `bili + codex`: acp-kernel + thin host glue providing in-host native tools. + +## Scope + +- ① Verify the full pure-proxy chain on OpenCode 2.0: auth, request parsing, + SSE rewriting, ACP tool injection & execution. Record and fix any 2.0 + baseURL/auth differences. +- ② Add the V2 launcher path in `src/agent/opencode.ts`: + - tools compress / decompress / search_context / acp_status (+ absorb) with + JSON-Schema inputs and structured results; + - header stamping so the proxy binds sessions into plugin mode; + - context-window identification from the host catalog domain; + - native-compaction boundary reporting to the proxy archive (#421 path); + - launcher auto-disables native compaction (`compaction.auto: false`). +- Docs: OpenCode 2.0 install/configuration (pure-proxy config shape, launcher + behavior, known limitations). + +## Acceptance criteria (adapted from opencode-acp#395 item 9) + +- Plugin loads on a real OpenCode 2.0 binary (tools visible in-host); +- Tools register with JSON Schema inputs and execute against the proxy; +- System/message context handling verified (mutability probed live); +- Session restore/fork not regressed (plugin state is per-setup, re-created); +- Model switching + context window identification (catalog domain); +- Permission handling: tools registered with `permission: "allow"`; +- Plugin unload/reload cleans up subscriptions (no leaks); +- Full run with built-in auto-compaction disabled (`compaction.auto: false`). + +## Constraints + +- No new runtime dependencies (agent bundles stay self-contained via tsup); +- No `as any` / `@ts-ignore`; no comments unless load-bearing; +- Both compression modes must keep working (proxy-mode clients unchanged); +- The same agent artifact must still serve OpenCode 1.x hosts (dual-shape + export, supported since host ≥ 1.18.29); +- Version field untouched (feature branch). diff --git a/devlog/2026-09-13_opencode-v2/WORKLOG.md b/devlog/2026-09-13_opencode-v2/WORKLOG.md new file mode 100644 index 0000000000..4b2e1c2937 --- /dev/null +++ b/devlog/2026-09-13_opencode-v2/WORKLOG.md @@ -0,0 +1,48 @@ +# WORKLOG — OpenCode 2.0 support + +Branch: `2026-09-13_opencode-v2` · Issue: #735 (from opencode-acp#395) + +## Changes + +| File | Change | +|------|--------| +| `src/agent/opencode.ts` | V2 branch appended: `setup(ctx)` per the probed 2.0 runtime API; default export becomes the dual-shape object `{ id, setup, server }` (V1 `server()` untouched) | +| `src/agent/shared.ts` | `fetchManifest` gains an optional `"openai"` format (maps `tools.openai[] {name, description, parameters}` → `{name, description, inputSchema}`); new `reportCompactionBoundary` POST helper (`/__bili/plugin/compact`) | +| `src/launcher.ts` | `prepareOpencodeHttpRewrite` merges `compaction: { ...existing, auto: false }` into the generated temp config (safe on both generations — V1 tolerates the unknown key) | +| `tests/opencode-v2.test.ts` | New: 9 tests — dual export shape, static tool parity vs bundled schemas, inert-without-proxy, kill switch, `/bili/`-URL activation + header timing + tool forwarding, env-based activation, compaction-boundary reporting, cleanup dispose, manifest openai mapping | +| `tests/launcher.test.ts` | +2 assertions: temp opencode config carries `compaction.auto === false` | +| `README.md` | "Which do I need?" table split by generation; launcher line; new "OpenCode 2.0" section (pure-proxy config incl. apiKey requirement, launcher behavior, `/acp` limitation) | + +## Verification + +- `npm run typecheck` — clean; `npm run build` — clean; `npm test` — 1243/1244 + (sole failure: pre-existing sandbox env issue in `resolveClientCommand` + codex test, fails identically on unmodified master). +- Live ①: real OpenCode 2.0 pre-release binary against a local sglang upstream + through the proxy — pure-proxy round-trip OK with the documented config + shape; provider requires a non-empty `apiKey` even for local endpoints. +- Live ②: real OC2 binary + built `dist/agent/opencode.js` plugin: + - model called the **native** `acp_status` tool; bili log shows + `[plugin] tool acp_status executed via plugin` and zero `[acp-loop]` + lines → true plugin mode, no wire-level tool injection; + - probe harness confirmed header mutations on `e.request.headers` reach the + wire (probe header recorded by an echo server on every request). + +## Lessons learned (probed against the real 2.0 pre-release binary) + +1. **`session.hook("model.request")` registers but never fires.** The working + interception point is `session.hook("http.request")` — fires per outgoing + provider request with a standard fetch `Request` at `e.request`; mutating + `e.request.headers` reaches the wire. The published `@opencode/plugin@2.0.2` + typings advertise `model.request`; trust runtime probes over typings here. +2. **No `ctx.tool.reload()`.** The host replays transforms on its own reload + events; tools must be registered synchronously from bundled schemas (this + file and the proxy's OpenAI tool list are built from the same source, + `src/compress-tool.ts`, so parity cannot drift). +3. **Command editor is read/update-only** (`list/get/update/remove`) — plugins + cannot add commands, hence no `/acp` under 2.0; the `acp_status` native + tool is the equivalent. +4. OC2 swallows plugin `console.error` output in `run` mode — probes must log + to a file. +5. Stale OC2 persistent service (`serve --service`) makes new runs die with + "Error: Transport" before any request — kill it first when debugging. diff --git a/src/agent/opencode.ts b/src/agent/opencode.ts index 0f744802cf..58926ef8f4 100644 --- a/src/agent/opencode.ts +++ b/src/agent/opencode.ts @@ -8,7 +8,8 @@ // pending-register queue (POST /__bili/plugin/register on session.created) // - renders the proxy's buildStatusPanel via an ignored chat message -import { fetchProxyVersion } from "./shared.js"; +import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js"; +import { fetchProxyVersion, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js"; interface OpencodeCommandConfig { template: string; @@ -126,4 +127,206 @@ const server = async (ctx: OpencodePluginContext): Promise => { }; }; -export default server; +// --------------------------------------------------------------------------- +// 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; + }; +}; + +export default { id: "billion-context-opencode", setup, server }; diff --git a/src/agent/shared.ts b/src/agent/shared.ts index f13f649646..c6bcfc99fb 100644 --- a/src/agent/shared.ts +++ b/src/agent/shared.ts @@ -84,15 +84,36 @@ async function fetchJson(url: string, init: RequestInit | undefined, timeoutMs: } } -export async function fetchManifest(proxyBase: string): Promise { +export async function fetchManifest(proxyBase: string, format: "anthropic" | "openai" = "anthropic"): Promise { const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/manifest`, undefined, MANIFEST_TIMEOUT_MS); if (!ok || !json || typeof json !== "object") throw new Error(`manifest fetch failed: ${status}`); + if (format === "openai") { + // OpenAI function style: {name, description, parameters} (plain JSON Schema). + const data = json as { tools?: { openai?: { name?: string; description?: string; parameters?: unknown }[] } }; + const tools = (data.tools?.openai ?? []).filter((t): t is { name: string; description?: string; parameters?: unknown } => typeof t.name === "string"); + if (tools.length === 0) throw new Error("manifest served no openai tools"); + return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters ?? { type: "object", properties: {} } })); + } const data = json as { tools?: { anthropic?: { name?: string; description?: string; input_schema?: unknown }[] } }; const tools = (data.tools?.anthropic ?? []).filter((t): t is { name: string; description?: string; input_schema?: unknown } => typeof t.name === "string"); if (tools.length === 0) throw new Error("manifest served no anthropic tools"); return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema ?? { type: "object", properties: {} } })); } +const COMPACT_TIMEOUT_MS = 5000; + +/** Report a host-native compaction boundary to the proxy archive (#395): + * hosts that compact natively (opencode) cannot cancel it, so the proxy + * marks the boundary and archives unreachable blocks. Fire-and-forget at + * call sites — a missed report degrades to stale blocks, not broken turns. */ +export async function reportCompactionBoundary(proxyBase: string, conversationId: string): Promise { + await fetchJson(`${proxyBase}/__bili/plugin/compact`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId }), + }, COMPACT_TIMEOUT_MS); +} + export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal): Promise { const { ok, status, json } = await fetchJson(`${proxyBase}/__bili/plugin/tool`, { method: "POST", diff --git a/src/launcher.ts b/src/launcher.ts index 944f2e83cc..3d67da2b3e 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -32,7 +32,7 @@ import net from "node:net"; import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { spawn, type StdioOptions } from "node:child_process"; +import { execFileSync, spawn, type StdioOptions } from "node:child_process"; import { DEFAULT_MITM_DOMAINS } from "./mitm.js"; import { claimStartingMarker, @@ -1624,11 +1624,36 @@ export function dshArgsWithPatch(args: readonly string[], patchFile: string): st return ["--patch", patchFile, ...args]; } +export function parseOpencodeMajor(output: string): number | undefined { + const m = /(\d+)\s*\./.exec(output); + return m ? parseInt(m[1], 10) : undefined; +} + +const ocMajorCache = new Map(); + +/** Major version of an OpenCode CLI binary via `--version` (cached per path). + * Probe failure defaults to 1 — the legacy file-path plugin injection that + * OpenCode 1.x understands — so a broken probe can never break a launch. */ +export function opencodeMajorVersion(command: string): number { + 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 parsed = parseOpencodeMajor(out); + if (parsed !== undefined) major = parsed; + } catch {} + ocMajorCache.set(command, major); + return major; +} + /** * opencode counterpart of preparePiHttpRewrite: write a full copy of the user's * opencode.json with the discovered providers' baseURL rewritten (HTTP → * /bili/ wrap, wrapped-HTTPS → raw https for cert MITM) into a temp dir, and * point OPENCODE_CONFIG at it. The real opencode.json is never touched. + * With pluginDirMode (OpenCode 2.x), the plugin rides as a temp directory whose + * index.js re-exports pluginPath — 2.x rejects bare file paths in `plugin`. * Returns the temp config FILE path (undefined when there is nothing to do or * the config can't be parsed). */ @@ -1638,6 +1663,7 @@ export function prepareOpencodeHttpRewrite( httpRewrites: HttpRewrite[], httpsRewrites: HttpRewrite[], pluginPath?: string, + pluginDirMode?: boolean, ): string | undefined { if (httpRewrites.length === 0 && httpsRewrites.length === 0 && !pluginPath) return undefined; let root: Record = {}; @@ -1666,12 +1692,28 @@ export function prepareOpencodeHttpRewrite( rewrite(httpRewrites, true); rewrite(httpsRewrites, false); } - if (pluginPath) { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bili-opencode-")); + let pluginEntry = pluginPath; + if (pluginPath && pluginDirMode) { + const wrapDir = path.join(tmp, "plugin"); + fs.mkdirSync(wrapDir); + fs.writeFileSync(path.join(wrapDir, "index.js"), `export { default } from ${JSON.stringify(pluginPath)};\n`); + pluginEntry = wrapDir; + } + if (pluginEntry) { const plugins = Array.isArray(root.plugin) ? root.plugin.filter((p): p is string => typeof p === "string") : []; - if (!plugins.includes(pluginPath)) plugins.push(pluginPath); + if (!plugins.includes(pluginEntry)) plugins.push(pluginEntry); root.plugin = plugins; } - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bili-opencode-")); + // ACP owns compression in launcher mode: disable the host's native + // auto-compaction so it cannot destroy ACP-tagged context. The key is + // unknown (and ignored) on OpenCode 1.x, so this is safe on both + // generations; user-set fields (keep/buffer) survive via the merge. + const existingCompaction = root.compaction; + root.compaction = { + ...(existingCompaction && typeof existingCompaction === "object" && !Array.isArray(existingCompaction) ? existingCompaction as Record : {}), + auto: false, + }; const tmpFile = path.join(tmp, "opencode.json"); fs.writeFileSync(tmpFile, JSON.stringify(root)); return tmpFile; @@ -2319,7 +2361,8 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {} env = { ...process.env, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: ca, BILLION_CONTEXT_PROXY: origin }; const opencodePlugin = selfDistFile("agent/opencode.js"); const opencodePluginPath = opencodePlugin && fs.existsSync(opencodePlugin) ? opencodePlugin : undefined; - opencodeTmpFile = prepareOpencodeHttpRewrite(resolveOpencodeConfigFile(process.env), origin, routes.httpRewrites, routes.httpsRewrites, opencodePluginPath); + const ocDirMode = opencodePluginPath !== undefined && opencodeMajorVersion(resolveClientCommand("opencode", process.env).command) >= 2; + opencodeTmpFile = prepareOpencodeHttpRewrite(resolveOpencodeConfigFile(process.env), origin, routes.httpRewrites, routes.httpsRewrites, opencodePluginPath, ocDirMode); if (opencodeTmpFile) env.OPENCODE_CONFIG = opencodeTmpFile; } else if (base === "hermes") { // #535 phase 2: file-free — no overlay HERMES_HOME, no config.yaml diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index c08e337846..66dbccb375 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -28,6 +28,8 @@ import { buildClaudeEnv, buildCodexArgs, prepareOpencodeHttpRewrite, + opencodeMajorVersion, + parseOpencodeMajor, stripInheritedProxy, resolvePiHome, resolveOmpHome, @@ -1792,6 +1794,7 @@ test("prepareOpencodeHttpRewrite: writes rewritten copy, original untouched", () const rewritten = JSON.parse(fs.readFileSync(tmpFile, "utf8")); assert.equal(rewritten.provider["zhipuai-lb"].options.baseURL, "http://127.0.0.1:8787/bili/http://127.0.0.1:18081/v1"); assert.deepEqual(rewritten.plugin, ["opencode-acp@latest"]); + assert.deepEqual(rewritten.compaction, { auto: false }); assert.equal(fs.readFileSync(cfgFile, "utf8"), original); fs.rmSync(path.dirname(tmpFile), { recursive: true, force: true }); assert.equal(prepareOpencodeHttpRewrite(cfgFile, "http://127.0.0.1:8787", [], []), undefined); @@ -1805,12 +1808,54 @@ test("prepareOpencodeHttpRewrite: writes rewritten copy, original untouched", () assert.ok(missingCfg); const fromEmpty = JSON.parse(fs.readFileSync(missingCfg, "utf8")); assert.deepEqual(fromEmpty.plugin, ["/opt/bili/dist/agent/opencode.js"]); + assert.deepEqual(fromEmpty.compaction, { auto: false }); fs.rmSync(path.dirname(missingCfg), { recursive: true, force: true }); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); +test("prepareOpencodeHttpRewrite: pluginDirMode wraps the plugin in an index.js shim dir", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "oc-rw2-")); + try { + const cfgFile = path.join(dir, "opencode.json"); + fs.writeFileSync(cfgFile, JSON.stringify({ provider: {} })); + const tmpFile = prepareOpencodeHttpRewrite(cfgFile, "http://127.0.0.1:8787", [], [], "/opt/bili/dist/agent/opencode.js", true); + assert.ok(tmpFile); + const injected = JSON.parse(fs.readFileSync(tmpFile, "utf8")); + const entry = injected.plugin[injected.plugin.length - 1]; + assert.ok(entry !== "/opt/bili/dist/agent/opencode.js"); + assert.ok(fs.statSync(entry).isDirectory()); + const shim = fs.readFileSync(path.join(entry, "index.js"), "utf8"); + assert.match(shim, /export \{ default \} from "\/opt\/bili\/dist\/agent\/opencode\.js";/); + assert.deepEqual(injected.compaction, { auto: false }); + fs.rmSync(path.dirname(tmpFile), { recursive: true, force: true }); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("opencodeMajorVersion: parses --version output, defaults to 1 on failure", () => { + assert.equal(parseOpencodeMajor("opencode v2.0.3"), 2); + assert.equal(parseOpencodeMajor("1.14.46"), 1); + assert.equal(parseOpencodeMajor("no digits here"), undefined); + assert.equal(opencodeMajorVersion("/nonexistent/bili-test-bin"), 1); + if (process.platform === "win32") return; // shebang fakes are not executable on Windows + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "oc-ver-")); + try { + const mk = (name: string, out: string): string => { + const f = path.join(dir, name); + fs.writeFileSync(f, `#!/bin/sh\necho "${out}"\n`); + fs.chmodSync(f, 0o755); + return f; + }; + assert.equal(opencodeMajorVersion(mk("oc-v2.sh", "opencode v2.0.3")), 2); + assert.equal(opencodeMajorVersion(mk("oc-v1.sh", "1.14.46")), 1); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + test("resolveOpencodeConfigFile: OPENCODE_CONFIG wins, XDG fallback", () => { assert.equal(resolveOpencodeConfigFile({ OPENCODE_CONFIG: "/tmp/x.json" }), "/tmp/x.json"); const p = resolveOpencodeConfigFile({ XDG_CONFIG_HOME: "/tmp/xdg" }); diff --git a/tests/opencode-v2.test.ts b/tests/opencode-v2.test.ts new file mode 100644 index 0000000000..3023b6327a --- /dev/null +++ b/tests/opencode-v2.test.ts @@ -0,0 +1,345 @@ +import assert from "node:assert"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import biliOpencodePlugin from "../src/agent/opencode.ts"; +import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../src/compress-tool.ts"; +import { fetchManifest } from "../src/agent/shared.ts"; + +const EXPECTED_TOOLS = [...ACP_TOOLS_OPENAI.map((t) => t.function.name), ABSORB_TOOL_OPENAI.function.name]; + +function startFakeProxyV2(): Promise<{ origin: string; toolCalls: Array<{ conversationId?: string; tool?: string; args?: unknown }>; compacts: string[]; close: () => Promise }> { + const toolCalls: Array<{ conversationId?: string; tool?: string; args?: unknown }> = []; + const compacts: string[] = []; + const server = http.createServer((req, res) => { + const url = req.url ?? ""; + if (url === "/__bili/plugin/tool" && req.method === "POST") { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const data = JSON.parse(body) as { conversationId?: string; tool?: string; args?: unknown }; + toolCalls.push(data); + res.writeHead(200, { "content-type": "application/json" }); + if (data.tool === "acp_status") { + res.end(JSON.stringify({ ok: true, result: "STATUS-RESULT" })); + } else { + res.end(JSON.stringify({ ok: false, error: `boom-${data.tool}` })); + } + }); + return; + } + if (url === "/__bili/plugin/compact" && req.method === "POST") { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const data = JSON.parse(body) as { conversationId?: string }; + compacts.push(data.conversationId ?? ""); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + }); + return; + } + res.writeHead(404); + res.end("{}"); + }); + server.listen(0, "127.0.0.1"); + return once(server, "listening").then(() => ({ + origin: `http://127.0.0.1:${(server.address() as { port: number }).port}`, + toolCalls, + compacts, + close: () => new Promise((resolve) => server.close(() => resolve())), + })); +} + +interface FakeAddedTool { + name: string; + description?: string; + input: unknown; + options?: Record; + execute: (input: Record, ctx: { sessionID: string }) => Promise<{ content: string }>; +} + +function makeFakeCtx() { + const eventQueue: Array<{ type?: unknown; data?: Record }> = []; + let wake: (() => void) | undefined; + let closed = false; + let signal: AbortSignal | undefined; + const addedTools: FakeAddedTool[] = []; + let modelRequestCb: ((e: Record) => void | Promise) | undefined; + const disposed: number[] = []; + + const ctx = { + session: { + hook: async (name: string, cb: (e: Record) => void | Promise) => { + assert.equal(name, "http.request"); + modelRequestCb = cb; + return { dispose: () => { disposed.push(1); } }; + }, + }, + tool: { + transform: async (cb: (editor: { add: (t: FakeAddedTool) => void }) => void) => { + cb({ add: (t) => addedTools.push(t) }); + return { dispose: () => { disposed.push(2); } }; + }, + }, + event: { + subscribe: (opts?: { signal?: AbortSignal }) => { + signal = opts?.signal; + signal?.addEventListener("abort", () => { closed = true; wake?.(); }, { once: true }); + return { + [Symbol.asyncIterator]: (): AsyncIterator<{ type?: unknown; data?: Record }> => ({ + next: async () => { + while (eventQueue.length === 0 && !closed && !signal?.aborted) { + await new Promise((r) => (wake = r)); + } + wake = undefined; + const v = eventQueue.shift(); + return v === undefined ? { done: true as const, value: undefined } : { done: false as const, value: v }; + }, + }), + }; + }, + }, + catalog: { + model: { + list: async () => ({ data: [{ providerID: "qwen", id: "m1", limit: { context: 262144 } }] }), + }, + }, + }; + + return { + ctx, + fireModelRequest: async (opts: { sessionID?: unknown; baseURL?: unknown; model?: unknown }) => { + const store: Record = {}; + await modelRequestCb!({ + sessionID: opts.sessionID, + model: opts.model, + request: { + url: opts.baseURL, + headers: { set: (k: string, v: string) => { store[k] = v; } }, + }, + }); + return { headers: store }; + }, + pushEvent: (evt: { type?: unknown; data?: Record }) => { eventQueue.push(evt); wake?.(); }, + get addedTools() { return addedTools; }, + get disposed() { return disposed; }, + }; +} + +async function until(cond: () => boolean, timeoutMs = 3000): Promise { + const deadline = Date.now() + timeoutMs; + while (!cond()) { + if (Date.now() > deadline) throw new Error("condition not met in time"); + await new Promise((r) => setTimeout(r, 10)); + } +} + +function withEnv(vars: Record, fn: () => void | 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; + } + return Promise.resolve(fn()).finally(() => { + for (const [k, v] of saved) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); +} + +test("object export: .id/.setup for V2 and .server for V1 >= 1.18.29", () => { + assert.equal(typeof biliOpencodePlugin, "object"); + assert.ok(biliOpencodePlugin !== null); + assert.equal(biliOpencodePlugin.id, "billion-context-opencode"); + assert.equal(typeof biliOpencodePlugin.setup, "function"); + assert.equal(typeof biliOpencodePlugin.server, "function"); +}); + +test("v2 setup: registers the bundled bili tools synchronously with exact schema parity", 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 { + assert.deepEqual(fake.addedTools.map((t) => t.name), EXPECTED_TOOLS); + for (const t of fake.addedTools) { + assert.equal(t.options?.codemode, false); + assert.equal(t.options?.permission, "allow"); + } + const compressSrc = [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI].find((t) => t.function.name === "compress")!; + assert.deepEqual(fake.addedTools.find((t) => t.name === "compress")!.input, compressSrc.function.parameters); + } finally { + cleanup(); + } + }); +}); + +test("v2 setup: inert without proxy detection (tools present but no headers, no forwarding)", 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 res = await fake.fireModelRequest({ sessionID: "s1", baseURL: "http://upstream.example/v1" }); + assert.deepEqual(res.headers, {}); + const out = await fake.addedTools[0].execute({}, { sessionID: "s1" }); + assert.match(out.content, /no proxy detected/); + } finally { + cleanup(); + assert.ok(fake.disposed.includes(1) && fake.disposed.includes(2)); + } + }); +}); + +test("v2 setup: inert-safe when the host exposes none of the V2 seams", async () => { + const cleanup = await biliOpencodePlugin.setup({} as never); + assert.equal(typeof cleanup, "function"); + cleanup(); +}); + +test("v2 setup: kill switch stays inert even with /bili/ URL + proxy env", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: proxy.origin, BILLION_CONTEXT_PLUGIN: "0" }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const res = await fake.fireModelRequest({ sessionID: "s1", baseURL: `${proxy.origin}/bili/http://upstream.example/v1` }); + assert.deepEqual(res.headers, {}); + const out = await fake.addedTools.find((t) => t.name === "compress")!.execute({ content: [] }, { sessionID: "s1" }); + assert.match(out.content, /disabled \(BILLION_CONTEXT_PLUGIN=0\)/); + assert.equal(proxy.toolCalls.length, 0); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: activates from /bili/ baseURL on round 1, stamps headers, forwards tools", async () => { + const proxy = await startFakeProxyV2(); + const fake = makeFakeCtx(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => { + const cleanup = await biliOpencodePlugin.setup(fake.ctx as never); + try { + const r1 = await fake.fireModelRequest({ + sessionID: "ses_v2_1", + baseURL: `${proxy.origin}/bili/http://upstream.example/v1`, + model: { providerID: "qwen", id: "m1" }, + }); + assert.equal(r1.headers["x-bili-plugin"], "opencode"); + assert.equal(r1.headers["x-bili-plugin-conversation"], "ses_v2_1"); + // window header needs the async catalog fetch — lands from round 2 + const r2 = await fake.fireModelRequest({ + sessionID: "ses_v2_1", + baseURL: `${proxy.origin}/bili/http://upstream.example/v1`, + model: { providerID: "qwen", id: "m1" }, + }); + await until(() => r2.headers["x-bili-plugin-context-window"] === "262144"); + + const out = await fake.addedTools.find((t) => t.name === "compress")!.execute({ content: [] }, { sessionID: "ses_v2_1" }); + assert.match(out.content, /boom-compress/); + 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" }); + assert.equal(statusOut.content, "STATUS-RESULT"); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: env-based activation without /bili/ URL", 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 res = await fake.fireModelRequest({ sessionID: "s2", baseURL: "http://real-upstream.example/v1" }); + assert.equal(res.headers["x-bili-plugin"], "opencode"); + assert.equal(res.headers["x-bili-plugin-conversation"], "s2"); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: session.compaction.ended reports boundary to proxy archive", 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 { + await fake.fireModelRequest({ sessionID: "s3", baseURL: "http://u.example/v1", headers: {} }); + fake.pushEvent({ type: "session.compaction.ended", data: { sessionID: "s3", reason: "manual" } }); + fake.pushEvent({ type: "session.created", data: { info: { id: "nope" } } }); + await until(() => proxy.compacts.includes("s3")); + assert.deepEqual(proxy.compacts, ["s3"]); + } finally { + cleanup(); + } + }); + } finally { + await proxy.close(); + } +}); + +test("v2 setup: cleanup aborts event subscription and disposes registrations", 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); + await fake.fireModelRequest({ sessionID: "s4", baseURL: "http://u.example/v1", headers: {} }); + cleanup(); + assert.ok(fake.disposed.includes(1), "model.request hook registration disposed"); + assert.ok(fake.disposed.includes(2), "tool transform registration disposed"); + }); + } finally { + await proxy.close(); + } +}); + +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"] } }, + { name: "acp_status", description: "Context status", parameters: { type: "object", properties: {} } }, + ]; + const server = http.createServer((req, res) => { + if ((req.url ?? "") === "/__bili/plugin/manifest" && req.method === "GET") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, protocolVersion: 1, version: "99.0.0-test", tools: { openai: MANIFEST_OPENAI } })); + 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}`; + try { + const tools = await fetchManifest(origin, "openai"); + assert.deepEqual(tools.map((t) => t.name), ["compress", "acp_status"]); + assert.deepEqual(tools[0].inputSchema, MANIFEST_OPENAI[0].parameters); + const anthropic = await fetchManifest(origin, "anthropic").catch((e) => e); + assert.ok(anthropic instanceof Error, "fake serves no anthropic tools — format must not cross-contaminate"); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +});