cdp-toolkit 3.3.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}`;
@@ -3506,6 +3553,9 @@ async function pickContext(conn, contexts, selector) {
3506
3553
  return exact;
3507
3554
  throw driverError2("no-such-target", `no context matching '${selector}'`);
3508
3555
  }
3556
+ function bidiCreateTabParams(opts) {
3557
+ return { type: "tab", background: opts?.focus !== true };
3558
+ }
3509
3559
 
3510
3560
  class BidiBrowserDriver {
3511
3561
  endpoint;
@@ -3532,12 +3582,13 @@ class BidiBrowserDriver {
3532
3582
  conn.release();
3533
3583
  }
3534
3584
  }
3535
- async newPage(url) {
3585
+ async newPage(url, opts) {
3536
3586
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3537
3587
  try {
3538
- const { context } = await conn.send("browsingContext.create", { type: "tab" }).catch((e) => {
3588
+ const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
3539
3589
  throw mapBidiError(e);
3540
3590
  });
3591
+ const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
3541
3592
  if (url)
3542
3593
  await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
3543
3594
  throw mapBidiError(e);
@@ -3550,9 +3601,9 @@ class BidiBrowserDriver {
3550
3601
  async closePage(id) {
3551
3602
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3552
3603
  try {
3553
- await conn.send("browsingContext.close", { context: id }).catch((e) => {
3604
+ await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
3554
3605
  throw mapBidiError(e);
3555
- });
3606
+ }));
3556
3607
  return { success: true };
3557
3608
  } finally {
3558
3609
  conn.release();
@@ -3736,6 +3787,7 @@ function createFirefoxDriverForEndpoint(wsUrl, opts) {
3736
3787
  }
3737
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;
3738
3789
  var init_driver2 = __esm(() => {
3790
+ init_frontApp();
3739
3791
  init_driver();
3740
3792
  init_leases();
3741
3793
  init_origins();
@@ -4077,8 +4129,11 @@ var init_driver2 = __esm(() => {
4077
4129
  await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
4078
4130
  return;
4079
4131
  }
4080
- const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
4081
- 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
+ }
4082
4137
  await this.sendKeys(value);
4083
4138
  }
4084
4139
  async typeText(loc, text) {
@@ -4486,6 +4541,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
4486
4541
  // src/cdp/driver.ts
4487
4542
  init_client();
4488
4543
  init_session();
4544
+ init_frontApp();
4489
4545
  init_leases();
4490
4546
  init_endpoints();
4491
4547
  init_activity();
@@ -4663,6 +4719,47 @@ async function centerOf(conn, objectId) {
4663
4719
  throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
4664
4720
  return result.value;
4665
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
+ }
4666
4763
  async function focusElement(conn, objectId) {
4667
4764
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
4668
4765
  }
@@ -4677,10 +4774,12 @@ async function awaitScrollSettle(conn) {
4677
4774
  }
4678
4775
  async function setValueOnObject(conn, objectId, value, sendInput) {
4679
4776
  await focusElement(conn, objectId);
4680
- const fn = "function(){if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}}";
4681
- await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
4682
- if (value.length)
4683
- 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";
4684
4783
  }
4685
4784
  var NAMED_KEYS = {
4686
4785
  enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
@@ -5228,13 +5327,12 @@ class CdpPageDriver {
5228
5327
  }
5229
5328
  async setValue(loc, value) {
5230
5329
  const { objectId } = await resolveElementLocator(this.conn, loc);
5231
- 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));
5232
5331
  }
5233
5332
  async typeText(loc, text) {
5234
5333
  const { objectId } = await resolveElementLocator(this.conn, loc);
5235
5334
  await focusElement(this.conn, objectId);
5236
- if (text.length)
5237
- await this.dispatchInput("Input.insertText", { text });
5335
+ return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
5238
5336
  }
5239
5337
  async pressKey(press) {
5240
5338
  const spec = resolveKey(press.key);
@@ -5249,8 +5347,10 @@ class CdpPageDriver {
5249
5347
  const down = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
5250
5348
  if (spec.text && !suppressText)
5251
5349
  down.text = spec.text;
5252
- await this.dispatchInput("Input.dispatchKeyEvent", down);
5253
- 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
+ });
5254
5354
  }
5255
5355
  async setFiles(loc, files) {
5256
5356
  const { objectId } = await resolveElementLocator(this.conn, loc);
@@ -5627,7 +5727,7 @@ function noSuchTarget(e) {
5627
5727
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
5628
5728
  }
5629
5729
  var NEW_TARGET_SETTLE_MS = 2000;
5630
- async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5730
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, opts = {}) {
5631
5731
  const changed = new Set;
5632
5732
  let id = "";
5633
5733
  let wake;
@@ -5643,7 +5743,8 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5643
5743
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5644
5744
  return;
5645
5745
  });
5646
- 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);
5647
5748
  if (!targetId)
5648
5749
  throw driverError("page-error", "Target.createTarget returned no targetId");
5649
5750
  id = targetId;
@@ -5673,15 +5774,15 @@ class CdpBrowserDriver {
5673
5774
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
5674
5775
  return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
5675
5776
  }
5676
- async newPage(url) {
5777
+ async newPage(url, opts) {
5677
5778
  return withBrowserConn(async (conn) => {
5678
- 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 });
5679
5780
  return { id: targetId, url: url ?? "about:blank", title: "" };
5680
5781
  });
5681
5782
  }
5682
5783
  async closePage(id) {
5683
5784
  return withBrowserConn(async (conn) => {
5684
- const res = await conn.send("Target.closeTarget", { targetId: id });
5785
+ const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
5685
5786
  if (res.success !== false)
5686
5787
  beaconSessions.drop(beaconKey(id));
5687
5788
  return { success: res.success ?? true };
@@ -6351,7 +6452,6 @@ init_workers();
6351
6452
  init_frames();
6352
6453
  init_endpoints();
6353
6454
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
6354
- var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
6355
6455
 
6356
6456
  class SharedToolError extends Error {
6357
6457
  }
@@ -6510,7 +6610,7 @@ async function listPagesOne(driver, args = {}) {
6510
6610
  }
6511
6611
  async function newPage(driver, args = {}) {
6512
6612
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
6513
- 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 });
6514
6614
  const explicit = args.claim === true;
6515
6615
  if (!explicit && !requireLease())
6516
6616
  return { targetId: p.id, url: p.url };
@@ -6533,16 +6633,17 @@ async function closePage(driver, args) {
6533
6633
  return { closed: p.id, success: true, ...released.released ? { leaseReleased: true } : {} };
6534
6634
  }
6535
6635
  async function writeSelectedFile(id) {
6536
- await mkdir5(STATE_DIR, { recursive: true });
6537
- 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");
6538
6639
  }
6539
6640
  async function selectPage(driver, args) {
6540
6641
  if (args.target === undefined || args.target === "")
6541
6642
  throw new SharedToolError("select_page requires an explicit target");
6542
6643
  const p = await resolvePage(driver, args.target);
6543
- const activated = await driver.activatePage(p.id);
6544
- await writeSelectedFile(activated.id);
6545
- 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 };
6546
6647
  }
6547
6648
  function toLegacyWaitedFor(w) {
6548
6649
  if (w === "committed")
@@ -6901,14 +7002,17 @@ async function drag(driver, args) {
6901
7002
  };
6902
7003
  });
6903
7004
  }
7005
+ function inputPathField(path) {
7006
+ return path && path !== "trusted" ? { inputPath: path } : {};
7007
+ }
6904
7008
  async function fill(driver, args) {
6905
7009
  if (typeof args.value !== "string")
6906
7010
  throw new SharedToolError("fill requires a string { value }");
6907
7011
  const loc = locatorOf(args);
6908
7012
  return withPage2(driver, args.target, async (page) => {
6909
7013
  const element = await describeElement(page, loc);
6910
- await page.setValue(loc, args.value);
6911
- 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) };
6912
7016
  });
6913
7017
  }
6914
7018
  async function fillForm(driver, args) {
@@ -6917,15 +7021,16 @@ async function fillForm(driver, args) {
6917
7021
  return withPage2(driver, args.target, async (page) => {
6918
7022
  let filled = 0;
6919
7023
  const elements = [];
7024
+ const paths = [];
6920
7025
  for (const f of args.fields) {
6921
7026
  if (typeof f.value !== "string")
6922
7027
  throw new SharedToolError("each fill_form field requires a string value");
6923
7028
  const loc = locatorOf(f);
6924
7029
  elements.push(await describeElement(page, loc) ?? null);
6925
- await page.setValue(loc, f.value);
7030
+ paths.push(await page.setValue(loc, f.value) || "trusted");
6926
7031
  filled++;
6927
7032
  }
6928
- return { filled, fields: args.fields.length, elements };
7033
+ return { filled, fields: args.fields.length, elements, ...paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {} };
6929
7034
  });
6930
7035
  }
6931
7036
  async function typeText(driver, args) {
@@ -6934,8 +7039,8 @@ async function typeText(driver, args) {
6934
7039
  const loc = locatorOf(args);
6935
7040
  return withPage2(driver, args.target, async (page) => {
6936
7041
  const element = await describeElement(page, loc);
6937
- await page.typeText(loc, args.text);
6938
- 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) };
6939
7044
  });
6940
7045
  }
6941
7046
  async function pressKey(driver, args) {
@@ -6943,7 +7048,15 @@ async function pressKey(driver, args) {
6943
7048
  throw new SharedToolError("press_key requires a non-empty { key }");
6944
7049
  const modifiers = args.modifiers ?? [];
6945
7050
  return withPage2(driver, args.target, async (page) => {
6946
- 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
+ }
6947
7060
  return { pressed: args.key, modifiers };
6948
7061
  });
6949
7062
  }
@@ -7211,7 +7324,7 @@ async function claimPage(driver, args = {}) {
7211
7324
  url = existing.url;
7212
7325
  opened = false;
7213
7326
  } else {
7214
- 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 });
7215
7328
  targetId = page.id;
7216
7329
  url = page.url;
7217
7330
  opened = true;
@@ -7711,7 +7824,7 @@ init_client();
7711
7824
  import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7712
7825
  import { join as join6 } from "node:path";
7713
7826
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7714
- var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7827
+ var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7715
7828
  var DEFAULT_CATEGORIES = [
7716
7829
  "devtools.timeline",
7717
7830
  "blink.user_timing",
@@ -7727,7 +7840,7 @@ function shortId(id) {
7727
7840
  return id.slice(0, 8);
7728
7841
  }
7729
7842
  function stateFilePath() {
7730
- return join6(STATE_DIR2, "trace-state.json");
7843
+ return join6(STATE_DIR, "trace-state.json");
7731
7844
  }
7732
7845
  function bufferTraceData(conn, sink) {
7733
7846
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7772,7 +7885,7 @@ async function performanceStartTrace(args = {}) {
7772
7885
  throw err;
7773
7886
  }
7774
7887
  liveTraces.set(target.id, { conn, target, events, startedAt: Date.now() });
7775
- await mkdir7(STATE_DIR2, { recursive: true });
7888
+ await mkdir7(STATE_DIR, { recursive: true });
7776
7889
  const state = {
7777
7890
  targetId: target.id,
7778
7891
  url: target.url,
@@ -8101,7 +8214,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
8101
8214
  outPath
8102
8215
  ];
8103
8216
  }
8104
- function run(bin, args) {
8217
+ function run2(bin, args) {
8105
8218
  return new Promise((resolve, reject) => {
8106
8219
  const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
8107
8220
  let stdout = "";
@@ -8123,7 +8236,7 @@ async function probeEncoder() {
8123
8236
  encoderProbe = (async () => {
8124
8237
  let res;
8125
8238
  try {
8126
- res = await run(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
8239
+ res = await run2(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
8127
8240
  } catch (err) {
8128
8241
  throw new CdpError(`${FFMPEG_MISSING} (${err.message})`);
8129
8242
  }
@@ -8132,7 +8245,7 @@ async function probeEncoder() {
8132
8245
  const choice = selectEncoder(`${res.stdout}
8133
8246
  ${res.stderr}`);
8134
8247
  const output = async (args) => {
8135
- const r = await run(FFMPEG_BIN, args).catch(() => {
8248
+ const r = await run2(FFMPEG_BIN, args).catch(() => {
8136
8249
  return;
8137
8250
  });
8138
8251
  return r && r.code === 0 ? `${r.stdout}
@@ -8305,7 +8418,7 @@ async function stopScreenRecording(args = {}) {
8305
8418
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
8306
8419
  let res;
8307
8420
  try {
8308
- res = await run(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8421
+ res = await run2(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8309
8422
  } catch (err) {
8310
8423
  throw new CdpError(`${FFMPEG_MISSING} Spooled frames kept at ${rec.spoolDir}. (${err.message})`);
8311
8424
  }
@@ -9398,7 +9511,7 @@ var MANIFEST = [
9398
9511
  },
9399
9512
  {
9400
9513
  name: "new_page",
9401
- 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.",
9402
9515
  inputSchema: {
9403
9516
  type: "object",
9404
9517
  properties: {
@@ -9425,6 +9538,10 @@ var MANIFEST = [
9425
9538
  ttlMs: {
9426
9539
  type: "number",
9427
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)."
9428
9545
  }
9429
9546
  },
9430
9547
  required: [],
@@ -9454,7 +9571,7 @@ var MANIFEST = [
9454
9571
  },
9455
9572
  {
9456
9573
  name: "select_page",
9457
- 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.",
9458
9575
  inputSchema: {
9459
9576
  type: "object",
9460
9577
  properties: {
@@ -9465,6 +9582,10 @@ var MANIFEST = [
9465
9582
  target: {
9466
9583
  type: "string",
9467
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)."
9468
9589
  }
9469
9590
  },
9470
9591
  required: [
@@ -11056,7 +11177,7 @@ var MANIFEST = [
11056
11177
  },
11057
11178
  {
11058
11179
  name: "claim_page",
11059
- 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.",
11060
11181
  inputSchema: {
11061
11182
  type: "object",
11062
11183
  properties: {
@@ -11079,6 +11200,10 @@ var MANIFEST = [
11079
11200
  ttlMs: {
11080
11201
  type: "number",
11081
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)."
11082
11207
  }
11083
11208
  },
11084
11209
  required: [],
@@ -12032,14 +12157,15 @@ var TOOL_DOCS = {
12032
12157
  }
12033
12158
  },
12034
12159
  new_page: {
12035
- 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).",
12036
12161
  params: {
12037
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.",
12038
12163
  url: "URL to open in the new tab; defaults to about:blank.",
12039
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>'.",
12040
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.",
12041
12166
  label: "Agent label recorded on the lease when the tab is claimed; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
12042
- 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."
12043
12169
  }
12044
12170
  },
12045
12171
  close_page: {
@@ -12050,10 +12176,11 @@ var TOOL_DOCS = {
12050
12176
  }
12051
12177
  },
12052
12178
  select_page: {
12053
- 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.",
12054
12180
  params: {
12055
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.",
12056
- 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."
12057
12184
  }
12058
12185
  },
12059
12186
  navigate_page: {
@@ -12235,7 +12362,7 @@ var TOOL_DOCS = {
12235
12362
  }
12236
12363
  },
12237
12364
  fill: {
12238
- 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.`,
12239
12366
  params: {
12240
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.",
12241
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.",
@@ -12245,7 +12372,7 @@ var TOOL_DOCS = {
12245
12372
  }
12246
12373
  },
12247
12374
  fill_form: {
12248
- 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.",
12249
12376
  params: {
12250
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.",
12251
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.",
@@ -12253,7 +12380,7 @@ var TOOL_DOCS = {
12253
12380
  }
12254
12381
  },
12255
12382
  type_text: {
12256
- 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.",
12257
12384
  params: {
12258
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.",
12259
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.",
@@ -12263,7 +12390,7 @@ var TOOL_DOCS = {
12263
12390
  }
12264
12391
  },
12265
12392
  press_key: {
12266
- 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.",
12267
12394
  params: {
12268
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.",
12269
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.",
@@ -12422,7 +12549,7 @@ var TOOL_DOCS = {
12422
12549
  maxWidth: "Caps the streamed frame width in px; also pins frame size if the viewport may change mid-recording.",
12423
12550
  maxHeight: "Caps the streamed frame height in px.",
12424
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.",
12425
- 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."
12426
12553
  }
12427
12554
  },
12428
12555
  stop_screen_recording: {
@@ -12492,7 +12619,8 @@ var TOOL_DOCS = {
12492
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.",
12493
12620
  url: "When opening a fresh tab, navigate it here. Ignored when target or targetId is given.",
12494
12621
  label: "Agent label recorded on the lease; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
12495
- 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."
12496
12624
  }
12497
12625
  },
12498
12626
  release_page: {
@@ -12623,7 +12751,7 @@ function toolAnnotations(name) {
12623
12751
  }
12624
12752
 
12625
12753
  // src/version.ts
12626
- var VERSION = "3.3.0";
12754
+ var VERSION = "3.4.0";
12627
12755
 
12628
12756
  // src/mcp.ts
12629
12757
  function isDirectRun() {
@@ -12910,7 +13038,7 @@ async function runTool(name, args) {
12910
13038
  }
12911
13039
  });
12912
13040
  }
12913
- async function run2(argv) {
13041
+ async function run3(argv) {
12914
13042
  const serve = parseServeOptions(argv);
12915
13043
  auditCoverage();
12916
13044
  markLongLivedProcess();
@@ -12971,7 +13099,7 @@ async function run2(argv) {
12971
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()}`);
12972
13100
  }
12973
13101
  if (isDirectRun()) {
12974
- run2(process.argv.slice(2)).catch((err) => {
13102
+ run3(process.argv.slice(2)).catch((err) => {
12975
13103
  console.error(`[cdp-toolkit] ${err instanceof Error ? err.message : String(err)}`);
12976
13104
  process.exit(1);
12977
13105
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdp-toolkit",
3
- "version": "3.3.0",
3
+ "version": "3.4.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",