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
1 change: 1 addition & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ Environment variables take precedence over the config file. They are useful for
| `BILI_IMAGE_TOKEN_CAP` | Cap the per-image token estimate used by the preflight size gate and output clamp (#488/#496). By default an inline `data:` image counts as `base64 length / 4` tokens with **no cap** — correct for byte-billing relays, but a large over-estimate for pixel-tile upstreams (official Anthropic/OpenAI). For pixel-tile upstreams prefer [`imageBilling`](#imagebilling) (`"pixels"`, or `BILI_IMAGE_BILLING=pixels`) which charges real tile billing instead of capping the byte estimate; the cap still applies on top of both billing modes as a blanket ceiling. Unset = no cap (default). |
| `BILI_IMAGE_BILLING` | Override the image billing mode used by the preflight size gate and output clamp (#767): `pixels` or `bytes`. Live-read per request (no restart); beats the global `imageBilling` and every per-provider `providers.<url>.imageBilling`. Use `bytes` to force conservative billing on a route configured `"pixels"` (e.g. a byte-counting relay behind an OpenAI lookalike host), or `pixels` to enable tile billing process-wide without editing config. See [`imageBilling`](#imagebilling). |
| `BILI_PREFLIGHT_HOLD_MS` | Grace period (ms) before a long preflight compression starts holding the client with keep-alive bytes (default `30000`; see #568 / README "Preflight hold"). |
| `BILI_RECLAIM_FETCH_PATCH` | Set to `0` to disable the native-mode fetch self-heal re-arm (#1158). By default the native fetch intercept installs `globalThis.fetch` as a guarded accessor, so a third-party patch that re-installs `globalThis.fetch` (e.g. dsh-http-proxy's settings refresh writing its frozen pre-bili `originalFetch`) is re-chained as the downstream and model traffic keeps routing through bili. With `0` the classic direct install stays: a third-party re-arm then wins and bili stops seeing model traffic for the session. **Egress note:** while the guard holds, claimed model traffic is dispatched by the bili proxy itself — it no longer rides the third-party chain's egress (e.g. a SOCKS5 proxy configured in dsh-http-proxy; bili's own upstream proxying supports HTTP proxies only). If you need the third-party egress back, set `0` and configure the egress at bili's level (`"proxy": "http://…"`). |
| `BILI_CONFIG_FILE` | Override the config file path (point at any JSON file). |
| `ACP_PORT` / `PORT` | Override the listen port. |
| `ACP_HOST` | Override the listen host. |
Expand Down
1 change: 1 addition & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@
| `BILI_IMAGE_TOKEN_CAP` | 预检尺寸门与输出钳制用的单图 token 估算上限(#488/#496)。默认内联 `data:` 图片按 `base64 长度 / 4` 计 token、**无上限** —— 对字节计费 relay 正确,但对像素 tile 计费的官方上游(Anthropic/OpenAI)会严重高估(后者无论字节多少,每图约计 1.1K–1.6K token)。像素 tile 上游建议改用 [`imageBilling`](#imagebilling)(`"pixels"`,或 `BILI_IMAGE_BILLING=pixels`),按真实 tile 计费而非截断字节估算;该上限仍在两种计费模式之上作为统一天花板生效。不设置 = 无上限(默认)。 |
| `BILI_IMAGE_BILLING` | 覆盖预检尺寸门与输出钳制的图片计费模式(#767):`pixels` 或 `bytes`。每次请求实时读取(无需重启);优先于全局 `imageBilling` 与所有按 provider 的 `providers.<url>.imageBilling`。在配置为 `"pixels"` 的路由上强制保守计费用 `bytes`(例如 OpenAI 同形 host 后面的字节计数 relay),或不想改配置文件就全进程启用 tile 计费用 `pixels`。详见 [`imageBilling`](#imagebilling)。 |
| `BILI_PREFLIGHT_HOLD_MS` | 预压缩超过该宽限期(毫秒)后,代理提前提交响应并用保活字节挂住客户端(默认 `30000`;见 #568 / README「预压缩挂起」)。 |
| `BILI_RECLAIM_FETCH_PATCH` | 设为 `0` 关闭 native 模式 fetch 自愈重武装(#1158)。默认情况下 native fetch 拦截会把 `globalThis.fetch` 装成受保护的访问器:第三方补丁重新赋值 `globalThis.fetch` 时(如 dsh-http-proxy 的 settings 刷新用冻结的 pre-bili `originalFetch` 盲覆盖),会被接链为下游,模型流量继续经过 bili。设 `0` 则回到经典直装:第三方重装生效,bili 将看不到本会话的模型流量。**出口提示:** 自愈生效期间,被认领的模型流量由 bili 代理自身派发——不再走第三方链的出口(例如 dsh-http-proxy 里配置的 SOCKS5;bili 自身的上游代理仅支持 HTTP 形式)。若需要回退第三方出口,设 `0` 并在 bili 层配置出口(`"proxy": "http://…"`)。 |
| `BILI_CONFIG_FILE` | 覆盖配置文件路径(指向任意 JSON 文件)。 |
| `ACP_PORT` / `PORT` | 覆盖监听端口。 |
| `ACP_HOST` | 覆盖监听主机。 |
Expand Down
72 changes: 70 additions & 2 deletions src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ export interface NativeInterceptState {

const INTERCEPT_FLAG = "__biliNativeFetchIntercept";

/** #1158 escape hatch: `BILI_RECLAIM_FETCH_PATCH=0` keeps the classic direct
* install — a third-party re-arm (dsh-http-proxy refresh) then wins and
* bili stops seeing model traffic (documented degradation, visible instead
* of silently healed) for setups that NEED the third-party chain on top
* (e.g. a socks egress bili's upstream proxying does not support). */
function shouldReclaimFetchPatch(): boolean {
const raw = process.env.BILI_RECLAIM_FETCH_PATCH;
if (raw === undefined) return true;
return !/^(0|false|off|no)$/i.test(raw.trim());
}

/** #1158 self-heal: the property descriptor captured before we installed the
* guarded accessor, so _resetForTest can restore a plain writable data
* property. Undefined before the first install in a process. */
let preInstallDesc: PropertyDescriptor | undefined;

// Model-API endpoint suffixes across the wires bili proxies: Anthropic
// `/v1/messages`, OpenAI chat `/v1/chat/completions` (and legacy
// `/v1/completions`), Responses `/v1/responses`, Mistral
Expand Down Expand Up @@ -286,14 +302,18 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea
const g = globalThis as Record<string, unknown>;
if (g[INTERCEPT_FLAG] === true) return false;
const orig = globalThis.fetch;
// Shared across every re-armed chain link (a re-arm replaces the chain
// top but must not forget what this process already learned).
let warned = false;
// Origins verified dead-and-replaced during a runtime recovery (#1130).
// Launcher settings overlays bake the origin into request URLs, so after
// a replace we must reroute those pre-baked URLs before they touch the
// network again. Only ever contains origins we ourselves observed dying.
const replacedOrigins = new Set<string>();

const patched = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
const makeChain = (downstream: typeof globalThis.fetch) => {
const patched = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
const orig = downstream;
const url = fetchUrlOf(input);
if (url === undefined) return orig(input, init);
// Rebuild a Request-object input against a different target. A
Expand Down Expand Up @@ -446,7 +466,50 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea
}
};

globalThis.fetch = patched as typeof globalThis.fetch;
return patched as typeof globalThis.fetch;
};

// #1158 self-heal re-arm: dsh-http-proxy (0.1.3) re-applies by writing its
// module-load-time frozen originalFetch over globalThis.fetch, silently
// un-routing every model request away from bili while the session keeps
// working (observed live on Windows). Guard the property instead of
// trusting the assignment to survive: any third-party install becomes
// our downstream and model traffic keeps routing through bili.
const desc = Object.getOwnPropertyDescriptor(globalThis, "fetch");
let rearmCount = 0;
const REARM_LIMIT = 16;
const guard = desc === undefined || desc.configurable;
let top = makeChain(orig);
if (guard && shouldReclaimFetchPatch()) {
preInstallDesc = desc;
Object.defineProperty(globalThis, "fetch", {
configurable: true,
enumerable: desc?.enumerable ?? true,
get: () => top,
set: (v: unknown) => {
if (typeof v !== "function" || v === top) return;
// Visibility (#1158): an evict attempt used to be silent —
// log it so "un-routed by a third party" is diagnosable even
// when the heal itself is not wanted/limited away.
if (rearmCount < REARM_LIMIT) {
console.warn(`[bili-native] third-party globalThis.fetch install detected (#1158) — re-chaining as downstream (evict attempt ${rearmCount + 1})`);
}
if (rearmCount >= REARM_LIMIT) {
// A fighting patch (two self-healers) would loop forever;
// past the limit stop guarding and let the winner stand.
top = v as typeof globalThis.fetch;
return;
}
rearmCount += 1;
top = makeChain(v as typeof globalThis.fetch);
},
});
} else {
// Non-configurable host property or reclaim disabled
// (BILI_RECLAIM_FETCH_PATCH=0): keep the classic direct install
// (no guard, the old behavior).
globalThis.fetch = top;
}
g[INTERCEPT_FLAG] = true;
return true;
}
Expand All @@ -456,4 +519,9 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea
export function _resetForTest(): void {
const g = globalThis as Record<string, unknown>;
delete g[INTERCEPT_FLAG];
if (preInstallDesc !== undefined) {
const d = preInstallDesc;
preInstallDesc = undefined;
Object.defineProperty(globalThis, "fetch", { ...d, configurable: true });
}
}
111 changes: 111 additions & 0 deletions tests/native-intercept-selfheal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from "node:assert/strict";
import test from "node:test";
import { installNativeFetchIntercept, type NativeInterceptState } from "../src/agent/native-intercept.js";

function fakeFetch(sink: string[]) {
return (async (input: RequestInfo | URL, _init?: RequestInit) => {
sink.push(typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url);
return new Response("{}", { status: 200 });
}) as typeof fetch;
}

async function withHeal<T>(fn: (ctx: { sink: string[]; rearm: (v: typeof fetch) => void; fetch: () => typeof fetch }) => Promise<T>): Promise<{ sink: string[]; result: T }> {
const saved = globalThis.fetch;
const sink: string[] = [];
const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") };
const { _resetForTest } = await import("../src/agent/native-intercept.js");
_resetForTest();
globalThis.fetch = fakeFetch(sink);
try {
assert.equal(installNativeFetchIntercept(state), true);
const result = await fn({
sink,
rearm: (v) => {
globalThis.fetch = v;
},
fetch: () => globalThis.fetch,
});
return { sink, result };
} finally {
globalThis.fetch = saved;
_resetForTest();
}
}

test("#1158 self-heal: third-party reset to a frozen bare fetch re-chains and keeps routing through bili", async () => {
const bareSink: string[] = [];
const { sink } = await withHeal(async ({ rearm, fetch }) => {
rearm(fakeFetch(bareSink));
const res = await fetch()("http://127.0.0.1:8199/v1/messages", { method: "POST" });
assert.equal(res.status, 200);
});
assert.deepEqual(bareSink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]);
assert.deepEqual(sink, []);
});

test("#1158 self-heal: third-party wrapper becomes the downstream (dsh-http-proxy apply shape)", async () => {
const downstreamSeen: string[] = [];
const { sink } = await withHeal(async ({ rearm, fetch }) => {
const wrapper = (async (input: RequestInfo | URL, init?: RequestInit) => {
downstreamSeen.push(typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url);
return fakeFetch([])(input, init);
}) as typeof fetch;
rearm(wrapper);
const res = await fetch()("http://127.0.0.1:8199/v1/messages");
assert.equal(res.status, 200);
// Non-model URL still passes through to the third-party wrapper untouched.
await fetch()("https://registry.npmjs.org/billion-context");
});
assert.deepEqual(downstreamSeen, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages", "https://registry.npmjs.org/billion-context"]);
assert.deepEqual(sink, []);
assert.equal(downstreamSeen.length, 2);
});

test("#1158 self-heal: guarded property is transparent when nobody fights it", async () => {
const { sink } = await withHeal(async ({ fetch }) => {
const res = await fetch()("http://127.0.0.1:8199/v1/messages");
assert.equal(res.status, 200);
// A re-read of the global yields a stable callable (accessor works).
assert.equal(typeof fetch(), "function");
});
assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]);
});

test("#1158 self-heal: non-function and self writes are ignored by the guard", async () => {
const { sink } = await withHeal(async ({ rearm, fetch }) => {
rearm(undefined as unknown as typeof fetch);
const mine = fetch();
rearm(mine);
const res = await mine("http://127.0.0.1:8199/v1/messages");
assert.equal(res.status, 200);
});
assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]);
});

test("#1158 escape hatch: BILI_RECLAIM_FETCH_PATCH=0 keeps the classic direct install", async () => {
process.env.BILI_RECLAIM_FETCH_PATCH = "0";
try {
const saved = globalThis.fetch;
const { _resetForTest } = await import("../src/agent/native-intercept.js");
_resetForTest();
const sink: string[] = [];
globalThis.fetch = fakeFetch(sink);
const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") };
try {
assert.equal(installNativeFetchIntercept(state), true);
// A plain writable data property again (no accessor guard).
assert.equal(Object.getOwnPropertyDescriptor(globalThis, "fetch")?.writable, true);
const thirdParty = fakeFetch([]);
globalThis.fetch = thirdParty;
// The third party wins: direct send, no bili rewrite.
assert.equal(globalThis.fetch, thirdParty);
const res = await globalThis.fetch("http://127.0.0.1:8199/v1/messages");
assert.equal(res.status, 200);
} finally {
globalThis.fetch = saved;
_resetForTest();
}
} finally {
delete process.env.BILI_RECLAIM_FETCH_PATCH;
}
});
Loading