/** * ============================================================ * src/tools/webbrowser/agentBrowserPath.ts —— 解析 agent-browser 可执行文件 + 内置浏览器 * ------------------------------------------------------------ * 内置 agent 浏览器底座(Step1):WebBrowser 工具 / skill 脚本 / 工作流 bash 步 * 共用同一份「二进制定位 + 浏览器降级」逻辑 —— 单一事实源,完全对标 * ripgrep 的 `src/tools/grep/rgPath.ts`。 * * 引擎 = vercel-labs/agent-browser(原生 Rust CLI + CDP,已是 kakadeai 子模块, * 只读引用)。它的原生二进制按 `agent-browser--[.exe]` 命名、从 GitHub * releases 下载;我们像 vendor/ripgrep 一样把它放进 vendor/agent-browser/-/。 * * ── agent-browser 二进制定位(按优先级,全程 existsSync 过滤)── * ① MINIMAL_AGENT_BROWSER_PATH 环境变量(手动指定,调试最高优先) * ② 托管 npm 安装:当前状态根下 .minimal-agent/agent-browser * ③ 项目自带 vendor/agent-browser/-/agent-browser(.exe) * ④ 绿色版(bun --compile):exe 同级 vendor/agent-browser/...(compile 后 import.meta.url * 是虚拟路径、③ 命不中,绿色目录把 vendor/ 摆 exe 旁边从这捞回) * ⑤ 系统 PATH 上的 agent-browser(用户自己 npm i -g / brew / cargo 装的) * ⑥ 都没有 → null(调用方降级:返回可操作错误并提示回退 WebFetch) * * ── 浏览器(Chrome)分层降级(落实「opt2+opt3 融合」)── * agent-browser 自己会:读 AGENT_BROWSER_EXECUTABLE_PATH → 自动探测系统 * Chrome/Brave/Edge/Playwright/Puppeteer → 缺则可 `agent-browser install` 下完整 * Chrome for Testing。我们只补**离线兜底**:当无系统浏览器且无法联网安装时, * 用绿色版内置的轻量 chromium(resolveBundledChromium)保证「插上永远有浏览器」。 * dev/npm 下 vendor/chromium 不存在 → 返回 null → 不影响 agent-browser 原生探测。 * * dev/npm 模式零副作用:execPath 指向 node/bun 二进制,其同级没有 vendor/; * findPackageRoot 在源码/安装态下指向真实包根,vendor/agent-browser 不存在时 * existsSync 过滤掉 —— 与 rgPath/greenRoot 同一套「加性、命不中即丢弃」铁律。 * * 可测性:核心解析 detectAgentBrowser / resolveBundledChromium 都接受可注入依赖 * (env/exists/siblingDir/packageRoot/trySpawn),默认走真实实现;单测注入假依赖 * 确定性覆盖每条优先级分支,不碰真实 fs、不用 mock.module(见项目测试约定)。 * ============================================================ */ import { spawn } from 'node:child_process'; import { chmodSync, existsSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, isAbsolute, resolve, posix, win32 } from 'node:path'; import { sanitizeCredentialEnv } from '../../config/configService.js'; import { execSiblingDir } from '../../utils/greenRoot.js'; import { findPackageRoot } from '../../utils/packageRoot.js'; /** 可注入依赖(默认走真实实现,单测注入假实现)。 */ export interface ResolveDeps { env: NodeJS.ProcessEnv; exists: (p: string) => boolean; /** 绿色版 exe 同级目录。 */ siblingDir: () => string; /** 包根目录;找不到(compile 虚拟路径)返回 null。 */ packageRoot: () => string | null; /** 试跑 ` --version`,退出码 0 即 true。 */ trySpawn: (cmd: string) => Promise; /** 平台/架构(注入便于测试跨平台命名)。 */ platform: NodeJS.Platform; arch: string; } /** Locate the private on-demand npm install without requiring a global PATH entry. */ export function managedAgentBrowserRoot(env: NodeJS.ProcessEnv = process.env, fallbackHome = homedir()): string { return resolve(env.MINIMAL_AGENT_HOME?.trim() || env.HOME?.trim() || env.USERPROFILE?.trim() || fallbackHome, '.minimal-agent', 'agent-browser'); } export function managedAgentBrowserPath( deps: Pick, ): string | null { const stateRoot = deps.env.MINIMAL_AGENT_HOME?.trim() || deps.env.HOME?.trim() || deps.env.USERPROFILE?.trim(); if (!stateRoot) return null; const root = managedAgentBrowserRoot(deps.env, stateRoot); const packageBin = resolve(root, 'node_modules', 'agent-browser', 'bin'); if (deps.platform === 'win32') { const native = resolve(packageBin, 'agent-browser-win32-x64.exe'); if (deps.exists(native)) return native; } // The JS launcher selects glibc vs musl and x64 vs ARM64 at runtime. Keep // it for Unix so Alpine and aarch64 do not inherit a guessed binary name. const wrapper = resolve(packageBin, 'agent-browser.js'); if (deps.exists(wrapper)) return wrapper; return null; } function realDeps(): ResolveDeps { return { env: process.env, exists: existsSync, siblingDir: execSiblingDir, packageRoot: () => { try { return findPackageRoot(import.meta.url); } catch { return null; } }, trySpawn: defaultTrySpawn, platform: process.platform, arch: process.arch, }; } let cachedBin: string | null | undefined; /** * 解析一次 agent-browser 二进制路径,结果缓存(同进程复用)。 * 返回 null 表示找不到(调用方需降级)。 */ export async function resolveAgentBrowserPath(): Promise { if (cachedBin !== undefined) return cachedBin; cachedBin = await detectAgentBrowser(realDeps()); return cachedBin; } /** 仅供测试重置缓存。 */ export function _resetAgentBrowserCache(): void { cachedBin = undefined; } /** * 把已解析到的 agent-browser 二进制所在目录前置进 PATH —— 让子进程(Bash 工具 / * skill 脚本 / 工作流 bash 步)也能直接 `agent-browser ...`,实现 tools/skills/工作流 * **共用同一内置浏览器底座**。仅当解析到**绝对路径**(vendored/sibling/env)时生效; * 解析到裸 'agent-browser'(已在 PATH)或 null(没装)时 no-op —— dev/npm 无 vendored * 二进制时天然 no-op,与 greenRoot 同一套加性铁律。可纯函数化测试:注入 path/env。 * * 注意:离线兜底的轻量 chromium 仅 WebBrowser 工具自动补 --executable-path 用;直接 * 经 CLI 调 agent-browser 的 skill/bash 走 agent-browser 自身的自动探测/在线安装。 */ export async function ensureAgentBrowserOnPath(): Promise { applyBinToPath( await resolveAgentBrowserPath(), process.env, process.platform, ); } /** 纯函数:把 bin 所在目录前置进 env.PATH(已含则跳过;非绝对路径/null 不动)。 */ export function applyBinToPath( bin: string | null, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, ): void { if (!bin || bin === 'agent-browser') return; const pathApi = platform === 'win32' ? win32 : posix; if (!pathApi.isAbsolute(bin)) return; const dir = pathApi.dirname(bin); const sep = platform === 'win32' ? ';' : ':'; const resolvePath = pathApi.resolve; const cur = env.PATH ?? ''; const dirs = [dir]; // npm's private install keeps the executable under package/bin while the // shell shim lives under node_modules/.bin. Export both so Bash/skills and // the direct Browser tool resolve the same installed runner. if ( dir.endsWith(`${platform === 'win32' ? '\\' : '/'}bin`) && pathApi .dirname(dir) .endsWith(`${platform === 'win32' ? '\\' : '/'}agent-browser`) ) { dirs.unshift(resolvePath(dir, '..', '..', '.bin')); } const missing = dirs.filter( (candidate) => !cur.split(sep).includes(candidate), ); if (missing.length === 0) return; env.PATH = cur ? `${missing.join(sep)}${sep}${cur}` : missing.join(sep); } /** 纯解析(可注入依赖):按 ①→⑤ 优先级返回 agent-browser 二进制路径或 null。 */ export async function detectAgentBrowser( deps: ResolveDeps, ): Promise { const sub = subdir(deps); const bin = binName(deps); // ① 显式 env 覆盖 const fromEnv = deps.env.MINIMAL_AGENT_BROWSER_PATH; if (fromEnv && deps.exists(fromEnv)) return fromEnv; const managed = managedAgentBrowserPath(deps); if (managed) { ensureExecutable(managed, deps.platform); return managed; } // ② 项目自带 vendored(默认路径,开箱即用) const root = deps.packageRoot(); if (root) { const vendored = resolve(root, 'vendor', 'agent-browser', sub, bin); if (deps.exists(vendored)) { ensureExecutable(vendored, deps.platform); return vendored; } } // ③ 绿色版 exe 同级 const sibling = resolve( deps.siblingDir(), 'vendor', 'agent-browser', sub, bin, ); if (deps.exists(sibling)) { ensureExecutable(sibling, deps.platform); return sibling; } // ④ PATH 上的 agent-browser if (await deps.trySpawn('agent-browser')) return 'agent-browser'; // ⑤ 找不到 return null; } /** * 绿色版离线兜底:内置轻量 chromium 的可执行路径。返回 null 表示没带 * (dev/npm 常态,或绿色版未打包 chromium)—— 此时交回 agent-browser 自动探测/在线安装。 * * 约定布局:vendor/chromium/-/ 下放该平台 chromium,可执行名按平台 * 探测一组常见相对路径(不同 chromium 构建解包名不一,宁可多探几个)。 */ export function resolveBundledChromium( deps: ResolveDeps = realDeps(), ): string | null { const sub = subdir(deps); const roots: string[] = [ resolve(deps.siblingDir(), 'vendor', 'chromium', sub), ]; const root = deps.packageRoot(); if (root) roots.push(resolve(root, 'vendor', 'chromium', sub)); for (const r of roots) { for (const rel of chromiumExeCandidates(deps.platform)) { const p = resolve(r, rel); if (deps.exists(p)) { ensureExecutable(p, deps.platform); return p; } } } return null; } /** * `/snap/bin/` 是 snap-run 生成的**包装脚本**,不是真正的 ELF 可执行文件——它对 * `--version` 之类的单次探测完全透明(退出码正常、版本号正常),但 agent-browser daemon * 的启动/接管链路要的是能被直接 spawn、可稳定复用的真实二进制,指向包装脚本时 daemon * 迟迟不能就绪,45s 后只会报一个无信息量的 aborted 超时。 * * ⚠️ 真实事故(2026-09-16,teche-nvr,ARM64 Ubuntu,snap Chromium 136):现场重启+对照 * 实测已排除 --no-sandbox 缺失、snap AppArmor 沙箱两个最初怀疑的假因——唯一变量换成 * snap 包内的真实二进制后,daemon 的 open/snapshot/screenshot/stream status 四件套立即 * 100% 通过。ARM64 Linux 没有 Chrome for Testing 下载包(见 agentBrowserInstaller.ts 同类 * 注释),这台机器上 snap 是唯一能装到的 Chromium,这个坑绕不开,只能在这一层解开包装脚本。 */ function resolveSnapRealBinary( wrapperPath: string, exists: (p: string) => boolean, ): string | null { const match = /^\/snap\/bin\/([^/]+)$/.exec(wrapperPath); if (!match) return null; const snapName = match[1]!; // snap 包名与包内真实二进制名不总一致(chromium 包解包后的可执行文件叫 chrome), // current 是 snap 自己维护的「当前版本」软链接,随 snap refresh 自动指向新版本目录。 const binaryNames = [snapName, 'chrome', 'chromium', 'chromium-browser']; for (const bin of binaryNames) { const candidate = `/snap/${snapName}/current/usr/lib/${snapName}-browser/${bin}`; if (exists(candidate)) return candidate; } return null; } /** * Prefer a user-installed stable browser executable while keeping KakadeAI's * own profile directory. This improves site compatibility without touching * the user's normal Chrome profile or attempting fingerprint evasion. */ export function resolveSystemBrowser( deps: ResolveDeps = realDeps(), ): string | null { const explicit = deps.env.MINIMAL_AGENT_BROWSER_EXECUTABLE_PATH ?? deps.env.AGENT_BROWSER_EXECUTABLE_PATH; if (explicit && deps.exists(explicit)) return resolveSnapRealBinary(explicit, deps.exists) ?? explicit; const home = deps.env.HOME ?? deps.env.USERPROFILE ?? ''; const candidates = deps.platform === 'darwin' ? [ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', '/Applications/Chromium.app/Contents/MacOS/Chromium', home ? resolve( home, 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ) : '', ] : deps.platform === 'win32' ? [ deps.env.PROGRAMFILES ? resolve( deps.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe', ) : '', deps.env['PROGRAMFILES(X86)'] ? resolve( deps.env['PROGRAMFILES(X86)'], 'Microsoft/Edge/Application/msedge.exe', ) : '', deps.env.LOCALAPPDATA ? resolve( deps.env.LOCALAPPDATA, 'Google/Chrome/Application/chrome.exe', ) : '', ] : [ '/usr/bin/google-chrome-stable', '/usr/bin/google-chrome', '/usr/bin/microsoft-edge-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium', ]; const found = candidates.find((candidate) => candidate && deps.exists(candidate)); return found ? (resolveSnapRealBinary(found, deps.exists) ?? found) : null; } /** vendor 子目录名 = -(对齐 rgPath.ts / build-green.ts 的 vendor 约定)。 */ function subdir(deps: Pick): string { return `${deps.arch}-${deps.platform}`; } function binName(deps: Pick): string { return deps.platform === 'win32' ? 'agent-browser.exe' : 'agent-browser'; } /** 各平台 chromium 可执行的候选相对路径(解包布局因构建而异,逐个探)。 */ function chromiumExeCandidates(platform: NodeJS.Platform): string[] { switch (platform) { case 'win32': return ['chrome.exe', 'chrome-headless-shell.exe']; case 'darwin': return [ 'Chromium.app/Contents/MacOS/Chromium', 'Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing', 'chrome', 'chrome-headless-shell', ]; default: // linux return ['chrome', 'chrome-headless-shell', 'chromium']; } } /** * Unix 上 git/tarball/cp 偶尔丢可执行位;Windows 不需要。失败忽略(后续 spawn 会响亮报错)。 */ function ensureExecutable(path: string, platform: NodeJS.Platform): void { if (platform === 'win32') return; try { chmodSync(path, 0o755); } catch { /* ignore */ } } /** * 试 spawn ` --version`,退出码 0 即认为可用。 * 传命令名(非绝对路径)让 OS 解析 PATH;windowsHide 防弹窗;5s 兜底超时。 */ function defaultTrySpawn(cmd: string): Promise { return new Promise((resolveP) => { let settled = false; const done = (ok: boolean) => { if (settled) return; settled = true; resolveP(ok); }; try { const child = spawn(cmd, ['--version'], { stdio: ['ignore', 'ignore', 'ignore'], env: sanitizeCredentialEnv(), windowsHide: true, }); child.on('error', () => done(false)); child.on('close', (code) => done(code === 0)); setTimeout(() => { try { child.kill(); } catch {} done(false); }, 5_000); } catch { done(false); } }); }