Skip to content
Open
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
18 changes: 16 additions & 2 deletions docs/clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -444,8 +444,22 @@ two small node scripts that do the work around the client:
exact port instead (strict-port: a squatter is refused loudly, no hop).
`BILI_ZCODE_ROUTE`
(`plans`/`none`) is a compat escape hatch, and `BILI_ZCODE_SIGNING_FIXED=1`
flips the #1621 skips off once a ZCode build ships the signing fix.
- **Watchdog & lifecycle:** the MCP child probes the proxy every 30 s. In
flips the #1621 skips off once a ZCode build ships the signing fix.
- **Built-in account bypass (#4692):** the z.ai **built-in** account connects through
`ZAI_BUSINESS_BASE_URL`, an env var that lives in the ZCode MAIN process and never
lands in the provider store — so native routing (which rewrites only that store) has
no target for it, and its model traffic runs **direct / uncompressed**. A hook/MCP
child cannot rewrite the parent's env (the same wall that keeps codex's login provider
out of reach, #1660/#403), and there is no config-file seam for this surface, so it
cannot be routed natively. bili now logs a loud line at session start whenever it
detects a live `ZAI_BUSINESS_BASE_URL` past loopback / any `/bili/` wrapper, so going
blind on it is no longer silent. The only in-proxy path is cert-MITM (GUI Settings →
Network: HTTP proxy + root CA), which intercepts below the URL layer regardless of how
the base URL is derived — confirm on your build that the built-in account's traffic
actually rides that proxy setting. Second layer: even once in, zai-series coding-plan
model traffic still trips the #661 anti-fraud wall (working-but-uncompressed,
#4593/#4610), so this entry does not buy compression for that family.
- **Watchdog & lifecycle:** the MCP child probes the proxy every 30 s. In
attach mode it waits forever (it never touches a user-owned proxy); in spawn
mode a dead proxy is respawned and the routing rewritten to the new origin.
If recovery fails, the managed rewrite is removed so traffic degrades back
Expand Down
1 change: 1 addition & 0 deletions docs/clients.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ fork 继承同一面;Antigravity 自带用户插件系统 —— `plugins/<name>
- **环回目标(#809):** http 环回 `baseURL`(localhost / 127.x.x.x / ::1)永不二次代理 —— 包装它会把 bili 叠在自己或你自己的本地中继上。
- **`direct` 豁免:** `providers` 表(以上游 URL 为键,见 configuration.zh-CN.md)里声明 `"direct": true` 的路由保持直连 —— 任何 lane 都能遵守的同一套豁免机制。
通道把代理拉在自管端口区(#1660):基准口 `18787`,每 lane 粘性记录(自动跟随历史上的 +1 阶梯漂移),碰撞由子进程 +1 阶梯解决,漂移时共享 store 改写到存活 origin —— 即使没有交接,包装也能跨会话重启存活。`BILI_ZCODE_PORT` 钉死一个确切端口(严格模式:占用者被大声拒绝,不跳口)。`BILI_ZCODE_ROUTE`(`plans`/`none`)是兼容逃生舱;`BILI_ZCODE_SIGNING_FIXED=1` 在 ZCode 发布签名修复后关掉 #1621 跳过。
- **内置账号绕过(#4692):** z.ai **内置**账号经 `ZAI_BUSINESS_BASE_URL` 连接 —— 这是活在 ZCode **主进程**里的环境变量,从不落进 provider store。原生路由只改写那个 store,对它没有目标可动,所以它的模型流量**直连 / 不压缩**。hook/MCP 子进程改不了父进程的 env(和 codex login provider 够不着是同一堵墙,#1660/#403),这个面也没有 config-file seam,所以**无法被原生路由**。bili 现在会在会话启动时,只要检测到活的 `ZAI_BUSINESS_BASE_URL`(指向 loopback 之外、且不是 `/bili/` wrapper)就响亮打一行日志,因此在这个面上失明不再静默。唯一能进代理的路径是 cert-MITM(GUI 设置 → Network:HTTP proxy + root CA),它在 URL 层之下拦截、与 base URL 怎么派生无关 —— 请在你的 build 上确认内置账号的流量确实走那个 proxy 设置。第二层:即便进了,zai 系 coding-plan 模型流量仍会撞上 #661 反欺诈墙(working-but-uncompressed,#4593/#4610),所以这个入口不为该系列买到压缩。
- **看门狗与生命周期:** MCP 子进程每 30 s 探测一次代理。attach 模式下永远等待(绝不碰用户自己的代理);spawn 模式下代理死亡则重新拉起并把路由改写到新 origin。恢复失败时移除受管改写,让流量退回直连上游而不是打到死端口。会话结束时 ZCode 杀掉 MCP 子进程,父进程 pid 看门狗随之收掉拉起的代理;MCP 子进程退出前(SIGTERM/SIGINT/正常退出)在锁下交接:若共享 provider store 仍指向它自己的代理,优先改写到另一个存活兼容实例,没有则移除受管改写退回直连(#1623)——实例死后共享配置不留死端口。看门狗每个 tick 同时检查共享 store:若残留着其他实例的死端口(硬杀场景,上述交接没跑成——如 Windows TerminateProcess 跳过 JS handler),接管修复(优先改到存活实例,否则回退直连);只在 store 指向死端口时动手,绝不从存活实例手里抢路由。多个并发会话共享第一个拉起的代理;它消失后其余会话自动重新拉起并改路。边界:ZCode 按会话缓存 provider baseURL,上述修复只对「之后的新读取」(新会话/新查询)生效,在途会话仍会重试缓存的旧端口直到重读;要结构性规避,把 `BILLION_CONTEXT_PROXY` 钉到一个常驻代理(`bili start`)让所有会话 attach 上去(attach 模式绝不碰用户自己的代理)。
- **已知局限:** ZCode 的反欺诈指纹(#661)作用于 `zcode.z.ai` 登录流量的 MITM 重建 body —— 原生模式不碰那个面(模型流量走 provider store,不走 GUI 代理);若你同时使用 GUI 代理/MITM 配置,请保留 `"mitm://zcode.z.ai": { "passthrough": true }` 路由。v3.14+ 构建上,coding-plan 账号的 ClientRequestSigningV4 在模型创建阶段拒绝非 HTTPS origin,且其握手路径只从 origin 派生(丢弃任何 /bili/ 前缀),因此 /bili/ 包装的 baseURL 会以 "Client signing handshake requires HTTPS." 失败(#1621)。该冲突硬编码在 ZCode 侧,原生模式把这些账号**逐条跳过** —— 记录原因、这些账号保持直连;在这些账号上请用 GUI 证书 MITM 配置获得压缩能力,直到 ZCode 发布签名修复,届时设 `BILI_ZCODE_SIGNING_FIXED=1` 即可恢复路由。默认 `route:"all"` 下只有这些账号被跳过 —— store 上其余 provider 继续路由;整体退场(路由全关)只在 `route:"plans"` 下发生,因为那里 plan 账号本身就是签名账号。pre-3.14 legacy-store 客户端不受影响。`BILLION_CONTEXT_PROXY` 已设置(attach 模式管着代理)或定义了 `BILI_PROVIDER_REWRITES` 时插件整体退场。退出开关:`BILI_NATIVE_ZCODE=0`。

Expand Down
5 changes: 4 additions & 1 deletion src/zcode/bootstrap-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { resolveProxyOrigin } from "../mcp.js";
import { reportRuntimeInfo, runSessionStartHook } from "../agent/shared.js";
import { planNativeZcode, routeZcodeConfig, waitForProxyHealthy, zcodePolicyFromEnv } from "./native.js";
import { defaultLog, detectZcodeBuiltinAccount, planNativeZcode, reportZcodeBuiltinAccount, routeZcodeConfig, waitForProxyHealthy, zcodePolicyFromEnv } from "./native.js";

const HOOK_HEALTH_DEADLINE_MS = 4000;

Expand Down Expand Up @@ -41,6 +41,9 @@ export async function main(): Promise<void> {
// #1622: pass the resolved policy — routeZcodeConfig's default ignores BILI_ZCODE_ROUTE / providers direct.
const policy = zcodePolicyFromEnv(process.env);
if (policy.route === "none") return;
// #4692: independent entry point from the authoritative MCP child — report the same built-in-account blind spot on stderr, like the hook's other diagnostics.
const builtin = detectZcodeBuiltinAccount(process.env);
if (builtin !== undefined) reportZcodeBuiltinAccount(builtin, defaultLog);
const origin = plan.mode === "attach" ? plan.attachOrigin : resolveProxyOrigin();
if (!(await waitForProxyHealthy(origin, HOOK_HEALTH_DEADLINE_MS))) return;
const applied = await routeZcodeConfig({ origin, policy });
Expand Down
2 changes: 1 addition & 1 deletion src/zcode/json-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export function zcodeSigningBlocksRouting(kind: ZcodeStoreKind, policy: ZcodeRou
/** #809 parity with the in-process natives: a loopback proxy target is never
* re-proxied — wrapping it would stack bili onto itself or onto the user's
* own local relay. */
function isLoopbackHttpUrl(url: string): boolean {
export function isLoopbackHttpUrl(url: string): boolean {
let parsed: URL;
try {
parsed = new URL(url);
Expand Down
47 changes: 47 additions & 0 deletions src/zcode/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
defaultZcodeRoutePolicy,
detectCurrentZcodeOrigin,
detectZcodeStore,
isLoopbackHttpUrl,
resolveZcodeDataDir,
stampZcodePluginHeader,
unrouteZcodeText,
Expand Down Expand Up @@ -441,6 +442,45 @@ interface BootstrapZcodeOptions {
readonly healthDeadlineMs?: number;
}

/** #4692: the z.ai built-in account connects through ZAI_BUSINESS_BASE_URL —
* an env var that lives in the ZCode MAIN process and never lands in the
* provider store. Native routing rewrites only that store, so this surface
* has no JSON-surgery target and its model traffic bypasses bili entirely. A
* hook/MCP child cannot rewrite the parent's env (same wall as codex's login
* provider, #1660/#403), so cert-MITM is the only way to cover it. Detected
* here so a session going blind on it is loud instead of silent (#1896
* extended past the empty-store shape to the non-empty one). */
interface ZcodeBuiltinAccount {
readonly baseUrl: string;
readonly host: string;
}

/** Read-only: does this env configure a live z.ai built-in account whose
* traffic bypasses native routing? Undefined when the var is absent, not
* http(s), already a /bili/ wrapper, or a loopback target (none of those are
* public-bypass surfaces). Never throws. */
export function detectZcodeBuiltinAccount(env: NodeJS.ProcessEnv = process.env): ZcodeBuiltinAccount | undefined {
const raw = (env.ZAI_BUSINESS_BASE_URL ?? "").trim();
if (!raw) return undefined;
let url: URL;
try {
url = new URL(raw);
} catch {
return undefined;
}
if (url.protocol !== "https:" && url.protocol !== "http:") return undefined;
if (url.pathname.startsWith("/bili/")) return undefined;
// Shared #809 loopback predicate — keeps this detector drift-free from the routing side.
if (isLoopbackHttpUrl(raw)) return undefined;
return { baseUrl: raw, host: url.hostname.toLowerCase() };
}

export function reportZcodeBuiltinAccount(account: ZcodeBuiltinAccount, log: (msg: string) => void): void {
log(
`z.ai built-in account detected (ZAI_BUSINESS_BASE_URL=${account.baseUrl}): it connects directly to ${account.host} and BYPASSES bili — native routing only rewrites the provider store, and this account never lands there, so its model traffic runs direct/uncompressed. Cover it via the GUI cert-MITM setup (Settings → Network: HTTP proxy + root CA path); note zai-series coding-plan model traffic additionally hits the #661 anti-fraud wall (working-but-uncompressed — see CLIENTS.md, #4593/#4610).`,
);
}

export async function bootstrapZcodeNative(opts: BootstrapZcodeOptions = {}): Promise<BootstrapMode> {
const env = opts.env ?? process.env;
const log = opts.log ?? defaultLog;
Expand All @@ -455,6 +495,13 @@ export async function bootstrapZcodeNative(opts: BootstrapZcodeOptions = {}): Pr
return { mode: "off" };
}

// #4692: the built-in account (ZAI_BUSINESS_BASE_URL) never lands in the
// provider store, so nothing downstream can signal when a session goes
// blind on it. Fire once here — after the kill-switch opt-out, before any
// proxy bring-up — so both the degraded and active outcomes stay loud.
const builtin = detectZcodeBuiltinAccount(env);
if (builtin !== undefined) reportZcodeBuiltinAccount(builtin, log);

// #1621 + #1892: settle routing viability with the PURE dry-run BEFORE
// any proxy bring-up. A degraded session (empty personal store, signing
// wall, missing store) must not spawn a proxy it can never route
Expand Down
42 changes: 42 additions & 0 deletions tests/hook-graceful-exit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,46 @@ describe("zcode bootstrap-hook entry contract (#2943)", () => {
clearTimeout(kill);
assert.equal(code, 0, `zcode hook must exit 0 (got ${code}); stderr=${stderr.join("")}`);
});

// #4692: the hook is an independent entry point from the MCP child — the
// built-in-account blind spot must be reported on stderr from HERE too.
async function runHook(env: NodeJS.ProcessEnv): Promise<{ code: number | null; out: string }> {
const hookPath = here("../src/zcode/bootstrap-hook.ts");
const e = { ...env };
delete e.NODE_TEST_CONTEXT;
const child = spawn(process.execPath, ["--import", "tsx", hookPath], { env: e, stdio: ["pipe", "pipe", "pipe"] });
const stderr: string[] = [];
child.stderr.on("data", (d) => stderr.push(String(d)));
child.stdin.write(JSON.stringify({ hook_event_name: "SessionStart", session_id: "t" }));
child.stdin.end();
const kill = setTimeout(() => child.kill("SIGKILL"), 15000);
const code = await new Promise<number | null>((resolve) => {
child.on("close", (c) => resolve(c));
child.on("error", () => resolve(null));
});
clearTimeout(kill);
return { code, out: stderr.join("") };
}

it("#4692: reports the built-in account on stderr, then fails open (no proxy reachable)", async () => {
const env = { ...process.env };
env.ZAI_BUSINESS_BASE_URL = "https://api.z.ai";
// attach to a dead port: health wait fails after its deadline -> fail-open return BEFORE any store write
env.BILLION_CONTEXT_PROXY = "http://127.0.0.1:9";
delete env.BILI_NATIVE_ZCODE;
delete env.BILI_ZCODE_ROUTE;
const { code, out } = await runHook(env);
assert.equal(code, 0, `hook must still fail open (got ${code}); stderr=${out}`);
assert.match(out, /z\.ai built-in account detected \(ZAI_BUSINESS_BASE_URL=https:\/\/api\.z\.ai\)/);
assert.match(out, /BYPASSES bili/);
});

it("#4692: kill-switch opt-out keeps the hook silent about the built-in account", async () => {
const env = { ...process.env };
env.ZAI_BUSINESS_BASE_URL = "https://api.z.ai";
env.BILI_NATIVE_ZCODE = "0";
const { code, out } = await runHook(env);
assert.equal(code, 0, `hook must exit 0 (got ${code}); stderr=${out}`);
assert.doesNotMatch(out, /built-in account detected/);
});
});
96 changes: 96 additions & 0 deletions tests/zcode-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import path from "node:path";
import {
activateZcodePluginMode,
bootstrapZcodeNative,
detectZcodeBuiltinAccount,
handoffZcodeRoutingOnExit,
planNativeZcode,
planZcodeRouting,
probeProxyHealth,
repairSharedStoreDrift,
reportZcodeBuiltinAccount,
restoreZcodeBackup,
routeZcodeConfig,
unrouteZcode,
Expand Down Expand Up @@ -860,3 +862,97 @@ test("bootstrapZcodeNative returns degraded, without proxy bring-up, for an empt
rmrf(dir);
}
});

// ── #4692: z.ai built-in account (ZAI_BUSINESS_BASE_URL) bypasses the store ──

test("detectZcodeBuiltinAccount classifies the built-in-account surface (#4692)", () => {
assert.equal(detectZcodeBuiltinAccount({}), undefined);
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "" }), undefined);
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: " " }), undefined);
// Non-http(s) or unparseable → not a bypass surface, and never throws.
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "ftp://api.z.ai" }), undefined);
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "not a url" }), undefined);
// Loopback targets are not public-bypass surfaces (incl. a /bili/ wrapper on one).
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "http://127.0.0.1:18787/bili/https://api.z.ai" }), undefined);
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "http://localhost:8787" }), undefined);
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "http://[::1]:8787" }), undefined);
// An already-/bili/-wrapped URL on a non-loopback proxy is covered, not a bypass.
assert.equal(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "https://proxy.example.com/bili/https://upstream.example" }), undefined);
assert.deepEqual(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: "https://api.z.ai" }), { baseUrl: "https://api.z.ai", host: "api.z.ai" });
// Trims surrounding whitespace; lowercases the host.
assert.deepEqual(detectZcodeBuiltinAccount({ ZAI_BUSINESS_BASE_URL: " https://API.Z.AI/ " }), { baseUrl: "https://API.Z.AI/", host: "api.z.ai" });
});

test("reportZcodeBuiltinAccount names the surface and the cert-MITM exit (#4692)", () => {
const lines: string[] = [];
reportZcodeBuiltinAccount({ baseUrl: "https://api.z.ai", host: "api.z.ai" }, (m) => lines.push(m));
assert.equal(lines.length, 1);
assert.match(lines[0], /ZAI_BUSINESS_BASE_URL=https:\/\/api\.z\.ai/);
assert.match(lines[0], /BYPASSES bili/);
assert.match(lines[0], /cert-MITM/);
assert.match(lines[0], /#661/);
});

test("bootstrapZcodeNative signals the built-in account instead of going silent (#4692)", async () => {
// The blind case: personal store emptied by the switch, built-in account active.
const empty = emptyPersonalStoreDir();
try {
let proxyTouched = false;
const logs: string[] = [];
const out = await bootstrapZcodeNative({
env: { ZAI_BUSINESS_BASE_URL: "https://api.z.ai" },
dataDir: empty,
log: (m) => logs.push(m),
ensureProxy: async () => {
proxyTouched = true;
return { origin: "http://127.0.0.1:1", attached: false };
},
});
assert.deepEqual(out, { mode: "degraded", reason: "empty-rules" });
assert.equal(proxyTouched, false);
assert.match(logs.join(" "), /z\.ai built-in account detected \(ZAI_BUSINESS_BASE_URL=https:\/\/api\.z\.ai\)/);
assert.match(logs.join(" "), /BYPASSES bili/);
} finally {
rmrf(empty);
}
// …and it stays loud even when the store DOES route (the active account moved outside it).
const dir = dataDir();
try {
const logs: string[] = [];
const out = await bootstrapZcodeNative({
env: { ZAI_BUSINESS_BASE_URL: "https://api.z.ai" },
dataDir: dir,
log: (m) => logs.push(m),
ensureProxy: async () => ({ origin: "http://127.0.0.1:1", attached: false }),
});
assert.equal(out.mode, "active");
const joined = logs.join(" ");
assert.match(joined, /z\.ai built-in account detected/);
assert.match(joined, /routed .* via http:\/\/127\.0\.0\.1:1/);
} finally {
rmrf(dir);
}
});

test("bootstrapZcodeNative does not signal the built-in account when routing is opted out (#4692)", async () => {
const optOutEnvs: Array<Record<string, string>> = [
{ BILI_NATIVE_ZCODE: "0" },
{ BILI_ZCODE_ROUTE: "none" },
];
for (const extra of optOutEnvs) {
const dir = dataDir();
try {
const logs: string[] = [];
const out = await bootstrapZcodeNative({
env: { ...extra, ZAI_BUSINESS_BASE_URL: "https://api.z.ai" },
dataDir: dir,
log: (m) => logs.push(m),
ensureProxy: async () => ({ origin: "http://127.0.0.1:1", attached: false }),
});
assert.equal(out.mode, "off");
assert.doesNotMatch(logs.join(" "), /built-in account detected/);
} finally {
rmrf(dir);
}
}
});
Loading