import { randomUUID } from 'node:crypto'; import { z } from 'zod'; import { configService } from '../../config/configService.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { resolveOrHealAgentBrowserPath } from './agentBrowserInstaller.js'; import { sessionArgs, spawnRunner } from './browser.js'; import { BROWSER_TAB_MARKER_KEY, browserPagePoolKey, bufferedPageHistory, type CdpEvent, getBrowserAutomation, releaseBrowserAutomation, } from './browserAutomation.js'; import { ensureDaemon } from './browserDaemon.js'; import { packageBrowserEvidence } from './browserEvidence.js'; import { browserRunRegistry } from './browserRunRegistry.js'; import { browserService } from './browserService.js'; import { ensureConversationTab } from './browserTabs.js'; const inputSchema = z.object({ operation: z.enum(['send', 'read_events']), method: z.string().optional(), params: z.record(z.unknown()).optional(), target: z .string() .optional() .describe('Optional CDP session id for the currently claimed page target'), after_sequence: z.number().int().nonnegative().optional(), methods: z.array(z.string()).optional(), limit: z.number().int().min(1).max(500).optional(), timeout_ms: z.number().int().min(100).max(120_000).optional(), }); type Input = z.infer; /** Internal browser observers also record connection-wide events. Only the * current page's ordered cursor window belongs in a model-visible receipt. */ export function pageEventWindow(events: readonly CdpEvent[], session: string | undefined, after = 0, methods?: string[], limit = 100): CdpEvent[] { if (!session) throw new Error('BrowserCDP 缺少当前标签会话,无法读取事件'); return events.filter(e => e.sessionId === session && e.sequence > after && (!methods?.length || methods.includes(e.method))) .slice(0, limit); } const SAFE_BROWSER_CDP_METHODS = new Set([ 'Browser.getVersion', 'Target.getTargetInfo', ]); export function validateBrowserCdpMethod( method: string, params: Record | undefined, pageTargetId: string | undefined, ): void { const domain = method.split('.', 1)[0]; const pageScoped = /^(Accessibility|DOM|Input|Log|Network|Page|Performance|Runtime|Security)\./.test( method, ); if (!pageScoped && !SAFE_BROWSER_CDP_METHODS.has(method)) throw new Error(`BrowserCDP 不允许调用未授权的 CDP 方法:${method}`); const targetId = params?.targetId; if (targetId !== undefined && targetId !== pageTargetId) throw new Error('BrowserCDP 只能访问当前会话认领的浏览器标签'); if (domain === 'Target' && (!pageTargetId || targetId !== pageTargetId)) throw new Error('BrowserCDP 缺少当前会话标签归属信息'); } async function call( input: Input, signal?: AbortSignal, _ctx: ToolCallContext = {}, ): Promise { const ctx = _ctx; if (signal?.aborted) return { ok: false, error: 'BrowserCDP 已取消' }; if (!(await configService.browser()).enabled) return { ok: false, error: '内置浏览器已在设置中关闭' }; if (!ctx.browserRun) return { ok: false, error: 'BrowserCDP 需要宿主启用本地浏览器运行时', }; const conversationKey = ctx.browserRun.conversationKey ?? `headless:${process.pid}`; const runId = ctx.browserRun.runId ?? ctx.toolCallId ?? randomUUID(); const run = browserRunRegistry.ensure({ sessionName: ctx.browserRun.sessionName, profileId: ctx.browserRun.profileId, conversationKey, runId, grants: ctx.browserRun.grants, }); let cdp: Awaited> | undefined; try { try { browserRunRegistry.requireGrant(run, 'interact'); } catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error), }; } const sessionName = run.sessionName; if (input.operation === 'read_events') { const tabs = run.activeTabId ? [run.activeTabId] : browserRunRegistry.claimedTabs(conversationKey, sessionName); if (tabs.length !== 1) throw new Error('缺少唯一的已认领标签,无法读取原调试事件历史'); const tab = tabs[0]!; browserRunRegistry.assertTab(run, tab); const history = bufferedPageHistory(sessionName, browserPagePoolKey(conversationKey, tab), input.target); const events = pageEventWindow(history.events, history.sessionId, input.after_sequence, input.methods, input.limit); return { ok: true, content: JSON.stringify(await packageBrowserEvidence(`${sessionName}:${conversationKey}`, { result: { events, next_sequence: events.at(-1)?.sequence ?? input.after_sequence ?? 0 }, tab_id: tab, execution: 'executed', verification: 'not_requested', targetId: history.targetId, })) }; } const bin = await resolveOrHealAgentBrowserPath({}, signal); if (!bin) return { ok: false, error: '内置浏览器不可用:自动修复 agent-browser 安装已尝试但未成功' }; const profileId = ctx.browserRun.profileId; const windowMode = ctx.browserRun.windowMode; await ensureDaemon(sessionName, { signal, profileId, windowMode }); let claimedTabId = run.activeTabId; const tabMarker = `${conversationKey}:${run.runId}:${randomUUID()}`; if (!claimedTabId) { claimedTabId = await ensureConversationTab({ context: run, sessionName, bin, globals: sessionArgs(sessionName), runner: spawnRunner, signal, }); } else { browserRunRegistry.assertTab(run, claimedTabId); } const serviceInput = { sessionName, bin, runner: spawnRunner, signal, }; // Switching tabs, resolving the page and issuing the operation belong to // the same session lock. A replacement daemon has neither the old page // identity nor its event history; never rebind an old numeric tab on retry. const result = await browserService.exclusive(serviceInput, async runCommand => { browserRunRegistry.assertTab(run, claimedTabId!); const globals = sessionArgs(sessionName); const switched = await runCommand([...globals, 'tab', claimedTabId!]); if (switched.code !== 0) throw new Error('当前会话标签不可用,请重新观察'); const marked = await runCommand([...globals, 'eval', `globalThis[${JSON.stringify(BROWSER_TAB_MARKER_KEY)}]=${JSON.stringify(tabMarker)}`]); if (marked.code !== 0) throw new Error('无法标记当前浏览器会话标签'); // A verified marker, not a URL match, proves the page identity. const page = await getBrowserAutomation(sessionName, bin, spawnRunner, signal, undefined, tabMarker, browserPagePoolKey(conversationKey, claimedTabId!)); cdp = page; browserRunRegistry.assertTab(run, claimedTabId!); signal?.throwIfAborted(); if (!input.method) throw new Error('send requires method'); validateBrowserCdpMethod(input.method, input.params, page.attachedPageTargetId); if (input.target && input.target !== page.attachedPageSessionId) throw new Error('BrowserCDP 只能操作当前会话认领页面;跨页面 target 已拒绝'); return page.send(input.method, input.params, input.target, input.timeout_ms ?? 30_000, signal); }); return { ok: true, content: JSON.stringify(await packageBrowserEvidence(`${sessionName}:${conversationKey}`, { result, tab_id: claimedTabId, execution: 'executed', verification: 'not_requested', targetId: cdp?.attachedPageTargetId, capability: 'raw_debugging_may_mutate', })), }; } catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error), }; } finally { if (cdp) releaseBrowserAutomation(cdp); browserRunRegistry.finish(conversationKey, runId, run.sessionName); } } export const browserCdpTool: Tool = { name: 'BrowserCDP', description: 'Raw CDP access to the host browser, including headless CLI/TUI; scoped to the conversation-owned page.', inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: false, isConcurrencySafe: false, call, callWithContext: call, };