cdp-toolkit 3.3.0 → 3.5.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
@@ -323,6 +323,9 @@ function leaseTtlMs() {
323
323
  function markLongLivedProcess(value = true) {
324
324
  longLived = value;
325
325
  }
326
+ function isLongLivedProcess() {
327
+ return longLived;
328
+ }
326
329
  function requireLease() {
327
330
  if (!longLived)
328
331
  return false;
@@ -687,7 +690,7 @@ async function originIndex(backend, liveIds) {
687
690
  return index;
688
691
  }
689
692
  async function newTrackedPage(driver, backend, opts = {}) {
690
- const page = await driver.newPage(opts.url);
693
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
691
694
  await recordOrigin(backend, page.id, { label: opts.label });
692
695
  return page;
693
696
  }
@@ -1001,6 +1004,165 @@ var init_session = __esm(() => {
1001
1004
  init_endpoint();
1002
1005
  });
1003
1006
 
1007
+ // src/cdp/hiddenTabs.ts
1008
+ function hiddenTabsRequested() {
1009
+ return TRUTHY.has((process.env.CDP_HIDDEN_TABS ?? "").trim().toLowerCase());
1010
+ }
1011
+ function hiddenTabsMax() {
1012
+ const raw = Number(process.env.CDP_HIDDEN_TABS_MAX);
1013
+ return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : DEFAULT_HIDDEN_TABS_MAX;
1014
+ }
1015
+
1016
+ class HiddenTabOwner {
1017
+ deps;
1018
+ conn;
1019
+ connecting;
1020
+ tabs = new Map;
1021
+ reserved = 0;
1022
+ constructor(deps) {
1023
+ this.deps = deps;
1024
+ }
1025
+ sweep() {
1026
+ if (this.conn && !this.conn.isOpen) {
1027
+ this.conn = undefined;
1028
+ this.tabs.clear();
1029
+ }
1030
+ }
1031
+ has(id) {
1032
+ this.sweep();
1033
+ return this.tabs.has(id);
1034
+ }
1035
+ ids() {
1036
+ this.sweep();
1037
+ return [...this.tabs.keys()];
1038
+ }
1039
+ async owner() {
1040
+ this.sweep();
1041
+ if (this.conn)
1042
+ return this.conn;
1043
+ if (!this.connecting) {
1044
+ this.connecting = (async () => {
1045
+ const conn = await this.deps.connect();
1046
+ conn.on("Target.targetDestroyed", (params) => {
1047
+ const id = params.targetId;
1048
+ if (typeof id === "string")
1049
+ this.tabs.delete(id);
1050
+ });
1051
+ this.conn = conn;
1052
+ return conn;
1053
+ })().finally(() => {
1054
+ this.connecting = undefined;
1055
+ });
1056
+ }
1057
+ return this.connecting;
1058
+ }
1059
+ async create(url) {
1060
+ this.sweep();
1061
+ const max = (this.deps.max ?? hiddenTabsMax)();
1062
+ if (this.tabs.size + this.reserved >= max)
1063
+ throw new HiddenTabCapError(max, [...this.tabs.keys()]);
1064
+ this.reserved++;
1065
+ try {
1066
+ const conn = await this.owner();
1067
+ const id = await this.deps.createSettled(conn, url, { hidden: true });
1068
+ try {
1069
+ const { sessionId } = await conn.send("Target.attachToTarget", { targetId: id, flatten: true }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
1070
+ const dpr = await conn.send("Runtime.evaluate", { expression: "devicePixelRatio", returnByValue: true }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).then((r) => r.result?.value).catch(() => {
1071
+ return;
1072
+ });
1073
+ await conn.send("Emulation.setDeviceMetricsOverride", {
1074
+ width: HIDDEN_TAB_VIEWPORT.width,
1075
+ height: HIDDEN_TAB_VIEWPORT.height,
1076
+ deviceScaleFactor: typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0 ? dpr : FALLBACK_DEVICE_SCALE_FACTOR,
1077
+ mobile: false
1078
+ }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
1079
+ this.tabs.set(id, sessionId);
1080
+ return id;
1081
+ } catch (e) {
1082
+ await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
1083
+ return;
1084
+ });
1085
+ throw e;
1086
+ }
1087
+ } finally {
1088
+ this.reserved--;
1089
+ }
1090
+ }
1091
+ async close(id) {
1092
+ this.sweep();
1093
+ const conn = this.conn;
1094
+ const held = this.tabs.delete(id);
1095
+ if (!conn || !held)
1096
+ return { success: false };
1097
+ const res = await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
1098
+ return { success: res.success ?? true };
1099
+ }
1100
+ async dispose() {
1101
+ const conn = this.conn;
1102
+ const ids = [...this.tabs.keys()];
1103
+ this.tabs.clear();
1104
+ this.conn = undefined;
1105
+ if (!conn)
1106
+ return;
1107
+ if (conn.isOpen) {
1108
+ await Promise.all(ids.map((targetId) => conn.send("Target.closeTarget", { targetId }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
1109
+ return;
1110
+ })));
1111
+ }
1112
+ conn.close();
1113
+ }
1114
+ }
1115
+ function hiddenTabOwner(base, deps) {
1116
+ let owner = owners.get(base);
1117
+ if (!owner) {
1118
+ owner = new HiddenTabOwner(deps());
1119
+ owners.set(base, owner);
1120
+ }
1121
+ return owner;
1122
+ }
1123
+ function existingHiddenTabOwner(base) {
1124
+ return owners.get(base);
1125
+ }
1126
+ function markHiddenTargets(base, targets) {
1127
+ const owner = owners.get(base);
1128
+ if (!owner)
1129
+ return targets;
1130
+ const hidden = new Set(owner.ids());
1131
+ if (hidden.size === 0)
1132
+ return targets;
1133
+ const visible = [];
1134
+ const marked = [];
1135
+ for (const t of targets) {
1136
+ if (hidden.has(t.id))
1137
+ marked.push({ ...t, type: "page", hidden: true });
1138
+ else
1139
+ visible.push(t);
1140
+ }
1141
+ return marked.length ? [...visible, ...marked] : targets;
1142
+ }
1143
+ async function disposeHiddenTabs() {
1144
+ const all = [...owners.values()];
1145
+ owners.clear();
1146
+ await Promise.all(all.map((o) => o.dispose()));
1147
+ }
1148
+ var DEFAULT_HIDDEN_TABS_MAX = 20, HIDDEN_TAB_VIEWPORT, FALLBACK_DEVICE_SCALE_FACTOR = 2, OWNER_COMMAND_TIMEOUT_MS = 5000, TRUTHY, HiddenTabCapError, owners;
1149
+ var init_hiddenTabs = __esm(() => {
1150
+ HIDDEN_TAB_VIEWPORT = { width: 1280, height: 800 };
1151
+ TRUTHY = new Set(["1", "true", "yes", "on"]);
1152
+ HiddenTabCapError = class HiddenTabCapError extends Error {
1153
+ max;
1154
+ openIds;
1155
+ code = "page-error";
1156
+ constructor(max, openIds) {
1157
+ super(`hidden-tab cap reached: ${openIds.length} hidden tabs are open (CDP_HIDDEN_TABS_MAX=${max}). ` + `Close one with close_page (open hidden tabs, oldest first: ${openIds.join(", ")}), ` + `or pass focus:true to open a visible tab instead.`);
1158
+ this.max = max;
1159
+ this.openIds = openIds;
1160
+ this.name = "HiddenTabCapError";
1161
+ }
1162
+ };
1163
+ owners = new Map;
1164
+ });
1165
+
1004
1166
  // src/client.ts
1005
1167
  class CdpConnection {
1006
1168
  wsUrl;
@@ -1119,6 +1281,9 @@ class CdpConnection {
1119
1281
  });
1120
1282
  });
1121
1283
  }
1284
+ get isOpen() {
1285
+ return !this.closed && this.ws !== undefined;
1286
+ }
1122
1287
  close() {
1123
1288
  this.closed = true;
1124
1289
  this.rejectAll(new CdpError("closed by caller"));
@@ -1147,11 +1312,11 @@ async function getTargetsOverBrowserWs() {
1147
1312
  async function listTargets() {
1148
1313
  const base = currentEndpoint().base;
1149
1314
  if (knownTransports.get(base) === "browser-ws")
1150
- return getTargetsOverBrowserWs();
1315
+ return markHiddenTargets(base, await getTargetsOverBrowserWs());
1151
1316
  try {
1152
1317
  const listing = await httpJson("/json/list");
1153
1318
  knownTransports.set(base, "http");
1154
- return listing;
1319
+ return markHiddenTargets(base, listing);
1155
1320
  } catch (httpError) {
1156
1321
  const detected = await detectEndpoint().catch(() => {
1157
1322
  return;
@@ -1162,7 +1327,7 @@ async function listTargets() {
1162
1327
  throw httpError;
1163
1328
  });
1164
1329
  knownTransports.set(base, "browser-ws");
1165
- return targets;
1330
+ return markHiddenTargets(base, targets);
1166
1331
  }
1167
1332
  }
1168
1333
  async function browserWsUrl() {
@@ -1275,6 +1440,7 @@ var init_client = __esm(() => {
1275
1440
  init_frames();
1276
1441
  init_endpoint();
1277
1442
  init_session();
1443
+ init_hiddenTabs();
1278
1444
  init_session();
1279
1445
  BASE = (() => {
1280
1446
  try {
@@ -1297,6 +1463,53 @@ var init_client = __esm(() => {
1297
1463
  knownTransports = new Map;
1298
1464
  });
1299
1465
 
1466
+ // src/frontApp.ts
1467
+ import { execFile } from "node:child_process";
1468
+ function run(cmd, args) {
1469
+ return new Promise((resolve) => {
1470
+ execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
1471
+ });
1472
+ }
1473
+ function restoreFrontAppEnabled(platform = process.platform) {
1474
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
1475
+ }
1476
+ async function keepFrontApp(fn, opts = {}) {
1477
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
1478
+ if (!enabled)
1479
+ return fn();
1480
+ const ops = opts.ops ?? macFrontAppOps;
1481
+ const before = await ops.front().catch(() => null);
1482
+ const result = await fn();
1483
+ if (before === null)
1484
+ return result;
1485
+ const fix = async () => {
1486
+ const now = await ops.front().catch(() => null);
1487
+ if (now !== null && now !== before)
1488
+ await ops.setFront(before).catch(() => {
1489
+ return;
1490
+ });
1491
+ };
1492
+ await fix();
1493
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
1494
+ await fix();
1495
+ return result;
1496
+ }
1497
+ var macFrontAppOps;
1498
+ var init_frontApp = __esm(() => {
1499
+ macFrontAppOps = {
1500
+ async front() {
1501
+ const asn = (await run("lsappinfo", ["front"])).trim();
1502
+ if (!asn)
1503
+ return null;
1504
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
1505
+ return m ? Number(m[1]) : null;
1506
+ },
1507
+ async setFront(pid) {
1508
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
1509
+ }
1510
+ };
1511
+ });
1512
+
1300
1513
  // src/activity.ts
1301
1514
  function dispatchKey(backend, targetId) {
1302
1515
  return `${backend}:${targetId}`;
@@ -3506,6 +3719,9 @@ async function pickContext(conn, contexts, selector) {
3506
3719
  return exact;
3507
3720
  throw driverError2("no-such-target", `no context matching '${selector}'`);
3508
3721
  }
3722
+ function bidiCreateTabParams(opts) {
3723
+ return { type: "tab", background: opts?.focus !== true };
3724
+ }
3509
3725
 
3510
3726
  class BidiBrowserDriver {
3511
3727
  endpoint;
@@ -3532,12 +3748,13 @@ class BidiBrowserDriver {
3532
3748
  conn.release();
3533
3749
  }
3534
3750
  }
3535
- async newPage(url) {
3751
+ async newPage(url, opts) {
3536
3752
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3537
3753
  try {
3538
- const { context } = await conn.send("browsingContext.create", { type: "tab" }).catch((e) => {
3754
+ const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
3539
3755
  throw mapBidiError(e);
3540
3756
  });
3757
+ const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
3541
3758
  if (url)
3542
3759
  await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
3543
3760
  throw mapBidiError(e);
@@ -3550,9 +3767,9 @@ class BidiBrowserDriver {
3550
3767
  async closePage(id) {
3551
3768
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3552
3769
  try {
3553
- await conn.send("browsingContext.close", { context: id }).catch((e) => {
3770
+ await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
3554
3771
  throw mapBidiError(e);
3555
- });
3772
+ }));
3556
3773
  return { success: true };
3557
3774
  } finally {
3558
3775
  conn.release();
@@ -3736,6 +3953,7 @@ function createFirefoxDriverForEndpoint(wsUrl, opts) {
3736
3953
  }
3737
3954
  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
3955
  var init_driver2 = __esm(() => {
3956
+ init_frontApp();
3739
3957
  init_driver();
3740
3958
  init_leases();
3741
3959
  init_origins();
@@ -4077,8 +4295,11 @@ var init_driver2 = __esm(() => {
4077
4295
  await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
4078
4296
  return;
4079
4297
  }
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);
4298
+ 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';}";
4299
+ const state = await this.callFunctionValue(clear, [], ref);
4300
+ if (state === "disabled" || state === "readonly") {
4301
+ throw driverError2("page-error", `cannot fill a ${state} field: it was left unchanged`);
4302
+ }
4082
4303
  await this.sendKeys(value);
4083
4304
  }
4084
4305
  async typeText(loc, text) {
@@ -4486,7 +4707,9 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
4486
4707
  // src/cdp/driver.ts
4487
4708
  init_client();
4488
4709
  init_session();
4710
+ init_frontApp();
4489
4711
  init_leases();
4712
+ init_hiddenTabs();
4490
4713
  init_endpoints();
4491
4714
  init_activity();
4492
4715
 
@@ -4663,6 +4886,47 @@ async function centerOf(conn, objectId) {
4663
4886
  throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
4664
4887
  return result.value;
4665
4888
  }
4889
+ 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);}";
4890
+ 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);});}";
4891
+ 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';}";
4892
+ async function insertTextVerified(conn, objectId, text, sendInput) {
4893
+ const call = async (fn, args = [], awaitPromise = false) => {
4894
+ const { result, exceptionDetails } = await conn.send("Runtime.callFunctionOn", {
4895
+ objectId,
4896
+ functionDeclaration: fn,
4897
+ arguments: args.map((value) => ({ value })),
4898
+ returnByValue: true,
4899
+ awaitPromise
4900
+ });
4901
+ if (exceptionDetails)
4902
+ throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
4903
+ return result?.value;
4904
+ };
4905
+ const before = await call(SNAPSHOT_TEXT_FN);
4906
+ await sendInput("Input.insertText", { text });
4907
+ if (await call(LANDED_TEXT_FN, [before], true) === true)
4908
+ return "trusted";
4909
+ const via = await call(FALLBACK_TEXT_FN, [text]);
4910
+ if (via === "execCommand" || via === "setter" || via === "skipped")
4911
+ return via;
4912
+ 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");
4913
+ }
4914
+ var ARM_KEY_WITNESS = "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
4915
+ var READ_KEY_WITNESS = "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
4916
+ async function pressKeyObserved(conn, dispatch) {
4917
+ const eval_ = (expression, awaitPromise = false) => conn.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => {
4918
+ return;
4919
+ });
4920
+ const armed = await eval_(ARM_KEY_WITNESS) === true;
4921
+ await dispatch();
4922
+ if (!armed)
4923
+ return;
4924
+ const seen = await eval_(READ_KEY_WITNESS, true);
4925
+ if (seen === false)
4926
+ return { delivered: false };
4927
+ if (seen === true)
4928
+ return { delivered: true };
4929
+ }
4666
4930
  async function focusElement(conn, objectId) {
4667
4931
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
4668
4932
  }
@@ -4677,10 +4941,12 @@ async function awaitScrollSettle(conn) {
4677
4941
  }
4678
4942
  async function setValueOnObject(conn, objectId, value, sendInput) {
4679
4943
  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 });
4944
+ 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';}";
4945
+ const { result } = await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
4946
+ if (result?.value === "disabled" || result?.value === "readonly") {
4947
+ throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
4948
+ }
4949
+ return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
4684
4950
  }
4685
4951
  var NAMED_KEYS = {
4686
4952
  enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
@@ -5228,13 +5494,12 @@ class CdpPageDriver {
5228
5494
  }
5229
5495
  async setValue(loc, value) {
5230
5496
  const { objectId } = await resolveElementLocator(this.conn, loc);
5231
- await setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
5497
+ return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
5232
5498
  }
5233
5499
  async typeText(loc, text) {
5234
5500
  const { objectId } = await resolveElementLocator(this.conn, loc);
5235
5501
  await focusElement(this.conn, objectId);
5236
- if (text.length)
5237
- await this.dispatchInput("Input.insertText", { text });
5502
+ return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
5238
5503
  }
5239
5504
  async pressKey(press) {
5240
5505
  const spec = resolveKey(press.key);
@@ -5249,8 +5514,10 @@ class CdpPageDriver {
5249
5514
  const down = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
5250
5515
  if (spec.text && !suppressText)
5251
5516
  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 });
5517
+ return pressKeyObserved(this.conn, async () => {
5518
+ await this.dispatchInput("Input.dispatchKeyEvent", down);
5519
+ await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
5520
+ });
5254
5521
  }
5255
5522
  async setFiles(loc, files) {
5256
5523
  const { objectId } = await resolveElementLocator(this.conn, loc);
@@ -5627,7 +5894,7 @@ function noSuchTarget(e) {
5627
5894
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
5628
5895
  }
5629
5896
  var NEW_TARGET_SETTLE_MS = 2000;
5630
- async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5897
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, opts = {}) {
5631
5898
  const changed = new Set;
5632
5899
  let id = "";
5633
5900
  let wake;
@@ -5643,7 +5910,10 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5643
5910
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5644
5911
  return;
5645
5912
  });
5646
- const { targetId } = await conn.send("Target.createTarget", { url });
5913
+ const hidden = opts.hidden === true;
5914
+ const params = hidden ? { url, background: true, hidden: true } : { url, background: opts.focus !== true };
5915
+ const create = () => conn.send("Target.createTarget", params);
5916
+ const { targetId } = opts.focus === true || hidden ? await create() : await keepFrontApp(create);
5647
5917
  if (!targetId)
5648
5918
  throw driverError("page-error", "Target.createTarget returned no targetId");
5649
5919
  id = targetId;
@@ -5661,6 +5931,19 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5661
5931
  off();
5662
5932
  }
5663
5933
  }
5934
+ function hiddenTabsEnabled() {
5935
+ return hiddenTabsRequested() && isLongLivedProcess();
5936
+ }
5937
+ function currentHiddenOwner() {
5938
+ return hiddenTabOwner(currentEndpoint().base, () => ({
5939
+ connect: () => openBrowser(),
5940
+ createSettled: (conn, url, opts) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, opts)
5941
+ }));
5942
+ }
5943
+ function hiddenOwnerOf(id) {
5944
+ const owner = existingHiddenTabOwner(currentEndpoint().base);
5945
+ return owner?.has(id) ? owner : undefined;
5946
+ }
5664
5947
 
5665
5948
  class CdpBrowserDriver {
5666
5949
  scheme = "cdp";
@@ -5671,17 +5954,28 @@ class CdpBrowserDriver {
5671
5954
  async listPages(opts) {
5672
5955
  const targets = await listTargets();
5673
5956
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
5674
- return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
5957
+ return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type, ...t.hidden ? { hidden: true } : {} }));
5675
5958
  }
5676
- async newPage(url) {
5959
+ async newPage(url, opts) {
5960
+ if (opts?.focus !== true && hiddenTabsEnabled()) {
5961
+ const id = await currentHiddenOwner().create(url ?? "about:blank");
5962
+ return { id, url: url ?? "about:blank", title: "", hidden: true };
5963
+ }
5677
5964
  return withBrowserConn(async (conn) => {
5678
- const targetId = await createSettledTarget(conn, url ?? "about:blank");
5965
+ const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
5679
5966
  return { id: targetId, url: url ?? "about:blank", title: "" };
5680
5967
  });
5681
5968
  }
5682
5969
  async closePage(id) {
5970
+ const owner = hiddenOwnerOf(id);
5971
+ if (owner) {
5972
+ const res = await owner.close(id);
5973
+ if (res.success)
5974
+ beaconSessions.drop(beaconKey(id));
5975
+ return res;
5976
+ }
5683
5977
  return withBrowserConn(async (conn) => {
5684
- const res = await conn.send("Target.closeTarget", { targetId: id });
5978
+ const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
5685
5979
  if (res.success !== false)
5686
5980
  beaconSessions.drop(beaconKey(id));
5687
5981
  return { success: res.success ?? true };
@@ -5689,6 +5983,16 @@ class CdpBrowserDriver {
5689
5983
  }
5690
5984
  async activatePage(id) {
5691
5985
  const target = await resolveTarget(id).catch(noSuchTarget);
5986
+ const owner = hiddenOwnerOf(target.id);
5987
+ if (owner) {
5988
+ const url = target.url || "about:blank";
5989
+ const newId = await withBrowserConn((conn) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, { focus: true }));
5990
+ await owner.close(target.id).catch(() => {
5991
+ return;
5992
+ });
5993
+ beaconSessions.drop(beaconKey(target.id));
5994
+ return { id: newId, url, title: target.title, revealedFrom: target.id };
5995
+ }
5692
5996
  await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
5693
5997
  return { id: target.id, url: target.url, title: target.title };
5694
5998
  }
@@ -5762,6 +6066,7 @@ class CdpBrowserDriver {
5762
6066
  }
5763
6067
  async dispose() {
5764
6068
  beaconSessions.clear();
6069
+ await disposeHiddenTabs();
5765
6070
  }
5766
6071
  }
5767
6072
  function createCdpDriver() {
@@ -6351,7 +6656,6 @@ init_workers();
6351
6656
  init_frames();
6352
6657
  init_endpoints();
6353
6658
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
6354
- var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
6355
6659
 
6356
6660
  class SharedToolError extends Error {
6357
6661
  }
@@ -6510,17 +6814,18 @@ async function listPagesOne(driver, args = {}) {
6510
6814
  }
6511
6815
  async function newPage(driver, args = {}) {
6512
6816
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
6513
- const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label });
6817
+ const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
6818
+ const hidden = p.hidden === true ? { hidden: true } : {};
6514
6819
  const explicit = args.claim === true;
6515
6820
  if (!explicit && !requireLease())
6516
- return { targetId: p.id, url: p.url };
6821
+ return { targetId: p.id, url: p.url, ...hidden };
6517
6822
  const { record, token } = await claimLease(backendOf(driver), p.id, {
6518
6823
  label,
6519
6824
  ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(),
6520
6825
  auto: !explicit
6521
6826
  });
6522
6827
  await installBeacon(driver, p.id);
6523
- return { targetId: p.id, url: p.url, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
6828
+ return { targetId: p.id, url: p.url, ...hidden, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
6524
6829
  }
6525
6830
  async function closePage(driver, args) {
6526
6831
  if (args.target === undefined || args.target === "")
@@ -6533,16 +6838,41 @@ async function closePage(driver, args) {
6533
6838
  return { closed: p.id, success: true, ...released.released ? { leaseReleased: true } : {} };
6534
6839
  }
6535
6840
  async function writeSelectedFile(id) {
6536
- await mkdir5(STATE_DIR, { recursive: true });
6537
- await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6841
+ const stateDir = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
6842
+ await mkdir5(stateDir, { recursive: true });
6843
+ await writeFile4(join5(stateDir, "selected"), id, "utf8");
6538
6844
  }
6539
6845
  async function selectPage(driver, args) {
6540
6846
  if (args.target === undefined || args.target === "")
6541
6847
  throw new SharedToolError("select_page requires an explicit target");
6542
6848
  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 };
6849
+ if (args.focus !== true) {
6850
+ await writeSelectedFile(p.id);
6851
+ return { selected: p.id, focused: false };
6852
+ }
6853
+ const shown = await driver.activatePage(p.id);
6854
+ if (shown.revealedFrom === undefined || shown.id === p.id) {
6855
+ await writeSelectedFile(shown.id);
6856
+ return { selected: shown.id, focused: true };
6857
+ }
6858
+ const moved = await moveRevealedTab(backendOf(driver), shown.revealedFrom, shown.id);
6859
+ await writeSelectedFile(shown.id);
6860
+ return { selected: shown.id, focused: true, revealedFrom: shown.revealedFrom, ...moved.lease ? { lease: moved.lease } : {} };
6861
+ }
6862
+ async function moveRevealedTab(backend, fromId, toId) {
6863
+ const origin = await readOrigin(backend, fromId).catch(() => {
6864
+ return;
6865
+ });
6866
+ if (origin)
6867
+ await recordOrigin(backend, toId, { label: origin.label, now: origin.createdAt });
6868
+ const lease = await readLease(backend, fromId).catch(() => {
6869
+ return;
6870
+ });
6871
+ if (!lease)
6872
+ return {};
6873
+ await releaseLeaseFor(backend, fromId);
6874
+ const { token } = await claimLease(backend, toId, { label: lease.label, ttlMs: lease.ttlMs, auto: lease.auto === true });
6875
+ return { lease: token };
6546
6876
  }
6547
6877
  function toLegacyWaitedFor(w) {
6548
6878
  if (w === "committed")
@@ -6901,14 +7231,17 @@ async function drag(driver, args) {
6901
7231
  };
6902
7232
  });
6903
7233
  }
7234
+ function inputPathField(path) {
7235
+ return path && path !== "trusted" ? { inputPath: path } : {};
7236
+ }
6904
7237
  async function fill(driver, args) {
6905
7238
  if (typeof args.value !== "string")
6906
7239
  throw new SharedToolError("fill requires a string { value }");
6907
7240
  const loc = locatorOf(args);
6908
7241
  return withPage2(driver, args.target, async (page) => {
6909
7242
  const element = await describeElement(page, loc);
6910
- await page.setValue(loc, args.value);
6911
- return { filled: true, ...elementField(element), value: args.value };
7243
+ const path = await page.setValue(loc, args.value);
7244
+ return { filled: true, ...elementField(element), value: args.value, ...inputPathField(path) };
6912
7245
  });
6913
7246
  }
6914
7247
  async function fillForm(driver, args) {
@@ -6917,15 +7250,16 @@ async function fillForm(driver, args) {
6917
7250
  return withPage2(driver, args.target, async (page) => {
6918
7251
  let filled = 0;
6919
7252
  const elements = [];
7253
+ const paths = [];
6920
7254
  for (const f of args.fields) {
6921
7255
  if (typeof f.value !== "string")
6922
7256
  throw new SharedToolError("each fill_form field requires a string value");
6923
7257
  const loc = locatorOf(f);
6924
7258
  elements.push(await describeElement(page, loc) ?? null);
6925
- await page.setValue(loc, f.value);
7259
+ paths.push(await page.setValue(loc, f.value) || "trusted");
6926
7260
  filled++;
6927
7261
  }
6928
- return { filled, fields: args.fields.length, elements };
7262
+ return { filled, fields: args.fields.length, elements, ...paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {} };
6929
7263
  });
6930
7264
  }
6931
7265
  async function typeText(driver, args) {
@@ -6934,8 +7268,8 @@ async function typeText(driver, args) {
6934
7268
  const loc = locatorOf(args);
6935
7269
  return withPage2(driver, args.target, async (page) => {
6936
7270
  const element = await describeElement(page, loc);
6937
- await page.typeText(loc, args.text);
6938
- return { typed: true, ...elementField(element), text: args.text };
7271
+ const path = await page.typeText(loc, args.text);
7272
+ return { typed: true, ...elementField(element), text: args.text, ...inputPathField(path) };
6939
7273
  });
6940
7274
  }
6941
7275
  async function pressKey(driver, args) {
@@ -6943,7 +7277,15 @@ async function pressKey(driver, args) {
6943
7277
  throw new SharedToolError("press_key requires a non-empty { key }");
6944
7278
  const modifiers = args.modifiers ?? [];
6945
7279
  return withPage2(driver, args.target, async (page) => {
6946
- await page.pressKey({ key: args.key, modifiers });
7280
+ const res = await page.pressKey({ key: args.key, modifiers });
7281
+ if (res && res.delivered === false) {
7282
+ return {
7283
+ pressed: args.key,
7284
+ modifiers,
7285
+ delivered: false,
7286
+ 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."
7287
+ };
7288
+ }
6947
7289
  return { pressed: args.key, modifiers };
6948
7290
  });
6949
7291
  }
@@ -7196,6 +7538,7 @@ async function claimPage(driver, args = {}) {
7196
7538
  let targetId;
7197
7539
  let url;
7198
7540
  let opened;
7541
+ let hidden = false;
7199
7542
  if (hasTarget) {
7200
7543
  const hit = await pickPage(driver, pages, args.target).catch((err) => {
7201
7544
  throw new LeaseToolError(`claim_page: no open tab matches target '${args.target}' (${err.message}). No tab was opened: claim_page never creates one when 'target' is given.`);
@@ -7211,10 +7554,11 @@ async function claimPage(driver, args = {}) {
7211
7554
  url = existing.url;
7212
7555
  opened = false;
7213
7556
  } else {
7214
- const page = await newTrackedPage(driver, backend, { url: args.url, label });
7557
+ const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
7215
7558
  targetId = page.id;
7216
7559
  url = page.url;
7217
7560
  opened = true;
7561
+ hidden = page.hidden === true;
7218
7562
  }
7219
7563
  const humanMs = opened ? null : await readHumanActiveMs(driver, backend, targetId);
7220
7564
  const liveIds = [...pages.map((p) => p.id), targetId];
@@ -7233,6 +7577,7 @@ async function claimPage(driver, args = {}) {
7233
7577
  ttlMs: record.ttlMs,
7234
7578
  expiresAt: record.lastUsedAt + record.ttlMs,
7235
7579
  opened,
7580
+ ...hidden ? { hidden: true } : {},
7236
7581
  ...beaconSupported(driver) ? { humanActiveMs: humanMs } : {},
7237
7582
  ...contention !== undefined ? { contention } : {}
7238
7583
  };
@@ -7711,7 +8056,7 @@ init_client();
7711
8056
  import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7712
8057
  import { join as join6 } from "node:path";
7713
8058
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7714
- var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
8059
+ var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7715
8060
  var DEFAULT_CATEGORIES = [
7716
8061
  "devtools.timeline",
7717
8062
  "blink.user_timing",
@@ -7727,7 +8072,7 @@ function shortId(id) {
7727
8072
  return id.slice(0, 8);
7728
8073
  }
7729
8074
  function stateFilePath() {
7730
- return join6(STATE_DIR2, "trace-state.json");
8075
+ return join6(STATE_DIR, "trace-state.json");
7731
8076
  }
7732
8077
  function bufferTraceData(conn, sink) {
7733
8078
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7772,7 +8117,7 @@ async function performanceStartTrace(args = {}) {
7772
8117
  throw err;
7773
8118
  }
7774
8119
  liveTraces.set(target.id, { conn, target, events, startedAt: Date.now() });
7775
- await mkdir7(STATE_DIR2, { recursive: true });
8120
+ await mkdir7(STATE_DIR, { recursive: true });
7776
8121
  const state = {
7777
8122
  targetId: target.id,
7778
8123
  url: target.url,
@@ -8101,7 +8446,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
8101
8446
  outPath
8102
8447
  ];
8103
8448
  }
8104
- function run(bin, args) {
8449
+ function run2(bin, args) {
8105
8450
  return new Promise((resolve, reject) => {
8106
8451
  const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
8107
8452
  let stdout = "";
@@ -8123,7 +8468,7 @@ async function probeEncoder() {
8123
8468
  encoderProbe = (async () => {
8124
8469
  let res;
8125
8470
  try {
8126
- res = await run(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
8471
+ res = await run2(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
8127
8472
  } catch (err) {
8128
8473
  throw new CdpError(`${FFMPEG_MISSING} (${err.message})`);
8129
8474
  }
@@ -8132,7 +8477,7 @@ async function probeEncoder() {
8132
8477
  const choice = selectEncoder(`${res.stdout}
8133
8478
  ${res.stderr}`);
8134
8479
  const output = async (args) => {
8135
- const r = await run(FFMPEG_BIN, args).catch(() => {
8480
+ const r = await run2(FFMPEG_BIN, args).catch(() => {
8136
8481
  return;
8137
8482
  });
8138
8483
  return r && r.code === 0 ? `${r.stdout}
@@ -8305,7 +8650,7 @@ async function stopScreenRecording(args = {}) {
8305
8650
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
8306
8651
  let res;
8307
8652
  try {
8308
- res = await run(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8653
+ res = await run2(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
8309
8654
  } catch (err) {
8310
8655
  throw new CdpError(`${FFMPEG_MISSING} Spooled frames kept at ${rec.spoolDir}. (${err.message})`);
8311
8656
  }
@@ -9398,7 +9743,7 @@ var MANIFEST = [
9398
9743
  },
9399
9744
  {
9400
9745
  name: "new_page",
9401
- description: "Open a browser tab, optionally claim it; navigation is not awaited.",
9746
+ description: "Open a browser tab in the background, optionally claim it; navigation is not awaited.",
9402
9747
  inputSchema: {
9403
9748
  type: "object",
9404
9749
  properties: {
@@ -9425,6 +9770,10 @@ var MANIFEST = [
9425
9770
  ttlMs: {
9426
9771
  type: "number",
9427
9772
  description: "Lease TTL in milliseconds."
9773
+ },
9774
+ focus: {
9775
+ type: "boolean",
9776
+ description: "Open in the foreground and take focus; default false (background tab)."
9428
9777
  }
9429
9778
  },
9430
9779
  required: [],
@@ -9454,7 +9803,7 @@ var MANIFEST = [
9454
9803
  },
9455
9804
  {
9456
9805
  name: "select_page",
9457
- description: "Focus a selected page and persist it as active; target must resolve explicitly.",
9806
+ description: "Persist a page as selected; focus:true also raises it. Target must resolve explicitly.",
9458
9807
  inputSchema: {
9459
9808
  type: "object",
9460
9809
  properties: {
@@ -9465,6 +9814,10 @@ var MANIFEST = [
9465
9814
  target: {
9466
9815
  type: "string",
9467
9816
  description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9817
+ },
9818
+ focus: {
9819
+ type: "boolean",
9820
+ description: "Also raise the tab and take window focus; default false (selection only)."
9468
9821
  }
9469
9822
  },
9470
9823
  required: [
@@ -11056,7 +11409,7 @@ var MANIFEST = [
11056
11409
  },
11057
11410
  {
11058
11411
  name: "claim_page",
11059
- description: "Claim an existing tab or open a fresh one; CLI use is refused.",
11412
+ description: "Claim an existing tab or open a fresh one in the background; CLI use is refused.",
11060
11413
  inputSchema: {
11061
11414
  type: "object",
11062
11415
  properties: {
@@ -11079,6 +11432,10 @@ var MANIFEST = [
11079
11432
  ttlMs: {
11080
11433
  type: "number",
11081
11434
  description: "Lease TTL in milliseconds."
11435
+ },
11436
+ focus: {
11437
+ type: "boolean",
11438
+ description: "Fresh tab only: open it in the foreground; default false (background)."
11082
11439
  }
11083
11440
  },
11084
11441
  required: [],
@@ -11469,6 +11826,9 @@ async function disposeFirefoxSession() {
11469
11826
  });
11470
11827
  }
11471
11828
 
11829
+ // src/mcp.ts
11830
+ init_hiddenTabs();
11831
+
11472
11832
  // src/capabilities.ts
11473
11833
  init_driver2();
11474
11834
  init_driver();
@@ -12022,7 +12382,7 @@ function resolveProfile(spec) {
12022
12382
  // src/toolDocs.ts
12023
12383
  var TOOL_DOCS = {
12024
12384
  list_pages: {
12025
- description: "Enumerate browser page targets (GET /json/list); page-type tabs only unless all=true, which also lists workers and out-of-process (OOPIF) iframes. Each entry carries its targetId plus an origin field: 'agent' means this toolkit created it (also carries the creating label/createdAt, and stays 'agent' after the lease is released or the creator dies, making stray agent tabs findable), 'unknown' means no creation record - it never says 'human', the honest word for any tab it did not create; a record that exists but won't read adds originUnreadable. An entry under an active, readable lease also carries a 'lease' object {label,pid,idleMs,expiresAt,stale}, with idleMs and expiresAt computed fresh every call (never off disk), independent of probe. Under CDP_REQUIRE_LEASE this call also reaps abandoned agent tabs into an additive reaped array - but a lease reads reclaimable the moment its TTL elapses, while the tab is CLOSED only after a further grace (CDP_REAP_GRACE_MS, default 2700000ms/45min, so 60min total after last use); a dead-pid lease is reaped at once, a tab with no lease never. With probe, each page-type entry also gets 'responsive' (and humanActiveMs where human input is seen); both are absent, never false/null, without probe.",
12385
+ description: "Enumerate browser page targets (GET /json/list); page-type tabs only unless all=true, which also lists workers and out-of-process (OOPIF) iframes. Each entry carries its targetId plus an origin field: 'agent' means this toolkit created it (also carries the creating label/createdAt, and stays 'agent' after the lease is released or the creator dies, making stray agent tabs findable), 'unknown' means no creation record - it never says 'human', the honest word for any tab it did not create; a record that exists but won't read adds originUnreadable. An entry under an active, readable lease also carries a 'lease' object {label,pid,idleMs,expiresAt,stale}, with idleMs and expiresAt computed fresh every call (never off disk), independent of probe. Under CDP_REQUIRE_LEASE this call also reaps abandoned agent tabs into an additive reaped array - but a lease reads reclaimable the moment its TTL elapses, while the tab is CLOSED only after a further grace (CDP_REAP_GRACE_MS, default 2700000ms/45min, so 60min total after last use); a dead-pid lease is reaped at once, a tab with no lease never. With probe, each page-type entry also gets 'responsive' (and humanActiveMs where human input is seen); both are absent, never false/null, without probe. Under CDP_HIDDEN_TABS=1 (MCP server, Chrome), a tab this server opened hidden carries hidden:true: it is live and drivable but in no browser window, so the user cannot see it (select_page focus:true reveals it); hidden tabs are listed after the visible ones.",
12026
12386
  params: {
12027
12387
  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.",
12028
12388
  all: "Include non-page targets (service/shared workers, background pages, out-of-process (OOPIF) iframes); default false lists page-type tabs only. A returned non-page targetId is accepted as a bare id by any tool's `target` param.",
@@ -12032,28 +12392,30 @@ var TOOL_DOCS = {
12032
12392
  }
12033
12393
  },
12034
12394
  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).",
12395
+ 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. Under CDP_HIDDEN_TABS=1 (MCP server, Chrome; ignored by the CLI) a non-focus new_page opens a HIDDEN tab instead (createTarget hidden:true): the browser app never comes forward, the result carries hidden:true, the tab is fully drivable (1280x800 emulated viewport, screenshots, clicks, typing, same cookies/logins) but the user cannot see it, it dies if this server or the browser restarts (later calls on its id fail no-such-target), and at most CDP_HIDDEN_TABS_MAX (default 20) may be open at once (new_page then refuses and names them; close_page frees one). Use select_page focus:true to show one to the user. Defaults to about:blank; navigation is not awaited here (use navigate_page to load and wait).",
12036
12396
  params: {
12037
12397
  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
12398
  url: "URL to open in the new tab; defaults to about:blank.",
12039
12399
  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
12400
  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
12401
  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."
12402
+ 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.",
12403
+ focus: "Open the tab in the foreground, switching the user's visible tab and taking focus. Default false: the tab opens in the background (a hidden tab under CDP_HIDDEN_TABS=1)."
12043
12404
  }
12044
12405
  },
12045
12406
  close_page: {
12046
- description: "Close a page target via Target.closeTarget. Requires an explicit, resolvable target; errors rather than guessing when the selector matches nothing.",
12407
+ description: "Close a page target via Target.closeTarget. Requires an explicit, resolvable target; errors rather than guessing when the selector matches nothing. A hidden tab (CDP_HIDDEN_TABS) is closed over the connection that keeps it alive, and closing it never brings the browser forward.",
12047
12408
  params: {
12048
12409
  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.",
12049
12410
  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."
12050
12411
  }
12051
12412
  },
12052
12413
  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.",
12414
+ 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. focus:true on a hidden tab (list_pages hidden:true, CDP_HIDDEN_TABS) cannot raise it in place: its current URL is opened in a new VISIBLE foreground tab, the hidden tab is closed, and the result's selected is the NEW targetId with revealedFrom naming the old one (its label moves along; a lease moves too and its new token comes back as lease). In-page state the URL does not carry (form input, scroll position) is lost. Requires an explicit, resolvable target.",
12054
12415
  params: {
12055
12416
  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."
12417
+ 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.",
12418
+ focus: "Also raise the tab and take window focus (Target.activateTarget / browsingContext.activate); a hidden tab is reopened visibly under a new targetId instead. Default false: selection only."
12057
12419
  }
12058
12420
  },
12059
12421
  navigate_page: {
@@ -12235,7 +12597,7 @@ var TOOL_DOCS = {
12235
12597
  }
12236
12598
  },
12237
12599
  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").`,
12600
+ 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
12601
  params: {
12240
12602
  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
12603
  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 +12607,7 @@ var TOOL_DOCS = {
12245
12607
  }
12246
12608
  },
12247
12609
  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.",
12610
+ 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
12611
  params: {
12250
12612
  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
12613
  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 +12615,7 @@ var TOOL_DOCS = {
12253
12615
  }
12254
12616
  },
12255
12617
  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.",
12618
+ 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
12619
  params: {
12258
12620
  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
12621
  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 +12625,7 @@ var TOOL_DOCS = {
12263
12625
  }
12264
12626
  },
12265
12627
  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.",
12628
+ 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
12629
  params: {
12268
12630
  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
12631
  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 +12784,7 @@ var TOOL_DOCS = {
12422
12784
  maxWidth: "Caps the streamed frame width in px; also pins frame size if the viewport may change mid-recording.",
12423
12785
  maxHeight: "Caps the streamed frame height in px.",
12424
12786
  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."
12787
+ 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
12788
  }
12427
12789
  },
12428
12790
  stop_screen_recording: {
@@ -12492,7 +12854,8 @@ var TOOL_DOCS = {
12492
12854
  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
12855
  url: "When opening a fresh tab, navigate it here. Ignored when target or targetId is given.",
12494
12856
  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."
12857
+ 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.",
12858
+ 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
12859
  }
12497
12860
  },
12498
12861
  release_page: {
@@ -12623,7 +12986,7 @@ function toolAnnotations(name) {
12623
12986
  }
12624
12987
 
12625
12988
  // src/version.ts
12626
- var VERSION = "3.3.0";
12989
+ var VERSION = "3.5.0";
12627
12990
 
12628
12991
  // src/mcp.ts
12629
12992
  function isDirectRun() {
@@ -12910,7 +13273,7 @@ async function runTool(name, args) {
12910
13273
  }
12911
13274
  });
12912
13275
  }
12913
- async function run2(argv) {
13276
+ async function run3(argv) {
12914
13277
  const serve = parseServeOptions(argv);
12915
13278
  auditCoverage();
12916
13279
  markLongLivedProcess();
@@ -12932,6 +13295,9 @@ async function run2(argv) {
12932
13295
  shuttingDown = true;
12933
13296
  await disposeFirefoxSession();
12934
13297
  await disposeBrowserSession();
13298
+ await disposeHiddenTabs().catch(() => {
13299
+ return;
13300
+ });
12935
13301
  if (stdioHandle)
12936
13302
  await stdioHandle.close().catch(() => {
12937
13303
  return;
@@ -12971,7 +13337,7 @@ async function run2(argv) {
12971
13337
  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
13338
  }
12973
13339
  if (isDirectRun()) {
12974
- run2(process.argv.slice(2)).catch((err) => {
13340
+ run3(process.argv.slice(2)).catch((err) => {
12975
13341
  console.error(`[cdp-toolkit] ${err instanceof Error ? err.message : String(err)}`);
12976
13342
  process.exit(1);
12977
13343
  });