cdp-toolkit 3.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdp-toolkit",
3
- "version": "3.1.0",
3
+ "version": "3.3.0",
4
4
  "description": "A lightweight chrome-devtools-mcp alternative: an MCP server + CLI that drives the tabs you name, one target per call over one direct WebSocket, with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 48 tools (only 5 core tools listed by default, plus search_tools/call_tool to reach the rest) including built-in network mocking, a cookie group, tab leases with human-activity detection, real HTML5 drag-and-drop, raw mouse/scroll dispatch, downloads, permission grants, and tab-to-video screen recording so several agents can drive one browser without stealing each other's tabs or a human's. No Puppeteer, no all-target fan-out.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -89,6 +89,8 @@
89
89
  "extension:smoke": "bun run ./test/extension-smoke.ts",
90
90
  "focus:smoke": "bun run ./test/focus-emulation-smoke.ts",
91
91
  "extract:smoke": "bun run ./test/extract-smoke.ts",
92
+ "browser-ws:smoke": "bun run ./test/browser-ws-smoke.ts",
93
+ "browser-ws:wedge": "bun run ./test/browser-ws-wedge.ts",
92
94
  "gateway:smoke": "bun run ./test/gateway-smoke.ts"
93
95
  },
94
96
  "devDependencies": {
@@ -39,7 +39,7 @@ import {
39
39
  type DragDestination, type DragOptions,
40
40
  type SetCookieParams,
41
41
  type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel,
42
- type MouseButtonOptions, type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo,
42
+ type MouseButtonOptions, type RawMouseEvent, type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo,
43
43
  type ScreenshotOptions, type ScreenshotResult, type ScrollOptions, type SnapshotNode, type UidStability,
44
44
  type BandConsumer, type CaptureDelivery,
45
45
  } from "../driver.ts";
@@ -139,6 +139,10 @@ function mapBidiError(e: unknown): DriverError {
139
139
  if (code === "no such frame") return driverError("no-such-target", e.message);
140
140
  if (code === "invalid session id") return driverError("disconnected", e.message);
141
141
  if (code === "unsupported operation") return driverError("unsupported", e.message);
142
+ // A Firefox older than the one a capability was verified on answers a newer BiDi command with
143
+ // "unknown command". That is a capability gap, not a protocol fault: surface it as "unsupported"
144
+ // and name the version that has it (BIDI_CAPABILITY_MIN_FIREFOX).
145
+ if (code === "unknown command") return driverError("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
142
146
  if (!code && /timed out/i.test(e.message)) return driverError("timeout", e.message);
143
147
  if (!code && /(disposed|not open|connection closed)/i.test(e.message)) return driverError("disconnected", e.message);
144
148
  // NS_ERROR_FILE_ACCESS_DENIED from browsingContext.navigate means the browser process was
@@ -291,6 +295,47 @@ const KEY_VALUES: Record<string, string> = {
291
295
  };
292
296
  const MODIFIER_VALUES: Record<string, string> = { shift: "\uE008", control: "\uE009", ctrl: "\uE009", alt: "\uE00A", meta: "\uE03D", cmd: "\uE03D", command: "\uE03D" };
293
297
  const BUTTON_CODES: Record<"left" | "right" | "middle", number> = { left: 0, middle: 1, right: 2 };
298
+ const RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse";
299
+
300
+ /** Modifier names (Alt/Control/Meta/Shift, any case, plus the aliases pressKey takes) to WebDriver
301
+ * key values, in the order given. Unknown names are refused, never skipped. */
302
+ function modifierKeyValues(mods: readonly string[] | undefined): string[] {
303
+ const out: string[] = [];
304
+ for (const m of mods ?? []) {
305
+ const v = MODIFIER_VALUES[m.toLowerCase()];
306
+ if (v === undefined) throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
307
+ if (!out.includes(v)) out.push(v);
308
+ }
309
+ return out;
310
+ }
311
+
312
+ /**
313
+ * The input sources for pointer `actions` with `keys` held across them. With no keys it is the plain
314
+ * pointer source. With keys, a "key" source is TICK-ALIGNED with the pointer source in the same
315
+ * performActions call: [keyDown x k, pause x n, keyUp x k] against [pause x k, ...actions, pause x k],
316
+ * so every modifier is down before the first pointer action and released after the last. This is the
317
+ * shape measured on Firefox 160.0 (a lone key source or a misaligned one did not reach the click).
318
+ */
319
+ function modifierChord(pointerId: string, actions: InputPointerSourceAction[], keys: readonly string[]): InputSourceActions[] {
320
+ const pointer: InputPointerSourceAction[] = actions;
321
+ if (keys.length === 0) return [{ type: "pointer", id: pointerId, actions: pointer }];
322
+ const k = keys.length;
323
+ const pause = (): { type: "pause" } => ({ type: "pause" });
324
+ const keyActions: InputKeySourceAction[] = [
325
+ ...keys.map((v): InputKeySourceAction => ({ type: "keyDown", value: v })),
326
+ ...pointer.map(pause),
327
+ ...[...keys].reverse().map((v): InputKeySourceAction => ({ type: "keyUp", value: v })),
328
+ ];
329
+ const pointerActions: InputPointerSourceAction[] = [
330
+ ...Array.from({ length: k }, pause),
331
+ ...pointer,
332
+ ...Array.from({ length: k }, pause),
333
+ ];
334
+ return [
335
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
336
+ { type: "pointer", id: pointerId, actions: pointerActions },
337
+ ];
338
+ }
294
339
 
295
340
  /** Same scroll-settle technique as cdp/driver.ts's ARM_SCROLL_SETTLE_WATCH / awaitScrollSettle,
296
341
  * see that file's doc comment for the full rationale: a capture-phase 'scroll' listener on
@@ -303,8 +348,8 @@ const AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}
303
348
  /**
304
349
  * Firefox 153 capabilities. Only what was empirically verified is declared: emulate.deviceMetrics
305
350
  * (browsingContext.setViewport) and the userAgent path (universal, no capability token) both work.
306
- * emulate.mediaFeatures, emulate.cpuThrottling, emulate.networkConditions, trace.performance,
307
- * heap.snapshot, audit.lighthouse, input.insertTextAtomic and snapshot.accessibilityTree are all
351
+ * emulate.cpuThrottling, trace.performance (emulate.mediaFeatures and emulate.networkConditions were
352
+ * added later at Firefox 160, see BIDI_CAPABILITY_MIN_FIREFOX), heap.snapshot, audit.lighthouse, input.insertTextAtomic and snapshot.accessibilityTree are all
308
353
  * deliberately absent, several because Firefox 153 does not implement the underlying BiDi command
309
354
  * at all (see protocol.ts's "Firefox 153: not implemented" tags), the rest because this driver has
310
355
  * no accessibility-tree source or CPU-multiplier primitive to offer. locate.xpath rides
@@ -323,8 +368,13 @@ const AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}
323
368
  * screenshot.renderSize IS declared, and it is the one screenshot capability here that is not a
324
369
  * Chrome-only gap: it rides browsingContext.setViewport, the very command emulate.deviceMetrics
325
370
  * above already rides, applied for one capture and undone afterwards. Refusing it would be dishonest
326
- * in the opposite direction — claiming a missing primitive this driver demonstrably has. Contrast
327
- * screenshot.scale, absent because captureScreenshot genuinely has no scale parameter.
371
+ * in the opposite direction — claiming a missing primitive this driver demonstrably has.
372
+ * screenshot.scale (Firefox >= 160, BIDI_CAPABILITY_MIN_FIREFOX) is the same trick one step on:
373
+ * captureScreenshot itself still has no scale parameter, but setViewport({devicePixelRatio}) with NO
374
+ * viewport key multiplies the capture and leaves the layout viewport alone (measured on 160.0:
375
+ * a 1366x683 capture became 2732x1366 at ratio 2, innerWidth/innerHeight unchanged), so scale rides
376
+ * that for one capture and undoes it, like renderSize. network.responseBodyPostHoc (Firefox >= 160)
377
+ * is armed per SESSION, see armPostHocBodies.
328
378
  * screenshot.tile stays undeclared, but no longer for an unmeasured reason: live-fired against
329
379
  * Firefox 153.0.3, a 20,000px-tall page captured with take_screenshot --fullPage true came back
330
380
  * as a single 1366x20000 PNG at scale 1, verified complete top-to-bottom — no clip, no bands.
@@ -333,8 +383,108 @@ const AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}
333
383
  * no gap here to close. It stays undeclared because it would advertise a forced-tiling primitive
334
384
  * this backend has never needed, not because band-tiling behavior is untested.
335
385
  */
386
+ /**
387
+ * Capabilities verified on a Firefox NEWER than 153, keyed to the first major version they were
388
+ * measured on. They are declared in BIDI_CAPABILITIES (tool listing is static: capabilities.ts reads
389
+ * this set without opening a socket), and each method that rides one calls requireFirefox(conn,
390
+ * token) before touching browser state, so an older Firefox gets an "unsupported" DriverError that
391
+ * names the version instead of a half-applied change or a raw "unknown command".
392
+ *
393
+ * input.raw (dispatch_mouse) and input.modifierClick (click with modifiers), measured on headless
394
+ * Firefox 160.0: a pointerDown issued in one input.performActions call stays held for a pointerUp in
395
+ * a LATER call that reuses the same pointer source id (page saw mousedown, then mouseup+click), so
396
+ * one raw event per call works; and a modifier chord works when a "key" source (keyDown of the
397
+ * modifier, pauses, keyUp) is TICK-ALIGNED with the pointer source in ONE call (page saw
398
+ * shiftKey/ctrlKey/altKey/metaKey on the click). input.html5Drag is NOT declared: on 160.0 a
399
+ * pointer drag starts a real drag session (dragstart, dragenter, dragover reach the page) but the
400
+ * session never completes under BiDi input (no drop, no dragend, no mouseup, even after a pause or
401
+ * a second performActions call), so a drag cannot be delivered; see test/bidi-input-ff160.test.ts.
402
+ *
403
+ * browser.downloads (160): browser.setDownloadBehavior {type:"allowed", destinationFolder} plus the
404
+ * browsingContext.downloadWillBegin/downloadEnd events, measured on headless Firefox 160.0 — the
405
+ * file landed in the folder, downloadEnd carried status "complete" and its filepath, and
406
+ * `downloadBehavior: null` put a later download back in the profile's own download dir. Drives
407
+ * wait_for_download through ../bidi-browser-tools.ts.
408
+ * browser.permissions (160): permissions.setPermission {descriptor, state, origin}, measured on
409
+ * Firefox 160.0 — navigator.permissions.query followed granted/denied/prompt. Drives
410
+ * grant_permissions through ../bidi-browser-tools.ts, which also documents the Chrome asymmetries.
411
+ */
412
+ export const BIDI_CAPABILITY_MIN_FIREFOX: Readonly<Partial<Record<Capability, number>>> = {
413
+ "browser.downloads": 160,
414
+ "browser.permissions": 160,
415
+ "emulate.mediaFeatures": 160,
416
+ "emulate.networkConditions": 160,
417
+ "input.raw": 160,
418
+ "input.modifierClick": 160,
419
+ "network.responseBodyPostHoc": 160,
420
+ "screenshot.scale": 160,
421
+ };
422
+
423
+ /** Firefox major version from session.new's capabilities.browserVersion (e.g. "160.0" -> 160).
424
+ * undefined when the session reported none (a stub connection in tests): treated as new enough. */
425
+ export function firefoxMajor(conn: { capabilities: unknown }): number | undefined {
426
+ const v = (conn.capabilities as { browserVersion?: unknown } | undefined)?.browserVersion;
427
+ if (typeof v !== "string") return undefined;
428
+ const major = Number.parseInt(v, 10);
429
+ return Number.isFinite(major) ? major : undefined;
430
+ }
431
+
432
+ /** Throw "unsupported" when `token` needs a newer Firefox than the one this session is on. */
433
+ export function requireFirefox(conn: { capabilities: unknown }, token: Capability): void {
434
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
435
+ if (min === undefined) return;
436
+ const major = firefoxMajor(conn);
437
+ if (major !== undefined && major < min) {
438
+ const v = (conn.capabilities as { browserVersion?: string }).browserVersion;
439
+ throw driverError("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Largest single response body the session-wide collector keeps, in bytes. maxEncodedDataSize is a
445
+ * PER-RESPONSE cap (measured on Firefox 160.0: cap 10 dropped a 20-byte body; cap 2,000,000 kept every
446
+ * 1 MB body). A larger body is simply not retained and reads back as "no such network data". The
447
+ * TOTAL is Firefox's own and not ours to set: with a 2 MB cap or a 20 MB cap alike, 260 sequential
448
+ * 1 MB responses left the oldest ~60 answering "unavailable network data" (evicted) and the newest
449
+ * ~160 readable, so the browser's own budget is on the order of 100-200 MB regardless of this number
450
+ * (no pref for it was found; attach mode gets the browser default). This number only bounds how
451
+ * much of that budget one response can take.
452
+ */
453
+ const POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
454
+
455
+ /**
456
+ * Arm the ONE session-wide response collector that makes network.responseBodyPostHoc true.
457
+ *
458
+ * WHY HERE. network.addDataCollector is scoped to the BiDi SESSION, and it only retains bodies of
459
+ * requests that start after it exists. This toolkit shares ONE real session per browser (the holder
460
+ * path of getConnection, which the mux daemon reaches through hostFirefoxMux), so the place that
461
+ * covers every client, every tab and every request since the session began is the moment that real
462
+ * session is created: no `contexts`/`userContexts`, so tabs opened later are covered too. A JOINED
463
+ * connection must NOT arm another: its commands are forwarded to the same upstream session and a
464
+ * second collector would double-retain every body. Best-effort and silent on a Firefox older than
465
+ * 160 (the capability is version-gated, see requireFirefox): a failed arm leaves reads answering
466
+ * "no such network data" rather than failing the connection the caller asked for.
467
+ */
468
+ async function armPostHocBodies(conn: BidiConnection): Promise<void> {
469
+ // Opt-out for an everyday Firefox where retaining response bodies is unwanted. With it off, a
470
+ // body is readable only after startBodyCapture, and an unarmed read is the "no such network
471
+ // data" DriverError, the same as on a Firefox older than 160.
472
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off") return;
473
+ try {
474
+ requireFirefox(conn, "network.responseBodyPostHoc");
475
+ } catch {
476
+ return;
477
+ }
478
+ try {
479
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
480
+ } catch (e) {
481
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
482
+ }
483
+ }
484
+
336
485
  const BIDI_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([
337
486
  "emulate.deviceMetrics", "screenshot.fullPage", "screenshot.element", "screenshot.renderSize", "network.intercept", "locate.xpath",
487
+ ...(Object.keys(BIDI_CAPABILITY_MIN_FIREFOX) as Capability[]),
338
488
  ]);
339
489
 
340
490
  /* --------------------------------- module-scope session memoization --------------------------------- */
@@ -381,6 +531,9 @@ const connecting = new Map<string, Promise<BidiConnection>>();
381
531
  const sessionEpochs = new Map<string, number>();
382
532
  // Reverse lookup so resolveContext (which only has a BidiConnection) can find its endpoint's epoch.
383
533
  const connEndpoints = new WeakMap<BidiConnection, string>();
534
+ // Per-endpoint cleanup BidiBrowserDriver.dispose() runs on the live connection before session.end
535
+ // (see setDisposeHook). Keyed by endpoint, then by the registering feature.
536
+ const disposeHooks = new Map<string, Map<string, (conn: BidiConnection) => Promise<void>>>();
384
537
 
385
538
  function bumpEpoch(endpoint: string, conn: BidiConnection): void {
386
539
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
@@ -718,6 +871,8 @@ async function getConnection(endpoint: string, timeoutMs?: number, attached = fa
718
871
  }
719
872
  connections.set(endpoint, conn);
720
873
  bumpEpoch(endpoint, conn);
874
+ // We own the real session: arm the post-hoc body collector on it (never on a joined one).
875
+ await armPostHocBodies(conn);
721
876
  // We are the HOLDER. Front our one real session with a loopback BiDi mux and advertise it in
722
877
  // the slot record, so any other process that wants this Firefox JOINS us instead of being told
723
878
  // the slot is busy. Strictly additive and strictly best-effort: any failure here leaves a
@@ -1058,26 +1213,41 @@ class BidiPageDriver implements PageDriver {
1058
1213
  await this.performActions([{ type: "pointer", id: "cdp-mouse", actions: [{ type: "pointerMove", x, y, duration: 0 }] }]);
1059
1214
  return { x, y };
1060
1215
  }
1061
- // modifiers is new in 1.8.0 (Track P1). Chrome expresses it as a bitmask on the same
1062
- // mousePressed/mouseReleased events (cdp/driver.ts's inputModifierBits); WebDriver BiDi has no
1063
- // equivalent field on a pointerDown/pointerUp action; a modifier chord instead requires a SECOND
1064
- // "key" input source ticked in lockstep with the pointer source across the same performActions
1065
- // call, which the spec explicitly permits skipping ("throw a clear error when modifiers are
1066
- // passed on firefox" — see cdp-toolkit's 1.8.0 spec, Track P1 §3) and this driver was not
1067
- // verified against real Firefox for this pass, so it throws "unsupported" rather than guess at
1068
- // untested tick-synchronization semantics.
1216
+ // modifiers (1.8.0 Track P1). Chrome expresses it as a bitmask on the same mousePressed/mouseReleased
1217
+ // events (cdp/driver.ts's inputModifierBits); BiDi has no such field on pointerDown/pointerUp, so a
1218
+ // chord is a SECOND "key" source ticked in lockstep with the pointer source inside ONE
1219
+ // performActions call (modifierChord below). Measured on Firefox 160.0 (shift+click saw
1220
+ // shiftKey=true); an older Firefox is refused by requireFirefox("input.modifierClick").
1069
1221
  async click(loc: ElementLocator, opts?: MouseButtonOptions): Promise<{ x: number; y: number }> {
1070
- if (opts?.modifiers && opts.modifiers.length > 0) {
1071
- throw driverError("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
1072
- }
1222
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
1223
+ if (hasModifiers) requireFirefox(this.conn, "input.modifierClick");
1224
+ const keys = modifierKeyValues(opts?.modifiers);
1073
1225
  const ref = await resolveElementLocator(this.conn, this.contextId, loc);
1074
1226
  const { x, y } = await this.centerOf(ref);
1075
1227
  const button = BUTTON_CODES[opts?.button ?? "left"];
1076
1228
  const actions: InputPointerSourceAction[] = [{ type: "pointerMove", x, y, duration: 0 }];
1077
1229
  for (let i = 0; i < (opts?.clickCount ?? 1); i++) actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
1078
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
1230
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
1079
1231
  return { x, y };
1080
1232
  }
1233
+ // dispatch_mouse on Firefox (capability "input.raw", 160+): ONE raw pointer event per call. BiDi's
1234
+ // pointer source is a virtual device with session-lifetime state, so a "down" in one call stays held
1235
+ // for an "up" in a later call as long as the source id is the same: RAW_MOUSE_SOURCE_ID is a constant
1236
+ // for that reason (and distinct from click/drag's "cdp-mouse", which always finish their own press).
1237
+ // The state lives in the shared BiDi session (bidi/mux.ts), not in this driver instance, so it
1238
+ // survives the per-tool-call driver acquisition. Unlike CDP, BiDi has no coordinate-less event: every
1239
+ // action is a pointerMove to (x,y) first, so a "down"/"up" also emits a mousemove if the pointer
1240
+ // was elsewhere. clickCount is not a BiDi field (the browser derives click counts from timing), so
1241
+ // it is ignored here.
1242
+ async dispatchMouse(event: RawMouseEvent): Promise<void> {
1243
+ requireFirefox(this.conn, "input.raw");
1244
+ const keys = modifierKeyValues(event.modifiers);
1245
+ const button = BUTTON_CODES[event.button ?? "left"];
1246
+ const actions: InputPointerSourceAction[] = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
1247
+ if (event.action === "down") actions.push({ type: "pointerDown", button });
1248
+ else if (event.action === "up") actions.push({ type: "pointerUp", button });
1249
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
1250
+ }
1081
1251
  // 1.8.0 Track P1: BiDi's "wheel" input source (a distinct source type from "pointer"/"key")
1082
1252
  // carries x/y/deltaX/deltaY directly on its one "scroll" action — no tick synchronization with
1083
1253
  // another source needed, unlike click's modifiers above, which is what makes this tractable.
@@ -1245,13 +1415,28 @@ class BidiPageDriver implements PageDriver {
1245
1415
  opts?.renderWidth !== undefined && opts?.renderHeight !== undefined
1246
1416
  ? { width: opts.renderWidth, height: opts.renderHeight }
1247
1417
  : undefined;
1248
- if (!renderSize) return this.capture(opts);
1418
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
1419
+ if (!renderSize && scale === undefined) return this.capture(opts);
1420
+ if (scale !== undefined) requireFirefox(this.conn, "screenshot.scale");
1249
1421
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
1422
+ // BiDi's devicePixelRatio REPLACES the page's ratio, where Chrome's clip.scale MULTIPLIES it, so
1423
+ // a scale of 2 on a ratio-2 display must send 4 or it would be a silent no-op. The base is the
1424
+ // ratio this toolkit last emulated, else the live window.devicePixelRatio.
1425
+ let dprOverride: number | undefined;
1426
+ if (scale !== undefined) {
1427
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
1428
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
1429
+ }
1250
1430
  try {
1251
- // devicePixelRatio is deliberately not sent: this changes the render SIZE, and omitting the
1252
- // field leaves whatever ratio an earlier emulate set in place (the CDP path inherits it the
1253
- // same way).
1254
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
1431
+ // With a render size only, devicePixelRatio is deliberately not sent: that changes the render
1432
+ // SIZE, and omitting the field leaves whatever ratio an earlier emulate set in place (the CDP
1433
+ // path inherits it the same way). With a scale, the ratio is sent and, when no render size is
1434
+ // asked for, so is no viewport at all (measured: the layout viewport is left as it was).
1435
+ await this.conn.send("browsingContext.setViewport", {
1436
+ context: this.contextId,
1437
+ ...(renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {}),
1438
+ ...(dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}),
1439
+ });
1255
1440
  } catch (e) {
1256
1441
  throw mapBidiError(e);
1257
1442
  }
@@ -1270,20 +1455,33 @@ class BidiPageDriver implements PageDriver {
1270
1455
  await this.conn.send("browsingContext.setViewport", {
1271
1456
  context: this.contextId,
1272
1457
  viewport: { width: previous.width, height: previous.height },
1273
- ...(previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}),
1458
+ // A scaled capture changed the ratio, so it is always put back: to the recorded one, or to
1459
+ // null (the real display's) when no emulated ratio was ever recorded.
1460
+ ...(previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}),
1274
1461
  });
1275
1462
  } else {
1276
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
1463
+ await this.conn.send("browsingContext.setViewport", {
1464
+ context: this.contextId,
1465
+ ...(renderSize ? { viewport: null } : {}),
1466
+ ...(scale !== undefined ? { devicePixelRatio: null } : {}),
1467
+ });
1277
1468
  }
1278
1469
  } catch (e) {
1279
1470
  restoreError = e instanceof Error ? e.message : String(e);
1280
1471
  }
1281
1472
  if (!shot) {
1282
1473
  if (restoreError !== undefined && captureError instanceof Error) {
1283
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
1474
+ captureError.message = renderSize
1475
+ ? `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`
1476
+ : `${captureError.message} (and restoring the device pixel ratio failed too, the tab may still be emulated at ratio ${dprOverride}: ${restoreError})`;
1284
1477
  }
1285
1478
  throw captureError;
1286
1479
  }
1480
+ if (!renderSize) {
1481
+ // Scale-only capture: no render size to report, but a failed restore is still never swallowed.
1482
+ if (restoreError !== undefined) throw driverError("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
1483
+ return shot;
1484
+ }
1287
1485
  const result: ScreenshotResult = { ...shot, renderSize, renderRestored: restoreError === undefined };
1288
1486
  if (restoreError !== undefined) result.renderRestoreError = restoreError;
1289
1487
  return result;
@@ -1291,18 +1489,8 @@ class BidiPageDriver implements PageDriver {
1291
1489
  /** The capture itself, with no viewport emulation of its own. Split out so screenshot()'s restore
1292
1490
  * wraps EVERY way this can fail, the throwing paths included. */
1293
1491
  private async capture(opts?: ScreenshotOptions): Promise<ScreenshotResult> {
1294
- // ADR-001 param-level gap, same shape as drag's mode:"html5" (see resolveDragMode in
1295
- // ../shared-tools.ts): browsingContext.captureScreenshot has NO scale parameter — its only
1296
- // knobs are origin, format and clip — so a scale asked for here is refused outright rather
1297
- // than silently captured at 1x, which would hand back an image the caller never asked for.
1298
- if (opts?.scale !== undefined && opts.scale !== 1) {
1299
- throw driverError(
1300
- "unsupported",
1301
- `screenshot scale ${opts.scale} is not supported by this backend (WebDriver BiDi's ` +
1302
- "browsingContext.captureScreenshot has no scale parameter). Call emulate with " +
1303
- `deviceScaleFactor:${opts.scale} first and capture at scale 1, or use --browser chrome.`,
1304
- );
1305
- }
1492
+ // `scale` never reaches here: screenshot() applies it as a one-capture devicePixelRatio
1493
+ // override (captureScreenshot itself still has no scale parameter) and puts it back.
1306
1494
  // Same ADR-001 param-level shape, but now a measured non-gap rather than an unmeasured one.
1307
1495
  // Live-fired against Firefox 153.0.3: a 20,000px-tall page captured with take_screenshot
1308
1496
  // --fullPage true came back as one 1366x20000 PNG at scale 1, verified complete top-to-bottom,
@@ -1334,9 +1522,10 @@ class BidiPageDriver implements PageDriver {
1334
1522
  throw mapBidiError(e);
1335
1523
  }
1336
1524
  }
1337
- // Only userAgent and width/height/deviceScaleFactor are applied: mediaFeatures, cpuThrottling
1338
- // and networkConditions are not in BIDI_CAPABILITIES (see its comment) and this method never
1339
- // claims them. `mobile` has no BiDi viewport-emulation equivalent and is silently ignored,
1525
+ // Applied: userAgent, width/height/deviceScaleFactor, and (Firefox 160+, BIDI_CAPABILITY_MIN_FIREFOX)
1526
+ // mediaFeatures and offline-only networkConditions. cpuThrottling is not in BIDI_CAPABILITIES and
1527
+ // this method never claims it; a media TYPE and a throttled network are refused as "unsupported".
1528
+ // `mobile` has no BiDi viewport-emulation equivalent and is silently ignored,
1340
1529
  // a real parity gap noted in the footer rather than smoothed over.
1341
1530
  async emulate(opts: EmulationOptions): Promise<{ applied: string[] }> {
1342
1531
  if (opts.clearOverrides) {
@@ -1356,11 +1545,29 @@ class BidiPageDriver implements PageDriver {
1356
1545
  // no "set-then-clear" workaround needed; left as it was.
1357
1546
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: null, contexts: [this.contextId] }).catch(() => undefined);
1358
1547
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => undefined);
1548
+ // Best-effort like the two above: a Firefox older than 160 has neither command, and then
1549
+ // there is nothing of ours to clear. The overrides are session-scoped (one shared BiDi
1550
+ // session per browser, see mux.ts), so this clears what ANY driver instance on this browser set.
1551
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => undefined);
1552
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => undefined);
1359
1553
  // No override of ours left to put back: a render-size capture should restore to null.
1360
1554
  await clearViewportRecord(this.browser.scheme, this.contextId);
1361
1555
  return { applied: [] };
1362
1556
  }
1363
1557
  const applied: string[] = [];
1558
+ // Refusals first, before ANY browser state changes, so a refused call never half-applies.
1559
+ if (opts.media != null && opts.media !== "") {
1560
+ 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.`);
1561
+ }
1562
+ const net = opts.networkConditions;
1563
+ if (net != null) {
1564
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
1565
+ if (throttled) {
1566
+ 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.");
1567
+ }
1568
+ requireFirefox(this.conn, "emulate.networkConditions");
1569
+ }
1570
+ if (opts.mediaFeatures != null) requireFirefox(this.conn, "emulate.mediaFeatures");
1364
1571
  try {
1365
1572
  if (opts.width != null && opts.height != null) {
1366
1573
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...(opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {}) });
@@ -1377,6 +1584,22 @@ class BidiPageDriver implements PageDriver {
1377
1584
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
1378
1585
  applied.push("userAgent");
1379
1586
  }
1587
+ if (opts.mediaFeatures != null) {
1588
+ // BiDi takes an OBJECT {name: value}; null resets (an empty list mirrors Chrome's "clear").
1589
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
1590
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
1591
+ features: opts.mediaFeatures.length > 0 ? features : null,
1592
+ contexts: [this.contextId],
1593
+ });
1594
+ applied.push("mediaFeatures");
1595
+ }
1596
+ if (net != null) {
1597
+ await this.conn.send("emulation.setNetworkConditions", {
1598
+ networkConditions: net.offline ? { type: "offline" } : null,
1599
+ contexts: [this.contextId],
1600
+ });
1601
+ applied.push("networkConditions");
1602
+ }
1380
1603
  } catch (e) {
1381
1604
  throw mapBidiError(e);
1382
1605
  }
@@ -1559,11 +1782,29 @@ class BidiPageDriver implements PageDriver {
1559
1782
  };
1560
1783
  }
1561
1784
  async getResponseBody(requestId: string): Promise<{ body: string; base64Encoded: boolean }> {
1562
- if (!this.bodyCollector) throw driverError("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
1785
+ // On Firefox >= 160 the session-wide collector (armPostHocBodies) already holds the body, so no
1786
+ // collector id is passed and startBodyCapture is optional. An older Firefox has no such collector:
1787
+ // only a body armed through this page's own startBodyCapture is readable there.
1788
+ let collector: string | undefined;
1563
1789
  try {
1564
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
1790
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
1791
+ } catch (e) {
1792
+ if (!this.bodyCollector) {
1793
+ throw driverError("unsupported", `${(e as Error).message} Call startBodyCapture() before the request to read its body on this Firefox.`);
1794
+ }
1795
+ collector = this.bodyCollector;
1796
+ }
1797
+ try {
1798
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...(collector ? { collector } : {}) });
1565
1799
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
1566
1800
  } catch (e) {
1801
+ // Two distinct BiDi answers, measured on Firefox 160.0. Never surface either as an empty body.
1802
+ if (e instanceof BidiError && e.code === "unavailable network data") {
1803
+ 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.`);
1804
+ }
1805
+ if (e instanceof BidiError && e.code === "no such network data") {
1806
+ 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.`);
1807
+ }
1567
1808
  throw mapBidiError(e);
1568
1809
  }
1569
1810
  }
@@ -1742,7 +1983,43 @@ class BidiBrowserDriver implements BrowserDriver {
1742
1983
  }
1743
1984
  }
1744
1985
 
1986
+ /**
1987
+ * Run `fn` against this endpoint's live BiDi connection, for BROWSER-scoped commands that have
1988
+ * no page to hang off (browser.setDownloadBehavior, permissions.setPermission). Retains and
1989
+ * releases a holder exactly like page() does. NOT a lease gate: callers resolve their target
1990
+ * through page() first (resolveContext is the gate), then come here for the browser-wide work.
1991
+ */
1992
+ async withBrowserConnection<T>(fn: (conn: BidiConnection) => Promise<T>): Promise<T> {
1993
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
1994
+ try {
1995
+ return await fn(conn);
1996
+ } finally {
1997
+ conn.release();
1998
+ }
1999
+ }
2000
+
2001
+ /**
2002
+ * Register cleanup that must run against the LIVE connection before dispose() ends the session —
2003
+ * browser state this process changed that would otherwise outlive it (a download redirect left
2004
+ * armed, a permission grant that Firefox persists in the profile). Keyed by `key` so re-registering
2005
+ * replaces rather than stacks. Hooks are best-effort and run once.
2006
+ */
2007
+ setDisposeHook(key: string, hook: ((conn: BidiConnection) => Promise<void>) | undefined): void {
2008
+ let hooks = disposeHooks.get(this.endpoint);
2009
+ if (!hooks) { hooks = new Map(); disposeHooks.set(this.endpoint, hooks); }
2010
+ if (hook) hooks.set(key, hook);
2011
+ else hooks.delete(key);
2012
+ }
2013
+
1745
2014
  async dispose(): Promise<void> {
2015
+ // Browser-state restores first, while the connection (and, for a mux holder, every joiner's
2016
+ // shared session) is still alive.
2017
+ const hooks = disposeHooks.get(this.endpoint);
2018
+ disposeHooks.delete(this.endpoint);
2019
+ const live = connections.get(this.endpoint);
2020
+ if (hooks && live) {
2021
+ for (const hook of hooks.values()) await hook(live).catch(() => undefined);
2022
+ }
1746
2023
  for (const key of [...bidiBeaconScripts.keys()]) {
1747
2024
  if (key.startsWith(`${this.endpoint}:`)) bidiBeaconScripts.delete(key);
1748
2025
  }
@@ -1870,7 +2147,9 @@ export { BidiBrowserDriver, BidiPageDriver, resolveContext };
1870
2147
  * (create, close, activate, getTree, navigate, reload, locateNodes, captureScreenshot, setViewport,
1871
2148
  * handleUserPrompt); script (evaluate, callFunction); input (performActions, setFiles); network
1872
2149
  * (addDataCollector, removeDataCollector, getData, addIntercept, removeIntercept, continueRequest,
1873
- * provideResponse, failRequest, beforeRequestSent event); emulation (setUserAgentOverride). Events
2150
+ * provideResponse, failRequest, beforeRequestSent event); emulation (setUserAgentOverride);
2151
+ * browser (setDownloadBehavior) and permissions (setPermission), both via withBrowserConnection
2152
+ * from ../bidi-browser-tools.ts. Events
1874
2153
  * subscribed via BidiConnection.on/waitFor: browsingContext.navigationCommitted/userPromptOpened/
1875
2154
  * contextDestroyed, log.entryAdded, network.beforeRequestSent/responseCompleted.
1876
2155
  *
@@ -1900,10 +2179,14 @@ export { BidiBrowserDriver, BidiPageDriver, resolveContext };
1900
2179
  * this one. Neither insertText route synthesizes a <br> or a block break.
1901
2180
  * - trace.performance / heap.snapshot / audit.lighthouse: not declared, Chrome-only domains with
1902
2181
  * no BiDi equivalent at all.
1903
- * - screenshot.scale: not declared. browsingContext.captureScreenshot's parameters are context,
1904
- * origin, format and clip — no scale anywhere, and its clip types (box/element) carry no
1905
- * multiplier either. A `scale` other than 1 is a refusal in screenshot() (ADR-001 param-level
1906
- * gap, like drag's html5 mode), pointing at emulate's deviceScaleFactor as the real workaround.
2182
+ * - screenshot.scale: DECLARED for Firefox >= 160 (BIDI_CAPABILITY_MIN_FIREFOX; requireFirefox
2183
+ * gives an older one "unsupported"). browsingContext.captureScreenshot still has no scale
2184
+ * parameter, so screenshot() sets browsingContext.setViewport({devicePixelRatio: base * scale})
2185
+ * for the one capture (no viewport key: the layout viewport is untouched) and puts the ratio back
2186
+ * (the recorded emulate ratio, else null). base is the recorded or live window.devicePixelRatio
2187
+ * because BiDi's ratio replaces where Chrome's clip.scale multiplies. Measured on 160.0 headless:
2188
+ * 1366x683 at scale 1, 2732x1366 at ratio 2, ratio back to 1 after setViewport({devicePixelRatio:
2189
+ * null}). Limit: a ratio emulated by ANOTHER process with no viewport record is restored to null.
1907
2190
  * - screenshot.renderSize: DECLARED, and the one screenshot capability here that is not a gap. It
1908
2191
  * rides browsingContext.setViewport — the same command emulate.deviceMetrics already uses —
1909
2192
  * applied for one capture and restored to the tracked viewport (or `viewport:null`) afterwards.
@@ -1920,13 +2203,22 @@ export { BidiBrowserDriver, BidiPageDriver, resolveContext };
1920
2203
  * tile:true) has nothing to do here. `tile:true` is still a refusal in screenshot() naming
1921
2204
  * --browser chrome; the default (auto) still never bands on this backend — both unchanged, now
1922
2205
  * for a documented reason instead of an untested one.
1923
- * - emulate.mediaFeatures / emulate.cpuThrottling / emulate.networkConditions: not declared.
1924
- * Firefox 153 does not implement setMediaFeaturesOverride; CPU throttling and network condition
1925
- * emulation have no verified-working BiDi path in this environment, so emulate() never claims
1926
- * them and silently ignores the `mobile` flag (no BiDi mobile-viewport emulation exists either).
1927
- * - network.responseBodyPostHoc: not declared, deliberately, mirroring cdp/driver.ts's own call.
1928
- * network.addDataCollector must be armed before the request; there is no reading a body for a
1929
- * request that predates arming, so an honest capability set omits it exactly as Chrome's does.
2206
+ * - emulate.mediaFeatures / emulate.networkConditions: declared via BIDI_CAPABILITY_MIN_FIREFOX
2207
+ * at 160 (measured on 160.0: emulation.setMediaFeaturesOverride takes features as an OBJECT,
2208
+ * features:null resets; setNetworkConditions has only {type:"offline"}, null resets). A media
2209
+ * TYPE (print/screen) and any latency/throughput throttle are refused "unsupported", never
2210
+ * ignored. emulate.cpuThrottling: not declared; CPU throttling has no BiDi path, so emulate()
2211
+ * never claims it and silently ignores the `mobile` flag (no BiDi mobile-viewport emulation exists either).
2212
+ * - network.responseBodyPostHoc: DECLARED for Firefox >= 160. A collector is session-scoped and
2213
+ * retains only requests that start after it, so armPostHocBodies adds ONE (all contexts, 2 MB per
2214
+ * response) the moment the real session is created, in the holder path of getConnection (which
2215
+ * the mux daemon also runs); joined connections never arm. A body the page fetched before any
2216
+ * tool call is then readable by request id (getData, no collector id) as text or base64. Limits:
2217
+ * Firefox's own total budget evicts the oldest bodies ("unavailable network data" -> clear
2218
+ * DriverError), over-cap/unknown ids read "no such network data" (also a DriverError, never empty
2219
+ * text), and the request id must come from somewhere (a network.response event, or
2220
+ * get_network_request): a request that predates this process's own subscription has no id here.
2221
+ * Chrome still does not declare it (cdp/driver.ts).
1930
2222
  * - NavigateResult.waitedFor never returns "timeout": BiDi's navigate/reload block server-side on
1931
2223
  * `wait`, so an unreachable milestone is a thrown "timeout" DriverError, not CDP's soft return.
1932
2224
  * - LifetimeModel's "MUST re-establish itself transparently if the transport dies" is NOT