Skip to content

feat: OpenCode 2.0 support — V2 launcher mode + pure-proxy validation (#735) - #754

Merged
ranxianglei merged 8 commits into
masterfrom
2026-09-13_opencode-v2
Sep 15, 2026
Merged

ranxianglei merged 8 commits into
masterfrom
2026-09-13_opencode-v2

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Sep 13, 2026 •

Copy link
Copy Markdown
Owner

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 (provider singular, options.baseURL → /bili/, npm: provider package, agent.title.model, compaction:{auto:false}).

  • Key finding: OC2's @ai-sdk/openai-compatible provider requires a non-empty apiKey even for local endpoints — documented in README.
  • V1 1.14.46 tolerates the unknown top-level compaction key → 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

File Change
src/agent/opencode.ts V2 branch (setup(ctx)) appended to the existing file; default export becomes the dual-shape object { id, setup, server } (V1 server() untouched, ≥1.18.29 dual-entry support)
src/agent/shared.ts fetchManifest gains an optional "openai" format mapping; new reportCompactionBoundary POST helper (/__bili/plugin/compact)
src/launcher.ts prepareOpencodeHttpRewrite merges compaction: { ...existing, auto: false } into the generated temp config
tests/opencode-v2.test.ts New: 9 cases (dual export shape, schema parity vs bundled schemas, inert-without-proxy, kill switch, activation + header timing + tool forwarding, env 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; new OpenCode 2.0 section (pure-proxy config incl. apiKey requirement, launcher behavior, /acp limitation)
devlog/2026-09-13_opencode-v2/ DESIGN / REQ / WORKLOG

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):

  1. On the next-17444 pre-release, session.hook("model.request") registers but never fires. The working interception point there 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 (probe-verified end-to-end). The published @opencode/plugin@2.0.2 typings advertise model.request; runtime probes won there. Not universal: per an external report in this thread (repro script provided), on 2.0.1 stable model.request, http.request, and context hooks all fire and reach the wire; and two adjacent npm dev builds probed during review expose different surfaces entirely (one loads plugins via V1 server() only; the other exposes setup() but has no ctx.session/ctx.tool at 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.
  2. No 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.
  3. No observed 2.x build exposes an add-command entry point (list/get/update/remove on next-17444; list/transform/reload reported on 2.0.1) — plugins cannot add commands, hence no /acp under 2.0; the native acp_status tool 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)
  • Review probes (2026-09-14, this thread): published artifact 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-config compaction.auto:false merge 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 confirmed
  • Review fixes on branch: 80c089c kill switch now gates tool forwarding + compaction reporting too (was header-stamping only); 80f631c docs scoped to specific builds (this description + README + comment block) and a new test pinning setup({}) inert-safety
  • Live ①: real OC2 binary, pure-proxy round-trip OK (see above)
  • 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
  • Codex e2e suite not run in this sandbox (no local upstream reachable); changes do not touch the request pipeline (server.ts / src/loop / adapters / preflight) — covered by the OC2 live e2e instead

Stable 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; bins opencode/opencode2). The earlier "private binary" caveat no longer applies — the validation below ran against the stable v2.0.3 release plus the real bili opencode launcher.

Launcher fix — plugin entries must be directories (bd20f51). OC2 only loads plugin directories whose index.js is the entrypoint (a bare file path logs configured plugin path must be a directory and never loads). src/launcher.ts now probes the client major version (opencodeMajorVersion()) and, for ≥2, writes the bundled plugin into a temp shim dir (<tmp>/plugin/index.js re-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 native acp_status; bili log shows [plugin] tool acp_status executed via plugin, zero [acp-loop] lines, context panel reports host=billion-context. No wire-level tool injection.

Also probed on 2.0.3: both model.request and http.request hooks fire per request; ctx.command.transform(editor.add) works — the /acp command limitation of the earlier pre-release is gone (TUI invoke: Tab+Enter, since /name<Enter> only completes; opencode run dispatches 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 transient logger-rotate failure was the sandbox disk hitting 100% — ENOSPC; passes with free space; unrelated to this diff).

…#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).
@github-actions

github-actions Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-13_opencode-v2 (5d93155)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-754

Each push to this PR publishes a new version under the pr-754 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr754.tgz
npm install -g package

This comment is automatically updated on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始 review PR #754(2026-09-13_opencode-v2)。流程:查重 → 拉分支审 diff → typecheck/test/build → 小问题直接在分支上修。有结论会回本帖。

…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.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[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 bb8e35d):

  • npm run typecheck — clean
  • npm test — 1451/1453 pass, 0 fail, 2 skipped (matches your claim)
  • npm run build — clean (dist/agent/opencode.js 1.05 MB, one artifact serving both generations)

Contract cross-checks (all pass):

  • header strings in src/agent/opencode.ts match the constants in src/plugin.ts (x-bili-plugin / -conversation / -context-window)
  • /__bili/plugin/{manifest,status,tool,compact} endpoints exist in server.ts; handlePluginCompact accepts exactly {conversationId}, so the compaction-boundary POST shape is right
  • V2's bundled tool schemas are the same consts the proxy injects on the wire (ACP_TOOLS_OPENAI + absorb) → the "parity cannot drift" claim holds structurally
  • launcher always sets BILLION_CONTEXT_PROXY for opencode → plugin activation path is sound

Fixed directly on the branch (commit 80c089c, pushed to 2026-09-13_opencode-v2):

  • Kill-switch gap: BILLION_CONTEXT_PLUGIN=0 only gated header stamping in httpRequestHook. Native tool execute() still forwarded to the proxy (proxyBaseFromEnv() is always populated — the launcher sets it), and session.compaction.ended reporting ignored the flag entirely. That's a half-disabled state inconsistent with pi/omp's detectProxyBase semantics (kill switch ⇒ fully inert). Now all three sites go through one pluginDisabled() helper; the kill-switch test was also weakened before (proxy env unset) — it now sets the proxy origin and asserts zero tool forwarding. Post-fix: typecheck clean, 9/9 opencode-v2 tests, full suite green again.

Non-blocking notes:

  1. The dual-shape default export breaks OpenCode hosts < 1.18.29 (they invoke the default export as a function; object form is only understood ≥1.18.29 per your probe). It's documented in README/devlog and OC2 is the target, so acceptable — but if older hosts matter later, a launcher-side version check wrapping the export in a function shim would close it without touching the plugin file.
  2. fetchManifest("openai") has no runtime caller today (V2 registers from bundled schemas by design) — test-exercised only. Fine as an escape hatch, just noting.

Codex e2e wasn't runnable here (no upstream in sandbox); changes don't touch the request pipeline (server.ts / src/loop / adapters / preflight), and the OC2 live e2e you ran covers the wire path.

中文摘要: diff 干净、本地复验全绿(typecheck/build/test 均通过);修复了一个小 bug——BILLION_CONTEXT_PLUGIN=0 开关原来只挡了请求头注入,原生工具转发和压缩边界上报仍会打到代理(与 pi/omp 的完全失活语义不一致),已直接在 PR 分支补上(80c089c)并强化了测试,可以合并。

@jensenojs

Copy link
Copy Markdown
Contributor

蹲蹲

@ranxianglei

Copy link
Copy Markdown
Owner Author

再触发一个 📦 Built Package Artifact
现在缺少实际验证,最好你能下载opencode2 tmux里面验证一下 配置本地qwen代理即可

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 已用发布的 artifact 在 tmux 里做了实机验证(本地 qwen 上游,全程隔离环境,不碰真实配置)。结论先说:artifact 可用,pure-proxy 通过;但公开渠道目前拿不到真正的 OC2,V2 原生路径无法在公开构建上复验。

📦 Artifact 状态(不用重新触发)

  • pr-754 npm tag 已是 0.1.109-pr.754.597,由 80c089c(含 review 时我补的 kill-switch 修复)的 CI run 成功发布(run 34763951598)。floor 1 的 e-work 镜像评论还显示旧 sha 3e81d74,是镜像未同步,不是构建缺失。
  • 我直接 npm install billion-context@pr-754 装了这个 tarball 做验证(并确认其 dist/agent/opencode.js 内含修复标记)。要强制新 run 需要推新 commit,空 commit 我就不推了。

验证环境

  • OC2 二进制:公开渠道没有 2.x —— anomalyco/opencode 的 releases 只到 v1.18.30。装的是 npm dev channel 预发布构建 opencode-ai@0.0.0-dev-202609132139(昨天发布,最接近 2.0 的公开产物)。
  • 上游:本地 qwen,经 bili 代理;tmux 会话内运行,HOME 全量隔离(fakehome),真实 opencode.json / bili 配置零改动。

结果 ① Pure-proxy 模式 ✅
OC2 dev 构建 + README 文档同款配置(provider 单数、options.baseURL → /bili/<上游>,非空 dummy apiKey,无插件)完成完整往返:模型精确返回 PURE-OK;bili 日志 processTurn / [acp-usage] / forward POST …/chat/completions 全部正常。auth、请求解析、SSE stream rewrite 在这条新构建上复验通过。

结果 ② Launcher 管线 ✅(附关键发现 ⚠️)
bili opencode run "…调用 acp_status…" 全链路跑通:代理自启 → 日志 HTTP /bili/ rewrites: 1 → 模型成功拿到 acp_status 面板(host=billion-context 0.1.109-pr.754.597)→ 回复 LAUNCHER-DONE。运行中实时抓到了 artifact 生成的临时配置,逐项确认:

  • baseURL 已改写为 <proxy>/bili/<上游> 包装形式;
  • plugin 数组注入的正是 artifact 内的 dist/agent/opencode.js;
  • 基础配置里没有 compaction 键时,launcher 仍合入了 compaction: { auto: false }(PR 声称的行为,实机证实)。

⚠️ 关键发现:这个公开 dev 构建还不是 V2 代宿主。 用双入口探针插件(setup/server 各写一行标记到文件)实测:只有 server() 被调用(V1 dual-shape 兼容入口),setup() 从未触发。因此 x-bili-plugin 头没有打上——bili 日志零 [plugin] 行、出现 1 行 [acp-loop](工具走代理侧执行后重放)。也就是说该构建上优雅降级为 proxy 模式,功能完整可用,但不是 PR 描述的 V2 插件模式(native tools + 零 wire 注入)。真正的 V2 路径(session.hook("http.request")、同步注册 native tools)只能在你手里的私有 OC2 pre-release 构建上验证——公开的 npm/GitHub 渠道截至今天还没有带 V2 插件 API 的 CLI。

建议:PR 维持可合并状态;等 OC2 官方放出(或再拿到私有构建)后,用同一套 tmux 脚本补一轮 Live ② 回归(acp_status 走 [plugin] tool … executed via plugin、零 [acp-loop])即可收口。

@jensenojs

jensenojs commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

PR 描述里的 V2 runtime facts 是对 next-17444 pre-release 测的,2.0.1 正式版上四条都对不上:

  • model.request 会触发,不是"注册得上但从不触发"。
  • ctx.tool 有 reload。
  • ctx.command 有 transform,所以 2.0 下不是不可能有 /acp。
  • 能改上下文的不止 http.request:context(messages/system/tools 可变)和 model.request(baseURL/headers 可变)都生效,改动也确实到了线上。

最后一条动到本 PR 的取舍:薄壳的前提是"V2 下插件改不了上下文,所以压缩权得交给代理",这在 2.0.1 上不成立。选纯协议客户端还可以有别的原因(kernel 版本漂移、单一压缩权威),但那跟这四条无关。

响应侧也测了:http.response 拿到的 response 尚未被消费(bodyUsed=false),可以读完整段 SSE、改写、赋回,客户端认改写后的内容。对一次原本回答 pong 的请求,把每个 delta 的 content 追加 <X>,客户端显示 p<X>ong<X>。也就是说"改上行 + 改下行"的闭环在进程内成立,不存在只能做一半的技术障碍。

复现脚本,四组证据各一次运行,测完自动删除插件文件,只往 /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 resp

2.0.1 上跑出来是这样(模型 baidu/DeepSeek-V4-Flash):

facts → model   pong
        tool    reload,transform,hook
        command list,transform,reload
        model.request kind=primary
        http.request  http://localhost:8899/v1/chat/completions

ctx   → model   ZQXMUT             (facts 那轮是 pong)
        context       改了最后一条 user 消息

url   → model   ConnectionRefused
        http.request  http://127.0.0.1:9/v1/chat/completions

resp  → model   p<X>ong<X>
        response      改了 2 个 delta

pre-release 和正式版有差异很正常,问题只在 PR 描述和 README 把 pre-release 行为当成了 V2 的一般行为。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,这个"pre-release 观察被写成一般行为"的问题必须拿真二进制逐条验。先报状态:我这边沙箱磁盘一度写满(ENOSPC,所有命令和回帖都失败),已清掉自己的旧验证产物恢复 ~1.7GB,验证正在进行,结果稍后补。先说进展和一个需要你确认的关键疑点。

验证进展

  • 公开渠道目前找不到"2.0.1":npm opencode-ai latest=1.18.30、无任何 2.x 版本(也查了 opencode / opencode-cli / @opencode/cli 等候选包名);anomalyco/opencode 的 GitHub releases 只到 v1.18.30(9/9)。
  • 但 dev tag 一夜之间前移了:昨天我装的是 0.0.0-dev-202609132139(实测:双入口探针插件只走 V1 server(),setup() 从不触发——所以我当时结论是"公开构建还不是 V2 宿主")。今早已更新到 0.0.0-dev-202609140717。如果你测的产物就是这个当前 dev 构建(或更晚的内部构建),相邻两个 dev 构建之间 API 面就变了——这同时能解释你的四条观测和作者 next-17444 上的观测。
  • 待办(进行中):装当前 dev 构建 → 原样跑你的 v2probe.sh facts/ctx/url 三种模式(本地 qwen 上游)→ 再补一轮 Live ② 回归(bili opencode run,期望 [plugin] tool … executed via plugin + 零 [acp-loop])。

两个问题

  1. 你测的"2.0.1 正式版"具体是什么来源?npm dev channel 的哪个版本号,还是内部/私有构建?给我一个可获取的标识,我对着同一产物复现,避免再次出现"不同构建对不上"的情况。
  2. 第 3 条有个细节:你的探针输出 ctx.command keys = list,transform,reload —— 仍然没有新增命令的入口(transform 只能改已有命令的话,"V2 下无 /acp"的结论其实还站得住,需要修的只是 API 形状的描述)。我跑探针时会加一个尝试新增命令的模式来确认。

对设计前提的立场(先表态,验证后落地)
同意你的分层判断:若 context 改写在正式版上生效,"V2 插件改不了上下文"就不能再作为薄壳的设计前提,README/PR 描述里的论证应改为基于"消除 kernel 版本漂移 + 单一压缩权威"——这两条理由独立于那四条事实,依然成立。验证通过后我直接在 PR 分支上修 README(OpenCode 2.0 一节)、PR 描述和 devlog DESIGN 里的 pre-release 观察注记。功能面:现有实现用 http.request 打头,按你的实测该 hook 在 2.0.1 上仍触发且改动到达线上,所以代码路径本身应该不受影响——这点我会用 Live ② 回归确认而不是推断。

…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.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 独立验证完成(能拿到的公开产物都拿了),文档已按你的意见修正并推到分支。结论:你的核心论点被独立证据支持——2.x 插件 API 面在构建之间持续漂移,pre-release 观察不能写成一般行为;但"2.0.1"这个具体产物在所有公开渠道都找不到,精确复现仍差一个来源标识。

独立复现结果(本地 qwen 上游,隔离环境,探针逻辑与你的 v2probe.sh 一致,另加了命令新增探测模式):

构建 插件入口 ctx.session ctx.tool hook 触发 bili 结果
next-17444 pre-release(作者实测) setup() 有 无 reload 仅 http.request 真插件模式
npm dev …202609132139 仅 V1 server() n/a n/a n/a 优雅降级 proxy 模式(零 [plugin],一 [acp-loop])
npm dev …202609140717(今晨发布) setup() 整个不存在(ctx = options,agent,aisdk,catalog,command,integration,plugin,reference,skill) 不存在 无法注册 同上,干净降级

要点:① 两个相邻 dev 构建互相矛盾、且都与 next-17444 不同——API 面确实在逐日变动,你指出的"把 pre-release 写成一般行为"是实锤问题;② 第 3 条细节:所有可观测构建(含你报的 2.0.1 list,transform,reload)都没有新增命令的入口,所以"V2 下无 /acp"的结论仍然成立,需要修的只是 API 形状描述;③ 降级路径实机确认:seam 缺失时代理侧 wire 注入兜底,功能完整不炸。

已落地(commit 80f631c,已推):

  • README OpenCode 2.0 一节:事实改为按构建标注 + "dev 相邻构建互斥"注记 + 优雅降级说明;薄壳论证改基为"单一压缩权威 + 消除 kernel 版本漂移",不再依赖"插件改不了上下文";
  • src/agent/opencode.ts 头部注释块重写为 per-build 事实(含你报告的 2.0.1 行为,标注为外部报告待精确复现);
  • 代码零改动——所有注册本来就是可选链(inert-safe),新加一个测试钉住 setup({}) 在无任何 seam 的宿主上干净返回;
  • devlog DESIGN.md 追加 2026-09-14 addendum(上表 + 出处);
  • PR 描述已同步更新(version-scoped facts + 设计理由 + review probes 验证行)。
  • 全绿:typecheck、npm test 1452/1454(0 fail)、build。

仍待你补充:那个"2.0.1 正式版"二进制的获取来源(npm 哪个 tag/版本号,或内部构建渠道)?npm opencode-ai 无任何 2.x 版本、GitHub releases 只到 v1.18.30,我目前只能对 dev channel 构建复现。拿到同一产物后我会原样跑你的三模式探针收口。

中文摘要:独立探针证实 2.x 插件 API 在相邻构建间持续漂移(你的核心论点成立),已把 README/PR 描述/源码注释中的 runtime facts 全部改为按构建标注、设计理由改基于单一压缩权威与 kernel 漂移消除(80f631c,代码本身因可选链无需改动并补了 inert-safety 测试),全量验证绿;"2.0.1"具体产物公开渠道不可得,待提供来源后做最终精确复现。

@jensenojs

Copy link
Copy Markdown
Contributor

先答来源,再改一条你的要点②。

来源:@opencode/cli@2.0.1

$ npm view @opencode/cli versions
... 2.0.0, 2.0.1, 2.0.2, 2.0.3

$ npm view @opencode/cli dist-tags
{ beta: '0.0.0-beta-19507', dev: '0.0.0-dev-19595', latest: '2.0.3', reserved: '0.0.0-reserved' }

$ npm view @opencode/cli@2.0.1 bin
{ opencode: 'bin/opencode.exe', opencode2: 'bin/opencode.exe' }

opencode-ai(latest 1.18.30)、opencode(404)、@opencode-ai/cli(1.18.x)都是 1.x 线,2.x 换了包名,所以"公开渠道找不到"是包名搜错了。

装完的目录形状和 bin 字段对得上:

~/.local/opt/opencode-v2/bin/opencode    # 182MB Mach-O
~/.local/opt/opencode-v2/bin/opencode2   # #!/bin/sh  exec "$(dirname "$0")/opencode" "$@"

二进制内嵌常量也一致:var Cn="2.0.1", la="latest", mf="cli"。

一条保留:逐字节比对我没做成。真实的 182MB 二进制在平台包 @opencode/cli-darwin-arm64@2.0.1 里(@opencode/cli 本身只有 7KB + postinstall),npmjs 拉大文件中途停了,npmmirror 没同步那个平台包(NoSuchKey)。所以"本机文件 == 该包文件"目前靠 bin 映射和版本常量印证,没有 hash 坐实,别当已验证。

要点② 要改:ctx.command 的 key 不是 editor

list,transform,reload 是命名空间的 key。transform 回调收到的才是 editor,它只有一个 key:

editor keys = add

类型定义(@opencode/plugin 的 command.d.ts):

export interface CommandEditor { add(definition: CommandDefinition): void }
export interface CommandDomain extends Pick<CommandApi, "list"> {
  readonly transform: Transform<CommandEditor>
  readonly reload: () => Promise<void>
}

2.0.1 上新建命令是通的:

editor.add() ok
list count = 9, list has acp-probe = true
list tail = ...,zotero:zotero_synthesize_my_notes,acp-probe

ctx.command.list() 里出现了新加的 acp-probe,两个不同上下文(9 条、3 条)下都出现。

我没证明的是"能被调用":opencode run "/acp-probe" 没走到 execute,那条消息被当成普通 prompt 交给了模型(模型自己去 ls 找命令文件了)。所以能说的是"有新增入口、命令进了注册表",不能说"TUI 里能点起来"。调用链这条留给你收口。

据此,"V2 下无 /acp"在 2.0.1 上要撤回——需要修的确实是描述,但方向跟你的相反:入口存在。

复现脚本:

#!/usr/bin/env bash
# 用法: MODEL=<模型> ./cmdprobe.sh
set -uo pipefail

MODEL="${MODEL:?}"
PLUGIN="$HOME/.config/opencode/plugins/zz-cmdprobe.js"
LOG=/tmp/cmdprobe.log
OUT=/tmp/cmdprobe.out
trap 'rm -f "$PLUGIN"' EXIT
rm -f "$LOG" "$OUT"

cat > "$PLUGIN" <<'JS'
import { appendFileSync } from "node:fs"
const LOG = "/tmp/cmdprobe.log"
const log = (m) => { try { appendFileSync(LOG, m + "\n") } catch {} }

const setup = async (ctx) => {
  await ctx.command.transform((editor) => {
    log("editor keys = " + Object.keys(editor || {}).join(","))
    try {
      editor.add({
        name: "acp-probe",
        description: "probe command",
        execute: async (input) => {
          log("COMMAND EXECUTED, input keys = " + Object.keys(input || {}).join(","))
        },
      })
      log("editor.add() ok")
    } catch (e) {
      log("editor.add() THREW: " + e?.message)
    }
  })
  log("transform registered")
  try { await ctx.command.reload() } catch (e) { log("reload FAILED: " + e?.message) }
  const res = await ctx.command.list()
  const names = (res?.data ?? res ?? []).map((c) => c?.name)
  log("list count = " + names.length)
  log("list has acp-probe = " + names.includes("acp-probe"))
  log("list tail = " + names.slice(-5).join(","))
  return () => {}
}
export default { id: "zz-cmdprobe", setup }
JS

opencode --version 2>&1 | tail -1
timeout 180 opencode run -m "$MODEL" "/acp-probe" >"$OUT" 2>&1
echo "model   $(grep -v WARN "$OUT" | head -3 | tr '\n' ' ')"
awk '!seen[$0]++' "$LOG"

2.0.1 上跑出来(baidu/DeepSeek-V4-Flash):

opencode v2.0.1
transform registered
editor keys = add
editor.add() ok
list count = 9
list has acp-probe = true
list tail = zotero:zotero_expand_from_paper,...,zotero:zotero_synthesize_my_notes,acp-probe

@ranxianglei

Copy link
Copy Markdown
Owner Author

补充,我已经在沙盒安装了opencodev2

@jensenojs

Copy link
Copy Markdown
Contributor

感谢, 主要是没有上下文压缩的插件用opencode太难受了, vibe 重写了一下dcp感觉不是很好弄. 所以多调戏了一下你的qwen3.8-27b

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 不客气——没有压缩的 opencode 长会话确实难用,这正是 bili 要解决的。qwen3.8-27b 皮实,随便调戏(它今天被拿来做了一整天 acp_status 回归,状态良好)。

正在继续收口:刚在真实的 @opencode/cli 2.0.3 上验证了 V2 插件模式端到端可用(native 工具走 [plugin] 通道、零 wire 注入),同时发现并修复了 launcher 的一个真 bug——2.x 拒绝配置文件里的文件路径插件项,bili opencode 之前会静默降级到 proxy 模式。修完会连测试和文档一起推上来,稍等。

…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).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 @ranxianglei 收到——沙盒里的 opencodev2 已经验证完毕,而且它把之前"私有二进制"的缺口补上了:/usr/bin/opencode2 = npm 包 @opencode/cli v2.0.3(bin 名 opencode/opencode2)。也就是说 2.x 正式线已经在 npm 公开了(2.0.0–2.0.3,latest=2.0.3),不再是 pre-release。我在 tmux + 本地 qwen 代理上跑完了真实 bili opencode launcher 全流程 E2E,过程中发现并修掉了一个真 bug:

发现的 bug:launcher 传的插件路径形态 OC2 不认(已修,bd20f51)

OC2 只加载目录形式的插件条目(目录内 index.js 为入口);直接传裸文件路径会报 configured plugin path must be a directory 且静默不加载 → 插件模式退化成 proxy mode(零 [plugin] 行)。修复:src/launcher.ts 新增 opencodeMajorVersion()(对客户端跑一次 --version 探测,major ≥ 2 才启用),dirMode 下把 dist 插件包进临时 shim 目录(<tmp>/plugin/index.js re-export dist 文件)再传入;V1 启动路径字节级不变。+2 单测(fake sh 脚本测解析与 fallback)。

v2.0.3 上的完整验证结果

  • 真插件模式端到端确认:temp config 捕获到 shim-dir 插件条目 + /bili/ baseURL 包装 + compaction.auto:false;模型调用了原生 acp_status;bili 日志 [plugin] tool acp_status executed via plugin,零 [acp-loop] 行,上下文面板显示 host=billion-context —— 无 wire 级工具注入
  • 两个运维坑(都踩过,记下来):① OC2 的 managed service 跨调用存活且缓存旧配置——首次运行被残留 service 静默绕过代理,opencode service stop 后恢复;② bili auto-update 会覆盖全局安装(忘了 ACP_AUTO_UPDATE=0 时 0.1.109-pr.754.597 被换成 registry 版,导致一轮测试作废重装)
  • 额外探针:model.request 和 http.request hook 在 2.0.3 上都按请求触发;ctx.command.transform(editor.add) 可用——pre-release 时代的 /acp 命令限制解除了(TUI 调用链是 Tab+Enter:/name<Enter> 只做补全;opencode run 完全不 dispatch slash 命令)。README 与注释块的 caveats 已同步更新

分支状态

已 rebase 到你的 master merge(2869130,含 v0.1.110、kimi/jcode launcher 等):typecheck clean、build clean、测试 1500 pass / 0 fail / 2 skipped(中途一次 logger-rotate 失败是沙盒磁盘被打满 100% 的 ENOSPC,腾出空间后立即通过,与本 diff 无关)。PR 描述已追加 "Stable OpenCode 2.x line — validated" 一节(origin、wrapper 修复、2.0.3 实测、rebase 后套件状态)。

环境已清理(无 tmux 残留、无本会话进程;8787 端口的 bili 属于 #735 会话,未动)。

中文摘要:找到了 2.x 正式线的来源(npm @opencode/cli v2.0.3),在稳定版上实测发现并修复了 launcher 插件路径必须为目录的真 bug(bd20f51,V1 不受影响),确认真插件模式端到端可用(/acp 限制同时解除),PR 描述与文档已更新,可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

ci失败

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 失败已定位——Windows 专属的测试 flake,与本 PR 的改动无关,我已触发失败 job 重跑,结果出来再跟进。

失败详情(run bd20f51):5 个 job 里只有 test (windows-latest, 24) 和 test (windows-latest, 22) 挂,ubuntu 22/24 全绿。两个 Windows job 挂的都是同一个断言:

✖ discoverMitmDomains: codebuddy settings.json + models.json hosts discovered
  AssertionError: codebuddy host present:    ← domains 列表为空
  at tests\discover.test.ts (codebuddy 断言行)

判定为 flake 的证据链:

  1. diff 无关:本 PR(含我 review 补的两个 commit)只动 src/launcher.ts / src/agent/opencode.ts / opencode 相关测试 / README;tests/discover.test.ts 和 src/discover.ts、src/client-config.ts 零改动,且 discover.test.ts 根本不 import launcher(agent 插件模块)。
  2. 同一套代码 22 分钟前刚绿过:上一个 commit 2869130(你的 master merge,与 bd20f51 只差我的 launcher wrapper commit)在 14:56 的完整 CI 全部通过,包括这两个 Windows job。更早的 80c089c / 80f631c / 6f867a9 也全绿。
  3. 该测试自 feat: 新增 codebuddy 客户端支持(bili codebuddy) #640(codebuddy 支持)起就在 Windows CI 上反复跑过并一直通过。

机制推测:readJsonObject(src/client-config.ts:352)对读文件错误是静默吞掉返回 null 的——Windows runner 上新写入 Temp 目录的文件被 Defender 瞬时占用/扫描时 readFileSync 抛错,两个 codebuddy fixture 文件都没读到 → domains = [] → 断言挂。这解释了为什么是"整个列表为空"而不是少一个 host,也没有任何 crash。

已执行 rerun-failed-jobs,等结果。如果是 flake(预期),按小问题处理:本 thread 报告即可,不动代码;如果重跑还挂同样的断言,我再深挖(拉 win22 日志对比、考虑给测试加诊断)。

中文摘要:CI 失败是 Windows 上 codebuddy 发现测试的一次性 flake(临时文件读取被瞬时干扰且错误被静默吞掉),与本 PR diff 无关——同代码 22 分钟前刚全绿;已触发重跑,待确认。

ework-agent added 2 commits September 14, 2026 23:47
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.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 更正上一条的"flake"判断 + 已修复,等新 CI

rerun 之后发现我之前的结论只对了一半:两个 Windows job 失败里有一个是我自己新加的测试(bd20f51),不是与 diff 无关的瞬时故障。抱歉误导。

根因:新增的 opencodeMajorVersion 单测写了一个 #!/bin/sh 假二进制再按路径 exec —— Windows 上 execFileSync 无法直接执行 shebang 脚本(第一次尝试改成 .cmd 也不行:Node 不带 shell:true 同样 spawn 不了 .bat/.cmd)。探测抛错 → 回退 major=1 → 1 !== 2。两次 CI(run 34861266253 / 34864477230)都是它挂的,ubuntu 全绿。

修法(commit 5d93155,已推):把解析逻辑抽成纯函数 parseOpencodeMajor(output)(src/launcher.ts),所有平台直接测纯函数(含 v2/v1/无版本号三例);spawn 端到端断言保留在 POSIX(那里 shebang 假二进制真实可执行);fallback 路径(/nonexistent → 1)全平台保留。生产代码行为不变,只是解析从内联正则变成可测试的导出函数。

本地验证:typecheck 干净、全套 1501 pass / 0 fail / 2 skipped、build 干净。

codebuddy discover 那个失败(attempt-1 出现过的 domains=[]):后续两轮均未复现(每次只有一个 ✖,且最新日志里只有我的测试)→ 按一次性瞬态处理,不另开 issue;若再出现我会深挖。

新 CI 跑完我再报结果。
中文摘要:Windows CI 挂的是我新加的版本探测单测(shebang 脚本在 Windows 不可执行),已抽纯函数修复并推送,等 CI 转绿后确认合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 已转绿 ✅ — run 34865278406(HEAD 5d93155)全部通过

  • test (ubuntu-latest, 22/24) ✅、test (windows-latest, 22/24) ✅、version-guard ✅;同提交的 e2e-fake-codex 与 PR Build Artifact 工作流也全绿。
  • codebuddy discover 的瞬态失败三轮未再复现,维持"一次性"结论,不另开 issue。

本 PR 当前在我接手后新增的三个 commit(叠在你的 master 合并之上):

  1. bd20f51 — launcher shim-dir 修复(OC2 stable 2.x 要求 plugin 条目为目录)+ opencodeMajorVersion 探测 + 单测
  2. b2e0929 — 跨平台假二进制的第一个尝试(.cmd,验证了 Node 无 shell:true 也 spawn 不了 .bat/.cmd,已被取代)
  3. 5d93155 — 抽出纯函数 parseOpencodeMajor,解析逻辑全平台直接测,spawn e2e 断言限 POSIX;生产行为不变

本地终态:typecheck 干净 / 1501 pass · 0 fail · 2 skipped / build 干净。分支可合并(合并操作留给你)。若你想让 diff 更干净,squash-merge 时可以把 2+3 并成一个 fix commit —— 由你决定。

中文摘要:Windows CI 失败根因是我新增版本探测单测在 Windows 上无法执行 shebang 假二进制,已通过抽取纯函数 parseOpencodeMajor 修复(CI 全绿),PR 可以合并。

@ranxianglei
ranxianglei merged commit d974149 into master Sep 15, 2026
7 checks passed
This was referenced Sep 15, 2026
antclt pushed a commit to antclt/billion-context that referenced this pull request Sep 18, 2026
… — 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.
@ranxianglei
ranxianglei deleted the 2026-09-13_opencode-v2 branch October 15, 2026 05:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: OpenCode V2 支持:验证纯代理模式 + 新增 V2 启动器模式(opencode-acp#395 移交)

2 participants