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/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.5.0] - 2026-11-18
11
+
12
+ ### Added
13
+
14
+ - **Hidden tabs: `new_page` without any flash of the browser (opt-in, `CDP_HIDDEN_TABS=1`).** 3.4.0's restore puts the user's app back, but on macOS the browser still comes forward for a moment: every visible `Target.createTarget` variant activated Vivaldi in a tight `lsappinfo front` sample (`background`, `focus:false`, `newWindow`, a minimized new window, `window.open` from a background tab). Only `hidden:true` targets stayed clean. With `CDP_HIDDEN_TABS=1` in the MCP server, `new_page` and `claim_page` open such a tab on one held owner connection per endpoint, which keeps it alive and sets a 1280x800 viewport at the screen's pixel ratio, so screenshots, clicks and typing work and logins are shared (same browser context). Measured through the MCP server with the restore off: 3/3 `new_page` + `close_page` runs never changed the front app, against a flash on the visible path.
15
+ - `list_pages` marks these tabs `hidden: true` (the user cannot see them) and lists them after visible tabs.
16
+ - `select_page` with `focus:true` on a hidden tab reopens its URL in a visible tab, closes the hidden one, and returns the new id with `revealedFrom`. Page state the URL does not carry (form input, scroll) is lost.
17
+ - At most `CDP_HIDDEN_TABS_MAX` (default 20) hidden tabs; past the cap `new_page` is refused with the open ids. Server shutdown closes them all. A hidden tab dies with the server or the browser and then reports `no-such-target`.
18
+ - Default off, and the one-shot CLI always uses visible tabs (a hidden tab would die when the CLI exits). `focus:true` keeps the visible path.
19
+
10
20
  ## [3.4.0] - 2026-11-18
11
21
 
12
22
  ### Changed
package/README.md CHANGED
@@ -244,6 +244,8 @@ await TOOLS.navigate_page({ target: "index:0", url: "https://example.com" });
244
244
  | `CDP_ARTIFACT_DIR` | `/tmp/cdp-toolkit` | Screenshots, traces, heap snapshots, lighthouse reports, recorder buffers. |
245
245
  | `CDP_STATE_DIR` | `/tmp/cdp-toolkit` | `select_page` selected-target file, in-flight trace state. |
246
246
  | `CDP_RESTORE_FRONT_APP` | on (macOS only) | `0` stops `new_page` / `claim_page` / `close_page` from putting the user's frontmost app back after a background tab brings the browser forward. |
247
+ | `CDP_HIDDEN_TABS` | off | `1`: MCP server only, Chrome only. `new_page` / `claim_page` without `focus:true` open a hidden tab (`Target.createTarget {background:true, hidden:true}`), so the browser never flashes in front of the user's app. See "Hidden tabs" below. Ignored by the CLI, where a hidden tab would die at exit. |
248
+ | `CDP_HIDDEN_TABS_MAX` | `20` | Most hidden tabs open at once per endpoint. At the cap `new_page` refuses and names the open hidden ids; it never closes one for you. |
247
249
  | `CDP_EXTRACT_BASE_URL` | `http://127.0.0.1:8090/v1` | `extract_page` only. Base URL of the OpenAI-compatible extraction endpoint (the server appends `/chat/completions`). The default is loopback llm-ferry, so page content never leaves the machine; overriding it sends page content wherever the operator points. |
248
250
  | `CDP_EXTRACT_MODEL` | `schematron` | `extract_page` only. Model name for the extraction endpoint call. |
249
251
  | `CDP_EXTRACT_API_KEY` | unset | `extract_page` only. Bearer token for the endpoint. Never logged and redacted from every error; the response never contains it. |
@@ -524,10 +526,10 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
524
526
 
525
527
  | MCP name | CDP method(s) | Parity notes / gaps |
526
528
  |---|---|---|
527
- | `list_pages` | `GET /json/list` | `all` flag also exposes worker/background and out-of-process (OOPIF) iframe targets; MCP lists only page tabs. A non-page targetId from this listing is accepted by any tool's `target` param as a bare id, and `take_snapshot` marks a cross-origin iframe node with `frame:"<targetId>"` (input inside such an iframe is invisible to the activity beacon — see "Staleness" below — but the frame itself is fully driveable as its own target). Each row additionally carries `origin` (`agent` or `unknown`, never `human`) plus `label`/`createdAt` for tabs this toolkit created, and, for a tab under an active lease of this backend, a `lease:{label,pid,idleMs,expiresAt,stale}` field (unconditional on `probe`). `probe:true` pings each page-type target's renderer (one bounded 500ms `Runtime.evaluate`, never more) and adds `responsive:boolean` plus `humanActiveMs` where that round trip found human-attributed input; a wedged/unreachable tab reports `responsive:false`, never an error for the whole call. Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs first (destructively, only once a lease is `CDP_REAP_GRACE_MS` past its TTL — see "Staleness" below), reporting closures in an additive `reaped` array. |
528
- | `new_page` | `Target.createTarget` (+ lease file) | Opens the tab in the background (`background:true`), so the user's visible tab and focus stay put; `focus:true` opens it in the foreground. Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. |
529
+ | `list_pages` | `GET /json/list` | `all` flag also exposes worker/background and out-of-process (OOPIF) iframe targets; MCP lists only page tabs. A non-page targetId from this listing is accepted by any tool's `target` param as a bare id, and `take_snapshot` marks a cross-origin iframe node with `frame:"<targetId>"` (input inside such an iframe is invisible to the activity beacon — see "Staleness" below — but the frame itself is fully driveable as its own target). Each row additionally carries `origin` (`agent` or `unknown`, never `human`) plus `label`/`createdAt` for tabs this toolkit created, and, for a tab under an active lease of this backend, a `lease:{label,pid,idleMs,expiresAt,stale}` field (unconditional on `probe`). `probe:true` pings each page-type target's renderer (one bounded 500ms `Runtime.evaluate`, never more) and adds `responsive:boolean` plus `humanActiveMs` where that round trip found human-attributed input; a wedged/unreachable tab reports `responsive:false`, never an error for the whole call. Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs first (destructively, only once a lease is `CDP_REAP_GRACE_MS` past its TTL — see "Staleness" below), reporting closures in an additive `reaped` array. This server's hidden tabs (`CDP_HIDDEN_TABS`) are listed last with `hidden:true`. |
530
+ | `new_page` | `Target.createTarget` (+ lease file) | Opens the tab in the background (`background:true`), so the user's visible tab and focus stay put; `focus:true` opens it in the foreground. Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. Under `CDP_HIDDEN_TABS=1` (MCP server) a non-focus `new_page` opens a hidden tab instead and returns `hidden:true`; see "Hidden tabs". |
529
531
  | `close_page` | `Target.closeTarget` (+ lease file) | Reports `success:true` on the empty result newer Chromium returns. A successful close also releases that tab's lease; a failed close leaves it in place. |
530
- | `select_page` | selected-state file (+ `Target.activateTarget` with `focus:true`) | Writes a flat-file selected target and returns `{selected,focused}`; it raises the tab only with `focus:true`; `resolveTarget` does not read it, so `active` still means `index:0` unless a tool opts in. |
532
+ | `select_page` | selected-state file (+ `Target.activateTarget` with `focus:true`) | Writes a flat-file selected target and returns `{selected,focused}`; it raises the tab only with `focus:true`; `resolveTarget` does not read it, so `active` still means `index:0` unless a tool opts in. On a hidden tab, `focus:true` reopens its URL in a new visible tab, closes the hidden one, and returns the new id as `selected` plus `revealedFrom`. |
531
533
  | `navigate_page` | `Page.navigate` / `Page.reload` + load events, or `history:'back'\|'forward'` (Chrome: `Page.getNavigationHistory` + `Page.navigateToHistoryEntry`; Firefox: `browsingContext.traverseHistory`) | Returns `{url,frameId,waitedFor}` (no auto-snapshot; a history move also returns `traversed:'back'\|'forward'`). `waitUntil` supports `load`/`domcontentloaded`. `reload:true` (+ `ignoreCache:true` for a hard reload). `url`/`reload`/`history` are mutually exclusive; going back from the first entry (or forward from the last) is an error naming the direction, never a silent no-op. Works on both backends. |
532
534
  | `wait_for` | `Runtime.evaluate` (poll `innerText`) | Text-substring waiting only; throws on timeout rather than returning `{found:false}`. |
533
535
  | `evaluate_script` | `Runtime.evaluate` / `callFunctionOn` | No live `page`/element handle; `args` are plain JSON. Main-world context only. Toolkit addition: optional `savePath` writes the value to a JSON file and keeps it out of the response entirely. If `expression` is missing/empty and the call instead carries `function`/`code`/`js`/`script`/`fn`/`body`, the error names the wrong key and points at `expression`. One of four tools that also accept `target: "worker:<substring>"` (Chrome only, capability `worker.targets`) to reach an MV3 extension's background service worker — see "Driving MV3 extensions" below. |
@@ -717,6 +719,19 @@ So every tab this toolkit creates is written to a creation ledger, and `list_pag
717
719
  - No protection from humans. The lease is enforced against cdp-toolkit's own tool calls. It cannot stop someone clicking into the tab.
718
720
  - Not for the CLI. A CLI invocation is one process per call, so a lease it claimed would be reclaimable immediately by the dead-pid rule. `claim_page` is refused there. CLI calls can still present a token minted by the MCP server with `--lease`. Strict mode (`CDP_REQUIRE_LEASE`) is likewise MCP-only and for the same underlying reason, doubled: an auto-acquired lease would be reclaimable on arrival, worse than no lease at all, and reap would then be free to read that instantly-dead-pid record as an abandoned tab and close it on the next listing.
719
721
 
722
+ ## Hidden tabs: no browser flash (`CDP_HIDDEN_TABS`)
723
+
724
+ A background tab (`Target.createTarget {background:true}`) leaves the user's active tab alone, but on macOS it still brings the browser **app** in front of whatever the user is working in, for a moment. `CDP_RESTORE_FRONT_APP` puts their app back afterwards; it cannot stop the flash. Measured on Vivaldi (Chromium 156) by sampling the frontmost app around each raw CDP call: `{background:true}`, `{background:true, focus:false}`, a background `newWindow` and a minimized new window all flash. `{background:true, hidden:true}` does not, and neither do `Target.closeTarget` or `Page.navigate` on an existing tab.
725
+
726
+ Set `CDP_HIDDEN_TABS=1` on the **MCP server** and `new_page` / `claim_page` without `focus:true` open hidden tabs:
727
+
728
+ - **Fully drivable.** A hidden tab starts with a 0x0 viewport, where screenshots hang and clicks land nowhere, so the server attaches to it, sets a 1280x800 viewport at the screen's own device pixel ratio (read from the tab), and keeps that session open. Snapshots, screenshots, clicks, typing and navigation then work from any call. It shares the normal browser profile, so cookies and logins carry over.
729
+ - **Invisible.** It is in no window. `list_pages` marks it `hidden:true` and lists it after the visible tabs, so `index:` numbers and the default target are unchanged for the visible ones. Every selector (`url:`, `title:`, `label:`, an id) reaches it.
730
+ - **Tied to this server.** A hidden tab lives only while the server's connection that created it is open. A server restart, a browser restart or a dropped socket takes every hidden tab with it; the next `new_page` reconnects, and calls on a dead id fail fast with `no-such-target`. That is also why the CLI ignores the variable: its tab would die when the command exits.
731
+ - **Showing one to the user.** `select_page {focus:true}` cannot raise a hidden tab (Chromium accepts the activate call and shows nothing), so it opens the tab's current URL in a new visible tab (this one flash is the point), closes the hidden tab, and returns `{selected:<new id>, revealedFrom:<old id>}`. The tab's label moves with it; a lease moves too, and its new token comes back as `lease`. State the URL does not carry (form input, scroll position, a POST result) is lost. `new_page {focus:true}` still opens an ordinary visible tab.
732
+ - **Bounded.** The user cannot see or close these tabs, so at most `CDP_HIDDEN_TABS_MAX` (default 20) are open per endpoint. At the cap `new_page` refuses with an error naming the open hidden ids, oldest first; it never closes a tab another call may still be driving. `close_page` frees one, and server shutdown closes them all.
733
+ - **Scope.** Chrome-family browsers over CDP only (Firefox is unchanged). Only hidden tabs this server opened are marked; another server's hidden tabs list with the browser's own type, `"other"`.
734
+
720
735
  ## Named endpoints: several browsers or apps from one server
721
736
 
722
737
  One server can drive more than one DevTools port: your browser on `9222` and, say, the Microsoft Teams desktop app (WebView2, launched with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`) or an Electron app. Chrome backend only.
@@ -322,6 +322,9 @@ function leaseTtlMs() {
322
322
  function markLongLivedProcess(value = true) {
323
323
  longLived = value;
324
324
  }
325
+ function isLongLivedProcess() {
326
+ return longLived;
327
+ }
325
328
  function requireLease() {
326
329
  if (!longLived)
327
330
  return false;
@@ -2506,6 +2509,165 @@ var init_session = __esm(() => {
2506
2509
  init_endpoint();
2507
2510
  });
2508
2511
 
2512
+ // src/cdp/hiddenTabs.ts
2513
+ function hiddenTabsRequested() {
2514
+ return TRUTHY.has((process.env.CDP_HIDDEN_TABS ?? "").trim().toLowerCase());
2515
+ }
2516
+ function hiddenTabsMax() {
2517
+ const raw = Number(process.env.CDP_HIDDEN_TABS_MAX);
2518
+ return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : DEFAULT_HIDDEN_TABS_MAX;
2519
+ }
2520
+
2521
+ class HiddenTabOwner {
2522
+ deps;
2523
+ conn;
2524
+ connecting;
2525
+ tabs = new Map;
2526
+ reserved = 0;
2527
+ constructor(deps) {
2528
+ this.deps = deps;
2529
+ }
2530
+ sweep() {
2531
+ if (this.conn && !this.conn.isOpen) {
2532
+ this.conn = undefined;
2533
+ this.tabs.clear();
2534
+ }
2535
+ }
2536
+ has(id) {
2537
+ this.sweep();
2538
+ return this.tabs.has(id);
2539
+ }
2540
+ ids() {
2541
+ this.sweep();
2542
+ return [...this.tabs.keys()];
2543
+ }
2544
+ async owner() {
2545
+ this.sweep();
2546
+ if (this.conn)
2547
+ return this.conn;
2548
+ if (!this.connecting) {
2549
+ this.connecting = (async () => {
2550
+ const conn = await this.deps.connect();
2551
+ conn.on("Target.targetDestroyed", (params) => {
2552
+ const id = params.targetId;
2553
+ if (typeof id === "string")
2554
+ this.tabs.delete(id);
2555
+ });
2556
+ this.conn = conn;
2557
+ return conn;
2558
+ })().finally(() => {
2559
+ this.connecting = undefined;
2560
+ });
2561
+ }
2562
+ return this.connecting;
2563
+ }
2564
+ async create(url) {
2565
+ this.sweep();
2566
+ const max = (this.deps.max ?? hiddenTabsMax)();
2567
+ if (this.tabs.size + this.reserved >= max)
2568
+ throw new HiddenTabCapError(max, [...this.tabs.keys()]);
2569
+ this.reserved++;
2570
+ try {
2571
+ const conn = await this.owner();
2572
+ const id = await this.deps.createSettled(conn, url, { hidden: true });
2573
+ try {
2574
+ const { sessionId } = await conn.send("Target.attachToTarget", { targetId: id, flatten: true }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
2575
+ const dpr = await conn.send("Runtime.evaluate", { expression: "devicePixelRatio", returnByValue: true }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).then((r) => r.result?.value).catch(() => {
2576
+ return;
2577
+ });
2578
+ await conn.send("Emulation.setDeviceMetricsOverride", {
2579
+ width: HIDDEN_TAB_VIEWPORT.width,
2580
+ height: HIDDEN_TAB_VIEWPORT.height,
2581
+ deviceScaleFactor: typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0 ? dpr : FALLBACK_DEVICE_SCALE_FACTOR,
2582
+ mobile: false
2583
+ }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
2584
+ this.tabs.set(id, sessionId);
2585
+ return id;
2586
+ } catch (e) {
2587
+ await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
2588
+ return;
2589
+ });
2590
+ throw e;
2591
+ }
2592
+ } finally {
2593
+ this.reserved--;
2594
+ }
2595
+ }
2596
+ async close(id) {
2597
+ this.sweep();
2598
+ const conn = this.conn;
2599
+ const held = this.tabs.delete(id);
2600
+ if (!conn || !held)
2601
+ return { success: false };
2602
+ const res = await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
2603
+ return { success: res.success ?? true };
2604
+ }
2605
+ async dispose() {
2606
+ const conn = this.conn;
2607
+ const ids = [...this.tabs.keys()];
2608
+ this.tabs.clear();
2609
+ this.conn = undefined;
2610
+ if (!conn)
2611
+ return;
2612
+ if (conn.isOpen) {
2613
+ await Promise.all(ids.map((targetId) => conn.send("Target.closeTarget", { targetId }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
2614
+ return;
2615
+ })));
2616
+ }
2617
+ conn.close();
2618
+ }
2619
+ }
2620
+ function hiddenTabOwner(base, deps) {
2621
+ let owner = owners.get(base);
2622
+ if (!owner) {
2623
+ owner = new HiddenTabOwner(deps());
2624
+ owners.set(base, owner);
2625
+ }
2626
+ return owner;
2627
+ }
2628
+ function existingHiddenTabOwner(base) {
2629
+ return owners.get(base);
2630
+ }
2631
+ function markHiddenTargets(base, targets) {
2632
+ const owner = owners.get(base);
2633
+ if (!owner)
2634
+ return targets;
2635
+ const hidden = new Set(owner.ids());
2636
+ if (hidden.size === 0)
2637
+ return targets;
2638
+ const visible = [];
2639
+ const marked = [];
2640
+ for (const t of targets) {
2641
+ if (hidden.has(t.id))
2642
+ marked.push({ ...t, type: "page", hidden: true });
2643
+ else
2644
+ visible.push(t);
2645
+ }
2646
+ return marked.length ? [...visible, ...marked] : targets;
2647
+ }
2648
+ async function disposeHiddenTabs() {
2649
+ const all = [...owners.values()];
2650
+ owners.clear();
2651
+ await Promise.all(all.map((o) => o.dispose()));
2652
+ }
2653
+ var DEFAULT_HIDDEN_TABS_MAX = 20, HIDDEN_TAB_VIEWPORT, FALLBACK_DEVICE_SCALE_FACTOR = 2, OWNER_COMMAND_TIMEOUT_MS = 5000, TRUTHY, HiddenTabCapError, owners;
2654
+ var init_hiddenTabs = __esm(() => {
2655
+ HIDDEN_TAB_VIEWPORT = { width: 1280, height: 800 };
2656
+ TRUTHY = new Set(["1", "true", "yes", "on"]);
2657
+ HiddenTabCapError = class HiddenTabCapError extends Error {
2658
+ max;
2659
+ openIds;
2660
+ code = "page-error";
2661
+ constructor(max, openIds) {
2662
+ 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.`);
2663
+ this.max = max;
2664
+ this.openIds = openIds;
2665
+ this.name = "HiddenTabCapError";
2666
+ }
2667
+ };
2668
+ owners = new Map;
2669
+ });
2670
+
2509
2671
  // src/client.ts
2510
2672
  class CdpConnection {
2511
2673
  wsUrl;
@@ -2624,6 +2786,9 @@ class CdpConnection {
2624
2786
  });
2625
2787
  });
2626
2788
  }
2789
+ get isOpen() {
2790
+ return !this.closed && this.ws !== undefined;
2791
+ }
2627
2792
  close() {
2628
2793
  this.closed = true;
2629
2794
  this.rejectAll(new CdpError("closed by caller"));
@@ -2652,11 +2817,11 @@ async function getTargetsOverBrowserWs() {
2652
2817
  async function listTargets() {
2653
2818
  const base = currentEndpoint().base;
2654
2819
  if (knownTransports.get(base) === "browser-ws")
2655
- return getTargetsOverBrowserWs();
2820
+ return markHiddenTargets(base, await getTargetsOverBrowserWs());
2656
2821
  try {
2657
2822
  const listing = await httpJson("/json/list");
2658
2823
  knownTransports.set(base, "http");
2659
- return listing;
2824
+ return markHiddenTargets(base, listing);
2660
2825
  } catch (httpError) {
2661
2826
  const detected = await detectEndpoint().catch(() => {
2662
2827
  return;
@@ -2667,7 +2832,7 @@ async function listTargets() {
2667
2832
  throw httpError;
2668
2833
  });
2669
2834
  knownTransports.set(base, "browser-ws");
2670
- return targets;
2835
+ return markHiddenTargets(base, targets);
2671
2836
  }
2672
2837
  }
2673
2838
  async function browserWsUrl() {
@@ -2780,6 +2945,7 @@ var init_client2 = __esm(() => {
2780
2945
  init_frames();
2781
2946
  init_endpoint();
2782
2947
  init_session();
2948
+ init_hiddenTabs();
2783
2949
  init_session();
2784
2950
  BASE = (() => {
2785
2951
  try {
package/dist/cli.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 {
@@ -4530,6 +4696,7 @@ init_client();
4530
4696
  init_session();
4531
4697
  init_frontApp();
4532
4698
  init_leases();
4699
+ init_hiddenTabs();
4533
4700
  init_endpoints();
4534
4701
  init_activity();
4535
4702
 
@@ -5730,8 +5897,10 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
5730
5897
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5731
5898
  return;
5732
5899
  });
5733
- const create = () => conn.send("Target.createTarget", { url, background: opts.focus !== true });
5734
- const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
5900
+ const hidden = opts.hidden === true;
5901
+ const params = hidden ? { url, background: true, hidden: true } : { url, background: opts.focus !== true };
5902
+ const create = () => conn.send("Target.createTarget", params);
5903
+ const { targetId } = opts.focus === true || hidden ? await create() : await keepFrontApp(create);
5735
5904
  if (!targetId)
5736
5905
  throw driverError("page-error", "Target.createTarget returned no targetId");
5737
5906
  id = targetId;
@@ -5749,6 +5918,19 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
5749
5918
  off();
5750
5919
  }
5751
5920
  }
5921
+ function hiddenTabsEnabled() {
5922
+ return hiddenTabsRequested() && isLongLivedProcess();
5923
+ }
5924
+ function currentHiddenOwner() {
5925
+ return hiddenTabOwner(currentEndpoint().base, () => ({
5926
+ connect: () => openBrowser(),
5927
+ createSettled: (conn, url, opts) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, opts)
5928
+ }));
5929
+ }
5930
+ function hiddenOwnerOf(id) {
5931
+ const owner = existingHiddenTabOwner(currentEndpoint().base);
5932
+ return owner?.has(id) ? owner : undefined;
5933
+ }
5752
5934
 
5753
5935
  class CdpBrowserDriver {
5754
5936
  scheme = "cdp";
@@ -5759,15 +5941,26 @@ class CdpBrowserDriver {
5759
5941
  async listPages(opts) {
5760
5942
  const targets = await listTargets();
5761
5943
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
5762
- return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
5944
+ return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type, ...t.hidden ? { hidden: true } : {} }));
5763
5945
  }
5764
5946
  async newPage(url, opts) {
5947
+ if (opts?.focus !== true && hiddenTabsEnabled()) {
5948
+ const id = await currentHiddenOwner().create(url ?? "about:blank");
5949
+ return { id, url: url ?? "about:blank", title: "", hidden: true };
5950
+ }
5765
5951
  return withBrowserConn(async (conn) => {
5766
5952
  const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
5767
5953
  return { id: targetId, url: url ?? "about:blank", title: "" };
5768
5954
  });
5769
5955
  }
5770
5956
  async closePage(id) {
5957
+ const owner = hiddenOwnerOf(id);
5958
+ if (owner) {
5959
+ const res = await owner.close(id);
5960
+ if (res.success)
5961
+ beaconSessions.drop(beaconKey(id));
5962
+ return res;
5963
+ }
5771
5964
  return withBrowserConn(async (conn) => {
5772
5965
  const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
5773
5966
  if (res.success !== false)
@@ -5777,6 +5970,16 @@ class CdpBrowserDriver {
5777
5970
  }
5778
5971
  async activatePage(id) {
5779
5972
  const target = await resolveTarget(id).catch(noSuchTarget);
5973
+ const owner = hiddenOwnerOf(target.id);
5974
+ if (owner) {
5975
+ const url = target.url || "about:blank";
5976
+ const newId = await withBrowserConn((conn) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, { focus: true }));
5977
+ await owner.close(target.id).catch(() => {
5978
+ return;
5979
+ });
5980
+ beaconSessions.drop(beaconKey(target.id));
5981
+ return { id: newId, url, title: target.title, revealedFrom: target.id };
5982
+ }
5780
5983
  await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
5781
5984
  return { id: target.id, url: target.url, title: target.title };
5782
5985
  }
@@ -5850,6 +6053,7 @@ class CdpBrowserDriver {
5850
6053
  }
5851
6054
  async dispose() {
5852
6055
  beaconSessions.clear();
6056
+ await disposeHiddenTabs();
5853
6057
  }
5854
6058
  }
5855
6059
  function createCdpDriver() {
@@ -6598,16 +6802,17 @@ async function listPagesOne(driver, args = {}) {
6598
6802
  async function newPage(driver, args = {}) {
6599
6803
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
6600
6804
  const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
6805
+ const hidden = p.hidden === true ? { hidden: true } : {};
6601
6806
  const explicit = args.claim === true;
6602
6807
  if (!explicit && !requireLease())
6603
- return { targetId: p.id, url: p.url };
6808
+ return { targetId: p.id, url: p.url, ...hidden };
6604
6809
  const { record, token } = await claimLease(backendOf(driver), p.id, {
6605
6810
  label,
6606
6811
  ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(),
6607
6812
  auto: !explicit
6608
6813
  });
6609
6814
  await installBeacon(driver, p.id);
6610
- return { targetId: p.id, url: p.url, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
6815
+ return { targetId: p.id, url: p.url, ...hidden, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
6611
6816
  }
6612
6817
  async function closePage(driver, args) {
6613
6818
  if (args.target === undefined || args.target === "")
@@ -6628,9 +6833,33 @@ async function selectPage(driver, args) {
6628
6833
  if (args.target === undefined || args.target === "")
6629
6834
  throw new SharedToolError("select_page requires an explicit target");
6630
6835
  const p = await resolvePage(driver, args.target);
6631
- const id = args.focus === true ? (await driver.activatePage(p.id)).id : p.id;
6632
- await writeSelectedFile(id);
6633
- return { selected: id, focused: args.focus === true };
6836
+ if (args.focus !== true) {
6837
+ await writeSelectedFile(p.id);
6838
+ return { selected: p.id, focused: false };
6839
+ }
6840
+ const shown = await driver.activatePage(p.id);
6841
+ if (shown.revealedFrom === undefined || shown.id === p.id) {
6842
+ await writeSelectedFile(shown.id);
6843
+ return { selected: shown.id, focused: true };
6844
+ }
6845
+ const moved = await moveRevealedTab(backendOf(driver), shown.revealedFrom, shown.id);
6846
+ await writeSelectedFile(shown.id);
6847
+ return { selected: shown.id, focused: true, revealedFrom: shown.revealedFrom, ...moved.lease ? { lease: moved.lease } : {} };
6848
+ }
6849
+ async function moveRevealedTab(backend, fromId, toId) {
6850
+ const origin = await readOrigin(backend, fromId).catch(() => {
6851
+ return;
6852
+ });
6853
+ if (origin)
6854
+ await recordOrigin(backend, toId, { label: origin.label, now: origin.createdAt });
6855
+ const lease = await readLease(backend, fromId).catch(() => {
6856
+ return;
6857
+ });
6858
+ if (!lease)
6859
+ return {};
6860
+ await releaseLeaseFor(backend, fromId);
6861
+ const { token } = await claimLease(backend, toId, { label: lease.label, ttlMs: lease.ttlMs, auto: lease.auto === true });
6862
+ return { lease: token };
6634
6863
  }
6635
6864
  function toLegacyWaitedFor(w) {
6636
6865
  if (w === "committed")
@@ -7296,6 +7525,7 @@ async function claimPage(driver, args = {}) {
7296
7525
  let targetId;
7297
7526
  let url;
7298
7527
  let opened;
7528
+ let hidden = false;
7299
7529
  if (hasTarget) {
7300
7530
  const hit = await pickPage(driver, pages, args.target).catch((err) => {
7301
7531
  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.`);
@@ -7315,6 +7545,7 @@ async function claimPage(driver, args = {}) {
7315
7545
  targetId = page.id;
7316
7546
  url = page.url;
7317
7547
  opened = true;
7548
+ hidden = page.hidden === true;
7318
7549
  }
7319
7550
  const humanMs = opened ? null : await readHumanActiveMs(driver, backend, targetId);
7320
7551
  const liveIds = [...pages.map((p) => p.id), targetId];
@@ -7333,6 +7564,7 @@ async function claimPage(driver, args = {}) {
7333
7564
  ttlMs: record.ttlMs,
7334
7565
  expiresAt: record.lastUsedAt + record.ttlMs,
7335
7566
  opened,
7567
+ ...hidden ? { hidden: true } : {},
7336
7568
  ...beaconSupported(driver) ? { humanActiveMs: humanMs } : {},
7337
7569
  ...contention !== undefined ? { contention } : {}
7338
7570
  };