Skip to content
Merged
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,18 @@ This failure mode is now loud instead of silent:

To actually compress such a client: add its model domain to `"mitm".domains` in `billion-context.json` (e.g. `"mitm": { "domains": ["copilot.tencent.com"] }`) or via `BILI_MITM_DOMAINS`, restart bili, and make the client trust bili's root CA (`NODE_EXTRA_CA_CERTS=~/.local/share/billion-context/ca/root-ca.pem` for Node-based clients, or the client's own CA-path setting). The `/bili/` prefix trick does not apply here — there is no URL to change. Details: [CONFIGURATION.md → MITM](CONFIGURATION.md#mitm-transparent-proxy-login-clients).

### An unrecognized endpoint goes direct and nothing compresses (#1290)

bili only compresses requests whose path matches a known wire protocol (`/chat/completions`, `/llm_raw_chat`, `/v1/messages`, `/responses`, …). A request to any other path — e.g. a third-party plugin's **custom wire** such as Command Code's Go plan posting to `/alpha/generate` — is relayed byte-for-byte and **never compressed**. There is no config seam to declare an arbitrary new wire today; adding one is a separate feature, not a switch you can flip.

That outcome is now loud instead of silent (#1290):

- the client-side fetch hook logs each distinct unrouted endpoint once per process (`…is not a recognized model endpoint, so bili did not route it through the proxy…`);
- `unrecognizedPaths` (per-path counts) in `curl -s http://localhost:8787/__bili/stats` (loopback-only);
- an `UNRECOGNIZED PATHS (instance-level)` section in `acp_status` output while such requests exist.

If you expected compression at such an endpoint, use the provider's standard protocol endpoint instead (Command Code's Provider plan posts to `/provider/v1/chat/completions`, which bili does compress); a genuinely custom wire needs its own support.

## OpenCode

One bundled plugin serves **both** OpenCode generations: the agent file keeps
Expand Down
12 changes: 12 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,18 @@ fork 继承同一面)。按设计保持 launcher-only。

要真正压缩这类客户端:把它的模型域名加进 `billion-context.json` 的 `"mitm".domains`(如 `"mitm": { "domains": ["copilot.tencent.com"] }`)或环境变量 `BILI_MITM_DOMAINS`,重启 bili,并让客户端信任 bili 的根 CA(Node 系客户端用 `NODE_EXTRA_CA_CERTS=~/.local/share/billion-context/ca/root-ca.pem`,有 CA 路径设置的用其设置)。`/bili/` 前缀方案在这里不适用——没有 URL 可改。详见 [CONFIGURATION.zh-CN.md → MITM](CONFIGURATION.zh-CN.md#mitm-透明代理登录客户端)。

### 未识别的端点直连、什么都不压缩(#1290)

bili 只压缩路径匹配已知 wire 协议(`/chat/completions`、`/llm_raw_chat`、`/v1/messages`、`/responses`……)的请求。发往其它路径的请求——例如第三方插件的**自定义 wire**(Command Code 的 Go 套餐发 `POST /alpha/generate`)——会逐字节中继,**永不压缩**。目前没有任何配置口可以声明一种任意新 wire;那是一项独立功能,不是一个能打开的开关。

这个结果现在不再静默(#1290):

- 客户端侧 fetch 钩子对每个不同的未路由端点每进程记一次日志(`…is not a recognized model endpoint, so bili did not route it through the proxy…`);
- `curl -s http://localhost:8787/__bili/stats` 输出 `unrecognizedPaths`(按路径计数,仅 loopback);
- 存在此类请求时,`acp_status` 输出会多一节 `UNRECOGNIZED PATHS (instance-level)`。

如果你期望这类端点被压缩,改用 provider 的标准协议端点(Command Code 的 Provider 套餐发 `/provider/v1/chat/completions`,bili 能正常压缩);真正的自定义 wire 需要单独的支持。

## OpenCode

同一个内置插件同时服务两代 OpenCode:agent 文件同时保留 V1 `server()` 与 V2 `setup()` 导出 —— ≥ 1.18.29 的 1.x 宿主加载 V1 形状,2.x 宿主加载 V2 `setup()`。独立扩展 [`opencode-acp`](https://github.com/ranxianglei/opencode-acp) 仅支持 V1,在 2.x 下**不加载** —— 对 OpenCode 2.x,**billion-context 是推荐的上下文管理方案**。以下均在 `@opencode/cli` 2.0.3 上端到端验证过(V1 泳道:1.14.46 与 1.18.31)。
Expand Down
14 changes: 14 additions & 0 deletions src/acp-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type CoreMessage,
} from "acp-kernel";
import { getBlindTunnelStats } from "./mitm.js";
import { getUnrecognizedPathStats } from "./server/observability.js";
import { ccrEnabled, contentStoreOf } from "./store.js";
import { coveredRefSpan } from "./decompress-shared.js";
import { preCompactionArchiveOf, type Session } from "./session.js";
Expand Down Expand Up @@ -129,5 +130,18 @@ export function handleAcpStatus(args: Record<string, unknown>, ctx: AcpStatusCtx
extra.push("");
extra.push(`UNDECRYPTED TRAFFIC (instance-level): ${blind.total} CONNECT tunnel(s) to host(s) outside the MITM whitelist were blind-relayed since instance start — that traffic was never decrypted, so it never entered any session and CANNOT be compressed (${hosts}). To compress such a client: add its model domain to "mitm".domains in billion-context.json, restart bili, and make the client trust bili's root CA. Exact counts: GET /__bili/stats → blindTunnels.`);
}
const unrec = getUnrecognizedPathStats();
if (unrec.total > 0) {
// #1290: requests whose path matched no known protocol were relayed
// byte-for-byte and never entered a session — a second reason "no
// compressed blocks" can mean misrouting rather than a short chat.
const top = Object.entries(unrec.paths)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([p, n]) => `${p}×${n}`)
.join(", ");
extra.push("");
extra.push(`UNRECOGNIZED PATHS (instance-level): ${unrec.total} request(s) to ${Object.keys(unrec.paths).length} path(s) matched no known protocol (/chat/completions, /llm_raw_chat, /v1/messages, /responses, …) since instance start — they were relayed byte-for-byte and CANNOT be compressed (${top}). If you expected compression here, that endpoint's path is not in bili's protocol table. Exact counts: GET /__bili/stats → unrecognizedPaths.`);
}
return extra.length > 0 ? `${base}\n${extra.join("\n")}` : base;
}
24 changes: 24 additions & 0 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,30 @@ export function apply(ctx: PluginContext): void {
return false;
};

// #1290: the isModelApiUrl gate (native-intercept) returns BEFORE the
// takeover gate above, so a URL that is not a recognized model endpoint
// (e.g. a third-party plugin's custom wire such as commandcode's
// POST /alpha/generate) went direct with ZERO signal — contradicting the
// #1158 promise. Surface each distinct unrouted endpoint once per process
// through the durable channel GUI hosts need (persistClientEvent), bounded
// like gateRefusals above.
const unroutedEndpoints = new Set<string>();
state.onUnroutedModelUrl = (rawUrl) => {
let key: string;
try {
const u = new URL(rawUrl);
key = `${u.origin}${u.pathname}`;
} catch {
key = rawUrl.split("?")[0];
}
if (unroutedEndpoints.has(key)) return;
if (unroutedEndpoints.size >= 256) return;
unroutedEndpoints.add(key);
const line = `bili-native-dsh: request sent DIRECT (uncompressed) — ${key} is not a recognized model endpoint, so bili did not route it through the proxy. bili only compresses known protocol paths (/chat/completions, /v1/messages, /responses, …); a custom-wire endpoint needs its own support.`;
console.error(line);
persistClientEvent(line);
};

state.headersFor = (_url) => {
maybeRetry(ctx);
if (!register.toolsReady) return undefined;
Expand Down
27 changes: 26 additions & 1 deletion src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ export interface NativeInterceptState {
readyTimeoutMs?: number;
/** Test/observability hook: every dispatched decision. */
onDispatch?: (url: string, action: "rewrite" | "direct" | "self" | "retry") => void;
/** #1290: observability hook — fired for every request the fetch patch lets
* through WITHOUT routing because its URL is not a recognized model endpoint
* (isModelApiUrl miss). Such requests never reach a bili proxy, so without
* this their "went direct (uncompressed)" outcome was completely silent —
* #1158's logging promise only covered the attribution gate below. Called
* per request; hosts dedup once-per-process-per-endpoint like takeoverGate.
* Undefined hosts stay silent. */
onUnroutedModelUrl?: (url: string) => void;
}

const INTERCEPT_FLAG = "__biliNativeFetchIntercept";
Expand Down Expand Up @@ -97,6 +105,20 @@ export function isModelApiUrl(url: string): boolean {
}
}

/** True when the URL addresses bili's own control plane (`/__bili/*`,
* `/__acp/*`, or a `/bili/<protocol>/<url>` tunnel) — expected direct
* traffic, not an unrecognized endpoint (#1290): reporting it as "not a
* recognized model endpoint" would flag bili's own requests. */
function isBiliControlUrl(url: string): boolean {
if (url.includes("/__bili/") || url.includes("/__acp/")) return true;
try {
const segments = new URL(url).pathname.split("/").filter((s) => s.length > 0);
return segments[0] === "bili";
} catch {
return false;
}
}

/** A URL already routed by a bili proxy in `/bili/` rewrite form
* (`${proxy}/bili/${upstream}`): returns the embedded upstream URL when it
* is model-API shaped, else undefined. The launcher's settings overlay
Expand Down Expand Up @@ -399,7 +421,10 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea
return orig(makeTarget(routedTarget), init);
}
}
if (!isModelApiUrl(url)) return orig(input, init);
if (!isModelApiUrl(url)) {
if (!isBiliControlUrl(url)) state.onUnroutedModelUrl?.(url);
return orig(input, init);
}
// #1117: URL shape alone cannot claim a request — every model call in
// the process hits the same endpoints. When the host supplies an
// attribution gate, an unattributed caller keeps its original URL and
Expand Down
6 changes: 3 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ import { dumpRejectedBody } from "./error-dump.js";
import { decodeRequestBody, DecompressedTooLargeError } from "./content-encoding.js";
import { applyCompatRoles, applyCompatRolesJson, detectRoleRejection, detectSystemPlacementError, resolveCompatRoles, type CompatRoles } from "./compat-roles.js";
import { applyOutputSteering, applyOutputSteeringJson } from "./output-steering.js";
import { bodyDumpEnabled, isModelDiscoveryPath, logDumpFailure, logUnrecognizedPath } from "./server/observability.js";
import { bodyDumpEnabled, getUnrecognizedPathStats, isModelDiscoveryPath, logDumpFailure, logUnrecognizedPath } from "./server/observability.js";
import { BILI_HOP_HEADER, anthropicBetaContextWindow, LAUNCHER_MODEL_WINDOWS, LAUNCHER_MODEL_MAX_OUTPUTS, launcherContextWindow, launcherMaxOutput, parseLauncherModelWindows, windowSourceLogged } from "./server/context-window.js";
import { buildForwardHeaders, connectionNamedHeaders, NO_IDENTITY_MESSAGE, RESPONSE_ONLY_STRIP_HEADERS, safeSessionId, UPSTREAM_HOP_HEADERS } from "./server/headers.js";
import { isSideRequest, outputBudgetField, restoreOutputBudget, SIDE_REQUEST_MAX_TOKENS, sideRequestGuard } from "./server/side-request.js";
Expand Down Expand Up @@ -5246,7 +5246,7 @@ function sendStats(res: http.ServerResponse): void {
restored: s.restored === true,
}));
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ sessions, blindTunnels: getBlindTunnelStats() }, null, 2));
res.end(JSON.stringify({ sessions, blindTunnels: getBlindTunnelStats(), unrecognizedPaths: getUnrecognizedPathStats() }, null, 2));
}

/** Stale-install state for the web UI badge (#811): whether the on-disk
Expand Down Expand Up @@ -5329,7 +5329,7 @@ function logMsg(opts: ProxyOptions, level: string, msg: string): void {
loggerLog(level, msg);
}

export { logDumpFailure, logUnrecognizedPath } from "./server/observability.js";
export { getUnrecognizedPathStats, logDumpFailure, logUnrecognizedPath } from "./server/observability.js";
export { BILI_HOP_HEADER, parseLauncherModelWindows, anthropicBetaContextWindow } from "./server/context-window.js";
export { isSideRequest, outputBudgetField, restoreOutputBudget, sideRequestGuard, type OutputBudgetField } from "./server/side-request.js";
export { countSystemAndToolsTokens, estimateInputTokens, estimateWireOverhead, clampOutputBudget, emergencyNudge } from "./server/budget.js";
14 changes: 14 additions & 0 deletions src/server/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ export function logUnrecognizedPath(log: (level: string, msg: string) => void, u
}
}

// #1290: instance-level view of the map above — surfaced at /__bili/stats
// (unrecognizedPaths) and in the /acp status report so "this path never got
// compressed" is visible in a status face, not just 3 transient stderr warns.
export type UnrecognizedPathStats = { total: number; paths: Record<string, number> };
export function getUnrecognizedPathStats(): UnrecognizedPathStats {
const paths: Record<string, number> = {};
let total = 0;
for (const [path, n] of unrecognizedPathCounts) {
paths[path] = n;
total += n;
}
return { total, paths };
}

// Model-enumeration endpoints clients probe at startup (omp's openai-models-list
// discovery). Expected passthroughs, not unknown protocols — #393: exempt from
// the warn-level "unrecognized path" log.
Expand Down
16 changes: 15 additions & 1 deletion tests/dump-observability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import assert from "node:assert/strict";
process.env.NODE_ENV = "test";

import { setLogCapture } from "../src/logger.ts";
import { logDumpFailure, logUnrecognizedPath } from "../src/server.ts";
import { getUnrecognizedPathStats, logDumpFailure, logUnrecognizedPath } from "../src/server.ts";
import { maskUrlsInText } from "../src/log-mask.ts";

interface Line { level: string; msg: string; }

Expand Down Expand Up @@ -68,3 +69,16 @@ test("logDumpFailure: first failure logs, repeat suppressed, re-logs after windo
assert.equal(lines.length, 2);
assert.ok(lines[1].msg.includes("total 3x"));
});

// #1290: unrecognized paths were only visible as 3 transient stderr warns —
// expose the per-path counts so /__bili/stats and the /acp report can surface them.
test("getUnrecognizedPathStats: exposes per-path counts for /__bili/stats (#1290)", () => {
const url = "https://cc-stats-1290.example/alpha/generate?x=1";
const key = maskUrlsInText(url.split("?")[0]);
const before = getUnrecognizedPathStats();
const base = before.paths[key] ?? 0;
for (let i = 0; i < 5; i++) logUnrecognizedPath(() => {}, url);
const after = getUnrecognizedPathStats();
assert.equal(after.paths[key], base + 5, "counted under the masked path key");
assert.ok(after.total >= 5);
});
24 changes: 24 additions & 0 deletions tests/native-intercept.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,30 @@ test("install: leaves non-model URLs untouched", async () => {
assert.deepEqual(sink, ["https://registry.npmjs.org/billion-context", "http://127.0.0.1:40001/__bili/plugin/manifest"]);
});

test("install: non-model-API URLs fire onUnroutedModelUrl so direct sends are visible (#1290)", async () => {
const unrouted: string[] = [];
const state: NativeInterceptState = {
origin: "http://127.0.0.1:40001",
ready: Promise.resolve("http://127.0.0.1:40001"),
onUnroutedModelUrl: (u) => { unrouted.push(u); },
};
const { sink } = await withPatch(state, async (fetch) => {
// A third-party plugin's custom wire (commandcode's Go plan) — not a
// recognized model endpoint, so it goes direct AND is reported.
await fetch("https://api.commandcode.example/alpha/generate");
await fetch("https://api.commandcode.example/alpha/generate");
// A real model endpoint — routed, never reported as unrouted.
await fetch("http://127.0.0.1:8199/v1/messages");
// Bili's own control plane — direct by design, never reported either.
await fetch("http://127.0.0.1:40001/__bili/plugin/manifest");
await fetch("http://127.0.0.1:40001/bili/openai/http://127.0.0.1:9/alpha/generate");
});
assert.ok(sink.includes("https://api.commandcode.example/alpha/generate"), "custom wire sent direct");
assert.ok(sink.includes("http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"), "model endpoint routed");
assert.equal(unrouted.length, 2, "hook fires per unrouted request (host dedups)");
for (const u of unrouted) assert.ok(u.endsWith("/alpha/generate"), `unexpected unrouted: ${u}`);
});

test("install: proxy-origin URLs are never re-proxied (self guard)", async () => {
const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") };
const { sink } = await withPatch(state, async (fetch) => {
Expand Down
Loading