cdp-toolkit 3.4.0 → 3.6.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/src/manifest.ts CHANGED
@@ -819,6 +819,130 @@ export const MANIFEST: ToolSpec[] = [
819
819
  "additionalProperties": false
820
820
  }
821
821
  },
822
+ {
823
+ "name": "list_tab_groups",
824
+ "description": "List tab groups per window with member tabs (Chrome only, via a helper extension).",
825
+ "inputSchema": {
826
+ "type": "object",
827
+ "properties": {
828
+ "endpoint": {
829
+ "type": "string",
830
+ "description": "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
831
+ },
832
+ "windowId": {
833
+ "type": "integer",
834
+ "description": "Only this window."
835
+ },
836
+ "includeUngrouped": {
837
+ "type": "boolean",
838
+ "description": "Also list ungrouped tabs per window."
839
+ }
840
+ },
841
+ "required": [],
842
+ "additionalProperties": false
843
+ }
844
+ },
845
+ {
846
+ "name": "group_tabs",
847
+ "description": "Group tabs (new or existing group) and set title/color/collapsed (Chrome only).",
848
+ "inputSchema": {
849
+ "type": "object",
850
+ "properties": {
851
+ "endpoint": {
852
+ "type": "string",
853
+ "description": "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
854
+ },
855
+ "tabIds": {
856
+ "type": "array",
857
+ "items": {
858
+ "type": "integer"
859
+ },
860
+ "description": "Chrome tab ids (from list_tab_groups)."
861
+ },
862
+ "targetIds": {
863
+ "type": "array",
864
+ "items": {
865
+ "type": "string"
866
+ },
867
+ "description": "CDP target ids (list_pages ids)."
868
+ },
869
+ "urlMatch": {
870
+ "type": "string",
871
+ "description": "URL substring; matches tabs in every window."
872
+ },
873
+ "title": {
874
+ "type": "string",
875
+ "description": "Group title."
876
+ },
877
+ "color": {
878
+ "type": "string",
879
+ "enum": [
880
+ "grey",
881
+ "blue",
882
+ "red",
883
+ "yellow",
884
+ "green",
885
+ "pink",
886
+ "purple",
887
+ "cyan",
888
+ "orange"
889
+ ],
890
+ "description": "Group color."
891
+ },
892
+ "collapsed": {
893
+ "type": "boolean",
894
+ "description": "Collapse the group."
895
+ },
896
+ "groupId": {
897
+ "type": "integer",
898
+ "description": "Add to this existing group."
899
+ },
900
+ "windowId": {
901
+ "type": "integer",
902
+ "description": "Window for the new group; tabs elsewhere move there."
903
+ }
904
+ },
905
+ "required": [],
906
+ "additionalProperties": false
907
+ }
908
+ },
909
+ {
910
+ "name": "ungroup_tabs",
911
+ "description": "Remove tabs from their tab groups (Chrome only).",
912
+ "inputSchema": {
913
+ "type": "object",
914
+ "properties": {
915
+ "endpoint": {
916
+ "type": "string",
917
+ "description": "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
918
+ },
919
+ "tabIds": {
920
+ "type": "array",
921
+ "items": {
922
+ "type": "integer"
923
+ },
924
+ "description": "Chrome tab ids (from list_tab_groups)."
925
+ },
926
+ "targetIds": {
927
+ "type": "array",
928
+ "items": {
929
+ "type": "string"
930
+ },
931
+ "description": "CDP target ids (list_pages ids)."
932
+ },
933
+ "urlMatch": {
934
+ "type": "string",
935
+ "description": "URL substring; matches tabs in every window."
936
+ },
937
+ "groupId": {
938
+ "type": "integer",
939
+ "description": "Ungroup every tab of this group."
940
+ }
941
+ },
942
+ "required": [],
943
+ "additionalProperties": false
944
+ }
945
+ },
822
946
  {
823
947
  "name": "fill",
824
948
  "description": "Replace an element contents; provide exactly one of UID or selector.",
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
@@ -29,6 +29,7 @@
29
29
  * same way. That is why the annotation on list_pages says "unknown" and never
30
30
  * "human". Never add a "human" value here.
31
31
  */
32
+ import { focusDenied } from "./focusPolicy.ts";
32
33
  import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
33
34
  import { join } from "node:path";
34
35
  import type { BrowserDriver, PageInfo } from "./driver.ts";
@@ -263,8 +264,9 @@ export async function newTrackedPage(
263
264
  backend: LeaseBackend,
264
265
  opts: { url?: string; label?: string; focus?: boolean } = {},
265
266
  ): Promise<PageInfo> {
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
+ // Background by default: only an explicit focus:true may switch the user's visible tab,
268
+ // and not even that under CDP_DENY_FOCUS.
269
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true && !focusDenied() });
268
270
  await recordOrigin(backend, page.id, { label: opts.label });
269
271
  return page;
270
272
  }
package/src/policy.ts CHANGED
@@ -98,6 +98,10 @@ export const MUTATING_TOOLS: ReadonlySet<string> = new Set([
98
98
  "click_focus_gated",
99
99
  "wait_for_download", // borderline: Browser.setDownloadBehavior / BiDi browser.setDownloadBehavior changes browser state
100
100
  "grant_permissions", // Browser.grantPermissions / BiDi permissions.setPermission
101
+ // tab groups: all three install the helper extension (Extensions.loadUnpacked), even the listing
102
+ "list_tab_groups",
103
+ "group_tabs",
104
+ "ungroup_tabs",
101
105
  // leases: claim installs an activity beacon in the page and writes a lease; release can close a tab
102
106
  "claim_page",
103
107
  "release_page",
@@ -33,6 +33,7 @@
33
33
  * format (new feature work, not a safety-preserving migration). Per the explicit instruction that
34
34
  * behavior outranks the abstraction, these 7 stay two implementations; see the migration report.
35
35
  */
36
+ import { focusDenied } from "./focusPolicy.ts";
36
37
  import { mkdir, writeFile } from "node:fs/promises";
37
38
  import { dirname, join } from "node:path";
38
39
  import type {
@@ -42,11 +43,11 @@ import { isTiledCapture } from "./driver.ts";
42
43
  import { stitchPngBandsToFile } from "./png.ts";
43
44
  import type { TargetSelector } from "./types.ts";
44
45
  import {
45
- assertLeaseOk, chromeLeaseBackend, claimLease, defaultLabel, leaseTtlMs, listLeases, releaseLeaseFor, requireLease,
46
+ assertLeaseOk, chromeLeaseBackend, claimLease, defaultLabel, leaseTtlMs, listLeases, readLease, releaseLeaseFor, requireLease,
46
47
  type LeaseBackend, type LeaseStaleReason, type LeaseToken,
47
48
  } from "./leases.ts";
48
49
  import { installBeacon, probeRendererActivity, rendererProbeSupported } from "./activity.ts";
49
- import { newTrackedPage, originIndex, resolveLiveLabel, type PageOrigin } from "./origins.ts";
50
+ import { newTrackedPage, originIndex, readOrigin, recordOrigin, resolveLiveLabel, type PageOrigin } from "./origins.ts";
50
51
  import { isWorkerSelector, WORKER_SELECTOR_PAGE_ONLY_MESSAGE, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts";
51
52
  import { FRAME_SELECTOR_PAGE_ONLY_MESSAGE, FRAME_SELECTOR_UNSUPPORTED_MESSAGE, isFrameSelector } from "./frames.ts";
52
53
  import { reapAllowed, reapStaleAgentTabs, type ReapedTab } from "./reap.ts";
@@ -402,18 +403,24 @@ async function listPagesOne(
402
403
  export async function newPage(
403
404
  driver: BrowserDriver,
404
405
  args: { url?: string; claim?: boolean; label?: string; ttlMs?: number; focus?: boolean } = {},
405
- ): Promise<{ targetId: string; url: string; lease?: LeaseToken; label?: string; expiresAt?: number }> {
406
+ ): Promise<{ targetId: string; url: string; hidden?: true; focusDenied?: true; lease?: LeaseToken; label?: string; expiresAt?: number }> {
406
407
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
407
408
  // Creates the tab AND writes its creation record. The record outlives any
408
409
  // lease taken below, which is the point: a released tab is still an agent's.
409
410
  const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
411
+ // Present only for a hidden tab (CDP_HIDDEN_TABS), so the default output is byte-identical.
412
+ const hidden = {
413
+ ...(p.hidden === true ? { hidden: true as const } : {}),
414
+ // Present only when a focus:true was refused (CDP_DENY_FOCUS), so the default output is unchanged.
415
+ ...(args.focus === true && focusDenied() ? { focusDenied: true as const } : {}),
416
+ };
410
417
  // Under strict mode a tab nobody holds is a tab nobody may drive, so creating
411
418
  // one without claiming it would hand back a target the very next call has to
412
419
  // auto-acquire anyway. Doing it here means the tab is never briefly unowned
413
420
  // AND the caller is handed a token it can release with, which matters because
414
421
  // an auto-acquired lease never returns one.
415
422
  const explicit = args.claim === true;
416
- if (!explicit && !requireLease()) return { targetId: p.id, url: p.url };
423
+ if (!explicit && !requireLease()) return { targetId: p.id, url: p.url, ...hidden };
417
424
  // Atomic in the sense that matters: the tab is claimed before this call
418
425
  // returns, so no other agent can see it unclaimed and take it first.
419
426
  const { record, token } = await claimLease(backendOf(driver), p.id, {
@@ -430,7 +437,7 @@ export async function newPage(
430
437
  // it and a person has picked it up, which is the case the beacon exists for.
431
438
  // Nothing here is read back: a tab created a moment ago has no human history.
432
439
  await installBeacon(driver, p.id);
433
- return { targetId: p.id, url: p.url, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
440
+ return { targetId: p.id, url: p.url, ...hidden, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
434
441
  }
435
442
 
436
443
  export async function closePage(
@@ -464,13 +471,42 @@ async function writeSelectedFile(id: string): Promise<void> {
464
471
  * (Target.activateTarget / browsingContext.activate) switches the user's visible
465
472
  * tab and takes window focus, so it is never a side effect of selecting.
466
473
  * resolvePage already ran the lease gate, so skipping activatePage loses no check.
474
+ *
475
+ * focus:true on a HIDDEN tab (CDP_HIDDEN_TABS) cannot raise it in place: the driver reopens its
476
+ * URL in a new visible tab and closes the hidden one (see the CDP driver's activatePage). The new
477
+ * id is what gets selected and returned, with `revealedFrom` naming the closed hidden tab. The
478
+ * tab's provenance label moves with it, and a lease on the hidden tab is moved to the new tab and
479
+ * its NEW token returned as `lease`, since the old token names a tab that no longer exists.
467
480
  */
468
- export async function selectPage(driver: BrowserDriver, args: { target?: TargetSelector; focus?: boolean }): Promise<{ selected: string; focused: boolean }> {
481
+ export async function selectPage(
482
+ driver: BrowserDriver,
483
+ args: { target?: TargetSelector; focus?: boolean },
484
+ ): Promise<{ selected: string; focused: boolean; focusDenied?: true; revealedFrom?: string; lease?: LeaseToken }> {
469
485
  if (args.target === undefined || args.target === "") throw new SharedToolError("select_page requires an explicit target");
470
486
  const p = await resolvePage(driver, args.target);
471
- const id = args.focus === true ? (await driver.activatePage(p.id)).id : p.id;
472
- await writeSelectedFile(id);
473
- return { selected: id, focused: args.focus === true };
487
+ if (args.focus !== true || focusDenied()) {
488
+ await writeSelectedFile(p.id);
489
+ return { selected: p.id, focused: false, ...(args.focus === true ? { focusDenied: true as const } : {}) };
490
+ }
491
+ const shown = await driver.activatePage(p.id);
492
+ if (shown.revealedFrom === undefined || shown.id === p.id) {
493
+ await writeSelectedFile(shown.id);
494
+ return { selected: shown.id, focused: true };
495
+ }
496
+ const moved = await moveRevealedTab(backendOf(driver), shown.revealedFrom, shown.id);
497
+ await writeSelectedFile(shown.id);
498
+ return { selected: shown.id, focused: true, revealedFrom: shown.revealedFrom, ...(moved.lease ? { lease: moved.lease } : {}) };
499
+ }
500
+
501
+ /** Carry a revealed hidden tab's origin label and lease over to the visible tab that replaced it. */
502
+ async function moveRevealedTab(backend: LeaseBackend, fromId: string, toId: string): Promise<{ lease?: LeaseToken }> {
503
+ const origin = await readOrigin(backend, fromId).catch(() => undefined);
504
+ if (origin) await recordOrigin(backend, toId, { label: origin.label, now: origin.createdAt });
505
+ const lease = await readLease(backend, fromId).catch(() => undefined);
506
+ if (!lease) return {};
507
+ await releaseLeaseFor(backend, fromId);
508
+ const { token } = await claimLease(backend, toId, { label: lease.label, ttlMs: lease.ttlMs, auto: lease.auto === true });
509
+ return { lease: token };
474
510
  }
475
511
 
476
512
  /* ------------------------------ navigation (2) ------------------------------ */
@@ -1194,7 +1230,7 @@ export async function pressKey(driver: BrowserDriver, args: { target?: TargetSel
1194
1230
  if (res && res.delivered === false) {
1195
1231
  return {
1196
1232
  pressed: args.key, modifiers, delivered: false,
1197
- note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true. A key handled inside a cross-origin iframe also reads as not delivered.",
1233
+ note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true (which raises the browser over the user's work; refused under CDP_DENY_FOCUS). A key handled inside a cross-origin iframe also reads as not delivered.",
1198
1234
  };
1199
1235
  }
1200
1236
  return { pressed: args.key, modifiers };
package/src/toolDocs.ts CHANGED
@@ -3,7 +3,7 @@ export type ToolDoc = { readonly description: string; readonly params: Record<st
3
3
 
4
4
  export const TOOL_DOCS: Record<string, ToolDoc> = {
5
5
  "list_pages": {
6
- "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.",
6
+ "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.",
7
7
  "params": {
8
8
  "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.",
9
9
  "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.",
@@ -13,7 +13,7 @@ export const TOOL_DOCS: Record<string, ToolDoc> = {
13
13
  }
14
14
  },
15
15
  "new_page": {
16
- "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).",
16
+ "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).",
17
17
  "params": {
18
18
  "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.",
19
19
  "url": "URL to open in the new tab; defaults to about:blank.",
@@ -21,22 +21,22 @@ export const TOOL_DOCS: Record<string, ToolDoc> = {
21
21
  "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.",
22
22
  "label": "Agent label recorded on the lease when the tab is claimed; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
23
23
  "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.",
24
- "focus": "Open the tab in the foreground, switching the user's visible tab and taking focus. Default false: the tab opens in the background."
24
+ "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)."
25
25
  }
26
26
  },
27
27
  "close_page": {
28
- "description": "Close a page target via Target.closeTarget. Requires an explicit, resolvable target; errors rather than guessing when the selector matches nothing.",
28
+ "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.",
29
29
  "params": {
30
30
  "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.",
31
31
  "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."
32
32
  }
33
33
  },
34
34
  "select_page": {
35
- "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.",
35
+ "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.",
36
36
  "params": {
37
37
  "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.",
38
38
  "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.",
39
- "focus": "Also raise the tab and take window focus (Target.activateTarget / browsingContext.activate). Default false: selection only."
39
+ "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."
40
40
  }
41
41
  },
42
42
  "navigate_page": {
@@ -217,6 +217,38 @@ export const TOOL_DOCS: Record<string, ToolDoc> = {
217
217
  "reset": "Clear this server's previous permission grants (Browser.resetPermissions). With 'permissions' it resets FIRST and then grants, so the result is exactly the listed permissions; on its own it is a reset-only call answering {reset:true}. Not scoped to 'origin': CDP resets every origin at once."
218
218
  }
219
219
  },
220
+ "list_tab_groups": {
221
+ "description": "Lists the browser's tab groups, per window: {windows:[{windowId,tabCount,ungrouped,groups:[{groupId,title,color,collapsed,tabs:[{tabId,targetId,index,url,title}]}]}],groupCount,tabCount}; includeUngrouped:true adds each window's ungroupedTabs rows. targetId is the tab's CDP target id (the id list_pages shows), so a row can be driven by the other tools directly. CDP has no tab-group domain, so the three tab-group tools run chrome.tabGroups inside a tiny helper extension: the first call writes it under the artifact dir (tab-groups-helper/) and installs it with Extensions.loadUnpacked, and it stays installed in the profile afterwards (no UI, no state). That needs the helper directory on the browser's own machine and a Chromium that allows loadUnpacked over CDP (measured: Chromium 156-158, Helium, Vivaldi). Classified as changing state for read-only endpoints because of that install. Chrome only (capability 'browser.tabGroups'): absent under Firefox, whose BiDi cannot reach an extension background context.",
222
+ "params": {
223
+ "endpoint": "Name of a CDP endpoint configured with CDP_ENDPOINTS (Chrome only); acts on that browser instead of the default. These tools take no target.",
224
+ "windowId": "Only this chrome window id (from an earlier listing).",
225
+ "includeUngrouped": "Also return each window's ungrouped tabs as ungroupedTabs rows (same shape as group members), not just the ungrouped count. Default false."
226
+ }
227
+ },
228
+ "group_tabs": {
229
+ "description": "Puts tabs in a tab group and names it. Select tabs with EXACTLY ONE of tabIds (chrome tab ids from list_tab_groups), targetIds (CDP target ids, as list_pages shows them) or urlMatch (URL substring, matched in every window); a selection that matches nothing, or an unknown id, is an error and nothing is grouped. Without groupId a NEW group is created; with groupId the tabs join that existing group (its title/color are kept unless given). WINDOWS: a group lives in one window. If the selected tabs span several windows the call is REFUSED unless windowId names the destination, because Chrome would otherwise move them all into the last-focused window; with windowId, tabs from other windows are moved there and listed in 'moved'. groupId and windowId are mutually exclusive. title, color (grey|blue|red|yellow|green|pink|purple|cyan|orange) and collapsed are applied after grouping. Returns {groupId,windowId,title,color,collapsed,tabs,moved}. Never raises or focuses a window. Does not consult tab leases: grouping moves a tab in the tab strip, not the page. Helper-extension install and limits: see list_tab_groups. Chrome only (capability 'browser.tabGroups').",
230
+ "params": {
231
+ "endpoint": "Name of a CDP endpoint configured with CDP_ENDPOINTS (Chrome only). These tools take no target.",
232
+ "tabIds": "Chrome tab ids to group, from list_tab_groups. Non-empty.",
233
+ "targetIds": "CDP target ids to group (the ids list_pages shows). Non-empty.",
234
+ "urlMatch": "Substring of the tab URL; every matching tab in every window is selected.",
235
+ "title": "Group title shown on the tab strip.",
236
+ "color": "One of grey, blue, red, yellow, green, pink, purple, cyan, orange.",
237
+ "collapsed": "Collapse (true) or expand (false) the group.",
238
+ "groupId": "Add the tabs to this existing group instead of creating one. Not with windowId.",
239
+ "windowId": "Window the new group goes in; selected tabs in other windows are moved there. Required when the selection spans windows. Not with groupId."
240
+ }
241
+ },
242
+ "ungroup_tabs": {
243
+ "description": "Removes tabs from their tab groups; a group left with no tabs disappears. Select with EXACTLY ONE of tabIds, targetIds, urlMatch (as group_tabs) or groupId (every tab of that group). Tabs stay where they are in the window. Returns {ungrouped:[{tabId,targetId,index,url,title,fromGroupId}],alreadyUngrouped:[tabId]}; selected tabs that were in no group are listed in alreadyUngrouped rather than treated as an error. Helper-extension install and limits: see list_tab_groups. Chrome only (capability 'browser.tabGroups').",
244
+ "params": {
245
+ "endpoint": "Name of a CDP endpoint configured with CDP_ENDPOINTS (Chrome only). These tools take no target.",
246
+ "tabIds": "Chrome tab ids to ungroup.",
247
+ "targetIds": "CDP target ids to ungroup.",
248
+ "urlMatch": "Substring of the tab URL; matching tabs in every window are ungrouped.",
249
+ "groupId": "Ungroup every tab of this group."
250
+ }
251
+ },
220
252
  "fill": {
221
253
  "description": "Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes, so it won't fire per-keypress handlers). Give exactly one of uid or selector. Returns {filled,element,value}; element names the field (textbox \"Email\"). On a background tab (Chrome), which gets no trusted keyboard input, the commit is verified and falls back in-page (execCommand insertText, else the native value setter plus input/change events); the result then carries inputPath. The tab is never raised.",
222
254
  "params": {
package/src/toolGroups.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export const TOOL_GROUPS = [
2
2
  "core", "input", "cookies", "network", "console", "mocking",
3
3
  "emulation", "performance", "recording", "leases", "permissions",
4
- "dialogs", "downloads", "extraction",
4
+ "dialogs", "downloads", "extraction", "tabs",
5
5
  ] as const;
6
6
 
7
7
  export type ToolGroup = (typeof TOOL_GROUPS)[number];
@@ -32,6 +32,7 @@ export const GROUP_TOOLS: Record<ToolGroup, readonly string[]> = {
32
32
  dialogs: ["handle_dialog"],
33
33
  downloads: ["wait_for_download"],
34
34
  extraction: ["extract_page"],
35
+ tabs: ["list_tab_groups", "group_tabs", "ungroup_tabs"],
35
36
  } as const;
36
37
 
37
38
  export const TOOL_GROUP: Record<string, ToolGroup> = {};
@@ -50,6 +50,7 @@
50
50
  * shell-out shape lighthouse.ts uses. No Bun.* APIs anywhere (dist/ is bundled
51
51
  * to node ESM).
52
52
  */
53
+ import { focusDenied } from "../focusPolicy.ts";
53
54
  import { spawn } from "node:child_process";
54
55
  import { mkdir, rm, stat, writeFile } from "node:fs/promises";
55
56
  import { join } from "node:path";
@@ -597,7 +598,8 @@ export async function startScreenRecording(args: StartScreenRecordingArgs = {}):
597
598
 
598
599
  try {
599
600
  await conn.send("Page.enable");
600
- if (args.bringToFront) await conn.send("Page.bringToFront").catch(() => {});
601
+ // CDP_DENY_FOCUS refuses the raise; the 0-frame error below still explains a silent tab.
602
+ if (args.bringToFront && !focusDenied()) await conn.send("Page.bringToFront").catch(() => {});
601
603
  const params: Record<string, unknown> = { format };
602
604
  if (format === "jpeg" && args.quality !== undefined) params.quality = args.quality;
603
605
  if (args.maxWidth !== undefined) params.maxWidth = args.maxWidth;