/** * ADR-001: one browser-neutral Driver interface behind the tools. * * Context. Every tool in src/tools/ is a stateless one-shot on withPage(): * open a socket, act, always close. That is only correct because a CDP `Uid` * IS a backendDOMNodeId, a browser-global integer outliving the connection * that made it, so take_snapshot in one process and click(uid) in the next * interoperate. BiDi breaks both halves: a session is bound to ONE WebSocket * (re-dialing gets `invalid session id`) and a `sharedId` is document-scoped, * dying on any navigation with `no such node`. A literal port would break * snapshot-then-click, the tool's core workflow. * * Decision. * 1. `Uid` becomes an OPAQUE TAGGED STRING, `:`. Tools never * parse, build, or order uids; only the driver whose scheme tags a uid may * resolve it. Byte-level codec: THE UID CODEC block below. * 2. The CDP driver keeps its handle: `cdp:`, and still * accepts bare digits, so old snapshots and the MCP schema keep working. * 3. The BiDi driver does NOT encode a `sharedId`. It STAMPS the page: * snapshot writes `data-cdp-uid=""` onto every emitted node and the * uid is `bidi:`, resolved by a locateNodes css lookup. Page state, * not protocol state, so it survives a dropped socket, a fresh session, * and a fresh CLI process, which is what the one-shot tools depend on. * 4. Connection lifetime is declared, not implied: `lifetime` is "per-call" * (CDP, release() closes) or "session" (BiDi, release() is a refcount * decrement and the socket lives until dispose()). Tools call withDriver() * and stay ignorant of which they got. * 5. Anything on exactly one browser stays OUT of the interface and is named * in `Capability`. tools/list filters on REQUIRED_CAPABILITIES, so * tracing, heap, lighthouse, and CPU throttling are simply absent under * Firefox rather than present and throwing. * * Rejected alternatives. * A. `Uid = number` indexing a driver-side handle table. The table dies with * the process, so the CLI (one process per call) could never resolve a uid * it printed last call: works under MCP, fails under CLI, the worst split. * B. Encode the `sharedId` (`bidi::`). It is meaningless * outside the session that minted it and dies on every navigation. Both * verified against Firefox 153.0.3. * C. A long-lived module-scoped BiDi session as the WHOLE answer, no stamps. * Insufficient, not wrong: it fixes the socket, and recorder.ts / * network_mock.ts already prove the pattern, but navigation still voids * every sharedId and the CLI gets a new session per process. Adopted as * the transport (4) with stamps on top (3). Combination, not either/or. * D. A computed unique css path instead of stamping, to avoid touching the * DOM. Any sibling insertion silently resolves it to the WRONG node, while * a stamp resolves to the right node or none. Loud miss over quiet mis-hit. * E. One flat interface with `throw new Error("unsupported")` bodies under * Firefox. Moves discovery from tools/list to runtime and makes an honest * asymmetry look like a bug. * * Consequences. Stamping mutates the page (one attribute per snapshotted * node), and a node the page re-renders from scratch loses its stamp, so uids * expire on re-render rather than on navigation. Both are stated in * `uidStability`. Do not "simplify" Uid back to a number: that is A, and it * breaks the CLI. */ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import type { ToolName } from "./index.ts"; // leaseDir only, for the viewport-override record below. leases.ts imports nothing from this file // (node builtins only), so this is not a cycle; the record deliberately shares the lease directory // rather than minting a second state location. import { leaseDir } from "./leases.ts"; import type { TargetSelector } from "./types.ts"; import type { ContextEvalRow, ExecutionContextInfo, SettleOptions } from "./contexts.ts"; /* ---------------------------------- uids ---------------------------------- */ /** * An opaque element reference. NEVER parse, construct, or compare a DriverUid * except by string equality. It is produced by Driver.snapshot / Driver.locate * and consumed by Driver.resolve. */ export type DriverUid = string; /* THE UID CODEC, binding on every driver. Two implementers reading only this * block must produce interoperable encodings. * * GRAMMAR. `uid := scheme ":" payload`, split on the FIRST colon only. * scheme matches /^[a-z][a-z0-9]{0,7}$/ and equals the driver's `scheme` * field; payload is 1..503 chars, no control chars, MAY contain ":"; total * length <= 512. A driver MUST reject a uid whose scheme is not its own with * code "foreign-uid" and MUST NOT guess at another driver's scheme. * * SCHEME "cdp". payload := decimal backendDOMNodeId, no sign, no leading * zeros, no whitespace. Encode `cdp:${backendNodeId}`; decode Number(payload), * which must be a positive safe integer. LEGACY: a uid matching * LEGACY_NUMERIC_UID with no scheme prefix MUST be accepted by the cdp driver * as `cdp:`, and by no other driver. * * SCHEME "bidi". payload := exactly 12 lowercase hex chars, /^[0-9a-f]{12}$/, * from a cryptographically-uniform source, never reused within a document. * The driver writes it into the live DOM as UID_STAMP_ATTR on the referenced * element in the SAME call that mints the uid. Resolution is * browsingContext.locateNodes `{type:"css", value:'[data-cdp-uid=""]'}` * in the uid's context. Zero matches MUST raise "stale-uid". More than one * match MUST take the first node in document order and MUST NOT throw, since * cloning a stamped subtree is legal page behavior. */ /** Attribute the bidi scheme stamps onto elements. Never change this string. */ export const UID_STAMP_ATTR = "data-cdp-uid" as const; /** Matches the legacy bare-integer uid that the cdp driver must still accept. */ export const LEGACY_NUMERIC_UID = /^[0-9]+$/; /** True when `u` carries `scheme` as its tag (or is a legacy bare integer for cdp). */ export function uidHasScheme(u: DriverUid, scheme: string): boolean { return u.startsWith(`${scheme}:`) || (scheme === "cdp" && LEGACY_NUMERIC_UID.test(u)); } /** * How long a uid stays resolvable. Declared per driver so a caller can decide * when to re-snapshot instead of learning it from a failure. * - "browser-node": valid until the underlying DOM node is destroyed, across * connections and processes (cdp). * - "document-stamp": valid until the document unloads OR the node is * re-created by the page, across connections and processes (bidi). */ export type UidStability = "browser-node" | "document-stamp"; /* ------------------------------- capabilities ------------------------------- */ /** * Capabilities that are NOT universal. Anything a driver can always do has no * token here. A driver declares the subset it supports; tools/list filters on * REQUIRED_CAPABILITIES so an unsupported tool is absent, never present and * throwing. */ export type Capability = | "trace.performance" // Chrome tracing, behind every performance_* tool | "heap.snapshot" // V8 heap snapshots | "audit.lighthouse" // shelling out to lighthouse against a debug port | "capture.screencast" // streamed repaint frames (CDP Page.startScreencast); BiDi has no equivalent | "emulate.cpuThrottling" // CPU multiplier; absent from BiDi's emulation module | "emulate.mediaFeatures" // media type + features, e.g. prefers-color-scheme | "emulate.deviceMetrics" // past width/height: scale factor, mobile flag | "emulate.networkConditions" // throttled or offline conditions | "screenshot.fullPage" // one-shot full scrollable page, not just the viewport | "screenshot.element" // capture clipped to a single element | "screenshot.scale" // per-capture output-pixel multiplier; no permanent emulation change | "screenshot.renderSize" // emulate a viewport for the duration of ONE capture, then put the old one back | "screenshot.tile" // capture past the backend's one-image encode limit as vertical bands, stitched losslessly | "network.intercept" // fulfill, fail, or continue a matched request | "network.responseBodyPostHoc" // read a body for a request not armed in advance | "snapshot.accessibilityTree" // native a11y dump, not a DOM-walk approximation | "input.insertTextAtomic" // atomic value commit, not synthesized keystrokes | "locate.text" // find a node by visible text substring | "locate.xpath" // find a node by xpath | "input.raw" // raw single mouse-event dispatch (dispatch_mouse's move/down/up primitive); Chrome, and Firefox 160+ (BiDi) | "input.modifierClick" // click with Alt/Control/Meta/Shift held; Chrome, and Firefox 160+ (BiDi key source ticked with the pointer) | "input.html5Drag" // real HTML5 drag events (drag's mode:"html5"); Chrome only, see PageDriver.drag | "emulate.focus" // fake page focus without moving the OS window (focus_emulation / click_focus_gated); Chrome only — BiDi's emulation module has no focus primitive | "browser.downloads" // capture a file download to a known path (wait_for_download); Chrome, Firefox 160+ | "browser.permissions" // grant/reset browser permissions for an origin (grant_permissions); Chrome, Firefox 160+ | "browser.tabGroups" // list/create/remove tab groups through a helper extension (list_tab_groups, group_tabs, ungroup_tabs); Chrome only, BiDi cannot reach an extension background context | "worker.targets" // address a service/shared worker as a target ("worker:"), incl. waking an evicted MV3 worker; Chrome only | "frame.targets" // address an out-of-process (cross-origin) iframe as a target ("frame:"); Chrome only — same-site iframes are not targets at all | "runtime.contexts"; // list and pick execution contexts INSIDE a target (nested same-process frames, late contexts: issue #12); Chrome only /** * Tools whose availability depends on a capability. A tool absent from this * map is universal and must be listed by every driver. Keyed by ToolName so * the compiler catches a renamed tool. */ export const REQUIRED_CAPABILITIES: Partial> = { performance_start_trace: ["trace.performance"], performance_stop_trace: ["trace.performance"], performance_analyze_insight: ["trace.performance"], performance_trace: ["trace.performance"], take_heapsnapshot: ["heap.snapshot"], lighthouse_audit: ["audit.lighthouse"], start_screen_recording: ["capture.screencast"], stop_screen_recording: ["capture.screencast"], mock_request: ["network.intercept"], list_mocks: ["network.intercept"], clear_mocks: ["network.intercept"], dispatch_mouse: ["input.raw"], focus_emulation: ["emulate.focus"], click_focus_gated: ["emulate.focus"], wait_for_download: ["browser.downloads"], grant_permissions: ["browser.permissions"], list_tab_groups: ["browser.tabGroups"], group_tabs: ["browser.tabGroups"], ungroup_tabs: ["browser.tabGroups"], list_contexts: ["runtime.contexts"], } as const; /* --------------------------------- errors --------------------------------- */ /** Machine-readable failure kinds every driver maps its protocol errors onto. */ export type DriverErrorCode = | "foreign-uid" // the uid's scheme belongs to another driver | "stale-uid" // ours, but no longer resolves: node gone or document unloaded | "no-such-element" // a locator matched nothing | "no-such-target" // no page/context matched the TargetSelector | "unsupported" // operation not supported; check Capability first | "timeout" // the per-command deadline elapsed | "disconnected" // socket closed, session ended, or browser exited | "page-error"; // page-side exception: evaluate threw, navigation rejected export interface DriverError extends Error { readonly code: DriverErrorCode; readonly data?: unknown; } export function isDriverError(e: unknown): e is DriverError { return e instanceof Error && typeof (e as { code?: unknown }).code === "string"; } /* ------------------------------ neutral shapes ------------------------------ */ /** A page/tab, neutral over CDP targets and BiDi browsing contexts. */ export interface PageInfo { id: string; url: string; title: string; /** CDP target type ("page", "iframe", "worker", ...), when the driver has one. Additive: BiDi leaves it unset. */ type?: string; /** True for a hidden tab (CDP_HIDDEN_TABS=1, MCP server only): it is live and drivable, but it * is in no browser window, so the user cannot see it. Absent otherwise. */ hidden?: boolean; /** Set only by activatePage on a hidden tab: that tab cannot be shown in place, so the driver * opened its URL in a new visible tab (`id`) and closed the hidden one, whose id this is. */ revealedFrom?: string; } /** How a caller points at an element. Exactly one field is set. */ export type ElementLocator = | { uid: DriverUid } | { css: string } | { xpath: string } // requires Capability "locate.xpath" | { text: string }; // requires Capability "locate.text" /** One line of the snapshot tree, before it is rendered to text. */ export interface SnapshotNode { uid: DriverUid; role: string; name?: string; depth: number; /** value / checked / expanded / disabled / url / focused, already stringified. */ extras?: Record; } export interface NavigateOptions { url?: string; reload?: boolean; ignoreCache?: boolean; /** * Traverse the tab's session history instead of loading a URL: the browser Back / Forward * buttons. Mutually exclusive with `url` and `reload` (the tool layer enforces that; a driver * trusts its caller). Chrome: Page.getNavigationHistory + Page.navigateToHistoryEntry. Firefox: * browsingContext.traverseHistory{delta:-1|+1}. Universal — both drivers implement it, so this is * deliberately NOT a Capability. * * NO SILENT NO-OP. Asking to go back from the first history entry (or forward from the last) is a * caller mistake, not a legal outcome: both drivers MUST throw an error naming the direction * rather than return a success that navigated nowhere, because a no-op success reads as "you are * on the previous page" and the caller acts on that. */ history?: "back" | "forward"; waitUntil?: "load" | "domcontentloaded"; timeoutMs?: number; } export interface NavigateResult { url: string; /** CDP frameId or BiDi context id. Opaque. */ contextId: string; reloaded?: boolean; /** Which direction a `history` traversal actually moved. Present only for a history navigation, * the same way `reloaded` is present only for a reload. */ traversed?: "back" | "forward"; waitedFor: "load" | "domcontentloaded" | "committed" | "timeout"; } /** One raw mouse event for PageDriver.dispatchMouse. `modifiers` are held for this one event only. */ export interface RawMouseEvent { action: "move" | "down" | "up"; x: number; y: number; button?: "left" | "right" | "middle"; clickCount?: number; modifiers?: readonly string[]; } export interface MouseButtonOptions { button?: "left" | "right" | "middle"; clickCount?: number; /** "Alt" | "Control" | "Meta" | "Shift", held for the press/release. CDP bits: Alt=1, * Control=2, Meta=4, Shift=8 (cdp/driver.ts's inputModifierBits). On the Firefox/BiDi driver a * non-empty array rides a key input source ticked with the pointer (capability * "input.modifierClick", Firefox 160+; an older Firefox gets "unsupported"). */ modifiers?: readonly string[]; } /** * Where a drag ends. 1.8.0 Track P2 widened this past "an element": an absolute viewport point * ({x,y}) and an offset from the source point ({dx,dy}) are both real destinations for widgets * that have no droppable element to name — a range slider's track, a map canvas, a resize gutter. * The three branches are discriminated structurally ("dx" in / "x" in), the same way * PageDriver.scroll's anchor already discriminates an ElementLocator from a viewport point; no * ElementLocator variant carries an `x` or `dx` field, so the check is exact and not a heuristic. */ export type DragDestination = ElementLocator | { x: number; y: number } | { dx: number; dy: number }; export interface DragOptions { /** * "mouse" (default): synthetic mousePressed/mouseMoved…/mouseReleased. Fine for widgets built on * raw pointer events, and it is what `drag` has always done. * * "html5": a REAL HTML5 drag — Input.setInterceptDrags(true), the same press/move sequence, then * the intercepted DragData replayed as Input.dispatchDragEvent dragEnter/dragOver/drop at the * destination. * * WHAT THE DIFFERENCE ACTUALLY IS (measured on Chrome 151.0.7922.109, macOS, both --headless=new * and headed — NOT assumed). Synthetic mouse events DO start a real drag in modern Chrome, so * mouse mode is not inert on HTML5 drop zones the way the folklore says. What mouse mode does * not control is WHICH drag events the page receives: that follows the interpolated pointer * path, and at the default steps:2 a source-to-zone drag delivered dragstart and drop but ZERO * dragover. A drop zone written the standard way — preventDefault inside dragover, which is how * the HTML spec says you mark a valid drop target — therefore refused the drop outright, while * steps:1 and steps:8 on the very same page happened to work. html5 mode removes the luck: the * dragEnter/dragOver/drop triple is dispatched explicitly at the destination every time. * * Requires Capability "input.html5Drag" — Chrome only. A driver without that capability MUST * throw "unsupported"; it must never silently downgrade to mouse mode, because a caller who * asked for html5 asked precisely because mouse mode was not delivering the drop. */ mode?: "mouse" | "html5"; /** Interpolated mouseMoved events dispatched between the source and destination points, evenly * spaced, the last one landing exactly on the destination. Default 2 (the pre-1.8.0 hardcoded * behavior: midpoint, then destination). DnD libraries with a movement threshold or per-frame * sampling need more. The tool layer validates the range; a driver trusts its caller. */ steps?: number; } /** * The `steps` evenly-spaced points between `from` (exclusive) and `to` (inclusive), for a drag's * interpolated move sequence. The last point is EXACTLY `to`, emitted as `to` itself rather than * computed, so float error can never leave the pointer a fraction of a pixel short of the * destination element. steps:1 is a single jump to the destination; steps:2 is * midpoint-then-destination, the pre-1.8.0 hardcoded behavior. * * Lives here, in the backend-neutral module, because BOTH drivers need the identical geometry: * the CDP driver turns each point into an Input.dispatchMouseEvent{mouseMoved} and the BiDi driver * into a performActions pointerMove, but "where the pointer goes" must not differ by backend. * Callers pass an already-validated integer >= 1 (the tool layer validates; a driver trusts it). */ export function interpolatePoints( from: { x: number; y: number }, to: { x: number; y: number }, steps: number, ): Array<{ x: number; y: number }> { const out: Array<{ x: number; y: number }> = []; for (let i = 1; i < steps; i++) { out.push({ x: from.x + ((to.x - from.x) * i) / steps, y: from.y + ((to.y - from.y) * i) / steps }); } out.push({ x: to.x, y: to.y }); return out; } export interface ScrollOptions { /** Positive scrolls DOWN, positive scrolls RIGHT: wheel-event convention. The tool layer * (shared-tools.ts) requires at least one of deltaX/deltaY; a driver trusts its caller and * does not re-validate. */ deltaX?: number; deltaY?: number; } export interface KeyPress { /** "Enter", "Tab", "ArrowDown", or a single printable character. */ key: string; /** "Control" | "Shift" | "Alt" | "Meta", case-insensitive. */ modifiers?: readonly string[]; } export interface ScreenshotOptions { format?: "png" | "jpeg"; quality?: number; fullPage?: boolean; // requires "screenshot.fullPage" clip?: ElementLocator; // requires "screenshot.element" scale?: number; // requires "screenshot.scale"; absent or 1 leaves the capture byte-for-byte as it was /** * Render this capture at an emulated viewport, then put the previous one back. Both fields are * required TOGETHER (the tool layer enforces it; a driver trusts its caller) and both require * Capability "screenshot.renderSize". Absent, the capture is byte-for-byte what it was. * * NOT the same knob as `scale`, and the difference is measured, not asserted. `scale` multiplies * output pixels while the page keeps believing it is its old size: window.devicePixelRatio read 2 * both before and after a --scale 3 capture, and innerWidth/innerHeight stayed 1390x1064. This * pair changes what the page BELIEVES for the length of one capture, so media queries flip and * the document re-lays-out — which is the point (capture a responsive page at desktop 1920x1080 * from a tab that is not that size) and also why it must be undone afterwards. * * `deviceScaleFactor` and `mobile` are deliberately INHERITED from whatever override was already * in place rather than reset: the caller asked to change the render SIZE, and silently dropping * a device pixel ratio they set earlier would be a second, unrequested change. */ renderWidth?: number; // requires "screenshot.renderSize" renderHeight?: number; // requires "screenshot.renderSize" /** * Whether this capture may be taken as vertical BANDS and stitched, instead of as one image. * Three-valued, and the middle value is the default: * * undefined AUTO. One shot when the projected output fits under the backend's per-image encode * limit, banded when it does not. A capture that fits is byte-for-byte the call it * always was — the same params on the wire, no clip synthesized that was not there * before — so auto costs the common path nothing but the layout-metrics round trip * the decision itself needs. * false NEVER band. A capture past the limit is REFUSED by the encode guard instead. This * is the escape hatch back to the exact pre-tiling behaviour. * true ALWAYS band, even when one shot would have fitted. Mainly so the banded path is * directly testable on an ordinary page; see the driver for why "always" is made to * mean at least two bands rather than a one-band no-op. * * AUTO IS THE DEFAULT BECAUSE THE ALTERNATIVE IS A WEDGED TAB, not because banding is free. * Measured (see MAX_ENCODED_SIDE_PX in ../cdp/driver.ts): a plain capture of a document past the * limit does not fail fast — Page.captureScreenshot never answers, and because captureBeyondViewport * resizes the page to the clip for the length of the capture, the tab is left stuck at that size * with every later screenshot timing out too. * * Requires Capability "screenshot.tile" only for `true`. `undefined` and `false` ask a backend for * nothing it cannot already do. */ tile?: boolean; // `true` requires "screenshot.tile" } /** * A capture too big for one image, handed to the tool layer band by band. * * LAZY BY CONTRACT, not by convenience: the Nth band's Page.captureScreenshot runs only when the * consumer pulls the Nth band, so a driver never holds two bands at once and a whole 1.4 GB image * never exists in memory. Accumulating the bands into an array first would typecheck, work on a * small page, and defeat the entire point of the streaming stitcher on a large one. * * VERTICAL ONLY, AND THAT IS A SCOPE DECISION RATHER THAN AN OVERSIGHT. Bands stack top to bottom * because that is the one direction a PNG can be concatenated without decoding it whole: scanlines * are the unit, so appending rows is cheap and appending columns is not. A region whose projected * WIDTH alone is past the limit is therefore refused, naming the width, rather than silently * truncated or split into a grid this stitcher cannot reassemble. */ export interface BandedCapture { /** The bands, top to bottom, produced one at a time. */ bands: AsyncIterable; /** How many bands the sequence will yield. Known before the first one is captured. */ bandCount: number; /** Height of every band but the last, in CSS px. The last is the remainder. */ bandHeightCss: number; /** The whole region being tiled, CSS px, in document coordinates. */ clip: { x: number; y: number; width: number; height: number }; /** Always "png": the stitch is a PNG-scanline concatenation, and there is no lossless JPEG one. */ format: "png"; } /** * The tool layer's half of a banded capture: consume the bands and return whatever was made of * them. Called at most once per capture, BEFORE the first band is taken, so a consumer that cannot * accept a banded capture at all (it was asked for JPEG, or for base64 of a 300 MB image) refuses * by throwing here and no band is ever captured. * * This is why the driver takes a callback rather than returning the iterable: a banded capture may * hold a viewport override for its whole duration, and the driver can only put that back once it * knows the consumer is finished. Handing the iterable out would end the driver's call while the * page was still emulated. */ export type BandConsumer = (capture: BandedCapture) => Promise; /** What a banded capture returns in place of bytes: the consumer's own answer, plus how it was split. */ export interface TiledScreenshotResult { tiled: true; format: "png"; bandCount: number; bandHeightCss: number; /** Whatever the BandConsumer returned — for take_screenshot, the stitcher's measured report. */ consumed: T; /** Same three render-size fields a one-shot capture carries, same meaning. */ renderSize?: { width: number; height: number }; renderRestored?: boolean; renderRestoreError?: string; } /** One capture, delivered whole or in bands. Discriminate with isTiledCapture. */ export type CaptureDelivery = ScreenshotResult | TiledScreenshotResult; export function isTiledCapture(delivery: CaptureDelivery): delivery is TiledScreenshotResult { return (delivery as { tiled?: unknown }).tiled === true; } /** * What a capture returns. `data`/`format` are the whole answer for an ordinary capture; the three * render-size fields are present only when renderWidth/renderHeight were applied. * * `renderRestored:false` IS THE LOUD PART, and it is why this is a result shape rather than a bare * byte buffer. A failed restore means the caller's page is still emulated at the render size after * this call returns — a mutation they did not ask to keep — so it has to travel back with the image * instead of being swallowed. On the THROWING path there is no result to carry it, so a driver * appends the same fact to the error message instead (see CdpPageDriver.screenshot). */ export interface ScreenshotResult { data: Uint8Array; format: "png" | "jpeg"; /** The emulated viewport this capture ran at. Present only when renderWidth/renderHeight were given. */ renderSize?: { width: number; height: number }; /** Whether the previous viewport was put back. Present only when a render size was applied. */ renderRestored?: boolean; /** Why the restore failed. Present only when renderRestored is false. */ renderRestoreError?: string; } /* --------------------- the viewport-override record (both drivers) --------------------- */ /** * The device-metrics override this toolkit last applied to a target, as a file under the lease * directory. Written by PageDriver.emulate, removed by emulate{clearOverrides}, read by * PageDriver.screenshot so a render-size capture can put back what it displaced. * * WHY A FILE AND NOT A FIELD ON THE DRIVER. The spec for this feature called for a private field on * the page driver, and that is provably not enough here — MEASURED against Chrome/151.0.7922.76: * * $ cli emulate --target T --width 800 --height 600 # one process, socket closes on exit * $ cli evaluate_script --target T ...innerWidth... # a DIFFERENT process * "[800,600,2]" # the override OUTLIVED the connection * * The CDP driver's LifetimeModel is "per-call": a PageDriver instance lives for exactly one tool * call, so a field on it is empty by construction at the start of the screenshot call that needs * it, and the override it must not destroy was set by a process that has already exited. Same * reasoning leases.ts and origins.ts give for their own files, arrived at the same way. * * WHY THE RECORD IS LOAD-BEARING AND NOT A CONVENIENCE. Emulation.clearDeviceMetricsOverride does * NOT mean "undo the override" — measured, twice, on the same tab: * * fresh connection, never set an override, clear it -> returns {}, page STAYS 800x600 * fresh connection, set 1920x1080, then clear -> page becomes 1390x1064, the REAL device * * So clearing is a no-op for an override this session did not set, and once a session DOES set one, * clearing reverts to the physical device and takes any earlier override down with it. A * render-size capture always sets one, so its clear always lands — which is exactly why restoring * by clearing would silently destroy a caller's earlier `emulate` and why this record exists. * * WHAT IT CANNOT SEE, and this is a real limit rather than a caveat: an override applied by * something that is not this toolkit — the DevTools UI, Puppeteer, another automation client, or a * toolkit build older than this record — leaves no file, so a render-size capture restores by * clearing and that foreign override is reset to the real device. There is no CDP or BiDi command * that reads a device-metrics override back, so a driver genuinely cannot know it was there. */ export interface ViewportRecord { width: number; height: number; /** CDP's Emulation.setDeviceMetricsOverride sense: 0 means "the real device's". */ deviceScaleFactor?: number; mobile?: boolean; } /** Sibling of leases.ts's lease--.json, in the same directory and with the same * filename-safety policy. Keyed by the driver's uid SCHEME ("cdp" / "bidi") because a CDP targetId * and a BiDi context id are not disjoint by construction — the same reason lease files carry a * backend in the name. */ export function viewportRecordFile(scheme: string, targetId: string): string { return join(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`); } /** The override this toolkit last applied to `targetId`, or undefined when it has applied none. * A missing, unreadable, or malformed file all read as undefined: "we do not know" is the honest * answer, and it is the one that makes the caller restore by clearing rather than by guessing. */ export async function readViewportRecord(scheme: string, targetId: string): Promise { try { const raw = JSON.parse(await readFile(viewportRecordFile(scheme, targetId), "utf8")) as Partial; if (typeof raw?.width !== "number" || typeof raw?.height !== "number") return undefined; return { width: raw.width, height: raw.height, ...(typeof raw.deviceScaleFactor === "number" ? { deviceScaleFactor: raw.deviceScaleFactor } : {}), ...(typeof raw.mobile === "boolean" ? { mobile: raw.mobile } : {}), }; } catch { return undefined; } } /** Record an override this toolkit just applied. Deliberately best-effort: emulate's job is to * emulate, and a full disk must not turn a working override into a thrown error. The cost of a * lost write is stated above — a later render-size capture restores by clearing instead. */ export async function writeViewportRecord(scheme: string, targetId: string, rec: ViewportRecord): Promise { try { await mkdir(leaseDir(), { recursive: true }); await writeFile(viewportRecordFile(scheme, targetId), JSON.stringify({ scheme, targetId, ...rec }), "utf8"); } catch { /* best-effort, see above */ } } /** * What a driver appends to a capture's error when the render-size restore ALSO failed. Shared by * both drivers because the sentence is the caller's only warning that their page is still emulated, * and it must not read differently depending on which browser stranded it. Says what is wrong AND * how to undo it by hand, because at this point the toolkit has already failed to. */ export function renderRestoreFailureNote(size: { width: number; height: number }, why: string): string { return ( `— AND the ${size.width}x${size.height} render-size override could NOT be restored (${why}), so this page is STILL ` + `emulated at ${size.width}x${size.height}: put it back with emulate{width,height} or emulate{clearOverrides:true}.` ); } /** Forget the recorded override. Best-effort for the same reason, and a missing file is success. */ export async function clearViewportRecord(scheme: string, targetId: string): Promise { try { await unlink(viewportRecordFile(scheme, targetId)); } catch { /* best-effort, see above */ } } /** Each optional field names the Capability it requires, if any. */ export interface EmulationOptions { width?: number; height?: number; deviceScaleFactor?: number; // "emulate.deviceMetrics" mobile?: boolean; // "emulate.deviceMetrics" userAgent?: string; cpuThrottlingRate?: number; // "emulate.cpuThrottling" media?: string; // "emulate.mediaFeatures" mediaFeatures?: ReadonlyArray<{ name: string; value: string }>; // "emulate.mediaFeatures" /** Requires "emulate.networkConditions". connectionType is additive: CDP's optional * Network.ConnectionType hint ("wifi", "cellular4g", ...); drivers without a matching * concept simply ignore it. */ networkConditions?: { offline?: boolean; latency?: number; downloadThroughput?: number; uploadThroughput?: number; connectionType?: string }; clearOverrides?: boolean; } /** Neutral event names. Payload shapes are the driver's normalized records. */ export type DriverEvent = | "navigated" | "console" | "network.request" | "network.response" | "dialog" | "page.closed"; export interface DialogInfo { type: string; message: string; url: string; defaultPrompt?: string; } /** One dialog the driver answered, echoing back how it was answered. */ export interface HandledDialogInfo extends DialogInfo { accept: boolean; promptText?: string; handled: true; } /** * One cookie, neutral over CDP's `Network.Cookie` and BiDi's `network.Cookie`. * * Every flag a caller needs to reason about a session credential is present: * an httpOnly cookie is exactly the one `document.cookie` cannot read, so a * shape that dropped `httpOnly` would make the reason this exists invisible. * * Two normalizations, applied by both drivers so the shape does not change * with the backend: * - `expires` is a Unix timestamp in SECONDS, or -1 for a session cookie. * CDP reports exactly that; BiDi reports an optional `expiry` and omits it * for a session cookie, which the BiDi driver maps to -1. * - `sameSite` is lowercased to BiDi's vocabulary ("strict" | "lax" | "none" * | "default"). CDP capitalizes it and omits it entirely when unset, which * the CDP driver maps to "default". */ export interface BrowserCookie { name: string; value: string; domain: string; path: string; /** Unix seconds, or -1 for a session cookie. */ expires: number; /** Byte length of name plus value, as the browser reports it. */ size: number; httpOnly: boolean; secure: boolean; sameSite: "strict" | "lax" | "none" | "default"; /** True when the cookie expires with the browsing session (no expiry set). */ session: boolean; } /** * One cookie to WRITE, neutral over CDP's `Network.setCookie` and BiDi's * `storage.setCookie`. * * `url` and `domain` are both optional here but not both omittable: the cookie * has to be attributed to a site somehow, and every backend refuses without * one. The tool layer enforces that before either driver is reached, so the * refusal is one message rather than two different protocol errors. * * `expires` follows the read shape: Unix seconds. Omit it for a session cookie, * which is what both backends do when no expiry is supplied. */ export interface SetCookieParams { name: string; value: string; /** The URL the cookie is being set for. CDP derives domain, path and secure * from it; BiDi has no url parameter, so its driver derives the domain. */ url?: string; domain?: string; path?: string; /** Unix seconds. Omitted means a session cookie. */ expires?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "strict" | "lax" | "none" | "default"; } /** * Which cookies to DELETE, neutral over CDP's `Network.deleteCookies` and * BiDi's `storage.deleteCookies` filter. * * `name` is required and there is no wildcard: this deletes a named cookie, not * a swathe of them. As with SetCookieParams, one of `url` or `domain` must be * present, and the tool layer enforces it. */ export interface DeleteCookiesFilter { name: string; url?: string; domain?: string; path?: string; } export interface InterceptRule { /** Glob: `*` any run, `?` one char. Both drivers normalize to this. */ urlPattern: string; method?: string; action: "fulfill" | "fail" | "continue"; status?: number; body?: string; contentType?: string; headers?: Record; errorReason?: string; delayMs?: number; failRate?: number; } /* --------------------------------- drivers --------------------------------- */ /** * Connection ownership, declared rather than discovered. * - "per-call": acquiring opens a transport and release() closes it. Nothing * survives between tool calls. This is CDP today. * - "session": the transport carries a session that CANNOT be re-dialed, so * release() only decrements a refcount and the transport lives until * dispose(). This is BiDi. A "session" driver MUST be memoized at module * scope (see recorder.ts / network_mock.ts for the existing pattern) and * MUST tolerate concurrent holders. It does NOT transparently re-establish * itself if the transport dies: a BiDi session cannot be resumed on a * second socket (re-dialing gets `invalid session id`), so a dead * transport surfaces as an error on every subsequent call instead, and a * caller that hits one must dispose() and acquire a fresh driver. * Tools MUST NOT branch on this value. It exists so that withDriver's contract * is unambiguous and so a reader knows why release() is not a close(). */ export type LifetimeModel = "per-call" | "session"; /** * How a setValue/typeText commit actually reached the page (Chrome driver). "trusted": the * Input.insertText commit landed. A background tab never receives trusted keyboard input, so the * driver falls back in-page: "execCommand" (document.execCommand('insertText'), which fires real * beforeinput/input events) or "setter" (native value setter plus input/change events, for a * field execCommand cannot edit). "skipped": type_text on a disabled, read-only or non-text * element, which trusted typing would not have changed either (setValue refuses a disabled or * read-only field with a page-error instead, before clearing it). */ export type TextInputPath = "trusted" | "execCommand" | "setter" | "skipped"; /** Browser-scoped operations. One per browser process. */ export interface BrowserDriver { /** Uid scheme tag owned by this driver, e.g. "cdp" or "bidi". */ readonly scheme: string; readonly lifetime: LifetimeModel; readonly capabilities: ReadonlySet; readonly uidStability: UidStability; /** "accessibility-tree" when snapshots come from a native a11y dump. */ readonly snapshotFidelity: "accessibility-tree" | "dom-heuristic"; /** opts.all: include non-page targets (workers, iframes, ...) when the driver has that concept. */ listPages(opts?: { all?: boolean }): Promise; /** Opens the tab in the BACKGROUND by default, so the user's active tab and keyboard focus * stay put. opts.focus:true opens it in the foreground (the old default). */ newPage(url?: string, opts?: { focus?: boolean }): Promise; /** success mirrors the underlying protocol's own success signal when it has one (CDP's * Target.closeTarget); a driver without such a signal reports true once close resolves. */ closePage(id: string): Promise<{ success: boolean }>; /** Bring a page to the front: takes the user's active tab and window focus. Only an explicit * opt-in may call this (select_page with focus:true); nothing calls it implicitly. */ activatePage(id: string): Promise; /** Acquire a page handle. The caller MUST release() it. Prefer withDriver. */ page(selector: TargetSelector): Promise; /** * Install the activity beacon into a target and, where the backend can, into * every document it navigates to afterwards. Resolves true when the beacon is * in place. See src/activity.ts. * * OPTIONAL, per ADR-001's "absent rather than present-and-throwing" rule, but * NOT a `Capability`: that union gates whole tools out of tools/list, and no * tool is gated here. The beacon is an additive FIELD on claim_page and * list_leases, both of which work unchanged without it, so the honest * expression of a backend that cannot do this is an absent method producing an * absent field — not a missing tool and not a throw. */ installActivityBeacon?(targetId: string): Promise; /** * Read the beacon's timestamp for a target, or null when the target has no * beacon. WITHOUT THE LEASE GATE, which is required rather than convenient: * claim_page{target} must read this BEFORE claiming, and under * CDP_REQUIRE_LEASE a gated read would auto-acquire the lease and then collide * with the explicit claim behind it (the same reason pickPage is gate-free; * see leases-tools.ts's header). * * This is not a general gate bypass and must never become one: it returns one * number and takes no expression, so it cannot be made to read or change * anything else about the page. */ readActivityBeacon?(targetId: string): Promise; /** * Bounded liveness probe behind list_pages{probe:true}: run ONE Runtime.evaluate * (or backend equivalent) capped at `timeoutMs`, and report whether it * answered in time plus whatever the activity beacon said in that same round * trip. See src/activity.ts's RENDERER_PROBE_EXPRESSION for exactly what is * evaluated and why. * * MUST NEVER REJECT. A timeout, a thrown page-side exception, a dead * connection, or a target that no longer exists are all * `{responsive:false, beaconTs:null}` — indistinguishable from each other and * from a genuinely wedged renderer, which is the honest answer: none of them * let the caller drive that tab any faster than this call already told it. * * OPTIONAL and NOT a `Capability`, for the same reason installActivityBeacon * and readActivityBeacon are not: no whole tool is gated, only an additive * field on list_pages, so the honest expression of a backend that cannot do * this is an absent method producing an absent field. */ probeRenderer?(targetId: string, timeoutMs?: number): Promise<{ responsive: boolean; beaconTs: number | null }>; /** * Resolve a "worker:" selector to a concrete service/shared-worker * target, STARTING an idle-evicted MV3 service worker first when `wake` is * true. The returned PageInfo's id is a plain target id, so the caller then * acquires it through the ordinary page() path. * * OPTIONAL **and** gated by Capability "worker.targets", unlike * installActivityBeacon / readActivityBeacon / probeRenderer, which are * optional but deliberately NOT capabilities. The difference is what a caller * can observe: those three produce an absent FIELD on a result that is * otherwise complete, so silence is the honest answer. This one decides * whether an argument the caller explicitly wrote is honoured, and silently * resolving `worker:...` to something else — or to nothing — would be a wrong * answer rather than a missing annotation. So it refuses out loud, exactly as * drag's mode:'html5' does behind "input.html5Drag" (see resolveDragMode). * No tool is gated out of tools/list: evaluate_script is universal, only this * one arm of its `target` grammar is Chrome-only. * * MUST NOT report a wake it cannot see: an implementation is required to * confirm the worker is back in the target listing rather than trusting the * start command's own result. See cdp/workers.ts for why that is not * paranoia. */ resolveWorkerTarget?(selector: string, opts: { wake: boolean }): Promise; /** Tear down the transport: process exit (CLI) or shutdown (MCP server). * Idempotent. MUST NOT be called by a tool. */ dispose(): Promise; } /** Page-scoped operations. Every tool in src/tools/ maps onto this surface. */ export interface PageDriver { readonly info: PageInfo; readonly browser: BrowserDriver; /* navigation */ navigate(opts: NavigateOptions): Promise; /** Poll until `text` appears in the rendered body, or reject with "timeout". */ waitForText(text: string, timeoutMs?: number, pollMs?: number): Promise<{ found: true; elapsedMs: number }>; /* script */ /** Evaluate an expression, or call it as a function when `args` is given. */ evaluate(expression: string, opts?: { args?: readonly unknown[]; awaitPromise?: boolean }): Promise; /** * Execution contexts (issue #12; Capability "runtime.contexts", so optional: a driver without * it leaves all three undefined and the tools refuse the `context` / `allContexts` params). * listContexts waits for late contexts (settle: quiet period, capped). useContext PINS this * PageDriver to one context: every later evaluate, css locate and snapshot on it runs there. * evaluateAllContexts runs one expression in every context; a per-context throw is a row, not a throw. */ listContexts?(opts?: SettleOptions): Promise; useContext?(context: unknown, opts?: { css?: string; settle?: SettleOptions }): Promise; evaluateAllContexts?(expression: string, opts?: { args?: readonly unknown[]; awaitPromise?: boolean; settle?: SettleOptions }): Promise; /** Call a function literal with an element as `this`, returning by value. */ callOnElement(loc: ElementLocator, functionDeclaration: string, args?: readonly unknown[]): Promise; /* elements */ /** Emit the snapshot tree. Mints (and, under "bidi", stamps) every uid. */ snapshot(opts?: { interactiveOnly?: boolean }): Promise; /** Mint a uid for the first node matching a non-uid locator. */ locate(loc: ElementLocator): Promise; /** Assert a uid still resolves. Rejects "stale-uid" / "foreign-uid". */ resolve(uid: DriverUid): Promise; /* input */ click(loc: ElementLocator, opts?: MouseButtonOptions): Promise<{ x: number; y: number }>; hover(loc: ElementLocator): Promise<{ x: number; y: number }>; /** Press at `from`, move to `to`, release. `to` is an element, an absolute viewport point, or an * offset from the resolved source point (DragDestination). opts.mode picks synthetic-mouse vs. * real HTML5 drag events; opts.steps sets how many interpolated moves are dispatched. */ drag(from: ElementLocator, to: DragDestination, opts?: DragOptions): Promise<{ from: { x: number; y: number }; to: { x: number; y: number } }>; /** Dispatch a wheel/scroll event at an anchor point. `anchor` is an ElementLocator (scrolled * into view first, exactly like click/hover), an absolute viewport point, or `undefined` for * the viewport center. Chrome: Input.dispatchMouseEvent{type:"mouseWheel"}. Firefox: BiDi's * "wheel" input source via input.performActions. Universal: both drivers must implement it * (absent from driver.ts's REQUIRED_CAPABILITIES, unlike dispatch_mouse). */ scroll(anchor: ElementLocator | { x: number; y: number } | undefined, opts: ScrollOptions): Promise<{ x: number; y: number }>; /** One raw mouse event at viewport coordinates (dispatch_mouse), capability "input.raw". Only * the Firefox/BiDi driver implements it on this interface: Chrome's dispatch_mouse is the * standalone raw-CDP tool in tools/dispatch-mouse.ts, which has no PageDriver. Callers check the * method exists; the Firefox tool handler (bidi-tools.ts) does. */ dispatchMouse?(event: RawMouseEvent): Promise; /** Overwrite an element's value. One atomic commit under * "input.insertTextAtomic", else synthesized keystrokes, so per-key handlers * on the page WILL fire. Callers must not depend on either behavior. */ setValue(loc: ElementLocator, value: string): Promise; /** Append text at the focus point without clearing first. */ typeText(loc: ElementLocator, text: string): Promise; /** A driver that can tell returns { delivered:false } when the page saw no keydown. */ pressKey(press: KeyPress): Promise; /** Attach absolute file paths to a file input. */ setFiles(loc: ElementLocator, files: readonly string[]): Promise; /* rendering */ /** Returns raw image bytes. Artifact naming and writing stay in the tool. Under * renderWidth/renderHeight it also reports the emulated size it ran at and whether the previous * viewport was put back — see ScreenshotResult. * * `consumeBands` is how a caller says it can accept a capture too big to encode as one image * (see BandedCapture). Omitting it is a real and honest state, not a shortcut: a caller with * nowhere to put a band sequence gets the encode guard's refusal instead of a wedged tab, which * is exactly the pre-tiling behaviour. Supplying it lets the driver band the capture when the * projection demands it (the default) or when `tile:true` asks for it. The driver calls it at * most once and awaits it, so the whole capture — every band — is finished before this method * resolves and before any viewport override is put back. */ screenshot(opts?: ScreenshotOptions, consumeBands?: BandConsumer): Promise>; /** Apply overrides. Returns the field names actually applied. An implementation that applies * device metrics MUST record them with writeViewportRecord (and clear the record under * clearOverrides), or a later render-size capture will restore by clearing and destroy them. */ emulate(opts: EmulationOptions): Promise<{ applied: string[] }>; /* events */ /** Subscribe to a neutral event. Returns an unsubscribe fn. */ on(event: DriverEvent, handler: (payload: Record) => void): () => void; /** Resolve on the first matching event, or reject with "timeout". */ waitForEvent(event: DriverEvent, predicate?: (p: Record) => boolean, timeoutMs?: number): Promise>; /* dialogs */ /** Answer the next user prompt. Combine with waitForEvent("dialog") to arm first. * opts.timeoutMs: how long to wait for a dialog to open (default 15000). * opts.autoMs: instead of waiting for exactly one dialog, answer every dialog that * opens during this window (ms) and resolve with the list, never throwing on none. */ handleDialog( accept: boolean, promptText?: string, opts?: { timeoutMs?: number; autoMs?: number }, ): Promise; /* cookies */ /** * Every cookie visible to THIS page, httpOnly ones included. * * Deliberately page-scoped, not browser-scoped. Both protocols offer a * browser-wide jar (CDP's `Storage.getCookies` with no browserContextId, * BiDi's storageKey partition), and both would hand back every credential * for every site the browser has ever visited on a call that named one tab. * A tool scoped to a target returns that target's cookies; a caller who * wants another site's cookies points at a page on that site. */ getCookies(): Promise; /** * Write one cookie into the store this page reads from. * * Resolves only when the backend confirms the write. A backend that reports * a refusal (CDP's `Network.setCookie` answers `{success:false}` for a cookie * it will not accept) must throw rather than resolve, because a resolved * promise here reads as "the cookie is set" and a caller will believe it. */ setCookie(params: SetCookieParams): Promise; /** * Remove the cookies matching the filter from the store this page reads from. * * Neither backend reports how many cookies it removed, so this returns * nothing rather than an invented count. Deleting a cookie that was never * there is not an error on either backend. */ deleteCookies(filter: DeleteCookiesFilter): Promise; /* network */ /** Begin retaining response bodies. REQUIRED before getResponseBody unless * the driver declares "network.responseBodyPostHoc". Returns a stop fn. */ startBodyCapture(): Promise<() => Promise>; getResponseBody(requestId: string): Promise<{ body: string; base64Encoded: boolean }>; /** Requires "network.intercept". Returns a fn that removes the rule. */ intercept(rules: readonly InterceptRule[]): Promise<() => Promise>; /** Give up this handle: closes the transport under "per-call", decrements a * refcount under "session". Idempotent. Never assume it ends the session. */ release(): Promise; } /** The neutral replacement for withPage(): acquire, run, always release. The * ONLY acquisition path a tool should use, correct under both LifetimeModels. */ export type WithDriver = (selector: TargetSelector, fn: (page: PageDriver) => Promise) => Promise; /** Names a driver can be selected by, e.g. via a CDP_BROWSER env var. */ export type DriverKind = "chrome" | "firefox";