cdp-toolkit 3.0.3 → 3.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdp-toolkit",
3
- "version": "3.0.3",
3
+ "version": "3.2.0",
4
4
  "description": "A lightweight chrome-devtools-mcp alternative: an MCP server + CLI that drives the tabs you name, one target per call over one direct WebSocket, with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 48 tools (only 5 core tools listed by default, plus search_tools/call_tool to reach the rest) including built-in network mocking, a cookie group, tab leases with human-activity detection, real HTML5 drag-and-drop, raw mouse/scroll dispatch, downloads, permission grants, and tab-to-video screen recording so several agents can drive one browser without stealing each other's tabs or a human's. No Puppeteer, no all-target fan-out.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -89,6 +89,8 @@
89
89
  "extension:smoke": "bun run ./test/extension-smoke.ts",
90
90
  "focus:smoke": "bun run ./test/focus-emulation-smoke.ts",
91
91
  "extract:smoke": "bun run ./test/extract-smoke.ts",
92
+ "browser-ws:smoke": "bun run ./test/browser-ws-smoke.ts",
93
+ "browser-ws:wedge": "bun run ./test/browser-ws-wedge.ts",
92
94
  "gateway:smoke": "bun run ./test/gateway-smoke.ts"
93
95
  },
94
96
  "devDependencies": {
@@ -49,6 +49,128 @@ export function coerceSnapshotResult(raw: unknown): StampedSnapshot {
49
49
  return { snapshot: (raw as StampedSnapshot).snapshot, nodeCount: (raw as StampedSnapshot).nodeCount };
50
50
  }
51
51
 
52
+ /**
53
+ * The reduced role + accessible-name heuristics, as in-page JS source. Shared by the snapshot
54
+ * walker below and by `describeElementSource` (src/shared-tools.ts), which names the element an
55
+ * action is about to touch, so a click result and a snapshot line agree on what "button \"Save\""
56
+ * means. Expects a `MAX_NAME_LENGTH` var in the enclosing function; interpolates nothing itself.
57
+ */
58
+ export const ACCNAME_HELPERS_SOURCE = `
59
+ function truncate(s) {
60
+ s = s.trim().replace(/\\s+/g, " ");
61
+ if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
62
+ return s;
63
+ }
64
+
65
+ function textOf(el) {
66
+ return el.textContent || "";
67
+ }
68
+
69
+ function idRefsText(doc, ids) {
70
+ var parts = [];
71
+ var list = ids.trim().split(/\\s+/);
72
+ for (var i = 0; i < list.length; i++) {
73
+ var ref = doc.getElementById(list[i]);
74
+ if (ref) parts.push(textOf(ref));
75
+ }
76
+ return parts.join(" ").trim();
77
+ }
78
+
79
+ // Text of a <label>, minus any nested form control's own content: a
80
+ // label that WRAPS its control ("<label>Color <select>...</select></label>")
81
+ // would otherwise include every option's text in the control's own name.
82
+ function labelOwnText(label) {
83
+ var clone = label.cloneNode(true);
84
+ var controls = clone.querySelectorAll("input, select, textarea, button");
85
+ for (var i = 0; i < controls.length; i++) {
86
+ controls[i].parentNode.removeChild(controls[i]);
87
+ }
88
+ return textOf(clone);
89
+ }
90
+
91
+ // Guard: without this, an <option> inside a labelled <select> would
92
+ // inherit the select's own label via closest("label"), not its text.
93
+ var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
94
+
95
+ function nativeLabelText(el) {
96
+ if (!LABELABLE_TAGS[el.tagName]) return "";
97
+ var doc = el.ownerDocument;
98
+ if (el.id) {
99
+ var forLabel = doc.querySelector('label[for="' + el.id + '"]');
100
+ if (forLabel) return labelOwnText(forLabel);
101
+ }
102
+ var ancestor = el.closest ? el.closest("label") : null;
103
+ if (ancestor) return labelOwnText(ancestor);
104
+ return "";
105
+ }
106
+
107
+ // Reduced accname: aria-labelledby, then aria-label, then native label,
108
+ // then alt/title/placeholder, then trimmed own text for content-named
109
+ // elements. Not the full W3C accname algorithm (no recursive traversal
110
+ // rules for nested presentational content) but covers the common cases.
111
+ function accessibleName(el, contentNamed) {
112
+ var doc = el.ownerDocument;
113
+ var labelledby = el.getAttribute("aria-labelledby");
114
+ if (labelledby) {
115
+ var viaIds = idRefsText(doc, labelledby);
116
+ if (viaIds) return truncate(viaIds);
117
+ }
118
+ var ariaLabel = el.getAttribute("aria-label");
119
+ if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
120
+ var native = nativeLabelText(el);
121
+ if (native && native.trim()) return truncate(native);
122
+ var alt = el.getAttribute("alt");
123
+ if (alt && alt.trim()) return truncate(alt);
124
+ var title = el.getAttribute("title");
125
+ if (title && title.trim()) return truncate(title);
126
+ var placeholder = el.getAttribute("placeholder");
127
+ if (placeholder && placeholder.trim()) return truncate(placeholder);
128
+ if (contentNamed) {
129
+ var text = textOf(el);
130
+ if (text && text.trim()) return truncate(text);
131
+ }
132
+ return "";
133
+ }
134
+
135
+ var IMPLICIT_ROLE_BY_TAG = {
136
+ A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
137
+ UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
138
+ SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
139
+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
140
+ PROGRESS: "progressbar", METER: "meter"
141
+ };
142
+
143
+ var INPUT_TYPE_ROLE = {
144
+ button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
145
+ range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
146
+ url: "textbox", password: "textbox", text: "textbox", image: "button"
147
+ };
148
+
149
+ var CONTENT_NAMED_ROLES = {
150
+ button: true, link: true, heading: true, option: true, cell: true,
151
+ columnheader: true, listitem: true, menuitem: true, tab: true
152
+ };
153
+
154
+ function implicitRole(el) {
155
+ var explicit = el.getAttribute("role");
156
+ if (explicit) return explicit;
157
+ var tag = el.tagName;
158
+ if (tag === "INPUT") {
159
+ var type = (el.getAttribute("type") || "text").toLowerCase();
160
+ return INPUT_TYPE_ROLE[type] || "textbox";
161
+ }
162
+ if (tag === "A" && !el.getAttribute("href")) return "";
163
+ if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
164
+ return IMPLICIT_ROLE_BY_TAG[tag];
165
+ }
166
+ // Deliberate divergence: Chrome's real AX tree says "generic" here,
167
+ // but "textbox" is the useful signal an agent needs. Chrome is out of
168
+ // step, do not "fix" this toward parity.
169
+ if (el.isContentEditable) return "textbox";
170
+ return "";
171
+ }
172
+ `;
173
+
52
174
  /**
53
175
  * The in-page function source. Zero-argument, self-contained: no closures
54
176
  * over TypeScript scope, no imports, nothing but plain DOM/ARIA calls that
@@ -102,119 +224,7 @@ export function buildSnapshotFunctionSource(): string {
102
224
  return true;
103
225
  }
104
226
 
105
- function truncate(s) {
106
- s = s.trim().replace(/\\s+/g, " ");
107
- if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
108
- return s;
109
- }
110
-
111
- function textOf(el) {
112
- return el.textContent || "";
113
- }
114
-
115
- function idRefsText(doc, ids) {
116
- var parts = [];
117
- var list = ids.trim().split(/\\s+/);
118
- for (var i = 0; i < list.length; i++) {
119
- var ref = doc.getElementById(list[i]);
120
- if (ref) parts.push(textOf(ref));
121
- }
122
- return parts.join(" ").trim();
123
- }
124
-
125
- // Text of a <label>, minus any nested form control's own content: a
126
- // label that WRAPS its control ("<label>Color <select>...</select></label>")
127
- // would otherwise include every option's text in the control's own name.
128
- function labelOwnText(label) {
129
- var clone = label.cloneNode(true);
130
- var controls = clone.querySelectorAll("input, select, textarea, button");
131
- for (var i = 0; i < controls.length; i++) {
132
- controls[i].parentNode.removeChild(controls[i]);
133
- }
134
- return textOf(clone);
135
- }
136
-
137
- // Guard: without this, an <option> inside a labelled <select> would
138
- // inherit the select's own label via closest("label"), not its text.
139
- var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
140
-
141
- function nativeLabelText(el) {
142
- if (!LABELABLE_TAGS[el.tagName]) return "";
143
- var doc = el.ownerDocument;
144
- if (el.id) {
145
- var forLabel = doc.querySelector('label[for="' + el.id + '"]');
146
- if (forLabel) return labelOwnText(forLabel);
147
- }
148
- var ancestor = el.closest ? el.closest("label") : null;
149
- if (ancestor) return labelOwnText(ancestor);
150
- return "";
151
- }
152
-
153
- // Reduced accname: aria-labelledby, then aria-label, then native label,
154
- // then alt/title/placeholder, then trimmed own text for content-named
155
- // elements. Not the full W3C accname algorithm (no recursive traversal
156
- // rules for nested presentational content) but covers the common cases.
157
- function accessibleName(el, contentNamed) {
158
- var doc = el.ownerDocument;
159
- var labelledby = el.getAttribute("aria-labelledby");
160
- if (labelledby) {
161
- var viaIds = idRefsText(doc, labelledby);
162
- if (viaIds) return truncate(viaIds);
163
- }
164
- var ariaLabel = el.getAttribute("aria-label");
165
- if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
166
- var native = nativeLabelText(el);
167
- if (native && native.trim()) return truncate(native);
168
- var alt = el.getAttribute("alt");
169
- if (alt && alt.trim()) return truncate(alt);
170
- var title = el.getAttribute("title");
171
- if (title && title.trim()) return truncate(title);
172
- var placeholder = el.getAttribute("placeholder");
173
- if (placeholder && placeholder.trim()) return truncate(placeholder);
174
- if (contentNamed) {
175
- var text = textOf(el);
176
- if (text && text.trim()) return truncate(text);
177
- }
178
- return "";
179
- }
180
-
181
- var IMPLICIT_ROLE_BY_TAG = {
182
- A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
183
- UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
184
- SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
185
- H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
186
- PROGRESS: "progressbar", METER: "meter"
187
- };
188
-
189
- var INPUT_TYPE_ROLE = {
190
- button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
191
- range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
192
- url: "textbox", password: "textbox", text: "textbox", image: "button"
193
- };
194
-
195
- var CONTENT_NAMED_ROLES = {
196
- button: true, link: true, heading: true, option: true, cell: true,
197
- columnheader: true, listitem: true, menuitem: true, tab: true
198
- };
199
-
200
- function implicitRole(el) {
201
- var explicit = el.getAttribute("role");
202
- if (explicit) return explicit;
203
- var tag = el.tagName;
204
- if (tag === "INPUT") {
205
- var type = (el.getAttribute("type") || "text").toLowerCase();
206
- return INPUT_TYPE_ROLE[type] || "textbox";
207
- }
208
- if (tag === "A" && !el.getAttribute("href")) return "";
209
- if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
210
- return IMPLICIT_ROLE_BY_TAG[tag];
211
- }
212
- // Deliberate divergence: Chrome's real AX tree says "generic" here,
213
- // but "textbox" is the useful signal an agent needs. Chrome is out of
214
- // step, do not "fix" this toward parity.
215
- if (el.isContentEditable) return "textbox";
216
- return "";
217
- }
227
+ ${ACCNAME_HELPERS_SOURCE}
218
228
 
219
229
  function headingLevel(el) {
220
230
  var m = /^H([1-6])$/.exec(el.tagName);
package/src/cdp/driver.ts CHANGED
@@ -5,9 +5,11 @@
5
5
  * one connection via openPage and holds it for the PageDriver's life; release() closes it. Uid
6
6
  * codec (scheme "cdp"): `cdp:<backendDOMNodeId>`, or a bare legacy numeric uid, per THE UID CODEC block in ../driver.ts.
7
7
  */
8
- import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget } from "../client.ts";
8
+ import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget, type PageConnection } from "../client.ts";
9
+ import { openSession } from "./session.ts";
9
10
  import type { Target, TargetSelector } from "../types.ts";
10
- import { LeaseConflictError } from "../leases.ts";
11
+ import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
12
+ import { currentEndpoint } from "../endpoints.ts";
11
13
  import { BEACON_READ_EXPRESSION, BEACON_SOURCE, BeaconSessions, RENDERER_PROBE_EXPRESSION, RENDERER_PROBE_TIMEOUT_MS, sendInput } from "../activity.ts";
12
14
  import { resolveUid } from "../tools/snapshot.ts";
13
15
  import { resolveWorkerSelector } from "./workers.ts";
@@ -81,7 +83,7 @@ export function cdpSameSite(sameSite?: "strict" | "lax" | "none" | "default"): "
81
83
 
82
84
  /* ---------------------- copied helpers, see attributions below ---------------------- */
83
85
  // Copied verbatim from src/tools/input.ts `centerOf`: scroll into view, read viewport-space center.
84
- async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: number; y: number }> {
86
+ async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: number; y: number }> {
85
87
  const fn = "function(){this.scrollIntoView({block:'center',inline:'center'});const r=this.getBoundingClientRect();if(r.width===0&&r.height===0)return null;return {x:r.left+r.width/2,y:r.top+r.height/2};}";
86
88
  const { result, exceptionDetails } = await conn.send<{ result: { value?: { x: number; y: number } | null }; exceptionDetails?: { text?: string } }>(
87
89
  "Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true },
@@ -90,7 +92,7 @@ async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: num
90
92
  if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
91
93
  return result.value;
92
94
  }
93
- async function focusElement(conn: CdpConnection, objectId: string): Promise<void> {
95
+ async function focusElement(conn: PageConnection, objectId: string): Promise<void> {
94
96
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
95
97
  }
96
98
  /**
@@ -112,10 +114,10 @@ async function focusElement(conn: CdpConnection, objectId: string): Promise<void
112
114
  const ARM_SCROLL_SETTLE_WATCH =
113
115
  "(function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" +
114
116
  "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});})()";
115
- async function armScrollSettleWatch(conn: CdpConnection): Promise<void> {
117
+ async function armScrollSettleWatch(conn: PageConnection): Promise<void> {
116
118
  await conn.send("Runtime.evaluate", { expression: ARM_SCROLL_SETTLE_WATCH, returnByValue: true });
117
119
  }
118
- async function awaitScrollSettle(conn: CdpConnection): Promise<void> {
120
+ async function awaitScrollSettle(conn: PageConnection): Promise<void> {
119
121
  // Best-effort: a navigation racing the wheel event could tear down window.__cdpScrollSettle
120
122
  // before this reads it, and that is not a scroll failure worth surfacing as one.
121
123
  await conn.send("Runtime.evaluate", { expression: "window.__cdpScrollSettle", awaitPromise: true, returnByValue: true }).catch(() => undefined);
@@ -129,7 +131,7 @@ async function awaitScrollSettle(conn: CdpConnection): Promise<void> {
129
131
  // It is a parameter rather than a `conn.send` here because the choke point is per-PAGE
130
132
  // (it knows the target id) and this helper only has a connection.
131
133
  async function setValueOnObject(
132
- conn: CdpConnection,
134
+ conn: PageConnection,
133
135
  objectId: string,
134
136
  value: string,
135
137
  sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
@@ -245,7 +247,7 @@ function axExtras(node: AxNode): Record<string, string> {
245
247
  }
246
248
  /* ------------------------------- locator helpers ------------------------------- */
247
249
  // css branch copied from src/tools/input.ts `resolveElement`; uid/text/xpath branches are new.
248
- async function resolveElementLocator(conn: CdpConnection, loc: ElementLocator): Promise<{ objectId: string }> {
250
+ async function resolveElementLocator(conn: PageConnection, loc: ElementLocator): Promise<{ objectId: string }> {
249
251
  if ("uid" in loc) {
250
252
  return resolveUid(conn, decodeUid(loc.uid)).catch(() => {
251
253
  throw driverError("stale-uid", `uid does not resolve: ${loc.uid}`);
@@ -270,7 +272,7 @@ async function resolveElementLocator(conn: CdpConnection, loc: ElementLocator):
270
272
  * XPath expression and disambiguates them itself. Not copied from any tools/ module (none
271
273
  * implement this); built only on the client primitives per CONTRACT.md rule 2.
272
274
  */
273
- async function searchLocate(conn: CdpConnection, query: string): Promise<number> {
275
+ async function searchLocate(conn: PageConnection, query: string): Promise<number> {
274
276
  await conn.send("DOM.getDocument", { depth: 0 }).catch(() => undefined);
275
277
  const { searchId, resultCount } = await conn.send<{ searchId: string; resultCount: number }>("DOM.performSearch", { query });
276
278
  try {
@@ -285,7 +287,7 @@ async function searchLocate(conn: CdpConnection, query: string): Promise<number>
285
287
  }
286
288
  }
287
289
 
288
- async function backendNodeIdOf(conn: CdpConnection, loc: ElementLocator): Promise<number> {
290
+ async function backendNodeIdOf(conn: PageConnection, loc: ElementLocator): Promise<number> {
289
291
  if ("uid" in loc) return decodeUid(loc.uid);
290
292
  if ("css" in loc) {
291
293
  const { objectId } = await resolveElementLocator(conn, loc);
@@ -323,7 +325,7 @@ interface LayoutMetrics {
323
325
  cssVisualViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number };
324
326
  cssContentSize?: { width: number; height: number };
325
327
  }
326
- async function layoutMetrics(conn: CdpConnection): Promise<LayoutMetrics> {
328
+ async function layoutMetrics(conn: PageConnection): Promise<LayoutMetrics> {
327
329
  return conn.send<LayoutMetrics>("Page.getLayoutMetrics");
328
330
  }
329
331
  /**
@@ -554,7 +556,7 @@ export function planTiledCapture(
554
556
  * document-frame correction below is what buys correctness. Keeping it also means the offset this
555
557
  * scroll CREATES must be read after it settles — see capture()'s ordering.
556
558
  */
557
- async function elementBox(conn: CdpConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> {
559
+ async function elementBox(conn: PageConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> {
558
560
  const backendNodeId = await backendNodeIdOf(conn, loc);
559
561
  await conn.send("DOM.scrollIntoViewIfNeeded", { backendNodeId }).catch(() => undefined);
560
562
  const box = await conn.send<{ model: { content: number[] } }>("DOM.getBoxModel", { backendNodeId });
@@ -663,7 +665,7 @@ class CdpPageDriver implements PageDriver {
663
665
  // side effect) it did not have before this migration. See the per-method comments below.
664
666
  private readonly enabledDomains = new Set<string>();
665
667
  private released = false;
666
- constructor(private readonly conn: CdpConnection, target: Target, readonly browser: BrowserDriver) {
668
+ constructor(private readonly conn: PageConnection, target: Target, readonly browser: BrowserDriver) {
667
669
  this.info = { id: target.id, url: target.url, title: target.title, type: target.type };
668
670
  }
669
671
  private async ensureDomain(name: string): Promise<void> {
@@ -703,7 +705,7 @@ class CdpPageDriver implements PageDriver {
703
705
  * one.
704
706
  */
705
707
  private async dispatchInput<T = Record<string, unknown>>(method: string, params: Record<string, unknown> = {}): Promise<T> {
706
- return sendInput<T>(this.conn, "chrome", this.info.id, method, params);
708
+ return sendInput<T>(this.conn, chromeLeaseBackend(), this.info.id, method, params);
707
709
  }
708
710
  /** Same as ensureDomain but tolerates the enable call itself failing (matches a legacy
709
711
  * `.catch(() => undefined)` site); a failed enable is NOT re-attempted on the next call. */
@@ -1595,12 +1597,32 @@ class CdpPageDriver implements PageDriver {
1595
1597
  * process, which degrades the beacon to current-document-only — correct, since
1596
1598
  * a CLI process cannot hold anything across calls by construction.
1597
1599
  */
1598
- const beaconSessions = new BeaconSessions<CdpConnection>((conn) => conn.close());
1600
+ const beaconSessions = new BeaconSessions<PageConnection>((conn) => conn.close());
1599
1601
 
1600
- /** The page endpoint for a target id, or undefined if the browser no longer has it. */
1601
- async function targetWsUrl(targetId: string): Promise<string | undefined> {
1602
+ /** Beacon sessions are keyed by endpoint plus target id: a target id only means
1603
+ * something inside one browser, and named endpoints are separate browsers. The
1604
+ * default endpoint keeps the bare id. */
1605
+ function beaconKey(targetId: string): string {
1606
+ const backend = chromeLeaseBackend(currentEndpoint());
1607
+ return backend === "chrome" ? targetId : `${backend}\u0000${targetId}`;
1608
+ }
1609
+
1610
+ /**
1611
+ * A connection to one target by id, or undefined if the browser no longer has
1612
+ * it. The beacon paths' counterpart of client.ts's `openPage`, and deliberately
1613
+ * NOT that function: these three callers are gate-free by contract (see
1614
+ * ../driver.ts) and must not go through the lease gate `resolveTarget` applies.
1615
+ *
1616
+ * Transport-routed like `openPage`, for the same reason: on a browser-ws
1617
+ * endpoint the listing carries no per-target URL to dial.
1618
+ */
1619
+ async function openTargetConn(targetId: string, opts: { timeoutMs?: number } = {}): Promise<PageConnection | undefined> {
1602
1620
  const hit = (await listTargets()).find((t) => t.id === targetId);
1603
- return hit?.webSocketDebuggerUrl;
1621
+ if (!hit) return undefined;
1622
+ // Same marker openPage reads: no per-target URL means this endpoint serves
1623
+ // none, so the target is reached by session instead.
1624
+ if (!hit.webSocketDebuggerUrl) return openSession(targetId, opts).catch(() => undefined);
1625
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => undefined);
1604
1626
  }
1605
1627
 
1606
1628
  /**
@@ -1612,7 +1634,7 @@ async function targetWsUrl(targetId: string): Promise<string | undefined> {
1612
1634
  * its tab look exactly like a live tab nobody has touched, and the held session
1613
1635
  * would never be dropped or retried.
1614
1636
  */
1615
- async function readBeaconOver(conn: CdpConnection): Promise<number | null | undefined> {
1637
+ async function readBeaconOver(conn: PageConnection): Promise<number | null | undefined> {
1616
1638
  try {
1617
1639
  const res = await conn.send<{ result: { value?: unknown } }>("Runtime.evaluate", {
1618
1640
  expression: BEACON_READ_EXPRESSION,
@@ -1634,7 +1656,7 @@ async function readBeaconOver(conn: CdpConnection): Promise<number | null | unde
1634
1656
  * the same {responsive:false} — that IS the correct answer for both, since the
1635
1657
  * caller cannot drive either tab any faster than this already told it.
1636
1658
  */
1637
- async function probeOver(conn: CdpConnection, timeoutMs: number): Promise<{ responsive: boolean; beaconTs: number | null }> {
1659
+ async function probeOver(conn: PageConnection, timeoutMs: number): Promise<{ responsive: boolean; beaconTs: number | null }> {
1638
1660
  try {
1639
1661
  const res = await conn.send<{ result: { value?: unknown } }>(
1640
1662
  "Runtime.evaluate",
@@ -1769,7 +1791,7 @@ class CdpBrowserDriver implements BrowserDriver {
1769
1791
  // Opportunistic, not load-bearing: the beacon socket dies with the tab
1770
1792
  // anyway, and readBeaconOver's dead-connection branch would drop it on the
1771
1793
  // next read. Dropping it here just avoids holding a corpse until then.
1772
- if (res.success !== false) beaconSessions.drop(id);
1794
+ if (res.success !== false) beaconSessions.drop(beaconKey(id));
1773
1795
  return { success: res.success ?? true };
1774
1796
  });
1775
1797
  }
@@ -1821,7 +1843,8 @@ class CdpBrowserDriver implements BrowserDriver {
1821
1843
  * into a document that already has it adds no second set of listeners.
1822
1844
  */
1823
1845
  async installActivityBeacon(targetId: string): Promise<boolean> {
1824
- const held = beaconSessions.get(targetId);
1846
+ const key = beaconKey(targetId);
1847
+ const held = beaconSessions.get(key);
1825
1848
  if (held) {
1826
1849
  const rearmed = await held
1827
1850
  .send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true })
@@ -1830,11 +1853,9 @@ class CdpBrowserDriver implements BrowserDriver {
1830
1853
  if (rearmed) return true;
1831
1854
  // The socket is gone (tab closed, browser restarted): fall through and
1832
1855
  // build a fresh one rather than reporting a beacon that is not there.
1833
- beaconSessions.drop(targetId);
1856
+ beaconSessions.drop(key);
1834
1857
  }
1835
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1836
- if (!wsUrl) return false;
1837
- const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
1858
+ const conn = await openTargetConn(targetId).catch(() => undefined);
1838
1859
  if (!conn) return false;
1839
1860
  try {
1840
1861
  await conn.send("Page.enable");
@@ -1844,7 +1865,7 @@ class CdpBrowserDriver implements BrowserDriver {
1844
1865
  conn.close();
1845
1866
  return false;
1846
1867
  }
1847
- beaconSessions.set(targetId, conn);
1868
+ beaconSessions.set(key, conn);
1848
1869
  return true;
1849
1870
  }
1850
1871
 
@@ -1859,15 +1880,14 @@ class CdpBrowserDriver implements BrowserDriver {
1859
1880
  * CLI, which holds nothing.
1860
1881
  */
1861
1882
  async readActivityBeacon(targetId: string): Promise<number | null> {
1862
- const held = beaconSessions.get(targetId);
1883
+ const key = beaconKey(targetId);
1884
+ const held = beaconSessions.get(key);
1863
1885
  if (held) {
1864
1886
  const value = await readBeaconOver(held);
1865
1887
  if (value !== undefined) return value;
1866
- beaconSessions.drop(targetId);
1888
+ beaconSessions.drop(key);
1867
1889
  }
1868
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1869
- if (!wsUrl) return null;
1870
- const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
1890
+ const conn = await openTargetConn(targetId).catch(() => undefined);
1871
1891
  if (!conn) return null;
1872
1892
  try {
1873
1893
  return (await readBeaconOver(conn)) ?? null;
@@ -1891,16 +1911,10 @@ class CdpBrowserDriver implements BrowserDriver {
1891
1911
  * would let one wedged tab cost the listing two timeouts instead of one.
1892
1912
  */
1893
1913
  async probeRenderer(targetId: string, timeoutMs: number = RENDERER_PROBE_TIMEOUT_MS): Promise<{ responsive: boolean; beaconTs: number | null }> {
1894
- const held = beaconSessions.get(targetId);
1914
+ const held = beaconSessions.get(beaconKey(targetId));
1895
1915
  if (held) return probeOver(held, timeoutMs);
1896
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1897
- if (!wsUrl) return { responsive: false, beaconTs: null };
1898
- const conn = new CdpConnection(wsUrl, { timeoutMs });
1899
- try {
1900
- await conn.connect();
1901
- } catch {
1902
- return { responsive: false, beaconTs: null };
1903
- }
1916
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => undefined);
1917
+ if (!conn) return { responsive: false, beaconTs: null };
1904
1918
  try {
1905
1919
  return await probeOver(conn, timeoutMs);
1906
1920
  } finally {