/** * Firefox-only tool implementations, built on the browser-neutral Driver contract (ADR-001). * These are the 7 tools NOT unified with Chrome's src/tools/*.ts implementations: Chrome's * console/network/mock tools are built on src/tools/recorder.ts, a disk-persisted, * cross-process capture keyed by target id; these are a same-process, in-memory event buffer. * See src/shared-tools.ts's file header for why unifying them was not a safe behavior-preserving * move and was left as two implementations. This file is what src/neutral.ts shrank to once its * other 20 tools became src/shared-tools.ts's single real implementation. */ import type { BrowserDriver, InterceptRule, PageDriver, PageInfo } from "./driver.ts"; import { selectRule, buildFulfillParams, effectiveAction } from "./tools/network_mock.ts"; import type { TargetSelector } from "./types.ts"; import { modifierBits, validateDispatchMouseArgs, type DispatchMouseArgs, type DispatchMouseResult } from "./tools/dispatch-mouse.ts"; import { isWorkerSelector, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts"; class BidiToolError extends Error {} async function withPage(driver: BrowserDriver, target: TargetSelector | undefined, fn: (page: PageDriver) => Promise): Promise { const page = await driver.page(target); try { return await fn(page); } finally { await page.release(); } } /* ------------------------------ dispatch_mouse (Firefox 160+) ------------------------------ */ // Same schema, validator and result shape as Chrome's tools/dispatch-mouse.ts (capability "input.raw"); // the event itself rides PageDriver.dispatchMouse (bidi/driver.ts, one pointer action per call). // A page driver without that method (Chrome's, which never reaches this registry) is "unsupported". export async function dispatchMouse(driver: BrowserDriver, args: DispatchMouseArgs): Promise { validateDispatchMouseArgs(args); modifierBits(args.modifiers); // validates the closed Alt/Control/Meta/Shift enum, same refusal text as Chrome return withPage(driver, args.target, async (page) => { if (!page.dispatchMouse) throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch"); await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers }); return { dispatched: args.action, x: args.x, y: args.y }; }); } /* ------------------------------ console + network (4) ------------------------------ */ // No recorder-style raw-CDP buffer exists for the neutral driver. Buffering rides // PageDriver.on(), scoped to the calling process's lifetime, an identical constraint // to the CDP recorder (both are per-process). Payloads are the driver's own event // shape (BiDi's log.entryAdded / network.* records), NOT normalized to CDP's // Runtime.consoleAPICalled / Network.* shapes, a real cross-driver difference, // documented in README.md rather than smoothed over. const consoleBuffers = new Map>>(); const networkBuffers = new Map>>(); /** * Refuse the Chrome-only `worker:` arm BEFORE a browser is launched. * * pickContext already refuses it (bidi/driver.ts), but only after driver.page() * has dialed — and on Firefox that means LAUNCHING a browser for a call that * cannot possibly succeed. The gate is written as a capability check rather than * "this file is the BiDi one" so it stays true if a future BiDi driver ever * gains the capability, and the message is the shared one, so the teaching does * not fork. */ function refuseWorkerSelector(driver: BrowserDriver, target: TargetSelector): void { if (isWorkerSelector(target) && !driver.capabilities.has("worker.targets")) { throw new BidiToolError(WORKER_SELECTOR_UNSUPPORTED_MESSAGE); } } function bufferFor(map: Map>>, id: string): Array> { let b = map.get(id); if (!b) { b = []; map.set(id, b); } return b; } async function captureFresh(page: PageDriver, durationMs: number): Promise { const cBuf = bufferFor(consoleBuffers, page.info.id); const nBuf = bufferFor(networkBuffers, page.info.id); cBuf.length = 0; nBuf.length = 0; const offC = page.on("console", (p) => cBuf.push(p)); const offReq = page.on("network.request", (p) => nBuf.push({ ...p, phase: "request" })); const offRes = page.on("network.response", (p) => nBuf.push({ ...p, phase: "response" })); try { await page.navigate({ reload: true }).catch(() => undefined); await new Promise((r) => setTimeout(r, durationMs)); } finally { offC(); offReq(); offRes(); } } export async function listConsoleMessages( driver: BrowserDriver, args: { target?: TargetSelector; reload?: boolean; durationMs?: number } = {}, ): Promise<{ messages: Array>; count: number }> { refuseWorkerSelector(driver, args.target); return withPage(driver, args.target, async (page) => { if (args.reload) await captureFresh(page, args.durationMs ?? 2500); const buf = bufferFor(consoleBuffers, page.info.id); return { messages: [...buf], count: buf.length }; }); } export async function getConsoleMessage( driver: BrowserDriver, args: { target?: TargetSelector; index?: number } = {}, ): Promise> { refuseWorkerSelector(driver, args.target); return withPage(driver, args.target, async (page) => { const buf = bufferFor(consoleBuffers, page.info.id); const idx = args.index ?? 0; const entry = buf[idx]; if (!entry) throw new BidiToolError(`no console message at index ${idx}; run list_console_messages first`); return entry; }); } export async function listNetworkRequests( driver: BrowserDriver, args: { target?: TargetSelector; reload?: boolean; durationMs?: number; filterUrl?: string } = {}, ): Promise<{ requests: Array>; count: number }> { refuseWorkerSelector(driver, args.target); return withPage(driver, args.target, async (page) => { if (args.reload) await captureFresh(page, args.durationMs ?? 2500); let buf = bufferFor(networkBuffers, page.info.id); if (args.filterUrl) buf = buf.filter((r) => typeof r.url === "string" && (r.url as string).includes(args.filterUrl as string)); return { requests: buf, count: buf.length }; }); } export async function getNetworkRequest( driver: BrowserDriver, args: { target?: TargetSelector; requestId?: string; url?: string; includeBody?: boolean } = {}, ): Promise> { refuseWorkerSelector(driver, args.target); if (!args.requestId && !args.url) throw new BidiToolError("get_network_request requires requestId or url"); return withPage(driver, args.target, async (page) => { const buf = bufferFor(networkBuffers, page.info.id); const found = args.requestId ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId) : buf.find((r) => typeof r.url === "string" && (r.url as string).includes(args.url as string)); if (args.includeBody) { // Firefox >= 160 retains response bodies per SESSION (network.responseBodyPostHoc, armed when // the session is created), so a body is readable for a request made BEFORE this call, by its // request id, with no reload. A requestId therefore needs no buffer entry; a url alone does, // because the url -> id map is the buffer (filled by list_network_requests{reload:true}). // A driver without the capability answers getResponseBody with "unsupported", surfaced as is. const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : ""); if (!id) throw new BidiToolError("get_network_request includeBody on this backend needs a requestId, or a url already present in the buffer (run list_network_requests with reload first)"); const { body, base64Encoded } = await page.getResponseBody(id); return { ...(found ?? { requestId: id }), body, bodyBase64Encoded: base64Encoded }; } if (!found) throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first"); return found; }); } /* ------------------------------- network mocking (3) ------------------------------- */ // Reuses tools/network_mock.ts's pure logic layer (selectRule/buildFulfillParams/ // effectiveAction) over PageDriver.intercept(), same pattern bidi/driver.ts's own // intercept() uses internally. Session-scoped: intercept() takes the FULL rule set // on every (re)arm, so adding a rule disposes the old interceptor and re-arms with // the appended array. Persistent only for the life of the calling process: the MCP // server (long-lived) keeps it across calls; the CLI (one-shot) does not. interface MockSession { rules: Array; dispose: () => Promise; } const mockSessions = new Map(); export async function mockRequest( driver: BrowserDriver, args: { target?: TargetSelector; urlPattern: string; action?: "fulfill" | "fail" | "continue"; status?: number; body?: string; contentType?: string; headers?: Record; errorReason?: string; method?: string; delayMs?: number; failRate?: number; reload?: boolean; }, ): Promise<{ target: PageInfo; rule: { urlPattern: string; action: string }; ruleCount: number }> { if (!args.urlPattern) throw new BidiToolError("mock_request requires a { urlPattern }"); return withPage(driver, args.target, async (page) => { const existing = mockSessions.get(page.info.id); const rule: InterceptRule & { hits: number } = { urlPattern: args.urlPattern, method: args.method, action: args.action ?? "fulfill", status: args.status, body: args.body, contentType: args.contentType, headers: args.headers, errorReason: args.errorReason, delayMs: args.delayMs, failRate: args.failRate, hits: 0, }; const rules = existing ? [...existing.rules, rule] : [rule]; if (existing) await existing.dispose().catch(() => undefined); const dispose = await page.intercept(rules); mockSessions.set(page.info.id, { rules, dispose }); if (args.reload) await page.navigate({ reload: true }).catch(() => undefined); return { target: page.info, rule: { urlPattern: rule.urlPattern, action: rule.action }, ruleCount: rules.length }; }); } export async function listMocks( _driver: BrowserDriver, _args: { target?: TargetSelector } = {}, ): Promise<{ sessions: Array<{ target: string; rules: Array<{ urlPattern: string; action: string; method?: string }> }> }> { const sessions = [...mockSessions.entries()].map(([id, s]) => ({ target: id, rules: s.rules.map((r) => ({ urlPattern: r.urlPattern, action: r.action, method: r.method })), })); return { sessions }; } export async function clearMocks( driver: BrowserDriver, args: { target?: TargetSelector; all?: boolean } = {}, ): Promise<{ cleared: number }> { if (args.all) { let n = 0; for (const [, s] of mockSessions) { await s.dispose().catch(() => undefined); n++; } mockSessions.clear(); return { cleared: n }; } return withPage(driver, args.target, async (page) => { const existing = mockSessions.get(page.info.id); if (!existing) return { cleared: 0 }; await existing.dispose().catch(() => undefined); mockSessions.delete(page.info.id); return { cleared: 1 }; }); } // selectRule/buildFulfillParams/effectiveAction are imported above purely so this module's // footer can name them as reused; the actual call sites live inside bidi/driver.ts's // PageDriver.intercept() implementation, which this file drives through the neutral // `intercept(rules)` surface rather than re-implementing. void selectRule; void buildFulfillParams; void effectiveAction; /** The 7 Firefox-only tools, plus dispatch_mouse (a Firefox handler beside Chrome's tools/dispatch-mouse.ts). */ export const BIDI_ONLY_TOOLS = { list_console_messages: listConsoleMessages, get_console_message: getConsoleMessage, list_network_requests: listNetworkRequests, get_network_request: getNetworkRequest, mock_request: mockRequest, list_mocks: listMocks, clear_mocks: clearMocks, dispatch_mouse: dispatchMouse, } satisfies Record Promise>;