import { spawn } from 'node:child_process'; import { readFile, writeFile } from 'node:fs/promises'; import { dirname, isAbsolute, join } from 'node:path'; import { _resetVerifiedRunnerCache, resolveOrHealAgentBrowserPath, } from './agentBrowserInstaller.js'; import { resolveAgentBrowserPath, resolveBundledChromium, resolveSystemBrowser, } from './agentBrowserPath.js'; import { type AgentBrowserRunner, type BrowserWindowMode, browserGlobalArgs, browserProfilePath, pinBrowserLaunch, runBounded, sessionArgs, spawnRunner, } from './browser.js'; /** * ⚠️ 真实事故:`launches`(下面那个 Map)只活在**当前进程**内存里,但 agent-browser * daemon 是刻意 detached 的长期后台进程——寿命远超启动它的那次 CLI 调用。下一次全新进程 * 里 `launches.get(sessionName)` 永远是 undefined,"windowMode 不一致就不能静默复用"这条 * (见 ensureDaemon 里的注释)因此从未真正生效过:只要探测到同名 daemon 在跑,不管它当初 * 是不是 headed 启动的,直接原样复用,还把内存记录悄悄改写成"当前是 desired 的模式"—— * 记录是假的,真实窗口还在。同一台机器上任何一次 headed 会话(人工介入/半自动接管)之后, * 所有"明明要无头"的后续调用都会一直复用那个可见窗口,直到有人手动关掉它。 * 用磁盘标记文件把 windowMode 绑定在 profile 目录上(profile 目录本身就是这个 Chrome * 实例的持久身份,天然跨进程可见),复用前先核对,不一致就当成不一致处理(强制关闭重启), * 而不是无条件相信内存里那份可能来自另一个进程、早已过期的记录。 */ function windowModeMarkerPath(profileId: string): string { return join(browserProfilePath(profileId), '.minimal-agent-window-mode'); } async function readPersistedWindowMode( profileId: string, ): Promise { const raw = await readFile(windowModeMarkerPath(profileId), 'utf8').catch( () => undefined, ); const trimmed = raw?.trim(); return trimmed === 'headed' || trimmed === 'headless' ? trimmed : undefined; } async function writePersistedWindowMode( profileId: string, windowMode: BrowserWindowMode, ): Promise { await writeFile(windowModeMarkerPath(profileId), windowMode, 'utf8').catch( () => undefined, ); } export interface BrowserDaemonInfo { sessionName: string; streamPort: number; pid?: number; alreadyRunning: boolean; } /** Daemon 启动(拉起 Chrome + CDP 就绪)总预算:超时即掐断并抛可操作错误,绝不无限挂。 */ export const DAEMON_BRINGUP_TIMEOUT_MS = 45_000; /** 单次 `stream status` 探测预算:daemon socket 卡死时不拖累调用方。 */ export const STATUS_TIMEOUT_MS = 8_000; const ports = new Map(); const starts = new Map>(); const cleanups = new Map>(); const launches = new Map< string, { profileId: string; windowMode: BrowserWindowMode } >(); /** Daemon 生命周期可选项:透传父级中断 signal + 覆盖启动预算 + 回收注入(测试用)。 */ export interface EnsureDaemonOptions { signal?: AbortSignal; timeoutMs?: number; reclaim?: ReclaimDeps; /** Forcefully rebuild a browser whose CDP endpoint has gone stale. */ forceRestart?: boolean; /** Isolated KakadeAI profile to use when this daemon is first launched. */ profileId?: string; /** agent-browser defaults to headless; headed is an explicit host request. */ windowMode?: BrowserWindowMode; } /** * Daemon 子进程执行缝(默认走真实实现):单测注入假 runner/resolveBin 即可确定性覆盖 * 「启动有界/可中断」等分支,不碰真 Chrome、不用 mock.module(见项目测试约定)。 */ export interface DaemonDeps { resolveBin: (signal?: AbortSignal) => Promise; runner: AgentBrowserRunner; } const realDaemonDeps: DaemonDeps = { resolveBin: (signal) => resolveOrHealAgentBrowserPath({}, signal), runner: spawnRunner, }; /** 回收残留进程用的杀进程执行器(默认真实 spawn,等它结束再 resolve;单测注入假实现断言作用域)。 */ export type ReclaimExec = (file: string, args: string[]) => Promise; const realReclaimExec: ReclaimExec = (file, args) => new Promise((resolve) => { try { const child = spawn(file, args, { stdio: 'ignore', windowsHide: true }); child.on('close', () => resolve()); child.on('error', () => resolve()); } catch { resolve(); } }); export interface ReclaimDeps { binDir?: () => Promise; platform?: NodeJS.Platform; exec?: ReclaimExec; } /** * 回收「本仓库/本 App 的」残留 agent-browser daemon + 其 Chrome 子树(Windows `taskkill /F /T`)。 * * 根因:agent-browser 的 daemon 是「黏」的后台进程,`--profile`/`--executable-path` 等 launch-only * flag 首次启动即固化、之后忽略(见 readStatus 头注)。一次无 profile 的启动就毒化整个 session, * 之后复用继承临时 profile、重启 App 也不解,且孤儿 Chrome 堆积。宿主(Desktop runtime)在启动时 * 调用一次本函数,把上一轮残留清干净,下次 bring-up 便以我们的持久 `--profile` 干净重启。 * * 安全:**仅**按「已解析二进制所在目录前缀」作用域匹配 agent-browser.exe,绝不误伤安装版桌面 App * 或系统上别处的 agent-browser 用法(对标 scripts/dev-browser.ts::reclaimStalePort)。无法作用域限定 * (PATH 上裸二进制 / 没装)时保守放弃,不做全局杀。幂等、best-effort(失败静默)。 */ export async function reclaimStaleDaemons( deps: ReclaimDeps = {}, ): Promise { const platform = deps.platform ?? process.platform; const exec = deps.exec ?? realReclaimExec; const resolveDir = deps.binDir ?? (async () => { const bin = await resolveAgentBrowserPath(); return bin && isAbsolute(bin) ? dirname(bin) : null; }); const dir = await resolveDir(); if (!dir) return; ports.clear(); if (platform === 'win32') { const root = dir.toLowerCase().replace(/'/g, "''"); const ps = // (a) 本 App 路径下的 agent-browser daemon + 其 Chrome 子树。 `Get-CimInstance Win32_Process -Filter "Name='agent-browser.exe'" | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.ToLower().StartsWith('${root}') } | ForEach-Object { taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null }; $alive=@{}; Get-CimInstance Win32_Process | ForEach-Object { $alive[[int]$_.ProcessId]=$true }; Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { ($_.CommandLine -match 'agent-browser-chrome' -or $_.CommandLine -match '\\.minimal-agent.{0,40}profiles') -and -not $alive.ContainsKey([int]$_.ParentProcessId) } | ForEach-Object { taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null }`; await exec('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps]); } else { // unix:按可执行路径前缀 pkill agent-browser(其 Chrome 子进程随之收尾)。unix 孤儿会被 // reparent 到 init,无「父已死」信号,故此处不做等价的孤儿 Chrome 清扫(Windows 才是主战场)。 await exec('pkill', ['-f', `${dir}/agent-browser`]); } } function parsePort(text: string): number | null { // agent-browser currently emits localhost URLs, but accept IPv6 loopback // as well. Snap/ARM builds have used both textual and JSON status output. const match = text.match( /wss?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]|::1):([0-9]+)/i, ); if (!match) return null; const port = Number(match[1]); return Number.isInteger(port) && port > 0 && port < 65_536 ? port : null; } type StreamStatus = { port: number | null; connected: boolean }; /** * Parse both the documented `stream status --json` response and the text * response used by older agent-browser releases. Do not trust arbitrary JSON * from stderr: only accept the small, typed status shape we need. */ function parseStreamStatus(text: string): StreamStatus | null { const candidates = [ text.trim(), ...text.split(/\r?\n/).map((line) => line.trim()), ]; for (const candidate of candidates) { if (!candidate.startsWith('{') || !candidate.endsWith('}')) continue; try { const value = JSON.parse(candidate) as Record; const rawPort = value.port; const port = typeof rawPort === 'number' ? rawPort : typeof rawPort === 'string' ? Number(rawPort) : null; const enabled = value.enabled; const connected = value.connected; if (!('port' in value || 'enabled' in value || 'connected' in value)) continue; if ( (port === null || (Number.isInteger(port) && port > 0 && port < 65_536)) && (connected === undefined || typeof connected === 'boolean') ) { return { port: enabled === false ? null : port !== null && Number.isInteger(port) && port > 0 && port < 65_536 ? port : null, connected: connected === true, }; } } catch { // Fall through to the legacy text parser. } } const port = parsePort(text); if (port === null && !/Connected:\s*(?:true|false)/i.test(text)) return null; return { port, connected: /Connected:\s*true/i.test(text) }; } export const _parseStreamStatus = parseStreamStatus; function browserRuntimeMissing(text: string): boolean { return /browser\s+(?:not found|was not found)|chrom(?:e|ium).*(?:not found|missing)|executable.*(?:not found|does not exist)|run ['\"]?agent-browser install/i.test( text, ); } export { browserRuntimeMissing as _browserRuntimeMissing }; async function readStatus( bin: string, sessionName: string, opts: EnsureDaemonOptions = {}, deps: DaemonDeps = realDaemonDeps, ): Promise { // Profile/executable flags are launch-only. Repeating them against a running // daemon makes agent-browser ignore the profile and emit misleading warnings. // 有界:daemon socket 卡死时不把 status 探测拖成无限挂(getStreamPort/ensureDaemon 都靠它)。 const deadline = Date.now() + (opts.timeoutMs ?? STATUS_TIMEOUT_MS); const probe = async (args: string[]) => { const remaining = Math.max(1, deadline - Date.now()); return runBounded( bin, [...sessionArgs(sessionName), ...args], { signal: opts.signal, timeoutMs: remaining }, deps.runner, ); }; // JSON is stable across locales and Snap wrappers. Keep the text fallback // for older agent-browser binaries which reject the --json flag. const jsonResult = await probe(['stream', 'status', '--json']); const jsonText = `${jsonResult.stdout}\n${jsonResult.stderr}`; if (jsonResult.code === 0) { const parsed = parseStreamStatus(jsonText); if (parsed) return parsed; } if (Date.now() >= deadline) return { port: null, connected: false }; const textResult = await probe(['stream', 'status']); if (textResult.code !== 0) return { port: null, connected: false }; return ( parseStreamStatus(`${textResult.stdout}\n${textResult.stderr}`) ?? { port: null, connected: false, } ); } async function waitForDaemonStopped( bin: string, sessionName: string, opts: EnsureDaemonOptions, deps: DaemonDeps, ): Promise { const deadline = Date.now() + Math.min(opts.timeoutMs ?? STATUS_TIMEOUT_MS, 2_000); while (Date.now() < deadline) { const status = await readStatus(bin, sessionName, opts, deps); if (!status.port && !status.connected) return; await new Promise((resolve) => setTimeout(resolve, 50)); } } /** * Some distro builds persist a disabled stream flag in the daemon profile. * Re-enable it after `open` so screenshots/desktop preview do not depend on a * previous invocation's state. Older agent-browser versions may not expose the * command; in that case the normal status probe remains the compatibility path. */ async function enableStreamBestEffort( bin: string, sessionName: string, signal: AbortSignal, deps: DaemonDeps, ): Promise { await runBounded( bin, [...sessionArgs(sessionName), 'stream', 'enable'], { signal, timeoutMs: 5_000 }, deps.runner, ).catch(() => undefined); } export async function ensureDaemon( sessionName = 'minimal-agent', opts: EnsureDaemonOptions = {}, deps: DaemonDeps = realDaemonDeps, ): Promise { if ( opts.windowMode === 'headed' && process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY ) { throw new Error( 'browser_display_missing: headed 需要 DISPLAY/Wayland;纯命令行请使用 --browser=headless', ); } if (opts.forceRestart) _resetVerifiedRunnerCache(); const bin = await deps.resolveBin(opts.signal); if (!bin) throw new Error('未找到 agent-browser 可执行文件'); // A failed prior launch may still be closing this exact session. The failed // caller is released promptly, while a retry waits here instead of racing // the late close against its new browser. await cleanups.get(sessionName); opts.signal?.throwIfAborted(); const desired = { profileId: opts.profileId ?? launches.get(sessionName)?.profileId ?? 'default', windowMode: opts.windowMode ?? launches.get(sessionName)?.windowMode ?? 'headless', }; // A daemon fixes profile/window mode at first launch. Do not silently reuse // a headless daemon for an explicit headed request (or vice versa). // // ⚠️ `launches`(内存)只对**当前进程**可信——daemon 是 detached 长期进程,寿命跨越单次 // CLI 调用,下一个全新进程里这个 Map 永远是空的。只信内存,这条"不静默复用"的保证在 // 「本进程刚启动、daemon 是之前某次调用留下的」这个最常见场景下从未生效过:磁盘标记 // 才是能跨进程存活的真相来源,必须一起核对;只要有一边认为不一致就按不一致处理。 const previousLaunch = launches.get(sessionName); const persistedWindowMode = await readPersistedWindowMode(desired.profileId); const launchMismatch = (previousLaunch !== undefined && (previousLaunch.profileId !== desired.profileId || previousLaunch.windowMode !== desired.windowMode)) || (persistedWindowMode !== undefined && persistedWindowMode !== desired.windowMode); if (opts.forceRestart || launchMismatch) { // Restart only this daemon; other CLI processes may use the same binary. await runBounded( bin, [...sessionArgs(sessionName), 'close'], { signal: opts.signal, timeoutMs: opts.timeoutMs ?? STATUS_TIMEOUT_MS }, deps.runner, ).catch(() => undefined); // `close` is asynchronous. Starting immediately can race with the old // daemon and produce "daemon already running" while its socket is dying. await waitForDaemonStopped(bin, sessionName, opts, deps); } const pinnedGlobals = await browserGlobalArgs(sessionName, desired.profileId, desired.windowMode); const pinnedBrowser = resolveSystemBrowser(); pinBrowserLaunch(bin, sessionName, [...pinnedGlobals, ...(pinnedBrowser ? ['--executable-path', pinnedBrowser] : [])]); const status = await readStatus( bin, sessionName, { signal: opts.signal }, deps, ); if (status.port && status.connected) { ports.set(sessionName, status.port); launches.set(sessionName, desired); // 复用路径也要落盘:标记缺失时(老 profile、这次修复之前建的)上面的 mismatch 判断 // 一直拿不到证据、只能放行复用——真复用发生后立刻把当前真实生效的 windowMode 写回去, // 下一次(哪怕是另一个全新进程)才有据可查,不必永远等到下次真正重启才补上这份记录。 if (persistedWindowMode !== desired.windowMode) await writePersistedWindowMode(desired.profileId, desired.windowMode); return { sessionName, streamPort: status.port, alreadyRunning: true }; } // 半死 daemon(socket 端口在、但 Chrome 已亡 connected:false):对谁都没用,先回收再重启, // 否则新 open 可能连到无 Chrome 的僵尸 daemon 上卡死。回收对健康的共享 daemon 无影响(那会 // 走上面的 connected 分支直接复用)。 if (status.port && !status.connected) { await runBounded( bin, [...sessionArgs(sessionName), 'close'], { signal: opts.signal, timeoutMs: opts.timeoutMs ?? STATUS_TIMEOUT_MS }, deps.runner, ); } const pending = starts.get(sessionName); if (pending) return pending; const budget = opts.timeoutMs ?? DAEMON_BRINGUP_TIMEOUT_MS; const start = (async () => { // Bring-up 边界:父级 signal abort 或超预算即掐断所有内部子进程。旧缺陷是 ensureDaemon // 全程无 timeout、不接 signal —— Chrome/CDP 起不来时无限挂、用户 stop/ESC 也掐不断 // (「访问网站卡 5m53s」的根因)。这里统一一个控制器兜住整段启动。 const ac = new AbortController(); let timedOut = false; const onParent = () => ac.abort(opts.signal?.reason); const timer = setTimeout(() => { timedOut = true; ac.abort(); }, budget); let phase = '准备浏览器运行时'; let launchTimedOut = false; let launchAttempted = false; if (opts.signal) { if (opts.signal.aborted) ac.abort(opts.signal.reason); else opts.signal.addEventListener('abort', onParent, { once: true }); } const bringUpError = () => new Error( timedOut ? `内置浏览器启动超时:Chrome 未在 ${Math.round(budget / 1000)}s 内就绪(可能被残留浏览器进程占用)。可稍后重试,或改用 WebFetch 读取网页。` : '内置浏览器启动已被中断。', ); // 单次尝试的自身上限;`budget` 可以被调用方传得很小(测试常传几十毫秒),这里必须 // 和 launch() 里实际传给 runBounded 的 timeoutMs 是同一个值,否则超时消息报的秒数 // 和真正等待的时长对不上。 const perAttemptTimeoutMs = Math.min(20_000, Math.max(1, budget)); const launch = async (args: string[]) => { launchAttempted = true; pinBrowserLaunch(bin, sessionName, args); const result = await runBounded( bin, args, // A distro wrapper (notably Snap) can keep the client alive while its // child browser is starting. Bound each attempt so we can try the // agent-browser auto-discovery path before the global bring-up budget. { signal: ac.signal, timeoutMs: perAttemptTimeoutMs }, deps.runner, ); launchTimedOut ||= result.timedOut === true; return result; }; try { phase = '启动 Chrome/Chromium'; const globals = await browserGlobalArgs( sessionName, desired.profileId, desired.windowMode, ); // Prefer a stable system browser executable, but always use KakadeAI's // isolated profile. Bundled Chromium remains an offline fallback. const systemBrowser = resolveSystemBrowser(); let opened = await launch([ ...globals, ...(systemBrowser ? ['--executable-path', systemBrowser] : []), 'open', 'about:blank', ]); if (ac.signal.aborted) throw bringUpError(); // `/snap/bin/chromium` is a wrapper. If that explicit executable does // not bring up a daemon, let agent-browser perform its own discovery; // this is often able to select the real snap payload or a downloaded // Chrome-for-Testing binary. Keep the retry limited to Snap paths. if (opened.code !== 0 && systemBrowser?.startsWith('/snap/')) { opened = await launch([...globals, 'open', 'about:blank']); if (ac.signal.aborted) throw bringUpError(); } if ( opened.code !== 0 && browserRuntimeMissing(`${opened.stderr}\n${opened.stdout}`) ) { const chromium = resolveBundledChromium(); if (chromium) { opened = await launch([ ...globals, '--executable-path', chromium, 'open', 'about:blank', ]); } else { throw new Error( 'browser_dependency_missing: 请显式运行 agent-browser install;Linux 可使用 agent-browser install --with-deps', ); } if (ac.signal.aborted) throw bringUpError(); } if (opened.code !== 0) { throw new Error( (opened.stderr || opened.stdout || '浏览器启动失败').trim(), ); } phase = '启用浏览器实时流'; await enableStreamBestEffort(bin, sessionName, ac.signal, deps); if (ac.signal.aborted) throw bringUpError(); phase = '等待实时流端口'; const streamPort = await waitForStreamPort(sessionName, 10_000, deps); ports.set(sessionName, streamPort); launches.set(sessionName, desired); // 落盘:下一个进程(甚至下一次同进程但内存已被别的调用覆盖)复用这个 daemon 前, // 能核对出它当初到底是不是以这个 windowMode 启动的,不必再盲信内存记录。 await writePersistedWindowMode(desired.profileId, desired.windowMode); return { sessionName, streamPort, alreadyRunning: false }; } catch (error) { _resetVerifiedRunnerCache(); // A timed-out `open` can leave a Snap/Chromium child and a half-created // agent-browser daemon behind. Only close when this invocation actually // timed out launching it; never turn a status-format/peer-daemon error // into a destructive close of a healthy shared daemon. if ( timedOut || launchTimedOut || (ac.signal.aborted && launchAttempted) ) { const cleanup = runBounded( bin, [...sessionArgs(sessionName), 'close'], { timeoutMs: 1_500 }, deps.runner, ).then( () => undefined, () => undefined, ); cleanups.set(sessionName, cleanup); void cleanup.finally(() => { if (cleanups.get(sessionName) === cleanup) cleanups.delete(sessionName); }); } if (timedOut) throw new Error( `内置浏览器启动超时:${phase}未在 ${Math.round(budget / 1000)}s 内完成。` + ' ARM/Snap 可检查 agent-browser stream status --json;也可改用 WebFetch。', ); // ⚠️ 真实事故:`launch()` 内部给每次尝试单独套了一层 20s 超时(`runBounded` 自己的 // 局部 timer/AbortController,与本函数外层这个 45s 预算完全是两套独立计时器)。单次 // 尝试冷启动 Chrome 超过 20s(常见于机器负载高/首次启动)时,只有 `launchTimedOut` 置位, // 外层 `timedOut`/`ac.signal.aborted` 全程未被触碰——原来的判断只看这两者,于是这类 // 超时会落空所有"友好消息"分支,直接把 Node child_process 底层的原生英文 abort 文案 // ("The operation was aborted")从 `opened.stderr` 一路冒泡到用户面前。 if (launchTimedOut) throw new Error( `内置浏览器启动超时:${phase}单次尝试未在 ${Math.round(perAttemptTimeoutMs / 1000)}s 内完成(可能是机器首次冷启动 Chrome 较慢,或被残留浏览器进程占用)。可稍后重试,或改用 WebFetch 读取网页。`, ); if ( (error instanceof Error && error.name === 'AbortError') || ac.signal.aborted ) throw bringUpError(); if ( error instanceof Error && error.message.startsWith('内置浏览器启动超时') ) throw error; throw new Error( `内置浏览器启动失败(${phase}):${ error instanceof Error ? error.message : String(error) }`, ); } finally { clearTimeout(timer); opts.signal?.removeEventListener('abort', onParent); } })().finally(() => starts.delete(sessionName)); starts.set(sessionName, start); return start; } export async function stopDaemon( sessionName = 'minimal-agent', deps: DaemonDeps = realDaemonDeps, reclaim?: ReclaimDeps, ): Promise { // Stopping must not install a missing browser. const bin = await (deps === realDaemonDeps ? resolveAgentBrowserPath() : deps.resolveBin()); ports.delete(sessionName); launches.delete(sessionName); if (bin) { await runBounded( bin, [...sessionArgs(sessionName), 'close'], { timeoutMs: STATUS_TIMEOUT_MS }, deps.runner, ); } // A tool may only stop its own daemon. Broad stale-process cleanup belongs // to an explicit host maintenance operation, never an individual tool call. } export async function getStreamPort( sessionName = 'minimal-agent', deps: DaemonDeps = realDaemonDeps, ): Promise { const cached = ports.get(sessionName); if (cached) return cached; const bin = await (deps === realDaemonDeps ? resolveAgentBrowserPath() : deps.resolveBin()); if (!bin) return null; const port = (await readStatus(bin, sessionName, {}, deps)).port; if (port) ports.set(sessionName, port); return port; } export async function waitForStreamPort( sessionName = 'minimal-agent', timeoutMs = 10_000, deps: DaemonDeps = realDaemonDeps, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const port = await getStreamPort(sessionName, deps); if (port) return port; await new Promise((resolve) => setTimeout(resolve, 120)); } throw new Error('浏览器已启动,但实时画面端口未就绪'); }