Skip to content

feat: opencode 2.x no-launcher npm-plugin deployment - #810

Closed
ranxianglei wants to merge 4 commits into
masterfrom
2026-09-15_opencode-npm-plugin
Closed

ranxianglei wants to merge 4 commits into
masterfrom
2026-09-15_opencode-npm-plugin

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Adds a second OpenCode plugin entry so the no-launcher deployment works:

// ~/.config/opencode/opencode.json
{ "plugin": ["billion-context"] }

No bili opencode launcher, 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)

  1. On setup the plugin resolves its upstream base from options.port → default http://127.0.0.1:18787.
  2. It probes <base>/__bili/plugin/manifest and asserts the identity field (proxy === "billion-context") before adopting. A foreign service squatting the port is refused loudly, never adopted.
  3. On connection refusal it spawns 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-update is 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.
  4. The first provider request rewrites the URL to /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.
  5. Stand-down (inert): if BILLION_CONTEXT_PROXY is already set (a launcher-managed proxy exists) or the BILLION_CONTEXT_PLUGIN=0 kill 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

File Change
src/agent/opencode-v2.ts new — shared V2 factory createOpencodeV2Setup(config) extracted from opencode.ts; both entries call it so their wire behavior cannot drift
src/agent/opencode-local.ts new — no-launcher entry (id billion-context-opencode-local): options→base, probe+identity, lazy spawn, idempotent /bili/ rewrite, stand-down gates
src/agent/shared.ts probeProxy() — manifest fetch + identity assert + protocol read, soft-fail (never throws)
src/agent/opencode.ts refactored to consume the factory; V1 server path byte-identical; V2 section removed
package.json explicit-enum exports { ".", "./server" } (version untouched)
tsup.config.ts builds the opencode-local entry
tests/opencode-local.test.ts new — rewrite idempotency/https/special-chars, options fallback+warn, env/kill-switch stand-down, adoption-without-spawn

Design decisions (converged in #809)

  • Carrier A: billion-context itself ships the plugin. Explicit-enum exports (not wildcard) so dist isn't re-exposed as public API. Cross-repo bare-subpath pre-flight: GitHub code search for billion-context/dist and "billion-context/ returned zero hits.
  • Separate entry + shared factory: distinct ids avoid a dual-load tool-registration collision when both the launcher and the npm entry are present.
  • Embedded tool registration (not manifest+reload): same-package schema is same-source, so drift protection is zero; the handshake is gated on protocolVersion and the version diff stays informational.
  • acp mutual exclusion: documented + startup warning in v1 (true auto-exclusion is a cross-repo follow-up, source-tagged opencode 2.x: no-launcher npm-plugin deployment — plugins: ["billion-context"], plugin lazily spawns the proxy #809).
  • Auto-update off on spawn: --no-auto-update CLI flag (cmdline-visible, zero new env namespace).

Pre-flight

  • npm run typecheck — clean
  • npm test — 1618 pass / 0 fail / 2 skip (pre-existing skips)
  • npm run build — emits dist/agent/opencode-local.js
  • Built-artifact smoke — default.id = billion-context-opencode-local, setup is a function, resolvePackageRoot() resolves to an existing dist/index.js, spawn args correct
  • exports targets verified present on disk

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

  1. url-mutation reaches the wire — the http.request hook mutates e.request.url; the comment at opencode.ts proves 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 the model.request baseURL instead (deferred, not v1).
  2. spawn convergence — the EADDRINUSE race (two processes) converges because the loser exits cleanly without a launch token (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_PROXY stand-down check.

Out of scope (Phase 2)

  • options.enabled toggle (the BILLION_CONTEXT_PLUGIN=0 kill switch already covers emergency stop)
  • inert-state visibility in the web UI
  • manifest-driven tool reload

Fixes #809

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
@github-actions

github-actions Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-15_opencode-npm-plugin (5e0b89e)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-810

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

Option B — Download artifact

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

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 On it — reviewing PR #810 (2026-09-15_opencode-npm-plugin → master, open). Pulling the branch, auditing diff cleanliness + code, running typecheck/test/build, and checking CI. Will report findings shortly.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

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

  • Diff is clean. Caveat: my clone's local master was stale; the true base is origin/master (a1b24aa). Against that, the PR is exactly one commit cb8c00b touching 7 files, all directly serving the feature — no scope creep.
  • npm run typecheck — clean.
  • npm run build — emits dist/agent/opencode-local.js ✔.
  • npm test — 1618 pass / 0 fail / 2 skip (matches your claim).
  • CI on head cb8c00b: all 7 Actions green (ubuntu/windows × node 22/24 tests, build-artifact, version-guard, codex fake-upstream e2e).
  • Read every changed file. Design is sound: shared V2 factory so the two entries can't drift; soft-fail probeProxy; loud foreign-service refusal; loopback-only spawn with mandatory --no-auto-update; correct stand-down gates (!BILLION_CONTEXT_PROXY && !pluginDisabled()); explicit-enum exports; version untouched (0.1.114), acp-kernel pinned 0.0.72. console.error/warn in the agent plugins is fine — they're client-side, not server modules.

🔴 Blocking finding — the documented plugin string resolves to the wrong module (evidence-backed).

Deployed as { "plugin": ["billion-context"] }. I ran Node's own resolver (self-referential from the package root, no execution):

import.meta.resolve("billion-context")        => ./dist/index.js                 (CLI/proxy server)
import.meta.resolve("billion-context/server") => ./dist/agent/opencode-local.js  (the plugin)

src/index.ts:6 calls main() unconditionally at top level and exports no plugin-shaped default. Under standard Node/jiti resolution — which is how OpenCode 2.x loads an npm plugin entry — the bare name "billion-context" loads the self-executing CLI (it'd start a stray loopback proxy or misparse argv), so the local plugin never activates. The local plugin is reachable only via the /server subpath.

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:

  1. Does "billion-context/server" actually load and report id === "billion-context-opencode-local"? (The feat: OpenCode 2.0 support — V2 launcher mode + pure-proxy validation (#735) #754 live probes covered the launcher shim-dir path, not this npm-subpath resolution.)
  2. Your runtime-facts note says 2.x stable wants plugin entries to be directories (hence the launcher's temp index.js shim at launcher.ts:1691). A plain npm install exposes a file via exports["./server"], not a directory — confirm 2.x accepts a file-resolving subpath; if it insists on a directory we'd need a different mechanism (postinstall shim or an opencode package field).

Recommendation: hold merge. Run your suggested smoke test with the corrected string "billion-context/server" first and confirm it loads, then confirm the two listed behaviors. Once you confirm the working string, I'll patch the doc example (opencode-local.ts header + README/PR body) to match — say the word and I'll commit it. I can also add a regression test asserting exports["./server"] resolves to the module whose default export has id: "billion-context-opencode-local".


中文摘要: 代码质量高、diff 干净(相对真正基线 origin/master 仅 7 个文件、单提交)、typecheck/test/build 与 CI 全绿;但发现一个可复现的阻塞问题——文档里的 { "plugin": ["billion-context"] } 经 Node 解析器实际会加载到自执行的 CLI(dist/index.js,顶层无条件跑 main())而非本地插件,本地插件只能经 "billion-context/server" 子路径到达;需按修正后的字符串在真实 OpenCode 2.x 上确认入口能加载(并确认 2.x 是否接受指向文件的子路径),再合并。当前不建议直接合并。

ework-agent added 2 commits September 15, 2026 21:32
…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.
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.
cskwork pushed a commit to cskwork/billion-context that referenced this pull request Oct 21, 2026
…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
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.

opencode 2.x: no-launcher npm-plugin deployment — plugins: ["billion-context"], plugin lazily spawns the proxy

1 participant