Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

### Features

- **Output-side compression: verbosity steering + effort routing (#1093)**: ports headroom's two output-token levers to bili's forward boundary. Output tokens cost ~5× input and are billed the instant they stream out, so the only lever is at request time. Both levers are **default off** (zero behavior change until enabled) and run LAST at the forward boundary — after every other body mutation, after `compat.roles` — so the turn classifier sees the final wire list; compress-retry re-sends share the same idempotent transform (`wireTransform`), and launcher / native-plugin / `/bili/` lanes inherit automatically. When disabled the path is byte-identical (no parse, no re-serialize).
- *Verbosity steering* appends a byte-stable conciseness directive (levels L0–L4, default L2) at the **tail** of the system prompt. Never prepends (that busts the prefix cache); **skip-if-absent** — it never fabricates a system carrier the client didn't send (a newly injected system can itself be rejected by placement-strict backends, #377 class); sentinel-wrapped and idempotent — re-applying the same level is a byte-stable no-op, a level change replaces the block in place, so retries never accumulate it. Covers all four wires: Anthropic `system` (string + block array, `cache_control` breakpoints preserved), OpenAI `system`/`developer` message, Responses `instructions`, Google `systemInstruction.parts`.
- *Effort routing* classifies the final turn **structurally** (block composition only, no content pattern-matching) and, on a mechanical continuation turn (clean tool result, no error), lowers an **already-present** effort field toward its floor: OpenAI `reasoning_effort`→`low`; Responses `reasoning.effort`→`low`; Anthropic `output_config.effort`→`low` + `thinking.budget_tokens`→1024 (documented API floor); Google `generationConfig.thinkingConfig.thinkingBudget`→128 (**assumed** floor, documented as such). Clamp-only safety rules: never injects an effort field the client didn't send (models without effort support 400 on it), never toggles `thinking.type` (disabling thinking over a history that carries thinking blocks 400s and busts the cache tier), dynamic budgets (`-1`) and non-mechanical turns untouched, unrecognized structural shapes not classified (conservative — request goes out unchanged). The Responses classifier walks the flat `input` list BACKWARD from the tail: clients re-send full history every request (codex does), so a forward scan would hit the original ask on every turn and could never classify a continuation; assistant-side items between the last user signal and the trailing tool outputs (`message`, `function_call`, `custom_tool_call`, `local_shell_call`, `apply_patch_call`, `reasoning`) do not break the continuation.
- Config: `billion-context.json` `outputSteering` block (global + per-provider route overlay, same shape as `compat`). 35 regression tests across all four wires (idempotency, skip-if-absent, clamp-only rules, full-history continuation classification).

- **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.
Expand Down
17 changes: 17 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ Top-level keys that control how the proxy listens and behaves globally.
- **Description:** Global wire-compat role map. `roles` maps message roles to the role name your upstream accepts, e.g. `{"compat":{"roles":{"developer":"system"}}}` rewrites `developer` → `system` on the final forwarded body for upstreams that reject the `developer` role (#552, newer codex clients). Applies to `openai` chat-completions and `responses` requests; exact-match roles only, everything else in the body is untouched; re-sent compress-retry bodies carry the same rewrite. Per-provider `compat.roles` entries (see [Providers](#providers)) win per key. Default `{}` forwards bodies byte-for-byte unchanged.
- **Learn-on-failure:** with no compat configured, an upstream `400 Invalid role: …` is auto-fixed — bili rewrites the offending role to `system`, retries once, and remembers the mapping **session-scoped** (in-memory on the session; never written to config). Later requests in that session skip the 400 round-trip. The info log emitted when the fix fires carries the permanent per-provider snippet.

### `outputSteering`

- **Type:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }`
- **Default:** `{ enabled: false, verbosityLevel: 2, effortRouting: true }` (OFF — zero behavior change until enabled)
- **Status:** ACTIVE
- **Description:** Output-side compression (#1093). Output tokens cost ~5× input and are billed the instant they stream out, so both levers act at request time. They run at the forward boundary **after** every other body mutation (last, after `compat.roles`), so the turn classifier sees the final wire list; compress-retry re-sends carry the same idempotent transform. All launcher / native-plugin / `/bili/` lanes inherit it automatically.
- **Verbosity steering** — appends a byte-stable conciseness directive at the **tail** of the system prompt (`verbosityLevel` L0–L4, default L2; L0 = no directive). Never prepends (that busts the prefix cache), and is **skip-if-absent** — it never fabricates a system carrier the client didn't send (a newly injected system can itself be rejected by placement-strict backends, #377 class). Idempotent: re-applying the same level is a byte-stable no-op, a level change replaces the sentinel-wrapped block in place, so retries never accumulate it. Covers all four wires: Anthropic `system` (string or block array — `cache_control` breakpoints preserved), OpenAI `system`/`developer` message, Responses `instructions`, Google `systemInstruction.parts`.
- **Effort routing** — classifies the final turn **structurally** (block composition only, no content pattern-matching). On a mechanical continuation turn (clean tool result, no error) it lowers an **already-present** effort field toward its floor: OpenAI `reasoning_effort` → `low`; Responses `reasoning.effort` → `low`; Anthropic `output_config.effort` → `low` + `thinking.budget_tokens` → 1024 (documented API floor); Google `generationConfig.thinkingConfig.thinkingBudget` → 128 (**assumed** floor — verify per-model before relying on it). Clamp-only: it never injects an effort field the client didn't send (models without effort support 400 on it), never toggles `thinking.type` (disabling thinking over a history that carries thinking blocks 400s and busts the cache tier), and leaves dynamic budgets (`-1`) and non-mechanical turns untouched. Unrecognized structural shapes are not classified (conservative — the request goes out unchanged).
- A per-provider `providers.<url>.outputSteering` replaces this global block for that route (see [Providers](#providers)).

### `proxy`

- **Type:** `string`
Expand Down Expand Up @@ -195,6 +205,13 @@ A shallow key (`https://open.bigmodel.cn`) matches every path on that host. A de
- **Status:** ACTIVE
- **Description:** Per-provider wire-compat overrides. `roles` maps message roles to the role name this upstream accepts, e.g. `{"developer": "system"}` for upstreams that reject the `developer` role newer codex clients send (#552). Applied to the final forwarded `openai`/`responses` body — client-sent roles and bili's own injected prompt alike — and to every body the compress-retry loops re-send. Wins per key over the global `compat` block (see [Server Settings](#server-settings)). Default `{}` forwards byte-for-byte unchanged.

### `outputSteering`

- **Type:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }`
- **Default:** *(inherits the global [`outputSteering`](#outputsteering) block)*
- **Status:** ACTIVE
- **Description:** Per-provider override of output-side compression (#1093) — verbosity steering + effort routing, see [Server Settings](#server-settings) for the two levers and their safety rules. Replaces the global block for this route rather than merging field-by-field: e.g. enable steering globally but keep one route untouched with `{"enabled": false}`, or run a different level on a specific upstream. Fields omitted inside a route entry fall back to the built-in defaults (`verbosityLevel: 2`, `effortRouting: true`), not to the global values.

### `passthrough`

- **Type:** `boolean`
Expand Down
17 changes: 17 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@
- **说明:** 全局线上兼容角色映射。`roles` 把消息角色映射为上游接受的角色名,例如 `{"compat":{"roles":{"developer":"system"}}}` 把 `developer` → `system`,用于拒绝 `developer` 角色的上游(#552,新版 codex 客户端会发送)。作用于 `openai` chat-completions 与 `responses` 请求;仅精确匹配角色,体内其它内容不动;压缩重试重发的请求体同样携带。按 provider 的 `compat.roles`(见 [Providers](#providers))按键优先。默认 `{}` 逐字节透明转发。
- **失败自学习:** 未配置 compat 时,上游返回 `400 Invalid role: …` 会被自动修复 —— bili 把被拒角色改写为 `system`,重试一次,并把学到的映射记在**会话上**(仅内存,绝不写入配置)。该会话后续请求免 400 往返。修复生效时打印的 info 日志附带可永久化的 per-provider 片段。

### `outputSteering`

- **类型:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }`
- **默认值:** `{ enabled: false, verbosityLevel: 2, effortRouting: true }`(关闭 —— 启用前零行为变化)
- **状态:** ACTIVE
- **说明:** 输出侧压缩(#1093)。输出 token 价格约为输入 token 的 5 倍,且一经流出即计费,所以两个杠杆都只能在请求时生效。二者在转发边界执行,位于所有其它 body 变更**之后**(最后,在 `compat.roles` 之后),保证轮次分类器看到的是最终 wire 列表;压缩重试重发的请求体携带同一幂等变换。launcher / native-plugin / `/bili/` 各通道自动继承。
- **Verbosity steering(详略引导)** —— 在 system prompt **尾部**追加一段字节稳定的简洁指令(`verbosityLevel` L0–L4,默认 L2;L0 = 不加指令)。绝不前置(会破坏 prefix cache),且**缺席即跳过** —— 从不伪造客户端没发送的 system 载体(新注入的 system 本身就可能被放置严格的上游拒绝,#377 一类)。幂等:重复应用同一级别是字节级 no-op,级别变化就地替换 sentinel 包裹的块,重试不会累积。覆盖全部四种 wire:Anthropic `system`(字符串或块数组 —— `cache_control` 断点保留)、OpenAI `system`/`developer` 消息、Responses `instructions`、Google `systemInstruction.parts`。
- **Effort routing(努力度路由)** —— 对最后一轮做**结构性**分类(只看块组成,不做内容模式匹配)。机械续轮(干净的 tool 结果、无错误)上把**已存在**的 effort 字段向地板值压低:OpenAI `reasoning_effort` → `low`;Responses `reasoning.effort` → `low`;Anthropic `output_config.effort` → `low` + `thinking.budget_tokens` → 1024(文档化 API 下限);Google `generationConfig.thinkingConfig.thinkingBudget` → 128(**假定**下限 —— 依赖前请按模型核实)。只降不注:从不注入客户端没发送的 effort 字段(不支持 effort 的模型会 400),从不切换 `thinking.type`(在携带 thinking 块的历史上禁用 thinking 会 400 并击穿缓存层),动态预算(`-1`)与非机械轮一律不动。无法识别的结构形状不做分类(保守 —— 请求原样发出)。
- 按 provider 的 `providers.<url>.outputSteering` 对该路由整体替换此全局块(见 [Providers](#providers))。

### `proxy`

- **类型:** `string`
Expand Down Expand Up @@ -193,6 +203,13 @@
- **状态:** ACTIVE
- **说明:** 按 provider 的线上兼容覆盖。`roles` 把消息角色映射为该上游接受的角色名,例如 `{"developer": "system"}` —— 用于拒绝 `developer` 角色的上游(#552,新版 codex 客户端会发这个角色)。作用于最终转发的 `openai`/`responses` 请求体 —— 客户端发送的角色和 bili 自己注入的提示一视同仁 —— 压缩重试循环重发的请求体同样携带该改写。按键覆盖全局 `compat` 块(见[服务端设置](#服务端设置))。默认 `{}` 逐字节透明转发。

### `outputSteering`

- **类型:** `{ enabled?: boolean; verbosityLevel?: number; effortRouting?: boolean }`
- **默认值:** *(继承全局 [`outputSteering`](#outputsteering) 块)*
- **状态:** ACTIVE
- **说明:** 输出侧压缩(#1093)的按 provider 覆盖 —— verbosity steering + effort routing,两个杠杆及其安全规则见[服务端设置](#server-settings)。对该路由**整体替换**全局块,而不是逐字段合并:例如全局开启 steering、用 `{"enabled": false}` 保持某个路由不受影响,或在特定上游使用不同级别。route 条目内省略的字段回落到内置默认值(`verbosityLevel: 2`、`effortRouting: true`),而非全局块的取值。

### `passthrough`

- **类型:** `boolean`
Expand Down
Loading
Loading