cdp-toolkit 3.2.0 → 3.4.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/dist/mcp.js CHANGED
@@ -687,7 +687,7 @@ async function originIndex(backend, liveIds) {
687
687
  return index;
688
688
  }
689
689
  async function newTrackedPage(driver, backend, opts = {}) {
690
- const page = await driver.newPage(opts.url);
690
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
691
691
  await recordOrigin(backend, page.id, { label: opts.label });
692
692
  return page;
693
693
  }
@@ -1297,6 +1297,53 @@ var init_client = __esm(() => {
1297
1297
  knownTransports = new Map;
1298
1298
  });
1299
1299
 
1300
+ // src/frontApp.ts
1301
+ import { execFile } from "node:child_process";
1302
+ function run(cmd, args) {
1303
+ return new Promise((resolve) => {
1304
+ execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
1305
+ });
1306
+ }
1307
+ function restoreFrontAppEnabled(platform = process.platform) {
1308
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
1309
+ }
1310
+ async function keepFrontApp(fn, opts = {}) {
1311
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
1312
+ if (!enabled)
1313
+ return fn();
1314
+ const ops = opts.ops ?? macFrontAppOps;
1315
+ const before = await ops.front().catch(() => null);
1316
+ const result = await fn();
1317
+ if (before === null)
1318
+ return result;
1319
+ const fix = async () => {
1320
+ const now = await ops.front().catch(() => null);
1321
+ if (now !== null && now !== before)
1322
+ await ops.setFront(before).catch(() => {
1323
+ return;
1324
+ });
1325
+ };
1326
+ await fix();
1327
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
1328
+ await fix();
1329
+ return result;
1330
+ }
1331
+ var macFrontAppOps;
1332
+ var init_frontApp = __esm(() => {
1333
+ macFrontAppOps = {
1334
+ async front() {
1335
+ const asn = (await run("lsappinfo", ["front"])).trim();
1336
+ if (!asn)
1337
+ return null;
1338
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
1339
+ return m ? Number(m[1]) : null;
1340
+ },
1341
+ async setFront(pid) {
1342
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
1343
+ }
1344
+ };
1345
+ });
1346
+
1300
1347
  // src/activity.ts
1301
1348
  function dispatchKey(backend, targetId) {
1302
1349
  return `${backend}:${targetId}`;
@@ -3000,6 +3047,8 @@ function mapBidiError(e) {
3000
3047
  return driverError2("disconnected", e.message);
3001
3048
  if (code === "unsupported operation")
3002
3049
  return driverError2("unsupported", e.message);
3050
+ if (code === "unknown command")
3051
+ return driverError2("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
3003
3052
  if (!code && /timed out/i.test(e.message))
3004
3053
  return driverError2("timeout", e.message);
3005
3054
  if (!code && /(disposed|not open|connection closed)/i.test(e.message))
@@ -3153,6 +3202,69 @@ async function resolveElementLocator2(conn, contextId, loc) {
3153
3202
  throw driverError2("no-such-element", `text '${loc.text}' matched no element`);
3154
3203
  return sharedRefOf(nodes[0], `text '${loc.text}'`);
3155
3204
  }
3205
+ function modifierKeyValues(mods) {
3206
+ const out = [];
3207
+ for (const m of mods ?? []) {
3208
+ const v = MODIFIER_VALUES[m.toLowerCase()];
3209
+ if (v === undefined)
3210
+ throw driverError2("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
3211
+ if (!out.includes(v))
3212
+ out.push(v);
3213
+ }
3214
+ return out;
3215
+ }
3216
+ function modifierChord(pointerId, actions, keys) {
3217
+ const pointer = actions;
3218
+ if (keys.length === 0)
3219
+ return [{ type: "pointer", id: pointerId, actions: pointer }];
3220
+ const k = keys.length;
3221
+ const pause = () => ({ type: "pause" });
3222
+ const keyActions = [
3223
+ ...keys.map((v) => ({ type: "keyDown", value: v })),
3224
+ ...pointer.map(pause),
3225
+ ...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
3226
+ ];
3227
+ const pointerActions = [
3228
+ ...Array.from({ length: k }, pause),
3229
+ ...pointer,
3230
+ ...Array.from({ length: k }, pause)
3231
+ ];
3232
+ return [
3233
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
3234
+ { type: "pointer", id: pointerId, actions: pointerActions }
3235
+ ];
3236
+ }
3237
+ function firefoxMajor(conn) {
3238
+ const v = conn.capabilities?.browserVersion;
3239
+ if (typeof v !== "string")
3240
+ return;
3241
+ const major = Number.parseInt(v, 10);
3242
+ return Number.isFinite(major) ? major : undefined;
3243
+ }
3244
+ function requireFirefox(conn, token) {
3245
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
3246
+ if (min === undefined)
3247
+ return;
3248
+ const major = firefoxMajor(conn);
3249
+ if (major !== undefined && major < min) {
3250
+ const v = conn.capabilities.browserVersion;
3251
+ throw driverError2("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
3252
+ }
3253
+ }
3254
+ async function armPostHocBodies(conn) {
3255
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
3256
+ return;
3257
+ try {
3258
+ requireFirefox(conn, "network.responseBodyPostHoc");
3259
+ } catch {
3260
+ return;
3261
+ }
3262
+ try {
3263
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
3264
+ } catch (e) {
3265
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
3266
+ }
3267
+ }
3156
3268
  function bumpEpoch(endpoint, conn) {
3157
3269
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
3158
3270
  connEndpoints.set(conn, endpoint);
@@ -3350,6 +3462,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
3350
3462
  }
3351
3463
  connections.set(endpoint, conn);
3352
3464
  bumpEpoch(endpoint, conn);
3465
+ await armPostHocBodies(conn);
3353
3466
  if (muxMode(attached) !== "off") {
3354
3467
  try {
3355
3468
  const mux = await startBidiMux(conn);
@@ -3440,6 +3553,9 @@ async function pickContext(conn, contexts, selector) {
3440
3553
  return exact;
3441
3554
  throw driverError2("no-such-target", `no context matching '${selector}'`);
3442
3555
  }
3556
+ function bidiCreateTabParams(opts) {
3557
+ return { type: "tab", background: opts?.focus !== true };
3558
+ }
3443
3559
 
3444
3560
  class BidiBrowserDriver {
3445
3561
  endpoint;
@@ -3466,12 +3582,13 @@ class BidiBrowserDriver {
3466
3582
  conn.release();
3467
3583
  }
3468
3584
  }
3469
- async newPage(url) {
3585
+ async newPage(url, opts) {
3470
3586
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3471
3587
  try {
3472
- const { context } = await conn.send("browsingContext.create", { type: "tab" }).catch((e) => {
3588
+ const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
3473
3589
  throw mapBidiError(e);
3474
3590
  });
3591
+ const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
3475
3592
  if (url)
3476
3593
  await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
3477
3594
  throw mapBidiError(e);
@@ -3484,9 +3601,9 @@ class BidiBrowserDriver {
3484
3601
  async closePage(id) {
3485
3602
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3486
3603
  try {
3487
- await conn.send("browsingContext.close", { context: id }).catch((e) => {
3604
+ await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
3488
3605
  throw mapBidiError(e);
3489
- });
3606
+ }));
3490
3607
  return { success: true };
3491
3608
  } finally {
3492
3609
  conn.release();
@@ -3565,7 +3682,35 @@ class BidiBrowserDriver {
3565
3682
  conn.release();
3566
3683
  }
3567
3684
  }
3685
+ async withBrowserConnection(fn) {
3686
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3687
+ try {
3688
+ return await fn(conn);
3689
+ } finally {
3690
+ conn.release();
3691
+ }
3692
+ }
3693
+ setDisposeHook(key, hook) {
3694
+ let hooks = disposeHooks.get(this.endpoint);
3695
+ if (!hooks) {
3696
+ hooks = new Map;
3697
+ disposeHooks.set(this.endpoint, hooks);
3698
+ }
3699
+ if (hook)
3700
+ hooks.set(key, hook);
3701
+ else
3702
+ hooks.delete(key);
3703
+ }
3568
3704
  async dispose() {
3705
+ const hooks = disposeHooks.get(this.endpoint);
3706
+ disposeHooks.delete(this.endpoint);
3707
+ const live = connections.get(this.endpoint);
3708
+ if (hooks && live) {
3709
+ for (const hook of hooks.values())
3710
+ await hook(live).catch(() => {
3711
+ return;
3712
+ });
3713
+ }
3569
3714
  for (const key of [...bidiBeaconScripts.keys()]) {
3570
3715
  if (key.startsWith(`${this.endpoint}:`))
3571
3716
  bidiBeaconScripts.delete(key);
@@ -3640,8 +3785,9 @@ async function hostFirefoxMux(endpoint, opts = {}) {
3640
3785
  function createFirefoxDriverForEndpoint(wsUrl, opts) {
3641
3786
  return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
3642
3787
  }
3643
- var LINE_RE, INTERACTIVE_ROLES3, 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, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3788
+ var LINE_RE, INTERACTIVE_ROLES3, 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, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3644
3789
  var init_driver2 = __esm(() => {
3790
+ init_frontApp();
3645
3791
  init_driver();
3646
3792
  init_leases();
3647
3793
  init_origins();
@@ -3695,13 +3841,25 @@ var init_driver2 = __esm(() => {
3695
3841
  MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
3696
3842
  BUTTON_CODES = { left: 0, middle: 1, right: 2 };
3697
3843
  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);});}";
3844
+ BIDI_CAPABILITY_MIN_FIREFOX = {
3845
+ "browser.downloads": 160,
3846
+ "browser.permissions": 160,
3847
+ "emulate.mediaFeatures": 160,
3848
+ "emulate.networkConditions": 160,
3849
+ "input.raw": 160,
3850
+ "input.modifierClick": 160,
3851
+ "network.responseBodyPostHoc": 160,
3852
+ "screenshot.scale": 160
3853
+ };
3854
+ POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
3698
3855
  BIDI_CAPABILITIES = new Set([
3699
3856
  "emulate.deviceMetrics",
3700
3857
  "screenshot.fullPage",
3701
3858
  "screenshot.element",
3702
3859
  "screenshot.renderSize",
3703
3860
  "network.intercept",
3704
- "locate.xpath"
3861
+ "locate.xpath",
3862
+ ...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
3705
3863
  ]);
3706
3864
  connections = new Map;
3707
3865
  slotHandles = new Map;
@@ -3710,6 +3868,7 @@ var init_driver2 = __esm(() => {
3710
3868
  connecting = new Map;
3711
3869
  sessionEpochs = new Map;
3712
3870
  connEndpoints = new WeakMap;
3871
+ disposeHooks = new Map;
3713
3872
  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";
3714
3873
  bidiBeaconScripts = new Map;
3715
3874
  BidiPageDriver = class BidiPageDriver {
@@ -3876,18 +4035,30 @@ var init_driver2 = __esm(() => {
3876
4035
  return { x, y };
3877
4036
  }
3878
4037
  async click(loc, opts) {
3879
- if (opts?.modifiers && opts.modifiers.length > 0) {
3880
- throw driverError2("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
3881
- }
4038
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
4039
+ if (hasModifiers)
4040
+ requireFirefox(this.conn, "input.modifierClick");
4041
+ const keys = modifierKeyValues(opts?.modifiers);
3882
4042
  const ref = await resolveElementLocator2(this.conn, this.contextId, loc);
3883
4043
  const { x, y } = await this.centerOf(ref);
3884
4044
  const button = BUTTON_CODES[opts?.button ?? "left"];
3885
4045
  const actions = [{ type: "pointerMove", x, y, duration: 0 }];
3886
4046
  for (let i = 0;i < (opts?.clickCount ?? 1); i++)
3887
4047
  actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
3888
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
4048
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
3889
4049
  return { x, y };
3890
4050
  }
4051
+ async dispatchMouse(event) {
4052
+ requireFirefox(this.conn, "input.raw");
4053
+ const keys = modifierKeyValues(event.modifiers);
4054
+ const button = BUTTON_CODES[event.button ?? "left"];
4055
+ const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
4056
+ if (event.action === "down")
4057
+ actions.push({ type: "pointerDown", button });
4058
+ else if (event.action === "up")
4059
+ actions.push({ type: "pointerUp", button });
4060
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
4061
+ }
3891
4062
  async scroll(anchor, opts) {
3892
4063
  const { x, y } = await this.resolveScrollPoint(anchor);
3893
4064
  const deltaX = Math.round(opts.deltaX ?? 0);
@@ -3958,8 +4129,11 @@ var init_driver2 = __esm(() => {
3958
4129
  await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
3959
4130
  return;
3960
4131
  }
3961
- const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
3962
- await this.callFunctionValue(clear, [], ref);
4132
+ const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
4133
+ const state = await this.callFunctionValue(clear, [], ref);
4134
+ if (state === "disabled" || state === "readonly") {
4135
+ throw driverError2("page-error", `cannot fill a ${state} field: it was left unchanged`);
4136
+ }
3963
4137
  await this.sendKeys(value);
3964
4138
  }
3965
4139
  async typeText(loc, text) {
@@ -3996,11 +4170,23 @@ var init_driver2 = __esm(() => {
3996
4170
  }
3997
4171
  async screenshot(opts, _consumeBands) {
3998
4172
  const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
3999
- if (!renderSize)
4173
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
4174
+ if (!renderSize && scale === undefined)
4000
4175
  return this.capture(opts);
4176
+ if (scale !== undefined)
4177
+ requireFirefox(this.conn, "screenshot.scale");
4001
4178
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
4179
+ let dprOverride;
4180
+ if (scale !== undefined) {
4181
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
4182
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
4183
+ }
4002
4184
  try {
4003
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
4185
+ await this.conn.send("browsingContext.setViewport", {
4186
+ context: this.contextId,
4187
+ ...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
4188
+ ...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
4189
+ });
4004
4190
  } catch (e) {
4005
4191
  throw mapBidiError(e);
4006
4192
  }
@@ -4017,29 +4203,35 @@ var init_driver2 = __esm(() => {
4017
4203
  await this.conn.send("browsingContext.setViewport", {
4018
4204
  context: this.contextId,
4019
4205
  viewport: { width: previous.width, height: previous.height },
4020
- ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
4206
+ ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
4021
4207
  });
4022
4208
  } else {
4023
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
4209
+ await this.conn.send("browsingContext.setViewport", {
4210
+ context: this.contextId,
4211
+ ...renderSize ? { viewport: null } : {},
4212
+ ...scale !== undefined ? { devicePixelRatio: null } : {}
4213
+ });
4024
4214
  }
4025
4215
  } catch (e) {
4026
4216
  restoreError = e instanceof Error ? e.message : String(e);
4027
4217
  }
4028
4218
  if (!shot) {
4029
4219
  if (restoreError !== undefined && captureError instanceof Error) {
4030
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
4220
+ 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})`;
4031
4221
  }
4032
4222
  throw captureError;
4033
4223
  }
4224
+ if (!renderSize) {
4225
+ if (restoreError !== undefined)
4226
+ throw driverError2("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
4227
+ return shot;
4228
+ }
4034
4229
  const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
4035
4230
  if (restoreError !== undefined)
4036
4231
  result.renderRestoreError = restoreError;
4037
4232
  return result;
4038
4233
  }
4039
4234
  async capture(opts) {
4040
- if (opts?.scale !== undefined && opts.scale !== 1) {
4041
- throw driverError2("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.`);
4042
- }
4043
4235
  if (opts?.tile === true) {
4044
4236
  throw driverError2("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.");
4045
4237
  }
@@ -4067,10 +4259,29 @@ var init_driver2 = __esm(() => {
4067
4259
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
4068
4260
  return;
4069
4261
  });
4262
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
4263
+ return;
4264
+ });
4265
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
4266
+ return;
4267
+ });
4070
4268
  await clearViewportRecord(this.browser.scheme, this.contextId);
4071
4269
  return { applied: [] };
4072
4270
  }
4073
4271
  const applied = [];
4272
+ if (opts.media != null && opts.media !== "") {
4273
+ throw driverError2("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.`);
4274
+ }
4275
+ const net = opts.networkConditions;
4276
+ if (net != null) {
4277
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
4278
+ if (throttled) {
4279
+ throw driverError2("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.');
4280
+ }
4281
+ requireFirefox(this.conn, "emulate.networkConditions");
4282
+ }
4283
+ if (opts.mediaFeatures != null)
4284
+ requireFirefox(this.conn, "emulate.mediaFeatures");
4074
4285
  try {
4075
4286
  if (opts.width != null && opts.height != null) {
4076
4287
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
@@ -4085,6 +4296,21 @@ var init_driver2 = __esm(() => {
4085
4296
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
4086
4297
  applied.push("userAgent");
4087
4298
  }
4299
+ if (opts.mediaFeatures != null) {
4300
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
4301
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
4302
+ features: opts.mediaFeatures.length > 0 ? features : null,
4303
+ contexts: [this.contextId]
4304
+ });
4305
+ applied.push("mediaFeatures");
4306
+ }
4307
+ if (net != null) {
4308
+ await this.conn.send("emulation.setNetworkConditions", {
4309
+ networkConditions: net.offline ? { type: "offline" } : null,
4310
+ contexts: [this.contextId]
4311
+ });
4312
+ applied.push("networkConditions");
4313
+ }
4088
4314
  } catch (e) {
4089
4315
  throw mapBidiError(e);
4090
4316
  }
@@ -4219,12 +4445,25 @@ var init_driver2 = __esm(() => {
4219
4445
  };
4220
4446
  }
4221
4447
  async getResponseBody(requestId) {
4222
- if (!this.bodyCollector)
4223
- throw driverError2("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
4448
+ let collector;
4449
+ try {
4450
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
4451
+ } catch (e) {
4452
+ if (!this.bodyCollector) {
4453
+ throw driverError2("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
4454
+ }
4455
+ collector = this.bodyCollector;
4456
+ }
4224
4457
  try {
4225
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
4458
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
4226
4459
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
4227
4460
  } catch (e) {
4461
+ if (e instanceof BidiError && e.code === "unavailable network data") {
4462
+ throw driverError2("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.`);
4463
+ }
4464
+ if (e instanceof BidiError && e.code === "no such network data") {
4465
+ throw driverError2("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.`);
4466
+ }
4228
4467
  throw mapBidiError(e);
4229
4468
  }
4230
4469
  }
@@ -4302,6 +4541,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
4302
4541
  // src/cdp/driver.ts
4303
4542
  init_client();
4304
4543
  init_session();
4544
+ init_frontApp();
4305
4545
  init_leases();
4306
4546
  init_endpoints();
4307
4547
  init_activity();
@@ -4479,6 +4719,47 @@ async function centerOf(conn, objectId) {
4479
4719
  throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
4480
4720
  return result.value;
4481
4721
  }
4722
+ var SNAPSHOT_TEXT_FN = "function(){var e=this;e.__cdpSawInput=false;var f=function(){e.__cdpSawInput=true;};" + "e.addEventListener('beforeinput',f,{capture:true,once:true});e.addEventListener('input',f,{capture:true,once:true});" + "return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);}";
4723
+ var LANDED_TEXT_FN = "function(before){var e=this;var now=function(){return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);};" + "var hit=function(){return e.__cdpSawInput===true||now()!==before;};" + "if(hit())return true;return new Promise(function(r){setTimeout(function(){r(hit());},50);});}";
4724
+ var FALLBACK_TEXT_FN = "function(t){var e=this;if(e.disabled||e.readOnly)return 'skipped';var ce=e.isContentEditable===true;" + "var ta=e instanceof HTMLTextAreaElement;var inp=e instanceof HTMLInputElement&&!/^(checkbox|radio|file|button|submit|reset|image|hidden|range|color)$/i.test(e.type);" + "if(!ce&&!ta&&!inp)return 'skipped';e.focus();" + "if(ce){var r=document.createRange();r.selectNodeContents(e);r.collapse(false);var s=window.getSelection();s.removeAllRanges();s.addRange(r);}" + "else{try{var n=e.value.length;e.setSelectionRange(n,n);}catch(x){}}" + "var read=function(){return ce?e.textContent:e.value;};var before=read();" + "if(document.execCommand('insertText',false,t)&&read()!==before){e.dispatchEvent(new Event('change',{bubbles:true}));return 'execCommand';}" + "if(ce)return 'failed';var proto=ta?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;" + "Object.getOwnPropertyDescriptor(proto,'value').set.call(e,before+t);" + "e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:t}));" + "e.dispatchEvent(new Event('change',{bubbles:true}));return 'setter';}";
4725
+ async function insertTextVerified(conn, objectId, text, sendInput) {
4726
+ const call = async (fn, args = [], awaitPromise = false) => {
4727
+ const { result, exceptionDetails } = await conn.send("Runtime.callFunctionOn", {
4728
+ objectId,
4729
+ functionDeclaration: fn,
4730
+ arguments: args.map((value) => ({ value })),
4731
+ returnByValue: true,
4732
+ awaitPromise
4733
+ });
4734
+ if (exceptionDetails)
4735
+ throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
4736
+ return result?.value;
4737
+ };
4738
+ const before = await call(SNAPSHOT_TEXT_FN);
4739
+ await sendInput("Input.insertText", { text });
4740
+ if (await call(LANDED_TEXT_FN, [before], true) === true)
4741
+ return "trusted";
4742
+ const via = await call(FALLBACK_TEXT_FN, [text]);
4743
+ if (via === "execCommand" || via === "setter" || via === "skipped")
4744
+ return via;
4745
+ throw driverError("page-error", "text did not land: trusted Input.insertText was not delivered (a background tab gets no trusted keyboard input) and document.execCommand('insertText') changed nothing on this element");
4746
+ }
4747
+ var ARM_KEY_WITNESS = "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
4748
+ var READ_KEY_WITNESS = "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
4749
+ async function pressKeyObserved(conn, dispatch) {
4750
+ const eval_ = (expression, awaitPromise = false) => conn.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => {
4751
+ return;
4752
+ });
4753
+ const armed = await eval_(ARM_KEY_WITNESS) === true;
4754
+ await dispatch();
4755
+ if (!armed)
4756
+ return;
4757
+ const seen = await eval_(READ_KEY_WITNESS, true);
4758
+ if (seen === false)
4759
+ return { delivered: false };
4760
+ if (seen === true)
4761
+ return { delivered: true };
4762
+ }
4482
4763
  async function focusElement(conn, objectId) {
4483
4764
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
4484
4765
  }
@@ -4493,10 +4774,12 @@ async function awaitScrollSettle(conn) {
4493
4774
  }
4494
4775
  async function setValueOnObject(conn, objectId, value, sendInput) {
4495
4776
  await focusElement(conn, objectId);
4496
- const fn = "function(){if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}}";
4497
- await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
4498
- if (value.length)
4499
- await sendInput("Input.insertText", { text: value });
4777
+ const fn = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}return 'ok';}";
4778
+ const { result } = await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
4779
+ if (result?.value === "disabled" || result?.value === "readonly") {
4780
+ throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
4781
+ }
4782
+ return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
4500
4783
  }
4501
4784
  var NAMED_KEYS = {
4502
4785
  enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
@@ -4765,6 +5048,7 @@ var CDP_CAPABILITIES = new Set([
4765
5048
  "locate.xpath",
4766
5049
  "capture.screencast",
4767
5050
  "input.raw",
5051
+ "input.modifierClick",
4768
5052
  "input.html5Drag",
4769
5053
  "emulate.focus",
4770
5054
  "browser.downloads",
@@ -5043,13 +5327,12 @@ class CdpPageDriver {
5043
5327
  }
5044
5328
  async setValue(loc, value) {
5045
5329
  const { objectId } = await resolveElementLocator(this.conn, loc);
5046
- await setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
5330
+ return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
5047
5331
  }
5048
5332
  async typeText(loc, text) {
5049
5333
  const { objectId } = await resolveElementLocator(this.conn, loc);
5050
5334
  await focusElement(this.conn, objectId);
5051
- if (text.length)
5052
- await this.dispatchInput("Input.insertText", { text });
5335
+ return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
5053
5336
  }
5054
5337
  async pressKey(press) {
5055
5338
  const spec = resolveKey(press.key);
@@ -5064,8 +5347,10 @@ class CdpPageDriver {
5064
5347
  const down = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
5065
5348
  if (spec.text && !suppressText)
5066
5349
  down.text = spec.text;
5067
- await this.dispatchInput("Input.dispatchKeyEvent", down);
5068
- await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
5350
+ return pressKeyObserved(this.conn, async () => {
5351
+ await this.dispatchInput("Input.dispatchKeyEvent", down);
5352
+ await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
5353
+ });
5069
5354
  }
5070
5355
  async setFiles(loc, files) {
5071
5356
  const { objectId } = await resolveElementLocator(this.conn, loc);
@@ -5442,7 +5727,7 @@ function noSuchTarget(e) {
5442
5727
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
5443
5728
  }
5444
5729
  var NEW_TARGET_SETTLE_MS = 2000;
5445
- async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5730
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, opts = {}) {
5446
5731
  const changed = new Set;
5447
5732
  let id = "";
5448
5733
  let wake;
@@ -5458,7 +5743,8 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5458
5743
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5459
5744
  return;
5460
5745
  });
5461
- const { targetId } = await conn.send("Target.createTarget", { url });
5746
+ const create = () => conn.send("Target.createTarget", { url, background: opts.focus !== true });
5747
+ const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
5462
5748
  if (!targetId)
5463
5749
  throw driverError("page-error", "Target.createTarget returned no targetId");
5464
5750
  id = targetId;
@@ -5488,15 +5774,15 @@ class CdpBrowserDriver {
5488
5774
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
5489
5775
  return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
5490
5776
  }
5491
- async newPage(url) {
5777
+ async newPage(url, opts) {
5492
5778
  return withBrowserConn(async (conn) => {
5493
- const targetId = await createSettledTarget(conn, url ?? "about:blank");
5779
+ const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
5494
5780
  return { id: targetId, url: url ?? "about:blank", title: "" };
5495
5781
  });
5496
5782
  }
5497
5783
  async closePage(id) {
5498
5784
  return withBrowserConn(async (conn) => {
5499
- const res = await conn.send("Target.closeTarget", { targetId: id });
5785
+ const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
5500
5786
  if (res.success !== false)
5501
5787
  beaconSessions.drop(beaconKey(id));
5502
5788
  return { success: res.success ?? true };
@@ -6166,7 +6452,6 @@ init_workers();
6166
6452
  init_frames();
6167
6453
  init_endpoints();
6168
6454
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
6169
- var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
6170
6455
 
6171
6456
  class SharedToolError extends Error {
6172
6457
  }
@@ -6325,7 +6610,7 @@ async function listPagesOne(driver, args = {}) {
6325
6610
  }
6326
6611
  async function newPage(driver, args = {}) {
6327
6612
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
6328
- const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label });
6613
+ const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
6329
6614
  const explicit = args.claim === true;
6330
6615
  if (!explicit && !requireLease())
6331
6616
  return { targetId: p.id, url: p.url };
@@ -6348,16 +6633,17 @@ async function closePage(driver, args) {
6348
6633
  return { closed: p.id, success: true, ...released.released ? { leaseReleased: true } : {} };
6349
6634
  }
6350
6635
  async function writeSelectedFile(id) {
6351
- await mkdir5(STATE_DIR, { recursive: true });
6352
- await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6636
+ const stateDir = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
6637
+ await mkdir5(stateDir, { recursive: true });
6638
+ await writeFile4(join5(stateDir, "selected"), id, "utf8");
6353
6639
  }
6354
6640
  async function selectPage(driver, args) {
6355
6641
  if (args.target === undefined || args.target === "")
6356
6642
  throw new SharedToolError("select_page requires an explicit target");
6357
6643
  const p = await resolvePage(driver, args.target);
6358
- const activated = await driver.activatePage(p.id);
6359
- await writeSelectedFile(activated.id);
6360
- return { selected: activated.id };
6644
+ const id = args.focus === true ? (await driver.activatePage(p.id)).id : p.id;
6645
+ await writeSelectedFile(id);
6646
+ return { selected: id, focused: args.focus === true };
6361
6647
  }
6362
6648
  function toLegacyWaitedFor(w) {
6363
6649
  if (w === "committed")
@@ -6716,14 +7002,17 @@ async function drag(driver, args) {
6716
7002
  };
6717
7003
  });
6718
7004
  }
7005
+ function inputPathField(path) {
7006
+ return path && path !== "trusted" ? { inputPath: path } : {};
7007
+ }
6719
7008
  async function fill(driver, args) {
6720
7009
  if (typeof args.value !== "string")
6721
7010
  throw new SharedToolError("fill requires a string { value }");
6722
7011
  const loc = locatorOf(args);
6723
7012
  return withPage2(driver, args.target, async (page) => {
6724
7013
  const element = await describeElement(page, loc);
6725
- await page.setValue(loc, args.value);
6726
- return { filled: true, ...elementField(element), value: args.value };
7014
+ const path = await page.setValue(loc, args.value);
7015
+ return { filled: true, ...elementField(element), value: args.value, ...inputPathField(path) };
6727
7016
  });
6728
7017
  }
6729
7018
  async function fillForm(driver, args) {
@@ -6732,15 +7021,16 @@ async function fillForm(driver, args) {
6732
7021
  return withPage2(driver, args.target, async (page) => {
6733
7022
  let filled = 0;
6734
7023
  const elements = [];
7024
+ const paths = [];
6735
7025
  for (const f of args.fields) {
6736
7026
  if (typeof f.value !== "string")
6737
7027
  throw new SharedToolError("each fill_form field requires a string value");
6738
7028
  const loc = locatorOf(f);
6739
7029
  elements.push(await describeElement(page, loc) ?? null);
6740
- await page.setValue(loc, f.value);
7030
+ paths.push(await page.setValue(loc, f.value) || "trusted");
6741
7031
  filled++;
6742
7032
  }
6743
- return { filled, fields: args.fields.length, elements };
7033
+ return { filled, fields: args.fields.length, elements, ...paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {} };
6744
7034
  });
6745
7035
  }
6746
7036
  async function typeText(driver, args) {
@@ -6749,8 +7039,8 @@ async function typeText(driver, args) {
6749
7039
  const loc = locatorOf(args);
6750
7040
  return withPage2(driver, args.target, async (page) => {
6751
7041
  const element = await describeElement(page, loc);
6752
- await page.typeText(loc, args.text);
6753
- return { typed: true, ...elementField(element), text: args.text };
7042
+ const path = await page.typeText(loc, args.text);
7043
+ return { typed: true, ...elementField(element), text: args.text, ...inputPathField(path) };
6754
7044
  });
6755
7045
  }
6756
7046
  async function pressKey(driver, args) {
@@ -6758,7 +7048,15 @@ async function pressKey(driver, args) {
6758
7048
  throw new SharedToolError("press_key requires a non-empty { key }");
6759
7049
  const modifiers = args.modifiers ?? [];
6760
7050
  return withPage2(driver, args.target, async (page) => {
6761
- await page.pressKey({ key: args.key, modifiers });
7051
+ const res = await page.pressKey({ key: args.key, modifiers });
7052
+ if (res && res.delivered === false) {
7053
+ return {
7054
+ pressed: args.key,
7055
+ modifiers,
7056
+ delivered: false,
7057
+ note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true. A key handled inside a cross-origin iframe also reads as not delivered."
7058
+ };
7059
+ }
6762
7060
  return { pressed: args.key, modifiers };
6763
7061
  });
6764
7062
  }
@@ -6785,7 +7083,7 @@ function resolveScreenshotScale(scale, capabilities) {
6785
7083
  throw new SharedToolError(`take_screenshot: 'scale' must be a finite number greater than 0 and at most ${MAX_SCREENSHOT_SCALE} (default 1)`);
6786
7084
  }
6787
7085
  if (scale !== 1 && !capabilities.has("screenshot.scale")) {
6788
- throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (WebDriver BiDi's browsingContext.captureScreenshot has no scale parameter). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`);
7086
+ throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (no per-capture scale primitive). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`);
6789
7087
  }
6790
7088
  return scale;
6791
7089
  }
@@ -7026,7 +7324,7 @@ async function claimPage(driver, args = {}) {
7026
7324
  url = existing.url;
7027
7325
  opened = false;
7028
7326
  } else {
7029
- const page = await newTrackedPage(driver, backend, { url: args.url, label });
7327
+ const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
7030
7328
  targetId = page.id;
7031
7329
  url = page.url;
7032
7330
  opened = true;
@@ -7526,7 +7824,7 @@ init_client();
7526
7824
  import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7527
7825
  import { join as join6 } from "node:path";
7528
7826
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7529
- var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7827
+ var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7530
7828
  var DEFAULT_CATEGORIES = [
7531
7829
  "devtools.timeline",
7532
7830
  "blink.user_timing",
@@ -7542,7 +7840,7 @@ function shortId(id) {
7542
7840
  return id.slice(0, 8);
7543
7841
  }
7544
7842
  function stateFilePath() {
7545
- return join6(STATE_DIR2, "trace-state.json");
7843
+ return join6(STATE_DIR, "trace-state.json");
7546
7844
  }
7547
7845
  function bufferTraceData(conn, sink) {
7548
7846
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7587,7 +7885,7 @@ async function performanceStartTrace(args = {}) {
7587
7885
  throw err;
7588
7886
  }
7589
7887
  liveTraces.set(target.id, { conn, target, events, startedAt: Date.now() });
7590
- await mkdir7(STATE_DIR2, { recursive: true });
7888
+ await mkdir7(STATE_DIR, { recursive: true });
7591
7889
  const state = {
7592
7890
  targetId: target.id,
7593
7891
  url: target.url,
@@ -7916,7 +8214,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
7916
8214
  outPath
7917
8215
  ];
7918
8216
  }
7919
- function run(bin, args) {
8217
+ function run2(bin, args) {
7920
8218
  return new Promise((resolve, reject) => {
7921
8219
  const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
7922
8220
  let stdout = "";
@@ -7938,7 +8236,7 @@ async function probeEncoder() {
7938
8236
  encoderProbe = (async () => {
7939
8237
  let res;
7940
8238
  try {
7941
- res = await run(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
8239
+ res = await run2(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
7942
8240
  } catch (err) {
7943
8241
  throw new CdpError(`${FFMPEG_MISSING} (${err.message})`);
7944
8242
  }
@@ -7947,7 +8245,7 @@ async function probeEncoder() {
7947
8245
  const choice = selectEncoder(`${res.stdout}
7948
8246
  ${res.stderr}`);
7949
8247
  const output = async (args) => {
7950
- const r = await run(FFMPEG_BIN, args).catch(() => {
8248
+ const r = await run2(FFMPEG_BIN, args).catch(() => {
7951
8249
  return;
7952
8250
  });
7953
8251
  return r && r.code === 0 ? `${r.stdout}
@@ -8120,7 +8418,7 @@ async function stopScreenRecording(args = {}) {
8120
8418
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
8121
8419
  let res;
8122
8420
  try {
8123
- res = await run(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8421
+ res = await run2(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8124
8422
  } catch (err) {
8125
8423
  throw new CdpError(`${FFMPEG_MISSING} Spooled frames kept at ${rec.spoolDir}. (${err.message})`);
8126
8424
  }
@@ -9213,7 +9511,7 @@ var MANIFEST = [
9213
9511
  },
9214
9512
  {
9215
9513
  name: "new_page",
9216
- description: "Open a browser tab, optionally claim it; navigation is not awaited.",
9514
+ description: "Open a browser tab in the background, optionally claim it; navigation is not awaited.",
9217
9515
  inputSchema: {
9218
9516
  type: "object",
9219
9517
  properties: {
@@ -9240,6 +9538,10 @@ var MANIFEST = [
9240
9538
  ttlMs: {
9241
9539
  type: "number",
9242
9540
  description: "Lease TTL in milliseconds."
9541
+ },
9542
+ focus: {
9543
+ type: "boolean",
9544
+ description: "Open in the foreground and take focus; default false (background tab)."
9243
9545
  }
9244
9546
  },
9245
9547
  required: [],
@@ -9269,7 +9571,7 @@ var MANIFEST = [
9269
9571
  },
9270
9572
  {
9271
9573
  name: "select_page",
9272
- description: "Focus a selected page and persist it as active; target must resolve explicitly.",
9574
+ description: "Persist a page as selected; focus:true also raises it. Target must resolve explicitly.",
9273
9575
  inputSchema: {
9274
9576
  type: "object",
9275
9577
  properties: {
@@ -9280,6 +9582,10 @@ var MANIFEST = [
9280
9582
  target: {
9281
9583
  type: "string",
9282
9584
  description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9585
+ },
9586
+ focus: {
9587
+ type: "boolean",
9588
+ description: "Also raise the tab and take window focus; default false (selection only)."
9283
9589
  }
9284
9590
  },
9285
9591
  required: [
@@ -9779,7 +10085,7 @@ var MANIFEST = [
9779
10085
  },
9780
10086
  {
9781
10087
  name: "dispatch_mouse",
9782
- description: "Dispatch one raw mouse event at viewport coordinates; Chrome-only.",
10088
+ description: "Dispatch one raw mouse event at viewport coordinates; Firefox needs 160 or newer.",
9783
10089
  inputSchema: {
9784
10090
  type: "object",
9785
10091
  properties: {
@@ -9936,7 +10242,7 @@ var MANIFEST = [
9936
10242
  },
9937
10243
  {
9938
10244
  name: "grant_permissions",
9939
- description: "Grant or reset browser permissions; permissions are origin-scoped and Chrome-only.",
10245
+ description: "Grant or reset browser permissions; permissions are origin-scoped (Chrome, Firefox 160+).",
9940
10246
  inputSchema: {
9941
10247
  type: "object",
9942
10248
  properties: {
@@ -10871,7 +11177,7 @@ var MANIFEST = [
10871
11177
  },
10872
11178
  {
10873
11179
  name: "claim_page",
10874
- description: "Claim an existing tab or open a fresh one; CLI use is refused.",
11180
+ description: "Claim an existing tab or open a fresh one in the background; CLI use is refused.",
10875
11181
  inputSchema: {
10876
11182
  type: "object",
10877
11183
  properties: {
@@ -10894,6 +11200,10 @@ var MANIFEST = [
10894
11200
  ttlMs: {
10895
11201
  type: "number",
10896
11202
  description: "Lease TTL in milliseconds."
11203
+ },
11204
+ focus: {
11205
+ type: "boolean",
11206
+ description: "Fresh tab only: open it in the foreground; default false (background)."
10897
11207
  }
10898
11208
  },
10899
11209
  required: [],
@@ -11319,6 +11629,16 @@ async function withPage4(driver, target, fn) {
11319
11629
  await page.release();
11320
11630
  }
11321
11631
  }
11632
+ async function dispatchMouse2(driver, args) {
11633
+ validateDispatchMouseArgs(args);
11634
+ modifierBits(args.modifiers);
11635
+ return withPage4(driver, args.target, async (page) => {
11636
+ if (!page.dispatchMouse)
11637
+ throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
11638
+ await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
11639
+ return { dispatched: args.action, x: args.x, y: args.y };
11640
+ });
11641
+ }
11322
11642
  var consoleBuffers = new Map;
11323
11643
  var networkBuffers = new Map;
11324
11644
  function refuseWorkerSelector(driver, target) {
@@ -11391,6 +11711,13 @@ async function getNetworkRequest2(driver, args = {}) {
11391
11711
  return withPage4(driver, args.target, async (page) => {
11392
11712
  const buf = bufferFor(networkBuffers, page.info.id);
11393
11713
  const found = args.requestId ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId) : buf.find((r) => typeof r.url === "string" && r.url.includes(args.url));
11714
+ if (args.includeBody) {
11715
+ const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
11716
+ if (!id)
11717
+ throw new BidiToolError("get_network_request includeBody on this backend needs a requestId, or a url already present in the buffer (run list_network_requests with reload first)");
11718
+ const { body, base64Encoded } = await page.getResponseBody(id);
11719
+ return { ...found ?? { requestId: id }, body, bodyBase64Encoded: base64Encoded };
11720
+ }
11394
11721
  if (!found)
11395
11722
  throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
11396
11723
  return found;
@@ -11466,7 +11793,232 @@ var BIDI_ONLY_TOOLS = {
11466
11793
  get_network_request: getNetworkRequest2,
11467
11794
  mock_request: mockRequest2,
11468
11795
  list_mocks: listMocks2,
11469
- clear_mocks: clearMocks2
11796
+ clear_mocks: clearMocks2,
11797
+ dispatch_mouse: dispatchMouse2
11798
+ };
11799
+
11800
+ // src/bidi-browser-tools.ts
11801
+ init_driver2();
11802
+ import { mkdir as mkdir14, readdir as readdir4, realpath, rename as rename4, stat as stat5 } from "node:fs/promises";
11803
+ import { basename as basename2, dirname as dirname4, join as join14, resolve } from "node:path";
11804
+ function unsupported(message) {
11805
+ return Object.assign(new Error(message), { code: "unsupported" });
11806
+ }
11807
+ function scopeOf(driver, tool) {
11808
+ const d = driver;
11809
+ if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
11810
+ throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
11811
+ }
11812
+ return d;
11813
+ }
11814
+ async function targetOf(driver, target) {
11815
+ const page = await driver.page(target);
11816
+ try {
11817
+ return { id: page.info.id, url: page.info.url, title: page.info.title };
11818
+ } finally {
11819
+ await page.release();
11820
+ }
11821
+ }
11822
+ var FIREFOX_DOWNLOAD_STAGING_DIR = join14(dirname4(DOWNLOADS_DIR), "downloads-firefox-staging");
11823
+ var downloadStates = new WeakMap;
11824
+ function downloadId(p) {
11825
+ const v = p.download ?? p.navigation;
11826
+ return typeof v === "string" && v.length > 0 ? v : undefined;
11827
+ }
11828
+ function deliver(s, r) {
11829
+ r.state = "completed";
11830
+ s.downloads.push(r);
11831
+ while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
11832
+ const i = s.downloads.findIndex((d) => d.consumed);
11833
+ s.downloads.splice(i >= 0 ? i : 0, 1);
11834
+ }
11835
+ const waiter = s.waiters.shift();
11836
+ if (waiter) {
11837
+ r.consumed = true;
11838
+ waiter(r);
11839
+ }
11840
+ }
11841
+ function downloadStateFor(conn) {
11842
+ let s = downloadStates.get(conn);
11843
+ if (s)
11844
+ return s;
11845
+ const state = { downloads: [], begun: new Map, waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
11846
+ downloadStates.set(conn, state);
11847
+ conn.on("browsingContext.downloadWillBegin", (p) => {
11848
+ const id = downloadId(p);
11849
+ if (!id)
11850
+ return;
11851
+ state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
11852
+ if (state.begun.size > DOWNLOAD_BUFFER_LIMIT)
11853
+ state.begun.delete(state.begun.keys().next().value);
11854
+ });
11855
+ conn.on("browsingContext.downloadEnd", (p) => {
11856
+ const id = downloadId(p);
11857
+ if (!id)
11858
+ return;
11859
+ const rec = state.begun.get(id) ?? { id, state: "inProgress", consumed: false };
11860
+ state.begun.delete(id);
11861
+ if (p.status !== "complete" || !p.filepath)
11862
+ return;
11863
+ if (!state.stagingDirs.has(resolve(dirname4(p.filepath))))
11864
+ return;
11865
+ rec.url ??= p.url;
11866
+ const held = join14(dirname4(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
11867
+ rename4(p.filepath, held).then(() => {
11868
+ rec.filePath = held;
11869
+ }, () => {
11870
+ rec.filePath = p.filepath ?? undefined;
11871
+ }).finally(() => deliver(state, rec));
11872
+ });
11873
+ return state;
11874
+ }
11875
+ async function armFirefoxDownloads(conn, s, scope) {
11876
+ await mkdir14(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
11877
+ await mkdir14(DOWNLOADS_DIR, { recursive: true });
11878
+ s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
11879
+ scope.setDisposeHook("browser.downloads", async (c) => {
11880
+ await c.send("browser.setDownloadBehavior", { downloadBehavior: null });
11881
+ });
11882
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
11883
+ }
11884
+ async function disarmFirefoxDownloads(conn, scope) {
11885
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
11886
+ scope.setDisposeHook("browser.downloads", undefined);
11887
+ }
11888
+ function nextFirefoxDownload(s, timeoutMs) {
11889
+ const buffered = s.downloads.find((d) => !d.consumed);
11890
+ if (buffered) {
11891
+ buffered.consumed = true;
11892
+ return Promise.resolve(buffered);
11893
+ }
11894
+ return new Promise((resolvePromise, reject) => {
11895
+ const waiter = (r) => {
11896
+ clearTimeout(timer);
11897
+ resolvePromise(r);
11898
+ };
11899
+ const timer = setTimeout(() => {
11900
+ const i = s.waiters.indexOf(waiter);
11901
+ if (i >= 0)
11902
+ s.waiters.splice(i, 1);
11903
+ reject(new Error(`wait_for_download: no download completed within ${timeoutMs}ms. On Firefox, downloads are captured only while a wait_for_download call is armed: arm (arm:true) BEFORE the triggering click, and again before every later download, because each collecting call restores Firefox's normal download behavior when it returns.`));
11904
+ }, timeoutMs);
11905
+ s.waiters.push(waiter);
11906
+ });
11907
+ }
11908
+ async function waitForDownloadFirefox(driver, args = {}) {
11909
+ validateWaitForDownloadArgs(args);
11910
+ const scope = scopeOf(driver, "wait_for_download");
11911
+ const target = await targetOf(driver, args.target);
11912
+ return scope.withBrowserConnection(async (conn) => {
11913
+ requireFirefox(conn, "browser.downloads");
11914
+ const s = downloadStateFor(conn);
11915
+ await armFirefoxDownloads(conn, s, scope);
11916
+ if (args.arm === true) {
11917
+ return { armed: true, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
11918
+ }
11919
+ let rec;
11920
+ try {
11921
+ rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30000);
11922
+ } finally {
11923
+ if (s.waiters.length === 0)
11924
+ await disarmFirefoxDownloads(conn, scope).catch(() => {
11925
+ return;
11926
+ });
11927
+ }
11928
+ if (!rec.filePath) {
11929
+ throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
11930
+ }
11931
+ const suggestedFilename = safeFilename(rec.suggestedFilename);
11932
+ const taken = new Set(await readdir4(DOWNLOADS_DIR).catch(() => []));
11933
+ taken.delete(basename2(rec.filePath));
11934
+ const finalName = nextFreeName(suggestedFilename, taken);
11935
+ const path = join14(DOWNLOADS_DIR, finalName);
11936
+ await rename4(rec.filePath, path);
11937
+ const bytes = (await stat5(path)).size;
11938
+ return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
11939
+ });
11940
+ }
11941
+ var FIREFOX_PERMISSION_DESCRIPTORS = {
11942
+ geolocation: { name: "geolocation" },
11943
+ notifications: { name: "notifications" },
11944
+ audioCapture: { name: "microphone" },
11945
+ videoCapture: { name: "camera" },
11946
+ durableStorage: { name: "persistent-storage" },
11947
+ midi: { name: "midi" },
11948
+ midiSysex: { name: "midi", sysex: true },
11949
+ wakeLockScreen: { name: "screen-wake-lock" }
11950
+ };
11951
+ function mapFirefoxPermissions(names) {
11952
+ return names.map((n) => {
11953
+ const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
11954
+ if (!d) {
11955
+ throw unsupported(`grant_permissions: permission '${n}' is not supported on Firefox (WebDriver BiDi permissions.setPermission has no measured equivalent). Supported on Firefox: ${Object.keys(FIREFOX_PERMISSION_DESCRIPTORS).join(", ")}.`);
11956
+ }
11957
+ return d;
11958
+ });
11959
+ }
11960
+ var trackedGrants = new WeakMap;
11961
+ function grantKey(origin, d) {
11962
+ return `${origin} ${JSON.stringify(d)}`;
11963
+ }
11964
+ async function restoreGrants(conn, grants) {
11965
+ const all = [...grants.values()];
11966
+ grants.clear();
11967
+ for (const g of all) {
11968
+ await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
11969
+ }
11970
+ }
11971
+ async function queryState(page, d) {
11972
+ try {
11973
+ const v = await page.evaluate(`navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`, { awaitPromise: true });
11974
+ return v === "granted" || v === "denied" ? v : "prompt";
11975
+ } catch {
11976
+ return "prompt";
11977
+ }
11978
+ }
11979
+ async function grantPermissionsFirefox(driver, args = {}) {
11980
+ validateGrantPermissionsArgs(args);
11981
+ const reset = args.reset === true;
11982
+ const permissions = args.permissions ?? [];
11983
+ const descriptors = mapFirefoxPermissions(permissions);
11984
+ const scope = scopeOf(driver, "grant_permissions");
11985
+ let grants = trackedGrants.get(driver);
11986
+ if (!grants) {
11987
+ grants = new Map;
11988
+ trackedGrants.set(driver, grants);
11989
+ }
11990
+ const tracked = grants;
11991
+ const page = await driver.page(args.target);
11992
+ try {
11993
+ const target = { id: page.info.id, url: page.info.url, title: page.info.title };
11994
+ return await scope.withBrowserConnection(async (conn) => {
11995
+ requireFirefox(conn, "browser.permissions");
11996
+ if (reset)
11997
+ await restoreGrants(conn, tracked);
11998
+ if (permissions.length === 0)
11999
+ return { reset: true, target };
12000
+ const origin = args.origin ?? originOf(page.info.url);
12001
+ if (!origin) {
12002
+ throw new Error(`grant_permissions: cannot derive an origin from the target tab's url (${JSON.stringify(page.info.url)}); pass 'origin' explicitly, e.g. origin:"https://example.com"`);
12003
+ }
12004
+ const pageIsOrigin = originOf(page.info.url) === origin;
12005
+ scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
12006
+ for (const d of descriptors) {
12007
+ const key = grantKey(origin, d);
12008
+ if (!tracked.has(key)) {
12009
+ tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
12010
+ }
12011
+ await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
12012
+ }
12013
+ return { granted: [...permissions], origin, ...reset ? { reset: true } : {}, target };
12014
+ });
12015
+ } finally {
12016
+ await page.release();
12017
+ }
12018
+ }
12019
+ var BIDI_BROWSER_TOOLS = {
12020
+ wait_for_download: waitForDownloadFirefox,
12021
+ grant_permissions: grantPermissionsFirefox
11470
12022
  };
11471
12023
 
11472
12024
  // src/firefox-tools.ts
@@ -11474,6 +12026,7 @@ var FIREFOX_TOOLS = {
11474
12026
  ...SHARED_TOOLS,
11475
12027
  ...BIDI_ONLY_TOOLS,
11476
12028
  ...LEASE_TOOLS,
12029
+ ...BIDI_BROWSER_TOOLS,
11477
12030
  extract_page: extractPage
11478
12031
  };
11479
12032
 
@@ -11604,14 +12157,15 @@ var TOOL_DOCS = {
11604
12157
  }
11605
12158
  },
11606
12159
  new_page: {
11607
- description: "Open a new browser tab via Target.createTarget and return {targetId,url}. Defaults to about:blank; navigation is not awaited here (use navigate_page to load and wait).",
12160
+ description: "Open a new browser tab via Target.createTarget and return {targetId,url}. The tab opens in the BACKGROUND (createTarget background:true; browsingContext.create background:true on Firefox), so the user's visible tab and keyboard focus stay put (on macOS the user's frontmost app is put back if the browser app came forward; CDP_RESTORE_FRONT_APP=0 turns that off); pass focus:true to open it in the foreground. Defaults to about:blank; navigation is not awaited here (use navigate_page to load and wait).",
11608
12161
  params: {
11609
12162
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11610
12163
  url: "URL to open in the new tab; defaults to about:blank.",
11611
12164
  endpoint: "Name of a CDP endpoint configured with CDP_ENDPOINTS / CDP_ENDPOINTS_FILE to open the tab on (Chrome only); default endpoint when omitted. Address the new tab later as 'endpoint:<name>/<targetId>'.",
11612
12165
  claim: "Claim the new tab atomically and return a lease token alongside {targetId,url}. Under CDP_REQUIRE_LEASE the tab is claimed and a lease returned even without claim:true; claim:true makes it an EXPLICIT lease that demands its token on every later call, even from this process. Default false.",
11613
12166
  label: "Agent label recorded on the lease when the tab is claimed; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
11614
- ttlMs: "How long a claimed lease survives without use before it is reclaimable. Defaults to CDP_LEASE_TTL_MS, else 900000 (15min); every checked call refreshes it. Ignored when not claiming."
12167
+ ttlMs: "How long a claimed lease survives without use before it is reclaimable. Defaults to CDP_LEASE_TTL_MS, else 900000 (15min); every checked call refreshes it. Ignored when not claiming.",
12168
+ focus: "Open the tab in the foreground, switching the user's visible tab and taking focus. Default false: the tab opens in the background."
11615
12169
  }
11616
12170
  },
11617
12171
  close_page: {
@@ -11622,10 +12176,11 @@ var TOOL_DOCS = {
11622
12176
  }
11623
12177
  },
11624
12178
  select_page: {
11625
- description: "Activate/focus a page target via Target.activateTarget and persist its bare targetId to the selected-state file (CDP_STATE_DIR/selected). Requires an explicit, resolvable target.",
12179
+ description: "Persist a page target's bare targetId to the selected-state file (CDP_STATE_DIR/selected) and return {selected,focused}. By default it does NOT raise the tab: the user's visible tab and window focus stay put. focus:true also activates it (Target.activateTarget; browsingContext.activate on Firefox), which was the old default. Requires an explicit, resolvable target.",
11626
12180
  params: {
11627
12181
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11628
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions."
12182
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
12183
+ focus: "Also raise the tab and take window focus (Target.activateTarget / browsingContext.activate). Default false: selection only."
11629
12184
  }
11630
12185
  },
11631
12186
  navigate_page: {
@@ -11755,7 +12310,7 @@ var TOOL_DOCS = {
11755
12310
  }
11756
12311
  },
11757
12312
  dispatch_mouse: {
11758
- description: "Dispatches one raw mouse event (move/down/up) at absolute viewport coordinates — the toolkit's lowest-level input primitive. Compose move/down/move/up calls yourself for anything click/drag's fixed sequences can't reach: canvas drag-painting, marquee/rubber-band selection, custom hit-testing widgets. Chrome-only: absent from tools/list under the Firefox backend, never present-and-throwing.",
12313
+ description: "Dispatches one raw mouse event (move/down/up) at absolute viewport coordinates — the toolkit's lowest-level input primitive. Compose move/down/move/up calls yourself for anything click/drag's fixed sequences can't reach: canvas drag-painting, marquee/rubber-band selection, custom hit-testing widgets. Works on Chrome and on Firefox 160 or newer (WebDriver BiDi: a press held by 'down' in one call is released by 'up' in a later call); an older Firefox gets an unsupported error naming the version.",
11759
12314
  params: {
11760
12315
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11761
12316
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11763,7 +12318,7 @@ var TOOL_DOCS = {
11763
12318
  x: "Viewport x-coordinate. Required every call — CDP has no 'current pointer position' to default from.",
11764
12319
  y: "Viewport y-coordinate. Required every call.",
11765
12320
  button: "Mouse button: 'left' (default), 'right', or 'middle'.",
11766
- clickCount: "Click-run length for a 'down' or 'up' event (2 = second half of a double-click, 3 = triple-click). Ignored for 'move'; defaults to 1.",
12321
+ clickCount: "Click-run length for a 'down' or 'up' event (2 = second half of a double-click, 3 = triple-click). Ignored for 'move'; defaults to 1. Ignored on Firefox (click counts follow native timing).",
11767
12322
  modifiers: "Modifier keys held for this one event, e.g. ['Shift']."
11768
12323
  }
11769
12324
  },
@@ -11788,7 +12343,7 @@ var TOOL_DOCS = {
11788
12343
  }
11789
12344
  },
11790
12345
  wait_for_download: {
11791
- description: "Wait for a file download to finish and return it as a real file on disk: {path,suggestedFilename,bytes,url,target}, written under the artifact dir's downloads/. ORDERING RULE, not optional: capture must be ARMED BEFORE the click that starts the download — call wait_for_download{arm:true} first (returns {armed:true,downloadPath,pending}), then click, then call again to collect the file. The download-behavior override is per-connection state Chrome REVERTS the moment the arming client disconnects, and an unarmed headless Chrome denies the download outright, so one triggered before arming is lost. SIDE EFFECT, browser-global: arming redirects EVERY download in this browser (all tabs, all origins) into the toolkit's downloads dir until this server exits — they no longer land in the user's normal Downloads folder. The arm lives on a connection this server holds open (an MCP-server capability): under the one-shot CLI the connection dies with the process and nothing is captured. Chrome-only (capability 'browser.downloads'): absent from tools/list under Firefox.",
12346
+ description: "Wait for a file download to finish and return it as a real file on disk: {path,suggestedFilename,bytes,url,target}, written under the artifact dir's downloads/. ORDERING RULE, not optional: capture must be ARMED BEFORE the click that starts the download — call wait_for_download{arm:true} first (returns {armed:true,downloadPath,pending}), then click, then call again to collect the file. The download-behavior override is per-connection state Chrome REVERTS the moment the arming client disconnects, and an unarmed headless Chrome denies the download outright, so one triggered before arming is lost. SIDE EFFECT, browser-global: arming redirects EVERY download in this browser (all tabs, all origins) into the toolkit's downloads dir until this server exits — they no longer land in the user's normal Downloads folder. The arm lives on a connection this server holds open (an MCP-server capability): under the one-shot CLI the connection dies with the process and nothing is captured. Capability 'browser.downloads': Chrome, and Firefox 160+ (an older Firefox is refused as unsupported). FIREFOX DIFFERS: every call arms, and a collecting call (no arm:true) RESTORES Firefox's normal download behavior when it returns or times out, so arm again before every later download.",
11792
12347
  params: {
11793
12348
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11794
12349
  target: "Names the tab for the lease check and the echoed target — a download is browser-scoped, so this does not pick which download is returned. Grammar: server instructions.",
@@ -11797,7 +12352,7 @@ var TOOL_DOCS = {
11797
12352
  }
11798
12353
  },
11799
12354
  grant_permissions: {
11800
- description: "Grant browser permissions for an origin up front, so a page asking for geolocation / notifications / clipboard gets an answer instead of a prompt no agent can click. 'permissions' takes CDP PermissionType values ('geolocation','notifications','clipboardReadWrite','camera',...); an unknown name is refused by Chrome, quoting the bad value. Returns {granted,origin,target}, or {reset:true,target} for a reset-only call. Grants are keyed by ORIGIN, not by tab: every tab on that origin is affected, including ones opened later. reset:true clears this server's previous grants first (or instead, when no permissions are given) — CDP's reset is not origin-scoped, so it clears them for every origin at once. The grant lives on a connection this server holds open and Chrome DISCARDS IT when that connection closes: an MCP-server capability, so under the one-shot CLI the grant dies with the process. Chrome-only (capability 'browser.permissions'): absent from tools/list under Firefox, never present-and-throwing.",
12355
+ description: "Grant browser permissions for an origin up front, so a page asking for geolocation / notifications / clipboard gets an answer instead of a prompt no agent can click. 'permissions' takes CDP PermissionType values ('geolocation','notifications','clipboardReadWrite','camera',...); an unknown name is refused by Chrome, quoting the bad value. Returns {granted,origin,target}, or {reset:true,target} for a reset-only call. Grants are keyed by ORIGIN, not by tab: every tab on that origin is affected, including ones opened later. reset:true clears this server's previous grants first (or instead, when no permissions are given) — CDP's reset is not origin-scoped, so it clears them for every origin at once. The grant lives on a connection this server holds open and Chrome DISCARDS IT when that connection closes: an MCP-server capability, so under the one-shot CLI the grant dies with the process. Capability 'browser.permissions': Chrome, and Firefox 160+ (an older Firefox is refused as unsupported). FIREFOX DIFFERS: only geolocation, notifications, audioCapture, videoCapture, durableStorage, midi, midiSysex, wakeLockScreen map to a Firefox permission (any other name, e.g. clipboardReadWrite, is refused as unsupported); Firefox stores grants in the profile, so this server undoes them on reset:true and at shutdown (back to the state the page reported before the grant, or 'prompt' for another origin).",
11801
12356
  params: {
11802
12357
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11803
12358
  target: "Also the origin source when 'origin' is omitted. Grammar: server instructions.",
@@ -11807,7 +12362,7 @@ var TOOL_DOCS = {
11807
12362
  }
11808
12363
  },
11809
12364
  fill: {
11810
- description: `Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector. Returns {filled,element,value}; element names the field (textbox "Email").`,
12365
+ description: `Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes, so it won't fire per-keypress handlers). Give exactly one of uid or selector. Returns {filled,element,value}; element names the field (textbox "Email"). On a background tab (Chrome), which gets no trusted keyboard input, the commit is verified and falls back in-page (execCommand insertText, else the native value setter plus input/change events); the result then carries inputPath. The tab is never raised.`,
11811
12366
  params: {
11812
12367
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11813
12368
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11817,7 +12372,7 @@ var TOOL_DOCS = {
11817
12372
  }
11818
12373
  },
11819
12374
  fill_form: {
11820
- description: "Fills multiple form fields in one call; each is focused, cleared, then set via Input.insertText (overwrites existing content, same as fill). Each entry in the non-empty 'fields' array takes exactly one of uid or selector plus a string value.",
12375
+ description: "Fills multiple form fields in one call; each is focused, cleared, then set via Input.insertText (overwrites existing content, same as fill). Each entry in the non-empty 'fields' array takes exactly one of uid or selector plus a string value. Background tab (Chrome): each field falls back in-page like fill, and inputPaths lists the path per field when any fell back.",
11821
12376
  params: {
11822
12377
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11823
12378
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11825,7 +12380,7 @@ var TOOL_DOCS = {
11825
12380
  }
11826
12381
  },
11827
12382
  type_text: {
11828
- description: "Focuses an element and appends text via Input.insertText without clearing first — closest primitive to typing, but still atomic (not per-character keystrokes). Give exactly one of uid or selector.",
12383
+ description: "Focuses an element and appends text via Input.insertText without clearing first: the closest primitive to typing, but still atomic (not per-character keystrokes). Give exactly one of uid or selector. Background tab (Chrome): falls back in-page like fill and reports inputPath.",
11829
12384
  params: {
11830
12385
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11831
12386
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11835,7 +12390,7 @@ var TOOL_DOCS = {
11835
12390
  }
11836
12391
  },
11837
12392
  press_key: {
11838
- description: "Dispatches a keyDown/keyUp pair for one key with optional modifiers. 'key' is a named key (Enter, Tab, Escape, ArrowDown, Backspace, etc.) or a single printable character — the named-key table is curated, with no F-keys, numpad, or IME support.",
12393
+ description: "Dispatches a keyDown/keyUp pair for one key with optional modifiers. 'key' is a named key (Enter, Tab, Escape, ArrowDown, Backspace, etc.) or a single printable character; the named-key table is curated, with no F-keys, numpad, or IME support. A background tab gets no trusted keys: the result then says delivered:false (nothing is faked). A click on the page first usually gives it focus so keys land.",
11839
12394
  params: {
11840
12395
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11841
12396
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11861,7 +12416,7 @@ var TOOL_DOCS = {
11861
12416
  format: "Image format, default png. quality applies only to jpeg.",
11862
12417
  quality: "JPEG quality 0-100, default 80; ignored for png.",
11863
12418
  fullPage: "Capture the full scrollable height (via Page.getLayoutMetrics), not just the viewport.",
11864
- scale: "Output-pixel multiplier for this capture only (0<scale<=8, default 1): output px = ceil(css px x scale x devicePixelRatio); the page is never told anything changed. Chrome only (screenshot.scale) — Firefox BiDi has no scale param, use emulate{deviceScaleFactor} then scale:1. A projection over 16384 device px/side is refused up front, naming the largest scale that fits.",
12419
+ scale: "Output-pixel multiplier for this capture only (0<scale<=8, default 1): output px = ceil(css px x scale x devicePixelRatio); the page is never told anything changed. Needs capability screenshot.scale: Chrome, and Firefox 160 or newer (an older Firefox: emulate{deviceScaleFactor} then scale:1). A projection over 16384 device px/side is refused up front, naming the largest scale that fits.",
11865
12420
  renderWidth: "Emulates this viewport width (CSS px, 1-16384) for one capture, then restores it. Required with renderHeight. Unlike scale, this changes what the page believes (media queries re-flow) — e.g. capture a responsive page at 1920x1080 from a differently-sized tab. Restore only works for an override this toolkit itself set; check result.renderRestored (false = still emulated, fix via emulate). Works on both backends (capability screenshot.renderSize).",
11866
12421
  renderHeight: "Emulates this viewport height (CSS px, 1-16384) for one capture. Required with renderWidth — a viewport is two numbers. A narrow renderWidth often reflows pages TALLER, which is the usual way a render-size capture trips the 16384px encode limit.",
11867
12422
  tile: "Whether to allow vertical-band stitching: omitted=AUTO (band only if a single shot wouldn't fit), false=never band (refuse instead), true=always band (Chrome-only capability). Banded output is PNG-only, can't returnBase64, and only bands on HEIGHT (oversized WIDTH is refused, not split). Bands are a faithful crop, but lazy/virtualized content the real viewport never scrolled to renders blank.",
@@ -11994,7 +12549,7 @@ var TOOL_DOCS = {
11994
12549
  maxWidth: "Caps the streamed frame width in px; also pins frame size if the viewport may change mid-recording.",
11995
12550
  maxHeight: "Caps the streamed frame height in px.",
11996
12551
  everyNthFrame: "Capture only every Nth repaint (1=every frame), to shrink spool size on a busy page; per-frame durations keep playback at wallclock speed either way.",
11997
- bringToFront: "Activate the tab (Page.bringToFront) before recording, default false. A backgrounded/occluded tab may never repaint, yielding a 0-frame recording."
12552
+ bringToFront: "Activate the tab (Page.bringToFront) before recording, default false. A backgrounded/occluded tab may never repaint, yielding a 0-frame recording. new_page opens tabs in the background, so a fresh tab needs this (or new_page focus:true) for a real frame rate."
11998
12553
  }
11999
12554
  },
12000
12555
  stop_screen_recording: {
@@ -12064,7 +12619,8 @@ var TOOL_DOCS = {
12064
12619
  targetId: "Exact target id (not a selector) of an already-open page to claim instead of opening one. Back-compat only; prefer target, which also accepts an exact id. Mutually exclusive with target.",
12065
12620
  url: "When opening a fresh tab, navigate it here. Ignored when target or targetId is given.",
12066
12621
  label: "Agent label recorded on the lease; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
12067
- ttlMs: "How long the lease survives without use before it is reclaimable. Defaults to CDP_LEASE_TTL_MS, else 900000 (15min); every checked call refreshes it."
12622
+ ttlMs: "How long the lease survives without use before it is reclaimable. Defaults to CDP_LEASE_TTL_MS, else 900000 (15min); every checked call refreshes it.",
12623
+ focus: "Fresh-tab mode only: open the tab in the foreground and take focus. Default false: the tab opens in the background. Ignored on takeover (target/targetId), which never raises the tab."
12068
12624
  }
12069
12625
  },
12070
12626
  release_page: {
@@ -12195,7 +12751,7 @@ function toolAnnotations(name) {
12195
12751
  }
12196
12752
 
12197
12753
  // src/version.ts
12198
- var VERSION = "3.2.0";
12754
+ var VERSION = "3.4.0";
12199
12755
 
12200
12756
  // src/mcp.ts
12201
12757
  function isDirectRun() {
@@ -12482,7 +13038,7 @@ async function runTool(name, args) {
12482
13038
  }
12483
13039
  });
12484
13040
  }
12485
- async function run2(argv) {
13041
+ async function run3(argv) {
12486
13042
  const serve = parseServeOptions(argv);
12487
13043
  auditCoverage();
12488
13044
  markLongLivedProcess();
@@ -12543,7 +13099,7 @@ async function run2(argv) {
12543
13099
  console.error(`[cdp-toolkit] MCP server v${VERSION} listening on streamable-http port ${listener.port} (http://${serve.host}:${listener.port}/), browser=${BROWSER}${FIREFOX_ENDPOINT ? ` (attach ${FIREFOX_ENDPOINT})` : ""}, ${AVAILABILITY.available.length} tools available, ${LISTING.length} listed (CDP_TOOL_PROFILE=${PROFILE.label}), CDP_BASE=${BASE}${endpointsLogSuffix()}`);
12544
13100
  }
12545
13101
  if (isDirectRun()) {
12546
- run2(process.argv.slice(2)).catch((err) => {
13102
+ run3(process.argv.slice(2)).catch((err) => {
12547
13103
  console.error(`[cdp-toolkit] ${err instanceof Error ? err.message : String(err)}`);
12548
13104
  process.exit(1);
12549
13105
  });