Skip to content
67 changes: 65 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <client>` (launcher, preferred) or `/bili/` prefix |

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
133 changes: 133 additions & 0 deletions devlog/2026-09-13_opencode-v2/DESIGN.md
Original file line number Diff line number Diff line change
@@ -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: <sessionID>`,
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).
52 changes: 52 additions & 0 deletions devlog/2026-09-13_opencode-v2/REQ.md
Original file line number Diff line number Diff line change
@@ -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).
48 changes: 48 additions & 0 deletions devlog/2026-09-13_opencode-v2/WORKLOG.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading