cdp-toolkit 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,23 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.3.0] - 2026-11-16
11
+
12
+ ### Added
13
+
14
+ - **Firefox 160 parity.** Eight capabilities the BiDi backend lacked on Firefox 153 now work on Firefox 160 or newer, each measured against a real Firefox 160.0. They are version-gated (`BIDI_CAPABILITY_MIN_FIREFOX`, `src/bidi/driver.ts`): on an older Firefox the same call returns `unsupported` naming the version it needs. Under `--browser firefox`, 38 of the 48 tools are now available (was 35).
15
+ - `dispatch_mouse` (`input.raw`), with a press held across calls. `clickCount` is ignored on Firefox.
16
+ - `click` `modifiers` (new capability token `input.modifierClick`, also declared by Chrome). On macOS, Firefox turns Ctrl+click into a context-menu gesture with no `click`.
17
+ - `emulate` `mediaFeatures` and offline `networkConditions`. Latency/throughput throttling and a media type are refused `unsupported`, never ignored.
18
+ - `wait_for_download` (`browser.setDownloadBehavior`, re-armed per call) and `grant_permissions` (`permissions.setPermission`, with a W3C name mapping and restore-on-reset/dispose, because Firefox grants persist in the profile). New `src/bidi-browser-tools.ts`.
19
+ - `get_network_request` `includeBody` reads a body fetched before any capture call (`network.addDataCollector`, 2 MB per response, Firefox-managed total budget). Evicted or unknown bodies are clear errors. Chrome does not have this.
20
+ - `take_screenshot` `scale` via a one-capture `devicePixelRatio` change that is then restored.
21
+ - `CDP_FIREFOX_BODY_COLLECTOR=off` skips the session-wide response-body collector.
22
+
23
+ ### Notes
24
+
25
+ - Still unimplemented in Firefox 160: forced-colors emulation, disabling scripting, touch emulation, `locateNodes` by `innerText`, and HTML5 drag (a BiDi pointer drag never fires `drop` or `dragend`).
26
+
10
27
  ## [3.2.0] - 2026-11-10
11
28
 
12
29
  ### Added
package/README.md CHANGED
@@ -211,7 +211,7 @@ cdp take_screenshot --target url:example --fullPage true
211
211
  # taken as vertical bands and stitched into one lossless PNG. No flag needed — this is the
212
212
  # default — and the result says so: {"width":2780,"height":281964,"tiled":true,"bands":18}.
213
213
  cdp take_screenshot --target url:example --fullPage true --savePath /tmp/whole-page.png
214
- # 3x output pixels for one capture (Chrome only). The page is not told anything changed.
214
+ # 3x output pixels for one capture (Chrome, or Firefox 160+). The page is not told anything changed.
215
215
  cdp take_screenshot --target url:example --scale 3
216
216
  # Shoot a responsive page at desktop width from a tab that isn't that size, then restore it.
217
217
  cdp take_screenshot --target url:example --renderWidth 1920 --renderHeight 1080
@@ -257,6 +257,7 @@ await TOOLS.navigate_page({ target: "index:0", url: "https://example.com" });
257
257
  | `CDP_FIREFOX_SESSION_WAIT_MS` | `10000` | Firefox backend only. How long a second process waits for a live holder to release Firefox's one BiDi session before returning the distinguishable "held by a live process" error. See "Firefox" below. |
258
258
  | `CDP_FIREFOX_MUX` | `daemon` when attaching, `host` when launching | Firefox backend only. Which process hosts the loopback BiDi multiplexer that lets several cdp-toolkit processes drive one Firefox: `daemon` (attach-mode default) spawns/joins a detached process that owns the real session for as long as anyone needs it; `host` makes THIS process the holder (launch mode's default, since a launched Firefox and its holder already share a lifetime); `off` restores pre-mux behavior — one live session per Firefox, a second process refused after the wait. See "Firefox" below and "Parallel tabs" below. |
259
259
  | `CDP_FIREFOX_MUX_IDLE_MS` | `15000` | Firefox backend only, daemon mode. How long the mux daemon stays up with zero connected clients before it exits on its own (also counted from its own startup, so a spawner that never connects can't strand one). |
260
+ | `CDP_FIREFOX_BODY_COLLECTOR` | on | Firefox 160+ only. `off` skips the session-wide response-body collector, so Firefox keeps no response bodies for this toolkit; `get_network_request` `includeBody` then reads only bodies armed by a capture call first, like Chrome. |
260
261
  | `CDP_FIREFOX_MUX_DAEMON` | resolved from the running module's location | Firefox backend only, tests only. Absolute path override for the daemon script the driver spawns, in place of the built-in resolution (`./mux-daemon.ts` in source, `dist/bidi/mux-daemon.js` in the published package). |
261
262
 
262
263
  ## Progressive disclosure
@@ -478,27 +479,41 @@ This coordinates and recovers **around** Firefox's one-session limit; it does no
478
479
 
479
480
  **Attaching is not relaunching.** The one thing that is genuinely impossible is handing a debug port to an *already-running* Firefox process after the fact: the `--remote-debugging-port` flag only takes effect on a process's original launch, so relaunching the `firefox` binary against a running instance hands off to it and exits silently, opening no port (verified against Firefox 153.0.3). That is a real, narrow limitation of the Firefox binary itself. It is not the same claim as "Firefox cannot be attached to" — a Firefox that was launched *with* the debug port open, whether by this toolkit or by your own hand, exposes a plain BiDi endpoint that any number of fresh clients can connect to later, which is exactly what `--connect`/`CDP_FIREFOX_ENDPOINT` does.
480
481
 
481
- **Tool availability is filtered per backend**, not per call: `tools/list` (MCP) and `--list`/`--capabilities` (CLI) only ever advertise a tool the selected browser can actually run. A tool is never listed and then thrown from at call time. On the MCP server a second filter composes on top: a tool is listed only when the backend can run it *and* the startup profile includes it — backend availability first, `CDP_TOOL_PROFILE` second (see [Progressive disclosure](#progressive-disclosure)). Under Firefox, six capability areas are absent because Firefox 153's BiDi implementation has no equivalent domain:
482
+ **Tool availability is filtered per backend**, not per call: `tools/list` (MCP) and `--list`/`--capabilities` (CLI) only ever advertise a tool the selected browser can actually run. A tool is never listed and then thrown from at call time. On the MCP server a second filter composes on top: a tool is listed only when the backend can run it *and* the startup profile includes it — backend availability first, `CDP_TOOL_PROFILE` second (see [Progressive disclosure](#progressive-disclosure)). Under Firefox, five capability areas are absent because WebDriver BiDi (as of Firefox 160) has no equivalent domain:
482
483
 
483
484
  - `performance_start_trace`, `performance_stop_trace`, `performance_analyze_insight`, `performance_trace` (needs `trace.performance`)
484
485
  - `take_heapsnapshot` (needs `heap.snapshot`)
485
486
  - `lighthouse_audit` (needs `audit.lighthouse`)
486
487
  - `start_screen_recording`, `stop_screen_recording` (needs `capture.screencast`): BiDi has no streamed-frame primitive at all, only the one-shot `browsingContext.captureScreenshot`.
487
- - `dispatch_mouse` (needs `input.raw`): the raw move/down/up primitive is a direct `Input.dispatchMouseEvent` wrapper with no BiDi analogue.
488
- - `wait_for_download`, `grant_permissions` (need `browser.downloads` / `browser.permissions`): both drive Chrome's `Browser.*` domain; WebDriver BiDi has no command to redirect a download or pre-grant a permission.
488
+ - `focus_emulation`, `click_focus_gated` (need `emulate.focus`): no BiDi command keeps a background tab reporting focus.
489
489
 
490
- Everything else, including `mock_request`/`list_mocks`/`clear_mocks` (Firefox's `network.addIntercept` covers the same fake-backend use case as Chrome's `Fetch` domain), the `claim_page`/`release_page`/`list_leases` lease group, the `extract_page` extraction tool (its page work runs entirely through the driver's evaluate, no CDP-only capability), and the new `scroll` tool (Chrome dispatches `Input.dispatchMouseEvent{type:'mouseWheel'}`, Firefox uses BiDi's `wheel` input source — both live-verified), is available under both backends: 35 of the 48 tools. Under `CDP_BROWSER=firefox` the MCP server's `CDP_TOOL_PROFILE=full` listing is therefore 37 entries — those 35 plus `search_tools` and `call_tool` — while the 3.0 default (`gateway`) lists 7 under either browser; the profile filter applies after this backend filter. One asymmetry to know before expecting Chrome-style concurrency: the lease group fences *tabs* on both backends, but Firefox permits only **one BiDi session per browser instance**, so multiple agent PROCESSES under Firefox share that one session rather than opening independent ones the way Chrome's unlimited CDP connections allow — coordinated by the cross-process session lease and, by default, joined through the BiDi multiplexer above, so sharing no longer means waiting a turn — see "Parallel tabs" below.
490
+ **Firefox 160 closed several gaps (cdp-toolkit 3.3.0).** Each was measured against a real Firefox 160.0 and is version-gated: on an older Firefox the same call returns an `unsupported` error naming the Firefox version it needs, never a half-applied change.
491
+
492
+ | Capability | Tools / parameters | Firefox-side behavior to know |
493
+ |---|---|---|
494
+ | `input.raw` | `dispatch_mouse` | A `down` in one call stays held for an `up` in a later call. Each event is preceded by a move to its point, so expect an extra `mousemove`. `clickCount` is ignored (BiDi has no such field). |
495
+ | `input.modifierClick` | `click` `modifiers` | Alt/Control/Meta/Shift reach the page. On macOS, Firefox treats Ctrl+click as a context-menu gesture: the page gets `mousedown` + `contextmenu` with `ctrlKey`, and no `click`. |
496
+ | `emulate.mediaFeatures` | `emulate` `mediaFeatures` | e.g. `prefers-color-scheme`. A media *type* (`media: "print"`) is refused `unsupported`. |
497
+ | `emulate.networkConditions` | `emulate` `networkConditions` | **Offline only.** Any latency/throughput throttle is refused `unsupported`, never silently ignored. |
498
+ | `browser.downloads` | `wait_for_download` | Same arguments and result as Chrome. Firefox stays redirected only until the call returns or times out, then later downloads go back to the profile's normal folder, so arm before *every* download. While armed, a download the user starts in that Firefox is redirected too. |
499
+ | `browser.permissions` | `grant_permissions` | Firefox grants **persist in the profile** across sessions, so `reset` and session shutdown put back the state the page saw before the first grant. A process killed with `SIGKILL` leaves its grants behind. Names are mapped to W3C names (`audioCapture`→`microphone`, `videoCapture`→`camera`, `durableStorage`→`persistent-storage`, `wakeLockScreen`→`screen-wake-lock`, plus `geolocation`, `notifications`, `midi`, `midiSysex`). Anything else (e.g. `clipboardReadWrite`, which Firefox rejects) is refused `unsupported`. Only the named permissions are touched, unlike Chrome's grant. |
500
+ | `network.responseBodyPostHoc` | `get_network_request` `includeBody` | A body the page fetched *before* the body call is readable by request id, with no capture call first; the id must come from a network event this process observed (`list_network_requests`, `get_network_request`). A request that predates this process has no id here. One collector is armed when the session is created (2 MB cap per response). Firefox owns the total budget (measured ~100–200 MB) and evicts the oldest bodies first; an evicted or unknown body is a clear error, never empty text. Chrome still does not have this. `CDP_FIREFOX_BODY_COLLECTOR=off` turns the collector off. |
501
+ | `screenshot.scale` | `take_screenshot` `scale` | Rides `browsingContext.setViewport {devicePixelRatio}` for one capture, then restores the previous ratio. |
502
+
503
+ Still unimplemented in Firefox 160 (the commands return `unknown command`): forced-colors emulation, disabling scripting, touch emulation, and `locateNodes` by `innerText`.
504
+
505
+ Everything else, including `mock_request`/`list_mocks`/`clear_mocks` (Firefox's `network.addIntercept` covers the same fake-backend use case as Chrome's `Fetch` domain), the `claim_page`/`release_page`/`list_leases` lease group, the `extract_page` extraction tool (its page work runs entirely through the driver's evaluate, no CDP-only capability), and the new `scroll` tool (Chrome dispatches `Input.dispatchMouseEvent{type:'mouseWheel'}`, Firefox uses BiDi's `wheel` input source — both live-verified), is available under both backends: 38 of the 48 tools on Firefox 160 or newer. Under `CDP_BROWSER=firefox` the MCP server's `CDP_TOOL_PROFILE=full` listing is therefore 40 entries — those 38 plus `search_tools` and `call_tool` — while the 3.0 default (`gateway`) lists 7 under either browser; the profile filter applies after this backend filter. One asymmetry to know before expecting Chrome-style concurrency: the lease group fences *tabs* on both backends, but Firefox permits only **one BiDi session per browser instance**, so multiple agent PROCESSES under Firefox share that one session rather than opening independent ones the way Chrome's unlimited CDP connections allow — coordinated by the cross-process session lease and, by default, joined through the BiDi multiplexer above, so sharing no longer means waiting a turn — see "Parallel tabs" below.
491
506
 
492
507
  **Honest capability gaps, not oversold parity:**
493
508
 
494
- - **No accessibility tree.** `take_snapshot` under Chrome reads a native a11y tree (`Accessibility.getFullAXTree`). Firefox 153's BiDi has no equivalent domain, so the Firefox snapshot is a DOM-heuristic walk that infers roles from tag/attribute conventions. It is good enough to find and click things; it is not a substitute for a real accessibility audit.
509
+ - **No accessibility tree.** `take_snapshot` under Chrome reads a native a11y tree (`Accessibility.getFullAXTree`). Firefox's BiDi (still as of 160) has no equivalent domain, so the Firefox snapshot is a DOM-heuristic walk that infers roles from tag/attribute conventions. It is good enough to find and click things; it is not a substitute for a real accessibility audit.
495
510
  - **No atomic text insert.** Chrome's `fill`/`type_text` commit a value in one `Input.insertText` call. BiDi has no equivalent primitive, so Firefox always synthesizes real per-character keystrokes via `input.performActions` (one `<select>` exception: an exact-match value/index assignment, since typeahead-by-first-letter cannot reliably commit an arbitrary option).
496
- - **Thin emulation.** Only viewport size/DPR and `userAgent` are applied. CPU throttling, media-feature emulation (e.g. `prefers-color-scheme`), and network-condition throttling are not available: Firefox 153 does not implement the underlying BiDi commands.
511
+ - **Partial emulation.** Viewport size/DPR, `userAgent`, media features and offline mode are applied (the last two on Firefox 160+). CPU throttling and latency/throughput throttling are not available: BiDi has no command for either.
497
512
  - **No tracing, heap snapshots, or Lighthouse.** See the capability list above; there is no BiDi equivalent for any of the three.
498
- - **`locate.text` is not available** (Firefox 153's `browsingContext.locateNodes` rejects the `innerText` locator type as unsupported), unlike Chrome, which has it via `DOM.performSearch`.
499
- - **No modifier-key clicks.** `click`'s `modifiers` (Alt/Control/Meta/Shift) is a Chrome-only *parameter* on an otherwise-universal tool: a non-empty `modifiers` array throws under `--browser firefox` rather than being silently dropped. A plain click still works on both backends.
500
- - **No real HTML5 drag-and-drop mode.** `drag`'s `mode:"html5"` requires capability `input.html5Drag` and is rejected with a clear error under Firefox; `mode:"mouse"` (the default) works on both.
501
- - **No per-capture screenshot `scale`; band tiling is a Chrome-only workaround Firefox has no use for.** Two *parameters* on an otherwise-universal tool, for two different reasons. `scale` (`screenshot.scale`) is a genuine protocol gap: `browsingContext.captureScreenshot` has no scale parameter at all, and the refusal points at `emulate {deviceScaleFactor}` + a scale-1 capture instead — Firefox captures are always 1x. `tile:true` (`screenshot.tile`) is **not** a Firefox gap: measured against Firefox 153.0.3, `take_screenshot --fullPage true` on a 20,000px-tall page returned one 1366×20000 PNG at scale 1 from a single BiDi `captureScreenshot(origin:"document")` call — verified complete top-to-bottom (a marker at y=0, a marker at y=20000, an unbroken ruler through the middle, no truncation). Chrome's banding exists solely to route around its 16384-device-px encode cap; Firefox has no such cap, so there is nothing for tiling to work around, and auto-tiling correctly never fires there — a Firefox `fullPage` capture is already the whole page in one shot, however long. **`renderWidth`/`renderHeight` (`screenshot.renderSize`) are available on both backends** — that one is not a gap.
513
+ - **`locate.text` is not available** (Firefox 160's `browsingContext.locateNodes` still rejects the `innerText` locator type as unsupported), unlike Chrome, which has it via `DOM.performSearch`.
514
+ - **Modifier-key clicks need Firefox 160.** On an older Firefox a non-empty `modifiers` array throws rather than being silently dropped. A plain click works on every version.
515
+ - **No real HTML5 drag-and-drop mode.** `drag`'s `mode:"html5"` requires capability `input.html5Drag` and is rejected with a clear error under Firefox; `mode:"mouse"` (the default) works on both. Measured on Firefox 160.0: a BiDi pointer drag fires `dragstart`, `dragenter` and `dragover`, but never `drop` or `dragend`, so the capability stays undeclared.
516
+ - **Screenshot `scale` needs Firefox 160; band tiling is a Chrome-only workaround Firefox has no use for.** `scale` (`screenshot.scale`) rides a one-capture `devicePixelRatio` change on Firefox 160+ (see the table above); on older Firefox it is refused and the refusal points at `emulate {deviceScaleFactor}` + a scale-1 capture instead. `tile:true` (`screenshot.tile`) is **not** a Firefox gap: measured against Firefox 153.0.3, `take_screenshot --fullPage true` on a 20,000px-tall page returned one 1366×20000 PNG at scale 1 from a single BiDi `captureScreenshot(origin:"document")` call — verified complete top-to-bottom (a marker at y=0, a marker at y=20000, an unbroken ruler through the middle, no truncation). Chrome's banding exists solely to route around its 16384-device-px encode cap; Firefox has no such cap, so there is nothing for tiling to work around, and auto-tiling correctly never fires there — a Firefox `fullPage` capture is already the whole page in one shot, however long. **`renderWidth`/`renderHeight` (`screenshot.renderSize`) are available on both backends** — that one is not a gap.
502
517
 
503
518
  ## The tools (29 parity + 19 superset = 48)
504
519
 
@@ -519,11 +534,11 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
519
534
  | `set_cookie` *(superset)* | `Network.setCookie` | Writes one cookie, httpOnly and secure ones included, which `document.cookie` cannot create. Either `url` or `domain` is required and the call is refused with an error when neither is given. Chrome's `success:false` refusal is raised as an error rather than reported as a write. Answers `{set:true,target}` and never echoes the value back. `path` is passed through as given, never defaulted. |
520
535
  | `delete_cookies` *(superset)* | `Network.deleteCookies` | Removes the named cookie, httpOnly ones included. Requires `name` plus `url` or `domain`, so a name-only call cannot sweep the store; optional `path` narrows further. Answers `{deleted:true,target}` with no count, because neither protocol reports one; read `list_cookies` before and after for a real count. |
521
536
  | `take_snapshot` | `Accessibility.getFullAXTree` | uid is the raw `backendDOMNodeId` (stateless, non-sequential). Full tree in one shot; frames flattened. `interactiveOnly` is a toolkit addition. |
522
- | `click` | `Input.dispatchMouseEvent` | No implicit auto-wait/retry; resolves and acts once; re-snapshot between steps. `clickCount:3` triple-clicks (selects a paragraph/line in most editors). `modifiers` (Alt/Control/Meta/Shift) holds keys for the press and release, e.g. a shift-click — **Chrome-only param**: a non-empty array throws under `--browser firefox`. |
537
+ | `click` | `Input.dispatchMouseEvent` | No implicit auto-wait/retry; resolves and acts once; re-snapshot between steps. `clickCount:3` triple-clicks (selects a paragraph/line in most editors). `modifiers` (Alt/Control/Meta/Shift) holds keys for the press and release, e.g. a shift-click — On Firefox it needs Firefox 160+ (`input.modifierClick`); an older Firefox throws rather than dropping the keys. |
523
538
  | `hover` | `Input.dispatchMouseEvent` (`mouseMoved`) | Same single-shot model as `click`. |
524
539
  | `scroll` *(superset)* | Chrome: `Input.dispatchMouseEvent{type:'mouseWheel'}`; Firefox: BiDi's `wheel` input source | Anchor at `uid`/`selector`/`x`+`y`, or the viewport center if all three are omitted; an element anchor is scrolled into view first. At least one of `deltaX`/`deltaY` is required (positive `deltaY` scrolls down, positive `deltaX` scrolls right — wheel convention). Returns `{x,y,deltaX,deltaY,target}`. Works on both backends. |
525
540
  | `drag` | Chrome: `Input.dispatchMouseEvent` (press→move→release), or `mode:"html5"`: `Input.setInterceptDrags` + `Input.dispatchDragEvent` | `mode:"mouse"` (default) sends a synthetic mouse drag; Chrome does turn this into a real HTML5 drag too, but which `dragenter`/`dragover`/`drop` events reach the page depends on where the interpolated pointer path lands — at the default `steps:2`, a standard HTML5 drop zone (`preventDefault` inside `dragover`) sees zero `dragover` events and refuses the drop. `mode:"html5"` replays the page's own drag data as `dragEnter`/`dragOver`/`drop` exactly at the destination, so it works regardless of pointer path — **Chrome-only** (`input.html5Drag`), rejected with a clear error under Firefox. `steps` (default 2) sets the interpolated-move count for mouse mode. Destination is `to:{uid\|selector\|x,y}` or a new `by:{dx,dy}` offset (sliders, map panning); exactly one of `to`/`by` is required. |
526
- | `dispatch_mouse` *(superset)* | `Input.dispatchMouseEvent` (one event per call) | The raw primitive: dispatch exactly one `move`/`down`/`up` at absolute viewport coordinates (`x`/`y` required on every call — CDP has no notion of a "current pointer position"). Compose your own move/down/move/up sequences for anything a physical mouse can do that `click`/`drag`'s fixed sequences can't: canvas drag-painting, marquee/rubber-band selection, a custom-hit-testing widget. Takes the same `button`/`clickCount`/`modifiers` as `click`. **Chrome-only** (`input.raw`): absent from `tools/list` under `--browser firefox`, never present-and-throwing. |
541
+ | `dispatch_mouse` *(superset)* | `Input.dispatchMouseEvent` (one event per call) | The raw primitive: dispatch exactly one `move`/`down`/`up` at absolute viewport coordinates (`x`/`y` required on every call — CDP has no notion of a "current pointer position"). Compose your own move/down/move/up sequences for anything a physical mouse can do that `click`/`drag`'s fixed sequences can't: canvas drag-painting, marquee/rubber-band selection, a custom-hit-testing widget. Takes the same `button`/`clickCount`/`modifiers` as `click`. Firefox 160+ too (`input.raw`, via `input.performActions`; `clickCount` ignored there), refused `unsupported` on an older Firefox. |
527
542
  | `focus_emulation` *(superset)* | `Emulation.setFocusEmulationEnabled` | Makes the tab *believe* it is focused (`document.hasFocus()`→true, visibility stays `visible`, focus events fire) while the real OS window stays put — no focus theft. The primitive that unlocks focus-gated UI (a button a site disables unless its tab is focused, e.g. the Claude Code OAuth **Authorize** button) on a background tab. Call with `enabled:false` to restore. **Chrome-only** (`emulate.focus`): BiDi's emulation module has no focus primitive, so absent from `tools/list` under `--browser firefox`. |
528
543
  | `click_focus_gated` *(superset)* | `Emulation.setFocusEmulationEnabled` + `Input.dispatchMouseEvent` | The one-call compose: enable focus emulation, poll until the button (CSS selector or exact visible-text match, e.g. `"Authorize"`) exists **and** is enabled, deliver a **trusted** click (`isTrusted:true` — a content script's synthesized events can never satisfy a focus gate), then restore emulation (always, unless `keepFocus`, even on throw). Timeout error names the failure mode ("never located" vs "found but stayed disabled"). Same **Chrome-only** gap as `focus_emulation`. |
529
544
  | `fill` | `Input.insertText` | Atomic paste-like commit, not per-character keystrokes. |
@@ -531,7 +546,7 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
531
546
  | `type_text` | `Input.insertText` | Appends (does not clear first); insertText, not per-key. |
532
547
  | `press_key` | `Input.dispatchKeyEvent` | Curated named-key table + single chars; not the full Puppeteer KeyInput enum. |
533
548
  | `upload_file` | `DOM.setFileInputFiles` | Requires a resolvable `<input type=file>` (uid or selector). |
534
- | `take_screenshot` | `Page.captureScreenshot` (+ `Page.getLayoutMetrics` on **every** capture) | Full-page uses `captureBeyondViewport` + a layout-metrics clip. `scale` (>0, ≤8, **Chrome-only**) multiplies output pixels for one capture: output px = `ceil(css × scale × devicePixelRatio)`, and the page is never told (`devicePixelRatio`/`innerWidth` are unmoved). `renderWidth`+`renderHeight` (**both backends**, required together) emulate a viewport for one capture and restore it after — media queries flip, so this is how you shoot a responsive page at 1920×1080 from a tab that isn't. Chrome cannot encode past **16384 device px per side** and does not refuse politely there, so past the cap the capture is taken as vertical bands and stitched losslessly into one PNG (`tile`, auto by default; `tiled`/`bands` on the result): a 140,982 CSS px page returns 2780×281964 px in 18 bands instead of hanging and wedging the tab. Banding is vertical only (an over-wide projection is refused, not split), PNG-only, and never with `returnBase64`; content the page loads only on real scroll renders blank past the first viewport. `width`/`height` are decoded from the encoded bytes and omitted when undecodable. |
549
+ | `take_screenshot` | `Page.captureScreenshot` (+ `Page.getLayoutMetrics` on **every** capture) | Full-page uses `captureBeyondViewport` + a layout-metrics clip. `scale` (>0, ≤8; Firefox 160+ via a one-capture `devicePixelRatio`) multiplies output pixels for one capture: output px = `ceil(css × scale × devicePixelRatio)`, and the page is never told (`devicePixelRatio`/`innerWidth` are unmoved). `renderWidth`+`renderHeight` (**both backends**, required together) emulate a viewport for one capture and restore it after — media queries flip, so this is how you shoot a responsive page at 1920×1080 from a tab that isn't. Chrome cannot encode past **16384 device px per side** and does not refuse politely there, so past the cap the capture is taken as vertical bands and stitched losslessly into one PNG (`tile`, auto by default; `tiled`/`bands` on the result): a 140,982 CSS px page returns 2780×281964 px in 18 bands instead of hanging and wedging the tab. Banding is vertical only (an over-wide projection is refused, not split), PNG-only, and never with `returnBase64`; content the page loads only on real scroll renders blank past the first viewport. `width`/`height` are decoded from the encoded bytes and omitted when undecodable. |
535
550
  | `start_screen_recording` *(superset)* | `Page.startScreencast` / `Page.screencastFrame` / `Page.screencastFrameAck` | **Toolkit addition; chrome-devtools-mcp has no screen-recording tool.** Opens a persistent per-target connection and spools frames to a ledger on disk; pairs with `stop_screen_recording` in the SAME process, for the same cross-process reason as `performance_start_trace`. ffmpeg is probed here so a missing encoder fails before a recording is captured. Chrome only: absent from `tools/list` under `--browser firefox` (needs `capture.screencast`, which BiDi has no primitive for). |
536
551
  | `stop_screen_recording` *(superset)* | `Page.stopScreencast` (+ ffmpeg encode) | Assembles the spooled frames into an H.265 (`hevc_videotoolbox`, falling back to `h264_videotoolbox` → `libx265` → `libx264`) MP4 using per-frame durations from the capture ledger, coalesced onto ffmpeg's 40ms concat-demuxer grid. Returns `{path,bytes,durationMs,frameCount,encodedFrames,codec,encoder,width,height,droppedFrames,target}` (`frameCount` captured vs. `encodedFrames` in the video). On an ffmpeg failure the spool is kept and the exact re-run command is named in the error. |
537
552
  | `emulate` | `Emulation.*` / `Network.emulateNetworkConditions` | Stateless: UA/CPU/media/network overrides reset when the per-call connection closes. No named device presets. |
@@ -553,8 +568,8 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
553
568
  | `claim_page` *(superset)* | `Target.createTarget` + lease file | Opens a fresh tab and claims it (no `target`/`targetId`), or takes over a tab that is already open (`target`, any selector, or the exact-id `targetId`) and returns an opaque lease token plus `opened` (true only when this call created the tab). Never steals a tab another live process holds. Also returns `humanActiveMs` (ms since input this server did not dispatch; `null` means no data, never "no human") and, on a takeover of a tab a human used within the last 30s, a `contention` warning — the claim is never refused for it. MCP only; the CLI refuses it. The `search_tools` and `call_tool` meta-tools are likewise MCP-only. |
554
569
  | `release_page` *(superset)* | lease file | Gives a lease back via `lease` (the token) or `target` (a selector, for a lease the gate auto-acquired and so never handed out a token for). Idempotent. Closes the tab by default when this toolkit's creation ledger says it opened it; leaves a merely-claimed tab open. Override either way with `close`. |
555
570
  | `list_leases` *(superset)* | lease file | Who holds what, with pid liveness and reclaimability, plus computed `idleMs`/`expiresAt` and, where the tab's beacon answers, `humanActiveMs` (absent, not null, when there's no answer). Needs no token; never returns the nonce. A lease file that could not be read or parsed is reported as an `unreadable` row instead of being skipped (with `idleMs`/`expiresAt` omitted). Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs, reporting closures in an additive `reaped` array. |
556
- | `wait_for_download` *(superset)* | `Browser.setDownloadBehavior` + `Browser.downloadWillBegin`/`downloadProgress` on a standing browser-endpoint connection | Waits for a download to finish and returns it as a real file on disk: `{path,suggestedFilename,bytes,url,target}`. **Ordering rule, not optional:** call `wait_for_download{arm:true}` *before* the click that starts the download, then click, then call `wait_for_download` again to collect it — arming this late is not a preference, it's because Chrome reverts the download-behavior override the instant the arming client disconnects, and denies an unarmed download outright. **Browser-global side effect:** while armed, *every* download in the browser is redirected into the toolkit's downloads directory. **MCP-server only:** the arm lives on a connection this server process holds open; the one-shot CLI's connection dies with the process, so nothing is captured there. Chrome-only (`browser.downloads`). |
557
- | `grant_permissions` *(superset)* | `Browser.grantPermissions` / `Browser.resetPermissions` on the same standing connection | Grants permissions (`geolocation`, `notifications`, `clipboardReadWrite`, ...) for an origin up front, so a page doesn't show a prompt no agent can click. Keyed by **origin**, not tab — every tab on that origin is affected, including ones opened later. `reset:true` clears this server's previous grants first (or instead); note CDP's reset is not origin-scoped, so it clears every origin at once. Same MCP-server-only reasoning as `wait_for_download`: Chrome discards the grant the moment the granting connection closes. Chrome-only (`browser.permissions`). |
571
+ | `wait_for_download` *(superset)* | `Browser.setDownloadBehavior` + `Browser.downloadWillBegin`/`downloadProgress` on a standing browser-endpoint connection | Waits for a download to finish and returns it as a real file on disk: `{path,suggestedFilename,bytes,url,target}`. **Ordering rule, not optional:** call `wait_for_download{arm:true}` *before* the click that starts the download, then click, then call `wait_for_download` again to collect it — arming this late is not a preference, it's because Chrome reverts the download-behavior override the instant the arming client disconnects, and denies an unarmed download outright. **Browser-global side effect:** while armed, *every* download in the browser is redirected into the toolkit's downloads directory. **MCP-server only:** the arm lives on a connection this server process holds open; the one-shot CLI's connection dies with the process, so nothing is captured there. Firefox 160+ too (`browser.setDownloadBehavior`), where each call re-arms and the profile's normal download folder is restored when it returns. |
572
+ | `grant_permissions` *(superset)* | `Browser.grantPermissions` / `Browser.resetPermissions` on the same standing connection | Grants permissions (`geolocation`, `notifications`, `clipboardReadWrite`, ...) for an origin up front, so a page doesn't show a prompt no agent can click. Keyed by **origin**, not tab — every tab on that origin is affected, including ones opened later. `reset:true` clears this server's previous grants first (or instead); note CDP's reset is not origin-scoped, so it clears every origin at once. Same MCP-server-only reasoning as `wait_for_download`: Chrome discards the grant the moment the granting connection closes. Firefox 160+ too (`permissions.setPermission`), with the name mapping and persistence notes in the Firefox section. |
558
573
  | `extract_page` *(superset)* | `Runtime.evaluate` (clean the HTML in-page) → **non-CDP** `fetch` of an OpenAI-compatible `/chat/completions` endpoint | Sends the page's cleaned HTML plus your JSON Schema to the endpoint and returns **schema-conformant JSON** instead of prose. **The default endpoint is loopback** — llm-ferry at `http://127.0.0.1:8090/v1`, model `schematron` — so page content stays on this machine unless the operator points `baseUrl`/`CDP_EXTRACT_BASE_URL` elsewhere (see [Structured page extraction](#structured-page-extraction-extract_page)). The extraction *instructions* live in the schema's property `description`s; a schema whose properties carry none is rejected up front. Over `maxChars` (default 300000) it fails with `html_too_large` rather than truncating — shrink with `selector`/`clean:"aggressive"` or raise the cap. `usage` tokens (and cost, when the endpoint reports it) come back inline on every call; `savePath` keeps large payloads out of the transcript. `prompt:"schematron"` (or `CDP_EXTRACT_PROMPT`) swaps the default HTML-only user message for the open-weight Schematron model-card prompt with the schema inline — needed when `baseUrl` points at a locally served open-weight Schematron. Works on both backends. |
559
574
 
560
575
  ## Driving MV3 extensions
@@ -2999,6 +2999,8 @@ function mapBidiError(e) {
2999
2999
  return driverError("disconnected", e.message);
3000
3000
  if (code === "unsupported operation")
3001
3001
  return driverError("unsupported", e.message);
3002
+ if (code === "unknown command")
3003
+ return driverError("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
3002
3004
  if (!code && /timed out/i.test(e.message))
3003
3005
  return driverError("timeout", e.message);
3004
3006
  if (!code && /(disposed|not open|connection closed)/i.test(e.message))
@@ -3152,6 +3154,69 @@ async function resolveElementLocator(conn, contextId, loc) {
3152
3154
  throw driverError("no-such-element", `text '${loc.text}' matched no element`);
3153
3155
  return sharedRefOf(nodes[0], `text '${loc.text}'`);
3154
3156
  }
3157
+ function modifierKeyValues(mods) {
3158
+ const out = [];
3159
+ for (const m of mods ?? []) {
3160
+ const v = MODIFIER_VALUES[m.toLowerCase()];
3161
+ if (v === undefined)
3162
+ throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
3163
+ if (!out.includes(v))
3164
+ out.push(v);
3165
+ }
3166
+ return out;
3167
+ }
3168
+ function modifierChord(pointerId, actions, keys) {
3169
+ const pointer = actions;
3170
+ if (keys.length === 0)
3171
+ return [{ type: "pointer", id: pointerId, actions: pointer }];
3172
+ const k = keys.length;
3173
+ const pause = () => ({ type: "pause" });
3174
+ const keyActions = [
3175
+ ...keys.map((v) => ({ type: "keyDown", value: v })),
3176
+ ...pointer.map(pause),
3177
+ ...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
3178
+ ];
3179
+ const pointerActions = [
3180
+ ...Array.from({ length: k }, pause),
3181
+ ...pointer,
3182
+ ...Array.from({ length: k }, pause)
3183
+ ];
3184
+ return [
3185
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
3186
+ { type: "pointer", id: pointerId, actions: pointerActions }
3187
+ ];
3188
+ }
3189
+ function firefoxMajor(conn) {
3190
+ const v = conn.capabilities?.browserVersion;
3191
+ if (typeof v !== "string")
3192
+ return;
3193
+ const major = Number.parseInt(v, 10);
3194
+ return Number.isFinite(major) ? major : undefined;
3195
+ }
3196
+ function requireFirefox(conn, token) {
3197
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
3198
+ if (min === undefined)
3199
+ return;
3200
+ const major = firefoxMajor(conn);
3201
+ if (major !== undefined && major < min) {
3202
+ const v = conn.capabilities.browserVersion;
3203
+ throw driverError("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
3204
+ }
3205
+ }
3206
+ async function armPostHocBodies(conn) {
3207
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
3208
+ return;
3209
+ try {
3210
+ requireFirefox(conn, "network.responseBodyPostHoc");
3211
+ } catch {
3212
+ return;
3213
+ }
3214
+ try {
3215
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
3216
+ } catch (e) {
3217
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
3218
+ }
3219
+ }
3155
3220
  function bumpEpoch(endpoint, conn) {
3156
3221
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
3157
3222
  connEndpoints.set(conn, endpoint);
@@ -3349,6 +3414,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
3349
3414
  }
3350
3415
  connections.set(endpoint, conn);
3351
3416
  bumpEpoch(endpoint, conn);
3417
+ await armPostHocBodies(conn);
3352
3418
  if (muxMode(attached) !== "off") {
3353
3419
  try {
3354
3420
  const mux = await startBidiMux(conn);
@@ -3564,7 +3630,35 @@ class BidiBrowserDriver {
3564
3630
  conn.release();
3565
3631
  }
3566
3632
  }
3633
+ async withBrowserConnection(fn) {
3634
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3635
+ try {
3636
+ return await fn(conn);
3637
+ } finally {
3638
+ conn.release();
3639
+ }
3640
+ }
3641
+ setDisposeHook(key, hook) {
3642
+ let hooks = disposeHooks.get(this.endpoint);
3643
+ if (!hooks) {
3644
+ hooks = new Map;
3645
+ disposeHooks.set(this.endpoint, hooks);
3646
+ }
3647
+ if (hook)
3648
+ hooks.set(key, hook);
3649
+ else
3650
+ hooks.delete(key);
3651
+ }
3567
3652
  async dispose() {
3653
+ const hooks = disposeHooks.get(this.endpoint);
3654
+ disposeHooks.delete(this.endpoint);
3655
+ const live = connections.get(this.endpoint);
3656
+ if (hooks && live) {
3657
+ for (const hook of hooks.values())
3658
+ await hook(live).catch(() => {
3659
+ return;
3660
+ });
3661
+ }
3568
3662
  for (const key of [...bidiBeaconScripts.keys()]) {
3569
3663
  if (key.startsWith(`${this.endpoint}:`))
3570
3664
  bidiBeaconScripts.delete(key);
@@ -3639,7 +3733,7 @@ async function hostFirefoxMux(endpoint, opts = {}) {
3639
3733
  function createFirefoxDriverForEndpoint(wsUrl, opts) {
3640
3734
  return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
3641
3735
  }
3642
- var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3736
+ var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3643
3737
  var init_driver2 = __esm(() => {
3644
3738
  init_driver();
3645
3739
  init_leases();
@@ -3694,13 +3788,25 @@ var init_driver2 = __esm(() => {
3694
3788
  MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
3695
3789
  BUTTON_CODES = { left: 0, middle: 1, right: 2 };
3696
3790
  ARM_SCROLL_SETTLE_WATCH_SOURCE = "function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});}";
3791
+ BIDI_CAPABILITY_MIN_FIREFOX = {
3792
+ "browser.downloads": 160,
3793
+ "browser.permissions": 160,
3794
+ "emulate.mediaFeatures": 160,
3795
+ "emulate.networkConditions": 160,
3796
+ "input.raw": 160,
3797
+ "input.modifierClick": 160,
3798
+ "network.responseBodyPostHoc": 160,
3799
+ "screenshot.scale": 160
3800
+ };
3801
+ POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
3697
3802
  BIDI_CAPABILITIES = new Set([
3698
3803
  "emulate.deviceMetrics",
3699
3804
  "screenshot.fullPage",
3700
3805
  "screenshot.element",
3701
3806
  "screenshot.renderSize",
3702
3807
  "network.intercept",
3703
- "locate.xpath"
3808
+ "locate.xpath",
3809
+ ...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
3704
3810
  ]);
3705
3811
  connections = new Map;
3706
3812
  slotHandles = new Map;
@@ -3709,6 +3815,7 @@ var init_driver2 = __esm(() => {
3709
3815
  connecting = new Map;
3710
3816
  sessionEpochs = new Map;
3711
3817
  connEndpoints = new WeakMap;
3818
+ disposeHooks = new Map;
3712
3819
  STALE_ID_HINT = " — the Firefox BiDi session was re-established after its previous holder went away, and Firefox " + "assigns new context ids per session — re-resolve the tab with list_pages (url:/title: selectors) " + "and claim it again";
3713
3820
  bidiBeaconScripts = new Map;
3714
3821
  BidiPageDriver = class BidiPageDriver {
@@ -3875,18 +3982,30 @@ var init_driver2 = __esm(() => {
3875
3982
  return { x, y };
3876
3983
  }
3877
3984
  async click(loc, opts) {
3878
- if (opts?.modifiers && opts.modifiers.length > 0) {
3879
- throw driverError("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
3880
- }
3985
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
3986
+ if (hasModifiers)
3987
+ requireFirefox(this.conn, "input.modifierClick");
3988
+ const keys = modifierKeyValues(opts?.modifiers);
3881
3989
  const ref = await resolveElementLocator(this.conn, this.contextId, loc);
3882
3990
  const { x, y } = await this.centerOf(ref);
3883
3991
  const button = BUTTON_CODES[opts?.button ?? "left"];
3884
3992
  const actions = [{ type: "pointerMove", x, y, duration: 0 }];
3885
3993
  for (let i = 0;i < (opts?.clickCount ?? 1); i++)
3886
3994
  actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
3887
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
3995
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
3888
3996
  return { x, y };
3889
3997
  }
3998
+ async dispatchMouse(event) {
3999
+ requireFirefox(this.conn, "input.raw");
4000
+ const keys = modifierKeyValues(event.modifiers);
4001
+ const button = BUTTON_CODES[event.button ?? "left"];
4002
+ const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
4003
+ if (event.action === "down")
4004
+ actions.push({ type: "pointerDown", button });
4005
+ else if (event.action === "up")
4006
+ actions.push({ type: "pointerUp", button });
4007
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
4008
+ }
3890
4009
  async scroll(anchor, opts) {
3891
4010
  const { x, y } = await this.resolveScrollPoint(anchor);
3892
4011
  const deltaX = Math.round(opts.deltaX ?? 0);
@@ -3995,11 +4114,23 @@ var init_driver2 = __esm(() => {
3995
4114
  }
3996
4115
  async screenshot(opts, _consumeBands) {
3997
4116
  const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
3998
- if (!renderSize)
4117
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
4118
+ if (!renderSize && scale === undefined)
3999
4119
  return this.capture(opts);
4120
+ if (scale !== undefined)
4121
+ requireFirefox(this.conn, "screenshot.scale");
4000
4122
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
4123
+ let dprOverride;
4124
+ if (scale !== undefined) {
4125
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
4126
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
4127
+ }
4001
4128
  try {
4002
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
4129
+ await this.conn.send("browsingContext.setViewport", {
4130
+ context: this.contextId,
4131
+ ...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
4132
+ ...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
4133
+ });
4003
4134
  } catch (e) {
4004
4135
  throw mapBidiError(e);
4005
4136
  }
@@ -4016,29 +4147,35 @@ var init_driver2 = __esm(() => {
4016
4147
  await this.conn.send("browsingContext.setViewport", {
4017
4148
  context: this.contextId,
4018
4149
  viewport: { width: previous.width, height: previous.height },
4019
- ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
4150
+ ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
4020
4151
  });
4021
4152
  } else {
4022
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
4153
+ await this.conn.send("browsingContext.setViewport", {
4154
+ context: this.contextId,
4155
+ ...renderSize ? { viewport: null } : {},
4156
+ ...scale !== undefined ? { devicePixelRatio: null } : {}
4157
+ });
4023
4158
  }
4024
4159
  } catch (e) {
4025
4160
  restoreError = e instanceof Error ? e.message : String(e);
4026
4161
  }
4027
4162
  if (!shot) {
4028
4163
  if (restoreError !== undefined && captureError instanceof Error) {
4029
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
4164
+ captureError.message = renderSize ? `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}` : `${captureError.message} (and restoring the device pixel ratio failed too, the tab may still be emulated at ratio ${dprOverride}: ${restoreError})`;
4030
4165
  }
4031
4166
  throw captureError;
4032
4167
  }
4168
+ if (!renderSize) {
4169
+ if (restoreError !== undefined)
4170
+ throw driverError("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
4171
+ return shot;
4172
+ }
4033
4173
  const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
4034
4174
  if (restoreError !== undefined)
4035
4175
  result.renderRestoreError = restoreError;
4036
4176
  return result;
4037
4177
  }
4038
4178
  async capture(opts) {
4039
- if (opts?.scale !== undefined && opts.scale !== 1) {
4040
- throw driverError("unsupported", `screenshot scale ${opts.scale} is not supported by this backend (WebDriver BiDi's ` + "browsingContext.captureScreenshot has no scale parameter). Call emulate with " + `deviceScaleFactor:${opts.scale} first and capture at scale 1, or use --browser chrome.`);
4041
- }
4042
4179
  if (opts?.tile === true) {
4043
4180
  throw driverError("unsupported", "screenshot tile:true is not supported by this backend: band tiling is declared only where the band " + "arithmetic has been measured against a real browser, and Firefox was not driven for it " + `(browsingContext.captureScreenshot's clip:{type:"box"} is the primitive it would ride, untested). ` + "Capture a smaller region or a single element, or use --browser chrome for a tiled capture.");
4044
4181
  }
@@ -4066,10 +4203,29 @@ var init_driver2 = __esm(() => {
4066
4203
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
4067
4204
  return;
4068
4205
  });
4206
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
4207
+ return;
4208
+ });
4209
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
4210
+ return;
4211
+ });
4069
4212
  await clearViewportRecord(this.browser.scheme, this.contextId);
4070
4213
  return { applied: [] };
4071
4214
  }
4072
4215
  const applied = [];
4216
+ if (opts.media != null && opts.media !== "") {
4217
+ throw driverError("unsupported", `emulate media "${opts.media}": WebDriver BiDi's emulation.setMediaFeaturesOverride takes media features (prefers-color-scheme, ...) but has no print/screen media-type override. Use mediaFeatures, or --browser chrome for media type emulation.`);
4218
+ }
4219
+ const net = opts.networkConditions;
4220
+ if (net != null) {
4221
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
4222
+ if (throttled) {
4223
+ throw driverError("unsupported", 'emulate networkConditions: Firefox only emulates offline (emulation.setNetworkConditions has the single type "offline"); latency and download/upload throughput throttling are not available. Pass only {offline:true|false}, or use --browser chrome.');
4224
+ }
4225
+ requireFirefox(this.conn, "emulate.networkConditions");
4226
+ }
4227
+ if (opts.mediaFeatures != null)
4228
+ requireFirefox(this.conn, "emulate.mediaFeatures");
4073
4229
  try {
4074
4230
  if (opts.width != null && opts.height != null) {
4075
4231
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
@@ -4084,6 +4240,21 @@ var init_driver2 = __esm(() => {
4084
4240
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
4085
4241
  applied.push("userAgent");
4086
4242
  }
4243
+ if (opts.mediaFeatures != null) {
4244
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
4245
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
4246
+ features: opts.mediaFeatures.length > 0 ? features : null,
4247
+ contexts: [this.contextId]
4248
+ });
4249
+ applied.push("mediaFeatures");
4250
+ }
4251
+ if (net != null) {
4252
+ await this.conn.send("emulation.setNetworkConditions", {
4253
+ networkConditions: net.offline ? { type: "offline" } : null,
4254
+ contexts: [this.contextId]
4255
+ });
4256
+ applied.push("networkConditions");
4257
+ }
4087
4258
  } catch (e) {
4088
4259
  throw mapBidiError(e);
4089
4260
  }
@@ -4218,12 +4389,25 @@ var init_driver2 = __esm(() => {
4218
4389
  };
4219
4390
  }
4220
4391
  async getResponseBody(requestId) {
4221
- if (!this.bodyCollector)
4222
- throw driverError("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
4392
+ let collector;
4223
4393
  try {
4224
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
4394
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
4395
+ } catch (e) {
4396
+ if (!this.bodyCollector) {
4397
+ throw driverError("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
4398
+ }
4399
+ collector = this.bodyCollector;
4400
+ }
4401
+ try {
4402
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
4225
4403
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
4226
4404
  } catch (e) {
4405
+ if (e instanceof BidiError && e.code === "unavailable network data") {
4406
+ throw driverError("page-error", `getResponseBody: the body of request ${requestId} was collected but has been evicted (Firefox keeps only a bounded recent window of response bodies, on the order of 100-200 MB). Re-issue the request, then read it sooner.`);
4407
+ }
4408
+ if (e instanceof BidiError && e.code === "no such network data") {
4409
+ throw driverError("page-error", `getResponseBody: no body is held for request ${requestId}. Firefox cannot say which of these applies: the id is wrong, the request started before this Firefox session did, the response was larger than ${POST_HOC_BODY_MAX_BYTES} bytes (not retained), or it has no body.`);
4410
+ }
4227
4411
  throw mapBidiError(e);
4228
4412
  }
4229
4413
  }