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.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Hidden tabs (CDP_HIDDEN_TABS=1, MCP server only): new_page without focus:true opens a
3
+ * `Target.createTarget {background:true, hidden:true}` target that never becomes visible, so the
4
+ * browser APP never comes to the front of the user's screen.
5
+ *
6
+ * WHY. Measured on Vivaldi (Chromium 156) by sampling `lsappinfo front` around raw CDP calls:
7
+ * createTarget with {background:true}, {background:true, focus:false}, {newWindow:true,
8
+ * background:true} and a minimized new window all bring the browser app to the front for a
9
+ * moment (keepFrontApp in ../frontApp.ts puts the user's app back AFTER that flash). Only
10
+ * {background:true, hidden:true} leaves the front app alone. Target.closeTarget and
11
+ * Page.navigate on an existing tab are also clean.
12
+ *
13
+ * WHAT A HIDDEN TARGET IS, measured on the same browser:
14
+ * - It dies when the CDP connection that created it closes. So this module holds ONE owner
15
+ * browser connection per endpoint, for the life of the process. That is also why the feature
16
+ * is MCP-server only: under the one-shot CLI the tab would die at process exit, so the CLI
17
+ * keeps the visible path even with the env set (see hiddenTabsEnabled).
18
+ * - While the owner lives, the target is in /json/list and Target.getTargets, and any other
19
+ * connection can attach, evaluate, navigate and screenshot it. Its listing type is "other",
20
+ * not "page", so markHiddenTargets relabels the ids this process owns (see there).
21
+ * - Its viewport is 0x0: Page.captureScreenshot hangs and clicks land nowhere. The owner
22
+ * attaches (flatten), sets Emulation.setDeviceMetricsOverride and KEEPS that session, and then
23
+ * every other per-call connection sees the emulated viewport. A second connection that sets
24
+ * and clears its own override, or disconnects without clearing, leaves the owner's override
25
+ * in force once it is gone (measured). The device pixel ratio is read from the tab itself
26
+ * before the override: a hidden tab reports the real screen's devicePixelRatio (2 on a Retina
27
+ * Mac) even at 0x0.
28
+ * - It shares the default browser context, so cookies and logins carry over.
29
+ * - Target.activateTarget / Page.bringToFront return ok and show nothing, and window.open from
30
+ * it opens nothing. So a hidden tab cannot be revealed in place; see the driver's activatePage.
31
+ *
32
+ * OWNER LOSS (server restart, browser restart, socket drop) kills every hidden tab. The registry
33
+ * notices on the next access (the owner's `isOpen` is false) and forgets them all, and the next
34
+ * new_page reconnects lazily. A dead hidden id is then an ordinary missing target, so every tool
35
+ * fails it with the existing `no-such-target` error from target resolution, never a hang.
36
+ *
37
+ * LEAK BOUND. The user can neither see nor close these tabs, so at most CDP_HIDDEN_TABS_MAX
38
+ * (default 20) live at once per endpoint. At the cap new_page REFUSES with an error naming the
39
+ * open hidden ids, rather than closing the oldest: silently closing a tab another call may still
40
+ * be driving (or holds a lease on) is the one thing list_pages' reap is also never allowed to do
41
+ * without saying so. dispose() (the MCP server's shutdown) closes them all.
42
+ *
43
+ * THIS MODULE IMPORTS NOTHING AT RUNTIME FROM ../client.ts: client.ts imports it (listTargets
44
+ * calls markHiddenTargets), and the owner's connection factory is injected by ./driver.ts.
45
+ */
46
+ import type { Target } from "../types.ts";
47
+
48
+ /** Default cap on live hidden tabs per endpoint. */
49
+ export const DEFAULT_HIDDEN_TABS_MAX = 20;
50
+ /** Emulated viewport for a hidden tab, in CSS px. */
51
+ export const HIDDEN_TAB_VIEWPORT = { width: 1280, height: 800 } as const;
52
+ /** Used when the tab cannot report its own devicePixelRatio. */
53
+ export const FALLBACK_DEVICE_SCALE_FACTOR = 2;
54
+ /** Bound on each owner-side command, so a wedged browser costs seconds, never a hang. */
55
+ const OWNER_COMMAND_TIMEOUT_MS = 5_000;
56
+
57
+ const TRUTHY = new Set(["1", "true", "yes", "on"]);
58
+
59
+ /** CDP_HIDDEN_TABS is set to a truthy value. Read per call, so a test can flip it. */
60
+ export function hiddenTabsRequested(): boolean {
61
+ return TRUTHY.has((process.env.CDP_HIDDEN_TABS ?? "").trim().toLowerCase());
62
+ }
63
+
64
+ /** CDP_HIDDEN_TABS_MAX, else DEFAULT_HIDDEN_TABS_MAX. A non-positive or non-numeric value is ignored. */
65
+ export function hiddenTabsMax(): number {
66
+ const raw = Number(process.env.CDP_HIDDEN_TABS_MAX);
67
+ return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : DEFAULT_HIDDEN_TABS_MAX;
68
+ }
69
+
70
+ /** The slice of CdpConnection the owner needs. */
71
+ export interface OwnerConnection {
72
+ send<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>, opts?: { timeoutMs?: number; sessionId?: string }): Promise<T>;
73
+ on(method: string, handler: (params: Record<string, unknown>, sessionId?: string) => void): () => void;
74
+ close(): void;
75
+ readonly isOpen: boolean;
76
+ }
77
+
78
+ export interface HiddenTabOwnerDeps {
79
+ /** Opens a fresh browser-endpoint connection (openBrowser in production). */
80
+ connect(): Promise<OwnerConnection>;
81
+ /** Creates the target with the settle wait (createSettledTarget in production). */
82
+ createSettled(conn: OwnerConnection, url: string, opts: { hidden: true }): Promise<string>;
83
+ /** Live cap; hiddenTabsMax by default. */
84
+ max?: () => number;
85
+ }
86
+
87
+ /** Thrown at the cap. `code` makes it pass through noSuchTarget and the MCP error mapping typed. */
88
+ export class HiddenTabCapError extends Error {
89
+ readonly code = "page-error" as const;
90
+ constructor(readonly max: number, readonly openIds: string[]) {
91
+ super(
92
+ `hidden-tab cap reached: ${openIds.length} hidden tabs are open (CDP_HIDDEN_TABS_MAX=${max}). ` +
93
+ `Close one with close_page (open hidden tabs, oldest first: ${openIds.join(", ")}), ` +
94
+ `or pass focus:true to open a visible tab instead.`,
95
+ );
96
+ this.name = "HiddenTabCapError";
97
+ }
98
+ }
99
+
100
+ /** One endpoint's owner connection and the hidden tabs it keeps alive. */
101
+ export class HiddenTabOwner {
102
+ private conn: OwnerConnection | undefined;
103
+ private connecting: Promise<OwnerConnection> | undefined;
104
+ /** targetId -> the owner's session on it. Insertion order is age (oldest first). */
105
+ private readonly tabs = new Map<string, string>();
106
+ /** Creates in flight, counted against the cap so concurrent new_page calls cannot overshoot it. */
107
+ private reserved = 0;
108
+
109
+ constructor(private readonly deps: HiddenTabOwnerDeps) {}
110
+
111
+ /** Forget everything if the owner socket died: its hidden tabs died with it. */
112
+ private sweep(): void {
113
+ if (this.conn && !this.conn.isOpen) {
114
+ this.conn = undefined;
115
+ this.tabs.clear();
116
+ }
117
+ }
118
+
119
+ /** True when `id` is a live hidden tab this owner holds. */
120
+ has(id: string): boolean {
121
+ this.sweep();
122
+ return this.tabs.has(id);
123
+ }
124
+
125
+ /** Live hidden ids, oldest first. */
126
+ ids(): string[] {
127
+ this.sweep();
128
+ return [...this.tabs.keys()];
129
+ }
130
+
131
+ /** The owner connection, opened lazily and single-flight: concurrent callers share one connect. */
132
+ private async owner(): Promise<OwnerConnection> {
133
+ this.sweep();
134
+ if (this.conn) return this.conn;
135
+ if (!this.connecting) {
136
+ this.connecting = (async () => {
137
+ const conn = await this.deps.connect();
138
+ // A hidden tab closed by anyone (another process's close_page, the browser itself) drops
139
+ // out of the registry here; setDiscoverTargets is sent by createSettled.
140
+ conn.on("Target.targetDestroyed", (params) => {
141
+ const id = (params as { targetId?: unknown }).targetId;
142
+ if (typeof id === "string") this.tabs.delete(id);
143
+ });
144
+ this.conn = conn;
145
+ return conn;
146
+ })().finally(() => {
147
+ this.connecting = undefined;
148
+ });
149
+ }
150
+ return this.connecting;
151
+ }
152
+
153
+ /** Create a hidden tab at `url`, attach the owner to it and give it a real viewport. */
154
+ async create(url: string): Promise<string> {
155
+ this.sweep();
156
+ const max = (this.deps.max ?? hiddenTabsMax)();
157
+ if (this.tabs.size + this.reserved >= max) throw new HiddenTabCapError(max, [...this.tabs.keys()]);
158
+ this.reserved++;
159
+ try {
160
+ const conn = await this.owner();
161
+ const id = await this.deps.createSettled(conn, url, { hidden: true });
162
+ try {
163
+ const { sessionId } = await conn.send<{ sessionId: string }>(
164
+ "Target.attachToTarget",
165
+ { targetId: id, flatten: true },
166
+ { timeoutMs: OWNER_COMMAND_TIMEOUT_MS },
167
+ );
168
+ const dpr = await conn
169
+ .send<{ result?: { value?: unknown } }>(
170
+ "Runtime.evaluate",
171
+ { expression: "devicePixelRatio", returnByValue: true },
172
+ { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS },
173
+ )
174
+ .then((r) => r.result?.value)
175
+ .catch(() => undefined);
176
+ await conn.send(
177
+ "Emulation.setDeviceMetricsOverride",
178
+ {
179
+ width: HIDDEN_TAB_VIEWPORT.width,
180
+ height: HIDDEN_TAB_VIEWPORT.height,
181
+ deviceScaleFactor: typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0 ? dpr : FALLBACK_DEVICE_SCALE_FACTOR,
182
+ mobile: false,
183
+ },
184
+ { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS },
185
+ );
186
+ this.tabs.set(id, sessionId);
187
+ return id;
188
+ } catch (e) {
189
+ // A hidden tab without a viewport cannot be screenshotted or clicked: do not hand it out.
190
+ await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => undefined);
191
+ throw e;
192
+ }
193
+ } finally {
194
+ this.reserved--;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Close a hidden tab over the owner. Closing the target ends the owner's session on it. When
200
+ * the owner is already gone the tab is too, so this reports success:false like a close of any
201
+ * missing target.
202
+ */
203
+ async close(id: string): Promise<{ success: boolean }> {
204
+ this.sweep();
205
+ const conn = this.conn;
206
+ const held = this.tabs.delete(id);
207
+ if (!conn || !held) return { success: false };
208
+ const res = await conn.send<{ success?: boolean }>("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
209
+ return { success: res.success ?? true };
210
+ }
211
+
212
+ /** Close every hidden tab, then the owner. Best effort and bounded; never throws. */
213
+ async dispose(): Promise<void> {
214
+ const conn = this.conn;
215
+ const ids = [...this.tabs.keys()];
216
+ this.tabs.clear();
217
+ this.conn = undefined;
218
+ if (!conn) return;
219
+ if (conn.isOpen) {
220
+ await Promise.all(ids.map((targetId) => conn.send("Target.closeTarget", { targetId }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => undefined)));
221
+ }
222
+ conn.close();
223
+ }
224
+ }
225
+
226
+ /* ------------------------------ process registry ------------------------------ */
227
+
228
+ /**
229
+ * One owner per endpoint base, MODULE SCOPE like ./driver.ts's beaconSessions: the state belongs
230
+ * to the process (the MCP server), and named endpoints are separate browsers whose target ids
231
+ * mean nothing to each other.
232
+ */
233
+ const owners = new Map<string, HiddenTabOwner>();
234
+
235
+ /** The owner for `base`, created on first use with `deps`. */
236
+ export function hiddenTabOwner(base: string, deps: () => HiddenTabOwnerDeps): HiddenTabOwner {
237
+ let owner = owners.get(base);
238
+ if (!owner) {
239
+ owner = new HiddenTabOwner(deps());
240
+ owners.set(base, owner);
241
+ }
242
+ return owner;
243
+ }
244
+
245
+ /** The owner for `base` if one was ever created. Never creates one. */
246
+ export function existingHiddenTabOwner(base: string): HiddenTabOwner | undefined {
247
+ return owners.get(base);
248
+ }
249
+
250
+ /** True when `id` is a live hidden tab on endpoint `base`. */
251
+ export function isHiddenTab(base: string, id: string): boolean {
252
+ return owners.get(base)?.has(id) ?? false;
253
+ }
254
+
255
+ /**
256
+ * Relabel this process's hidden tabs in a target listing: type "other" becomes "page" with
257
+ * `hidden: true`, so every selector arm (index, url, title, label, the default) and list_pages
258
+ * see them as the pages they are. They move to the END of the listing, so the visible tabs keep
259
+ * their indexes and a call with no target still lands on the same visible tab as before.
260
+ *
261
+ * Returns the SAME array when this process holds no hidden tab on `base`, so with the feature off
262
+ * the listing is untouched. Only ids this process created are relabeled: another process's hidden
263
+ * tabs, and Vivaldi's own "other" targets, are left alone.
264
+ */
265
+ export function markHiddenTargets(base: string, targets: Target[]): Target[] {
266
+ const owner = owners.get(base);
267
+ if (!owner) return targets;
268
+ const hidden = new Set(owner.ids());
269
+ if (hidden.size === 0) return targets;
270
+ const visible: Target[] = [];
271
+ const marked: Target[] = [];
272
+ for (const t of targets) {
273
+ if (hidden.has(t.id)) marked.push({ ...t, type: "page", hidden: true });
274
+ else visible.push(t);
275
+ }
276
+ return marked.length ? [...visible, ...marked] : targets;
277
+ }
278
+
279
+ /** Close every hidden tab on every endpoint and the owner connections. The MCP server's shutdown
280
+ * path (via the CDP driver's dispose). */
281
+ export async function disposeHiddenTabs(): Promise<void> {
282
+ const all = [...owners.values()];
283
+ owners.clear();
284
+ await Promise.all(all.map((o) => o.dispose()));
285
+ }
package/src/client.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
 
28
28
  import { detectEndpoint, resetEndpointCache, type CdpTransport } from "./cdp/endpoint.ts";
29
29
  import { openSession, withBrowserSocket, type PageConnection } from "./cdp/session.ts";
30
+ import { markHiddenTargets } from "./cdp/hiddenTabs.ts";
30
31
  export { SessionConnection, withBrowserSocket, type PageConnection } from "./cdp/session.ts";
31
32
  /**
32
33
  * Base HTTP origin of the DEFAULT DevTools endpoint, fixed at import (CDP_BASE, else
@@ -197,6 +198,12 @@ export class CdpConnection {
197
198
  });
198
199
  }
199
200
 
201
+ /** False once the socket closed (either side) or before connect(). The hidden-tab owner reads
202
+ * this to notice that the tabs it kept alive died with it. */
203
+ get isOpen(): boolean {
204
+ return !this.closed && this.ws !== undefined;
205
+ }
206
+
200
207
  close(): void {
201
208
  this.closed = true;
202
209
  this.rejectAll(new CdpError("closed by caller"));
@@ -280,11 +287,13 @@ async function getTargetsOverBrowserWs(): Promise<Target[]> {
280
287
  */
281
288
  export async function listTargets(): Promise<Target[]> {
282
289
  const base = currentEndpoint().base;
283
- if (knownTransports.get(base) === "browser-ws") return getTargetsOverBrowserWs();
290
+ // markHiddenTargets returns the listing untouched unless this process holds hidden tabs on this
291
+ // endpoint (CDP_HIDDEN_TABS, see cdp/hiddenTabs.ts).
292
+ if (knownTransports.get(base) === "browser-ws") return markHiddenTargets(base, await getTargetsOverBrowserWs());
284
293
  try {
285
294
  const listing = await httpJson<Target[]>("/json/list");
286
295
  knownTransports.set(base, "http");
287
- return listing;
296
+ return markHiddenTargets(base, listing);
288
297
  } catch (httpError) {
289
298
  // Switch only when detection says this endpoint really serves no `/json`.
290
299
  // A Chrome that does serve it can still fail one `/json/list` (restarting,
@@ -301,7 +310,7 @@ export async function listTargets(): Promise<Target[]> {
301
310
  throw httpError;
302
311
  });
303
312
  knownTransports.set(base, "browser-ws");
304
- return targets;
313
+ return markHiddenTargets(base, targets);
305
314
  }
306
315
  }
307
316
 
package/src/driver.ts CHANGED
@@ -212,6 +212,12 @@ export interface PageInfo {
212
212
  title: string;
213
213
  /** CDP target type ("page", "iframe", "worker", ...), when the driver has one. Additive: BiDi leaves it unset. */
214
214
  type?: string;
215
+ /** True for a hidden tab (CDP_HIDDEN_TABS=1, MCP server only): it is live and drivable, but it
216
+ * is in no browser window, so the user cannot see it. Absent otherwise. */
217
+ hidden?: boolean;
218
+ /** Set only by activatePage on a hidden tab: that tab cannot be shown in place, so the driver
219
+ * opened its URL in a new visible tab (`id`) and closed the hidden one, whose id this is. */
220
+ revealedFrom?: string;
215
221
  }
216
222
 
217
223
  /** How a caller points at an element. Exactly one field is set. */
@@ -749,6 +755,17 @@ export interface InterceptRule {
749
755
  */
750
756
  export type LifetimeModel = "per-call" | "session";
751
757
 
758
+ /**
759
+ * How a setValue/typeText commit actually reached the page (Chrome driver). "trusted": the
760
+ * Input.insertText commit landed. A background tab never receives trusted keyboard input, so the
761
+ * driver falls back in-page: "execCommand" (document.execCommand('insertText'), which fires real
762
+ * beforeinput/input events) or "setter" (native value setter plus input/change events, for a
763
+ * field execCommand cannot edit). "skipped": type_text on a disabled, read-only or non-text
764
+ * element, which trusted typing would not have changed either (setValue refuses a disabled or
765
+ * read-only field with a page-error instead, before clearing it).
766
+ */
767
+ export type TextInputPath = "trusted" | "execCommand" | "setter" | "skipped";
768
+
752
769
  /** Browser-scoped operations. One per browser process. */
753
770
  export interface BrowserDriver {
754
771
  /** Uid scheme tag owned by this driver, e.g. "cdp" or "bidi". */
@@ -761,11 +778,14 @@ export interface BrowserDriver {
761
778
 
762
779
  /** opts.all: include non-page targets (workers, iframes, ...) when the driver has that concept. */
763
780
  listPages(opts?: { all?: boolean }): Promise<PageInfo[]>;
764
- newPage(url?: string): Promise<PageInfo>;
781
+ /** Opens the tab in the BACKGROUND by default, so the user's active tab and keyboard focus
782
+ * stay put. opts.focus:true opens it in the foreground (the old default). */
783
+ newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo>;
765
784
  /** success mirrors the underlying protocol's own success signal when it has one (CDP's
766
785
  * Target.closeTarget); a driver without such a signal reports true once close resolves. */
767
786
  closePage(id: string): Promise<{ success: boolean }>;
768
- /** Bring a page to the front. Also writes the selected-page state file. */
787
+ /** Bring a page to the front: takes the user's active tab and window focus. Only an explicit
788
+ * opt-in may call this (select_page with focus:true); nothing calls it implicitly. */
769
789
  activatePage(id: string): Promise<PageInfo>;
770
790
 
771
791
  /** Acquire a page handle. The caller MUST release() it. Prefer withDriver. */
@@ -894,10 +914,11 @@ export interface PageDriver {
894
914
  /** Overwrite an element's value. One atomic commit under
895
915
  * "input.insertTextAtomic", else synthesized keystrokes, so per-key handlers
896
916
  * on the page WILL fire. Callers must not depend on either behavior. */
897
- setValue(loc: ElementLocator, value: string): Promise<void>;
917
+ setValue(loc: ElementLocator, value: string): Promise<void | TextInputPath>;
898
918
  /** Append text at the focus point without clearing first. */
899
- typeText(loc: ElementLocator, text: string): Promise<void>;
900
- pressKey(press: KeyPress): Promise<void>;
919
+ typeText(loc: ElementLocator, text: string): Promise<void | TextInputPath>;
920
+ /** A driver that can tell returns { delivered:false } when the page saw no keydown. */
921
+ pressKey(press: KeyPress): Promise<void | { delivered: boolean }>;
901
922
  /** Attach absolute file paths to a file input. */
902
923
  setFiles(loc: ElementLocator, files: readonly string[]): Promise<void>;
903
924
 
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Keep the user's frontmost app in front when a background tab opens (macOS).
3
+ *
4
+ * Measured on a Chromium-based browser: Target.createTarget {background:true} leaves the user's
5
+ * active tab alone but still brings the browser APP in front of whatever app the user is in.
6
+ * CDP has no flag for that, so on macOS the driver notes the frontmost process before the call
7
+ * and, if it changed afterwards, puts it back (System Events, by pid). Off-mac this is a no-op.
8
+ * CDP_RESTORE_FRONT_APP=0 turns it off. Read per call so tests can flip it.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+
12
+ export interface FrontAppOps {
13
+ front(): Promise<number | null>;
14
+ setFront(pid: number): Promise<void>;
15
+ }
16
+
17
+ function run(cmd: string, args: string[]): Promise<string> {
18
+ return new Promise((resolve) => {
19
+ execFile(cmd, args, { timeout: 2_000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
20
+ });
21
+ }
22
+
23
+ export const macFrontAppOps: FrontAppOps = {
24
+ async front() {
25
+ // lsappinfo needs no Automation consent and answers in a few ms.
26
+ const asn = (await run("lsappinfo", ["front"])).trim();
27
+ if (!asn) return null;
28
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
29
+ return m ? Number(m[1]) : null;
30
+ },
31
+ async setFront(pid) {
32
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
33
+ },
34
+ };
35
+
36
+ export function restoreFrontAppEnabled(platform: string = process.platform): boolean {
37
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
38
+ }
39
+
40
+ /**
41
+ * Run `fn` (which may raise the browser app) and put the prior frontmost app back if it lost
42
+ * the front. Checks again after `recheckMs`, since the raise can land just after the CDP reply.
43
+ */
44
+ export async function keepFrontApp<T>(
45
+ fn: () => Promise<T>,
46
+ opts: { ops?: FrontAppOps; enabled?: boolean; recheckMs?: number } = {},
47
+ ): Promise<T> {
48
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
49
+ if (!enabled) return fn();
50
+ const ops = opts.ops ?? macFrontAppOps;
51
+ const before = await ops.front().catch(() => null);
52
+ const result = await fn();
53
+ if (before === null) return result;
54
+ const fix = async (): Promise<void> => {
55
+ const now = await ops.front().catch(() => null);
56
+ if (now !== null && now !== before) await ops.setFront(before).catch(() => undefined);
57
+ };
58
+ await fix();
59
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
60
+ await fix();
61
+ return result;
62
+ }
@@ -45,6 +45,9 @@ export interface ClaimPageResult {
45
45
  * in the answer so a caller knows without a second lookup whether
46
46
  * release_page will close the tab. */
47
47
  opened: boolean;
48
+ /** true when the tab this call created is a hidden tab (CDP_HIDDEN_TABS): live and drivable,
49
+ * but in no window, so no human can see it. Absent otherwise. */
50
+ hidden?: true;
48
51
  /**
49
52
  * Milliseconds since the last input this server cannot account for — i.e.
50
53
  * since a HUMAN last touched this tab. See src/activity.ts for how that
@@ -119,7 +122,7 @@ export interface ClaimPageResult {
119
122
  */
120
123
  export async function claimPage(
121
124
  driver: BrowserDriver,
122
- args: { target?: TargetSelector; targetId?: string; url?: string; label?: string; ttlMs?: number } = {},
125
+ args: { target?: TargetSelector; targetId?: string; url?: string; label?: string; ttlMs?: number; focus?: boolean } = {},
123
126
  ): Promise<ClaimPageResult> {
124
127
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
125
128
  const hasTargetId = typeof args.targetId === "string" && args.targetId.length > 0;
@@ -134,6 +137,7 @@ export async function claimPage(
134
137
  let targetId: string;
135
138
  let url: string;
136
139
  let opened: boolean;
140
+ let hidden = false;
137
141
  if (hasTarget) {
138
142
  // Gate-free on purpose: see the header. No tab is created on this path,
139
143
  // including when nothing matches.
@@ -156,10 +160,12 @@ export async function claimPage(
156
160
  // expiry, so the tab stays attributable to `label` after the lease is gone.
157
161
  // Claiming an EXISTING tab (the branches above) records nothing, because
158
162
  // this toolkit did not create it and provenance is not ownership.
159
- const page = await newTrackedPage(driver, backend, { url: args.url, label });
163
+ // Background unless focus:true, same as new_page. focus is ignored on takeover.
164
+ const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
160
165
  targetId = page.id;
161
166
  url = page.url;
162
167
  opened = true;
168
+ hidden = page.hidden === true;
163
169
  }
164
170
  // Gate-free, before the claim, and only for a takeover: a tab this call is
165
171
  // about to CREATE cannot have a human in it, so asking would be theatre.
@@ -184,6 +190,7 @@ export async function claimPage(
184
190
  ttlMs: record.ttlMs,
185
191
  expiresAt: record.lastUsedAt + record.ttlMs,
186
192
  opened,
193
+ ...(hidden ? { hidden: true as const } : {}),
187
194
  // Absent, not null, when the backend has no beacon at all: "cannot answer"
188
195
  // and "answered, no data" are different facts (ADR-001's absent-over-
189
196
  // throwing rule applied to a field rather than to a whole tool).
package/src/leases.ts CHANGED
@@ -114,6 +114,12 @@ export function markLongLivedProcess(value = true): void {
114
114
  longLived = value;
115
115
  }
116
116
 
117
+ /** Whether markLongLivedProcess ran: true in the MCP server, false under the CLI. Hidden tabs
118
+ * (cdp/hiddenTabs.ts) gate on it for the same reason requireLease does. */
119
+ export function isLongLivedProcess(): boolean {
120
+ return longLived;
121
+ }
122
+
117
123
  /**
118
124
  * Strict mode: every tool call acquires a lease for the tab it resolves, and
119
125
  * stale agent tabs are reaped on read. Off by default, so 1.4.0 consumers are
package/src/manifest.ts CHANGED
@@ -56,7 +56,7 @@ export const MANIFEST: ToolSpec[] = [
56
56
  },
57
57
  {
58
58
  "name": "new_page",
59
- "description": "Open a browser tab, optionally claim it; navigation is not awaited.",
59
+ "description": "Open a browser tab in the background, optionally claim it; navigation is not awaited.",
60
60
  "inputSchema": {
61
61
  "type": "object",
62
62
  "properties": {
@@ -83,6 +83,10 @@ export const MANIFEST: ToolSpec[] = [
83
83
  "ttlMs": {
84
84
  "type": "number",
85
85
  "description": "Lease TTL in milliseconds."
86
+ },
87
+ "focus": {
88
+ "type": "boolean",
89
+ "description": "Open in the foreground and take focus; default false (background tab)."
86
90
  }
87
91
  },
88
92
  "required": [],
@@ -112,7 +116,7 @@ export const MANIFEST: ToolSpec[] = [
112
116
  },
113
117
  {
114
118
  "name": "select_page",
115
- "description": "Focus a selected page and persist it as active; target must resolve explicitly.",
119
+ "description": "Persist a page as selected; focus:true also raises it. Target must resolve explicitly.",
116
120
  "inputSchema": {
117
121
  "type": "object",
118
122
  "properties": {
@@ -123,6 +127,10 @@ export const MANIFEST: ToolSpec[] = [
123
127
  "target": {
124
128
  "type": "string",
125
129
  "description": "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
130
+ },
131
+ "focus": {
132
+ "type": "boolean",
133
+ "description": "Also raise the tab and take window focus; default false (selection only)."
126
134
  }
127
135
  },
128
136
  "required": [
@@ -1714,7 +1722,7 @@ export const MANIFEST: ToolSpec[] = [
1714
1722
  },
1715
1723
  {
1716
1724
  "name": "claim_page",
1717
- "description": "Claim an existing tab or open a fresh one; CLI use is refused.",
1725
+ "description": "Claim an existing tab or open a fresh one in the background; CLI use is refused.",
1718
1726
  "inputSchema": {
1719
1727
  "type": "object",
1720
1728
  "properties": {
@@ -1737,6 +1745,10 @@ export const MANIFEST: ToolSpec[] = [
1737
1745
  "ttlMs": {
1738
1746
  "type": "number",
1739
1747
  "description": "Lease TTL in milliseconds."
1748
+ },
1749
+ "focus": {
1750
+ "type": "boolean",
1751
+ "description": "Fresh tab only: open it in the foreground; default false (background)."
1740
1752
  }
1741
1753
  },
1742
1754
  "required": [],
package/src/mcp.ts CHANGED
@@ -41,6 +41,7 @@ import { TOOLS, TOOL_NAMES, BASE } from "./index.ts";
41
41
  import { MANIFEST } from "./manifest.ts";
42
42
  import { resolveBackend, getOrCreateFirefoxSession, disposeFirefoxSession } from "./backend.ts";
43
43
  import { disposeBrowserSession } from "./tools/browser-session.ts";
44
+ import { disposeHiddenTabs } from "./cdp/hiddenTabs.ts";
44
45
  import { toolAvailability } from "./capabilities.ts";
45
46
  import { FIREFOX_TOOLS } from "./firefox-tools.ts";
46
47
  import { leaseFromArgs, markLongLivedProcess, withLeaseScope } from "./leases.ts";
@@ -528,6 +529,9 @@ async function run(argv: string[]): Promise<void> {
528
529
  // Track P3). Unlike Firefox it owns no OS process, so process.exit would collect it anyway; it is
529
530
  // closed explicitly so shutdown does not depend on that, and is a no-op when neither tool ran.
530
531
  await disposeBrowserSession();
532
+ // Hidden tabs (CDP_HIDDEN_TABS): the user can neither see nor close them, so close every one
533
+ // and their owner connection. A no-op when none were opened.
534
+ await disposeHiddenTabs().catch(() => undefined);
531
535
  // Close the active transport last, so a tool call still in flight over it cannot outlive the
532
536
  // browser resources it was driving. For http this also stops accepting new connections.
533
537
  if (stdioHandle) await stdioHandle.close().catch(() => undefined);
package/src/origins.ts CHANGED
@@ -261,9 +261,10 @@ export async function originIndex(
261
261
  export async function newTrackedPage(
262
262
  driver: BrowserDriver,
263
263
  backend: LeaseBackend,
264
- opts: { url?: string; label?: string } = {},
264
+ opts: { url?: string; label?: string; focus?: boolean } = {},
265
265
  ): Promise<PageInfo> {
266
- const page = await driver.newPage(opts.url);
266
+ // Background by default: only an explicit focus:true may switch the user's visible tab.
267
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
267
268
  await recordOrigin(backend, page.id, { label: opts.label });
268
269
  return page;
269
270
  }
package/src/policy.ts CHANGED
@@ -60,7 +60,8 @@ export const MUTATING_TOOLS: ReadonlySet<string> = new Set([
60
60
  // pages
61
61
  "new_page", // Target.createTarget
62
62
  "close_page", // Target.closeTarget
63
- // borderline: Target.activateTarget raises the tab and steals window focus. A state change.
63
+ // borderline: writes the selected-state file; with focus:true also Target.activateTarget,
64
+ // which raises the tab and takes window focus. A state change either way.
64
65
  "select_page",
65
66
  "navigate_page", // Page.navigate / reload / history
66
67
  "set_cookie",