/** * Persistent CDP transport used by BrowserBatch and BrowserCDP. * * The browser daemon is deliberately still owned by agent-browser; this module * only replaces the short lived command clients used for each automation step. */ import { mkdir, stat } from 'node:fs/promises'; import { createHash } from 'node:crypto'; import { agentStateDir } from '../../context/agentHome.js'; import path from 'node:path'; import type { AgentBrowserRunner } from './browser.js'; import { runBounded, sessionArgs } from './browser.js'; export type CdpEvent = { sequence: number; method: string; params: Record; sessionId?: string; at: number; }; export type BrowserDownload = { id: string; url: string; filename: string; path: string; state: 'start' | 'progress' | 'complete' | 'failed' | 'canceled'; receivedBytes?: number; totalBytes?: number; mime?: string; error?: string; }; export const BROWSER_TAB_MARKER_KEY = '__minimalAgentTabMarker'; type Pending = { resolve: (value: unknown) => void; reject: (reason: Error) => void; timer: ReturnType; onAbort?: () => void; signal?: AbortSignal; }; export class CdpConnection { private socket: WebSocket | null = null; private opening: Promise | null = null; private pageTargetId: string | undefined; private pageSessionId: string | undefined; private id = 0; private pending = new Map(); private events: CdpEvent[] = []; private sequence = 0; private listeners = new Set<(event: CdpEvent) => void>(); private inputListeners = new Set<(params: Record) => void>(); constructor(private readonly url: string) {} subscribeInput(listener: (params: Record) => void): () => void { this.inputListeners.add(listener); return () => { this.inputListeners.delete(listener); }; } /** * A connection is page-scoped. It must not be put back in a process-wide * pool and rebound by another conversation while this caller still holds it. */ close(): void { const socket = this.socket; this.resetTransport(); socket?.close(); } private resetTransport(): void { this.socket = null; this.pageTargetId = undefined; this.pageSessionId = undefined; for (const request of this.pending.values()) { clearTimeout(request.timer); if (request.onAbort) request.signal?.removeEventListener('abort', request.onAbort); request.reject(new Error('CDP connection closed')); } this.pending.clear(); } get attachedPageSessionId(): string | undefined { return this.pageSessionId; } get attachedPageTargetId(): string | undefined { return this.pageTargetId; } async evaluateInFrame( frameId: string, expression: string, signal?: AbortSignal, ): Promise { const isolated = (await this.send( 'Page.createIsolatedWorld', { frameId, worldName: 'minimal-agent-browser', grantUniveralAccess: false, }, undefined, 30_000, signal, )) as { executionContextId?: unknown }; if (typeof isolated.executionContextId !== 'number') throw new Error(`无法创建 frame execution context:${frameId}`); return this.send( 'Runtime.evaluate', { expression, contextId: isolated.executionContextId, returnByValue: true, awaitPromise: true, }, undefined, 30_000, signal, ); } async frameOwnerOffset( frameId: string, signal?: AbortSignal, ): Promise<{ x: number; y: number }> { const tree = await this.send('Page.getFrameTree', {}, undefined, 30_000, signal) as { frameTree?: { frame?: { id?: string } } }; // The main frame has no owning iframe. Opaque references intentionally // carry its frameId too, unlike old selector-only calls. if (tree.frameTree?.frame?.id === frameId) return { x: 0, y: 0 }; // CDP returns the owner quad in top-level viewport coordinates, including // nested cross-origin frames. Do not add ancestor offsets a second time. const owner = (await this.send( 'DOM.getFrameOwner', { frameId }, undefined, 30_000, signal, )) as { backendNodeId?: unknown }; if (typeof owner.backendNodeId !== 'number') throw new Error(`无法取得 frame owner:${frameId}`); const box = (await this.send( 'DOM.getBoxModel', { backendNodeId: owner.backendNodeId }, undefined, 30_000, signal, )) as { model?: { border?: unknown } }; const border = box.model?.border; if (!Array.isArray(border) || border.length < 2) throw new Error(`无法取得 frame owner 坐标:${frameId}`); const numbers = border.filter( (value): value is number => typeof value === 'number', ); if (numbers.length < 2) throw new Error(`frame owner 坐标无效:${frameId}`); return { x: numbers[0]!, y: numbers[1]! }; } async open(): Promise { if (this.socket?.readyState === WebSocket.OPEN) return; if (this.opening) return this.opening; this.opening = new Promise((resolve, reject) => { const socket = new WebSocket(this.url); this.socket = socket; const timer = setTimeout(() => { socket.close(); reject(new Error('CDP connection timed out')); }, 10_000); socket.onopen = () => { clearTimeout(timer); if (this.socket !== socket) { socket.close(); reject(new Error('CDP connection closed')); return; } resolve(); }; socket.onerror = () => { clearTimeout(timer); reject(new Error('Unable to connect to browser CDP')); }; socket.onclose = () => { clearTimeout(timer); reject(new Error('CDP connection closed')); // Late events from a retired socket cannot tear down its replacement. if (this.socket === socket) this.resetTransport(); }; socket.onmessage = (message) => { if (this.socket === socket) this.onMessage(String(message.data)); }; }).finally(() => { this.opening = null; }); return this.opening; } private onMessage(raw: string): void { let data: Record; try { data = JSON.parse(raw) as Record; } catch { return; } if (typeof data.id === 'number') { const request = this.pending.get(data.id); if (!request) return; this.pending.delete(data.id); clearTimeout(request.timer); if (request.signal && request.onAbort) request.signal.removeEventListener('abort', request.onAbort); if (data.error) request.reject(new Error(JSON.stringify(data.error))); else request.resolve(data.result ?? {}); return; } if (typeof data.method !== 'string') return; const event: CdpEvent = { sequence: ++this.sequence, method: data.method, params: (data.params ?? {}) as Record, sessionId: typeof data.sessionId === 'string' ? data.sessionId : undefined, at: Date.now(), }; if ( event.method === 'Target.detachedFromTarget' && String(event.params.sessionId ?? '') === this.pageSessionId ) { this.pageTargetId = undefined; this.pageSessionId = undefined; } if ( (event.method === 'Target.targetDestroyed' || event.method === 'Target.targetCrashed') && String(event.params.targetId ?? '') === this.pageTargetId ) { this.pageTargetId = undefined; this.pageSessionId = undefined; } this.events.push(event); if (this.events.length > 500) this.events.splice(0, this.events.length - 500); for (const listener of this.listeners) { try { listener(event); } catch { // One observer must not break delivery to the remaining CDP consumers. } } } async send( method: string, params: Record = {}, target?: string, timeoutMs = 30_000, signal?: AbortSignal, ): Promise { await this.open(); const socket = this.socket; if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('CDP connection is unavailable'); const id = ++this.id; const pageDomain = /^(Accessibility|DOM|Input|Log|Network|Page|Performance|Runtime|Security)\./.test( method, ); const effectiveTarget = target ?? (pageDomain ? this.pageSessionId : undefined); return new Promise((resolve, reject) => { const abortError = () => signal?.reason instanceof Error ? signal.reason : new Error(`CDP ${method} aborted`); const cleanup = () => { const request = this.pending.get(id); if (!request) return false; this.pending.delete(id); clearTimeout(request.timer); if (request.signal && request.onAbort) request.signal.removeEventListener('abort', request.onAbort); return true; }; const onAbort = () => { if (cleanup()) reject(abortError()); }; const timer = setTimeout(() => { if (cleanup()) reject(new Error(`CDP ${method} timed out`)); }, timeoutMs); this.pending.set(id, { resolve, reject, timer, onAbort, signal }); if (signal?.aborted) { onAbort(); return; } signal?.addEventListener('abort', onAbort, { once: true }); try { if (method === 'Input.dispatchMouseEvent') for (const listener of this.inputListeners) { try { listener(params); } catch { /* UI decoration must not block execution. */ } } socket.send( JSON.stringify({ id, method, params, ...(effectiveTarget ? { sessionId: effectiveTarget } : {}), }), ); } catch (error) { if (cleanup()) reject(error instanceof Error ? error : new Error(String(error))); } }); } async attachToPage( preferredUrl?: string, force = false, preferredMarker?: string, ): Promise { if (this.pageSessionId && !force) return; // A fresh marker must still be verified on every lease. If it is on the // already attached page, preserve the attachment and its event stream. const matchesMarker = async (sessionId: string) => { const response = await this.send('Runtime.evaluate', { expression: `globalThis[${JSON.stringify(BROWSER_TAB_MARKER_KEY)}] === ${JSON.stringify(preferredMarker)}`, returnByValue: true, }, sessionId).catch(() => undefined); return (response as { result?: { value?: unknown } } | undefined)?.result?.value === true; }; const current = this.pageSessionId; if (preferredMarker && current && await matchesMarker(current) && current === this.pageSessionId) return; if (force && this.pageSessionId) { const previousSession = this.pageSessionId; this.pageSessionId = undefined; this.pageTargetId = undefined; await this.send('Target.detachFromTarget', { sessionId: previousSession, }).catch(() => undefined); } const targets = (await this.send('Target.getTargets')) as { targetInfos?: Array<{ targetId?: unknown; type?: unknown; url?: unknown; }>; }; const pages = (targets.targetInfos ?? []).filter( (target) => target.type === 'page' && typeof target.targetId === 'string', ); if (!pages.length) throw new Error('浏览器没有可绑定的页面标签'); let selected = preferredMarker ? undefined : preferredUrl ? pages.find((target) => target.url === preferredUrl) : undefined; if (preferredMarker) { for (const candidate of pages) { const attached = (await this.send('Target.attachToTarget', { targetId: candidate.targetId, flatten: true, })) as { sessionId?: unknown }; const sessionId = attached.sessionId; if (typeof sessionId !== 'string') continue; if (await matchesMarker(sessionId)) { selected = candidate; this.pageTargetId = String(candidate.targetId); this.pageSessionId = sessionId; break; } await this.send('Target.detachFromTarget', { sessionId }).catch( () => undefined, ); } } if (preferredMarker) { // Only a verified marker establishes ownership of a stable target ID. // URL equality and page count never establish conversation ownership. if (!selected) { throw new Error('无法通过会话标记绑定到当前浏览器标签'); } return; } selected ??= pages[pages.length - 1]!; const attached = (await this.send('Target.attachToTarget', { targetId: selected.targetId, flatten: true, })) as { sessionId?: unknown }; if (typeof attached.sessionId !== 'string') throw new Error('浏览器未返回页面 target session'); this.pageTargetId = selected.targetId as string; this.pageSessionId = attached.sessionId; } read(after = 0, methods?: string[], limit = 100): CdpEvent[] { return this.events .filter( (event) => event.sequence > after && (!methods?.length || methods.includes(event.method)), ) .slice(-Math.max(1, Math.min(limit, 500))); } subscribe(listener: (event: CdpEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } } const connectionPool = new Map }>(); const connectionKeys = new WeakMap(); export function browserPagePoolKey(conversation: string, tabId: string): string { return JSON.stringify([conversation, tabId]); } /** Snapshot the existing page buffer synchronously. Never open a socket or * start a browser to answer a question about historical events. */ export function bufferedPageHistory(session: string, pageKey: string, target?: string) { const matches = [...connectionPool].filter(([key, { connection }]) => { const [owner, , page] = key.split('\u0000'); return owner === session && page === pageKey && connection.attachedPageSessionId && (!target || connection.attachedPageSessionId === target); }); if (matches.length !== 1) throw new Error('原标签的调试事件历史不可用或无法唯一确定;没有启动新的连接'); const connection = matches[0]![1].connection; return { events: connection.read(0, undefined, 500), sessionId: connection.attachedPageSessionId, targetId: connection.attachedPageTargetId }; } export function disposeBrowserAutomation(sessionName: string): void { for (const [key, entry] of connectionPool) { if (!key.startsWith(`${sessionName}\u0000`)) continue; if (entry.idleTimer) clearTimeout(entry.idleTimer); connectionPool.delete(key); entry.connection.close(); } } export function releaseBrowserAutomation(connection: CdpConnection): void { const key = connectionKeys.get(connection); const entry = key ? connectionPool.get(key) : undefined; if (!key || !entry || entry.connection !== connection) return connection.close(); if (!entry.leased) return; entry.leased = false; if (entry.idleTimer) clearTimeout(entry.idleTimer); entry.idleTimer = setTimeout(() => { if (connectionPool.get(key)?.connection === connection) { connectionPool.delete(key); connection.close(); } }, 30_000); entry.idleTimer.unref?.(); } function extractCdpUrl(text: string): string | 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; for (const key of ['cdp_url', 'cdpUrl', 'webSocketDebuggerUrl', 'url']) { const raw = value[key]; if (typeof raw === 'string' && /^wss?:\/\//i.test(raw)) return raw; } } catch { // The default text output is a bare WebSocket URL; use the regex below. } } const match = text.match(/wss?:\/\/[^\s"'<>]+/i)?.[0]; return match?.replace(/[),.;]+$/, '') ?? null; } export const _extractCdpUrl = extractCdpUrl; async function cdpUrl( sessionName: string, bin: string, run: AgentBrowserRunner, signal?: AbortSignal, ): Promise { // The caller owns launch configuration. Looking up CDP must never restart Chrome. const deadline = Date.now() + 10_000; let lastOutput = ''; while (Date.now() < deadline) { const output = await runBounded( bin, [...sessionArgs(sessionName), 'get', 'cdp-url'], { signal, timeoutMs: Math.min(3_000, Math.max(1, deadline - Date.now())), }, run, ); lastOutput = `${output.stdout}\n${output.stderr}`.trim(); const url = output.code === 0 ? extractCdpUrl(lastOutput) : null; if (url) return url; if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error('浏览器 CDP 地址获取已被中断'); await new Promise((resolve) => setTimeout(resolve, 150)); } const detail = lastOutput ? `:${lastOutput.slice(0, 300)}` : ''; throw new Error(`无法取得浏览器 CDP 地址${detail}`); } export async function getBrowserAutomation( sessionName: string, bin: string, run: AgentBrowserRunner, signal?: AbortSignal, preferredUrl?: string, preferredMarker?: string, pageKey?: string, ): Promise { const url = await cdpUrl(sessionName, bin, run, signal); // Pool by daemon endpoint and caller-owned page key, never by page URL. // Revalidate the ownership marker before returning each lease. const key = `${sessionName}\u0000${url}\u0000${pageKey ?? preferredMarker ?? crypto.randomUUID()}`; let entry = connectionPool.get(key); // An active caller retains its own page attachment. Never rebind its socket. if (entry?.leased) { const isolated = new CdpConnection(url); try { await isolated.open(); await isolated.attachToPage(preferredUrl, true, preferredMarker); return isolated; } catch (error) { isolated.close(); throw error; } } if (!entry) { entry = { connection: new CdpConnection(url), leased: true }; connectionPool.set(key, entry); connectionKeys.set(entry.connection, key); } else if (entry.idleTimer) { clearTimeout(entry.idleTimer); entry.idleTimer = undefined; } entry.leased = true; let conn = entry.connection; try { await conn.open(); } catch (error) { // A daemon restart can leave an idle pooled socket looking reusable. // Evict it and establish one clean connection before surfacing failure. connectionPool.delete(key); conn.close(); conn = new CdpConnection(url); connectionPool.set(key, { connection: conn, leased: true }); connectionKeys.set(conn, key); try { await conn.open(); } catch (retryError) { connectionPool.delete(key); conn.close(); throw retryError; } } try { await conn.attachToPage(preferredUrl, true, preferredMarker); } catch (error) { connectionPool.delete(key); conn.close(); throw error; } return conn; } export function browserDownloadDir( conversationKey = 'local', runId = 'default', ): string { // IDs are opaque; filename sanitisation collapsed distinct conversations // onto one directory and could leave dot-segments as path components. const safe = (value: string) => createHash('sha256').update(value).digest('hex'); const root = agentStateDir(); return path.join( root, 'browser', 'downloads', safe(conversationKey), safe(runId), ); } export async function configureDownloads( cdp: CdpConnection, conversationKey?: string, runId?: string, signal?: AbortSignal, ): Promise { signal?.throwIfAborted(); const dir = browserDownloadDir(conversationKey, runId); await mkdir(dir, { recursive: true, mode: 0o700 }); // Browser domain is current Chrome; Page fallback keeps older Chromium usable. await cdp .send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: dir, eventsEnabled: true, }, undefined, undefined, signal) .catch(() => { signal?.throwIfAborted(); return cdp.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: dir, }, undefined, undefined, signal); }); return dir; } export async function finalDownload( pathname: string, ): Promise> { const info = await stat(pathname); return { path: pathname, receivedBytes: info.size }; }