Skip to content

feat(pi): native plugin mode — self-bootstrapping proxy + fetch interception - #706

Merged
ranxianglei merged 43 commits into
masterfrom
feat/pi-native-plugin
Sep 18, 2026
Merged

ranxianglei merged 43 commits into
masterfrom
feat/pi-native-plugin

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Bare pi — with this package installed via pi's package manager or bili plugin install pi — now gets full plugin-mode compression with no launcher:

pi package install billion-context   # (or: bili plugin install pi)
# 之后裸跑 pi 即可,什么都不用管

How (all verified end-to-end on pi 0.83.6 / Node 25)

At extension load, dist/agent/pi-native.js (new tsup entry, now the pi manifest target):

  1. Spawns the package's own proxy via ensureProxyRunning — ephemeral port, parent-pid watchdog = the pi process; a healthy compatible instance is attached, not doubled (无单实例守卫:多个 bili 代理进程并存共写 sessions 目录,伴随孤儿 ref、有注册表无 transcript、计数自相矛盾的污染簇 #394/实例治理伞形:身份/验活/attach-or-spawn/优雅退出/状态卫生 —— 合并修复 #394 #403 #407 #414 #410 #406 #417 semantics).
  2. Patches globalThis.fetch (src/agent/native-intercept.ts) and rewrites model-API requests to <proxy>/bili/<full-upstream-url>. The load-bearing assumption from feat: pi native 模式——fetch 拦截层 + 插件胶水(native 模式 B) #519 is verified source-level and e2e: pi → pi-stable-ai → Anthropic/OpenAI SDKs resolve fetch from the global at first-request client construction (this.fetch = options.fetch ?? getDefaultFetch()), so a load-time patch always wins; SSE streams pass through untouched.
  3. Exports the existing createBiliPlugin factory with BILLION_CONTEXT_PROXY set — native tools, x-bili-plugin headers, /acp, and the compaction cancel all reuse the launcher-mode code paths unchanged.

Patch discipline

  • Matches only model-API URL shapes: (v\d+/)?(messages|chat/completions|completions|responses|conversations) suffix — version-unpinned (zhipuai /v4/chat/completions), path-prefixed upstreams included (bailian /apps/anthropic/v1/messages).
  • Never touches the proxy's own /bili/·/__bili/ paths (self-guard) or non-HTTP(S) URLs.
  • Pre-ready requests wait (≤15s) for the bootstrap; failure/timeout degrades to a direct (uncompressed) send with a one-time warning — the agent never breaks.
  • A TypeError (network failure) triggers one respawn + one retry — the watchdog reaps the proxy when the owning pi exits while later sessions still ride it.

Gating

  • Skipped entirely under a bili launch (BILLION_CONTEXT_PROXY / BILI_PROVIDER_REWRITES set) — bili pi keeps -e dist/agent/pi.js byte-identical.
  • Skipped under node:test (NODE_TEST_CONTEXT).
  • Opt-out: BILI_NATIVE_PI=0.

Smallest supporting change

ensureProxyRunning gained deps.scriptPath: inside pi, process.argv[1] is pi's own script, not the package bin — pi-native.ts resolves dist/index.js from its own module URL.

Evidence

Real run (bare pi --no-extensions -e dist/agent/pi-native.js -p --model vllm/qwen3.8-27b):

proxy log: [debug] tools=[read,bash,edit,write,compress,decompress,search_context,acp_status] msgs=2 stream=true
           [pfa-…] → upstream headers {…, "x-bili-tunnel":"1", host:127.0.0.1:8199}
           [pfa-…] [acp-usage] round 1 input=4273 cached=0 (cache hit 0%)
           parent-gone (pid …) received — flushing sessions…   ← watchdog reap on pi exit, zero orphans
pi stdout: NATIVE-OK

Tests: +15 (URL matcher positive/negative, rewrite/wait/timeout/self-guard/respawn-retry/Request-object/idempotency, gating predicates, script-path resolution, ensureProxyRunning scriptPath override). Full suite 1382/1382, typecheck clean.

Known limitation (tracked in #513)

The legacy billion-context-pi adapter self-disables by detecting a /bili/ prefix in its baseUrl — native mode does not rewrite baseUrl, so users with BOTH packages active get double compression. bili plugin install pi already removes the legacy entry; a startup detection warning for pi-package-manager installs is the follow-up.

Fixes #519

…ception (#519)

Bare pi (package installed via pi's package manager or bili plugin install
pi) now gets full plugin-mode compression with no launcher:

- dist/agent/pi-native.js (new tsup entry, now the pi manifest target):
  at extension load it spawns the package's own proxy via ensureProxyRunning
  (ephemeral port, parent-pid watchdog = the pi process; attaches to a
  healthy compatible instance instead of doubling), sets
  BILLION_CONTEXT_PROXY, and exports the existing createBiliPlugin factory
  so tools/headers//acp/compaction-cancel reuse launcher-mode paths.
- src/agent/native-intercept.ts: globalThis.fetch patch verified against
  pi 0.83.6 (SDK fetch resolves from the global at first-request client
  construction). Rewrites ONLY model-API URL shapes to
  <proxy>/bili/<full-upstream-url>; never touches the proxy's own paths
  or non-HTTP(S); waits for bootstrap (15s) then degrades to direct with
  a one-time warning; TypeError triggers one respawn+retry (parent
  watchdog fires when the owning pi exits while later sessions ride it).
- ensureProxyRunning: deps.scriptPath override (process.argv[1] is the
  host's script inside pi).
- Gating: skipped under bili launch (BILLION_CONTEXT_PROXY /
  BILI_PROVIDER_REWRITES) and node:test (NODE_TEST_CONTEXT); opt-out
  BILI_NATIVE_PI=0. bili pi keeps -e dist/agent/pi.js unchanged.

Known limitation: legacy billion-context-pi self-disables via the /bili/
baseUrl prefix native mode does not rewrite — tracked in #513.
@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: feat/pi-native-plugin (a627201)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-706

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

Option B — Download artifact

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

Install instructions are refreshed on each push.

… respawns (#519)

Review fixes for the native plugin mode:

- pi.ts: the session_before_compact cancel was gated on
  BILLION_CONTEXT_PROXY at factory (load) time. In native mode the proxy
  origin only lands in env AFTER the async bootstrap finishes, so the
  cancel was disarmed for the whole session and pi's native threshold/
  overflow compaction could fire alongside ACP compression (destroying
  the ACP-tagged context). Decide ownership at EVENT time via
  detectProxyBase instead: a failed bootstrap or a plain no-proxy run
  still degrades to fully native, and a manual /bili/ baseUrl routing
  now arms the cancel too.
- pi-native.ts: wrap the bootstrap in singleFlight() — a burst of
  TypeErrors (proxy died mid-session) used to call ensureProxyRunning
  once per failing request, which has no in-flight dedup and would spawn
  one orphaned proxy per request.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR review — feat(pi): native plugin mode

Duplicate screening: no overlapping open PRs/issues found — this is the sole implementation of #519; the co-install limitation is already tracked separately in #513. Diff is focused and clean (8 files, +432/−3, no unrelated churn) — passes the cleanliness gate.

Verified & cleared (no action needed):

  • Double plugin registration under bili pi + installed package: already guarded by piPluginInstalled() (src/launcher.ts:1324) — the launcher omits -e dist/agent/pi.js when settings.json already loads the bili entry, so exactly one factory runs.
  • Self-guard coverage: /bili/, /__bili/, /__acp/ paths and non-HTTP(S) URLs are never rewritten; Request-object input conversion preserves fetch-spec semantics (init still overrides the Request), abort signals survive the rewrite.
  • Gating predicates (shouldBootstrapNative) match the design; NODE_TEST_CONTEXT keeps test runs side-effect-free; nativeProxyScriptPath resolves correctly from any install root (bundled ESM keeps import.meta.url).

Bugs found — fixed directly on the branch (commit 3cb0331):

  1. Compaction cancel never armed in native mode (high). src/agent/pi.ts:286 gated the session_before_compact handler on process.env.BILLION_CONTEXT_PROXY !== undefined at factory time — but in native mode pi invokes the factory right after module load, while the env var only lands after the async bootstrap (spawn + health poll, ≥ hundreds of ms) finishes. The handler therefore effectively never got registered, so pi's native threshold/overflow compaction could fire alongside ACP compression — exactly the context-destroying race 注入零文件化:废除 overlay/临时目录机制(#531 设计返工) #535 exists to prevent. Fix: register the handler unconditionally for pi/omp and decide ownership at event time via detectProxyBase(ctx?.model?.baseUrl) (env is read fresh per event). This also degrades correctly when the bootstrap fails (stays fully native instead of cancelling compaction with no compression active — a static "force arm" flag would have bricked that case), and arms the cancel for manual /bili/ baseUrl routing, which previously slipped through. The 注入零文件化:废除 overlay/临时目录机制(#531 设计返工) #535 test now encodes the late-env timing plus the /bili/ path.
  2. Concurrent TypeErrors spawned one proxy per failing request (medium). On proxy death mid-session, every in-flight request hitting TypeError called state.respawn() independently; ensureProxyRunning has no in-flight dedup, so N concurrent failures → N spawns (orphaned extras sharing one sessions dir). Fixed with a singleFlight() wrapper around the bootstrap in pi-native.ts (+ unit test for share/re-arm semantics).

Observations (left for your call, not changed):

  • The URL matcher accepts versionless suffixes (/messages, /responses, /conversations, /completions). Every provider you cite carries a vN segment, so non-model endpoints shaped like https://api.example.com/conversations would be misrouted through the proxy. The failure asymmetry favors requiring v\d+/ (a false positive breaks a live fetch; missing a versionless provider just skips compression) — happy to tighten if you agree.
  • Nit: the retry-failure path emits onDispatch(url, "direct") but then throws instead of sending direct — misleading telemetry label.
  • Pre-existing (not introduced here): two processes starting within the probe→healthy window can each spawn a proxy before seeing the other — filed as bug: cross-process startup-window race — two concurrent launches each spawn a proxy (double writers over one sessions dir) #707; native mode makes back-to-back pi terminals a realistic trigger.

Verification: typecheck clean; full suite 1383 passed / 0 failed / 2 skipped (pre-existing skips); build green with dist/agent/pi-native.js emitted. My commit touches agent-side code only (no request-pipeline changes), so the e2e-codex gate isn't triggered by it; your e2e evidence for the feature itself stands.


中文摘要:修复了 PR 里两个真实缺陷——(1) native 模式下 compaction-cancel 因异步 bootstrap 时序在工厂期从未生效(改为事件时判定,bootstrap 失败时仍优雅降级为纯原生);(2) 并发 TypeError 会每个请求各 spawn 一个代理(加 singleFlight 去重)。补丁已直接提交到 PR 分支(3cb0331),typecheck/test/build 全绿,可以合并。

…t — a hardcoded file:///opt URL throws ERR_INVALID_FILE_URL_PATH on Windows
ranxianglei pushed a commit that referenced this pull request Sep 15, 2026
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.
…classify request-construction errors (#513 audit)
@ranxianglei

Copy link
Copy Markdown
Owner Author

审计(@jensenojs,#513)复核完成:三条中两条为真实 bug,已修复并推至本分支(commit ddbbf20);一条属潜在前提缺口,单开 issue #819。

Claim 2(respawn 失败不降级)— 确认,已修。 旧 catch 分支记了 onDispatch(url, "direct") 却仍然 throw,调用方拿到 TypeError 而非降级直连;更关键的是 bootstrap 写入的全局 BILLION_CONTEXT_PROXY 在中途死亡后无人清除 → session_before_compact 的事件时门(detectProxyBase)持续读到旧 origin、继续取消原生 compaction,而流量已全部直连——压缩永久失效 + 上下文无界增长。修复:give-up 路径真正直连发送(与 bootstrap 失败同一契约,一次性 warning)+ 新增 onGiveUp hook,pi-native 用它清 env,所有权检查随流量一起解除。这是有意的 per-session 永久降级(重新探测循环会在已失败的端口上空转)。顺带:review 里那条 "telemetry label misleading" nit 正是这个契约 bug 的表面症状,这次一并治了根。

Claim 3(consumed-body Request 误分类)— 确认,已修。 new Request(target, input) 重建原本在 proxy-death try 块内,body 已消费的 TypeError 被误判成代理死亡 → 白 respawn 一个孤儿代理。重建移出 try(makeTarget),调用方自身错误原样抛出。补了两个回归测试(give-up 直连 + onGiveUp 触发;consumed-body 不 respawn)。

Claim 1(execPath 宿主假设)— 属实但潜在,未在本分支修。 标准 npm 安装的 pi 可执行入口 shebang 实测为 #!/usr/bin/env node,process.execPath = node,主流路径不受影响;仅 bun install -g / 编译产物这类非 Node 宿主会踩中。修复依赖 findNodeRuntime(目前只在 #810 的 opencode-npm-plugin 分支上),现在接入还是等 #810 合入后统一接,留 owner 拍板,详见 issue #819。

Pre-flight:typecheck ✓ / 1385 pass 0 fail 2 skip ✓ / build ✓。

中文摘要:审计三查二实一潜——respawn 失败不降级(含陈旧 env 致压缩永久失效)与请求重建误分类两个真 bug 已修并推上本分支,execPath 宿主假设属潜在缺口单开 #819 待拍板,本分支可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 复核完成 — 审计修复已逐行验证,补了一个测试缺口(commit 314d03c),分支就绪。

在 ddbbf20 上逐行核了两处修复:

Claim 2(give-up 降级 + 陈旧 env) — 确认修对了。契约链完整:respawn 失败 → 真正直连发送(与 bootstrap 失败同路径、一次性 warning)→ onGiveUp 触发 → pi-native 清掉 BILLION_CONTEXT_PROXY → 我 3cb0331 里的事件时所有权检查(session_before_compact cancel、header stamping)随流量一起解除。陈旧 env 导致"压缩永久失效 + 上下文无界增长"的判断成立且严重。另独立验证了永久降级确实成立:give-up 后 state.ready 是已 settle 为 undefined 的 promise,后续请求走 bootstrap-failed 分支直连、不会再进 catch 触发 respawn —— 不存在死端口空转。

Claim 3(consumed-body 误分类) — 确认。makeTarget 提升到 try 之外,调用方自身缺陷(body 已消费/锁定)原样抛出,不再误判成代理死亡去 respawn 孤儿代理。

05b78b4(Windows 测试路径) — 无异议,pathToFileURL 构造比硬编码 file:///opt 正确。

Pre-flight 复跑(本地,分支 tip): typecheck ✓ / 全量 1385 pass · 0 fail · 2 skip ✓ / build ✓(dist/agent/pi-native.js 正常产出)—— 与你报的一致。

发现并直接修掉的小问题(314d03c,已在分支上):give-up 测试实际没有断言 onGiveUp 被触发——state 里根本没传这个 hook,state.origin === undefined 只能证明走了 give-up 分支,证明不了 hook 契约;"永久降级"这个关键属性也没有任何断言钉住。补了:spy 计数断言 respawns === 1 / giveUps === 1,再加一个 give-up 后的第二请求,断言它直连且不再触发 respawn(钉死"不空转")。重跑:该文件 12/12,全量仍 1385/0/2。

#819(execPath 宿主假设) — 同意你的分层:标准 npm 安装 shebang 是 #!/usr/bin/env node,主流路径不受影响,仅 bun install -g / 编译产物这类非 Node 宿主会踩中;等 #810 的 findNodeRuntime 落地统一接是对的,留你拍板。

分支现状:9e41419(feature) → 3cb0331(我的两处修复) → 05b78b4 → ddbbf20(审计修复) → 314d03c(测试补强)。无阻塞项,可以合并(按仓库规则 merge 由人来操作)。


中文摘要:审计的两处真 bug 修复(give-up 真降级+清陈旧 env、请求重建误分类)已逐行核实无误并本地复跑全绿;发现 give-up 测试漏断言 onGiveUp 触发与永久降级属性,已直接在分支上补强(314d03c),全量 1385/0/2 不变,本分支可以合并。

ranxianglei pushed a commit that referenced this pull request Sep 15, 2026
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.
…wning proxy in the plugin

Follows the pi-native pattern (#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, #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 #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, #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.
ework-agent added 2 commits September 16, 2026 00:50
…xtensions can back off under native mode (#820)

Verified against billion-context-pi and opencode-acp sources that their
existing auto-disable does not cover native mode: both check
BILLION_CONTEXT_PROXY only at extension-load time (native bootstrap writes
it asynchronously after the proxy is up) and detect /bili/ in the configured
baseUrl (native rewrites at the fetch layer, invisible to config). Launcher
mode and manual wiring keep working as before.

- native-bootstrap.ts: markNativeHost() — synchronous, first writer wins
- pi-native.ts / opencode-native.ts: set BILLION_CONTEXT_NATIVE=<host> at
  module evaluation, gated on the same shouldBootstrap*() condition as the
  bootstrap itself (opt-outs and launcher-managed launches leave it unset)
- README 'Which do I need?': mutual-exclusion note; CHANGELOG entries
- tests: marker assertions in pi-native/opencode-native files + units
@ranxianglei

Copy link
Copy Markdown
Owner Author

解决冲突

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到——正在处理。分支上已有一个同步提交(f7a5921,合到了较早的 master),master 此后又前进了 5 个提交(最新 95158f5,#827 opencode-plugin-path-reloc)。正在把当前 master 合入分支并解冲突,解完会跑全量验证再推上去,稍后回报结果。

Sisyphus and others added 12 commits September 17, 2026 22:42
…rst)

The forwarded kernel acp_status returns the legacy flat report while the
/acp command shows the rich status panel — tool and command disagreed.
acp_status is read-only, so the plugin now reads the panel from the
proxy's status endpoint first and falls back to forwardTool when no panel
is served (older proxy, unknown conversation).

Fixes #911
…-first

fix(agent): opencode v2 acp_status renders the status panel (panel-first)
…lugin

fix(agent): restore /acp status command under OpenCode V2 (#809)
…d install path

- src/agent/opencode-native.ts: V1 plugin surface — config hook rewrites
  provider baseURLs to <proxy>/bili/<upstream> on the shared in-process
  config object (idempotent, unwraps stale wraps), chat.headers stamps the
  plugin headers, tool registers the bili tool set with real zod shapes,
  /acp command renders the same status panel. Reuses the self-spawn/attach
  bootstrap; degrades to plain proxy mode when zod is unresolvable.
- src/agent/opencode-acp-command.ts: /acp hooks extracted from the launcher
  plugin, shared by V1 (.server) and V2 (setup) entries.
- src/agent/opencode.ts: launcher plugin now consumes the shared factory.
- zod 4.1.8 (exact, matches the opencode host's zod) added as the only
  runtime dependency; dist/index.js stays zod-free.
- tests/opencode-native-v1.test.ts: 11 tests (schema->zod mapping incl.
  cross-instance interop, provider rewrite idempotency, hooks + degrade).
- E2E verified in-container on opencode-ai 1.14.46 and 1.18.31 via
  'bili plugin install opencode': providers rewritten, plugin-mode headers,
  native acp_status round-trip, /acp panel render, tag-echo guard.
…lared limits

Completes V1<->V2 header parity flagged during #919 review. The V1 .server()
path reads provider.<id>.models.<m>.limit.context from the shared config object
(V1 exposes no catalog API like V2's ctx.catalog.model.list()) into a
provider/model map rebuilt on each config reload, then chat.headers stamps
x-bili-plugin-context-window only when the requested model carries a finite,
positive declared limit -- byte-compatible with the V2/pi stamping guard. When
absent (common for registry-discovered models) nothing is stamped, so the proxy
falls back to its models.dev registry window as before; never fabricates a
threshold. Adds extractV1Windows (+4 unit tests incl. end-to-end stamping).
Local pre-flight: typecheck + build + full suite green (1696 pass).
The V1 config-hook rewrite only reaches providers with an explicit
options.baseURL; providers relying on the SDK default (e.g. bare
@ai-sdk/openai -> api.openai.com) silently bypassed the proxy. Install
the shared native fetch intercept (pi-native's mechanism) in both the
native V1 server() and the launcher plugin server() — v1's provider
stack resolves fetch per-request, so a global patch catches those calls.

Verified end-to-end on opencode-ai 1.18.31 (container, hosts-redirect
api.openai.com -> local https shim -> sglang): leaktest provider with no
baseURL produced proxy log 'forward POST -> https://api.openai.com/v1/
responses' with x-bili-plugin headers — the request was captured,
/bili/-wrapped, and answered.
Adds the 1.x/2.x client-table rows, the native-vs-standalone mutual
exclusion note, the 2.x launcher bullet, and a condensed Chinese
counterpart of the OpenCode-specific section (launcher / native
install / V1 .server() details incl. the SDK-default fetch patch).
feat: OpenCode 1.x native support — V1 .server() hooks on the standard install path
…l opencode (#918)

Two compression owners in one host = double compression / ref-space
fights. The installer now removes opencode-acp entries from the global
opencode.json (bare / npm: / versioned / path specs, array or object
shape; original snapshotted to .bili-bak) and warns about project-local
installs it cannot touch. Object-shaped plugin maps are normalized to
their keys so sibling entries survive. Docs (EN+zh) document the strip
and the old-session migration semantics: old <acp> refs live in
opencode-acp's own store, decompress returns not-found, numbering
restarts — treat pre-migration sessions as read-only archives.
…ons, bili owns new ones (#920)

OpenCode 1.x hosts migrating from opencode-acp keep their pre-migration
sessions WORKING. The V1 native entry absorbs the installed opencode-acp
package (loadLegacyAcp: .opencode/node_modules > project node_modules >
global npm root > config-scope modules) by importing its server() with
BILLION_CONTEXT_PROXY unset strictly around the call (its only env check
is at entry), then routes per session:

- legacy session (acp state file exists in
  <XDG_DATA_HOME>/opencode/storage/plugin/acp/<sid>.json) — compression
  runs INSIDE the absorbed acp (its dcp refs, block store, all five
  tools). Model requests carry x-bili-plugin-bypass: 1; the proxy
  forwards them verbatim (no injection/nudge/binding).
- new session — tool executors forward to the proxy plugin endpoints
  (plugin mode). Tool slots carry the DCP schemas for both lanes (v1
  registers one def per name process-wide); the executor picks the lane.

acp's transforms (system/messages/text.complete) are gated on the
legacy predicate so new sessions never enter its registry; its config
hook runs on a provider-hidden shadow (its /bili/ self-disable is
neutered) and owned keys are merged back. /acp and /dcp route per lane.
Degradation: package absent/import-failed -> bili alone, legacy sessions
read-only (documented).

Also: cherry-picked 74701fb (installer strips legacy opencode-acp
entries, #918) — it was pushed to the already-merged #919 branch and
orphaned.
… any segment (#920 review)

Two review hardening fixes:

- loadLegacyAcp now receives the host's full ctx object instead of a
  {directory, client} projection. V1PluginContext types only the fields
  bili uses, but the runtime object may carry extra host fields that
  acp's hooks need at action time (the projection would drop them).
- isLegacyOpencodeAcpEntry matches path entries by ANY segment naming
  opencode-acp instead of only last/parent — deep entry paths like
  <dir>/opencode-acp/dist/index.js were missed, leaving both compression
  owners armed (the double-compression case #918 exists to prevent).
  Test fixture extended with the dist/index.js form.
- pass output param through all absorbed-acp wrappers (system.transform /
  text.complete / command.execute.before crashed with 'output is undefined'
  — acp hooks are (input, output) two-arg)
- legacyAcpCandidates: include v1 package cache
  ~/.cache/opencode/packages/opencode-acp@<ver>/node_modules (every version,
  newest first) — that is where 'opencode plugin opencode-acp' actually
  installs; project/global node_modules rarely see it
- wire loadLegacyAcp log through from .server() (absorption was silent)

Verified in container: legacy session ses_f4d9 — b1 decompress restores
phase-1 facts, model-created b2 block via absorbed acp, model requests
bypass-forwarded verbatim ([plugin-bypass] in proxy log); new session
ses_f4d821 — tools forward to proxy, session bound (plugin mode).
ework-agent and others added 6 commits September 18, 2026 12:06
…920 review)

7223468 fixed real 'output is undefined' crashes in acp's
system.transform / text.complete / command.execute.before handlers, but
the lane-routing test still called those hooks one-arg with fakes that
ignore the second parameter — so a regression of exactly this class
would not have been caught (tests are outside tsconfig.build.json, so
typecheck does not cover them either).

Fakes now record whether output reached them (:output/:no-output marker)
and the assertions require it on the legacy lane. Mutation-verified:
reverting the wrapper to a one-arg call fails the suite.
…ode install (#927)

- pick ONE effective plugin key by host major version (>=2 -> plugins,
  1.x/probe-failure -> plugin): 1.x hard-errors on 'plugins', 2.x merges
  both keys, so dual-writing is impossible and the probe fallback can
  never write a dead line
- write target = OPENCODE_CONFIG override, else highest-precedence file
  already present (opencode.jsonc > opencode.json > config.json), else
  create opencode.json — no more second file next to an existing config
- JSONC targets get surgical top-level-key edits (jsonc-parser), so user
  comments/formatting survive byte-for-byte; plain JSON keeps the
  historical full re-serialize; broken targets are refused, never
  overwritten
- compaction.auto is set to false only when the target does not already
  say auto:false (single source of truth); remove/status now recognize
  our entry under either key spelling and strip legacy acp entries from
  both
Union of the pi/opencode native branch stack (PRs #706/#919/#921 + #927
jsonc fix) with master's #923 lineage:

- Legacy opencode-acp sessions: keep the branch's opencode-legacy.ts
  (docker E2E verified on opencode 1.18.31 + acp 1.18.1: absorbed-acp
  compress/decompress/acp_status + x-bili-plugin-bypass verbatim
  forwarding) as the single legacy machinery; master's acp-bridge.ts is
  dropped as the duplicate. Its BILI_OPENCODE_ACP_SPEC launcher hint is
  adopted into legacyAcpCandidates (authoritative when the cache slot
  exists).
- src/agent/opencode.ts stays the branch's thin version-dispatch entry
  (V1 -> opencode-native server, V2 -> opencode-v2 setup).
- pi.ts: event-time proxy ownership gate (#519 native) UNION master's
  omp auto_compaction_start announcement tracking (#851).
- server.ts: master's early-return legacy bypass (BILI_PLUGIN_BYPASS_HEADER
  from util) replaces the branch's late pipeline exclusion; branch's
  pluginBypassHeader plumbing removed.
- plugin-install.ts: branch's full native installer (jsonc-first #927,
  plugin-entry + compaction.auto + stripLegacyOpencodeAcp) + master's
  claudeStatus isPlainMcpObject hardening (#839).
- Docs: table rows and launcher notes merged to describe both the native
  installer and the launcher legacy-session behavior; CHANGELOG union.

Verified: typecheck clean, 1822 tests (1820 pass / 2 E2E-gated skip),
build ok.
CI on windows-latest failed twice in tests/issue927-opencode-install.test.ts:
- detectOpencodeMajor execFileSync'd BILI_CLIENT_BIN directly — Windows npm
  global shims are .cmd/.bat, which execFileSync cannot spawn (EINVAL), so
  every probe failed soft to 1 and the v2 'plugins' key was never chosen.
  Route .cmd/.bat through the shell with explicit quoting on win32; plain
  exes and POSIX shebang scripts still go straight through.
- the test's fake bins were #!/bin/sh scripts (unspawnable on win32) — now
  .cmd fakes on Windows, matching the real-world BILI_CLIENT_BIN shape.
- 'installed -> <path>' assertions built RegExp from raw paths — win32
  backslash paths are regex metacharacters; switched to includes().

Verified: typecheck clean, 1829 tests (1827 pass / 2 E2E-gated skip), build ok.
…in (#927 follow-up)

Four windows-latest failures remained after 7a15acc:
- detectOpencodeMajor passed the quoted command STRING to execFileSync
  without shell:true — node treats the whole string as one executable path,
  ENOENT, probe fails soft to 1. Add shell:true to the .cmd/.bat branch.
- resolveNodeRuntime joined PATH candidates through the HOST path module:
  a posix-style entry on a win32 host gets rewritten to backslashes (and
  vice versa), so the probe misses runtimes the PATH actually contains.
  Concatenate separator-preserving instead — win32 accepts forward slashes,
  and the candidate keeps the exact bytes existsImpl can match.
- plugin-entry assertion grepped the raw index.js bytes where the path is
  JSON-escaped (doubled backslashes on win32) — normalize separators
  before matching.

Verified: typecheck clean, 1829 tests (1827 pass / 2 E2E-gated skip), build ok.
@ranxianglei
ranxianglei merged commit daa02a4 into master Sep 18, 2026
8 checks passed
@ranxianglei
ranxianglei deleted the feat/pi-native-plugin branch September 18, 2026 07:54
cskwork pushed a commit to cskwork/billion-context that referenced this pull request Oct 21, 2026
…reuse

Per @jensenojs: make sure the in-host spawn pitfall from ranxianglei#809 doesn't recur
across ranxianglei#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 ranxianglei#520/ranxianglei#521, and re-checking pi-native ranxianglei#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.
cskwork pushed a commit to cskwork/billion-context that referenced this pull request Oct 21, 2026
Addresses jensenojs's independent worktree audit of the opencode npm-plugin
(ranxianglei#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 ranxianglei#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.
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.

feat: pi native 模式——fetch 拦截层 + 插件胶水(native 模式 B)

1 participant