/** * Install the browser runner on demand for the current machine. * * The npm package is deliberately installed outside the minimal-agent * package. It contains platform launchers for the upstream project, while * the managed install only becomes reachable when the user explicitly enables * browser automation. This keeps normal installs small and avoids guessing a * target OS/CPU during packaging. */ import { runBoundedProcess } from '../../runtime/boundedProcess.js'; import { mkdir, readFile, stat } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { homedir } from 'node:os'; import { isAbsolute, join, relative, sep, win32 } from 'node:path'; import { verifyBrowserEnvironment, type BrowserHealthOptions } from './browserHealth.js'; import { _resetAgentBrowserCache, applyBinToPath, resolveAgentBrowserPath, resolveSystemBrowser, resolveBundledChromium, managedAgentBrowserRoot, } from './agentBrowserPath.js'; const PACKAGE = 'agent-browser@^0.37.0'; const INSTALL_TIMEOUT_MS = 10 * 60 * 1_000; export interface InstallCommandResult { code: number; stdout: string; stderr: string; } export interface AgentBrowserInstallerDeps { resolveExisting: () => Promise; probeRunner: (path: string, signal?: AbortSignal) => Promise; probeBrowser: (path: string, signal?: AbortSignal) => Promise; verifyEnvironment: (path: string, options: BrowserHealthOptions) => Promise; /** Full check on explicit enable; ordinary tool calls only repeat it after installation. */ verifyRendering: boolean; onProgress?: (message: string) => void; run: ( command: string, args: string[], timeoutMs?: number, signal?: AbortSignal, ) => Promise; makeDir: (path: string) => Promise; homeDir: () => string; env: NodeJS.ProcessEnv; platform: NodeJS.Platform; arch: string; exists: (path: string) => boolean; linuxRelease: () => Promise; isRoot: () => boolean; systemBrowser: () => string | null; readManagedVersion: (root: string) => Promise; signal?: AbortSignal; resolveWindowsNpm?: () => { command: string; prefix: string[] }; } /** Never spawn npm.cmd: Windows batch launchers require a shell. Resolve the * actual Node executable and npm JS entry instead, preserving literal argv. */ export function windowsNpmCommand( env: NodeJS.ProcessEnv = process.env, exists: (path: string) => boolean = existsSync, execPath = process.execPath, ): { command: string; prefix: string[] } { const pathValue = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? ''; const dirs = pathValue.split(';').map(dir => dir.trim().replace(/^"|"$/g, '')).filter(Boolean); const node = [env.npm_node_execpath, ...(win32.basename(execPath).toLowerCase() === 'node.exe' ? [execPath] : []), ...dirs.map(dir => win32.join(dir, 'node.exe'))].find(path => path && exists(path)); if (!node) throw new Error('Windows 浏览器安装需要 Node.js 与 npm;未找到 node.exe,请安装 Node.js 并配置 PATH。'); const cli = [env.npm_execpath, ...[win32.dirname(node), ...dirs].map(dir => win32.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'))] .find(path => path && win32.basename(path).toLowerCase() === 'npm-cli.js' && exists(path)); if (!cli) throw new Error('Windows 浏览器安装未找到 npm-cli.js;请修复 Node.js/npm 安装,不会尝试直接执行 npm.cmd。'); return { command: node, prefix: [cli] }; } async function runCommand( command: string, args: string[], timeoutMs = INSTALL_TIMEOUT_MS, signal?: AbortSignal, ): Promise { const result = await runBoundedProcess(command, args, { timeoutMs, signal, allowTruncatedOutput: true }); return { code: result.exitCode, stdout: result.stdout + (result.stdoutPath ? `\n完整输出:${result.stdoutPath}` : ''), stderr: result.stderr + (result.stderrPath ? `\n完整输出:${result.stderrPath}` : ''), }; } export { managedAgentBrowserRoot } from './agentBrowserPath.js'; export function npmInstallArgs(root: string): string[] { return [ 'install', '--prefix', root, '--no-save', '--no-package-lock', '--no-audit', '--no-fund', PACKAGE, ]; } export function browserInstallArgs(): string[] { return ['install']; } const realDeps: AgentBrowserInstallerDeps = { verifyEnvironment: verifyBrowserEnvironment, verifyRendering: true, resolveExisting: resolveAgentBrowserPath, probeRunner: async (path, signal) => { try { return (await runCommand(path, ['--version'], 15_000, signal)).code === 0; } catch (error) { if (signal?.aborted) throw error; return false; } }, probeBrowser: async (path, signal) => { try { return (await runCommand(path, ['--version'], 15_000, signal)).code === 0; } catch (error) { if (signal?.aborted) throw error; return false; } }, run: runCommand, makeDir: async (path) => { await mkdir(path, { recursive: true, mode: 0o700 }); }, homeDir: homedir, env: process.env, platform: process.platform, arch: process.arch, exists: existsSync, linuxRelease: () => readFile('/etc/os-release', 'utf8'), isRoot: () => process.getuid?.() === 0, systemBrowser: () => resolveSystemBrowser() ?? resolveBundledChromium(), readManagedVersion: async (root) => { try { const packageJson = await import('node:fs/promises').then( ({ readFile }) => readFile( join(root, 'node_modules', 'agent-browser', 'package.json'), 'utf8', ), ); const parsed = JSON.parse(packageJson) as { version?: unknown }; return typeof parsed.version === 'string' ? parsed.version : null; } catch { return null; } }, }; function isCompatibleManagedVersion(version: string | null): boolean { return typeof version === 'string' && /^0\.37\.\d+$/.test(version); } /** * Return an existing runner, or install the official npm package into the * user's private state directory and make it visible to this process. */ async function ensureRunner(deps: AgentBrowserInstallerDeps): Promise<{ path: string; installed: boolean }> { deps.onProgress?.('检查 agent-browser 启动器与版本…'); const existing = await deps.resolveExisting(); const root = managedAgentBrowserRoot(deps.env, deps.homeDir()); const relativePath = existing ? relative(root, existing) : null; const isManaged = relativePath !== null && relativePath !== '..' && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath); const managedVersion = isManaged ? await deps.readManagedVersion(root) : null; if (existing && (!isManaged || isCompatibleManagedVersion(managedVersion)) && await deps.probeRunner(existing, deps.signal)) { if (isManaged) deps.env.MINIMAL_AGENT_BROWSER_PATH = existing; applyBinToPath(existing, deps.env, deps.platform); return { path: existing, installed: false }; } await deps.makeDir(root); deps.onProgress?.('安装或修复 agent-browser,可能需要几分钟…'); const npm = deps.platform === 'win32' ? (deps.resolveWindowsNpm?.() ?? windowsNpmCommand(deps.env)) : { command: 'npm', prefix: [] }; const npmResult = await deps.run( npm.command, [...npm.prefix, ...npmInstallArgs(root)], INSTALL_TIMEOUT_MS, deps.signal, ); if (npmResult.code !== 0) { throw new Error( `agent-browser 安装失败(npm 退出码 ${npmResult.code}):${ npmResult.stderr || npmResult.stdout || '无输出' }`, ); } _resetAgentBrowserCache(); const installedPath = await deps.resolveExisting(); if (!installedPath) { throw new Error( `agent-browser 已下载但未找到当前平台启动器(${deps.platform}/${deps.arch})。`, ); } if (!await deps.probeRunner(installedPath, deps.signal)) { throw new Error(`agent-browser 启动器不能在 ${deps.platform}/${deps.arch} 运行:${installedPath}。请检查显式 MINIMAL_AGENT_BROWSER_PATH 是否指向旧的或其他平台文件,以及系统运行库是否齐全。`); } deps.env.MINIMAL_AGENT_BROWSER_PATH = installedPath; applyBinToPath(installedPath, deps.env, deps.platform); return { path: installedPath, installed: true }; } async function ensureBrowserRuntime(path: string, deps: AgentBrowserInstallerDeps): Promise { deps.onProgress?.('检查 Chrome/Chromium 可执行文件与运行依赖…'); const existing = deps.systemBrowser(); if (existing && await deps.probeBrowser(existing, deps.signal)) { deps.env.AGENT_BROWSER_EXECUTABLE_PATH = existing; deps.onProgress?.(`浏览器已就绪,已配置路径:${existing}`); return false; } if (existing && deps.env.MINIMAL_AGENT_BROWSER_EXECUTABLE_PATH) { throw new Error(`已配置的浏览器无法执行:${existing}。请修复该浏览器或清除浏览器路径环境变量后重新开启。`); } // Upstream install is idempotent (it reuses its download cache). Run it even // for an existing launcher when no usable system/explicit browser is found: // a previous attempt may have installed npm successfully but failed here. { deps.onProgress?.('安装或修复浏览器运行环境,可能需要几分钟…'); if (deps.platform === 'linux' && ['arm64', 'arm'].includes(deps.arch)) { const release = await deps.linuxRelease(); let command: string; let args: string[]; if (/^ID=["']?ubuntu["']?$/m.test(release) && deps.exists('/usr/bin/snap')) { command = '/usr/bin/snap'; args = ['install', 'chromium']; } else if (deps.exists('/usr/bin/apt-get')) { command = '/usr/bin/apt-get'; args = ['install', '-y', /^ID=["']?ubuntu["']?$/m.test(release) ? 'chromium-browser' : 'chromium']; } else if (deps.exists('/usr/bin/dnf')) { command = '/usr/bin/dnf'; args = ['install', '-y', 'chromium']; } else if (deps.exists('/usr/bin/pacman')) { command = '/usr/bin/pacman'; args = ['-S', '--needed', '--noconfirm', 'chromium']; } else if (deps.exists('/sbin/apk')) { command = '/sbin/apk'; args = ['add', 'chromium']; } else { throw new Error(`Linux ${deps.arch} 没有 Chrome for Testing 下载包。请通过系统包管理器安装 Chromium,或设置 MINIMAL_AGENT_BROWSER_EXECUTABLE_PATH 指向已有浏览器。`); } // Never prompt for passwords in FieldForm's non-interactive child pipes. // Authorized unattended sudo works; otherwise give an exact terminal step. const root = deps.isRoot(); const result = await deps.run(root ? command : 'sudo', root ? args : ['-n', command, ...args], INSTALL_TIMEOUT_MS, deps.signal); if (result.code !== 0) throw new Error(`Linux ${deps.arch} Chromium 安装未完成:${result.stderr || result.stdout}。请在终端执行:sudo ${command} ${args.join(' ')},完成后重新开启浏览器。`); const browser = deps.systemBrowser(); if (!browser) throw new Error('Chromium 安装命令已完成,但未找到可执行文件。请设置 MINIMAL_AGENT_BROWSER_EXECUTABLE_PATH 后重新开启。'); if (!await deps.probeBrowser(browser, deps.signal)) throw new Error(`Chromium 安装后仍无法执行:${browser}。请检查系统运行库及安装命令输出。`); deps.env.AGENT_BROWSER_EXECUTABLE_PATH = browser; return true; } const browserResult = await deps.run( path, browserInstallArgs(), INSTALL_TIMEOUT_MS, deps.signal, ); if (browserResult.code !== 0) { throw new Error( `Chrome 安装失败(agent-browser 退出码 ${browserResult.code}):${ browserResult.stderr || browserResult.stdout || '无输出' }。可以先安装系统 Chrome,或手动运行 agent-browser install。`, ); } return true; } } export async function ensureAgentBrowserInstalled( overrides: Partial = {}, ): Promise<{ path: string; installed: boolean; chromiumInstalled: boolean }> { const deps = { ...realDeps, ...overrides }; deps.signal?.throwIfAborted(); deps.onProgress?.(`重新检查浏览器环境:${deps.platform}/${deps.arch}`); _resetAgentBrowserCache(); const runner = await ensureRunner(deps); const chromiumInstalled = await ensureBrowserRuntime(runner.path, deps); if (deps.verifyRendering || runner.installed || chromiumInstalled) { await deps.verifyEnvironment(runner.path, { executablePath: deps.env.AGENT_BROWSER_EXECUTABLE_PATH, signal: deps.signal, onProgress: deps.onProgress, }); } deps.onProgress?.('环境检查与配置完成,正在保存开启状态…'); return { ...runner, chromiumInstalled }; } /** A verified environment cache is short-lived and tied to both executable files. */ const verifiedEnvironments = new Map(); interface HealFlight { controller: AbortController; promise: Promise; waiters: number } const healFlights = new Map(); export function _resetVerifiedRunnerCache(): void { verifiedEnvironments.clear(); } export const probeAgentBrowserRunner = realDeps.probeRunner; async function environmentFingerprint(path: string): Promise { const browser = resolveSystemBrowser() ?? resolveBundledChromium(); if (!browser) return undefined; try { const files = await Promise.all([path, browser].map(async (file) => { const s = await stat(file); return [file, s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs]; })); return JSON.stringify([files, process.platform, process.arch, process.env.AGENT_BROWSER_EXECUTABLE_PATH]); } catch { return undefined; } } /** Join one environment check/install; cancellation detaches one waiter, or stops the last one's job. */ export async function resolveOrHealAgentBrowserPath( deps: { resolveExisting?: () => Promise; ensureInstalled?: (overrides?: Partial) => Promise<{ path: string; installed: boolean; chromiumInstalled: boolean }>; fingerprint?: (path: string) => Promise; installationKey?: string; } = {}, signal?: AbortSignal, ): Promise { signal?.throwIfAborted(); const key = deps.installationKey ?? managedAgentBrowserRoot(); let flight = healFlights.get(key); if (!flight) { const controller = new AbortController(); const fresh: HealFlight = { controller, waiters: 0, promise: Promise.resolve('') }; // Defer execution until the flight is registered and the first waiter attached. fresh.promise = Promise.resolve().then(async () => { controller.signal.throwIfAborted(); const existing = await (deps.resolveExisting ?? resolveAgentBrowserPath)(); const fingerprint = deps.fingerprint ?? environmentFingerprint; const current = existing ? await fingerprint(existing) : undefined; const cached = verifiedEnvironments.get(key); if (existing && current && cached?.path === existing && cached.fingerprint === current && cached.until > Date.now()) return existing; verifiedEnvironments.delete(key); const result = await (deps.ensureInstalled ?? ensureAgentBrowserInstalled)({ signal: controller.signal, verifyRendering: false }); controller.signal.throwIfAborted(); const identity = await fingerprint(result.path); if (identity) verifiedEnvironments.set(key, { path: result.path, fingerprint: identity, until: Date.now() + 30_000 }); return result.path; }).finally(() => { if (healFlights.get(key) === fresh) healFlights.delete(key); }); healFlights.set(key, fresh); flight = fresh; } flight.waiters++; let onAbort: (() => void) | undefined; try { return await Promise.race([flight.promise, new Promise((_, reject) => { onAbort = () => reject(new DOMException('Aborted', 'AbortError')); signal?.addEventListener('abort', onAbort, { once: true }); if (signal?.aborted) onAbort(); })]); } finally { if (onAbort) signal?.removeEventListener('abort', onAbort); if (--flight.waiters === 0 && healFlights.get(key) === flight) { flight.controller.abort(); // Keep the flight registered until the installer exits: no overlapping installs. } } }