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
16 changes: 15 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ export type ProxyOptions = {
debug: boolean;
dumpSse?: string;
passthrough: boolean;
/** Where `passthrough` came from: "env" (ACP_PASSTHROUGH or --passthrough
* flag), "file" (config `passthrough: true`), or null (default off).
* Drives the #405 boot warning and the web panel's source display. */
passthroughSource: "env" | "file" | null;
autoUpdate: boolean;
logFile?: string;
/** MITM transparent-proxy mode. When enabled, an HTTP CONNECT handler is
Expand Down Expand Up @@ -280,6 +284,14 @@ export function loadRoutes(env: NodeJS.ProcessEnv = process.env): ProviderRoutes
return routes;
}

/** Resolved passthrough state shared by loadOptions and the web config API
* (single source of truth — the GET handler must not re-derive it). */
export function passthroughState(env: NodeJS.ProcessEnv): { enabled: boolean; source: "env" | "file" | null } {
const filePassthrough = loadConfigFile().passthrough === true;
if (env.ACP_PASSTHROUGH !== undefined) return { enabled: env.ACP_PASSTHROUGH === "1", source: "env" };
return { enabled: filePassthrough, source: filePassthrough ? "file" : null };
}

export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions {
// --- Source 1: JSON config file (~/.config/billion-context/billion-context.json) ---
// The canonical, user-editable config. Loaded first so env vars below can
Expand All @@ -295,6 +307,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions
const host = rawHost === "localhost" ? "127.0.0.1" : rawHost;
const upstream = (env.ACP_UPSTREAM ?? fileConfig.upstream ?? "https://api.anthropic.com").replace(/\/$/, "");
const routes = loadRoutes(env);
const passthrough = passthroughState(env);
const modelContextLimit = parseInt(env.ACP_MODEL_CONTEXT_LIMIT ?? `${fileConfig.modelContextLimit ?? 200000}`, 10);
const biliProxy = nonEmpty(env.BILI_UPSTREAM_PROXY);
const webProxy = nonEmpty(fileConfig.upstreamProxy);
Expand Down Expand Up @@ -364,7 +377,8 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions
log: env.ACP_LOG !== "0" && fileConfig.log !== false,
debug: (env.ACP_DEBUG ?? (fileConfig.debug ? "1" : "0")) === "1",
dumpSse: env.ACP_DUMP_SSE || fileConfig.dumpSse || undefined,
passthrough: (env.ACP_PASSTHROUGH ?? (fileConfig.passthrough ? "1" : "0")) === "1",
passthrough: passthrough.enabled,
passthroughSource: passthrough.source,
autoUpdate: (env.ACP_AUTO_UPDATE ?? (fileConfig.autoUpdate === false ? "0" : "1")) !== "0",
logFile: env.ACP_LOG_FILE !== undefined ? (env.ACP_LOG_FILE || undefined) : fileConfig.logFile,
mitm: {
Expand Down
32 changes: 30 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { renderUI, handleConfigGet, handleConfigPut } from "./web/index.js";
import { reapOrphanBlocks } from "./orphan-gc.js";
import { getStore } from "./persist.js";
import { log as loggerLog, configureLogger, getLogPath, closeLogger } from "./logger.js";
import { defaultLogFile, stateDir } from "./paths.js";
import { configFile, defaultLogFile, stateDir } from "./paths.js";
import { atomicWriteInstanceFile, clearProxyInstanceFile, isPidAlive, registerInstanceAndWarn, unregisterInstance } from "./instance.js";
import { compressLoopResponsesJson } from "./compress-loop-responses.js";
import { runCompressLoop, pickAdapter } from "./loop/index.js";
Expand Down Expand Up @@ -441,8 +441,28 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
` — web UI: http://${displayHost}:${actualPort}/__bili/` +
` — zero-config: prefix any baseURL with http://${displayHost}:${actualPort}/bili/` +
(nOverrides ? ` — context overrides for ${nOverrides} upstream URL(s)` : "")
+ (opts.mitm.enabled ? ` — MITM proxy on (whitelist)${opts.mitm.domains.length ? ` +${opts.mitm.domains.join(",")}` : ""}` : ""),
+ (opts.mitm.enabled ? ` — MITM proxy on (whitelist)${opts.mitm.domains.length ? ` +${opts.mitm.domains.join(",")}` : ""}` : "")
+ (opts.passthrough ? " — PASSTHROUGH (compression OFF)" : ""),
);
if (opts.passthrough) {
log(
"warn",
`[passthrough] compression is OFF — every request is forwarded verbatim, no tokens are saved ` +
`(source: ${opts.passthroughSource === "env" ? "ACP_PASSTHROUGH env var or --passthrough flag" : `config file ${configFile()}`}). ` +
(opts.passthroughSource === "env"
? "Unset ACP_PASSTHROUGH (or drop --passthrough) and restart to re-enable compression."
: "Clear it in the web UI (概览 page) or remove \"passthrough\": true from the config file to re-enable compression."),
);
}
const envKnobs: string[] = [];
if (process.env.ACP_PASSTHROUGH !== undefined) envKnobs.push(`ACP_PASSTHROUGH=${process.env.ACP_PASSTHROUGH}`);
if (process.env.ACP_MODEL_CONTEXT_LIMIT !== undefined) envKnobs.push(`ACP_MODEL_CONTEXT_LIMIT=${process.env.ACP_MODEL_CONTEXT_LIMIT}`);
if (process.env.ACP_COMPRESS_TOOL !== undefined) envKnobs.push(`ACP_COMPRESS_TOOL=${process.env.ACP_COMPRESS_TOOL}`);
if (process.env.ACP_COMPRESS_NUDGE !== undefined) envKnobs.push(`ACP_COMPRESS_NUDGE=${process.env.ACP_COMPRESS_NUDGE}`);
if (process.env.BILI_PERSIST !== undefined) envKnobs.push(`BILI_PERSIST=${process.env.BILI_PERSIST}`);
if (envKnobs.length > 0) {
log("info", `[config] env overrides active (win over the config file): ${envKnobs.join(", ")}`);
}
if (nonLoopbackBind) {
log(
"warn",
Expand Down Expand Up @@ -714,6 +734,14 @@ async function handle(
if (req.method === "PUT" && req.url === "/__bili/config") {
return handleConfigPut(req, res, () => {
const fresh = loadOptions();
if (fresh.passthrough !== opts.passthrough) {
log(
fresh.passthrough ? "warn" : "info",
`[passthrough] ${fresh.passthrough ? "compression turned OFF via web config — forwarding verbatim" : "compression re-enabled via web config"}`,
);
}
opts.passthrough = fresh.passthrough;
opts.passthroughSource = fresh.passthroughSource;
opts.proxy = fresh.proxy;
opts.proxyMode = fresh.proxyMode;
opts.proxySource = fresh.proxySource;
Expand Down
23 changes: 22 additions & 1 deletion src/web/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
parseCompressSettings,
parseRouteEntry,
parseUpstreamProxyMode,
passthroughState,
safeReadJson,
type ProviderRoute,
type ProviderRoutes,
Expand Down Expand Up @@ -85,6 +86,7 @@ export async function handleConfigGet(res: ServerResponse): Promise<void> {
upstreamProxy: upstream.proxy ?? null,
upstreamProxyMode: upstream.mode,
compress: config.compress ?? null,
passthrough: passthroughState(process.env),
...(parseError ? { parseError } : {}),
}, null, 2));
}
Expand All @@ -109,7 +111,8 @@ export async function handleConfigPut(
const hasProxy = Object.prototype.hasOwnProperty.call(body, "upstreamProxy");
const hasMode = Object.prototype.hasOwnProperty.call(body, "upstreamProxyMode");
const hasCompress = Object.prototype.hasOwnProperty.call(body, "compress");
if (!hasProviders && !hasProxy && !hasMode && !hasCompress) return sendError(res, 400, "expected providers, upstream proxy, or compress settings");
const hasPassthrough = Object.prototype.hasOwnProperty.call(body, "passthrough");
if (!hasProviders && !hasProxy && !hasMode && !hasCompress && !hasPassthrough) return sendError(res, 400, "expected providers, upstream proxy, compress, or passthrough settings");

const routes: Record<string, ProviderRoute> = {};
if (hasProviders) {
Expand Down Expand Up @@ -153,6 +156,19 @@ export async function handleConfigPut(
if (compress === undefined) return sendError(res, 400, "invalid compress settings");
}

// #405: the panel must be able to READ and CLEAR passthrough. An env
// ACP_PASSTHROUGH (or --passthrough flag, which lands in env) outranks
// the file on every reload — a file write would be a silent no-op, so
// refuse with the exact way out instead.
if (hasPassthrough) {
if (body.passthrough !== null && typeof body.passthrough !== "boolean") {
return sendError(res, 400, "passthrough must be a boolean or null");
}
if (passthroughState(process.env).source === "env") {
return sendError(res, 409, "passthrough is forced by the ACP_PASSTHROUGH environment variable (or --passthrough flag); unset it and restart to change here");
}
}

const config = readConfig();
if (hasProviders) config.providers = routes;
if (hasProxy) {
Expand All @@ -164,6 +180,10 @@ export async function handleConfigPut(
if (compress && Object.keys(compress).length > 0) config.compress = compress;
else delete config.compress;
}
if (hasPassthrough) {
if (body.passthrough === true) config.passthrough = true;
else delete config.passthrough;
}
try {
atomicWriteConfig(config);
onChanged?.();
Expand All @@ -174,6 +194,7 @@ export async function handleConfigPut(
if (hasProviders) changed.push(`${Object.keys(routes).length} routes`);
if (hasProxy || hasMode) changed.push("network");
if (hasCompress) changed.push("compress");
if (hasPassthrough) changed.push("passthrough");
log("info", `[acp-web] configuration updated (${changed.join(", ") || "none"})`);
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: true, providers: hasProviders ? Object.keys(routes).length : undefined }));
Expand Down
6 changes: 4 additions & 2 deletions src/web/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function busy(button,on,label){if(!button)return;if(on){button.dataset.label=but
async function json(url,options){const response=await fetch(url,options);const data=await response.json().catch(()=>({}));if(!response.ok)throw new Error(data.error||data.detail||("HTTP "+response.status));return data}
function showPage(name){document.querySelectorAll(".page").forEach((node)=>node.classList.toggle("active",node.id==="page-"+name));document.querySelectorAll(".nav button").forEach((node)=>node.classList.toggle("active",node.dataset.page===name));if(name==="sessions")loadSessions();if(name==="upstream"){loadUpstream();loadOverrides()}}
document.querySelectorAll(".nav button").forEach((button)=>button.addEventListener("click",()=>showPage(button.dataset.page)));
async function loadConfig(){const data=await json("/__bili/config");if(data.parseError)toast(String(data.parseError),true);byId("providers-json").value=JSON.stringify(data.providers||{},null,2);byId("proxy-url").value=data.upstreamProxy||"";byId("compress-json").value=data.compress?JSON.stringify(data.compress,null,2):"";document.querySelectorAll('input[name="proxy-mode"]').forEach((input)=>input.checked=input.value===(data.upstreamProxyMode||"direct"));return data}
async function loadConfig(){const data=await json("/__bili/config");if(data.parseError)toast(String(data.parseError),true);byId("providers-json").value=JSON.stringify(data.providers||{},null,2);byId("proxy-url").value=data.upstreamProxy||"";byId("compress-json").value=data.compress?JSON.stringify(data.compress,null,2):"";document.querySelectorAll('input[name="proxy-mode"]').forEach((input)=>input.checked=input.value===(data.upstreamProxyMode||"direct"));const pt=data.passthrough||{enabled:false};const banner=byId("passthrough-banner");if(banner){if(pt.enabled){banner.hidden=false;byId("passthrough-source").textContent=pt.source==="env"?"环境变量 ACP_PASSTHROUGH(或 --passthrough 参数)":"配置文件 passthrough: true";const btn=byId("clear-passthrough");btn.disabled=pt.source==="env";btn.title=pt.source==="env"?"需先 unset ACP_PASSTHROUGH 并重启":""}else{banner.hidden=true}}return data}
async function loadUpstream(){try{const data=await json("/__bili/upstream");const labels={"provider":"Provider 单独代理","provider-direct":"Provider 直连","bili-env":"BILI_UPSTREAM_PROXY","web-manual":"Web 手动代理","config":"配置文件代理","HTTPS_PROXY":"HTTPS_PROXY","HTTP_PROXY":"HTTP_PROXY","ALL_PROXY":"ALL_PROXY","windows-system":"Windows 系统代理","windows-bypass":"Windows 绕过列表","no-proxy":"NO_PROXY","direct":"直连"};byId("upstream-source").textContent=labels[data.source]||data.source||"直连";byId("upstream-effective").textContent=data.proxy||"direct";byId("upstream-pac").textContent=data.autoConfigUrl||"—";const state=byId("upstream-state");state.className="status "+(data.connected===true?"ok":data.connected===false?"err":"");state.textContent=data.connected===true?"CONNECT 正常":data.connected===false?(data.error||"连接失败"):"尚未观察到上游连接"}catch(error){byId("upstream-state").textContent=String(error)}}
async function saveUpstream(){const button=byId("save-upstream");busy(button,true,"保存中…");const mode=document.querySelector('input[name="proxy-mode"]:checked').value;try{await json("/__bili/config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({upstreamProxyMode:mode,upstreamProxy:byId("proxy-url").value.trim()||null})});toast("上游设置已热更新");await loadUpstream()}catch(error){toast(String(error),true)}finally{busy(button,false)}}
async function testUpstream(){const button=byId("test-upstream");busy(button,true,"测试中…");try{const data=await json("/__bili/upstream/test",{method:"POST"});toast("连接成功,HTTP "+data.status);await loadUpstream()}catch(error){toast(String(error),true);await loadUpstream()}finally{busy(button,false)}}
Expand All @@ -16,6 +16,8 @@ async function loadOverrides(){try{const data=await loadConfig();const providers
async function saveOverrides(){const button=byId("save-overrides");busy(button,true,"保存中…");try{const data=await loadConfig();const providers=data.providers||{};document.querySelectorAll(".override-proxy").forEach((input)=>{const url=input.dataset.url;if(!url)return;if(!providers[url])providers[url]={};const val=input.value.trim();if(val)providers[url].proxy=val;else delete providers[url].proxy});await json("/__bili/config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({providers})});await json("/__bili/config/reload",{method:"POST"});toast("按 URL 覆盖已热更新");await loadOverrides()}catch(error){toast(String(error),true)}finally{busy(button,false)}}
async function loadSessions(){try{const data=await json("/__bili/stats");const rows=(data.sessions||[]).map((item)=>"<tr><td>"+escapeHtml(item.title||"—")+"</td><td>"+escapeHtml(item.protocol||"—")+"</td><td class=mono>"+escapeHtml(item.label||"—")+"</td><td>"+escapeHtml(item.requests)+"</td><td>"+escapeHtml(item.contextTokens)+"</td><td>"+escapeHtml(new Date(item.lastSeen).toLocaleString())+(item.restored?" <span class=muted>(恢复,开机后未活动)</span>":"")+"</td></tr>").join("");byId("sessions-body").innerHTML=rows||'<tr><td colspan="6">暂无会话</td></tr>'}catch(error){toast(String(error),true);throw error}}
async function refreshSessions(){const button=byId("refresh-sessions");busy(button,true,"刷新中…");try{await loadSessions();toast("会话列表已刷新")}catch{}finally{busy(button,false)}}
document.querySelectorAll(".copy-btn").forEach((btn)=>btn.addEventListener("click",async()=>{busy(btn,true,"复制中…");try{await navigator.clipboard.writeText(btn.dataset.copy||"");toast("已复制")}catch(e){toast(String(e),true)}finally{busy(btn,false)}}));byId("save-upstream").addEventListener("click",saveUpstream);byId("test-upstream").addEventListener("click",testUpstream);byId("save-providers").addEventListener("click",saveProviders);byId("save-compress").addEventListener("click",saveCompress);byId("save-overrides").addEventListener("click",saveOverrides);byId("refresh-sessions").addEventListener("click",refreshSessions);
document.querySelectorAll(".copy-btn").forEach((btn)=>btn.addEventListener("click",async()=>{busy(btn,true,"复制中…");try{await navigator.clipboard.writeText(btn.dataset.copy||"");toast("已复制")}catch(e){toast(String(e),true)}finally{busy(btn,false)}}));async function clearPassthrough(){const button=byId("clear-passthrough");busy(button,true,"处理中…");try{await json("/__bili/config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({passthrough:null})});toast("已恢复压缩");await loadConfig()}catch(error){toast(String(error),true)}finally{busy(button,false)}}
byId("clear-passthrough").addEventListener("click",clearPassthrough);
byId("save-upstream").addEventListener("click",saveUpstream);byId("test-upstream").addEventListener("click",testUpstream);byId("save-providers").addEventListener("click",saveProviders);byId("save-compress").addEventListener("click",saveCompress);byId("save-overrides").addEventListener("click",saveOverrides);byId("refresh-sessions").addEventListener("click",refreshSessions);
Promise.all([loadConfig(),loadUpstream()]).catch((error)=>toast(String(error),true));setInterval(()=>{if(byId("page-sessions").classList.contains("active"))loadSessions().catch(()=>{})},5000);
`;
2 changes: 1 addition & 1 deletion src/web/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function renderPage(origin: string, version: string): string {
const caReady = existsSync(caPath);
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>billion-context</title><style>${WEB_STYLES}</style></head><body>
<div class="app"><aside class="sidebar"><div class="brand"><div class="brand-title">billion<span>-context</span></div><div class="version">v${version}</div></div><a class="fork-ribbon" href="https://github.com/ranxianglei/billion-context" target="_blank" rel="noopener">★ Fork me on GitHub</a><nav class="nav"><button class="active" data-page="overview">概览</button><button data-page="routing">接入</button><button data-page="upstream">上游</button><button data-page="sessions">会话</button><button data-page="settings">设置</button></nav></aside>
<main class="main"><section id="page-overview" class="page active"><h1>概览</h1><p class="lead">本地路由与上游网络相互独立,ACP 压缩运行在两者之间。</p><div class="grid"><div class="card"><h2>服务地址</h2><p class="mono">${origin}</p></div><div class="card"><h2>客户端接入</h2><p class="status">在"接入"页将各客户端(Codex / Claude Code / OpenCode / Pi 等)的流量路由到 bili。</p></div></div></section>
<main class="main"><section id="page-overview" class="page active"><h1>概览</h1><p class="lead">本地路由与上游网络相互独立,ACP 压缩运行在两者之间。</p><div id="passthrough-banner" class="notice" hidden>⚠️ <strong>Passthrough 已启用</strong>:所有请求原样转发,压缩完全关闭,不会节省任何 token。来源:<span id="passthrough-source" class="mono"></span>。 <button id="clear-passthrough" class="btn">恢复压缩</button></div><div class="grid"><div class="card"><h2>服务地址</h2><p class="mono">${origin}</p></div><div class="card"><h2>客户端接入</h2><p class="status">在"接入"页将各客户端(Codex / Claude Code / OpenCode / Pi 等)的流量路由到 bili。</p></div></div></section>
<section id="page-routing" class="page"><h1>客户端接入</h1><p class="lead">两类接入:A. 推荐接入方式(<span class="mono">/bili/</span> 前缀,零配置);B. 证书接入方式(MITM,需信任 CA 证书)。</p>
<h2 class="section-title">A. 推荐接入方式(/bili/ 前缀)</h2>
<p class="hint">在客户端配置里把原 baseURL 前加上 <span class="mono">${origin}/bili/</span> 即可,其余不变。</p>
Expand Down
Loading
Loading