cdp-toolkit 3.4.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;
@@ -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 {
@@ -4543,6 +4709,7 @@ init_client();
4543
4709
  init_session();
4544
4710
  init_frontApp();
4545
4711
  init_leases();
4712
+ init_hiddenTabs();
4546
4713
  init_endpoints();
4547
4714
  init_activity();
4548
4715
 
@@ -5743,8 +5910,10 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
5743
5910
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5744
5911
  return;
5745
5912
  });
5746
- const create = () => conn.send("Target.createTarget", { url, background: opts.focus !== true });
5747
- const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
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);
5748
5917
  if (!targetId)
5749
5918
  throw driverError("page-error", "Target.createTarget returned no targetId");
5750
5919
  id = targetId;
@@ -5762,6 +5931,19 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
5762
5931
  off();
5763
5932
  }
5764
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
+ }
5765
5947
 
5766
5948
  class CdpBrowserDriver {
5767
5949
  scheme = "cdp";
@@ -5772,15 +5954,26 @@ class CdpBrowserDriver {
5772
5954
  async listPages(opts) {
5773
5955
  const targets = await listTargets();
5774
5956
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
5775
- 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 } : {} }));
5776
5958
  }
5777
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
+ }
5778
5964
  return withBrowserConn(async (conn) => {
5779
5965
  const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
5780
5966
  return { id: targetId, url: url ?? "about:blank", title: "" };
5781
5967
  });
5782
5968
  }
5783
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
+ }
5784
5977
  return withBrowserConn(async (conn) => {
5785
5978
  const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
5786
5979
  if (res.success !== false)
@@ -5790,6 +5983,16 @@ class CdpBrowserDriver {
5790
5983
  }
5791
5984
  async activatePage(id) {
5792
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
+ }
5793
5996
  await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
5794
5997
  return { id: target.id, url: target.url, title: target.title };
5795
5998
  }
@@ -5863,6 +6066,7 @@ class CdpBrowserDriver {
5863
6066
  }
5864
6067
  async dispose() {
5865
6068
  beaconSessions.clear();
6069
+ await disposeHiddenTabs();
5866
6070
  }
5867
6071
  }
5868
6072
  function createCdpDriver() {
@@ -6611,16 +6815,17 @@ async function listPagesOne(driver, args = {}) {
6611
6815
  async function newPage(driver, args = {}) {
6612
6816
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
6613
6817
  const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
6818
+ const hidden = p.hidden === true ? { hidden: true } : {};
6614
6819
  const explicit = args.claim === true;
6615
6820
  if (!explicit && !requireLease())
6616
- return { targetId: p.id, url: p.url };
6821
+ return { targetId: p.id, url: p.url, ...hidden };
6617
6822
  const { record, token } = await claimLease(backendOf(driver), p.id, {
6618
6823
  label,
6619
6824
  ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(),
6620
6825
  auto: !explicit
6621
6826
  });
6622
6827
  await installBeacon(driver, p.id);
6623
- 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 };
6624
6829
  }
6625
6830
  async function closePage(driver, args) {
6626
6831
  if (args.target === undefined || args.target === "")
@@ -6641,9 +6846,33 @@ async function selectPage(driver, args) {
6641
6846
  if (args.target === undefined || args.target === "")
6642
6847
  throw new SharedToolError("select_page requires an explicit target");
6643
6848
  const p = await resolvePage(driver, args.target);
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 };
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 };
6647
6876
  }
6648
6877
  function toLegacyWaitedFor(w) {
6649
6878
  if (w === "committed")
@@ -7309,6 +7538,7 @@ async function claimPage(driver, args = {}) {
7309
7538
  let targetId;
7310
7539
  let url;
7311
7540
  let opened;
7541
+ let hidden = false;
7312
7542
  if (hasTarget) {
7313
7543
  const hit = await pickPage(driver, pages, args.target).catch((err) => {
7314
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.`);
@@ -7328,6 +7558,7 @@ async function claimPage(driver, args = {}) {
7328
7558
  targetId = page.id;
7329
7559
  url = page.url;
7330
7560
  opened = true;
7561
+ hidden = page.hidden === true;
7331
7562
  }
7332
7563
  const humanMs = opened ? null : await readHumanActiveMs(driver, backend, targetId);
7333
7564
  const liveIds = [...pages.map((p) => p.id), targetId];
@@ -7346,6 +7577,7 @@ async function claimPage(driver, args = {}) {
7346
7577
  ttlMs: record.ttlMs,
7347
7578
  expiresAt: record.lastUsedAt + record.ttlMs,
7348
7579
  opened,
7580
+ ...hidden ? { hidden: true } : {},
7349
7581
  ...beaconSupported(driver) ? { humanActiveMs: humanMs } : {},
7350
7582
  ...contention !== undefined ? { contention } : {}
7351
7583
  };
@@ -11594,6 +11826,9 @@ async function disposeFirefoxSession() {
11594
11826
  });
11595
11827
  }
11596
11828
 
11829
+ // src/mcp.ts
11830
+ init_hiddenTabs();
11831
+
11597
11832
  // src/capabilities.ts
11598
11833
  init_driver2();
11599
11834
  init_driver();
@@ -12147,7 +12382,7 @@ function resolveProfile(spec) {
12147
12382
  // src/toolDocs.ts
12148
12383
  var TOOL_DOCS = {
12149
12384
  list_pages: {
12150
- 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.",
12151
12386
  params: {
12152
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.",
12153
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.",
@@ -12157,7 +12392,7 @@ var TOOL_DOCS = {
12157
12392
  }
12158
12393
  },
12159
12394
  new_page: {
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).",
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).",
12161
12396
  params: {
12162
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.",
12163
12398
  url: "URL to open in the new tab; defaults to about:blank.",
@@ -12165,22 +12400,22 @@ var TOOL_DOCS = {
12165
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.",
12166
12401
  label: "Agent label recorded on the lease when the tab is claimed; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
12167
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.",
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."
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)."
12169
12404
  }
12170
12405
  },
12171
12406
  close_page: {
12172
- 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.",
12173
12408
  params: {
12174
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.",
12175
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."
12176
12411
  }
12177
12412
  },
12178
12413
  select_page: {
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.",
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.",
12180
12415
  params: {
12181
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.",
12182
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.",
12183
- focus: "Also raise the tab and take window focus (Target.activateTarget / browsingContext.activate). Default false: selection only."
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."
12184
12419
  }
12185
12420
  },
12186
12421
  navigate_page: {
@@ -12751,7 +12986,7 @@ function toolAnnotations(name) {
12751
12986
  }
12752
12987
 
12753
12988
  // src/version.ts
12754
- var VERSION = "3.4.0";
12989
+ var VERSION = "3.5.0";
12755
12990
 
12756
12991
  // src/mcp.ts
12757
12992
  function isDirectRun() {
@@ -13060,6 +13295,9 @@ async function run3(argv) {
13060
13295
  shuttingDown = true;
13061
13296
  await disposeFirefoxSession();
13062
13297
  await disposeBrowserSession();
13298
+ await disposeHiddenTabs().catch(() => {
13299
+ return;
13300
+ });
13063
13301
  if (stdioHandle)
13064
13302
  await stdioHandle.close().catch(() => {
13065
13303
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdp-toolkit",
3
- "version": "3.4.0",
3
+ "version": "3.5.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",
package/src/cdp/driver.ts CHANGED
@@ -9,7 +9,8 @@ import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTar
9
9
  import { openSession } from "./session.ts";
10
10
  import { keepFrontApp } from "../frontApp.ts";
11
11
  import type { Target, TargetSelector } from "../types.ts";
12
- import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
12
+ import { chromeLeaseBackend, isLongLivedProcess, LeaseConflictError } from "../leases.ts";
13
+ import { disposeHiddenTabs, existingHiddenTabOwner, hiddenTabOwner, hiddenTabsRequested, type HiddenTabOwner } from "./hiddenTabs.ts";
13
14
  import { currentEndpoint } from "../endpoints.ts";
14
15
  import { BEACON_READ_EXPRESSION, BEACON_SOURCE, BeaconSessions, RENDERER_PROBE_EXPRESSION, RENDERER_PROBE_TIMEOUT_MS, sendInput } from "../activity.ts";
15
16
  import { resolveUid } from "../tools/snapshot.ts";
@@ -1829,12 +1830,18 @@ export const NEW_TARGET_SETTLE_MS = 2000;
1829
1830
  * The tab opens with background:true unless opts.focus is true: a tab the
1830
1831
  * toolkit opens must not switch the user's visible tab or take keyboard focus.
1831
1832
  * Without the flag Chromium (Vivaldi included) foregrounds every new tab.
1833
+ *
1834
+ * opts.hidden (the CDP_HIDDEN_TABS path, see ./hiddenTabs.ts) sends {background:true,
1835
+ * hidden:true} instead and skips keepFrontApp: a hidden target activates nothing, so there is no
1836
+ * front app to put back. A hidden target emits its first targetInfoChanged like any other
1837
+ * (measured ~46ms on Vivaldi 156), so the settle wait is unchanged. Without opts.hidden the
1838
+ * params are exactly what they were before hidden tabs existed.
1832
1839
  */
1833
1840
  export async function createSettledTarget(
1834
1841
  conn: Pick<CdpConnection, "send" | "on">,
1835
1842
  url: string,
1836
1843
  settleMs = NEW_TARGET_SETTLE_MS,
1837
- opts: { focus?: boolean } = {},
1844
+ opts: { focus?: boolean; hidden?: boolean } = {},
1838
1845
  ): Promise<string> {
1839
1846
  const changed = new Set<string>();
1840
1847
  let id = "";
@@ -1847,9 +1854,12 @@ export async function createSettledTarget(
1847
1854
  });
1848
1855
  try {
1849
1856
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => undefined);
1850
- const create = () => conn.send<{ targetId: string }>("Target.createTarget", { url, background: opts.focus !== true });
1857
+ const hidden = opts.hidden === true;
1858
+ const params = hidden ? { url, background: true, hidden: true } : { url, background: opts.focus !== true };
1859
+ const create = () => conn.send<{ targetId: string }>("Target.createTarget", params);
1851
1860
  // A background createTarget still brings the browser app forward on macOS: put the user's app back.
1852
- const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
1861
+ // A hidden one does not, and a foreground one is meant to.
1862
+ const { targetId } = opts.focus === true || hidden ? await create() : await keepFrontApp(create);
1853
1863
  if (!targetId) throw driverError("page-error", "Target.createTarget returned no targetId");
1854
1864
  id = targetId;
1855
1865
  if (!changed.has(targetId)) {
@@ -1863,6 +1873,29 @@ export async function createSettledTarget(
1863
1873
  off();
1864
1874
  }
1865
1875
  }
1876
+ /**
1877
+ * Hidden tabs are on: CDP_HIDDEN_TABS is set AND this is the long-lived MCP server. Under the
1878
+ * one-shot CLI a hidden tab would die with the process that created it at exit, so the CLI keeps
1879
+ * the visible path whatever the env says, the same carve-out requireLease makes (../leases.ts).
1880
+ */
1881
+ export function hiddenTabsEnabled(): boolean {
1882
+ return hiddenTabsRequested() && isLongLivedProcess();
1883
+ }
1884
+
1885
+ /** The current endpoint's hidden-tab owner, created on first use. */
1886
+ function currentHiddenOwner(): HiddenTabOwner {
1887
+ return hiddenTabOwner(currentEndpoint().base, () => ({
1888
+ connect: () => openBrowser(),
1889
+ createSettled: (conn, url, opts) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, opts),
1890
+ }));
1891
+ }
1892
+
1893
+ /** The current endpoint's owner when `id` is one of its live hidden tabs. Never creates one. */
1894
+ function hiddenOwnerOf(id: string): HiddenTabOwner | undefined {
1895
+ const owner = existingHiddenTabOwner(currentEndpoint().base);
1896
+ return owner?.has(id) ? owner : undefined;
1897
+ }
1898
+
1866
1899
  class CdpBrowserDriver implements BrowserDriver {
1867
1900
  readonly scheme = "cdp";
1868
1901
  readonly lifetime: LifetimeModel = "per-call";
@@ -1874,9 +1907,16 @@ class CdpBrowserDriver implements BrowserDriver {
1874
1907
  async listPages(opts?: { all?: boolean }): Promise<PageInfo[]> {
1875
1908
  const targets = await listTargets();
1876
1909
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
1877
- return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
1910
+ // `hidden` is set by listTargets on this process's hidden tabs only (./hiddenTabs.ts).
1911
+ return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type, ...(t.hidden ? { hidden: true } : {}) }));
1878
1912
  }
1879
1913
  async newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo> {
1914
+ // CDP_HIDDEN_TABS (MCP server only): a hidden target on the held owner connection, which
1915
+ // never brings the browser app forward. focus:true keeps the visible path below.
1916
+ if (opts?.focus !== true && hiddenTabsEnabled()) {
1917
+ const id = await currentHiddenOwner().create(url ?? "about:blank");
1918
+ return { id, url: url ?? "about:blank", title: "", hidden: true };
1919
+ }
1880
1920
  return withBrowserConn(async (conn) => {
1881
1921
  const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
1882
1922
  return { id: targetId, url: url ?? "about:blank", title: "" };
@@ -1886,6 +1926,14 @@ class CdpBrowserDriver implements BrowserDriver {
1886
1926
  * propagated (defaulting true only when the response omits it, matching newer Chromium
1887
1927
  * builds), never hardcoded. */
1888
1928
  async closePage(id: string): Promise<{ success: boolean }> {
1929
+ // A hidden tab is closed over its owner (closing it raises nothing, so no keepFrontApp).
1930
+ // Checked regardless of the env, so a tab opened before the env changed still closes cleanly.
1931
+ const owner = hiddenOwnerOf(id);
1932
+ if (owner) {
1933
+ const res = await owner.close(id);
1934
+ if (res.success) beaconSessions.drop(beaconKey(id));
1935
+ return res;
1936
+ }
1889
1937
  return withBrowserConn(async (conn) => {
1890
1938
  // Closing a tab also brings the browser app forward on macOS (measured): put the user's app back.
1891
1939
  const res = await keepFrontApp(() => conn.send<{ success?: boolean }>("Target.closeTarget", { targetId: id }));
@@ -1896,8 +1944,24 @@ class CdpBrowserDriver implements BrowserDriver {
1896
1944
  return { success: res.success ?? true };
1897
1945
  });
1898
1946
  }
1947
+ /**
1948
+ * On a hidden tab this REVEALS rather than activates: Target.activateTarget and
1949
+ * Page.bringToFront return ok on a hidden target and show nothing (measured), so it cannot be
1950
+ * brought forward in place. Instead its current URL opens in a new VISIBLE, foreground tab (the
1951
+ * flash is the point: the caller asked to show it), then the hidden tab is closed, and the new
1952
+ * tab's id is returned with `revealedFrom` naming the old one. In-page state that a URL does
1953
+ * not carry (form input, scroll, sessionStorage, a POST result) does not survive the move.
1954
+ */
1899
1955
  async activatePage(id: string): Promise<PageInfo> {
1900
1956
  const target = await resolveTarget(id).catch(noSuchTarget);
1957
+ const owner = hiddenOwnerOf(target.id);
1958
+ if (owner) {
1959
+ const url = target.url || "about:blank";
1960
+ const newId = await withBrowserConn((conn) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, { focus: true }));
1961
+ await owner.close(target.id).catch(() => undefined);
1962
+ beaconSessions.drop(beaconKey(target.id));
1963
+ return { id: newId, url, title: target.title, revealedFrom: target.id };
1964
+ }
1901
1965
  await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
1902
1966
  return { id: target.id, url: target.url, title: target.title };
1903
1967
  }
@@ -2027,13 +2091,17 @@ class CdpBrowserDriver implements BrowserDriver {
2027
2091
  * path and the CLI's exit path; a tool must never call it (see ../driver.ts). */
2028
2092
  async dispose(): Promise<void> {
2029
2093
  beaconSessions.clear();
2094
+ // Hidden tabs die with their owner anyway; closing them first is explicit and bounded.
2095
+ await disposeHiddenTabs();
2030
2096
  }
2031
2097
  }
2032
2098
  /** Construct the CDP implementation of the frozen Driver contract. */
2033
2099
  export function createCdpDriver(): BrowserDriver { return new CdpBrowserDriver(); }
2034
2100
  export { CdpBrowserDriver, CdpPageDriver };
2035
2101
  /* ------------------------------------------------------------------------------
2036
- * CDP methods/domains used: Target.createTarget/closeTarget/activateTarget; Page.enable/
2102
+ * CDP methods/domains used: Target.createTarget/closeTarget/activateTarget, plus
2103
+ * Target.attachToTarget, targetDestroyed and Emulation.setDeviceMetricsOverride on the hidden-tab
2104
+ * owner (./hiddenTabs.ts); Page.enable/
2037
2105
  * navigate/reload/getFrameTree/loadEventFired/domContentEventFired/frameStoppedLoading/
2038
2106
  * captureScreenshot/getLayoutMetrics/javascriptDialogOpening/handleJavaScriptDialog/
2039
2107
  * addScriptToEvaluateOnNewDocument (the activity beacon, see ../activity.ts);