Repository navigation
feat: opencode 2.x no-launcher npm-plugin deployment - #810
ranxianglei wants to merge 4 commits into
Conversation
Add a second OpenCode plugin entry so `plugins: ["billion-context"]` works without `bili opencode`. The npm-plugin entry owns its proxy: on first need it spawns a loopback bili and rewrites provider requests to /bili/<url>. - src/agent/opencode-v2.ts: extract the shared V2 plugin factory (createOpencodeV2Setup) out of opencode.ts; both entries call it so their wire behavior cannot drift (#809 dual-file concern). - src/agent/opencode-local.ts: new no-launcher entry (id billion-context-opencode-local): options.port -> default 127.0.0.1:18787, manifest+identity probe, spawn `node <pkgroot>/dist/index.js start --port N --host 127.0.0.1 --no-auto-update` on miss, idempotent /bili/ rewrite, inert when BILLION_CONTEXT_PROXY is set or the kill switch is on. - src/agent/shared.ts: add probeProxy (identity + protocol read, soft-fail). - package.json: explicit-enum exports { ".", "./server" }. - tsup.config.ts: build the opencode-local entry. - tests/opencode-local.test.ts: rewrite idempotency/https/special-chars, options fallback+warn, env/kill-switch stand-down, adoption-without-spawn. Pre-flight: typecheck clean; node --test 1618 pass / 0 fail / 2 skip; tsup build emits dist/agent/opencode-local.js. Live-spawn convergence and url-mutation-reaches-the-wire are deferred to the e2e smoke matrix (PR body). Fixes #809
📦 Built Package ArtifactBranch: Option A — Install from npm PR tag (recommended)npm install -g billion-context@pr-810Each push to this PR publishes a new version under the Option B — Download artifact
tar xzf billion-context-pr810.tgz
npm install -g packageInstall instructions are refreshed on each push. |
[bot] 🏷 Review of PR #810 done. Verdict: well-built, clean diff, green pre-flight & CI — but one blocking resolution/doc bug to fix, plus the live-E2E you already flagged, before merge. Verified locally (reproduced):
🔴 Blocking finding — the documented plugin string resolves to the wrong module (evidence-backed). Deployed as
This is more fundamental than the two items you listed under "E2E still needed" (url-mutation reaches wire / spawn convergence): if the entry doesn't load, neither is even reached. Please confirm against real OpenCode 2.x before merge:
Recommendation: hold merge. Run your suggested smoke test with the corrected string 中文摘要: 代码质量高、diff 干净(相对真正基线 |
…untime Two real-host regressions confirmed by @jensenojs (OpenCode v2.0.3, PR #810): 1. httpRequestHook wrote e.request.url = next. The seam hands a WHATWG Request whose .url is a readonly getter — assignment throws in strict/ESM and fails every session through the hook. The event's request REFERENCE is swappable, so replace it wholesale: e.request = new Request(proxyUrl, e.request) carries method/headers/body over. Wrapped the hook so any error degrades to passthrough — the plugin must never take down host sessions. 2. spawn(process.execPath, [dist/index.js, ...]) assumed execPath is Node. Under a native OpenCode binary (Mach-O arm64 CLI) it is the host executable, so spawning it just prints CLI help and exits -> poll timeout -> silent inert. findNodeRuntime() resolves a real Node (execPath basename check -> PATH walk -> BILLION_CONTEXT_NODE override), else fails loud-and-inert. Tests now build real WHATWG Requests (plain-object mocks masked the readonly constraint) + regression test for the reference swap + findNodeRuntime branches. typecheck clean; 1623 pass / 0 fail / 2 skip; build emits dist/agent/opencode-local.js. Fixes #809
Per @jensenojs: make sure the in-host spawn pitfall from #809 doesn't recur across #513's sibling native hosts. Move findNodeRuntime (+ NodeLookupOpts) from opencode-local.ts into agent/shared.ts so every future in-host proxy spawn (omp/dsh native #520/#521, and re-checking pi-native #706) reuses one canonical, tested helper instead of re-deriving the process.execPath assumption. opencode-local now imports it from shared.js; tests import from there too. typecheck clean; 1623 pass / 0 fail / 2 skip; build emits.
Addresses jensenojs's independent worktree audit of the opencode npm-plugin (#809). All four findings verified against code before fixing; three are real defects now fixed, one (bare-name plugin load) is a deployment-model issue tracked separately. - F2: wire findNodeRuntime() into ensureProxyRunning (src/launcher.ts) so an in-host caller (pi-native #706) no longer inherits the wrong-executable spawn. Reorder findNodeRuntime so a running Node always wins over the BILLION_CONTEXT_NODE override — keeps the CLI/daemon launcher path byte-identical regardless of env; the override becomes a pure native-host fallback. - F3: observe the async spawn 'error' event in src/agent/opencode-local.ts so a bad runtime degrades to inert instead of throwing an unhandled 'error' that takes down the host process (reproduced as exit 1). Add DI (spawn/packageRoot) so this path is unit-testable, mirroring launcher's deps.spawnImpl convention. - F4: isProtocolSupported now fails closed on undefined/unknown versions instead of treating a missing protocolVersion as supported, matching its own docstring. Adds 5 regression tests (findNodeRuntime precedence, isProtocolSupported x3, async-spawn-error crash prevention). typecheck clean, 1628 pass / 0 fail / 2 skip (pre-existing), tsup build emits dist/agent/opencode-local.js.
… — 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.
…untime Two real-host regressions confirmed by @jensenojs (OpenCode v2.0.3, PR ranxianglei#810): 1. httpRequestHook wrote e.request.url = next. The seam hands a WHATWG Request whose .url is a readonly getter — assignment throws in strict/ESM and fails every session through the hook. The event's request REFERENCE is swappable, so replace it wholesale: e.request = new Request(proxyUrl, e.request) carries method/headers/body over. Wrapped the hook so any error degrades to passthrough — the plugin must never take down host sessions. 2. spawn(process.execPath, [dist/index.js, ...]) assumed execPath is Node. Under a native OpenCode binary (Mach-O arm64 CLI) it is the host executable, so spawning it just prints CLI help and exits -> poll timeout -> silent inert. findNodeRuntime() resolves a real Node (execPath basename check -> PATH walk -> BILLION_CONTEXT_NODE override), else fails loud-and-inert. Tests now build real WHATWG Requests (plain-object mocks masked the readonly constraint) + regression test for the reference swap + findNodeRuntime branches. typecheck clean; 1623 pass / 0 fail / 2 skip; build emits dist/agent/opencode-local.js. Fixes ranxianglei#809
What
Adds a second OpenCode plugin entry so the no-launcher deployment works:
No
bili opencodelauncher, no manually started proxy, no env wiring — the npm plugin owns its own loopback proxy and starts it lazily on first need. This is the carrier-A design converged in #809.How it works (local mode)
options.port→ defaulthttp://127.0.0.1:18787.<base>/__bili/plugin/manifestand asserts the identity field (proxy === "billion-context") before adopting. A foreign service squatting the port is refused loudly, never adopted.node <pkgroot>/dist/index.js start --port <port> --host 127.0.0.1 --no-auto-update(detached, loopback) and polls until the manifest answers.--no-auto-updateis mandatory: the auto-update git-checkout guard (auto-update overwrites tracked files when run from a git source checkout (findInstallDir resolves to repo root) #580) does not cover an npm-cache install, which strips.git./bili/<url>(idempotent — a second fire leaves it alone); the proxy resolves upstream from the embedded URL. All ACP headers (x-bili-plugin,-conversation,-context-window) stamp as usual.BILLION_CONTEXT_PROXYis already set (a launcher-managed proxy exists) or theBILLION_CONTEXT_PLUGIN=0kill switch is on, the plugin registers nothing and spawns nothing.Tool registration is gated on protocol support (manifest
protocolVersion∈ supported set, currently{1}); on mismatch the plugin activates headers-only and warns rather than registering stale tools.Changes
src/agent/opencode-v2.tscreateOpencodeV2Setup(config)extracted fromopencode.ts; both entries call it so their wire behavior cannot driftsrc/agent/opencode-local.tsid billion-context-opencode-local): options→base, probe+identity, lazy spawn, idempotent/bili/rewrite, stand-down gatessrc/agent/shared.tsprobeProxy()— manifest fetch + identity assert + protocol read, soft-fail (never throws)src/agent/opencode.tsserverpath byte-identical; V2 section removedpackage.jsonexports { ".", "./server" }(version untouched)tsup.config.tsopencode-localentrytests/opencode-local.test.tsDesign decisions (converged in #809)
distisn't re-exposed as public API. Cross-repo bare-subpath pre-flight: GitHub code search forbillion-context/distand"billion-context/returned zero hits.protocolVersionand the version diff stays informational.--no-auto-updateCLI flag (cmdline-visible, zero new env namespace).Pre-flight
npm run typecheck— cleannpm test— 1618 pass / 0 fail / 2 skip (pre-existing skips)npm run build— emitsdist/agent/opencode-local.jsdefault.id = billion-context-opencode-local,setupis a function,resolvePackageRoot()resolves to an existingdist/index.js, spawn args correctexportstargets verified present on diskE2E verification still needed (owner, real upstream)
Two behaviors are covered by unit tests of the pure logic but are not yet exercised against a live client/upstream:
e.request.url; the comment atopencode.tsproves headers reach the wire, but the url mutation is a typed writable property whose wire effect is unverified here. Fallback if it doesn't land: mutate themodel.requestbaseURLinstead (deferred, not v1).server.ts); verified by inspection, not by a live double-spawn.Suggested smoke: point a real OpenCode (2.x) at a Responses-compatible upstream via
options.port, confirm first-request rewrite + a compress round-trip, plus a kill-switch /BILLION_CONTEXT_PROXYstand-down check.Out of scope (Phase 2)
options.enabledtoggle (theBILLION_CONTEXT_PLUGIN=0kill switch already covers emergency stop)Fixes #809