Repository navigation
feat: OpenCode 2.0 support — V2 launcher mode + pure-proxy validation (#735) - #754
Conversation
…#735) - src/agent/opencode.ts: V2 branch (setup(ctx)) coexisting with V1 server() in one dual-shape default export { id, setup, server } (>=1.18.29); native tools compress/decompress/search_context/acp_status(+absorb) registered synchronously from bundled schemas (same source as proxy manifest, src/compress-tool.ts); header injection via probed working hook session.hook("http.request") (model.request registers but never fires in OC2 runtime); compaction-boundary reporting via session.compaction.ended -> /__bili/plugin/compact - src/agent/shared.ts: fetchManifest gains "openai" format mapping; new reportCompactionBoundary helper - src/launcher.ts: prepareOpencodeHttpRewrite merges compaction.auto=false into temp opencode config (safe on both generations) - tests/opencode-v2.test.ts: 9 new cases (dual export shape, schema parity, inert-without-proxy, kill switch, activation+header timing+tool forwarding, env activation, compaction boundary, cleanup dispose, manifest mapping) - tests/launcher.test.ts: +2 assertions (compaction.auto === false) - README.md: OpenCode 2.0 section (pure-proxy config incl. apiKey requirement, launcher behavior, /acp limitation) - devlog/2026-09-13_opencode-v2/: DESIGN/REQ/WORKLOG Verified live against real OpenCode 2.0 pre-release binary: pure-proxy round-trip OK; plugin mode confirmed ([plugin] tool executed via plugin, zero [acp-loop] wire injection). typecheck clean, build clean, tests 1243/1244 (sole failure pre-existing sandbox codex-path issue).
📦 Built Package ArtifactBranch: Option A — Install from npm PR tag (recommended)npm install -g billion-context@pr-754Each push to this PR publishes a new version under the Option B — Download artifact
tar xzf billion-context-pr754.tgz
npm install -g packageThis comment is automatically updated on each push. |
…forwarding + compaction report The V2 kill switch only gated header stamping in httpRequestHook; native tool execute() still forwarded to the proxy via proxyBaseFromEnv() (the launcher always sets BILLION_CONTEXT_PROXY) and session.compaction.ended reporting ignored it too — a half-disabled state inconsistent with pi/omp detectProxyBase semantics (fully inert). Gate all three sites with one pluginDisabled() helper; strengthen the kill-switch test to set the proxy env and assert zero tool forwarding.
[bot] 🏷 PR #754 review — OpenCode 2.0 support Duplicate screening: implements #735 (the 14-floor discussion; V2 launcher mode per floor 3, not the deprecated embedded-kernel design). No other open PR touches OpenCode V2 → not a duplicate. Diff cleanliness ✅ single commit, 9 files, +755/−5 — every line serves the stated purpose; no lockfile churn, no version bump, no unrelated files. Verification reproduced locally (rebased state on
Contract cross-checks (all pass):
Fixed directly on the branch (commit
Non-blocking notes:
Codex e2e wasn't runnable here (no upstream in sandbox); changes don't touch the request pipeline ( 中文摘要: diff 干净、本地复验全绿(typecheck/build/test 均通过);修复了一个小 bug—— |
|
蹲蹲 |
|
再触发一个 📦 Built Package Artifact |
[bot] 🏷 已用发布的 artifact 在 tmux 里做了实机验证(本地 qwen 上游,全程隔离环境,不碰真实配置)。结论先说:artifact 可用,pure-proxy 通过;但公开渠道目前拿不到真正的 OC2,V2 原生路径无法在公开构建上复验。 📦 Artifact 状态(不用重新触发)
验证环境
结果 ① Pure-proxy 模式 ✅ 结果 ② Launcher 管线 ✅(附关键发现
建议:PR 维持可合并状态;等 OC2 官方放出(或再拿到私有构建)后,用同一套 tmux 脚本补一轮 Live ② 回归(acp_status 走 |
|
PR 描述里的 V2 runtime facts 是对 next-17444 pre-release 测的,2.0.1 正式版上四条都对不上:
最后一条动到本 PR 的取舍:薄壳的前提是"V2 下插件改不了上下文,所以压缩权得交给代理",这在 2.0.1 上不成立。选纯协议客户端还可以有别的原因(kernel 版本漂移、单一压缩权威),但那跟这四条无关。 响应侧也测了: 复现脚本,四组证据各一次运行,测完自动删除插件文件,只往 /tmp 写日志: #!/usr/bin/env bash
# 用法: MODEL=<模型> ./v2probe.sh facts|ctx|url|resp
set -uo pipefail
MODE="${1:-facts}"
MODEL="${MODEL:?}"
PLUGIN="$HOME/.config/opencode/plugins/zz-v2probe.js"
LOG=/tmp/v2probe.log
OUT=/tmp/v2probe.out
trap 'rm -f "$PLUGIN"' EXIT
rm -f "$LOG" "$OUT"
# opencode 插件读不到宿主进程的 env,模式和日志路径直接写进插件源码
cat > "$PLUGIN" <<JS
import { appendFileSync } from "node:fs"
const LOG = "$LOG"
const MODE = "$MODE"
const log = (m) => { try { appendFileSync(LOG, m + "\n") } catch {} }
function patchSse(body) {
let deltas = 0
const lines = body.split("\n").map((line) => {
if (!line.startsWith("data: ")) return line
const payload = line.slice(6)
if (payload.trim() === "[DONE]") return line
let json
try { json = JSON.parse(payload) } catch { return line }
const c = json?.choices?.[0]?.delta?.content
if (typeof c === "string" && c.length > 0) {
json.choices[0].delta.content = c + "<X>"
deltas++
return "data: " + JSON.stringify(json)
}
return line
})
return { body: lines.join("\n"), deltas }
}
const setup = async (ctx) => {
log("tool " + Object.keys(ctx.tool || {}).join(","))
log("command " + Object.keys(ctx.command || {}).join(","))
await ctx.session.hook("model.request", (e) => {
log("model.request kind=" + e.kind)
if (MODE === "url" && e.kind === "primary") e.baseURL = "http://127.0.0.1:9/v1"
})
await ctx.session.hook("http.request", (e) => {
log("http.request " + e.request?.url)
})
await ctx.session.hook("context", (e) => {
if (MODE !== "ctx") return
const m = (e.messages || []).at(-1)
if (m && m.role === "user") {
m.content = [{ type: "text", text: "Reply with exactly: ZQXMUT" }]
log("context 改了最后一条 user 消息")
}
})
await ctx.session.hook("http.response", async (e) => {
if (MODE !== "resp" || !e.response || e.kind !== "primary") return
const r = e.response
const { body, deltas } = patchSse(await r.text())
e.response = new Response(body, { status: r.status, statusText: r.statusText, headers: r.headers })
log("response 改了 " + deltas + " 个 delta")
})
return () => {}
}
export default { id: "zz-v2probe", setup }
JS
opencode --version 2>&1 | tail -1
timeout 180 opencode run -m "$MODEL" "reply with the single word: pong" >"$OUT" 2>&1
echo "model $(tail -1 "$OUT")"
awk '!seen[$0]++' "$LOG"chmod +x v2probe.sh
MODEL=<模型> ./v2probe.sh facts
MODEL=<模型> ./v2probe.sh ctx
MODEL=<模型> ./v2probe.sh url
MODEL=<模型> ./v2probe.sh resp2.0.1 上跑出来是这样(模型 pre-release 和正式版有差异很正常,问题只在 PR 描述和 README 把 pre-release 行为当成了 V2 的一般行为。 |
[bot] 🏷 收到,这个"pre-release 观察被写成一般行为"的问题必须拿真二进制逐条验。先报状态:我这边沙箱磁盘一度写满(ENOSPC,所有命令和回帖都失败),已清掉自己的旧验证产物恢复 ~1.7GB,验证正在进行,结果稍后补。先说进展和一个需要你确认的关键疑点。 验证进展
两个问题
对设计前提的立场(先表态,验证后落地) |
…review External report (@jensenojs) showed all four next-17444 pre-release observations invert on 2.0.1 stable (model.request fires, ctx.tool.reload exists, context mutation reaches the wire). Independent probes of two adjacent npm dev builds confirmed the 2.x plugin surface changes between builds (one loads V1-only, the other exposes setup() but no ctx.session/ctx.tool). Docs now state facts per-build, the thin-shell rationale is re-based on single-authority + kernel-drift elimination instead of 'plugins cannot mutate context', and a new test pins setup({}) inert-safety on seam-less hosts. No code behavior change.
[bot] 🏷 独立验证完成(能拿到的公开产物都拿了),文档已按你的意见修正并推到分支。结论:你的核心论点被独立证据支持——2.x 插件 API 面在构建之间持续漂移,pre-release 观察不能写成一般行为;但"2.0.1"这个具体产物在所有公开渠道都找不到,精确复现仍差一个来源标识。 独立复现结果(本地 qwen 上游,隔离环境,探针逻辑与你的
要点:① 两个相邻 dev 构建互相矛盾、且都与 next-17444 不同——API 面确实在逐日变动,你指出的"把 pre-release 写成一般行为"是实锤问题;② 第 3 条细节:所有可观测构建(含你报的 2.0.1 已落地(commit
仍待你补充:那个"2.0.1 正式版"二进制的获取来源(npm 哪个 tag/版本号,或内部构建渠道)?npm 中文摘要:独立探针证实 2.x 插件 API 在相邻构建间持续漂移(你的核心论点成立),已把 README/PR 描述/源码注释中的 runtime facts 全部改为按构建标注、设计理由改基于单一压缩权威与 kernel 漂移消除( |
|
先答来源,再改一条你的要点②。 来源:
|
|
补充,我已经在沙盒安装了opencodev2 |
|
感谢, 主要是没有上下文压缩的插件用opencode太难受了, vibe 重写了一下dcp感觉不是很好弄. 所以多调戏了一下你的qwen3.8-27b |
[bot] 🏷 不客气——没有压缩的 opencode 长会话确实难用,这正是 bili 要解决的。qwen3.8-27b 皮实,随便调戏(它今天被拿来做了一整天 acp_status 回归,状态良好)。 正在继续收口:刚在真实的 |
…ir for OpenCode 2.x OC 2.0.x (@opencode/cli) rejects bare file paths in the config plugin array (WARN 'configured plugin path must be a directory'; a directory entry loads its index.js), so bili opencode silently degraded every 2.x launch to proxy mode. New opencodeMajorVersion --version probe (cached, failure -> 1) selects pluginDirMode in prepareOpencodeHttpRewrite, which injects a temp wrapper dir re-exporting dist/agent/opencode.js; 1.x keeps the bare file path. Verified end-to-end on @opencode/cli 2.0.3: [plugin] tool acp_status executed via plugin, zero [acp-loop]. Docs: README + agent comment block + devlog now carry the confirmed 2.0.x facts (both hooks fire, ctx.tool.reload exists, editor.add works with Tab+Enter TUI invocation, run mode dispatches no slash commands).
[bot] 🏷 @ranxianglei 收到——沙盒里的 opencodev2 已经验证完毕,而且它把之前"私有二进制"的缺口补上了: 发现的 bug:launcher 传的插件路径形态 OC2 不认(已修,
|
|
ci失败 |
[bot] 🏷 CI 失败已定位——Windows 专属的测试 flake,与本 PR 的改动无关,我已触发失败 job 重跑,结果出来再跟进。 失败详情(run 判定为 flake 的证据链:
机制推测: 已执行 中文摘要:CI 失败是 Windows 上 codebuddy 发现测试的一次性 flake(临时文件读取被瞬时干扰且错误被静默吞掉),与本 PR diff 无关——同代码 22 分钟前刚全绿;已触发重跑,待确认。 |
opencodeMajorVersion test wrote a #!/bin/sh script and exec'd it by path — Windows cannot exec shebang scripts, so execFileSync threw and the probe fell back to major 1 (CI run 34861266253, both windows-latest jobs). On win32 the fake is now a .cmd batch file, which Node spawns natively via cmd.exe; posix keeps the sh script.
…indows CI runs 34861266253 and 34864477230 both failed on windows-latest in the opencodeMajorVersion unit test: Node cannot exec a shebang .sh script by path on Windows, and .bat/.cmd files also cannot be spawned without shell:true, so every fake-binary approach threw and the probe fell back to major 1. Extract the pure parser as parseOpencodeMajor (tested directly on all platforms) and keep the spawn-based end-to-end assertions POSIX-only, where shebang fakes are genuinely executable.
[bot] 🏷 更正上一条的"flake"判断 + 已修复,等新 CI rerun 之后发现我之前的结论只对了一半:两个 Windows job 失败里有一个是我自己新加的测试(bd20f51),不是与 diff 无关的瞬时故障。抱歉误导。 根因:新增的 修法(commit 本地验证:typecheck 干净、全套 1501 pass / 0 fail / 2 skipped、build 干净。 codebuddy discover 那个失败(attempt-1 出现过的 新 CI 跑完我再报结果。 |
[bot] 🏷 CI 已转绿 ✅ — run 34865278406(HEAD
本 PR 当前在我接手后新增的三个 commit(叠在你的 master 合并之上):
本地终态:typecheck 干净 / 1501 pass · 0 fail · 2 skipped / build 干净。分支可合并(合并操作留给你)。若你想让 diff 更干净,squash-merge 时可以把 2+3 并成一个 fix commit —— 由你决定。 中文摘要:Windows CI 失败根因是我新增版本探测单测在 Windows 上无法执行 shebang 假二进制,已通过抽取纯函数 |
… — self-spawning proxy in the plugin Follows the pi-native pattern (ranxianglei#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 <proxy>/bili/<url> by replacing the request reference (Request.url is readonly, ranxianglei#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 ranxianglei#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 <configDir>/plugins/billion-context/index.js re-exporting dist/agent/opencode-native.js (OpenCode 2.x requires directory-form plugin entries, ranxianglei#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.
What
Fixes #735 (from opencode-acp#395). Two parts:
① Pure-proxy mode on OpenCode 2.0 — validated live ✅
Real OC2 pre-release binary against a local sglang upstream through the proxy: auth / request parsing / SSE stream rewrite round-trip all pass with V1-shaped config (
providersingular,options.baseURL→/bili/,npm:provider package,agent.title.model,compaction:{auto:false}).@ai-sdk/openai-compatibleprovider requires a non-emptyapiKeyeven for local endpoints — documented in README.compactionkey → launcher merges it unconditionally without version probing.② New OpenCode V2 launcher mode — implemented in the current protocol-client pattern (zero acp-kernel in the plugin; proxy is the single compression authority), per the discussion in #735 floor 3 (not the deprecated embedded-kernel design of billion-context-opencode).
Changes
src/agent/opencode.tssetup(ctx)) appended to the existing file; default export becomes the dual-shape object{ id, setup, server }(V1server()untouched, ≥1.18.29 dual-entry support)src/agent/shared.tsfetchManifestgains an optional"openai"format mapping; newreportCompactionBoundaryPOST helper (/__bili/plugin/compact)src/launcher.tsprepareOpencodeHttpRewritemergescompaction: { ...existing, auto: false }into the generated temp configtests/opencode-v2.test.tstests/launcher.test.tscompaction.auto === falseREADME.md/acplimitation)devlog/2026-09-13_opencode-v2/V2 runtime facts — version-specific (the 2.x plugin surface moves between builds)
Per-build observations; do not generalize beyond the build named (see also the DESIGN.md addendum):
session.hook("model.request")registers but never fires. The working interception point there issession.hook("http.request")— fires per outgoing provider request with a standard fetchRequestate.request; mutatinge.request.headersreaches the wire (probe-verified end-to-end). The published@opencode/plugin@2.0.2typings advertisemodel.request; runtime probes won there. Not universal: per an external report in this thread (repro script provided), on 2.0.1 stablemodel.request,http.request, andcontexthooks all fire and reach the wire; and two adjacent npmdevbuilds probed during review expose different surfaces entirely (one loads plugins via V1server()only; the other exposessetup()but has noctx.session/ctx.toolat all). All registrations use optional chaining, so the plugin is inert-safe on any surface; when no seam fires, sessions transparently run in plain proxy mode instead of breaking.ctx.tool.reload()on next-17444 (reported to exist on 2.0.1 stable). Tools are therefore registered synchronously from bundled schemas — same source as the proxy's OpenAI tool list (src/compress-tool.ts), so parity cannot drift regardless of which surface the host exposes./acpunder 2.0; the nativeacp_statustool is the equivalent.Design rationale: the protocol-client pattern rests on single compression authority + kernel-version-drift elimination — not on the plugin API being unable to mutate context (that capability varies by build).
Native tools: compress / decompress / search_context / acp_status (+ absorb), executed host-side via POST to the bili plugin tool endpoint. Compaction boundary reporting via
session.compaction.ended→/__bili/plugin/compact(#421 path).Verification
npm run typecheck— clean;npm run build— clean;npm test— 1452/1454 pass, 0 fail (2 skipped), rebased onto latest master (bb8e35d) with synced deps (acp-kernel 0.0.69)billion-context@pr-754+ two adjacent npm dev builds (0.0.0-dev-202609132139,0.0.0-dev-202609140717) — pure-proxy round-trip OK on both; launcher pipeline OK (temp-configcompaction.auto:falsemerge captured live); both degrade cleanly to proxy mode (zero[plugin], one[acp-loop]) since neither build fires the V2 seams — the graceful fallback is now empirically confirmed80c089ckill switch now gates tool forwarding + compaction reporting too (was header-stamping only);80f631cdocs scoped to specific builds (this description + README + comment block) and a new test pinningsetup({})inert-safetydist/agent/opencode.jsplugin — model called the nativeacp_statustool; bili log shows[plugin] tool acp_status executed via pluginand zero[acp-loop]lines → true plugin mode, no wire-level tool injectionserver.ts/src/loop/ adapters / preflight) — covered by the OC2 live e2e insteadStable OpenCode 2.x line — validated (2026-09-14)
Origin found. The 2.x generation ships as npm package
@opencode/cli(2.0.0–2.0.3,latest= 2.0.3; binsopencode/opencode2). The earlier "private binary" caveat no longer applies — the validation below ran against the stable v2.0.3 release plus the realbili opencodelauncher.Launcher fix — plugin entries must be directories (
bd20f51). OC2 only loads plugin directories whoseindex.jsis the entrypoint (a bare file path logsconfigured plugin path must be a directoryand never loads).src/launcher.tsnow probes the client major version (opencodeMajorVersion()) and, for ≥2, writes the bundled plugin into a temp shim dir (<tmp>/plugin/index.jsre-exporting the dist file) and passes that dir; V1 launches are byte-identical (no dirMode). +2 unit tests.Live ② on stable v2.0.3 — true plugin mode confirmed end-to-end. Real launcher run (tmux, local qwen upstream): temp config carries the shim-dir plugin entry +
/bili/baseURL wrap +compaction.auto:false; the model called the nativeacp_status; bili log shows[plugin] tool acp_status executed via plugin, zero[acp-loop]lines, context panel reportshost=billion-context. No wire-level tool injection.Also probed on 2.0.3: both
model.requestandhttp.requesthooks fire per request;ctx.command.transform(editor.add)works — the/acpcommand limitation of the earlier pre-release is gone (TUI invoke: Tab+Enter, since/name<Enter>only completes;opencode rundispatches no slash commands at all). README / comment-block caveats updated accordingly.Suite after rebasing onto the master merge (
2869130): typecheck clean, build clean, 1500 pass / 0 fail / 2 skipped (one transientlogger-rotatefailure was the sandbox disk hitting 100% — ENOSPC; passes with free space; unrelated to this diff).