Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
9e41419
feat(pi): native plugin mode — self-bootstrapping proxy + fetch inter…
Sep 11, 2026
3cb0331
fix(pi): arm compaction-cancel at event time; dedup concurrent native…
Sep 11, 2026
05b78b4
fix(test): platform-native absolute path in nativeProxyScriptPath tes…
Sep 11, 2026
ddbbf20
fix(pi-native): degrade to direct sends when respawn fails; don't mis…
Sep 15, 2026
314d03c
test(pi-native): assert onGiveUp fires and the degrade stays permanen…
Sep 15, 2026
f7a5921
chore: sync master into feat/pi-native-plugin (CHANGELOG conflict: ke…
Sep 15, 2026
9409d3b
feat(opencode): native plugin mode for OpenCode 2.x (#820) — self-spa…
Sep 15, 2026
385db4f
docs: README — fix 3-space continuation drift; table row covers nativ…
Sep 15, 2026
42c1782
feat(agent): BILLION_CONTEXT_NATIVE coexistence marker — standalone e…
Sep 16, 2026
e516ad8
Merge remote-tracking branch 'origin/master' into HEAD
Sep 16, 2026
2a2232a
Merge remote-tracking branch 'origin/master' into HEAD
Sep 16, 2026
54f8fb2
fix(launcher,plugin-install): async spawn error + non-object mcp guar…
Sep 16, 2026
1d4f38c
feat(agent): opencode native attach-to-external-proxy mode (#809)
Sep 16, 2026
ca4b1ab
Merge pull request #824 from ranxianglei/2026-09-15_opencode-native-p…
ranxianglei Sep 16, 2026
11a82d7
feat(agent): register /acp command under OpenCode V2 (#809)
Sep 16, 2026
f857ff1
fix(agent): harden /acp under OpenCode V2 (guard order, status timeou…
Sep 16, 2026
d6d60f8
fix(agent): /acp must not wake the model under OpenCode V2
Sep 17, 2026
304110a
fix(agent): make opencode v2 /acp status panel visible in the TUI
Sep 17, 2026
0f1cba9
Merge pull request #875 from ranxianglei/2026-09-17_opencode-v2-acp-n…
ranxianglei Sep 17, 2026
40c4970
Merge pull request #878 from ranxianglei/2026-09-17_opencode-v2-acp-v…
ranxianglei Sep 17, 2026
0b7127a
merge(agent): fold /acp visible-panel fix (#878) into #850 source branch
Sep 17, 2026
6d79228
fix(agent): show the idle notice on first opencode v2 /acp before any…
Sep 17, 2026
d596604
Merge pull request #882 from ranxianglei/2026-09-17_opencode-v2-acp-i…
ranxianglei Sep 17, 2026
202e811
fix(agent): preset BILLION_CONTEXT_PROXY attaches the opencode v2 nat…
Sep 17, 2026
a119940
Merge pull request #885 from ranxianglei/2026-09-17_opencode-v2-three…
ranxianglei Sep 17, 2026
96368b2
fix(agent): opencode v2 acp_status renders the status panel (panel-fi…
Sep 17, 2026
89928fe
Merge pull request #912 from ranxianglei/2026-09-18_opencode-v2-panel…
ranxianglei Sep 17, 2026
6159d25
Merge pull request #850 from ranxianglei/2026-09-15_opencode-native-p…
ranxianglei Sep 17, 2026
086e80a
feat: OpenCode 1.x native support — V1 .server() hooks on the standar…
Sep 17, 2026
eeb08de
feat: OpenCode V1 stamps x-bili-plugin-context-window from config-dec…
Sep 17, 2026
29a5966
fix: v1 catches SDK-default provider baseURLs via global fetch patch
Sep 18, 2026
9b3bd46
docs: sync README.zh-CN opencode coverage with the English README
Sep 18, 2026
2c5a6f8
Merge pull request #919 from ranxianglei/2026-09-18_opencode-v1-native
ranxianglei Sep 18, 2026
288eca8
fix(install): strip legacy opencode-acp entries on bili plugin instal…
Sep 18, 2026
8d79c08
feat: v1 legacy-lane routing — absorbed opencode-acp serves old sessi…
Sep 18, 2026
49b290f
fix: pass host ctx through to absorbed acp; match acp path entries by…
Sep 18, 2026
7223468
fix: legacy lane hardening from docker E2E (#920)
Sep 18, 2026
a63fa66
test: pin two-arg (input, output) contract on absorbed-acp wrappers (…
Sep 18, 2026
85c9dbf
fix(install): version-aware plugin key + jsonc-first target for openc…
Sep 18, 2026
510576e
merge: consolidate native stack with master (#706 ← master)
ranxianglei Sep 18, 2026
6b77d02
merge: sync master (#891 truncation continuation retry)
Sep 18, 2026
4bbc463
fix: windows portability of the opencode major-version probe (#927)
Sep 18, 2026
a627201
fix: windows CI — shell-mode .cmd probe, separator-preserving PATH jo…
Sep 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
| Language | TypeScript (strict, ESM) |
| Build | tsup (bundling, inlines acp-kernel) |
| Test | Node.js built-in: `node --import tsx --test tests/*.test.ts` |
| Runtime Dep | `acp-kernel` (bundled at build time, zero runtime deps in dist) |
| Runtime Dep | `acp-kernel` (bundled at build time) + `zod` (external, only used by `dist/agent/opencode-native.js` V1 tools; `dist/index.js` stays dependency-free) |

### Repository Info

Expand Down Expand Up @@ -65,7 +65,7 @@ billion-context/
│ ├── compress-tool.ts # compress tool parsing (kernel parseCompressArgs)
│ ├── decompress-shared.ts # Shared decompress logic
│ ├── orphan-gc.ts # Orphaned block cleanup
│ ├── agent/ # Thin agent-side plugins (pi/omp/opencode)
│ ├── agent/ # Thin agent-side plugins (pi/omp/opencode; opencode-acp-command.ts = shared /acp hooks V1+V2, opencode-native.ts = self-spawn native, V1 `.server()` + V2 `setup`)
│ ├── web/ # Web UI (config + context windows)
│ ├── fetch-util.ts # HTTP fetch with timeout
│ └── util.ts # Misc utilities
Expand All @@ -76,7 +76,7 @@ billion-context/

### Key Design Decisions

1. **acp-kernel is bundled inline** — tsup does NOT list it in `external`, so `dist/index.js` is self-contained (zero runtime deps)
1. **acp-kernel is bundled inline** — tsup does NOT list it in `external`, so `dist/index.js` is self-contained. Exception: `zod` (exact `4.1.8`, matching the opencode host's own zod so V1 plugin-tool shapes interoperate) is a real dependency and stays external — only `dist/agent/opencode-native.js` imports it (lazily, at plugin-tool registration); `dist/index.js` and every other entry remain zod-free. When zod cannot be resolved at runtime the V1 plugin degrades to plain proxy mode instead of failing.
2. **Tags use XML format** `<acp tokens="2" type="text">m00001</acp>` — written with hex escapes (`\x3c`, `\x3e`) to avoid Write/Edit tool stripping
3. **Auto-update**: checks npm registry every 3 min (`CHECK_INTERVAL_MS = 3*60*1000`), first check per process ignores throttle
4. **Tee logger**: all proxy logs go through `src/logger.ts` (file + stderr). Do NOT use `console.error` in server-side modules — use `loggerLog()`.
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

## [Unreleased]

### Features

- **Coexistence marker for standalone extensions (#820)**: the pi-native and opencode-native entries now set `BILLION_CONTEXT_NATIVE=<host>` synchronously at module evaluation (gated on their own bootstrap gate, first writer wins — `markNativeHost()` in `src/agent/native-bootstrap.ts`), so the standalone `billion-context-pi` / `opencode-acp` extensions can stand down at action time when running alongside a native entry. Verified against both sibling repos that the pre-existing auto-disable does NOT cover native mode: they 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. Standalone-side adoption of the marker is tracked in each repo's issue tracker.
- **opencode 2.x native mode: package-installed opencode gets plugin-mode compression with no launcher (#820, npm-package design #809)**: `bili plugin install opencode` now installs, alongside the MCP shell (kept, but optional — a missing live proxy origin skips it instead of failing the install), a self-spawning native plugin: a stable wrapper directory `<configDir>/plugins/billion-context/index.js` re-exporting `dist/agent/opencode-native.js` (OpenCode 2.x rejects bare FILE paths in `plugin` — the directory's index.js is the entrypoint, #754 probe) plus `compaction.auto=false` (single compression owner; merge-preserving, restored from the `.bili-bak` backup on remove). At plugin load the same gate as pi-native applies (`BILI_NATIVE_OPENCODE=0` opt-out; skipped entirely under a `bili` launch) and the package's own proxy is bootstrapped through `ensureProxyRunning` (attach-or-spawn, ephemeral port, parent-pid watchdog, `deps.scriptPath`). OpenCode plugins have no fetch seam to patch, so egress interception uses the `http.request` hook, replacing the outgoing fetch Request REFERENCE with `new Request("<proxy>/bili/<url>", old)` carrying method/headers/body (WHATWG Request.url is read-only at runtime — verified live, #810). Header stamping, native tools and compaction-boundary reporting reuse the shared V2 setup factory (`src/agent/opencode-v2.ts`, extracted from opencode.ts so launcher mode and native mode share ONE protocol implementation). Because an http.request hook cannot observe send failures (the host swallows them), every request liveness-probes `/__bili/health` of the current origin before routing — one respawn if the proxy died mid-session, direct send + one-time warning when no origin can be made healthy (auto-recovering: each request re-verifies, unlike pi's lifetime latch). Also fixes #819: `ensureProxyRunning` resolves the Node executable for spawning via `resolveNodeRuntime()` (live Node wins → `BILLION_CONTEXT_NODE` override → PATH search) instead of blind `process.execPath`, which inside a host binary (opencode/pi native) is the HOST executable — the spawned proxy died at spawn.
- **pi native mode: bare `pi` gets plugin-mode compression with no launcher (#519)**: with this package installed (pi's package manager or `bili plugin install pi`), the pi manifest now loads `dist/agent/pi-native.js`, which at extension load (1) spawns the package's own proxy (`ensureProxyRunning` — ephemeral port, parent-pid watchdog = the pi process, attaches to a healthy compatible instance instead of doubling), (2) patches `globalThis.fetch` to rewrite model-API requests to `<proxy>/bili/<full-upstream-url>` (verified end-to-end: pi's SDK stack resolves fetch from the global at first-request client construction, so a load-time patch always wins; SSE streams pass through untouched; a proxy death mid-session triggers one respawn + retry), and (3) exports the existing `createBiliPlugin` factory with `BILLION_CONTEXT_PROXY` set — tools, `x-bili-plugin` headers, `/acp` and the compaction cancel all reuse the launcher-mode code paths. The patch matches only model-API URL shapes (`/v1/messages`, `(v\d+/)?chat/completions|completions|responses|conversations` suffixes — version unpinned for zhipuai `/v4/…`, path-prefixed for bailian `/apps/anthropic/v1/messages`) and never touches the proxy's own `/bili/`|`/__bili/` paths or non-HTTP(S) URLs; a failed/timeout bootstrap degrades to direct sends with a one-time warning. Opt-out: `BILI_NATIVE_PI=0`. Skipped entirely under a `bili` launch (`BILLION_CONTEXT_PROXY`/`BILI_PROVIDER_REWRITES` set) — `bili pi` keeps injecting `dist/agent/pi.js` as before. `ensureProxyRunning` gained `deps.scriptPath` (inside pi, `process.argv[1]` is pi's own script, not the package bin). Coexistence: the legacy `billion-context-pi` adapter detects the proxy via a `/bili/` baseUrl prefix or `BILLION_CONTEXT_PROXY`, both invisible under native mode (fetch-layer rewrite; env written asynchronously) — so BOTH installed used to mean double compression. `bili plugin install pi` removes the legacy entry, and the synchronous `BILLION_CONTEXT_NATIVE=pi` marker (see above) lets the standalone extension stand down at action time once it adopts the check.
### Fixes

- **pi native mode: a failed mid-session respawn degrades to direct sends instead of rethrowing the proxy's network error (#513 audit)**: when the spawned proxy died and the one-shot respawn also failed, the interceptor logged an `onDispatch(url, "direct")` but then re-threw the original `TypeError` — the model call died instead of degrading, and `BILLION_CONTEXT_PROXY` stayed set, so the event-time `session_before_compact` cancel kept cancelling native compaction while all traffic went direct (context grows uncompressed, forever). The give-up path now sends the request direct (same contract as bootstrap failure, one-time warning) and fires a new `onGiveUp` hook; pi-native uses it to clear the env so event-time ownership checks disarm together with the traffic. Also: rebuilding a Request-object input against the rewritten target no longer routes caller-side defects (already-consumed or locked body) into the proxy-death branch — they surface as-is instead of respawning an orphaned proxy.
- **Proactive nudge fires on upstreams that NEVER report usage — no more unbounded climb to the hard limit (#728)**: ChatGPT-login-style backends omit `usage.input_tokens` entirely (`response.completed` carries none), so `lastInputTokens` stayed 0 for the whole session — and the kernel's `decideNudge` is structurally unfireable at tokenCount == 0 (growth reference falls back to tokenCount itself → growth ≡ 0; mass-ready and all pressure bands require usage ≥ their pct lines). Proactive compression therefore never fired and contexts climbed unbounded until preflight's hard-limit emergency path took over (#726 reached ~1.32M tokens against a 1.05M window before the ~630K-token emergency summarization — which then 502-looped). `effectiveTokenCount` fed 0 for explicit-identity zero-baseline sessions on the "self-heals via the next measured usage report" assumption, which breaks for never-reporting upstreams. The fix mirrors how OpenAI handles exactly this in codex itself (server-observed usage first-class, local estimator fallback underneath — verified against `openai/codex` sources during triage): each `prepare*` now records the char-count upper bound of THAT turn's outbound payload (post-fold processed messages + system/tools overhead + image tokens) into `session.stats.localInputEstimate`, and `effectiveTokenCount` feeds it ONLY while `lastInputTokens == 0`, capped by the current request's inbound upper bound so a stale-high reading can't outlive a client-side shrink. Real usage always takes precedence the moment any report lands (same invariant as #604's `armFailureShrink` exception — the upper-bound estimator only errs early, compresses earlier, never later); turn 1 of a fresh explicit session is byte-identical to before (nothing measured yet → still 0); anonymous-prefix-affinity forks keep their raw-inbound-bound regime untouched; the estimate self-corrects after every fold (post-fold outbound payload shrinks → next reading drops, no inflation even though proxy clients re-send full raw history every turn); it is cleared on the native-compaction-boundary reset. Net effect: silent-backend sessions get incremental compression from the moment the local estimate crosses the nudge thresholds instead of one giant emergency fold at the wall. Rebase onto current master exposed an interaction with #817's per-body preflight dead-end cooldown key: the nudge text injected into the system prompt changes every turn, so keying the cooldown on the sha256 of the proxy-REBUILT wire body misses on identical client retries once the fallback arms the nudge — every retry re-burned the doomed summarization walk, defeating #726's quota protection on exactly the silent backends this fix targets. The cooldown identity now hashes the client's raw inbound request body instead, so proxy-side injections (nudge/system/tools/tags) can no longer defeat it. Tests pin: silent-backend multi-turn (turn 1 idle → turn 2 nudges, preflight silent), real-usage precedence (reported tokens beat a ~90% payload), stale-high cap (shrunk history does not re-trigger).
- **Bump acp-kernel 0.0.74 → 0.0.77; `acp_cache` held off every wire surface until adoption (#800)**: the pin jumps three kernel releases — 0.0.75 (cache-reconciliation core: `acp_cache` tool + `buildCacheReport`; recommend tail-below-gate fix), 0.0.76 (Google/Gemini wire codec; recommend range integrity), 0.0.77 (nudge ranges ordered/merged by position instead of ref number — fixes #887). Kernel ≥0.0.75 ships a fifth proxy tool, `acp_cache`, but this proxy has no execution path for it: an intercepted call fell through `executeProxyTool` into the unknown-tool branch, which reports SUCCESS with `[Unknown proxy tool: acp_cache]` — a model calling it would get a plausible-looking result that did nothing. Until adoption lands (feature #800, owner decision pending), `src/compress-tool.ts` derives `PROXY_TOOL_NAMES` and the four `BILI_ACP_TOOLS_*` arrays from the kernel constants minus `UNADOPTED_KERNEL_TOOLS` (`{acp_cache}`) — the single choke point every serving surface consumes (Responses/OpenAI/Anthropic tool arrays, plugin manifest + allowed list, absorb gate, Responses-adapter classification), so the tool stays off the wire everywhere without touching call sites. `MUTATING_PROXY_TOOLS`/`READONLY_PROXY_TOOLS` stay raw re-exports (classification sets only; `acp_cache` is correctly classified readonly and no serving surface reads them). The #841 parity test (`tests/search-context-cross-session.test.ts`) extends the "no other tool may change" contract against the FILTERED kernel side only, so a future BILI-side leak of an unadopted tool still fails.
- **A render tag wrapped around the model's whole turn no longer reaches the client as orphan markup (PR #872)**: a model imitating the render tag can write its entire turn — tool call included — where the opening's attributes are still open (recorded shape: `<acp tokens="1" text="text` immediately followed by the turn's own markup). The span escapes every tag pattern at once: an attribute class stops at `<`, and the value opened with `"` is never closed, so no close tag is ever written. The filter dropped the opening and released the payload, and the agent received a completed turn of orphan `parameter`/`invoke`/`calls` closers with no tool call in it — it stalled until nudged by hand. The stripper now recognises the wrapped shape by form (the attribute list runs into a `<`, or carries an odd number of quotes) and swallows the span whole, to a loose close tag or to the end of the turn, in `stripAcpTags` and in the streaming filter alike; the turn then reaches the client empty, which the degenerate-turn retry (#870, PR #871) re-asks for. The #644 rule is unchanged: an over-long tail after a *plain* opening is still released as content.
Expand Down
Loading
Loading