diff --git a/docs/architecture.md b/docs/architecture.md
index 5ccec3305b..6097ab54c6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -23,7 +23,7 @@ How to read it:
|---|---|---|---|
| `storage` | Unified SQLite: table family, kstate, checkpoints, GC | [storage.md](./architecture/storage.md) · [zh](./architecture/storage.zh-CN.md) · [ja](./architecture/storage.ja.md) | ✅ |
| `pipeline` | Request pipeline (handle / prepare-* / relay / inject) | [pipeline.md](./architecture/pipeline.md) · [zh](./architecture/pipeline.zh-CN.md) · [ja](./architecture/pipeline.ja.md) | ✅ |
-| `lanes` | Host lanes (dsh / pi / opencode / codex / bare proxy + lane-decisions) | [lanes.md](./architecture/lanes.md) · [zh](./architecture/lanes.zh-CN.md) · [ja](./architecture/lanes.ja.md) | ✅ |
+| `lanes` | Host lanes (dsh / pi / opencode / codex / bare proxy + lane-decisions; Pi Anthropic full-request compatibility) | [lanes.md](./architecture/lanes.md) · [zh](./architecture/lanes.zh-CN.md) · [ja](./architecture/lanes.ja.md) | ✅ |
| `kernel` | Compression engine (acp-kernel: folds, summaries, ref ledger) | [kernel.md](./architecture/kernel.md) · [zh](./architecture/kernel.zh-CN.md) · [ja](./architecture/kernel.ja.md) | ✅ |
| `identity` | Session & message identity (session id, persona fork, msgid channels) | [identity.md](./architecture/identity.md) · [zh](./architecture/identity.zh-CN.md) · [ja](./architecture/identity.ja.md) | ✅ |
| `fastpaths` | Fastpaths (incremental lane, v5 watermark, D-lane snapshot render) | [fastpaths.md](./architecture/fastpaths.md) · [zh](./architecture/fastpaths.zh-CN.md) · [ja](./architecture/fastpaths.ja.md) | ✅ |
diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md
index 31552a1be8..57f0913366 100644
--- a/docs/architecture.zh-CN.md
+++ b/docs/architecture.zh-CN.md
@@ -23,7 +23,7 @@
|---|---|---|---|
| `storage` | 统一 SQLite 存储(表族 / kstate / ckpt / GC) | [storage.zh-CN.md](./architecture/storage.zh-CN.md) · [EN](./architecture/storage.md) | ✅ |
| `pipeline` | 请求管道(handle / prepare-* / relay / inject) | [pipeline.zh-CN.md](./architecture/pipeline.zh-CN.md) · [EN](./architecture/pipeline.md) | ✅ |
-| `lanes` | 宿主车道(dsh / pi / opencode / codex / 裸代理 + lane-decisions) | [lanes.zh-CN.md](./architecture/lanes.zh-CN.md) · [EN](./architecture/lanes.md) | ✅ |
+| `lanes` | 宿主车道(dsh / pi / opencode / codex / 裸代理 + lane-decisions;Pi Anthropic 全量请求兼容) | [lanes.zh-CN.md](./architecture/lanes.zh-CN.md) · [EN](./architecture/lanes.md) | ✅ |
| `kernel` | 压缩内核(acp-kernel:折叠 / 摘要 / ref 账本) | [kernel.zh-CN.md](./architecture/kernel.zh-CN.md) · [EN](./architecture/kernel.md) | ✅ |
| `identity` | 会话与消息身份(session id / persona fork / msgid 通道) | [identity.zh-CN.md](./architecture/identity.zh-CN.md) · [EN](./architecture/identity.md) | ✅ |
| `fastpaths` | 快路径(增量车道 / v5 watermark / D-lane 快照渲染) | [fastpaths.zh-CN.md](./architecture/fastpaths.zh-CN.md) · [EN](./architecture/fastpaths.md) | ✅ |
diff --git a/docs/architecture/assets/lanes.en.png b/docs/architecture/assets/lanes.en.png
index 7d745fd1c6..fe642c37a3 100644
Binary files a/docs/architecture/assets/lanes.en.png and b/docs/architecture/assets/lanes.en.png differ
diff --git a/docs/architecture/assets/lanes.en.svg b/docs/architecture/assets/lanes.en.svg
index cb1ef417ac..9a58e1d423 100644
--- a/docs/architecture/assets/lanes.en.svg
+++ b/docs/architecture/assets/lanes.en.svg
@@ -2,4 +2,4 @@
-Module: host lanes (src/agent + src/server/lane-decisions)who carries the request in, how it is attributed, and which processing lane it takesHost plugins (per-host)dsh shim (anthropic divert)pi entry-walker (+ omp re-export)opencode V1/V2 transform hookscodex Responses-over-WebSocketclaude hook (lane token #5095)kimi / zcode native TOML laneseach: a -native bootstrap gate+ native-intercept fetch routingIdentity & attributionsession id: request header, verbatimper-element host msgid: envelope only,stripped at ingest (#4491/#5842)persona fingerprint (dsh, evidencepermitlist #1104) → |sub:<fp> forkattribution reports → panel (#3581)anonymous: prefix-affinity pfa-*(simhash chain #2265)lane-decisions.tssingle resolver (#3417)request shape × session sticky bind+ one row: foundation-lane hit(negative+positive pair, #3617)decides: incremental / v5 / D-lane/ legacy per requestprocessing lanesincremental plugin-turn lane(anthropic wire divert)v5 watermark fastpath (5% cohort)D-lane snapshot render (#3756)legacy full-resend path(default + safety net)One request = one lane, decided per request, sticky per session (upgrade-only). Lanes share the kernel and the storage; they differ only in how much of the wire work they skip.Launcher posture: bili <client> (launcher.ts) auto-proxies both schemes; plugin posture: host loads dist/agent/<entry>.js in-process (default inline for pi, #5428).
\ No newline at end of file
+Module: host lanes (src/agent + src/server/lane-decisions)who carries the request in, how it is attributed, and which processing lane it takesHost plugins (per-host)dsh shim (anthropic divert)pi entry-walker (+ omp re-export)opencode V1/V2 transform hookscodex Responses-over-WebSocketclaude hook (lane token #5095)kimi / zcode native TOML laneseach: a -native bootstrap gate+ native-intercept fetch routingPi Anthropic: session-local threads offfull requests → bili compressionIdentity & attributionsession id: request header, verbatimper-element host msgid: envelope only,stripped at ingest (#4491/#5842)persona fingerprint (dsh, evidencepermitlist #1104) → |sub:<fp> forkattribution reports → panel (#3581)anonymous: prefix-affinity pfa-*(simhash chain #2265)lane-decisions.tssingle resolver (#3417)request shape × session sticky bind+ one row: foundation-lane hit(negative+positive pair, #3617)decides: incremental / v5 / D-lane/ legacy per requestprocessing lanesincremental plugin-turn lane(anthropic wire divert)v5 watermark fastpath (5% cohort)D-lane snapshot render (#3756)legacy full-resend path(default + safety net)One request = one lane, decided per request, sticky per session (upgrade-only). Lanes share the kernel and the storage; they differ only in how much of the wire work they skip.Launcher posture: bili <client> (launcher.ts) auto-proxies both schemes; plugin posture: host loads dist/agent/<entry>.js in-process (default inline for pi, #5428).
\ No newline at end of file
diff --git a/docs/architecture/assets/lanes.zh-CN.png b/docs/architecture/assets/lanes.zh-CN.png
index 996aa91d4f..581f093a61 100644
Binary files a/docs/architecture/assets/lanes.zh-CN.png and b/docs/architecture/assets/lanes.zh-CN.png differ
diff --git a/docs/architecture/assets/lanes.zh-CN.svg b/docs/architecture/assets/lanes.zh-CN.svg
index d5a2e30ff5..b4236e1118 100644
--- a/docs/architecture/assets/lanes.zh-CN.svg
+++ b/docs/architecture/assets/lanes.zh-CN.svg
@@ -2,4 +2,4 @@
-模块:宿主车道(src/agent + src/server/lane-decisions)谁把请求带进来、如何归因、走哪条处理车道宿主插件(按宿主)dsh shim(anthropic divert)pi entry-walker(+ omp 复用)opencode V1/V2 transform 钩子codex Responses-over-WebSocketclaude hook(lane token #5095)kimi / zcode 原生 TOML 车道每个都有 -native 启动闸门+ native-intercept fetch 路由身份与归因session id:请求头、逐字逐元素宿主 msgid:只在信封、入站即剥(#4491/#5842)persona 指纹(dsh,证据白名单#1104)→ |sub:<fp> 分叉归因报告 → 面板(#3581)匿名:前缀亲和 pfa-*(simhash 链 #2265)lane-decisions.ts单一裁决器(#3417)请求形状 × 会话粘滞绑定+ 一行:底座车道命中(正负成对断言 #3617)逐请求决定:增量 / v5 / D-lane/ legacy处理车道增量 plugin-turn 车道(anthropic wire divert)v5 watermark 快路径(5%灰度)D-lane 快照渲染(#3756)legacy 全量重发路径(默认 + 兜底安全网)一个请求 = 一条车道:逐请求裁决、逐会话粘滞(只升不降)。各车道共享内核与存储,差别只在跳过多少 wire 工作。两种接入姿态:bili <client> 启动器(launcher.ts,自动代理双协议);插件姿态:宿主进程内加载 dist/agent/<entry>.js(pi 默认内联,#5428)。
\ No newline at end of file
+模块:宿主车道(src/agent + src/server/lane-decisions)谁把请求带进来、如何归因、走哪条处理车道宿主插件(按宿主)dsh shim(anthropic divert)pi entry-walker(+ omp 复用)opencode V1/V2 transform 钩子codex Responses-over-WebSocketclaude hook(lane token #5095)kimi / zcode 原生 TOML 车道每个都有 -native 启动闸门+ native-intercept fetch 路由Pi Anthropic:会话级关闭原生 threads全量请求 → bili 压缩身份与归因session id:请求头、逐字逐元素宿主 msgid:只在信封、入站即剥(#4491/#5842)persona 指纹(dsh,证据白名单#1104)→ |sub:<fp> 分叉归因报告 → 面板(#3581)匿名:前缀亲和 pfa-*(simhash 链 #2265)lane-decisions.ts单一裁决器(#3417)请求形状 × 会话粘滞绑定+ 一行:底座车道命中(正负成对断言 #3617)逐请求决定:增量 / v5 / D-lane/ legacy处理车道增量 plugin-turn 车道(anthropic wire divert)v5 watermark 快路径(5%灰度)D-lane 快照渲染(#3756)legacy 全量重发路径(默认 + 兜底安全网)一个请求 = 一条车道:逐请求裁决、逐会话粘滞(只升不降)。各车道共享内核与存储,差别只在跳过多少 wire 工作。两种接入姿态:bili <client> 启动器(launcher.ts,自动代理双协议);插件姿态:宿主进程内加载 dist/agent/<entry>.js(pi 默认内联,#5428)。
\ No newline at end of file
diff --git a/docs/architecture/lanes.md b/docs/architecture/lanes.md
index 88ddd6198f..0658840eaf 100644
--- a/docs/architecture/lanes.md
+++ b/docs/architecture/lanes.md
@@ -19,6 +19,8 @@ This module answers three questions per request: who carried it in (which host,
**Host plugins (per host).** dsh shim (diverts anthropic-wire turns, openai shapes keep full resend — #3433) · pi entry-walker (omp re-exports the same entries) · opencode V1/V2 transform hooks · codex Responses-over-WebSocket · claude hook (lane token, #5095) · kimi / zcode native TOML lanes. Each host lane has a `-native` bootstrap gate, and `native-intercept.ts` routes the host's fetch traffic to the proxy with attribution headers.
+**Pi Anthropic compatibility.** For Anthropic Messages models routed through bili, the Pi plugin sets session-local `compat.supportsMessageThreads=false` using the host's model API at session start, model selection, and before a turn (after native bootstrap). Other model compatibility settings and the current thinking level are preserved; the shared model catalog and user configuration are not rewritten. Pi sends full requests, so bili still applies its normal compression and tool pipeline. Native thread deltas are unsafe here: Pi fingerprints history before bili's transport rewrites it. This is compatibility negotiation, not a pre-thread compression implementation. OMP keeps its existing separate thread negotiation; unrouted models and the plugin opt-out are unchanged. Restoring native threads requires preparing compression before the host fingerprints the full request. The override remains on the selected session model until another selection replaces it; switching routing off does not mutate that snapshot back. An in-flight compatibility selection does not restore thinking into a different model chosen by another listener.
+
**Identity & attribution.** The session id comes from the request header verbatim (native stable ids preferred, #280). Anonymous traffic resolves via prefix affinity (`pfa-*`, first-writer provenance #2879, simhash chain #2265). The dsh persona fingerprint is an EVIDENCE PERMITLIST (#1104/#2156): only hosts proven to reuse one id across personas fork onto `|sub:` sessions; the first system seen under an id anchors the raw key, side requests never claim it (#2156/#2160). Broken-injection state is visible via `/__bili/status` `attribution` (#3581).
**The resolver.** `lane-decisions.ts` matches request shape × session sticky binding (+ one planned row for the #5643 foundation lane, negative+positive pair) and picks: incremental plugin-turn lane / v5 watermark / D-lane snapshot render / legacy full-resend.
diff --git a/docs/architecture/lanes.zh-CN.md b/docs/architecture/lanes.zh-CN.md
index 8ece744022..72a45852e9 100644
--- a/docs/architecture/lanes.zh-CN.md
+++ b/docs/architecture/lanes.zh-CN.md
@@ -19,6 +19,8 @@
**宿主插件(按宿主)。** dsh shim(divert anthropic-wire 回合;openai 形保持全量重发——#3433) · pi entry-walker(omp 复用同一批 entry) · opencode V1/V2 transform 钩子 · codex Responses-over-WebSocket · claude hook(lane token,#5095) · kimi / zcode 原生 TOML 车道。每个宿主车道都有 `-native` 启动闸门;`native-intercept.ts` 把宿主 fetch 流量带归因头路由到代理。
+**Pi Anthropic 兼容。** 对经 bili 路由的 Anthropic Messages 模型,Pi 插件在会话开始、模型选择和每回合开始前(原生启动完成后)通过宿主模型 API 设置会话级 `compat.supportsMessageThreads=false`。保留其他兼容设置与当前 thinking 等级,不重写共享模型目录或用户配置。Pi 发送全量请求,bili 仍执行正常压缩与工具流水线。原生 thread 增量在此不安全:Pi 计算历史指纹后,bili 传输层才改写历史。这是兼容协商,并非压缩前移实现。OMP 保留已有独立协商;未路由模型与插件关闭状态不变。恢复原生 threads 需要在宿主计算完整请求指纹之前完成压缩。兼容覆盖保留在已选会话模型上,直到下一次选择替换它;关闭路由不会反向修改该快照。若其他监听器选择了不同模型,进行中的兼容协商不会向该模型恢复 thinking 等级。
+
**身份与归因。** session id 逐字取自请求头(优先原生稳定 id,#280)。匿名流量走前缀亲和(`pfa-*`,首写者出处 #2879、simhash 链 #2265)。dsh persona 指纹是**证据白名单**(#1104/#2156):只有被证明「一个 id 复用给多个 persona」的宿主才分叉到 `|sub:` 会话;某 id 下首个 system 锚定原始键,side 请求永不锚定(#2156/#2160)。注入坏状态经 `/__bili/status` 的 `attribution` 字段可见(#3581)。
**裁决器。** `lane-decisions.ts` 匹配请求形状 × 会话粘滞绑定(外加 #5643 底座车道的一行,正负成对),逐请求选出:增量 plugin-turn / v5 水位 / D-lane 快照渲染 / legacy 全量重发。
diff --git a/reference/architecture.md b/reference/architecture.md
index 484cd70bf1..fde7d99e88 100644
--- a/reference/architecture.md
+++ b/reference/architecture.md
@@ -215,7 +215,7 @@ billion-context/
│ │ ├── opencode-v2.ts # opencode V2 plugin (ModelApi probe, #1569)
│ │ ├── opencode-native.ts # opencode native bootstrap gate
│ │ ├── opencode-legacy.ts # Legacy DCP hooks table
-│ │ ├── pi.ts # pi plugin factory (session derivation, #1333/#1362)
+│ │ ├── pi.ts # pi plugin factory (session derivation, #1333/#1362; routed Anthropic thread compatibility)
│ │ ├── pi-subagents.ts # Inlined acp_delegate sub-agent surface (markEmbedded wiring, #2186)
│ │ ├── pi-host-stub.ts # esbuild alias stub for @earendil-works/pi-coding-agent (→ ".pi" fallback, #2186)
│ │ ├── pi-native.ts # pi native bootstrap gate
diff --git a/src/agent/pi.ts b/src/agent/pi.ts
index 66cb84fadc..700ac49ac4 100644
--- a/src/agent/pi.ts
+++ b/src/agent/pi.ts
@@ -96,8 +96,10 @@ type ExtensionAPI = {
// catalog BEFORE extensions load, and its registerProvider — unlike
// pi's _refreshCurrentModelFromRegistry — never re-resolves the live
// session model, so the extension must re-pin it via setModel (see the
- // session_start handler below). Optional because pi hosts lack it.
+ // session_start handler below). Optional on older hosts.
setModel?: (model: Record & { baseUrl?: string }) => Promise | boolean | void;
+ getThinkingLevel?: () => string;
+ setThinkingLevel?: (level: string) => void;
// Persistent transcript output (rendered by TUI and web hosts like
// pi-web); notify() is a transient toast — only the fallback for hosts
// without sendMessage (issue #359).
@@ -1317,6 +1319,35 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
});
}
}
+ // Pi fingerprints the uncompressed history before our transport runs.
+ // A native continuation therefore cannot carry our rewritten history.
+ const useFullAnthropicRequests = async (ctx: Ctx): Promise => {
+ if (agent !== "pi" || typeof pi.setModel !== "function") return;
+ const model = ctx.model;
+ if (model?.api !== "anthropic-messages" || proxyBaseForCtx(ctx) === undefined) return;
+ const base = model.baseUrl;
+ if (typeof base !== "string" || !/^https?:\/\//i.test(base)) return;
+ if (!destinationRoutedThroughProxy(base) && !(nativeInterceptInstalled() && isModelApiUrl(`${base.replace(/\/+$/, "")}/v1/messages`))) return;
+ const compat = model.compat;
+ if (compat !== undefined && (compat === null || typeof compat !== "object" || Array.isArray(compat))) return;
+ const settings = compat as Record | undefined;
+ if (settings?.supportsMessageThreads === false) return;
+ const thinking = pi.getThinkingLevel?.();
+ const fullModel = { ...model, compat: { ...settings, supportsMessageThreads: false } };
+ try {
+ if (await pi.setModel(fullModel) === false) {
+ logHostEvent("warn", "[native-client]", "bili-plugin(pi): could not disable native Anthropic threads for this session (model authentication unavailable)");
+ }
+ } catch (err) {
+ logHostEvent("warn", "[native-client]", `bili-plugin(pi): native thread compatibility negotiation failed (${err instanceof Error ? err.message : String(err)})`);
+ } finally {
+ if (ctx.model === fullModel && thinking !== undefined && pi.getThinkingLevel?.() !== thinking) pi.setThinkingLevel?.(thinking);
+ }
+ };
+ if (agent === "pi") {
+ pi.on("session_start", (_event, ctx) => useFullAnthropicRequests(ctx));
+ pi.on("model_select", (_event, ctx) => useFullAnthropicRequests(ctx));
+ }
// Await tool registration in before_agent_start so cold-start native
// sessions register ACP tools BEFORE pi's _prepareRun freezes Turn 1's
// active tool loadout and system prompt. Without this,
@@ -1331,6 +1362,11 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
} catch (err) {
logHostEvent("error", "[native-client]", `bili-plugin(${agent}): tool registration failed (${err instanceof Error ? err.message : String(err)}) — riding wire mode for this turn`);
}
+ try {
+ await useFullAnthropicRequests(ctx);
+ } catch (err) {
+ logHostEvent("warn", "[native-client]", `bili-plugin(${agent}): native thread compatibility negotiation failed (${err instanceof Error ? err.message : String(err)})`);
+ }
});
pi.on("before_provider_headers", async (event, ctx) => {
try {
diff --git a/tests/pi-message-threads.test.ts b/tests/pi-message-threads.test.ts
new file mode 100644
index 0000000000..7f72f0a103
--- /dev/null
+++ b/tests/pi-message-threads.test.ts
@@ -0,0 +1,138 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createBiliPlugin, type Ctx, type ExtensionAPI } from "../src/agent/pi.ts";
+
+test("Pi routed Anthropic models use full requests without changing registry models or thinking", async () => {
+ const savedFetch = globalThis.fetch;
+ const keys = ["BILLION_CONTEXT_PROXY", "BILLION_CONTEXT_PLUGIN", "BILI_PROVIDER_REWRITES", "BILI_MITM_HOSTS"];
+ const saved = new Map(keys.map((key) => [key, process.env[key]]));
+ globalThis.fetch = async () => new Response("{}", { status: 404 });
+ delete process.env.BILLION_CONTEXT_PROXY;
+ delete process.env.BILI_PROVIDER_REWRITES;
+ delete process.env.BILI_MITM_HOSTS;
+ process.env.BILLION_CONTEXT_PLUGIN = "1";
+ try {
+ const handlers = new Map unknown>>();
+ const emit = async (name: string, ctx: Ctx): Promise => {
+ for (const handler of handlers.get(name) ?? []) await handler({} as never, ctx);
+ };
+ let thinking = "medium";
+ let selection: "ok" | "refuse" | "reject" | "redirect" = "ok";
+ const changes: Ctx["model"][] = [];
+ const registryModel = { id: "claude-test", provider: "anthropic", api: "anthropic-messages", baseUrl: "http://127.0.0.1:9999/bili/https://api.anthropic.com", contextWindow: 200000, compat: { supportsMessageThreads: true, supportsToolChoice: true } };
+ const ctx: Ctx = { model: registryModel };
+ const pi: ExtensionAPI = {
+ on: (name, handler) => { handlers.set(name, [...(handlers.get(name) ?? []), handler]); },
+ registerTool: () => {},
+ getThinkingLevel: () => thinking,
+ setThinkingLevel: (level) => { thinking = level; },
+ setModel: async (model) => {
+ if (selection === "refuse") return false;
+ if (selection === "reject") throw new Error("host selection failed");
+ assert.ok(changes.length < 10, "model_select does not recurse");
+ changes.push(model);
+ ctx.model = model;
+ thinking = "low";
+ await emit("model_select", ctx);
+ if (selection === "redirect") {
+ ctx.model = { ...registryModel, api: "openai-responses" };
+ thinking = "high";
+ }
+ return true;
+ },
+ };
+ createBiliPlugin("pi")(pi);
+ await emit("session_start", ctx);
+ assert.equal(changes.length, 1);
+ assert.equal(thinking, "medium");
+ assert.notEqual(ctx.model, registryModel);
+ assert.equal(registryModel.compat.supportsMessageThreads, true, "do not mutate shared catalog");
+ assert.deepEqual(ctx.model, { ...registryModel, compat: { ...registryModel.compat, supportsMessageThreads: false } });
+ await emit("model_select", ctx);
+ assert.equal(changes.length, 1, "already-disabled model is idempotent");
+ ctx.model = { ...registryModel, id: "another-claude", compat: undefined };
+ await emit("model_select", ctx);
+ assert.equal(changes.length, 2, "subsequent model choices receive the same compatibility override");
+ assert.equal(ctx.model.compat && (ctx.model.compat as Record).supportsMessageThreads, false);
+
+ const untouched = [
+ { ...registryModel, api: "openai-responses" },
+ { ...registryModel, api: "pi-virtual", baseUrl: "" },
+ { ...registryModel, baseUrl: "claude-bridge" },
+ { ...registryModel, baseUrl: "https://api.anthropic.com" },
+ { ...registryModel, compat: { supportsMessageThreads: false } },
+ { ...registryModel, compat: null },
+ { ...registryModel, compat: [] },
+ { ...registryModel, compat: 1 },
+ ];
+ for (const model of untouched) {
+ ctx.model = model;
+ await emit("model_select", ctx);
+ assert.equal(ctx.model, model);
+ assert.equal(changes.length, 2);
+ }
+ const flag = Symbol.for("billion-context.native-fetch-intercept");
+ const globals = globalThis as Record;
+ const oldFlag = globals[flag];
+ try {
+ globals[flag] = true;
+ process.env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:9999";
+ ctx.model = { ...registryModel, baseUrl: "https://api.anthropic.com" };
+ await emit("before_agent_start", ctx);
+ assert.equal(changes.length, 3, "cold native routing negotiates at turn start even when the tool manifest is unavailable");
+ assert.equal(thinking, "medium");
+ const overridden = ctx.model;
+ process.env.BILLION_CONTEXT_PLUGIN = "0";
+ await emit("model_select", ctx);
+ assert.equal(ctx.model, overridden, "session override remains until the next model selection; no catalog was mutated");
+ process.env.BILLION_CONTEXT_PLUGIN = "1";
+ delete process.env.BILLION_CONTEXT_PROXY;
+ ctx.model = { ...registryModel, baseUrl: "https://api.anthropic.com" };
+ await emit("model_select", ctx);
+ assert.equal(changes.length, 3, "stale interceptor flag without a live routing claim is insufficient");
+ process.env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:9999";
+ globals[flag] = false;
+ process.env.BILI_MITM_HOSTS = "api.anthropic.com";
+ await emit("model_select", ctx);
+ assert.equal(changes.length, 4, "MITM routing also negotiates");
+ } finally {
+ if (oldFlag === undefined) delete globals[flag];
+ else globals[flag] = oldFlag;
+ delete process.env.BILLION_CONTEXT_PROXY;
+ delete process.env.BILI_MITM_HOSTS;
+ }
+ ctx.model = registryModel;
+ selection = "refuse";
+ await emit("model_select", ctx);
+ assert.equal(ctx.model, registryModel, "refused selection leaves the active model untouched");
+ selection = "reject";
+ await emit("model_select", ctx);
+ assert.equal(ctx.model, registryModel, "rejected selection is caught and leaves the active model untouched");
+ selection = "redirect";
+ await emit("model_select", ctx);
+ assert.equal(ctx.model?.api, "openai-responses");
+ assert.equal(thinking, "high", "do not restore thinking into a model chosen by another listener");
+ selection = "ok";
+ const negotiatedCount = changes.length;
+ process.env.BILLION_CONTEXT_PLUGIN = "0";
+ ctx.model = registryModel;
+ await emit("model_select", ctx);
+ assert.equal(changes.length, negotiatedCount, "plugin kill switch keeps native threads untouched");
+ process.env.BILLION_CONTEXT_PLUGIN = "1";
+ const ompHandlers = new Map unknown>>();
+ createBiliPlugin("omp")({ ...pi, on: (name, handler) => { ompHandlers.set(name, [...(ompHandlers.get(name) ?? []), handler]); } });
+ assert.equal(ompHandlers.has("model_select"), false, "OMP keeps its existing separate negotiation");
+ const legacyHandlers = new Map unknown>>();
+ const oldPi: ExtensionAPI = { on: (name, handler) => { legacyHandlers.set(name, [...(legacyHandlers.get(name) ?? []), handler]); }, registerTool: () => {} };
+ assert.doesNotThrow(() => createBiliPlugin("pi")(oldPi), "older hosts without setModel still load");
+ ctx.model = registryModel;
+ for (const handler of legacyHandlers.get("model_select") ?? []) await handler({} as never, ctx);
+ assert.equal(ctx.model, registryModel, "older hosts safely skip compatibility negotiation");
+ } finally {
+ globalThis.fetch = savedFetch;
+ for (const [key, value] of saved) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+});