🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
Agent commands use the user's proxy; loopback is never proxied
Marlaf7b55a150ce8
diff --git a/docs/development.md b/docs/development.mdindex 0f42815..81cbced 100644--- a/docs/development.md+++ b/docs/development.md@@ -64,6 +64,7 @@ npm run test:dsh-bundle # 用 Electron 跑真实 DSH 集成测试,加载打- DSH 代理运行时:`scripts/prepare-dsh.mjs` 按目标平台安装 `dsh-runtime/`,`scripts/bundle-dsh.mjs` 把它打成 `resources/dsh/dsh.asar`(全部 JS,一个文件)加上 `resources/dsh/node_modules/`(只有原生包,约 55 个文件)。Electron 主进程和 `ELECTRON_RUN_AS_NODE` 子进程直接读 asar,无需首启解压;安装包因此只需解出几百个文件(Windows 上解压与杀毒逐个扫描是安装慢的主因)。开发时仍直接用 `dsh-runtime/`。- Windows 上代理执行命令用的 PowerShell:经沙箱时 Windows PowerShell 5.1 每条命令要二三十秒,PowerShell 7 约 1 秒。应用按这个顺序选:系统里能用的 PowerShell 7(后台按 DSH 的方式试运行一次,什么都不下载)→ 应用内置的 PowerShell 7 → Windows PowerShell 5.1。没有能用的 7 且代理模式开着时,应用在后台自动下载官方 PowerShell 7.6.9(LTS)的 zip,装到 `%LOCALAPPDATA%\AnyModelBot\pwsh\`:不需要管理员权限,不写注册表、不改 PATH,不影响你自己的 PowerShell。版本和 x64 / arm64 两个 zip 的 SHA256 写死在 `src/agent/pwsh-private.ts`(升级用 `node scripts/pwsh-hashes.mjs <版本>`),下载后核对哈希、解压后核对微软 Authenticode 签名,再按 DSH 的方式试运行(版本、读写临时文件、拉起外部程序)通过才用;装失败或装了一半的不会被用,下次启动会清掉。装的时候对话页和 设置 → 常规 显示进度,`/status` 也有,装好之前命令照常用 5.1;装好后空闲的代理进程在后台换用它,不用重启应用。运行中代理拉不起它(被杀毒软件删除或隔离、被策略拦截)就自动退回上一种并提示原因;设置 → 故障排查 可以安装、重新安装、改回系统默认。Windows 10 1607 / Server 2016 以前的系统不下载。桌面版下载走系统代理(Chromium 网络栈);命令行版用 Node 的 fetch(较新的 Node 设 `NODE_USE_ENV_PROXY=1` 后认 `HTTPS_PROXY`);`AMB_PWSH_MIRROR` 可换成镜像前缀(照样核对哈希和签名),`AMB_PWSH_AUTO_INSTALL=0` 关掉自动安装。+- 代理执行的命令能联网(沙箱只限制写文件),用的是你的代理:应用环境变量里的 `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY`(及小写)和证书、软件源变量(`SSL_CERT_FILE`、`REQUESTS_CA_BUNDLE`、`NODE_EXTRA_CA_CERTS`、`PIP_INDEX_URL`、`npm_config_registry`、`GOPROXY` 等)原样传下去;环境里没设代理时,桌面版每次拉起代理进程都问一次系统代理(系统设置和 PAC),按 `http://主机:端口` 传下去(见 `src/agent/proxy-env.ts`)。本机地址(`127.0.0.1`、`localhost`、`::1`)总是并进 `NO_PROXY`,永不走代理。- 数据目录:`<userData>/data`(macOS `~/Library/Application Support/anymodel bot/data`,Windows `%APPDATA%\anymodel bot\data`,Linux `~/.config/anymodel bot/data`)。日志在数据目录的 `logs/app.log`。- 单实例;关闭窗口默认隐藏到托盘(设置 → 常规 可改为退出);托盘菜单:打开 / 在浏览器中打开 / 开机自启(macOS、Windows)/ 打开数据目录 / 退出。- macOS 下窗口无标题栏,红绿灯嵌在侧栏顶部;窗口最小宽度 860。diff --git a/docs/development_en.md b/docs/development_en.mdindex 7edfac8..456e4d7 100644--- a/docs/development_en.md+++ b/docs/development_en.md@@ -64,6 +64,7 @@ npm run test:dsh-bundle # real DSH integration test under Electron against the- DSH agent runtime: `scripts/prepare-dsh.mjs` installs `dsh-runtime/` for the target platform, and `scripts/bundle-dsh.mjs` packs it into `resources/dsh/dsh.asar` (all JavaScript, one file) plus `resources/dsh/node_modules/` (native packages only, about 55 files). The Electron main process and `ELECTRON_RUN_AS_NODE` child processes read the asar directly, with no extraction on first launch, so the installer only unpacks a few hundred files (on Windows, extraction and per-file antivirus scans are the main cause of slow installs). Development still uses `dsh-runtime/` directly.- PowerShell for agent commands on Windows: inside the sandbox, Windows PowerShell 5.1 takes 20–30 seconds per command and PowerShell 7 about 1 second. The app picks, in order: a working PowerShell 7 already on the system (tried once in the background the way DSH runs it; nothing is downloaded) → the app's private PowerShell 7 → Windows PowerShell 5.1. When no working 7 exists and agent mode is on, the app downloads the official PowerShell 7.6.9 (LTS) zip in the background into `%LOCALAPPDATA%\AnyModelBot\pwsh\`: no admin rights, no registry writes, no PATH changes, and your own PowerShell is untouched. The version and the SHA256 of the x64 / arm64 zips are pinned in `src/agent/pwsh-private.ts` (bump them with `node scripts/pwsh-hashes.mjs <version>`). After download the hash is checked, after extraction Microsoft's Authenticode signature is checked, and it is only used after a DSH-style trial run (version, read/write a temp file, launch an external program) passes; failed or half-finished installs are never used and are cleaned up on the next launch. While installing, the chat screen and Settings → General show progress, and so does `/status`; commands keep using 5.1 until it is ready, and idle agent processes switch over in the background without restarting the app. If the agent cannot start it at runtime (removed or quarantined by antivirus, blocked by policy), the app falls back to the previous option and says why; Settings → Troubleshooting can install, reinstall or revert to the system default. Nothing is downloaded on systems older than Windows 10 1607 / Server 2016. The desktop app downloads through the system proxy (Chromium network stack); the command-line build uses Node's fetch (newer Node versions honour `HTTPS_PROXY` when `NODE_USE_ENV_PROXY=1`). `AMB_PWSH_MIRROR` switches to a mirror prefix (hash and signature are still checked), and `AMB_PWSH_AUTO_INSTALL=0` turns automatic installation off.+- Agent commands have network access (the sandbox only restricts writes) and use your proxy: `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` (and their lowercase forms) and the certificate and package-index variables (`SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS`, `PIP_INDEX_URL`, `npm_config_registry`, `GOPROXY`, …) are passed through from the app's environment; when the environment sets no proxy, the desktop app asks for the system proxy (system settings and PAC) each time it starts the agent process and passes it on as `http://host:port` (see `src/agent/proxy-env.ts`). Loopback (`127.0.0.1`, `localhost`, `::1`) is always added to `NO_PROXY` and never proxied.- Data directory: `<userData>/data` (macOS `~/Library/Application Support/anymodel bot/data`, Windows `%APPDATA%\anymodel bot\data`, Linux `~/.config/anymodel bot/data`). Logs are in `logs/app.log` inside the data directory.- Single instance; closing the window hides to the tray by default (Settings → General can make it quit instead). Tray menu: Open / Open in browser / Launch at login (macOS, Windows) / Open data folder / Quit.- On macOS the window has no title bar and the traffic lights sit at the top of the sidebar; minimum window width is 860.diff --git a/electron/main.ts b/electron/main.tsindex 956dc30..9e02727 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -9,7 +9,7 @@* - 托盘菜单和对话框跟着应用语言(src/i18n):跟随系统时取系统首选语言,界面里换了语言托盘菜单立刻重建* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。*/-import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, nativeTheme, net, powerMonitor, shell, dialog, safeStorage } from "electron";+import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, nativeTheme, net, powerMonitor, session, shell, dialog, safeStorage } from "electron";import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -241,6 +241,8 @@ async function boot(): Promise<void> {: undefined,// 下载内置 PowerShell 走 Chromium 的网络栈:和浏览器一样用系统代理设置与系统证书fetch: ((input: string | URL | Request, init?: RequestInit) => net.fetch(input instanceof URL ? input.href : input, init)) as typeof fetch,+ // 代理执行的命令用的系统代理:Chromium 按系统设置和 PAC 解析(代理进程每次拉起时问)+ resolveProxy: (url) => session.defaultSession.resolveProxy(url),};await core.start();if (!core.web) throw new Error(t("desktop.uiNotStarted"));diff --git a/src/agent/cua-driver.ts b/src/agent/cua-driver.tsindex a5b758d..8dfaee1 100644--- a/src/agent/cua-driver.ts+++ b/src/agent/cua-driver.ts@@ -379,7 +379,10 @@ export function cuaConfig(st: CuaStatus, dir: string, opts: { readonly: boolean;};}-/** 图形会话相关的环境变量(DSH 子进程的环境里没有这些,需要显式传给 MCP 子进程)。不含任何密钥。 */+/**+ * 图形会话相关的环境变量(DSH 子进程的环境里没有这些,需要显式传给 MCP 子进程)。不含任何密钥。+ * 代理与证书不用在这里传:DSH 的 MCP 客户端把它自己的环境(去掉密钥样的变量)并在这些前面,代理变量已经在里面(host.ts env())。+ */export const CUA_PASS_ENV = ["DISPLAY","WAYLAND_DISPLAY",diff --git a/src/agent/host.ts b/src/agent/host.tsindex 07dbe2a..a435a29 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -12,6 +12,7 @@ import { findAppRoot } from "../magpie/supervisor.js";import { adaptSkill, mcpPatchLines, resolveComputerUse, type CuResolved } from "./computer-use.js";import { cuaConfig, cuaMcpEnv, discoverAppsCached, type CuaApp } from "./cua-driver.js";import { pwshPatchLines, pwshProbe } from "./pwsh.js";+import { hasEnvProxy, networkEnv, systemProxyEnv } from "./proxy-env.js";import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";import { acceptsImages } from "../llm/client.js";import { CUA_SKILL, MEDIA_SKILL, TASK_RULES, agentPersona, botPrompt } from "./prompts/index.js";@@ -213,6 +214,8 @@ export interface AgentHostOptions {onTaskEvent?: (root: string, n: SdkNotification) => void;/** 宿主这边也空闲(没有在跑或收尾的任务、规则 run,没有等批准的,没有在压缩的会话):开过的会话多了可以换新的子进程 */idle?: () => boolean;+ /** 桌面版:系统给这个地址用的代理(PAC 写法,如 "PROXY 127.0.0.1:7890");环境里没设代理时每次拉起子进程问一次 */+ systemProxy?: (url: string) => Promise<string | undefined>;}export type HostState = "stopped" | "starting" | "running" | "backoff" | "error";@@ -897,8 +900,13 @@ exec "$REAL" "$@"return dir;}- /** 子进程环境:完全替换 process.env,只给必需项;真实模型密钥永不进入。 */- private env(): Record<string, string> {+ /** 环境里没设代理时问桌面外壳系统用的代理(每次拉起子进程都重新问:之后才开的代理,下次重启就用上);命令行、Docker 没有 */+ private async systemProxy(): Promise<Record<string, string>> {+ return this.o.systemProxy && !hasEnvProxy(process.env) ? systemProxyEnv(this.o.systemProxy) : {};+ }++ /** 子进程环境:完全替换 process.env,只给必需项;真实模型密钥永不进入。sysProxy:桌面版问到的系统代理(环境里没设代理时用) */+ private env(sysProxy: Record<string, string> = {}): Record<string, string> {const shim = this.writeBwrapShim();const basePath = process.env.PATH || "/usr/local/bin:/usr/bin:/bin";const env: Record<string, string> = {@@ -922,6 +930,8 @@ exec "$REAL" "$@"};// 时区:本进程设了 TZ 才传下去;没设就不设,子进程用系统时区(各平台都是,Windows 上 TZ 也只认 POSIX 写法)if (process.env.TZ) env.TZ = process.env.TZ;+ // 代理与证书(用户自己的网络设置,不是密钥):命令里的 pip、npm、git、curl 和用户平时一样联网;回环地址永远不走代理(proxy-env.ts)+ Object.assign(env, networkEnv(process.env, sysProxy));if (process.platform === "win32") {// Windows:系统目录类变量不是密钥,但工具进程离不开(npm/pip 找 APPDATA,脚本找 ProgramFiles、ComSpec…)。// libuv 只自动补 SystemRoot/TEMP/USERPROFILE 等少数几个。@@ -1168,6 +1178,7 @@ exec "$REAL" "$@"const cu = this.computerUseActive();const apps = cu && cu.backend === "cua" ? await discoverAppsCached() : [];const pwshPath = await pwshProbe.dshPath();+ const sysProxy = await this.systemProxy();// 模型资料在新进程里重新查;用过的模型都写进补丁(会话各用各的模型),启动用的模型排第一this.routes.clear();this.known.add(model);@@ -1180,12 +1191,12 @@ exec "$REAL" "$@"this.sig = this.settingsSig(pwshPath);const timeoutMs = this.initTimeoutMs();this.control.reset();- this.stage("patch written", t0, { api, models: routes.length, computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs, ...(process.platform === "win32" ? { pwsh: pwshPath ?? "dsh default (Windows PowerShell 5.1)" } : {}) });+ this.stage("patch written", t0, { api, models: routes.length, computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs, proxy: hasEnvProxy(process.env) ? "env" : (sysProxy.HTTPS_PROXY ?? sysProxy.ALL_PROXY ?? "none"), ...(process.platform === "win32" ? { pwsh: pwshPath ?? "dsh default (Windows PowerShell 5.1)" } : {}) });h = new sdk.DeepSeekHarness({profile: "sdk",patches: [patch],dshHome: this.home,- env: this.env(),+ env: this.env(sysProxy),cwd: this.workspace,processCwd: this.workspace,provider: first.provider,diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex 5a2e059..3093470 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -55,6 +55,8 @@ export interface AgentManagerOptions {contextWindow?: (model: string) => Promise<number | undefined>;/** 模型支持的接口与是否推理(Modelflare 模型资料),DSH 按它选对话接口 */apiInfo?: (model: string) => Promise<ModelApiInfo | undefined>;+ /** 桌面版:系统给这个地址用的代理(PAC 写法);代理进程的环境里没设代理时用它 */+ systemProxy?: (url: string) => Promise<string | undefined>;/*** 服务端压缩(见 server-compaction.ts):listed = 价格目录是否列出该模型的压缩端点(只是提示,用前还要探测);* endpoint = 该模型(网关里的名字)直连的压缩端点。缺省则不做。@@ -238,6 +240,7 @@ export class AgentManager {onWake: (conv) => this.onWake?.(botId, conv),onTaskEvent: (root, n) => this.tasks?.onEvent(botId, root, n),idle: () => this.idle(botId),+ systemProxy: this.o.systemProxy,});// 代理进程退出(中止宽限期内没停下、设置变化、崩溃、重启、停止):进程里的压缩跟着没了,不再等它;跑着的后台任务记为中断、排恢复。// 空闲时换掉的(recycled)上面什么都没在跑:之后才开始的 run 已经在用新的进程,不能当成被打断diff --git a/src/agent/proxy-env.ts b/src/agent/proxy-env.tsnew file mode 100644index 0000000..33fd1c0--- /dev/null+++ b/src/agent/proxy-env.ts@@ -0,0 +1,121 @@+/**+ * 代理子进程(和代理跑的命令)的网络设置:代理与证书。+ *+ * 子进程的环境是整个替换掉的(host.ts env()),不传这些变量时,用户的代理(国内常见 Clash / V2Ray 的 127.0.0.1:7890)在命令里就没了。+ * Windows 上更糟:Python 退回注册表里的系统代理,urllib 把不带协议的 127.0.0.1:7890 补成 https://127.0.0.1:7890,+ * pip 于是用 TLS 去连一个普通 HTTP 代理,报 SSLEOFError(EOF occurred in violation of protocol)。环境变量里的代理优先于注册表,+ * 所以把代理写成 http://host:port 传下去就好了。+ *+ * 这些都是用户自己的网络设置,不是 AnyModelBot 的密钥:名字固定(不含 KEY / TOKEN / SECRET / PASSWORD),模型密钥不在其中。+ * DSH 拉起命令时按名字过滤密钥样的变量(dsh-subprocess scrubbedParentEnv),这些都会照样传到命令里。+ */++/** 代理变量:大小写两种都传(Python、curl 先认小写) */+export const PROXY_ENV = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"] as const;++/** 证书与软件源:公司网络的根证书、国内镜像 */+export const CERT_ENV = [+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "REQUESTS_CA_BUNDLE",+ "CURL_CA_BUNDLE",+ "NODE_EXTRA_CA_CERTS",+ "PIP_CERT",+ "PIP_INDEX_URL",+ "PIP_EXTRA_INDEX_URL",+ "PIP_TRUSTED_HOST",+ "npm_config_registry",+ "GOPROXY",+] as const;++/** 回环地址永远不走代理:本机的 bridge、magpie 网关,命令里起的本地服务 */+export const LOOPBACK_NO_PROXY = ["127.0.0.1", "localhost", "::1"];++/** 拿来问系统代理的地址:按顺序问,第一个不是直连的算数(PAC 可能只给部分网站走代理) */+export const PROXY_PROBE_URLS = ["https://pypi.org/", "https://github.com/"];++/** 问系统代理最多等这么久(PAC 要下载时可能慢);超时就当没有 */+export const SYSTEM_PROXY_TIMEOUT_MS = 3000;++type Env = Record<string, string | undefined>;++const PROXY_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];++/** 环境里设了代理(任一种、任一大小写) */+export function hasEnvProxy(env: Env): boolean {+ return PROXY_NAMES.some((k) => !!env[k]?.trim() || !!env[k.toLowerCase()]?.trim());+}++/** 把回环地址并进 NO_PROXY(保留用户原来的写法和顺序;`*` 本来就全部直连) */+export function withLoopback(noProxy: string | undefined): string {+ const entries = (noProxy ?? "")+ .split(/[,\s]+/)+ .map((e) => e.trim())+ .filter(Boolean);+ if (entries.includes("*")) return "*";+ const have = new Set(entries.map((e) => e.toLowerCase()));+ return [...entries, ...LOOPBACK_NO_PROXY.filter((e) => !have.has(e))].join(",");+}++/**+ * Chromium 的代理解析结果(PAC 写法,如 "PROXY 127.0.0.1:7890; DIRECT")→ 环境变量。+ * 按顺序取第一项:DIRECT 什么都不设;PROXY / HTTPS 设 HTTP_PROXY 和 HTTPS_PROXY(http:// 或 https://);SOCKS 设 ALL_PROXY。+ */+export function proxyEnvFromPac(pac: string | undefined): Record<string, string> {+ for (const item of (pac ?? "").split(";")) {+ const [kind = "", hostPort = ""] = item.trim().split(/\s+/);+ const k = kind.toUpperCase();+ if (!k) continue;+ if (k === "DIRECT") return {};+ if (!/^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):\d{1,5}$/.test(hostPort)) continue;+ const scheme = k === "PROXY" || k === "HTTP" ? "http" : k === "HTTPS" ? "https" : k === "SOCKS5" ? "socks5" : k === "SOCKS" || k === "SOCKS4" ? "socks4" : "";+ if (!scheme) continue;+ const url = `${scheme}://${hostPort}`;+ if (scheme.startsWith("socks")) return { ALL_PROXY: url, all_proxy: url };+ return { HTTP_PROXY: url, HTTPS_PROXY: url, http_proxy: url, https_proxy: url };+ }+ return {};+}++/**+ * 问系统用的代理(桌面版:Electron 按系统设置和 PAC 解析)。从不抛错:出错、超时、全是直连都返回 {}。+ */+export async function systemProxyEnv(resolve: (url: string) => Promise<string | undefined>, timeoutMs = SYSTEM_PROXY_TIMEOUT_MS): Promise<Record<string, string>> {+ let timer: NodeJS.Timeout | undefined;+ const timeout = new Promise<Record<string, string>>((r) => {+ timer = setTimeout(() => r({}), timeoutMs);+ timer.unref?.();+ });+ const probe = (async () => {+ for (const url of PROXY_PROBE_URLS) {+ const env = proxyEnvFromPac(await resolve(url));+ if (Object.keys(env).length) return env;+ }+ return {};+ })().catch(() => ({}));+ try {+ return await Promise.race([probe, timeout]);+ } finally {+ clearTimeout(timer);+ }+}++/**+ * 传给代理子进程的网络变量:parent 里的代理与证书变量原样传;parent 里没有代理时用 system(系统代理)。+ * 有任何代理时 NO_PROXY / no_proxy 都并进回环地址。+ */+export function networkEnv(parent: Env, system: Record<string, string> = {}): Record<string, string> {+ const env: Record<string, string> = {};+ for (const k of [...PROXY_ENV, ...CERT_ENV]) {+ const v = parent[k];+ if (v?.trim()) env[k] = v;+ }+ if (!hasEnvProxy(parent)) Object.assign(env, system);+ if (hasEnvProxy(env)) {+ const upper = env.NO_PROXY;+ const lower = env.no_proxy;+ env.NO_PROXY = withLoopback(upper ?? lower);+ env.no_proxy = withLoopback(lower ?? upper);+ }+ return env;+}diff --git a/src/app.ts b/src/app.tsindex 0842b2c..9ad6735 100644--- a/src/app.ts+++ b/src/app.ts@@ -69,6 +69,8 @@ export interface DesktopHooks {secretBox?: SecretBox;/** 走 Chromium 网络栈的 fetch(Electron net.fetch:系统代理、系统证书);下载内置 PowerShell 用,缺省时用 Node 的 fetch */fetch?: typeof fetch;+ /** 系统给这个地址用的代理(Electron resolveProxy:系统设置和 PAC),PAC 写法,如 "PROXY 127.0.0.1:7890" 或 "DIRECT" */+ resolveProxy?(url: string): Promise<string>;}export interface ModelflareStatus {@@ -208,6 +210,8 @@ export class App {approvalTtlMs: config.agent.approvalTtlMs,// 上下文长度来自 Modelflare 的模型资料(和模型选择器里显示的一致);内置兜底表跟不上新模型contextWindow: async (model) => (await this.infoOf(model))?.context,+ // 桌面版:代理执行的命令用系统代理(环境里没设代理时);命令行、Docker 只认环境变量+ systemProxy: async (url) => this.desktop?.resolveProxy?.(url),// 代理的对话接口按 Modelflare 目录选(Responses / Anthropic Messages / Chat);外部端点只当它会 ChatapiInfo: async (model) => {if (!this.magpie) return undefined;diff --git a/test/proxy-env.unit.test.ts b/test/proxy-env.unit.test.tsnew file mode 100644index 0000000..682c4e3--- /dev/null+++ b/test/proxy-env.unit.test.ts@@ -0,0 +1,162 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { Store } from "../src/store/db.js";+import { AgentHost } from "../src/agent/host.js";+import { CERT_ENV, PROXY_ENV, PROXY_PROBE_URLS, hasEnvProxy, networkEnv, proxyEnvFromPac, systemProxyEnv, withLoopback } from "../src/agent/proxy-env.js";++const LOOP = "127.0.0.1,localhost,::1";++describe("networkEnv: the user's proxy and certificate settings reach the agent child", () => {+ it("passes the proxy variables through", () => {+ const env = networkEnv({ HTTP_PROXY: "http://127.0.0.1:7890", HTTPS_PROXY: "http://127.0.0.1:7890", ALL_PROXY: "socks5://127.0.0.1:7891", PATH: "/bin" });+ expect(env.HTTP_PROXY).toBe("http://127.0.0.1:7890");+ expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:7890");+ expect(env.ALL_PROXY).toBe("socks5://127.0.0.1:7891");+ expect(env).not.toHaveProperty("PATH");+ });++ it("passes the lowercase forms through", () => {+ const env = networkEnv({ http_proxy: "http://p:1", https_proxy: "http://p:2", all_proxy: "socks5://p:3", no_proxy: "corp.example" });+ expect(env).toMatchObject({ http_proxy: "http://p:1", https_proxy: "http://p:2", all_proxy: "socks5://p:3" });+ expect(env.no_proxy).toBe(`corp.example,${LOOP}`);+ });++ it("passes certificate and package-index settings through", () => {+ const parent = Object.fromEntries(CERT_ENV.map((k) => [k, `v-${k}`]));+ expect(networkEnv(parent)).toEqual(parent);+ });++ it("merges loopback into NO_PROXY / no_proxy whenever a proxy is set", () => {+ const env = networkEnv({ HTTPS_PROXY: "http://p:1", NO_PROXY: "10.0.0.1, .corp.example,LOCALHOST" });+ // 用户的写法和顺序保留,已有的(不分大小写)不重复+ expect(env.NO_PROXY).toBe("10.0.0.1,.corp.example,LOCALHOST,127.0.0.1,::1");+ expect(env.no_proxy).toBe(env.NO_PROXY);+ // 没写 NO_PROXY 也补上+ expect(networkEnv({ https_proxy: "http://p:1" })).toMatchObject({ NO_PROXY: LOOP, no_proxy: LOOP });+ // 只设了 ALL_PROXY 也算有代理+ expect(networkEnv({ ALL_PROXY: "socks5://p:1" }).NO_PROXY).toBe(LOOP);+ // 两种大小写写得不一样:各自保留+ expect(networkEnv({ HTTP_PROXY: "http://p:1", NO_PROXY: "a", no_proxy: "b" })).toMatchObject({ NO_PROXY: `a,${LOOP}`, no_proxy: `b,${LOOP}` });+ expect(withLoopback("*")).toBe("*");+ });++ it("leaves NO_PROXY alone and sets nothing without a proxy", () => {+ expect(networkEnv({})).toEqual({});+ expect(networkEnv({ NO_PROXY: "corp.example", HTTPS_PROXY: " " })).toEqual({ NO_PROXY: "corp.example" });+ });++ it("uses the system proxy only when the environment names none", () => {+ const sys = proxyEnvFromPac("PROXY 127.0.0.1:7890");+ expect(networkEnv({}, sys)).toEqual({ ...sys, NO_PROXY: LOOP, no_proxy: LOOP });+ // 环境变量里的代理优先:系统代理整个不用+ expect(networkEnv({ https_proxy: "http://corp:3128" }, sys)).toEqual({ https_proxy: "http://corp:3128", NO_PROXY: LOOP, no_proxy: LOOP });+ });++ it("never carries a model key or token", () => {+ for (const k of [...PROXY_ENV, ...CERT_ENV]) expect(k).not.toMatch(/KEY|PASSWORD|SECRET|TOKEN/i);+ const env = networkEnv({ HTTPS_PROXY: "http://p:1", AMB_MAGPIE_API_KEY: "sk-real", OPENAI_API_KEY: "sk-x", FEISHU_APP_SECRET: "s", GITHUB_TOKEN: "t", HTTPS_PROXY_PASSWORD: "pw" });+ expect(Object.keys(env).sort()).toEqual(["HTTPS_PROXY", "NO_PROXY", "no_proxy"]);+ });+});++describe("system proxy (desktop: Electron resolveProxy)", () => {+ it("turns a PROXY result into http://host:port for both schemes", () => {+ const url = "http://127.0.0.1:7890";+ expect(proxyEnvFromPac("PROXY 127.0.0.1:7890")).toEqual({ HTTP_PROXY: url, HTTPS_PROXY: url, http_proxy: url, https_proxy: url });+ // 第一项算数;后面的 DIRECT 是退路+ expect(proxyEnvFromPac("PROXY proxy.corp:3128; DIRECT").HTTPS_PROXY).toBe("http://proxy.corp:3128");+ expect(proxyEnvFromPac("PROXY a:1;PROXY b:2").HTTPS_PROXY).toBe("http://a:1");+ expect(proxyEnvFromPac("HTTPS secure.corp:443").HTTPS_PROXY).toBe("https://secure.corp:443");+ expect(proxyEnvFromPac("PROXY [::1]:7890").HTTP_PROXY).toBe("http://[::1]:7890");+ });++ it("turns a SOCKS result into ALL_PROXY", () => {+ expect(proxyEnvFromPac("SOCKS5 127.0.0.1:7891")).toEqual({ ALL_PROXY: "socks5://127.0.0.1:7891", all_proxy: "socks5://127.0.0.1:7891" });+ // Chromium 的 SOCKS(不带 5)是 SOCKS4+ expect(proxyEnvFromPac("SOCKS 127.0.0.1:1080").ALL_PROXY).toBe("socks4://127.0.0.1:1080");+ });++ it("DIRECT (or nothing usable) sets nothing", () => {+ for (const pac of ["DIRECT", "", undefined, "DIRECT; PROXY a:1", "PROXY", "PROXY not a host", "QUIC q:443"]) expect(proxyEnvFromPac(pac)).toEqual({});+ });++ it("asks for each probe URL until one is proxied; errors and timeouts mean no proxy", async () => {+ const asked: string[] = [];+ const env = await systemProxyEnv(async (u) => (asked.push(u), u.includes("github") ? "PROXY 127.0.0.1:7890" : "DIRECT"));+ expect(asked).toEqual(PROXY_PROBE_URLS);+ expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:7890");+ expect(await systemProxyEnv(async () => "DIRECT")).toEqual({});+ expect(await systemProxyEnv(async () => undefined)).toEqual({});+ expect(await systemProxyEnv(async () => Promise.reject(new Error("boom")))).toEqual({});+ expect(await systemProxyEnv(() => new Promise(() => {}), 20)).toEqual({});+ });+});++describe("AgentHost env(): proxy for the agent child", () => {+ const NAMES = [...PROXY_ENV, ...CERT_ENV, "AMB_MAGPIE_API_KEY", "OPENAI_API_KEY", "FEISHU_APP_SECRET"];+ let saved: Record<string, string | undefined>;+ let dataDir: string;+ beforeEach(() => {+ saved = Object.fromEntries(NAMES.map((k) => [k, process.env[k]]));+ for (const k of NAMES) delete process.env[k];+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-proxy-"));+ });+ afterEach(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ fs.rmSync(dataDir, { recursive: true, force: true });+ });+ const host = (systemProxy?: (url: string) => Promise<string | undefined>) => {+ const h = new AgentHost({ botId: "b", dataDir, runtimeDir: "/rt", bridge: { url: "http://127.0.0.1:1", token: "bridge-tok" } as any, store: new Store(":memory:"), systemProxy });+ fs.mkdirSync(h.home, { recursive: true });+ return h as any;+ };++ it("passes the environment's proxy and certificates, merges loopback, and leaks no model key", async () => {+ process.env.HTTPS_PROXY = "http://127.0.0.1:7890";+ process.env.no_proxy = "corp.example";+ process.env.REQUESTS_CA_BUNDLE = "/etc/ssl/corp.pem";+ process.env.AMB_MAGPIE_API_KEY = "sk-real-model-key";+ process.env.OPENAI_API_KEY = "sk-other";+ process.env.FEISHU_APP_SECRET = "feishu-secret";+ let asked = 0;+ const h = host(async () => (asked++, "PROXY 10.9.9.9:8080"));+ // 环境里有代理:不问系统+ const env = h.env(await h.systemProxy());+ expect(asked).toBe(0);+ expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:7890");+ expect(env).not.toHaveProperty("HTTP_PROXY");+ expect(env.no_proxy).toBe(`corp.example,${LOOP}`);+ expect(env.NO_PROXY).toBe(`corp.example,${LOOP}`);+ expect(env.REQUESTS_CA_BUNDLE).toBe("/etc/ssl/corp.pem");+ // 宿主的 bridge 在回环上:不走代理+ expect(new URL(env.AMB_BRIDGE_URL).hostname).toBe("127.0.0.1");+ expect(env).not.toHaveProperty("NODE_USE_ENV_PROXY");+ const values = Object.values(env).join("\n");+ for (const secret of ["sk-real-model-key", "sk-other", "feishu-secret"]) expect(values).not.toContain(secret);+ expect(Object.keys(env).filter((k) => /KEY|SECRET/.test(k))).toEqual(["AMB_MAGPIE_KEY"]); // 这是 bridge 的令牌,不是模型密钥+ expect(env.AMB_MAGPIE_KEY).toBe("bridge-tok");+ });++ it("asks the desktop for the system proxy at every (re)start when the environment has none", async () => {+ let pac = "DIRECT";+ const h = host(async () => pac);+ expect(h.env(await h.systemProxy())).not.toHaveProperty("HTTPS_PROXY");+ // 用户后来开了代理:下次拉起就用上+ pac = "PROXY 127.0.0.1:7890";+ const env = h.env(await h.systemProxy());+ expect(env).toMatchObject({ HTTP_PROXY: "http://127.0.0.1:7890", HTTPS_PROXY: "http://127.0.0.1:7890", http_proxy: "http://127.0.0.1:7890", https_proxy: "http://127.0.0.1:7890", NO_PROXY: LOOP, no_proxy: LOOP });+ });++ it("command line and Docker: no desktop hook, nothing is invented", async () => {+ const h = host();+ expect(await h.systemProxy()).toEqual({});+ const env = h.env(await h.systemProxy());+ expect(hasEnvProxy(env)).toBe(false);+ expect(env).not.toHaveProperty("NO_PROXY");+ });+});