codex-browser-use 0.0.0-stage → 4.8.2

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,3787 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { BridgeClient } from "./bridge-client.js";
4
+ import { assertReadOnly } from "./read-only.js";
5
+ import { buildAxDiff, buildAxState, buildDialogAxState, formatAriaSnapshot, mergeFrameAriaSnapshots, mergeFrameAxStates } from "./ax-tree.js";
6
+ import { extractContentExpression } from "./content-extractor.js";
7
+ import {
8
+ LOCATOR_RUNTIME_VERSION,
9
+ domSnapshotExpression,
10
+ hitTestFunctionDeclaration,
11
+ inspectElementAtPointExpression,
12
+ locatorExpression,
13
+ locatorInvokeExpression,
14
+ locatorResolveNodeExpression,
15
+ locatorRuntimeInstallExpression,
16
+ selectOptionFunctionDeclaration,
17
+ smartSetValueFunctionDeclaration,
18
+ waitForTextExpression,
19
+ } from "./locators.js";
20
+
21
+ export { buildAxState };
22
+
23
+ const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
24
+ const DEFAULT_LOCATOR_TIMEOUT_MS = 3_000;
25
+ const DEFAULT_SETTLE_TIMEOUT_MS = 5_000;
26
+ export const TAB_GROUP_COLORS = new Set(["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]);
27
+ const KEY_MODIFIERS = {
28
+ alt: 1,
29
+ option: 1,
30
+ ctrl: 2,
31
+ control: 2,
32
+ meta: 4,
33
+ cmd: 4,
34
+ command: 4,
35
+ super: 4,
36
+ shift: 8,
37
+ controlormeta: process.platform === "darwin" ? 4 : 2,
38
+ };
39
+ const SPECIAL_KEYS = new Map([
40
+ ["enter", { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }],
41
+ ["return", { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }],
42
+ ["tab", { key: "Tab", code: "Tab", windowsVirtualKeyCode: 9 }],
43
+ ["escape", { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }],
44
+ ["esc", { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }],
45
+ ["backspace", { key: "Backspace", code: "Backspace", windowsVirtualKeyCode: 8 }],
46
+ ["delete", { key: "Delete", code: "Delete", windowsVirtualKeyCode: 46 }],
47
+ ["space", { key: " ", code: "Space", windowsVirtualKeyCode: 32, text: " " }],
48
+ ["arrowup", { key: "ArrowUp", code: "ArrowUp", windowsVirtualKeyCode: 38 }],
49
+ ["up", { key: "ArrowUp", code: "ArrowUp", windowsVirtualKeyCode: 38 }],
50
+ ["arrowdown", { key: "ArrowDown", code: "ArrowDown", windowsVirtualKeyCode: 40 }],
51
+ ["down", { key: "ArrowDown", code: "ArrowDown", windowsVirtualKeyCode: 40 }],
52
+ ["arrowleft", { key: "ArrowLeft", code: "ArrowLeft", windowsVirtualKeyCode: 37 }],
53
+ ["left", { key: "ArrowLeft", code: "ArrowLeft", windowsVirtualKeyCode: 37 }],
54
+ ["arrowright", { key: "ArrowRight", code: "ArrowRight", windowsVirtualKeyCode: 39 }],
55
+ ["right", { key: "ArrowRight", code: "ArrowRight", windowsVirtualKeyCode: 39 }],
56
+ ["home", { key: "Home", code: "Home", windowsVirtualKeyCode: 36 }],
57
+ ["end", { key: "End", code: "End", windowsVirtualKeyCode: 35 }],
58
+ ["pageup", { key: "PageUp", code: "PageUp", windowsVirtualKeyCode: 33 }],
59
+ ["pagedown", { key: "PageDown", code: "PageDown", windowsVirtualKeyCode: 34 }],
60
+ ["insert", { key: "Insert", code: "Insert", windowsVirtualKeyCode: 45 }],
61
+ ]);
62
+
63
+ /**
64
+ * Parse a key or chord such as "Return", "Tab" or "super+a".
65
+ * @param {string} combo
66
+ * @returns {{key:string, code:string, windowsVirtualKeyCode:number, modifiers:number, text?:string}}
67
+ */
68
+ export function parseKeyCombo(combo) {
69
+ const parts = String(combo).split("+").map((part) => part.trim()).filter(Boolean);
70
+ if (parts.length === 0) throw new Error("A key is required");
71
+ const token = parts.pop();
72
+ let modifiers = 0;
73
+ for (const part of parts) {
74
+ const mask = KEY_MODIFIERS[part.toLowerCase()];
75
+ if (!mask) throw new Error(`Unknown key modifier: ${part}`);
76
+ modifiers |= mask;
77
+ }
78
+ const special = SPECIAL_KEYS.get(token.toLowerCase());
79
+ if (special) return { ...special, modifiers };
80
+ if (/^[a-z]$/iu.test(token)) {
81
+ const upper = token.toUpperCase();
82
+ return {
83
+ key: token,
84
+ code: `Key${upper}`,
85
+ windowsVirtualKeyCode: upper.charCodeAt(0),
86
+ modifiers,
87
+ text: modifiers === 0 ? token : undefined,
88
+ };
89
+ }
90
+ if (/^[0-9]$/u.test(token)) {
91
+ return {
92
+ key: token,
93
+ code: `Digit${token}`,
94
+ windowsVirtualKeyCode: token.charCodeAt(0),
95
+ modifiers,
96
+ text: modifiers === 0 ? token : undefined,
97
+ };
98
+ }
99
+ const fn = /^f(\d{1,2})$/iu.exec(token);
100
+ if (fn) {
101
+ const number = Number(fn[1]);
102
+ return { key: `F${number}`, code: `F${number}`, windowsVirtualKeyCode: 111 + number, modifiers };
103
+ }
104
+ throw new Error(`Unsupported key: ${token}`);
105
+ }
106
+
107
+ /** @param {string|string[]|undefined} modifiers @returns {number} */
108
+ function parseModifiers(modifiers) {
109
+ if (!modifiers) return 0;
110
+ const list = Array.isArray(modifiers) ? modifiers : String(modifiers).split("+");
111
+ let mask = 0;
112
+ for (const mod of list) {
113
+ const part = String(mod).trim().toLowerCase();
114
+ if (!part) continue;
115
+ const bit = KEY_MODIFIERS[part];
116
+ if (!bit) throw new Error(`Unknown key modifier: ${mod}`);
117
+ mask |= bit;
118
+ }
119
+ return mask;
120
+ }
121
+
122
+ /** @param {string} button @returns {number} */
123
+ function buttonMask(button) {
124
+ if (button === "left") return 1;
125
+ if (button === "right") return 2;
126
+ if (button === "middle") return 4;
127
+ return 0;
128
+ }
129
+
130
+ /** @param {string} url @returns {string} */
131
+ export function normalizeUrl(url) {
132
+ const value = String(url).trim();
133
+ if (value === "about:blank") return value;
134
+ if (/^(?:https?|about|data|file|blob|chrome-error):/iu.test(value)) return value;
135
+ if (value.startsWith("/") || value.startsWith("./") || value.startsWith("../")) {
136
+ return `file://${path.resolve(value)}`;
137
+ }
138
+ if (/^[a-z]:[\\/]/iu.test(value)) return `file:///${value.replaceAll("\\", "/")}`;
139
+ return `https://${value}`;
140
+ }
141
+
142
+ /**
143
+ * Compare two URLs after the normalizations a browser applies, such as adding a
144
+ * trailing slash to an origin and dropping an empty fragment.
145
+ * @param {string} current
146
+ * @param {string} target
147
+ * @returns {boolean}
148
+ */
149
+ export function sameUrl(current, target) {
150
+ const normalize = (value) => {
151
+ try {
152
+ const url = new URL(value);
153
+ return `${url.origin}${url.pathname.replace(/\/+$/u, "")}${url.search}${url.hash}`;
154
+ } catch {
155
+ return value.replace(/\/+$/u, "");
156
+ }
157
+ };
158
+ return normalize(current) === normalize(target);
159
+ }
160
+
161
+ /** @param {unknown} value @returns {string[]} */
162
+ function splitIndices(value) {
163
+ if (value === undefined || value === null || value === "") return [];
164
+ return String(value).split(/[,;\s]+/u).map((entry) => entry.trim()).filter(Boolean);
165
+ }
166
+
167
+ /** @param {unknown} ms @returns {Promise<void>} */
168
+ function sleep(ms) {
169
+ return new Promise((resolve) => setTimeout(resolve, ms));
170
+ }
171
+
172
+ /** @param {Record<string, any>} params @returns {string} */
173
+ function formatConsoleArgs(params) {
174
+ if (!Array.isArray(params?.args)) return "";
175
+ return params.args.map((arg) => {
176
+ if (arg.value !== undefined) return typeof arg.value === "string" ? arg.value : JSON.stringify(arg.value);
177
+ if (arg.description) return String(arg.description);
178
+ return `[${arg.type ?? "unknown"}]`;
179
+ }).join(" ");
180
+ }
181
+
182
+ /**
183
+ * Browser facade over the project's Chrome bridge. Speaks CDP directly through the
184
+ * extension + native host without requiring any proprietary runtime or Playwright install.
185
+ */
186
+ export class BridgeBrowser {
187
+ /**
188
+ * @param {{request:(method:string,params?:Record<string,unknown>)=>Promise<unknown>, close:()=>Promise<void>, sessionId:string, turnId:string, info?:Record<string,unknown>, frameSessions?:Map<number, Map<string,string>>}} options
189
+ */
190
+ constructor({ request, close, sessionId, turnId, info = {}, frameSessions = new Map() }) {
191
+ this.request = request;
192
+ this.closeFn = close;
193
+ this.sessionId = sessionId;
194
+ this.turnId = turnId;
195
+ this.info = info;
196
+ this.frameSessions = frameSessions;
197
+ this.autoAttached = new Set();
198
+ /** @type {Map<number,{id:number,url?:string,title?:string,owned?:boolean,origin?:string}>} */
199
+ this.tabs = new Map();
200
+ /** @type {Set<number>} */
201
+ this.ownedTabs = new Set();
202
+ this.activeTabId = null;
203
+ /** @type {Set<number>} */
204
+ this.attached = new Set();
205
+ /** @type {Map<number, Promise<void>>} */
206
+ this.attaching = new Map();
207
+ /** @type {Set<(event: Record<string, unknown>) => void>} */
208
+ this.eventListeners = new Set();
209
+ /** @type {Map<number, Set<string>>} */
210
+ this.enabledDomains = new Map();
211
+ /** @type {Map<number, Map<string, Promise<void>>>} */
212
+ this.enablingDomains = new Map();
213
+ /** @type {Set<string>} */
214
+ this.enabledChildAxSessions = new Set();
215
+ /** @type {Map<number, {navRevision:number, routes:Map<string, any>}>} */
216
+ this.frameRouteCache = new Map();
217
+ /** @type {Map<string, number>} */
218
+ this.locatorRuntimeInstalled = new Map();
219
+ /** @type {Set<string>} */
220
+ this.statelessEvalTabs = new Set();
221
+ this.supportsPassiveRead = Boolean(info?.apiSupportOverrides?.["BrowserUser.getTabContext"]);
222
+ /** @type {Map<number, Map<string,{backendDOMNodeId:number|null,role:string,name:string,frameId?:string|null,sessionId?:string|null,actions?:string[],dialogControl?:string}>>} */
223
+ this.axCache = new Map();
224
+ /** @type {Map<number, {documentKey:string, entries:Array<any>}>} */
225
+ this.lastAxSnapshots = new Map();
226
+ /** @type {Map<number, {hasEvents:boolean, loading:boolean, committed:boolean, painted:boolean, ready:boolean, navRevision:number, mainFrameId:string|null, loaderId:string|null, url:string|null, lastAxUpdateMs:number, dialog:null|{type:string,message:string,defaultPrompt:string,url:string}, fileChooser:null|{backendNodeId?:number,mode?:string,frameId?:string}, consoleLogs:Array<{level:string,message:string,timestamp:string,url?:string}>, inFlightRequests:Set<string>, notifications:string[]}>} */
227
+ this.tabStates = new Map();
228
+ this.sessionName = null;
229
+ this.closed = false;
230
+ }
231
+
232
+ /**
233
+ * @param {{bridgeFile:string, sessionId?:string, turnId?:string, requestTimeoutMs?:number}} options
234
+ * @returns {Promise<BridgeBrowser>}
235
+ */
236
+ static async connect({ bridgeFile, sessionId = randomUUID(), turnId = randomUUID(), requestTimeoutMs }) {
237
+ const client = new BridgeClient({ bridgeFile, requestTimeoutMs });
238
+ await client.connect();
239
+ const request = (method, params = {}) => client.request(method, params);
240
+ const frameSessions = new Map();
241
+ let browserRef = null;
242
+ client.onEvent((method, params) => {
243
+ if (method === "onCDPEvent") {
244
+ browserRef?.handleCdpEvent(params);
245
+ } else if (method === "onCDPDetach" && Number.isSafeInteger(params?.tabId)) {
246
+ const tabId = params.tabId;
247
+ browserRef?.#clearTabCaches(tabId);
248
+ browserRef?.attached.delete(tabId);
249
+ browserRef?.autoAttached.delete(tabId);
250
+ } else if (method === "onTabCreated") {
251
+ browserRef?.handleTabCreated(params);
252
+ }
253
+ });
254
+ const info = await request("getInfo", { session_id: sessionId, turn_id: turnId });
255
+ const envCursorMode = process.env.BROWSER_USE_CURSOR_MODE;
256
+ if (envCursorMode === "fast" || envCursorMode === "smooth" || envCursorMode === "off") {
257
+ await request("setConfig", { session_id: sessionId, turn_id: turnId, cursorMode: envCursorMode }).catch(() => {});
258
+ }
259
+ browserRef = new BridgeBrowser({ request, close: () => client.close(), sessionId, turnId, info: info ?? {}, frameSessions });
260
+ return browserRef;
261
+ }
262
+
263
+ /** @param {Record<string, any>} params @returns {void} */
264
+ handleTabCreated(params) {
265
+ const tab = params?.tab;
266
+ const openerTabId = params?.openerTabId;
267
+ if (!tab || !Number.isSafeInteger(tab.id)) return;
268
+ this.ownedTabs.add(tab.id);
269
+ this.tabs.set(tab.id, { ...tab, owned: true, origin: "agent" });
270
+ if (Number.isSafeInteger(openerTabId)) {
271
+ const openerState = this.#tabState(openerTabId);
272
+ openerState.popups.push({
273
+ tab_id: String(tab.id),
274
+ url: tab.url || "",
275
+ title: tab.title || "",
276
+ opener_tab_id: String(openerTabId),
277
+ createdAtMs: Date.now(),
278
+ });
279
+ if (openerState.popups.length > 50) openerState.popups.shift();
280
+ this.#pushNotification(openerState, `Popup tab ${tab.id} opened from tab ${openerTabId}.`);
281
+ this.#notifyWaiters(openerState);
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Handle incoming CDP events for iframe session tracking, navigation settling,
287
+ * dialogs, file choosers, console messages, and active network requests.
288
+ * @param {Record<string, any>} params
289
+ */
290
+ handleCdpEvent(params) {
291
+ if (!params || typeof params !== "object") return;
292
+ const tabId = params.source?.tabId;
293
+ if (!Number.isSafeInteger(tabId)) return;
294
+ const sessionId = params.source?.sessionId;
295
+ const method = params.method;
296
+ const event = params.params ?? {};
297
+
298
+ if (method === "Target.attachedToTarget") {
299
+ const frameId = event?.targetInfo?.targetId;
300
+ const frameSessionId = event?.sessionId;
301
+ if (event?.targetInfo?.type === "iframe" && typeof frameId === "string" && typeof frameSessionId === "string") {
302
+ const map = this.frameSessions.get(tabId) ?? new Map();
303
+ map.set(frameId, frameSessionId);
304
+ this.frameSessions.set(tabId, map);
305
+ this.#notifyWaiters(this.tabStates.get(tabId));
306
+ }
307
+ return;
308
+ }
309
+ if (method === "Target.detachedFromTarget") {
310
+ const map = this.frameSessions.get(tabId);
311
+ if (map && typeof event?.sessionId === "string") {
312
+ for (const [frameId, id] of map) if (id === event.sessionId) map.delete(frameId);
313
+ }
314
+ if (typeof event?.sessionId === "string") {
315
+ this.enabledChildAxSessions.delete(event.sessionId);
316
+ this.#clearLocatorRuntime(tabId, event.sessionId);
317
+ }
318
+ this.frameRouteCache.delete(tabId);
319
+ return;
320
+ }
321
+
322
+ const state = this.#tabState(tabId);
323
+ state.hasEvents = true;
324
+
325
+ if (method === "Accessibility.loadComplete" || method === "Accessibility.nodesUpdated") {
326
+ state.lastAxUpdateMs = Date.now();
327
+ return;
328
+ }
329
+ if (method === "Page.javascriptDialogOpening") {
330
+ state.dialog = {
331
+ type: String(event.type || "alert"),
332
+ message: String(event.message || ""),
333
+ defaultPrompt: String(event.defaultPrompt || ""),
334
+ url: String(event.url || ""),
335
+ };
336
+ this.#pushNotification(state, `JavaScript ${state.dialog.type} dialog opened: ${JSON.stringify(state.dialog.message)}`);
337
+ this.#notifyWaiters(state);
338
+ return;
339
+ }
340
+ if (method === "Page.javascriptDialogClosed") {
341
+ state.dialog = null;
342
+ this.#notifyWaiters(state);
343
+ return;
344
+ }
345
+ if (method === "Page.fileChooserOpened") {
346
+ state.fileChooser = {
347
+ backendNodeId: event.backendNodeId,
348
+ mode: event.mode,
349
+ frameId: event.frameId,
350
+ openedAtMs: Date.now(),
351
+ };
352
+ this.#pushNotification(state, "File chooser opened; call browser_upload_files with file paths.");
353
+ this.#notifyWaiters(state);
354
+ return;
355
+ }
356
+ if (method === "Bridge.downloadCreated" || method === "Bridge.downloadChanged" ||
357
+ method === "Page.downloadWillBegin" || method === "Page.downloadProgress") {
358
+ const dlId = String(event.id ?? event.guid ?? "");
359
+ if (dlId) {
360
+ let entry = state.downloadById.get(dlId);
361
+ if (!entry) {
362
+ entry = {
363
+ id: dlId,
364
+ url: typeof event.url === "string" ? event.url : "",
365
+ suggestedFilename: typeof event.suggestedFilename === "string"
366
+ ? event.suggestedFilename
367
+ : (typeof event.filename === "string" && event.filename ? path.basename(event.filename) : ""),
368
+ filename: typeof event.filename === "string" ? event.filename : "",
369
+ state: String(event.state || "in_progress"),
370
+ error: typeof event.error === "string" ? event.error : null,
371
+ createdAtMs: Date.now(),
372
+ };
373
+ state.downloadById.set(dlId, entry);
374
+ state.downloads.push(entry);
375
+ if (state.downloads.length > 100) {
376
+ const removed = state.downloads.splice(0, state.downloads.length - 100);
377
+ for (const item of removed) state.downloadById.delete(item.id);
378
+ }
379
+ } else {
380
+ if (typeof event.url === "string" && event.url) entry.url = event.url;
381
+ if (typeof event.filename === "string" && event.filename) {
382
+ entry.filename = event.filename;
383
+ if (!entry.suggestedFilename) entry.suggestedFilename = path.basename(event.filename);
384
+ }
385
+ if (typeof event.suggestedFilename === "string" && event.suggestedFilename) {
386
+ entry.suggestedFilename = event.suggestedFilename;
387
+ }
388
+ if (typeof event.state === "string") entry.state = event.state;
389
+ if (typeof event.error === "string") entry.error = event.error;
390
+ }
391
+ this.#notifyWaiters(state);
392
+ }
393
+ return;
394
+ }
395
+ if (method === "Runtime.consoleAPICalled") {
396
+ const level = event.type === "warning" ? "warn" : (event.type || "log");
397
+ const entry = {
398
+ level,
399
+ message: formatConsoleArgs(event),
400
+ timestamp: new Date().toISOString(),
401
+ url: event.stackTrace?.callFrames?.[0]?.url,
402
+ };
403
+ this.#pushLog(state, entry);
404
+ this.#emitEvent({ kind: "console", tabId, entry });
405
+ return;
406
+ }
407
+ if (method === "Runtime.exceptionThrown") {
408
+ const details = event.exceptionDetails ?? {};
409
+ const msg = details.exception?.description || details.text || "Uncaught exception";
410
+ const entry = {
411
+ level: "error",
412
+ message: msg,
413
+ timestamp: new Date().toISOString(),
414
+ url: details.url,
415
+ };
416
+ this.#pushLog(state, entry);
417
+ this.#pushNotification(state, `Page exception: ${msg.split("\n")[0].slice(0, 160)}`);
418
+ this.#emitEvent({ kind: "pageerror", tabId, entry, error: new Error(msg) });
419
+ return;
420
+ }
421
+ if (method === "Network.requestWillBeSent" && typeof event.requestId === "string") {
422
+ if (state.inFlightRequests.size < 256) state.inFlightRequests.add(event.requestId);
423
+ const url = event.request?.url;
424
+ if (typeof url === "string") {
425
+ const entry = {
426
+ requestId: event.requestId,
427
+ url,
428
+ method: String(event.request?.method || "GET"),
429
+ resourceType: String(event.type || "Other"),
430
+ status: null,
431
+ statusText: null,
432
+ mimeType: null,
433
+ failed: false,
434
+ errorText: null,
435
+ timestamp: new Date().toISOString(),
436
+ };
437
+ state.networkById.set(event.requestId, entry);
438
+ state.networkLogs.push(entry);
439
+ if (state.networkLogs.length > 300) {
440
+ const removed = state.networkLogs.splice(0, state.networkLogs.length - 300);
441
+ for (const item of removed) state.networkById.delete(item.requestId);
442
+ }
443
+ }
444
+ this.#notifyWaiters(state);
445
+ return;
446
+ }
447
+ if (method === "Network.responseReceived" && typeof event.requestId === "string") {
448
+ const resp = event.response ?? {};
449
+ let entry = state.networkById.get(event.requestId);
450
+ if (!entry && typeof resp.url === "string") {
451
+ entry = {
452
+ requestId: event.requestId,
453
+ url: resp.url,
454
+ method: "GET",
455
+ resourceType: String(event.type || "Other"),
456
+ status: null,
457
+ statusText: null,
458
+ mimeType: null,
459
+ failed: false,
460
+ errorText: null,
461
+ timestamp: new Date().toISOString(),
462
+ };
463
+ state.networkById.set(event.requestId, entry);
464
+ state.networkLogs.push(entry);
465
+ if (state.networkLogs.length > 300) {
466
+ const removed = state.networkLogs.splice(0, state.networkLogs.length - 300);
467
+ for (const item of removed) state.networkById.delete(item.requestId);
468
+ }
469
+ }
470
+ if (entry) {
471
+ if (typeof resp.status === "number") entry.status = resp.status;
472
+ if (typeof resp.statusText === "string") entry.statusText = resp.statusText;
473
+ if (typeof resp.mimeType === "string") entry.mimeType = resp.mimeType;
474
+ if (typeof event.type === "string" && entry.resourceType === "Other") entry.resourceType = event.type;
475
+ }
476
+ this.#notifyWaiters(state);
477
+ return;
478
+ }
479
+ if (method === "Network.loadingFinished" && typeof event.requestId === "string") {
480
+ state.inFlightRequests.delete(event.requestId);
481
+ this.#notifyWaiters(state);
482
+ return;
483
+ }
484
+ if (method === "Network.loadingFailed" && typeof event.requestId === "string") {
485
+ state.inFlightRequests.delete(event.requestId);
486
+ const entry = state.networkById.get(event.requestId);
487
+ if (entry) {
488
+ entry.failed = true;
489
+ entry.errorText = typeof event.errorText === "string" ? event.errorText : "Request failed";
490
+ }
491
+ this.#notifyWaiters(state);
492
+ return;
493
+ }
494
+
495
+ if (sessionId !== undefined) return;
496
+ switch (method) {
497
+ case "Page.frameStartedLoading":
498
+ if (!state.mainFrameId || event.frameId === state.mainFrameId) {
499
+ state.loading = true;
500
+ state.committed = false;
501
+ state.painted = false;
502
+ state.ready = false;
503
+ state.domContentLoaded = false;
504
+ state.loaded = false;
505
+ state.navRevision += 1;
506
+ this.#clearLocatorRuntime(tabId);
507
+ this.#notifyWaiters(state);
508
+ }
509
+ break;
510
+ case "Page.frameNavigated":
511
+ if (!event.frame?.parentId) {
512
+ state.mainFrameId = event.frame?.id ?? state.mainFrameId;
513
+ state.loaderId = event.frame?.loaderId ?? state.loaderId;
514
+ state.url = event.frame?.url ?? state.url;
515
+ state.committed = true;
516
+ if (event.type === "BackForwardCacheRestore") {
517
+ state.loading = false;
518
+ state.painted = true;
519
+ state.ready = true;
520
+ state.domContentLoaded = true;
521
+ state.loaded = true;
522
+ }
523
+ state.navRevision += 1;
524
+ this.#clearLocatorRuntime(tabId);
525
+ this.#notifyWaiters(state);
526
+ }
527
+ break;
528
+ case "Page.navigatedWithinDocument":
529
+ if (!state.mainFrameId || event.frameId === state.mainFrameId) {
530
+ state.url = event.url ?? state.url;
531
+ state.loading = false;
532
+ state.committed = true;
533
+ state.ready = true;
534
+ state.domContentLoaded = true;
535
+ state.loaded = true;
536
+ state.navRevision += 1;
537
+ this.#notifyWaiters(state);
538
+ }
539
+ break;
540
+ case "Page.domContentEventFired":
541
+ state.domContentLoaded = true;
542
+ state.ready = true;
543
+ this.#notifyWaiters(state);
544
+ break;
545
+ case "Page.loadEventFired":
546
+ state.loading = false;
547
+ state.painted = true;
548
+ state.ready = true;
549
+ state.domContentLoaded = true;
550
+ state.loaded = true;
551
+ this.#notifyWaiters(state);
552
+ break;
553
+ case "Page.frameStoppedLoading":
554
+ if (!state.mainFrameId || event.frameId === state.mainFrameId) {
555
+ state.loading = false;
556
+ state.ready = true;
557
+ state.domContentLoaded = true;
558
+ state.loaded = true;
559
+ this.#notifyWaiters(state);
560
+ }
561
+ break;
562
+ case "Page.lifecycleEvent":
563
+ if (event.name === "firstMeaningfulPaint" || event.name === "firstContentfulPaint") {
564
+ state.painted = true;
565
+ this.#notifyWaiters(state);
566
+ } else if (event.name === "DOMContentLoaded") {
567
+ state.domContentLoaded = true;
568
+ state.ready = true;
569
+ this.#notifyWaiters(state);
570
+ } else if (event.name === "load" || event.name === "networkIdle") {
571
+ state.loading = false;
572
+ state.ready = true;
573
+ state.domContentLoaded = true;
574
+ state.loaded = true;
575
+ this.#notifyWaiters(state);
576
+ }
577
+ break;
578
+ default:
579
+ break;
580
+ }
581
+ }
582
+
583
+ #tabState(tabId) {
584
+ let state = this.tabStates.get(tabId);
585
+ if (!state) {
586
+ state = {
587
+ hasEvents: false,
588
+ loading: false,
589
+ committed: false,
590
+ painted: false,
591
+ ready: false,
592
+ domContentLoaded: false,
593
+ loaded: false,
594
+ navRevision: 0,
595
+ mainFrameId: null,
596
+ loaderId: null,
597
+ url: null,
598
+ lastAxUpdateMs: 0,
599
+ dialog: null,
600
+ fileChooser: null,
601
+ consoleLogs: [],
602
+ networkLogs: [],
603
+ networkById: new Map(),
604
+ networkBodyCaptureEnabled: false,
605
+ downloads: [],
606
+ downloadById: new Map(),
607
+ downloadWatchCount: 0,
608
+ popups: [],
609
+ viewportOverride: null,
610
+ inFlightRequests: new Set(),
611
+ notifications: [],
612
+ waiters: new Set(),
613
+ };
614
+ this.tabStates.set(tabId, state);
615
+ }
616
+ return state;
617
+ }
618
+
619
+ #notifyWaiters(state) {
620
+ if (!state?.waiters?.size) return;
621
+ for (const wake of state.waiters) wake();
622
+ }
623
+
624
+ /** @param {number} tabId @param {number} maxWaitMs */
625
+ async #waitForTabWakeup(tabId, maxWaitMs) {
626
+ const waitMs = Math.max(1, Number(maxWaitMs) || 1);
627
+ const state = this.#tabState(tabId);
628
+ let wakeFn;
629
+ let timer;
630
+ await new Promise((resolve) => {
631
+ wakeFn = () => {
632
+ clearTimeout(timer);
633
+ state.waiters.delete(wakeFn);
634
+ resolve();
635
+ };
636
+ timer = setTimeout(wakeFn, waitMs);
637
+ state.waiters.add(wakeFn);
638
+ });
639
+ }
640
+
641
+ #pushLog(state, entry) {
642
+ state.consoleLogs.push(entry);
643
+ if (state.consoleLogs.length > 500) {
644
+ state.consoleLogs.splice(0, state.consoleLogs.length - 500);
645
+ }
646
+ }
647
+
648
+ #pushNotification(state, text) {
649
+ if (state.notifications.at(-1) === text) return;
650
+ state.notifications.push(text);
651
+ if (state.notifications.length > 20) state.notifications.shift();
652
+ }
653
+
654
+ /** @param {number} tabId @returns {string[]} */
655
+ drainNotifications(tabId) {
656
+ const state = this.tabStates.get(tabId);
657
+ if (!state || state.notifications.length === 0) return [];
658
+ return state.notifications.splice(0, state.notifications.length);
659
+ }
660
+
661
+ /** @param {(event: Record<string, unknown>) => void} listener @returns {() => void} */
662
+ addEventListener(listener) {
663
+ if (typeof listener !== "function") return () => {};
664
+ this.eventListeners.add(listener);
665
+ return () => {
666
+ this.eventListeners.delete(listener);
667
+ };
668
+ }
669
+
670
+ /** @param {Record<string, unknown>} event @returns {void} */
671
+ #emitEvent(event) {
672
+ if (this.eventListeners.size === 0) return;
673
+ for (const listener of [...this.eventListeners]) {
674
+ try {
675
+ listener(event);
676
+ } catch {
677
+ // Ignore user script listener failures.
678
+ }
679
+ }
680
+ }
681
+
682
+ /** @param {string} method @param {Record<string, unknown>} [params] */
683
+ #rpc(method, params = {}) {
684
+ return this.request(method, { session_id: this.sessionId, turn_id: this.turnId, ...params });
685
+ }
686
+
687
+ /** @param {number} tabId @param {string|null|undefined} sessionId @param {string} method @param {Record<string, unknown>} [params] */
688
+ async #executeCdpWithRetry(tabId, sessionId, method, params = {}) {
689
+ const target = sessionId ? { tabId, sessionId } : { tabId };
690
+ try {
691
+ return await this.#rpc("executeCdp", { target, method, commandParams: params });
692
+ } catch (error) {
693
+ const msg = error instanceof Error ? error.message : String(error);
694
+ if (!/Debugger unattached/i.test(msg)) throw error;
695
+ this.attached.delete(tabId);
696
+ this.#clearTabCaches(tabId);
697
+ this.autoAttached.delete(tabId);
698
+ await this.attach(tabId);
699
+ if (sessionId) throw error;
700
+ return await this.#rpc("executeCdp", { target: { tabId }, method, commandParams: params });
701
+ }
702
+ }
703
+
704
+ /** @param {number} tabId @param {string} method @param {Record<string, unknown>} [params] */
705
+ #cdp(tabId, method, params = {}) {
706
+ return this.#executeCdpWithRetry(tabId, null, method, params);
707
+ }
708
+
709
+ /** @param {number} tabId @param {string} sessionId @param {string} method @param {Record<string, unknown>} [params] */
710
+ #cdpIn(tabId, sessionId, method, params = {}) {
711
+ return this.#executeCdpWithRetry(tabId, sessionId, method, params);
712
+ }
713
+
714
+ /** @param {number} tabId @param {string|null|undefined} sessionId @param {string} method @param {Record<string, unknown>} [params] */
715
+ #cdpTarget(tabId, sessionId, method, params = {}) {
716
+ return sessionId ? this.#cdpIn(tabId, sessionId, method, params) : this.#cdp(tabId, method, params);
717
+ }
718
+
719
+ /** @param {number} tabId @param {string|null} [sessionId] @returns {void} */
720
+ #clearLocatorRuntime(tabId, sessionId = null) {
721
+ if (sessionId !== null) {
722
+ this.locatorRuntimeInstalled.delete(`${tabId}:${sessionId}`);
723
+ return;
724
+ }
725
+ const prefix = `${tabId}:`;
726
+ for (const key of this.locatorRuntimeInstalled.keys()) {
727
+ if (key.startsWith(prefix)) this.locatorRuntimeInstalled.delete(key);
728
+ }
729
+ }
730
+
731
+ /** @param {number} tabId @returns {void} */
732
+ #clearTabCaches(tabId) {
733
+ this.enabledDomains.delete(tabId);
734
+ this.enablingDomains.delete(tabId);
735
+ this.frameRouteCache.delete(tabId);
736
+ this.#clearLocatorRuntime(tabId);
737
+ this.#clearLocatorRuntime(tabId);
738
+ const frameMap = this.frameSessions.get(tabId);
739
+ if (frameMap) {
740
+ for (const sessionId of frameMap.values()) this.enabledChildAxSessions.delete(sessionId);
741
+ }
742
+ this.frameSessions.delete(tabId);
743
+ }
744
+
745
+ /** @param {number} tabId @param {string} domain @param {string} method @param {Record<string, unknown>} [params] @param {boolean} [bestEffort] */
746
+ async #ensureDomain(tabId, domain, method, params = {}, bestEffort = false) {
747
+ let set = this.enabledDomains.get(tabId);
748
+ if (!set) {
749
+ set = new Set();
750
+ this.enabledDomains.set(tabId, set);
751
+ }
752
+ if (set.has(domain)) return;
753
+
754
+ let inflight = this.enablingDomains.get(tabId);
755
+ if (!inflight) {
756
+ inflight = new Map();
757
+ this.enablingDomains.set(tabId, inflight);
758
+ }
759
+ const existing = inflight.get(domain);
760
+ if (existing) {
761
+ await existing;
762
+ return;
763
+ }
764
+
765
+ const task = (async () => {
766
+ try {
767
+ await this.#cdp(tabId, method, params);
768
+ set.add(domain);
769
+ } catch (error) {
770
+ if (!bestEffort) throw error;
771
+ } finally {
772
+ inflight.delete(domain);
773
+ }
774
+ })();
775
+ inflight.set(domain, task);
776
+ await task;
777
+ }
778
+
779
+ /** @param {number} tabId @returns {Promise<void>} */
780
+ async #ensureAutoAttach(tabId) {
781
+ if (this.autoAttached.has(tabId)) return;
782
+ await this.#cdp(tabId, "Target.setAutoAttach", {
783
+ autoAttach: true,
784
+ flatten: true,
785
+ waitForDebuggerOnStart: false,
786
+ filter: [{ type: "iframe", exclude: false }],
787
+ });
788
+ this.autoAttached.add(tabId);
789
+ }
790
+
791
+ /** @returns {boolean} */
792
+ #supportsUserTabs() {
793
+ return Boolean(
794
+ this.info?.apiSupportOverrides?.["BrowserUser.openTabs"] ||
795
+ this.info?.apiSupportOverrides?.["BrowserUser.claimTab"],
796
+ );
797
+ }
798
+
799
+ /**
800
+ * Claim an already-open user tab in Chrome so this session can inspect and control it.
801
+ * Claimed user tabs are released (never closed) when the turn or session ends.
802
+ * @param {unknown} tabId
803
+ * @returns {Promise<{tab_id:string,title:string,url:string,active:boolean,owned:boolean,origin:string}>}
804
+ */
805
+ async claimTab(tabId) {
806
+ this.#assertOpen();
807
+ const id = Number(tabId);
808
+ if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
809
+ let tab;
810
+ try {
811
+ tab = await this.#rpc("claimUserTab", { tabId: id });
812
+ } catch {
813
+ throw new Error("Browser tab is unavailable to this session");
814
+ }
815
+ if (!Number.isSafeInteger(tab?.id)) throw new Error("Browser tab is unavailable to this session");
816
+ this.ownedTabs.add(tab.id);
817
+ this.tabs.set(tab.id, { ...tab, owned: true, origin: tab.origin || "user" });
818
+ this.activeTabId = tab.id;
819
+ await this.attach(tab.id);
820
+ return {
821
+ tab_id: String(tab.id),
822
+ title: tab.title || "Untitled",
823
+ url: tab.url || "",
824
+ active: true,
825
+ owned: true,
826
+ origin: tab.origin || "user",
827
+ };
828
+ }
829
+
830
+ /**
831
+ * @param {{includeUserTabs?:boolean|"force"}} [options]
832
+ * @returns {Promise<Array<{tab_id:string,title:string,url:string,active:boolean,owned?:boolean,origin?:string,browser_active?:boolean}>>}
833
+ */
834
+ async listTabs({ includeUserTabs = true } = {}) {
835
+ this.#assertOpen();
836
+ const fetchUserTabs = includeUserTabs === "force" || (includeUserTabs !== false && this.#supportsUserTabs());
837
+ const [tabs, userTabs] = await Promise.all([
838
+ this.#rpc("getTabs"),
839
+ fetchUserTabs ? this.#rpc("getUserTabs").catch(() => []) : Promise.resolve([]),
840
+ ]);
841
+ this.tabs.clear();
842
+ this.ownedTabs.clear();
843
+ const result = [];
844
+ for (const tab of Array.isArray(tabs) ? tabs : []) {
845
+ if (!Number.isSafeInteger(tab?.id)) continue;
846
+ this.ownedTabs.add(tab.id);
847
+ this.tabs.set(tab.id, tab);
848
+ result.push({
849
+ tab_id: String(tab.id),
850
+ title: tab.title || "Untitled",
851
+ url: tab.url || "",
852
+ active: tab.id === this.activeTabId,
853
+ ...(fetchUserTabs ? { owned: true, origin: tab.origin || "agent" } : {}),
854
+ });
855
+ }
856
+ if (this.activeTabId !== null && !this.ownedTabs.has(this.activeTabId)) this.activeTabId = null;
857
+ if (this.activeTabId === null && this.ownedTabs.size > 0) {
858
+ this.activeTabId = this.ownedTabs.values().next().value ?? null;
859
+ }
860
+ for (const tab of Array.isArray(userTabs) ? userTabs : []) {
861
+ if (!Number.isSafeInteger(tab?.id) || this.ownedTabs.has(tab.id)) continue;
862
+ this.tabs.set(tab.id, { ...tab, owned: false, origin: "user" });
863
+ result.push({
864
+ tab_id: String(tab.id),
865
+ title: tab.title || "Untitled",
866
+ url: tab.url || "",
867
+ active: false,
868
+ browser_active: Boolean(tab.active),
869
+ owned: false,
870
+ origin: "user",
871
+ });
872
+ }
873
+ for (const entry of result) entry.active = Number(entry.tab_id) === this.activeTabId;
874
+ return result;
875
+ }
876
+
877
+ /** @param {unknown} [tabId] @param {{autoCreate?:boolean}} [options] @returns {Promise<number>} */
878
+ async #resolveTab(tabId, { autoCreate = false } = {}) {
879
+ const hasExplicit = tabId !== undefined && tabId !== null && tabId !== "";
880
+ const candidate = hasExplicit ? Number(tabId) : this.activeTabId;
881
+ if (Number.isSafeInteger(candidate) && this.ownedTabs.has(candidate)) return candidate;
882
+ await this.listTabs({ includeUserTabs: false });
883
+ if (hasExplicit) {
884
+ if (!Number.isSafeInteger(candidate)) throw new Error("A numeric tab_id is required");
885
+ if (this.ownedTabs.has(candidate)) {
886
+ this.activeTabId = candidate;
887
+ return candidate;
888
+ }
889
+ if (this.#supportsUserTabs()) {
890
+ await this.claimTab(candidate);
891
+ return candidate;
892
+ }
893
+ throw new Error("Browser tab is unavailable to this session");
894
+ }
895
+ if (this.ownedTabs.size === 0) {
896
+ if (autoCreate) {
897
+ const created = await this.newTab();
898
+ return Number(created.tab_id);
899
+ }
900
+ throw new Error("No browser tab exists in this session; call browser_new_tab first");
901
+ }
902
+ this.activeTabId = this.ownedTabs.values().next().value ?? null;
903
+ return this.activeTabId;
904
+ }
905
+
906
+ /** @param {number} tabId @returns {Promise<void>} */
907
+ async attach(tabId) {
908
+ if (this.attached.has(tabId)) return;
909
+ const inflight = this.attaching.get(tabId);
910
+ if (inflight) {
911
+ await inflight;
912
+ return;
913
+ }
914
+ const task = (async () => {
915
+ try {
916
+ await this.#rpc("attach", { tabId });
917
+ } catch (error) {
918
+ const msg = error instanceof Error ? error.message : String(error);
919
+ if (/Browser tab is unavailable to this session/i.test(msg)) {
920
+ this.ownedTabs.delete(tabId);
921
+ this.tabs.delete(tabId);
922
+ this.attached.delete(tabId);
923
+ this.#clearTabCaches(tabId);
924
+ if (this.activeTabId === tabId) this.activeTabId = this.ownedTabs.values().next().value ?? null;
925
+ }
926
+ throw error;
927
+ }
928
+ this.attached.add(tabId);
929
+ this.axCache.delete(tabId);
930
+ this.enabledDomains.delete(tabId);
931
+ this.enablingDomains.delete(tabId);
932
+ this.frameRouteCache.delete(tabId);
933
+ this.#clearLocatorRuntime(tabId);
934
+ this.#tabState(tabId);
935
+ await this.#cdp(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
936
+ })().finally(() => {
937
+ this.attaching.delete(tabId);
938
+ });
939
+ this.attaching.set(tabId, task);
940
+ await task;
941
+ }
942
+
943
+ /** @param {unknown} [tabId] @returns {Promise<void>} */
944
+ async enableRuntime(tabId) {
945
+ const id = await this.#resolveTab(tabId);
946
+ await this.attach(id);
947
+ await this.#ensureDomain(id, "Runtime", "Runtime.enable", {}, true);
948
+ }
949
+
950
+ /** @param {unknown} [tabId] @param {{autoCreate?:boolean}} [options] @returns {Promise<number>} */
951
+ async #ensureAttachedTab(tabId, { autoCreate = false } = {}) {
952
+ const hasExplicit = tabId !== undefined && tabId !== null && tabId !== "";
953
+ const id = await this.#resolveTab(tabId, { autoCreate });
954
+ try {
955
+ await this.attach(id);
956
+ return id;
957
+ } catch (error) {
958
+ const msg = error instanceof Error ? error.message : String(error);
959
+ if (autoCreate && !hasExplicit && /Browser tab is unavailable to this session/i.test(msg)) {
960
+ const fresh = await this.#resolveTab(undefined, { autoCreate: true });
961
+ await this.attach(fresh);
962
+ return fresh;
963
+ }
964
+ throw error;
965
+ }
966
+ }
967
+
968
+ /** @param {number} tabId @param {{network?:boolean}} [options] */
969
+ async #enableInspectionDomains(tabId, { network = false } = {}) {
970
+ const tasks = [
971
+ this.#ensureDomain(tabId, "Page", "Page.enable", {}),
972
+ this.#ensureDomain(tabId, "Lifecycle", "Page.setLifecycleEventsEnabled", { enabled: true }, true),
973
+ this.#ensureDomain(tabId, "Runtime", "Runtime.enable", {}, true),
974
+ ];
975
+ if (network) {
976
+ tasks.push(this.#ensureDomain(tabId, "Network", "Network.enable", {
977
+ maxTotalBufferSize: 0,
978
+ maxResourceBufferSize: 0,
979
+ }, true));
980
+ }
981
+ await Promise.all(tasks);
982
+ }
983
+
984
+ /**
985
+ * Name the current automation session and visually group owned tabs in a Chrome tab group.
986
+ * @param {string} name
987
+ * @param {{color?:string}} [options]
988
+ */
989
+ async nameSession(name, { color = "blue" } = {}) {
990
+ this.#assertOpen();
991
+ const raw = typeof name === "string" ? name.trim() : "";
992
+ if (!raw) throw new Error("Session name must be a non-empty string");
993
+ const title = raw.slice(0, 80);
994
+ if (!TAB_GROUP_COLORS.has(color)) {
995
+ throw new Error(`Unsupported tab group color: ${String(color)}`);
996
+ }
997
+ const res = await this.#rpc("nameSession", { name: title, color });
998
+ this.sessionName = { name: title, color };
999
+ return {
1000
+ ok: true,
1001
+ name: title,
1002
+ color,
1003
+ groupId: res?.groupId ?? null,
1004
+ groupedTabs: res?.groupedTabs ?? this.tabs.size,
1005
+ supported: res?.supported !== false,
1006
+ };
1007
+ }
1008
+
1009
+ /** @param {string} [url] @returns {Promise<{tab_id:string,title:string,url:string,active:boolean}>} */
1010
+ async newTab(url) {
1011
+ this.#assertOpen();
1012
+ const tab = await this.#rpc("createTab");
1013
+ if (!Number.isSafeInteger(tab?.id)) throw new Error("Browser bridge returned a tab without an ID");
1014
+ this.ownedTabs.add(tab.id);
1015
+ this.tabs.set(tab.id, tab);
1016
+ this.activeTabId = tab.id;
1017
+ await this.attach(tab.id);
1018
+ if (url && normalizeUrl(url) !== "about:blank") await this.goto(url, tab.id);
1019
+ const current = (await this.#rpc("getTabs"))?.find((entry) => entry?.id === tab.id) ?? tab;
1020
+ this.ownedTabs.add(tab.id);
1021
+ this.tabs.set(tab.id, current);
1022
+ return { tab_id: String(tab.id), title: current.title || "Untitled", url: current.url || "", active: true };
1023
+ }
1024
+
1025
+ /** @param {unknown} tabId */
1026
+ async selectTab(tabId) {
1027
+ const id = Number(tabId);
1028
+ if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
1029
+ const resolved = await this.#resolveTab(id);
1030
+ this.activeTabId = resolved;
1031
+ await this.attach(resolved);
1032
+ return { tab_id: String(resolved), ok: true };
1033
+ }
1034
+
1035
+ /** @param {unknown} tabId @returns {Promise<{tab_id:string,closed:boolean}>} */
1036
+ async closeTab(tabId) {
1037
+ const id = await this.#resolveTab(tabId);
1038
+ await this.attach(id);
1039
+ await this.#cdp(id, "Page.close");
1040
+ this.tabs.delete(id);
1041
+ this.ownedTabs.delete(id);
1042
+ this.attached.delete(id);
1043
+ this.axCache.delete(id);
1044
+ this.lastAxSnapshots.delete(id);
1045
+ this.tabStates.delete(id);
1046
+ this.#clearTabCaches(id);
1047
+ this.autoAttached.delete(id);
1048
+ if (this.activeTabId === id) this.activeTabId = this.ownedTabs.values().next().value ?? null;
1049
+ return { tab_id: String(id), closed: true };
1050
+ }
1051
+
1052
+ /** @param {string} url @param {unknown} [tabId] @param {{waitUntil?:string, timeoutMs?:number, trackNetwork?:boolean}} [options] */
1053
+ async goto(url, tabId, { waitUntil = "load", timeoutMs = DEFAULT_LOAD_TIMEOUT_MS, trackNetwork = false } = {}) {
1054
+ const id = await this.#ensureAttachedTab(tabId, { autoCreate: true });
1055
+ const target = normalizeUrl(url);
1056
+ const needNetwork = waitUntil === "networkidle" || trackNetwork || process.env.BROWSER_USE_TRACK_NETWORK === "1";
1057
+ await this.#enableInspectionDomains(id, { network: needNetwork }).catch((err) => {
1058
+ // Page.enable is required, best-effort domains already swallow errors inside #enableInspectionDomains.
1059
+ if (!this.enabledDomains.get(id)?.has("Page")) throw err;
1060
+ });
1061
+ this.lastAxSnapshots.delete(id);
1062
+ this.frameRouteCache.delete(id);
1063
+ const state = this.#tabState(id);
1064
+ state.committed = false;
1065
+ state.ready = false;
1066
+ state.domContentLoaded = false;
1067
+ state.loaded = false;
1068
+ state.loading = true;
1069
+
1070
+ let committed = false;
1071
+ try {
1072
+ await this.#rpc("navigateTab", { tabId: id, url: target });
1073
+ await this.#waitForCommit(id, target, Math.min(5_000, timeoutMs));
1074
+ committed = true;
1075
+ } catch {
1076
+ // Fall back to CDP navigation when the tab-level navigation does not commit.
1077
+ }
1078
+ if (!committed) {
1079
+ await this.#navigateWithCdp(id, target);
1080
+ await this.#waitForCommit(id, target, timeoutMs);
1081
+ }
1082
+ if (waitUntil !== "commit") {
1083
+ await this.#waitForLoad(id, { waitUntil, timeoutMs });
1084
+ }
1085
+ state.url = target;
1086
+ state.committed = true;
1087
+ if (waitUntil !== "commit") {
1088
+ state.ready = true;
1089
+ state.loading = false;
1090
+ }
1091
+ return { tab_id: String(id), ok: true, url: target };
1092
+ }
1093
+
1094
+ /** @param {unknown} [tabId] @returns {Promise<string>} */
1095
+ async url(tabId) {
1096
+ const id = await this.#resolveTab(tabId);
1097
+ await this.attach(id);
1098
+ const current = await this.#evaluateRaw(id, "location.href").catch(() => null);
1099
+ if (typeof current === "string" && current) return current;
1100
+ return this.tabStates.get(id)?.url || this.tabs.get(id)?.url || "";
1101
+ }
1102
+
1103
+ /** @param {unknown} [tabId] @returns {Promise<string>} */
1104
+ async title(tabId) {
1105
+ const id = await this.#resolveTab(tabId);
1106
+ await this.attach(id);
1107
+ const current = await this.#evaluateRaw(id, "document.title").catch(() => null);
1108
+ if (typeof current === "string") return current;
1109
+ return this.tabs.get(id)?.title || "";
1110
+ }
1111
+
1112
+ /** @param {unknown} tabId @param {"back"|"forward"} direction */
1113
+ async history(direction, tabId) {
1114
+ const id = await this.#resolveTab(tabId);
1115
+ await this.attach(id);
1116
+ this.lastAxSnapshots.delete(id);
1117
+ this.frameRouteCache.delete(id);
1118
+ const state = this.#tabState(id);
1119
+ state.committed = false;
1120
+ state.ready = false;
1121
+ state.domContentLoaded = false;
1122
+ state.loaded = false;
1123
+ state.loading = true;
1124
+ const history = await this.#cdp(id, "Page.getNavigationHistory");
1125
+ const entries = Array.isArray(history?.entries) ? history.entries : [];
1126
+ const delta = direction === "back" ? -1 : 1;
1127
+ const entry = entries[(history?.currentIndex ?? 0) + delta];
1128
+ if (!entry || !Number.isSafeInteger(entry.id)) throw new Error(`No browser history entry to go ${direction}`);
1129
+ await this.#cdp(id, "Page.navigateToHistoryEntry", { entryId: entry.id });
1130
+ await this.#waitForLoad(id);
1131
+ return { tab_id: String(id), ok: true, direction };
1132
+ }
1133
+
1134
+ /** @param {unknown} tabId */
1135
+ async reload(tabId) {
1136
+ const id = await this.#resolveTab(tabId);
1137
+ await this.attach(id);
1138
+ this.lastAxSnapshots.delete(id);
1139
+ this.frameRouteCache.delete(id);
1140
+ const state = this.#tabState(id);
1141
+ state.committed = false;
1142
+ state.ready = false;
1143
+ state.domContentLoaded = false;
1144
+ state.loaded = false;
1145
+ state.loading = true;
1146
+ await this.#cdp(id, "Page.reload");
1147
+ await this.#waitForLoad(id);
1148
+ return { tab_id: String(id), ok: true, reloaded: true };
1149
+ }
1150
+
1151
+ /**
1152
+ * Capture a screenshot (defaults to fast 1x CSS-scaled JPEG for optimal token/speed balance).
1153
+ * Supports both screenshot(tabId, opts) and screenshot(opts).
1154
+ * @param {unknown} [tabIdOrOptions]
1155
+ * @param {{fullPage?:boolean, format?:"jpeg"|"png", quality?:number, clip?:{x:number,y:number,width:number,height:number}, scale?:"css"|"device"}} [maybeOptions]
1156
+ */
1157
+ async screenshot(tabIdOrOptions, maybeOptions) {
1158
+ let tabId = tabIdOrOptions;
1159
+ let options = maybeOptions;
1160
+ if (tabIdOrOptions && typeof tabIdOrOptions === "object" && !Array.isArray(tabIdOrOptions)) {
1161
+ options = tabIdOrOptions;
1162
+ tabId = options.tabId ?? options.tab_id;
1163
+ }
1164
+ const {
1165
+ fullPage = false,
1166
+ format = "jpeg",
1167
+ quality = 75,
1168
+ maxWidth = 1280,
1169
+ clip,
1170
+ scale = "css",
1171
+ } = options ?? {};
1172
+
1173
+ const id = await this.#resolveTab(tabId);
1174
+ await this.attach(id);
1175
+ const state = this.tabStates.get(id);
1176
+ if (state?.dialog) {
1177
+ throw new Error(`Screenshot unavailable while a JavaScript ${state.dialog.type} dialog is open.`);
1178
+ }
1179
+
1180
+ const fmt = format === "png" ? "png" : "jpeg";
1181
+ /** @type {Record<string, unknown>} */
1182
+ const params = { format: fmt, fromSurface: true };
1183
+ if (fmt === "jpeg") {
1184
+ params.quality = Math.max(10, Math.min(100, Number(quality) || 75));
1185
+ params.optimizeForSpeed = true;
1186
+ }
1187
+
1188
+ let cssScale = 1;
1189
+ let metrics = null;
1190
+ if (scale === "css" && !clip) {
1191
+ const [dpr, layout] = await Promise.all([
1192
+ this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1),
1193
+ this.#cdp(id, "Page.getLayoutMetrics").catch(() => null),
1194
+ ]);
1195
+ if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 1) cssScale = 1 / dpr;
1196
+ metrics = layout;
1197
+ } else if (scale === "css") {
1198
+ const dpr = await this.#evaluateRaw(id, "window.devicePixelRatio").catch(() => 1);
1199
+ if (typeof dpr === "number" && Number.isFinite(dpr) && dpr > 1) cssScale = 1 / dpr;
1200
+ }
1201
+
1202
+ if (clip && Number.isFinite(clip.width) && Number.isFinite(clip.height)) {
1203
+ params.captureBeyondViewport = true;
1204
+ params.clip = { x: clip.x ?? 0, y: clip.y ?? 0, width: clip.width, height: clip.height, scale: cssScale };
1205
+ } else if (fullPage) {
1206
+ params.captureBeyondViewport = true;
1207
+ if (cssScale < 1) {
1208
+ const content = metrics?.cssContentSize;
1209
+ if (content?.width > 0 && content?.height > 0) {
1210
+ params.clip = { x: 0, y: 0, width: content.width, height: content.height, scale: cssScale };
1211
+ }
1212
+ }
1213
+ } else {
1214
+ const vp = metrics?.cssVisualViewport ?? metrics?.cssLayoutViewport;
1215
+ const capWidth = Number.isFinite(Number(maxWidth)) && Number(maxWidth) >= 320 ? Number(maxWidth) : 1280;
1216
+ const widthRatio = vp?.clientWidth > capWidth ? capWidth / vp.clientWidth : 1;
1217
+ const effectiveScale = cssScale * widthRatio;
1218
+ if (effectiveScale < 1 && vp?.clientWidth > 0 && vp?.clientHeight > 0) {
1219
+ params.clip = {
1220
+ x: vp.pageX ?? 0,
1221
+ y: vp.pageY ?? 0,
1222
+ width: vp.clientWidth,
1223
+ height: vp.clientHeight,
1224
+ scale: effectiveScale,
1225
+ };
1226
+ }
1227
+ }
1228
+
1229
+ const capture = await this.#cdp(id, "Page.captureScreenshot", params);
1230
+ if (!capture || typeof capture.data !== "string") throw new Error("Browser screenshot returned no image data");
1231
+ return {
1232
+ tab_id: String(id),
1233
+ mimeType: fmt === "png" ? "image/png" : "image/jpeg",
1234
+ data: capture.data,
1235
+ };
1236
+ }
1237
+
1238
+ /**
1239
+ * Capture accessibility state (with structural diffing and iframe merging) plus optional screenshot.
1240
+ * Supports both getState(options) and getState(tabId, options).
1241
+ * @param {unknown} [tabIdOrOptions]
1242
+ * @param {{screenshot?:boolean, fullPage?:boolean, format?:"jpeg"|"png", quality?:number, maxLines?:number, diff?:boolean, full?:boolean}} [maybeOptions]
1243
+ */
1244
+ async getState(tabIdOrOptions, maybeOptions) {
1245
+ let tabId = tabIdOrOptions;
1246
+ let options = maybeOptions;
1247
+ if (tabIdOrOptions && typeof tabIdOrOptions === "object" && !Array.isArray(tabIdOrOptions)) {
1248
+ options = tabIdOrOptions;
1249
+ tabId = options.tabId ?? options.tab_id;
1250
+ }
1251
+ const {
1252
+ screenshot = true,
1253
+ fullPage = false,
1254
+ format = "jpeg",
1255
+ quality = 75,
1256
+ maxLines = 2_000,
1257
+ diff = false,
1258
+ full = false,
1259
+ mode = "full",
1260
+ allowUnindexedBaseline = false,
1261
+ } = options ?? {};
1262
+
1263
+ const id = await this.#ensureAttachedTab(tabId, { autoCreate: true });
1264
+
1265
+ const tabState = this.#tabState(id);
1266
+ if (tabState.dialog) {
1267
+ const meta = this.tabs.get(id) ?? {};
1268
+ const dialogState = buildDialogAxState(tabState.dialog, {
1269
+ tab_id: String(id),
1270
+ title: meta.title || "",
1271
+ url: meta.url || tabState.url || "",
1272
+ });
1273
+ this.axCache.set(id, dialogState.index);
1274
+ return { ...dialogState, notifications: this.drainNotifications(id) };
1275
+ }
1276
+
1277
+ await Promise.all([
1278
+ this.#enableInspectionDomains(id).catch(() => {}),
1279
+ this.#ensureDomain(id, "Accessibility", "Accessibility.enable"),
1280
+ ]);
1281
+
1282
+ // Capture main frame AX tree, frame tree, location, and optional screenshot in parallel.
1283
+ const [mainTree, frameTreeResp, location, cap] = await Promise.all([
1284
+ this.#cdp(id, "Accessibility.getFullAXTree"),
1285
+ this.#cdp(id, "Page.getFrameTree").catch(() => null),
1286
+ this.#evaluateRaw(id, "({title: document.title, url: location.href})").catch(() => ({
1287
+ title: this.tabs.get(id)?.title ?? "",
1288
+ url: this.tabs.get(id)?.url ?? "",
1289
+ })),
1290
+ screenshot ? this.screenshot(id, { fullPage, format, quality }).catch(() => null) : null,
1291
+ ]);
1292
+
1293
+ const frameTrees = [{
1294
+ nodes: mainTree?.nodes ?? [],
1295
+ frameId: null,
1296
+ sessionId: null,
1297
+ depth: 0,
1298
+ }];
1299
+ if (frameTreeResp?.frameTree) {
1300
+ await this.#collectChildFrames(id, frameTreeResp.frameTree, frameTrees);
1301
+ }
1302
+
1303
+ const merged = mergeFrameAxStates(frameTrees, { maxLines, mode });
1304
+ this.axCache.set(id, merged.index);
1305
+
1306
+ const title = String(location?.title || "");
1307
+ const url = String(location?.url || "");
1308
+ const documentKey = `${tabState.loaderId ?? ""}:${url}`;
1309
+
1310
+ const useDiff = diff && !full;
1311
+ const prev = this.lastAxSnapshots.get(id);
1312
+ let diffResult = useDiff
1313
+ ? buildAxDiff(prev, { documentKey, lines: merged.lines, entries: merged.entries })
1314
+ : { mode: "full", lines: merged.lines };
1315
+ if (useDiff && prev?.hasIndexedBaseline === false && diffResult.mode === "unchanged") {
1316
+ diffResult = allowUnindexedBaseline
1317
+ ? { ...diffResult, lines: ["No accessibility changes since last ariaSnapshot()."] }
1318
+ : { mode: "full", lines: merged.lines };
1319
+ }
1320
+
1321
+ this.lastAxSnapshots.set(id, { documentKey, entries: merged.entries, hasIndexedBaseline: true });
1322
+
1323
+ const image = cap?.data ?? null;
1324
+ const screenshotMimeType = cap?.mimeType ?? null;
1325
+
1326
+ const lines = [
1327
+ `Title: ${title}`,
1328
+ `URL: ${url}`,
1329
+ "<ax_state>",
1330
+ ...diffResult.lines,
1331
+ ...(merged.truncated && diffResult.mode === "full" ? ["...(truncated)"] : []),
1332
+ "</ax_state>",
1333
+ ];
1334
+
1335
+ return {
1336
+ tab_id: String(id),
1337
+ title,
1338
+ url,
1339
+ mode: diffResult.mode,
1340
+ axText: lines.join("\n"),
1341
+ elementCount: merged.count,
1342
+ screenshotBase64: image,
1343
+ screenshotMimeType,
1344
+ notifications: this.drainNotifications(id),
1345
+ };
1346
+ }
1347
+
1348
+ /** @param {number} tabId @param {Record<string, any>} frameTree @param {Array<any>} out */
1349
+ async #collectChildFrames(tabId, frameTree, out) {
1350
+ const attachedFrames = this.frameSessions.get(tabId);
1351
+ const queue = [];
1352
+ for (const child of frameTree.childFrames ?? []) queue.push({ node: child, depth: 1 });
1353
+ const candidates = [];
1354
+ while (queue.length > 0 && candidates.length < 8) {
1355
+ const { node, depth } = queue.shift();
1356
+ const frame = node?.frame;
1357
+ if (!frame?.id) continue;
1358
+ const childSessionId = attachedFrames?.get(frame.id) ?? null;
1359
+ if (childSessionId || (frame.url && frame.url !== "about:blank")) {
1360
+ candidates.push({ frameId: frame.id, url: frame.url, childSessionId, depth });
1361
+ }
1362
+ for (const grandChild of node.childFrames ?? []) queue.push({ node: grandChild, depth: depth + 1 });
1363
+ }
1364
+ const fetched = await Promise.all(candidates.map(async (item) => {
1365
+ try {
1366
+ if (item.childSessionId) {
1367
+ if (!this.enabledChildAxSessions.has(item.childSessionId)) {
1368
+ await this.#cdpIn(tabId, item.childSessionId, "Accessibility.enable", {}).then(
1369
+ () => { this.enabledChildAxSessions.add(item.childSessionId); },
1370
+ () => {},
1371
+ );
1372
+ }
1373
+ const tree = await this.#cdpIn(tabId, item.childSessionId, "Accessibility.getFullAXTree", { frameId: item.frameId });
1374
+ return { item, nodes: tree?.nodes };
1375
+ }
1376
+ const tree = await this.#cdp(tabId, "Accessibility.getFullAXTree", { frameId: item.frameId });
1377
+ return { item, nodes: tree?.nodes };
1378
+ } catch {
1379
+ return null;
1380
+ }
1381
+ }));
1382
+ for (const entry of fetched) {
1383
+ if (entry && Array.isArray(entry.nodes) && entry.nodes.length > 0) {
1384
+ out.push({
1385
+ nodes: entry.nodes,
1386
+ frameId: entry.item.frameId,
1387
+ sessionId: entry.item.childSessionId,
1388
+ url: entry.item.url,
1389
+ depth: entry.item.depth,
1390
+ });
1391
+ }
1392
+ }
1393
+ }
1394
+
1395
+ /**
1396
+ * Click by element_index (or comma-separated indices) or viewport coordinates { x, y }.
1397
+ * @param {unknown} elementIndex
1398
+ * @param {{tabId?:unknown, clickCount?:number, button?:string, modifiers?:string|string[], x?:number, y?:number, settle?:boolean}} [options]
1399
+ */
1400
+ async click(elementIndex, { tabId, clickCount = 1, button = "left", modifiers, x, y, settle = false } = {}) {
1401
+ const id = await this.#resolveTab(tabId);
1402
+ await this.attach(id);
1403
+ const modMask = parseModifiers(modifiers);
1404
+
1405
+ if ((elementIndex === undefined || elementIndex === null || elementIndex === "") &&
1406
+ Number.isFinite(x) && Number.isFinite(y)) {
1407
+ await this.#clickPoint(id, Number(x), Number(y), { clickCount, button, modifiers: modMask });
1408
+ if (settle) await this.#waitForSettle(id, { expectNavigation: true });
1409
+ return { tab_id: String(id), ok: true, action: "click", x: Number(x), y: Number(y) };
1410
+ }
1411
+
1412
+ const indices = splitIndices(elementIndex);
1413
+ if (indices.length === 0) throw new Error("An element index or (x, y) coordinates are required; call browser_get_state first");
1414
+ for (const index of indices) {
1415
+ const node = this.#axNode(id, index);
1416
+ if (node.dialogControl) {
1417
+ await this.handleDialog({ tabId: id, accept: node.dialogControl === "accept" });
1418
+ continue;
1419
+ }
1420
+ await this.#clickNode(id, node, { clickCount, button, modifiers: modMask });
1421
+ }
1422
+ if (settle) await this.#waitForSettle(id, { expectNavigation: true });
1423
+ return { tab_id: String(id), ok: true, action: "click", indices };
1424
+ }
1425
+
1426
+ /** @param {unknown} elementIndex @param {string} value @param {{tabId?:unknown, settle?:boolean}} [options] */
1427
+ async setValue(elementIndex, value, { tabId, settle = false } = {}) {
1428
+ const id = await this.#resolveTab(tabId);
1429
+ await this.attach(id);
1430
+ const node = this.#axNode(id, elementIndex);
1431
+ if (node.dialogControl === "prompt") {
1432
+ await this.handleDialog({ tabId: id, accept: true, promptText: String(value) });
1433
+ return { tab_id: String(id), ok: true, action: "set_value", index: String(elementIndex) };
1434
+ }
1435
+ const sessionId = node.sessionId ?? null;
1436
+ const { object } = await this.#cdpTarget(id, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
1437
+ if (!object?.objectId) throw new Error("Browser element could not be resolved");
1438
+ const response = await this.#cdpTarget(id, sessionId, "Runtime.callFunctionOn", {
1439
+ objectId: object.objectId,
1440
+ functionDeclaration: smartSetValueFunctionDeclaration(),
1441
+ arguments: [{ value: String(value) }],
1442
+ returnByValue: true,
1443
+ });
1444
+ if (response?.exceptionDetails) {
1445
+ throw new Error(response.exceptionDetails.exception?.description || response.exceptionDetails.text || "Failed to set element value");
1446
+ }
1447
+ const val = response?.result?.value;
1448
+ const status = val && typeof val === "object" ? val.status : val;
1449
+ if (status === "needs-click") {
1450
+ await this.#clickNode(id, node, { clickCount: 1, button: "left", modifiers: 0 });
1451
+ }
1452
+ if (settle) await this.#waitForSettle(id);
1453
+ return { tab_id: String(id), ok: true, action: "set_value", index: String(elementIndex) };
1454
+ }
1455
+
1456
+ /** @param {string} text @param {{tabId?:unknown, elementIndex?:unknown, settle?:boolean}} [options] */
1457
+ async typeText(text, { tabId, elementIndex, settle = false } = {}) {
1458
+ const id = await this.#resolveTab(tabId);
1459
+ await this.attach(id);
1460
+ if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
1461
+ await this.click(elementIndex, { tabId: id });
1462
+ }
1463
+ await this.#cdp(id, "Input.insertText", { text: String(text) });
1464
+ if (settle) await this.#waitForSettle(id);
1465
+ return { tab_id: String(id), ok: true, action: "type_text" };
1466
+ }
1467
+
1468
+ /** @param {string} combo @param {{tabId?:unknown, elementIndex?:unknown, settle?:boolean}} [options] */
1469
+ async pressKey(combo, { tabId, elementIndex, settle = false } = {}) {
1470
+ const id = await this.#resolveTab(tabId);
1471
+ await this.attach(id);
1472
+ if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
1473
+ const node = this.#axNode(id, elementIndex);
1474
+ await this.#scrollIntoView(id, node, node.sessionId).catch(() => {});
1475
+ await this.#cdpTarget(id, node.sessionId, "DOM.focus", { backendNodeId: node.backendDOMNodeId });
1476
+ }
1477
+ const key = await this.#sendKeyCombo(id, combo, null);
1478
+ if (settle) await this.#waitForSettle(id, { expectNavigation: key.key === "Enter" });
1479
+ return { tab_id: String(id), ok: true, action: "press_key", key: combo };
1480
+ }
1481
+
1482
+ /** @param {number} tabId @param {string} combo @param {string|null} [sessionId] */
1483
+ async #sendKeyCombo(tabId, combo, sessionId = null) {
1484
+ const key = parseKeyCombo(combo);
1485
+ const base = {
1486
+ key: key.key,
1487
+ code: key.code,
1488
+ windowsVirtualKeyCode: key.windowsVirtualKeyCode,
1489
+ nativeVirtualKeyCode: key.windowsVirtualKeyCode,
1490
+ modifiers: key.modifiers,
1491
+ location: 0,
1492
+ };
1493
+ if (key.key === "Enter" && key.modifiers === 0) {
1494
+ await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1495
+ type: "rawKeyDown",
1496
+ ...base,
1497
+ commands: ["insertNewline"],
1498
+ });
1499
+ await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1500
+ type: "char",
1501
+ ...base,
1502
+ text: key.text,
1503
+ unmodifiedText: key.text,
1504
+ });
1505
+ } else {
1506
+ await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", {
1507
+ type: key.text ? "keyDown" : "rawKeyDown",
1508
+ ...base,
1509
+ ...(key.text ? { text: key.text, unmodifiedText: key.text } : {}),
1510
+ });
1511
+ }
1512
+ await this.#cdpTarget(tabId, sessionId, "Input.dispatchKeyEvent", { type: "keyUp", ...base });
1513
+ return key;
1514
+ }
1515
+
1516
+ /** @param {"up"|"down"|"left"|"right"} direction @param {{tabId?:unknown, elementIndex?:unknown, pages?:number, x?:number, y?:number}} [options] */
1517
+ async scroll(direction, { tabId, elementIndex, pages = 1, x, y } = {}) {
1518
+ const id = await this.#resolveTab(tabId);
1519
+ await this.attach(id);
1520
+ const delta = 500 * Math.max(1, Number(pages) || 1);
1521
+ const deltas = {
1522
+ up: { deltaX: 0, deltaY: -delta },
1523
+ down: { deltaX: 0, deltaY: delta },
1524
+ left: { deltaX: -delta, deltaY: 0 },
1525
+ right: { deltaX: delta, deltaY: 0 },
1526
+ }[direction];
1527
+ if (!deltas) throw new Error(`Unsupported scroll direction: ${direction}`);
1528
+ let point = { x: 0, y: 0 };
1529
+ if (Number.isFinite(x) && Number.isFinite(y)) {
1530
+ point = { x: Number(x), y: Number(y) };
1531
+ } else if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
1532
+ const node = this.#axNode(id, elementIndex);
1533
+ const box = await this.#boxModel(id, node, node.sessionId);
1534
+ point = { x: box.x, y: box.y };
1535
+ } else {
1536
+ const metrics = await this.#cdp(id, "Page.getLayoutMetrics");
1537
+ const viewport = metrics?.cssLayoutViewport ?? metrics?.layoutViewport ?? { clientWidth: 1280, clientHeight: 800 };
1538
+ point = { x: Math.floor(viewport.clientWidth / 2), y: Math.floor(viewport.clientHeight / 2) };
1539
+ }
1540
+ await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseWheel", x: point.x, y: point.y, ...deltas });
1541
+ return { tab_id: String(id), ok: true, action: "scroll", direction, pages };
1542
+ }
1543
+
1544
+ /**
1545
+ * Hover over an element_index, locator selector, or viewport coordinates (x, y).
1546
+ * @param {{tabId?:unknown, elementIndex?:unknown, selector?:string, frame?:string, force?:boolean, timeoutMs?:number, x?:number, y?:number}} [options]
1547
+ */
1548
+ async hover({ tabId, elementIndex, selector, frame, force = false, timeoutMs, x, y } = {}) {
1549
+ const id = await this.#resolveTab(tabId);
1550
+ await this.attach(id);
1551
+ let point;
1552
+ if (Number.isFinite(x) && Number.isFinite(y)) {
1553
+ point = { x: Number(x), y: Number(y) };
1554
+ } else if (selector) {
1555
+ const { inCrossOriginFrame, result: match } = await this.#runLocatorWithAutoWait(id, selector, {
1556
+ frame,
1557
+ mutation: "hover",
1558
+ force,
1559
+ timeoutMs,
1560
+ });
1561
+ if (inCrossOriginFrame) {
1562
+ return { tab_id: String(id), ok: true, action: "hover", selector, frame, ...match };
1563
+ }
1564
+ point = { x: match.x, y: match.y };
1565
+ } else if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
1566
+ const node = this.#axNode(id, elementIndex);
1567
+ point = await this.#boxModel(id, node, node.sessionId);
1568
+ } else {
1569
+ throw new Error("hover requires element_index, selector, or (x, y) coordinates");
1570
+ }
1571
+ await this.#cdp(id, "Input.dispatchMouseEvent", {
1572
+ type: "mouseMoved",
1573
+ x: point.x,
1574
+ y: point.y,
1575
+ button: "none",
1576
+ buttons: 0,
1577
+ clickCount: 0,
1578
+ modifiers: 0,
1579
+ });
1580
+ return { tab_id: String(id), ok: true, action: "hover", x: point.x, y: point.y };
1581
+ }
1582
+
1583
+ /**
1584
+ * Drag from source (index or coordinates) to destination (index or coordinates).
1585
+ * @param {{tabId?:unknown, fromIndex?:unknown, toIndex?:unknown, fromX?:number, fromY?:number, toX?:number, toY?:number, steps?:number}} options
1586
+ */
1587
+ async drag({ tabId, fromIndex, toIndex, fromX, fromY, toX, toY, steps = 8 }) {
1588
+ const id = await this.#resolveTab(tabId);
1589
+ await this.attach(id);
1590
+ const start = (fromIndex !== undefined && fromIndex !== null && fromIndex !== "")
1591
+ ? await this.#boxModel(id, this.#axNode(id, fromIndex))
1592
+ : { x: Number(fromX), y: Number(fromY) };
1593
+ const end = (toIndex !== undefined && toIndex !== null && toIndex !== "")
1594
+ ? await this.#boxModel(id, this.#axNode(id, toIndex))
1595
+ : { x: Number(toX), y: Number(toY) };
1596
+ if (!Number.isFinite(start.x) || !Number.isFinite(start.y) || !Number.isFinite(end.x) || !Number.isFinite(end.y)) {
1597
+ throw new Error("drag requires valid start and end coordinates or element indices");
1598
+ }
1599
+ const count = Math.max(2, Math.min(30, Number(steps) || 8));
1600
+ await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: start.x, y: start.y, button: "none", buttons: 0, clickCount: 0, modifiers: 0 });
1601
+ await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mousePressed", x: start.x, y: start.y, button: "left", buttons: 1, clickCount: 1, modifiers: 0 });
1602
+ for (let i = 1; i <= count; i++) {
1603
+ const ratio = i / count;
1604
+ await this.#cdp(id, "Input.dispatchMouseEvent", {
1605
+ type: "mouseMoved",
1606
+ x: start.x + (end.x - start.x) * ratio,
1607
+ y: start.y + (end.y - start.y) * ratio,
1608
+ button: "left",
1609
+ buttons: 1,
1610
+ clickCount: 0,
1611
+ modifiers: 0,
1612
+ });
1613
+ }
1614
+ await this.#cdp(id, "Input.dispatchMouseEvent", { type: "mouseReleased", x: end.x, y: end.y, button: "left", buttons: 0, clickCount: 1, modifiers: 0 });
1615
+ return { tab_id: String(id), ok: true, action: "drag", from: start, to: end };
1616
+ }
1617
+
1618
+ /**
1619
+ * Select option(s) on a native <select> by element_index or locator.
1620
+ * @param {{tabId?:unknown, elementIndex?:unknown, selector?:string, frame?:string, value?:string|string[], label?:string|string[], index?:number|number[], force?:boolean, timeoutMs?:number}} options
1621
+ */
1622
+ async selectOption({ tabId, elementIndex, selector, frame, value, label, index, force = false, timeoutMs }) {
1623
+ const id = await this.#resolveTab(tabId);
1624
+ await this.attach(id);
1625
+ const specs = [];
1626
+ const toList = (v) => (Array.isArray(v) ? v : [v]);
1627
+ if (value !== undefined) for (const v of toList(value)) specs.push({ value: String(v) });
1628
+ if (label !== undefined) for (const l of toList(label)) specs.push({ label: String(l) });
1629
+ if (index !== undefined) for (const idx of toList(index)) specs.push({ index: Number(idx) });
1630
+ if (specs.length === 0) throw new Error("selectOption requires value, label, or index");
1631
+
1632
+ if (selector) {
1633
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, {
1634
+ frame,
1635
+ mutation: "select",
1636
+ select: specs,
1637
+ force,
1638
+ timeoutMs,
1639
+ });
1640
+ return { tab_id: String(id), ok: true, action: "select_option", selector, ...(frame ? { frame } : {}), selected: result.selected };
1641
+ }
1642
+
1643
+ if (elementIndex === undefined || elementIndex === null || elementIndex === "") {
1644
+ throw new Error("selectOption requires element_index or selector");
1645
+ }
1646
+ const node = this.#axNode(id, elementIndex);
1647
+ const sessionId = node.sessionId ?? null;
1648
+ const { object } = await this.#cdpTarget(id, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
1649
+ if (!object?.objectId) throw new Error("Select element could not be resolved");
1650
+ const response = await this.#cdpTarget(id, sessionId, "Runtime.callFunctionOn", {
1651
+ objectId: object.objectId,
1652
+ functionDeclaration: selectOptionFunctionDeclaration(),
1653
+ arguments: [{ value: specs }],
1654
+ returnByValue: true,
1655
+ });
1656
+ if (response?.exceptionDetails) {
1657
+ throw new Error(response.exceptionDetails.exception?.description || response.exceptionDetails.text || "selectOption failed");
1658
+ }
1659
+ return { tab_id: String(id), ok: true, action: "select_option", selected: response?.result?.value ?? [] };
1660
+ }
1661
+
1662
+ /**
1663
+ * Resolve a locator selector (with auto-wait + frame routing) to its CDP backendDOMNodeId.
1664
+ * @param {number} id
1665
+ * @param {string} selector
1666
+ * @param {{frame?:string, timeoutMs?:number, fallbackCss?:boolean}} [options]
1667
+ * @returns {Promise<{backendNodeId:number|undefined, sessionId:string|null, sameOriginFrames:string[]|null}>}
1668
+ */
1669
+ async #resolveLocatorBackendNode(id, selector, { frame, timeoutMs, fallbackCss = false } = {}) {
1670
+ let backendNodeId;
1671
+ let sessionId = null;
1672
+ let sameOriginFrames = null;
1673
+ if (frame) {
1674
+ const resolved = await this.#resolveFrameRoute(id, frame);
1675
+ if (resolved.kind === "same-origin") sameOriginFrames = resolved.selectors;
1676
+ else sessionId = resolved.sessionId;
1677
+ }
1678
+ const waitBudget = timeoutMs !== undefined ? Math.max(0, Number(timeoutMs) || 0) : DEFAULT_LOCATOR_TIMEOUT_MS;
1679
+ const deadline = Date.now() + waitBudget;
1680
+ const expr = locatorResolveNodeExpression(selector, { sameOriginFrames });
1681
+ while (true) {
1682
+ const response = await this.#cdpTarget(id, sessionId, "Runtime.evaluate", {
1683
+ expression: expr,
1684
+ returnByValue: false,
1685
+ awaitPromise: false,
1686
+ });
1687
+ const objectId = response?.result?.objectId;
1688
+ if (response?.exceptionDetails) {
1689
+ if (objectId) {
1690
+ await this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1691
+ }
1692
+ const msg = response.exceptionDetails.exception?.description || response.exceptionDetails.text || "Locator resolution failed";
1693
+ if (/did not match/i.test(msg) && Date.now() < deadline) {
1694
+ await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
1695
+ continue;
1696
+ }
1697
+ throw new Error(msg);
1698
+ }
1699
+ if (objectId && response?.result?.subtype !== "error") {
1700
+ let shouldRetry = false;
1701
+ try {
1702
+ const described = await this.#cdpTarget(id, sessionId, "DOM.describeNode", { objectId });
1703
+ backendNodeId = described?.node?.backendNodeId;
1704
+ } catch (err) {
1705
+ const msg = err instanceof Error ? err.message : String(err);
1706
+ if (/Object id doesn't reference a Node|Could not find node/i.test(msg) && Date.now() < deadline) {
1707
+ shouldRetry = true;
1708
+ } else {
1709
+ throw err;
1710
+ }
1711
+ } finally {
1712
+ await this.#cdpTarget(id, sessionId, "Runtime.releaseObject", { objectId }).catch(() => {});
1713
+ }
1714
+ if (shouldRetry) {
1715
+ await sleep(Math.min(50, Math.max(1, deadline - Date.now())));
1716
+ continue;
1717
+ }
1718
+ break;
1719
+ }
1720
+ break;
1721
+ }
1722
+
1723
+ // Minimal test mock fallback when Runtime.evaluate does not yield remote objectIds.
1724
+ if (!Number.isSafeInteger(backendNodeId) && fallbackCss) {
1725
+ const css = selector.startsWith("css=") ? selector.slice(4) : selector;
1726
+ const frameDoc = await this.#cdpTarget(id, sessionId, "DOM.getDocument", { depth: 0 });
1727
+ const { nodeId } = await this.#cdpTarget(id, sessionId, "DOM.querySelector", { nodeId: frameDoc.root.nodeId, selector: css });
1728
+ if (nodeId) {
1729
+ const described = await this.#cdpTarget(id, sessionId, "DOM.describeNode", { nodeId });
1730
+ backendNodeId = described?.node?.backendNodeId;
1731
+ }
1732
+ }
1733
+ return { backendNodeId, sessionId, sameOriginFrames };
1734
+ }
1735
+
1736
+ /**
1737
+ * Set files on a file input (<input type="file">) or pending file chooser.
1738
+ * Uses Shadow-DOM/locator node resolution with auto-wait first, falling back to DOM.querySelector on minimal mocks.
1739
+ * @param {string|string[]} files
1740
+ * @param {{tabId?:unknown, elementIndex?:unknown, selector?:string, frame?:string, timeoutMs?:number}} [options]
1741
+ */
1742
+ async uploadFiles(files, { tabId, elementIndex, selector, frame, timeoutMs } = {}) {
1743
+ const id = await this.#resolveTab(tabId);
1744
+ await this.attach(id);
1745
+ const list = (Array.isArray(files) ? files : [files]).map((f) => String(f));
1746
+ if (list.length === 0 || list.some((f) => !path.isAbsolute(f))) {
1747
+ throw new Error("uploadFiles requires at least one non-empty absolute file path");
1748
+ }
1749
+ let backendNodeId;
1750
+ let sessionId = null;
1751
+
1752
+ if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
1753
+ const node = this.#axNode(id, elementIndex);
1754
+ backendNodeId = node.backendDOMNodeId;
1755
+ sessionId = node.sessionId ?? null;
1756
+ } else if (selector) {
1757
+ const resolved = await this.#resolveLocatorBackendNode(id, selector, { frame, timeoutMs, fallbackCss: true });
1758
+ backendNodeId = resolved.backendNodeId;
1759
+ sessionId = resolved.sessionId;
1760
+ if (!Number.isSafeInteger(backendNodeId)) {
1761
+ throw new Error(`File input not matched: ${selector}`);
1762
+ }
1763
+ } else {
1764
+ const pending = this.#tabState(id).fileChooser;
1765
+ if (pending?.backendNodeId) {
1766
+ backendNodeId = pending.backendNodeId;
1767
+ if (pending.frameId) {
1768
+ sessionId = this.frameSessions.get(id)?.get(pending.frameId) ?? null;
1769
+ }
1770
+ this.#tabState(id).fileChooser = null;
1771
+ }
1772
+ }
1773
+
1774
+ if (!Number.isSafeInteger(backendNodeId)) {
1775
+ throw new Error("uploadFiles requires element_index, locator for input[type=file], or an active file chooser");
1776
+ }
1777
+ await this.#cdpTarget(id, sessionId, "DOM.setFileInputFiles", { backendNodeId, files: list });
1778
+ return { tab_id: String(id), ok: true, action: "upload_files", files: list };
1779
+ }
1780
+
1781
+ /**
1782
+ * Perform an action callback expected to trigger a navigation and wait for URL/load completion.
1783
+ * @template T
1784
+ * @param {() => Promise<T>} action
1785
+ * @param {{tabId?:unknown, url?:string|RegExp, waitUntil?:"commit"|"domcontentloaded"|"load"|"networkidle", timeoutMs?:number}} [options]
1786
+ * @returns {Promise<T>}
1787
+ */
1788
+ async expectNavigation(action, { tabId, url, waitUntil = "load", timeoutMs = DEFAULT_LOAD_TIMEOUT_MS } = {}) {
1789
+ if (typeof action !== "function") throw new Error("expectNavigation requires an async action function");
1790
+ const id = await this.#resolveTab(tabId);
1791
+ await this.attach(id);
1792
+ await this.#enableInspectionDomains(id, { network: waitUntil === "networkidle" }).catch(() => {});
1793
+ const state = this.#tabState(id);
1794
+ const startRev = state.navRevision;
1795
+ const startUrl = await this.#evaluateRaw(id, "location.href").catch(() => state.url || "");
1796
+ const actionResult = await action();
1797
+ const deadline = Date.now() + Math.max(100, Number(timeoutMs) || DEFAULT_LOAD_TIMEOUT_MS);
1798
+ let lastUrlPoll = 0;
1799
+ const matchesTargetUrl = (candidate) => typeof candidate === "string" && (url instanceof RegExp
1800
+ ? url.test(candidate)
1801
+ : (sameUrl(candidate, url) || candidate.includes(url)));
1802
+ while (Date.now() < deadline) {
1803
+ if (state.dialog) return actionResult;
1804
+ let urlMatched = false;
1805
+ if (url === undefined) {
1806
+ urlMatched = state.navRevision !== startRev;
1807
+ } else if (state.hasEvents && matchesTargetUrl(state.url)) {
1808
+ urlMatched = true;
1809
+ }
1810
+ if (!urlMatched) {
1811
+ const now = Date.now();
1812
+ if (!state.hasEvents || now - lastUrlPoll >= 300) {
1813
+ lastUrlPoll = now;
1814
+ const currentUrl = await this.#evaluateRaw(id, "location.href").catch(() => null);
1815
+ urlMatched = url === undefined
1816
+ ? (state.navRevision !== startRev || (typeof currentUrl === "string" && currentUrl !== startUrl))
1817
+ : matchesTargetUrl(currentUrl);
1818
+ }
1819
+ }
1820
+ if (urlMatched) {
1821
+ this.frameRouteCache.delete(id);
1822
+ if (waitUntil !== "commit") {
1823
+ await this.#waitForLoad(id, { waitUntil, timeoutMs: Math.max(100, deadline - Date.now()) });
1824
+ }
1825
+ return actionResult;
1826
+ }
1827
+ await this.#waitForTabWakeup(id, Math.min(state.hasEvents ? 200 : 80, Math.max(1, deadline - Date.now())));
1828
+ }
1829
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for navigation`);
1830
+ }
1831
+
1832
+ /**
1833
+ * Wait for a tab event such as "filechooser" or "download".
1834
+ * Call before clicking the triggering control, then await the returned promise.
1835
+ * @param {"filechooser"|"download"} eventName
1836
+ * @param {{tabId?:unknown, timeoutMs?:number}} [options]
1837
+ */
1838
+ async waitForEvent(eventName, { tabId, timeoutMs = 30_000 } = {}) {
1839
+ const id = await this.#resolveTab(tabId);
1840
+ await this.attach(id);
1841
+ const state = this.#tabState(id);
1842
+ const budget = Math.max(100, Number(timeoutMs) || 30_000);
1843
+
1844
+ if (eventName === "filechooser") {
1845
+ await this.#ensureDomain(id, "Page", "Page.enable");
1846
+ state.fileChooser = null;
1847
+ await this.#cdp(id, "Page.setInterceptFileChooserDialog", { enabled: true });
1848
+ const armedAt = Date.now();
1849
+ const deadline = armedAt + budget;
1850
+ try {
1851
+ while (Date.now() < deadline) {
1852
+ if (state.fileChooser && state.fileChooser.openedAtMs >= armedAt &&
1853
+ Number.isSafeInteger(state.fileChooser.backendNodeId)) {
1854
+ const fc = state.fileChooser;
1855
+ state.fileChooser = null;
1856
+ const frameSessionId = fc.frameId ? (this.frameSessions.get(id)?.get(fc.frameId) ?? null) : null;
1857
+ return {
1858
+ isMultiple: () => fc.mode === "selectMultiple",
1859
+ mode: fc.mode || "selectSingle",
1860
+ backendNodeId: fc.backendNodeId,
1861
+ frameId: fc.frameId ?? null,
1862
+ setFiles: async (files) => {
1863
+ const list = (Array.isArray(files) ? files : [files]).map((f) => String(f));
1864
+ if (list.length === 0 || list.some((f) => !path.isAbsolute(f))) {
1865
+ throw new Error("setFiles requires at least one non-empty absolute file path");
1866
+ }
1867
+ await this.#cdpTarget(id, frameSessionId, "DOM.setFileInputFiles", {
1868
+ backendNodeId: fc.backendNodeId,
1869
+ files: list,
1870
+ });
1871
+ return { tab_id: String(id), ok: true, files: list };
1872
+ },
1873
+ };
1874
+ }
1875
+ await this.#waitForTabWakeup(id, Math.min(80, Math.max(1, deadline - Date.now())));
1876
+ }
1877
+ throw new Error(`Timed out after ${budget}ms waiting for filechooser`);
1878
+ } finally {
1879
+ await this.#cdp(id, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
1880
+ }
1881
+ }
1882
+
1883
+ if (eventName === "download") {
1884
+ await this.#ensureDomain(id, "Page", "Page.enable").catch(() => {});
1885
+ const knownIds = new Set(state.downloads.map((d) => d.id));
1886
+ state.downloadWatchCount = (state.downloadWatchCount ?? 0) + 1;
1887
+ if (state.downloadWatchCount === 1) {
1888
+ await this.#rpc("watchDownloads", { tabId: id }).catch((err) => {
1889
+ if (!/Unknown Chrome bridge request|Unsupported/i.test(String(err?.message))) throw err;
1890
+ });
1891
+ }
1892
+ let released = false;
1893
+ const releaseWatch = async () => {
1894
+ if (released) return;
1895
+ released = true;
1896
+ state.downloadWatchCount = Math.max(0, (state.downloadWatchCount ?? 1) - 1);
1897
+ if (state.downloadWatchCount === 0) {
1898
+ await this.#rpc("unwatchDownloads", { tabId: id }).catch(() => {});
1899
+ }
1900
+ };
1901
+
1902
+ const deadline = Date.now() + budget;
1903
+ let matched = null;
1904
+ try {
1905
+ while (Date.now() < deadline) {
1906
+ matched = state.downloads.find((d) => !knownIds.has(d.id));
1907
+ if (matched) break;
1908
+ await this.#waitForTabWakeup(id, Math.min(80, Math.max(1, deadline - Date.now())));
1909
+ }
1910
+ if (!matched) {
1911
+ throw new Error(`Timed out after ${budget}ms waiting for download`);
1912
+ }
1913
+ } catch (err) {
1914
+ await releaseWatch();
1915
+ throw err;
1916
+ }
1917
+
1918
+ if (matched.state === "complete" || matched.state === "interrupted") {
1919
+ await releaseWatch();
1920
+ }
1921
+
1922
+ return {
1923
+ id: matched.id,
1924
+ get url() { return matched.url; },
1925
+ get suggestedFilename() { return matched.suggestedFilename || (matched.filename ? path.basename(matched.filename) : ""); },
1926
+ get state() { return matched.state; },
1927
+ path: async ({ timeoutMs: pathTimeoutMs = 120_000 } = {}) => {
1928
+ const pathDeadline = Date.now() + Math.max(100, Number(pathTimeoutMs) || 120_000);
1929
+ try {
1930
+ while (Date.now() < pathDeadline) {
1931
+ if (matched.state === "complete") {
1932
+ return matched.filename || matched.suggestedFilename || null;
1933
+ }
1934
+ if (matched.state === "interrupted") {
1935
+ throw new Error(`Download interrupted: ${matched.error || matched.suggestedFilename || matched.id}`);
1936
+ }
1937
+ await this.#waitForTabWakeup(id, Math.min(80, Math.max(1, pathDeadline - Date.now())));
1938
+ }
1939
+ throw new Error(`Timed out after ${pathTimeoutMs}ms waiting for download completion`);
1940
+ } finally {
1941
+ await releaseWatch();
1942
+ }
1943
+ },
1944
+ };
1945
+ }
1946
+
1947
+ if (eventName === "popup") {
1948
+ const armedAt = Date.now();
1949
+ const seen = new Set(state.popups.map((p) => p.tab_id));
1950
+ const deadline = armedAt + budget;
1951
+ while (Date.now() < deadline) {
1952
+ const matched = state.popups.find((p) => !seen.has(p.tab_id));
1953
+ if (matched) {
1954
+ return {
1955
+ tab_id: matched.tab_id,
1956
+ opener_tab_id: matched.opener_tab_id,
1957
+ url: matched.url,
1958
+ title: matched.title,
1959
+ };
1960
+ }
1961
+ await this.#waitForTabWakeup(id, Math.min(80, Math.max(1, deadline - Date.now())));
1962
+ }
1963
+ throw new Error(`Timed out after ${budget}ms waiting for popup`);
1964
+ }
1965
+
1966
+ throw new Error(`Unsupported waitForEvent target: ${String(eventName)}`);
1967
+ }
1968
+
1969
+ /**
1970
+ * Wait for a selector state, visible text, URL substring/exact match, load state, or timeout.
1971
+ * @param {{tabId?:unknown, selector?:string, text?:string, url?:string|RegExp, loadState?:"domcontentloaded"|"load"|"networkidle", state?:"attached"|"detached"|"visible"|"hidden", frame?:string, timeoutMs?:number}} [options]
1972
+ */
1973
+ async waitFor({ tabId, selector, text, url, loadState, state = "visible", frame, timeoutMs = 10_000 } = {}) {
1974
+ const id = await this.#resolveTab(tabId);
1975
+ await this.attach(id);
1976
+ const deadline = Date.now() + Math.max(100, Number(timeoutMs) || 10_000);
1977
+
1978
+ if (loadState) {
1979
+ if (loadState === "networkidle") {
1980
+ await this.#enableInspectionDomains(id, { network: true }).catch(() => {});
1981
+ }
1982
+ await this.#waitForLoad(id, { waitUntil: loadState, timeoutMs });
1983
+ return { tab_id: String(id), ok: true, matched: "loadState", loadState };
1984
+ }
1985
+
1986
+ if (url !== undefined) {
1987
+ const tabState = this.#tabState(id);
1988
+ let lastEvalAt = 0;
1989
+ const matchesUrl = (candidate) => typeof candidate === "string" && (url instanceof RegExp
1990
+ ? url.test(candidate)
1991
+ : (sameUrl(candidate, url) || candidate.includes(url)));
1992
+ while (Date.now() < deadline) {
1993
+ if (tabState.hasEvents && matchesUrl(tabState.url)) {
1994
+ return { tab_id: String(id), ok: true, matched: "url", url: tabState.url };
1995
+ }
1996
+ const now = Date.now();
1997
+ if (!tabState.hasEvents || now - lastEvalAt >= 350) {
1998
+ lastEvalAt = now;
1999
+ const current = await this.#evaluateRaw(id, "location.href").catch(() => null);
2000
+ if (matchesUrl(current)) {
2001
+ return { tab_id: String(id), ok: true, matched: "url", url: current };
2002
+ }
2003
+ }
2004
+ await this.#waitForTabWakeup(id, Math.min(tabState.hasEvents ? 200 : 80, Math.max(1, deadline - Date.now())));
2005
+ }
2006
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for URL ${String(url)}`);
2007
+ }
2008
+
2009
+ if (text !== undefined && !selector) {
2010
+ while (Date.now() < deadline) {
2011
+ const rem = Math.max(1, deadline - Date.now());
2012
+ const attemptStart = Date.now();
2013
+ const res = await this.#evaluateRaw(
2014
+ id,
2015
+ waitForTextExpression(text, { timeoutMs: Math.min(1_000, rem) }),
2016
+ { awaitPromise: true },
2017
+ ).catch(() => null);
2018
+ if (res?.matched === true || (typeof res === "string" && res.includes(text))) {
2019
+ return { tab_id: String(id), ok: true, matched: "text", text };
2020
+ }
2021
+ const left = deadline - Date.now();
2022
+ if (left <= 0) break;
2023
+ if (Date.now() - attemptStart < 20) await sleep(Math.min(50, left));
2024
+ }
2025
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for text ${JSON.stringify(text)}`);
2026
+ }
2027
+
2028
+ if (selector) {
2029
+ while (Date.now() < deadline) {
2030
+ const rem = Math.max(1, deadline - Date.now());
2031
+ const attemptStart = Date.now();
2032
+ const check = await this.#runLocator(id, selector, {
2033
+ frame,
2034
+ mutation: "wait",
2035
+ state,
2036
+ inPageWaitMs: Math.min(1_000, rem),
2037
+ }).then((r) => r.result).catch(() => null);
2038
+ if (check?.satisfied) {
2039
+ return { tab_id: String(id), ok: true, matched: "selector", selector, state };
2040
+ }
2041
+ const left = deadline - Date.now();
2042
+ if (left <= 0) break;
2043
+ if (Date.now() - attemptStart < 20) await sleep(Math.min(50, left));
2044
+ }
2045
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for selector ${JSON.stringify(selector)} to become ${state}`);
2046
+ }
2047
+
2048
+ await sleep(Math.min(10_000, Math.max(0, Number(timeoutMs) || 500)));
2049
+ return { tab_id: String(id), ok: true, waited_ms: timeoutMs };
2050
+ }
2051
+
2052
+ /**
2053
+ * Invoke a secondary accessibility action exposed for an element (such as "Expand" or "Collapse").
2054
+ * @param {unknown} elementIndex
2055
+ * @param {string} action
2056
+ * @param {{tabId?:unknown, settle?:boolean}} [options]
2057
+ */
2058
+ async performSecondaryAction(elementIndex, action, { tabId, settle = true } = {}) {
2059
+ const id = await this.#resolveTab(tabId);
2060
+ await this.attach(id);
2061
+ const node = this.#axNode(id, elementIndex);
2062
+ const available = Array.isArray(node.actions) ? node.actions : [];
2063
+ const wanted = String(action || "").trim().toLowerCase();
2064
+ const matched = available.find((entry) => String(entry).toLowerCase() === wanted);
2065
+ if (!matched) {
2066
+ const hint = available.length ? `; available: ${available.join(", ")}` : "";
2067
+ throw new Error(`Element index ${elementIndex} does not support secondary action ${JSON.stringify(action)}${hint}`);
2068
+ }
2069
+ await this.#clickNode(id, node, { clickCount: 1, button: "left", modifiers: 0 });
2070
+ if (settle) await this.#waitForSettle(id, { expectNavigation: false });
2071
+ return { tab_id: String(id), ok: true, action: "secondary_action", performed: matched, index: String(elementIndex) };
2072
+ }
2073
+
2074
+ /**
2075
+ * Return the active JavaScript dialog descriptor (if any) with accept()/dismiss() helpers.
2076
+ * @param {unknown} [tabId]
2077
+ */
2078
+ async getJsDialog(tabId) {
2079
+ const id = await this.#resolveTab(tabId);
2080
+ const dialog = this.#tabState(id).dialog;
2081
+ if (!dialog) return null;
2082
+ return {
2083
+ type: dialog.type,
2084
+ message: dialog.message,
2085
+ defaultPrompt: dialog.defaultPrompt,
2086
+ url: dialog.url,
2087
+ accept: (promptText) => this.handleDialog({
2088
+ tabId: id,
2089
+ accept: true,
2090
+ ...(promptText !== undefined ? { promptText: String(promptText) } : {}),
2091
+ }),
2092
+ dismiss: () => this.handleDialog({ tabId: id, accept: false }),
2093
+ };
2094
+ }
2095
+
2096
+ /**
2097
+ * Override viewport metrics for responsive / mobile UI testing.
2098
+ * @param {{tabId?:unknown, width:number, height:number, deviceScaleFactor?:number, mobile?:boolean}} options
2099
+ */
2100
+ async setViewport({ tabId, width, height, deviceScaleFactor = 1, mobile = false } = {}) {
2101
+ const w = Math.round(Number(width));
2102
+ const h = Math.round(Number(height));
2103
+ const dsf = Number(deviceScaleFactor);
2104
+ const mob = Boolean(mobile);
2105
+ if (!Number.isSafeInteger(w) || w < 100 || w > 4096 || !Number.isSafeInteger(h) || h < 100 || h > 4096) {
2106
+ throw new Error("Viewport width and height must be integers between 100 and 4096");
2107
+ }
2108
+ if (!Number.isFinite(dsf) || dsf < 0 || dsf > 8) {
2109
+ throw new Error("Viewport deviceScaleFactor must be a number between 0 and 8");
2110
+ }
2111
+ const id = await this.#resolveTab(tabId);
2112
+ await this.attach(id);
2113
+ await this.#cdp(id, "Emulation.setDeviceMetricsOverride", {
2114
+ width: w,
2115
+ height: h,
2116
+ deviceScaleFactor: dsf,
2117
+ mobile: mob,
2118
+ });
2119
+ this.#tabState(id).viewportOverride = { width: w, height: h, deviceScaleFactor: dsf, mobile: mob };
2120
+ return { tab_id: String(id), ok: true, width: w, height: h, deviceScaleFactor: dsf, mobile: mob };
2121
+ }
2122
+
2123
+ /**
2124
+ * Clear any explicit viewport override on the tab.
2125
+ * @param {unknown} [tabId]
2126
+ */
2127
+ async resetViewport(tabId) {
2128
+ const id = await this.#resolveTab(tabId);
2129
+ await this.attach(id);
2130
+ await this.#cdp(id, "Emulation.clearDeviceMetricsOverride", {});
2131
+ this.#tabState(id).viewportOverride = null;
2132
+ return { tab_id: String(id), ok: true, reset: true };
2133
+ }
2134
+
2135
+ /**
2136
+ * Read captured network requests/responses/failures for the active or specified tab.
2137
+ * @param {{tabId?:unknown, filter?:string, statusMin?:number, statusMax?:number, failedOnly?:boolean, resourceTypes?:string[], limit?:number, clear?:boolean}} [options]
2138
+ */
2139
+ async networkLogs({ tabId, filter, statusMin, statusMax, failedOnly = false, resourceTypes, limit = 100, clear = false } = {}) {
2140
+ const id = await this.#resolveTab(tabId);
2141
+ await this.attach(id);
2142
+ await this.#enableInspectionDomains(id, { network: true }).catch(() => {});
2143
+ const tabState = this.#tabState(id);
2144
+ let entries = tabState.networkLogs.map((entry) => ({ ...entry }));
2145
+ if (filter) {
2146
+ const needle = String(filter).toLowerCase();
2147
+ entries = entries.filter((entry) =>
2148
+ entry.url.toLowerCase().includes(needle) ||
2149
+ entry.method.toLowerCase().includes(needle) ||
2150
+ (entry.errorText && entry.errorText.toLowerCase().includes(needle)));
2151
+ }
2152
+ if (statusMin !== undefined) {
2153
+ const min = Number(statusMin);
2154
+ entries = entries.filter((entry) => typeof entry.status === "number" && entry.status >= min);
2155
+ }
2156
+ if (statusMax !== undefined) {
2157
+ const max = Number(statusMax);
2158
+ entries = entries.filter((entry) => typeof entry.status === "number" && entry.status <= max);
2159
+ }
2160
+ if (failedOnly === true) {
2161
+ entries = entries.filter((entry) => entry.failed === true || (typeof entry.status === "number" && entry.status >= 400));
2162
+ }
2163
+ if (Array.isArray(resourceTypes) && resourceTypes.length > 0) {
2164
+ const allowed = new Set(resourceTypes.map((r) => String(r).toLowerCase()));
2165
+ entries = entries.filter((entry) => allowed.has(entry.resourceType.toLowerCase()));
2166
+ }
2167
+ const sliced = entries.slice(-Math.max(1, Math.min(300, Number(limit) || 100)));
2168
+ if (clear) {
2169
+ tabState.networkLogs.length = 0;
2170
+ tabState.networkById.clear();
2171
+ }
2172
+ return { tab_id: String(id), count: sliced.length, requests: sliced };
2173
+ }
2174
+
2175
+ /**
2176
+ * Enable network tracking, optionally with buffered response bodies for `networkResponseBody()`.
2177
+ * @param {{tabId?:unknown, captureBodies?:boolean}} [options]
2178
+ */
2179
+ async enableNetwork({ tabId, captureBodies = false } = {}) {
2180
+ const id = await this.#resolveTab(tabId);
2181
+ await this.attach(id);
2182
+ const state = this.#tabState(id);
2183
+ if (captureBodies && !state.networkBodyCaptureEnabled) {
2184
+ await this.#cdp(id, "Network.enable", {
2185
+ maxTotalBufferSize: 8 * 1024 * 1024,
2186
+ maxResourceBufferSize: 2 * 1024 * 1024,
2187
+ });
2188
+ let set = this.enabledDomains.get(id);
2189
+ if (!set) {
2190
+ set = new Set();
2191
+ this.enabledDomains.set(id, set);
2192
+ }
2193
+ set.add("Network");
2194
+ state.networkBodyCaptureEnabled = true;
2195
+ } else {
2196
+ await this.#enableInspectionDomains(id, { network: true }).catch(() => {});
2197
+ }
2198
+ return { tab_id: String(id), ok: true, captureBodies: state.networkBodyCaptureEnabled };
2199
+ }
2200
+
2201
+ /**
2202
+ * Read the captured response body for a network request ID via CDP `Network.getResponseBody`.
2203
+ * @param {string} requestId
2204
+ * @param {{tabId?:unknown, maxChars?:number}} [options]
2205
+ */
2206
+ async networkResponseBody(requestId, { tabId, maxChars = 64_000 } = {}) {
2207
+ const reqId = typeof requestId === "string" ? requestId.trim() : "";
2208
+ if (!reqId) throw new Error("networkResponseBody requires a non-empty requestId");
2209
+ const id = await this.#resolveTab(tabId);
2210
+ await this.attach(id);
2211
+ const res = await this.#cdp(id, "Network.getResponseBody", { requestId: reqId });
2212
+ const raw = typeof res?.body === "string" ? res.body : "";
2213
+ const limit = Math.max(256, Math.min(2_000_000, Number(maxChars) || 64_000));
2214
+ const truncated = raw.length > limit;
2215
+ const body = truncated ? raw.slice(0, limit) : raw;
2216
+ return {
2217
+ tab_id: String(id),
2218
+ requestId: reqId,
2219
+ body,
2220
+ base64Encoded: Boolean(res?.base64Encoded),
2221
+ truncated,
2222
+ length: raw.length,
2223
+ };
2224
+ }
2225
+
2226
+ /**
2227
+ * Capture a cropped screenshot clipped tightly around a locator match.
2228
+ * @param {string} selector
2229
+ * @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, padding?:number, format?:"jpeg"|"png", quality?:number, scale?:"css"|"device"}} [options]
2230
+ */
2231
+ async elementScreenshot(selector, {
2232
+ tabId,
2233
+ frame,
2234
+ force = false,
2235
+ timeoutMs,
2236
+ padding = 0,
2237
+ format = "jpeg",
2238
+ quality = 75,
2239
+ scale = "css",
2240
+ } = {}) {
2241
+ const id = await this.#resolveTab(tabId);
2242
+ await this.attach(id);
2243
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, {
2244
+ frame,
2245
+ mutation: "box",
2246
+ force,
2247
+ timeoutMs,
2248
+ });
2249
+ const box = result?.box;
2250
+ if (!box || !Number.isFinite(box.width) || !Number.isFinite(box.height) || box.width <= 0 || box.height <= 0) {
2251
+ throw new Error(`Element has no visible bounding box: ${selector}`);
2252
+ }
2253
+ const pad = Math.max(0, Math.min(200, Number(padding) || 0));
2254
+ const clip = {
2255
+ x: Math.max(0, box.x - pad),
2256
+ y: Math.max(0, box.y - pad),
2257
+ width: Math.max(1, box.width + pad * 2),
2258
+ height: Math.max(1, box.height + pad * 2),
2259
+ };
2260
+ const cap = await this.screenshot(id, { format, quality, scale, clip });
2261
+ return { ...cap, box: clip };
2262
+ }
2263
+
2264
+ /**
2265
+ * Focus an AX element (if specified) and paste/insert text cleanly via `Input.insertText`.
2266
+ * @param {unknown} elementIndex
2267
+ * @param {string} text
2268
+ * @param {{tabId?:unknown, settle?:boolean}} [options]
2269
+ */
2270
+ async pasteText(elementIndex, text, { tabId, settle = false } = {}) {
2271
+ const id = await this.#resolveTab(tabId);
2272
+ await this.attach(id);
2273
+ if (elementIndex !== undefined && elementIndex !== null && elementIndex !== "") {
2274
+ const node = this.#axNode(id, elementIndex);
2275
+ const sessionId = node.sessionId ?? null;
2276
+ await this.#scrollIntoView(id, node, sessionId).catch(() => {});
2277
+ try {
2278
+ await this.#cdpTarget(id, sessionId, "DOM.focus", { backendNodeId: node.backendDOMNodeId });
2279
+ } catch {
2280
+ await this.#clickNode(id, node, { clickCount: 1, button: "left", modifiers: 0 });
2281
+ }
2282
+ }
2283
+ await this.#cdp(id, "Input.insertText", { text: String(text ?? "") });
2284
+ if (settle) await this.#waitForSettle(id);
2285
+ return { tab_id: String(id), ok: true, action: "paste" };
2286
+ }
2287
+
2288
+ /**
2289
+ * Select matching text inside an input, textarea, contenteditable, or text element.
2290
+ * @param {unknown} elementIndex
2291
+ * @param {string} text
2292
+ * @param {{tabId?:unknown, settle?:boolean}} [options]
2293
+ */
2294
+ async selectText(elementIndex, text, { tabId, settle = false } = {}) {
2295
+ const id = await this.#resolveTab(tabId);
2296
+ await this.attach(id);
2297
+ const needle = String(text ?? "");
2298
+ if (!needle) throw new Error("selectText requires non-empty text");
2299
+ if (elementIndex === undefined || elementIndex === null || elementIndex === "") {
2300
+ throw new Error("selectText requires element_index");
2301
+ }
2302
+ const node = this.#axNode(id, elementIndex);
2303
+ const sessionId = node.sessionId ?? null;
2304
+ const { object } = await this.#cdpTarget(id, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
2305
+ if (!object?.objectId) throw new Error("Browser element could not be resolved");
2306
+ const response = await this.#cdpTarget(id, sessionId, "Runtime.callFunctionOn", {
2307
+ objectId: object.objectId,
2308
+ functionDeclaration: `function (needle) {
2309
+ const query = String(needle || "");
2310
+ if (!query) return { selected: false };
2311
+ if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) {
2312
+ const val = String(this.value || "");
2313
+ const idx = val.indexOf(query);
2314
+ if (idx === -1) return { selected: false };
2315
+ this.focus();
2316
+ this.setSelectionRange(idx, idx + query.length);
2317
+ return { selected: true, start: idx, end: idx + query.length };
2318
+ }
2319
+ const doc = this.ownerDocument || document;
2320
+ const win = doc.defaultView || window;
2321
+ const walker = doc.createTreeWalker(this, NodeFilter.SHOW_TEXT);
2322
+ let current;
2323
+ while ((current = walker.nextNode())) {
2324
+ const str = current.nodeValue || "";
2325
+ const idx = str.indexOf(query);
2326
+ if (idx !== -1) {
2327
+ if (typeof this.focus === "function") this.focus();
2328
+ const range = doc.createRange();
2329
+ range.setStart(current, idx);
2330
+ range.setEnd(current, idx + query.length);
2331
+ const sel = win.getSelection();
2332
+ if (sel) {
2333
+ sel.removeAllRanges();
2334
+ sel.addRange(range);
2335
+ }
2336
+ return { selected: true, start: idx, end: idx + query.length };
2337
+ }
2338
+ }
2339
+ return { selected: false };
2340
+ }`,
2341
+ arguments: [{ value: needle }],
2342
+ returnByValue: true,
2343
+ });
2344
+ if (response?.exceptionDetails) {
2345
+ throw new Error(response.exceptionDetails.exception?.description || response.exceptionDetails.text || "selectText failed");
2346
+ }
2347
+ if (settle) await this.#waitForSettle(id);
2348
+ const outcome = (response?.result?.value && typeof response.result.value === "object")
2349
+ ? response.result.value
2350
+ : { selected: false };
2351
+ return { tab_id: String(id), ok: true, action: "select_text", ...outcome };
2352
+ }
2353
+
2354
+ /**
2355
+ * Open up to 10 URLs in temporary parallel tabs, extract structured content, and close the temporary tabs.
2356
+ * @param {string[]} urls
2357
+ * @param {{format?:"markdown"|"tables"|"links"|"text", maxChars?:number, concurrency?:number, timeoutMs?:number, waitUntil?:string}} [options]
2358
+ */
2359
+ async extractUrlsContent(urls, {
2360
+ format = "markdown",
2361
+ maxChars = 16_000,
2362
+ concurrency = 3,
2363
+ timeoutMs = 15_000,
2364
+ waitUntil = "domcontentloaded",
2365
+ } = {}) {
2366
+ if (!Array.isArray(urls) || urls.length === 0) {
2367
+ throw new Error("tabs.content requires a non-empty array of URLs");
2368
+ }
2369
+ if (urls.length > 10) {
2370
+ throw new Error("tabs.content accepts at most 10 URLs per call");
2371
+ }
2372
+ const items = urls.map((u, idx) => ({ url: String(u), idx }));
2373
+ const results = new Array(items.length);
2374
+ const workers = Math.min(items.length, Math.max(1, Math.min(4, Number(concurrency) || 3)));
2375
+ const prevActive = this.activeTabId;
2376
+ let cursor = 0;
2377
+
2378
+ try {
2379
+ await Promise.all(Array.from({ length: workers }, async () => {
2380
+ while (cursor < items.length) {
2381
+ const item = items[cursor++];
2382
+ let tempId = null;
2383
+ try {
2384
+ const tab = await this.newTab();
2385
+ tempId = tab.tab_id;
2386
+ await this.goto(item.url, tempId, { waitUntil, timeoutMs });
2387
+ const res = await this.getContent(tempId, { format, maxChars });
2388
+ const extractedText = String(res?.text ?? res?.content ?? "");
2389
+ results[item.idx] = {
2390
+ url: item.url,
2391
+ ok: true,
2392
+ title: res?.title ?? "",
2393
+ content: res?.content ?? extractedText,
2394
+ text: extractedText,
2395
+ ...(Array.isArray(res?.links) ? { links: res.links } : {}),
2396
+ ...(Array.isArray(res?.tables) ? { tables: res.tables } : {}),
2397
+ truncated: Boolean(res?.truncated),
2398
+ };
2399
+ } catch (error) {
2400
+ results[item.idx] = {
2401
+ url: item.url,
2402
+ ok: false,
2403
+ error: error instanceof Error ? error.message : String(error),
2404
+ };
2405
+ } finally {
2406
+ if (tempId != null) {
2407
+ await this.closeTab(tempId).catch(() => {});
2408
+ }
2409
+ }
2410
+ }
2411
+ }));
2412
+ } finally {
2413
+ if (prevActive !== null && this.tabs.has(prevActive)) {
2414
+ this.activeTabId = prevActive;
2415
+ }
2416
+ }
2417
+ return results;
2418
+ }
2419
+
2420
+ /**
2421
+ * Read captured console messages and runtime exceptions for the active or specified tab.
2422
+ * @param {{tabId?:unknown, levels?:string[], filter?:string, limit?:number, clear?:boolean}} [options]
2423
+ */
2424
+ async consoleLogs({ tabId, levels, filter, limit = 100, clear = false } = {}) {
2425
+ const id = await this.#resolveTab(tabId);
2426
+ await this.attach(id);
2427
+ await this.#enableInspectionDomains(id).catch(() => {});
2428
+ const tabState = this.#tabState(id);
2429
+ let entries = [...tabState.consoleLogs];
2430
+ if (Array.isArray(levels) && levels.length > 0) {
2431
+ const allowed = new Set(levels.map((l) => String(l).toLowerCase()));
2432
+ entries = entries.filter((entry) => allowed.has(entry.level.toLowerCase()));
2433
+ }
2434
+ if (filter) {
2435
+ const needle = String(filter).toLowerCase();
2436
+ entries = entries.filter((entry) => entry.message.toLowerCase().includes(needle));
2437
+ }
2438
+ const sliced = entries.slice(-Math.max(1, Math.min(500, Number(limit) || 100)));
2439
+ if (clear) tabState.consoleLogs.length = 0;
2440
+ return { tab_id: String(id), count: sliced.length, logs: sliced };
2441
+ }
2442
+
2443
+ /**
2444
+ * Inspect DOM elements at viewport coordinates (x, y) and generate ranked locators.
2445
+ * @param {number} x
2446
+ * @param {number} y
2447
+ * @param {{tabId?:unknown}} [options]
2448
+ */
2449
+ async inspectElement(x, y, { tabId } = {}) {
2450
+ const id = await this.#resolveTab(tabId);
2451
+ await this.attach(id);
2452
+ const result = await this.#evaluateRaw(id, inspectElementAtPointExpression(x, y));
2453
+ return { tab_id: String(id), ...(result ?? { x, y, elements: [] }) };
2454
+ }
2455
+
2456
+ /**
2457
+ * Return a clean Playwright-style YAML ARIA snapshot (with child iframes) without numeric clutter.
2458
+ * Also syncs the AX baseline in-memory so subsequent diff calls recognize unchanged trees.
2459
+ * @param {{tabId?:unknown, maxLines?:number, mode?:"full"|"compact"|"interactive"}} [options]
2460
+ */
2461
+ async ariaSnapshot({ tabId, maxLines = 2_000, mode = "compact" } = {}) {
2462
+ const id = await this.#resolveTab(tabId, { autoCreate: true });
2463
+ await this.attach(id);
2464
+ await Promise.all([
2465
+ this.#ensureDomain(id, "Page", "Page.enable").catch(() => {}),
2466
+ this.#ensureDomain(id, "Accessibility", "Accessibility.enable"),
2467
+ ]);
2468
+ const [mainTree, frameTreeResp] = await Promise.all([
2469
+ this.#cdp(id, "Accessibility.getFullAXTree"),
2470
+ this.#cdp(id, "Page.getFrameTree").catch(() => null),
2471
+ ]);
2472
+ const frameTrees = [{
2473
+ nodes: mainTree?.nodes ?? [],
2474
+ frameId: null,
2475
+ sessionId: null,
2476
+ depth: 0,
2477
+ }];
2478
+ if (frameTreeResp?.frameTree) {
2479
+ await this.#collectChildFrames(id, frameTreeResp.frameTree, frameTrees);
2480
+ }
2481
+ const snapshot = mergeFrameAriaSnapshots(frameTrees, { maxLines, mode });
2482
+ const tabState = this.#tabState(id);
2483
+ const url = String(frameTreeResp?.frameTree?.frame?.url || this.tabs.get(id)?.url || tabState.url || "");
2484
+ const documentKey = `${tabState.loaderId ?? ""}:${url}`;
2485
+ const baseline = mergeFrameAxStates(frameTrees, { maxLines, mode });
2486
+ this.axCache.set(id, baseline.index);
2487
+ this.lastAxSnapshots.set(id, { documentKey, entries: baseline.entries, hasIndexedBaseline: false });
2488
+ return { tab_id: String(id), ...snapshot };
2489
+ }
2490
+
2491
+ /**
2492
+ * Return a YAML ARIA snapshot scoped strictly to the subtree matched by `selector`.
2493
+ * @param {string} selector
2494
+ * @param {{tabId?:unknown, frame?:string, maxLines?:number, mode?:"full"|"compact"|"interactive", timeoutMs?:number}} [options]
2495
+ */
2496
+ async locatorAriaSnapshot(selector, { tabId, frame, maxLines = 2_000, mode = "compact", timeoutMs } = {}) {
2497
+ const id = await this.#resolveTab(tabId);
2498
+ await this.attach(id);
2499
+ const { backendNodeId, sessionId } = await this.#resolveLocatorBackendNode(id, selector, {
2500
+ frame,
2501
+ timeoutMs,
2502
+ fallbackCss: true,
2503
+ });
2504
+ if (!Number.isSafeInteger(backendNodeId)) {
2505
+ throw new Error(`Locator did not resolve to a DOM node: ${selector}`);
2506
+ }
2507
+ await this.#cdpTarget(id, sessionId, "Accessibility.enable", {}).catch(() => {});
2508
+ const tree = await this.#cdpTarget(id, sessionId, "Accessibility.getFullAXTree", {});
2509
+ let snapshot = formatAriaSnapshot(tree?.nodes ?? [], {
2510
+ maxLines,
2511
+ mode,
2512
+ rootBackendDOMNodeId: backendNodeId,
2513
+ });
2514
+ if (!snapshot.matched && !sessionId) {
2515
+ const frameTreeResp = await this.#cdp(id, "Page.getFrameTree").catch(() => null);
2516
+ if (frameTreeResp?.frameTree) {
2517
+ const childFrames = [];
2518
+ await this.#collectChildFrames(id, frameTreeResp.frameTree, childFrames);
2519
+ for (const child of childFrames) {
2520
+ const candidate = formatAriaSnapshot(child.nodes ?? [], {
2521
+ maxLines,
2522
+ mode,
2523
+ rootBackendDOMNodeId: backendNodeId,
2524
+ });
2525
+ if (candidate.matched) {
2526
+ snapshot = candidate;
2527
+ break;
2528
+ }
2529
+ }
2530
+ }
2531
+ }
2532
+ return {
2533
+ tab_id: String(id),
2534
+ selector,
2535
+ text: snapshot.text,
2536
+ lineCount: snapshot.lineCount,
2537
+ truncated: snapshot.truncated,
2538
+ };
2539
+ }
2540
+
2541
+ /**
2542
+ * Return a compact visible DOM snapshot (with same-origin iframes) or YAML ARIA snapshot.
2543
+ * @param {{tabId?:unknown, maxChars?:number, maxLines?:number, format?:"dom"|"aria", mode?:"full"|"compact"|"interactive"}} [options]
2544
+ */
2545
+ async domSnapshot({ tabId, maxChars = 24_000, maxLines = 2_000, format = "dom", mode = "compact" } = {}) {
2546
+ if (format === "aria") {
2547
+ const aria = await this.ariaSnapshot({ tabId, maxLines, mode });
2548
+ return {
2549
+ tab_id: aria.tab_id,
2550
+ format: "aria",
2551
+ snapshot: aria.text,
2552
+ lineCount: aria.lineCount,
2553
+ truncated: aria.truncated,
2554
+ };
2555
+ }
2556
+ const id = await this.#resolveTab(tabId);
2557
+ await this.attach(id);
2558
+ const result = await this.#evaluateRaw(id, domSnapshotExpression(maxChars));
2559
+ return { tab_id: String(id), format: "dom", ...(result ?? { title: "", url: "", truncated: false, snapshot: "" }) };
2560
+ }
2561
+
2562
+ /** @param {string} selector @param {boolean} checked @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2563
+ async locatorCheck(selector, checked, { tabId, frame, force = false, timeoutMs, settle = true } = {}) {
2564
+ const id = await this.#resolveTab(tabId);
2565
+ await this.attach(id);
2566
+ const action = checked ? "check" : "uncheck";
2567
+ const { inCrossOriginFrame, result: match } = await this.#runLocatorWithAutoWait(id, selector, {
2568
+ frame,
2569
+ mutation: action,
2570
+ force,
2571
+ timeoutMs,
2572
+ crossOriginOptions: { crossOriginDirect: true },
2573
+ });
2574
+ if (match.changed && !inCrossOriginFrame) {
2575
+ await this.#clickPoint(id, match.x, match.y, { clickCount: 1, button: "left", modifiers: 0 });
2576
+ if (settle) await this.#waitForSettle(id);
2577
+ }
2578
+ return {
2579
+ tab_id: String(id),
2580
+ ok: true,
2581
+ action,
2582
+ selector,
2583
+ checked: Boolean(match.checked),
2584
+ changed: Boolean(match.changed),
2585
+ ...(frame ? { frame } : {}),
2586
+ };
2587
+ }
2588
+
2589
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string}} [options] */
2590
+ async locatorCount(selector, { tabId, frame } = {}) {
2591
+ const id = await this.#resolveTab(tabId);
2592
+ await this.attach(id);
2593
+ const { result } = await this.#runLocator(id, selector, { frame, mutation: "count" });
2594
+ return { tab_id: String(id), count: Number(result?.count ?? 0) };
2595
+ }
2596
+
2597
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, mode?:"text"|"textContent"|"innerText", timeoutMs?:number}} [options] */
2598
+ async locatorText(selector, { tabId, frame, mode = "text", timeoutMs } = {}) {
2599
+ const id = await this.#resolveTab(tabId);
2600
+ await this.attach(id);
2601
+ const mutation = mode === "innerText" ? "innerText" : (mode === "textContent" ? "textContent" : "text");
2602
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, { frame, mutation, timeoutMs });
2603
+ return {
2604
+ tab_id: String(id),
2605
+ text: result?.text === null ? null : String(result?.text ?? ""),
2606
+ };
2607
+ }
2608
+
2609
+ /** @param {string} selector @param {string} name @param {{tabId?:unknown, frame?:string, timeoutMs?:number}} [options] */
2610
+ async locatorAttribute(selector, name, { tabId, frame, timeoutMs } = {}) {
2611
+ const id = await this.#resolveTab(tabId);
2612
+ await this.attach(id);
2613
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, {
2614
+ frame,
2615
+ mutation: "attr",
2616
+ attrName: String(name),
2617
+ timeoutMs,
2618
+ });
2619
+ return { tab_id: String(id), value: result?.value ?? null };
2620
+ }
2621
+
2622
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, timeoutMs?:number}} [options] */
2623
+ async locatorInputValue(selector, { tabId, frame, timeoutMs } = {}) {
2624
+ const id = await this.#resolveTab(tabId);
2625
+ await this.attach(id);
2626
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, { frame, mutation: "inputValue", timeoutMs });
2627
+ return { tab_id: String(id), value: String(result?.value ?? "") };
2628
+ }
2629
+
2630
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, mode?:"allTextContents"|"allInnerTexts"}} [options] */
2631
+ async locatorAllTexts(selector, { tabId, frame, mode = "allTextContents" } = {}) {
2632
+ const id = await this.#resolveTab(tabId);
2633
+ await this.attach(id);
2634
+ const mutation = mode === "allInnerTexts" ? "allInnerTexts" : "allTextContents";
2635
+ const { result } = await this.#runLocator(id, selector, { frame, mutation });
2636
+ return {
2637
+ tab_id: String(id),
2638
+ count: Number(result?.count ?? 0),
2639
+ values: Array.isArray(result?.values) ? result.values : [],
2640
+ };
2641
+ }
2642
+
2643
+ /** @param {string} selector @param {"isVisible"|"isEnabled"|"isChecked"} stateKind @param {{tabId?:unknown, frame?:string}} [options] */
2644
+ async locatorState(selector, stateKind, { tabId, frame } = {}) {
2645
+ const id = await this.#resolveTab(tabId);
2646
+ await this.attach(id);
2647
+ const { result } = await this.#runLocator(id, selector, { frame, mutation: stateKind });
2648
+ return { tab_id: String(id), value: Boolean(result?.value) };
2649
+ }
2650
+
2651
+ /** @param {string} selector @param {string|Function} fnOrExpr @param {{tabId?:unknown, frame?:string, all?:boolean, arg?:unknown, hasArg?:boolean, timeoutMs?:number}} [options] */
2652
+ async locatorEvaluate(selector, fnOrExpr, { tabId, frame, all = false, arg, hasArg = false, timeoutMs } = {}) {
2653
+ const source = typeof fnOrExpr === "function" ? fnOrExpr.toString() : String(fnOrExpr);
2654
+ assertReadOnly(source);
2655
+ const id = await this.#resolveTab(tabId);
2656
+ await this.attach(id);
2657
+ const opts = {
2658
+ frame,
2659
+ mutation: all ? "evalAll" : "eval",
2660
+ evalFn: source,
2661
+ evalArg: arg,
2662
+ hasEvalArg: Boolean(hasArg),
2663
+ asyncEval: true,
2664
+ timeoutMs,
2665
+ };
2666
+ const { result } = all
2667
+ ? await this.#runLocator(id, selector, opts)
2668
+ : await this.#runLocatorWithAutoWait(id, selector, opts);
2669
+ return { tab_id: String(id), count: Number(result?.count ?? 0), value: result?.value };
2670
+ }
2671
+
2672
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, clickCount?:number, button?:string, modifiers?:string|string[], force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2673
+ async locatorClick(selector, { tabId, frame, clickCount = 1, button = "left", modifiers, force = false, timeoutMs, settle = false } = {}) {
2674
+ const id = await this.#resolveTab(tabId);
2675
+ await this.attach(id);
2676
+ const modMask = parseModifiers(modifiers);
2677
+ const { inCrossOriginFrame, result: match } = await this.#runLocatorWithAutoWait(id, selector, {
2678
+ frame,
2679
+ mutation: "point",
2680
+ crossOriginMutation: "click",
2681
+ force,
2682
+ timeoutMs,
2683
+ });
2684
+ if (!inCrossOriginFrame) {
2685
+ await this.#clickPoint(id, match.x, match.y, { clickCount, button, modifiers: modMask });
2686
+ }
2687
+ if (settle) await this.#waitForSettle(id, { expectNavigation: true });
2688
+ return { tab_id: String(id), ok: true, action: "locator_click", selector, ...(frame ? { frame } : {}) };
2689
+ }
2690
+
2691
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, timeoutMs?:number}} [options] */
2692
+ async locatorScrollIntoView(selector, { tabId, frame, timeoutMs } = {}) {
2693
+ const id = await this.#resolveTab(tabId);
2694
+ await this.attach(id);
2695
+ const { result } = await this.#runLocatorWithAutoWait(id, selector, {
2696
+ frame,
2697
+ mutation: "scrollIntoView",
2698
+ timeoutMs,
2699
+ });
2700
+ return {
2701
+ tab_id: String(id),
2702
+ ok: true,
2703
+ action: "scroll_into_view",
2704
+ selector,
2705
+ ...(frame ? { frame } : {}),
2706
+ ...(result?.box ? { box: result.box } : {}),
2707
+ };
2708
+ }
2709
+
2710
+ /** @param {string} selector @param {string} value @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2711
+ async locatorFill(selector, value, { tabId, frame, force = false, timeoutMs, settle = false } = {}) {
2712
+ const id = await this.#resolveTab(tabId);
2713
+ await this.attach(id);
2714
+ await this.#runLocatorWithAutoWait(id, selector, {
2715
+ frame,
2716
+ mutation: "fill",
2717
+ value: String(value),
2718
+ force,
2719
+ timeoutMs,
2720
+ });
2721
+ if (settle) await this.#waitForSettle(id);
2722
+ return { tab_id: String(id), ok: true, action: "locator_fill", selector, ...(frame ? { frame } : {}) };
2723
+ }
2724
+
2725
+ /** @param {string} selector @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2726
+ async locatorClear(selector, { tabId, frame, force = false, timeoutMs, settle = false } = {}) {
2727
+ const id = await this.#resolveTab(tabId);
2728
+ await this.attach(id);
2729
+ await this.#runLocatorWithAutoWait(id, selector, {
2730
+ frame,
2731
+ mutation: "clear",
2732
+ force,
2733
+ timeoutMs,
2734
+ });
2735
+ if (settle) await this.#waitForSettle(id);
2736
+ return { tab_id: String(id), ok: true, action: "locator_clear", selector, ...(frame ? { frame } : {}) };
2737
+ }
2738
+
2739
+ /** @param {string} selector @param {string} key @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, settle?:boolean}} [options] */
2740
+ async locatorPress(selector, key, { tabId, frame, force = false, timeoutMs, settle = false } = {}) {
2741
+ const id = await this.#resolveTab(tabId);
2742
+ await this.attach(id);
2743
+ const { sessionId } = await this.#runLocatorWithAutoWait(id, selector, {
2744
+ frame,
2745
+ mutation: "focus",
2746
+ force,
2747
+ timeoutMs,
2748
+ });
2749
+ const parsed = await this.#sendKeyCombo(id, key, sessionId ?? null);
2750
+ if (settle) await this.#waitForSettle(id, { expectNavigation: parsed.key === "Enter" });
2751
+ return { tab_id: String(id), ok: true, action: "locator_press", selector, key };
2752
+ }
2753
+
2754
+ /** @param {string} selector @param {string} text @param {{tabId?:unknown, frame?:string, force?:boolean, timeoutMs?:number, sequentially?:boolean, delayMs?:number, settle?:boolean}} [options] */
2755
+ async locatorType(selector, text, { tabId, frame, force = false, timeoutMs, sequentially = false, delayMs = 0, settle = false } = {}) {
2756
+ const id = await this.#resolveTab(tabId);
2757
+ await this.attach(id);
2758
+ const { sessionId } = await this.#runLocatorWithAutoWait(id, selector, {
2759
+ frame,
2760
+ mutation: "focus",
2761
+ force,
2762
+ timeoutMs,
2763
+ });
2764
+ const value = String(text);
2765
+ const targetSession = sessionId ?? null;
2766
+ if (!sequentially) {
2767
+ await this.#cdpTarget(id, targetSession, "Input.insertText", { text: value });
2768
+ } else {
2769
+ for (const ch of value) {
2770
+ if (ch === "\n" || ch === "\r") {
2771
+ await this.#sendKeyCombo(id, "Enter", targetSession);
2772
+ } else if (/^[\x20-\x7e]$/u.test(ch)) {
2773
+ await this.#cdpTarget(id, targetSession, "Input.dispatchKeyEvent", {
2774
+ type: "keyDown",
2775
+ key: ch,
2776
+ text: ch,
2777
+ unmodifiedText: ch,
2778
+ });
2779
+ await this.#cdpTarget(id, targetSession, "Input.dispatchKeyEvent", { type: "keyUp", key: ch });
2780
+ } else {
2781
+ await this.#cdpTarget(id, targetSession, "Input.insertText", { text: ch });
2782
+ }
2783
+ if (delayMs > 0) await sleep(delayMs);
2784
+ }
2785
+ }
2786
+ if (settle) await this.#waitForSettle(id);
2787
+ return { tab_id: String(id), ok: true, action: sequentially ? "locator_press_sequentially" : "locator_type", selector };
2788
+ }
2789
+
2790
+ /**
2791
+ * Read an existing Chrome tab's content passively without attaching the Chrome debugger.
2792
+ * @param {unknown} tabId
2793
+ * @param {{format?:"markdown"|"text", maxChars?:number}} [options]
2794
+ */
2795
+ async readTabContext(tabId, { format = "markdown", maxChars = 16_000 } = {}) {
2796
+ this.#assertOpen();
2797
+ const id = Number(tabId ?? this.activeTabId);
2798
+ if (!Number.isSafeInteger(id)) throw new Error("A numeric tab_id is required");
2799
+ const res = await this.#rpc("readTabContext", {
2800
+ tabId: id,
2801
+ format: format === "text" ? "text" : "markdown",
2802
+ maxChars: Number.isFinite(Number(maxChars)) ? Number(maxChars) : 16_000,
2803
+ });
2804
+ return { tab_id: String(id), ...(res ?? {}) };
2805
+ }
2806
+
2807
+ /** @param {unknown} tabId @param {{format?:string, maxChars?:number}} [options] */
2808
+ async getContent(tabId, options = {}) {
2809
+ const hasExplicit = tabId !== undefined && tabId !== null && tabId !== "";
2810
+ const numId = hasExplicit ? Number(tabId) : NaN;
2811
+ if (this.supportsPassiveRead && Number.isSafeInteger(numId) &&
2812
+ !this.attached.has(numId) && !this.ownedTabs.has(numId)) {
2813
+ try {
2814
+ const passive = await this.readTabContext(numId, {
2815
+ format: options?.format === "markdown" ? "markdown" : "text",
2816
+ maxChars: options?.maxChars,
2817
+ });
2818
+ return {
2819
+ tab_id: String(numId),
2820
+ text: String(passive?.text ?? passive?.content ?? ""),
2821
+ ...(passive?.format ? { format: passive.format } : {}),
2822
+ ...(passive?.title !== undefined ? { title: passive.title } : {}),
2823
+ ...(passive?.url !== undefined ? { url: passive.url } : {}),
2824
+ ...(passive?.truncated !== undefined ? { truncated: passive.truncated } : {}),
2825
+ passive: true,
2826
+ };
2827
+ } catch (err) {
2828
+ const msg = String(err?.message || err);
2829
+ if (!/No handler|not supported|Unknown/i.test(msg)) throw err;
2830
+ }
2831
+ }
2832
+ const id = await this.#resolveTab(tabId);
2833
+ await this.attach(id);
2834
+ if (options && (options.format || options.maxChars !== undefined)) {
2835
+ const fmt = options.format ?? "markdown";
2836
+ const maxChars = options.maxChars ?? 16_000;
2837
+ const extracted = await this.#evaluateRaw(id, extractContentExpression({ format: fmt, maxChars }));
2838
+ if (extracted && typeof extracted === "object") {
2839
+ return {
2840
+ tab_id: String(id),
2841
+ ...extracted,
2842
+ text: String(extracted.text ?? extracted.content ?? ""),
2843
+ };
2844
+ }
2845
+ }
2846
+ const text = await this.#evaluateRaw(id, "document.body ? document.body.innerText : ''");
2847
+ return { tab_id: String(id), text: String(text ?? "") };
2848
+ }
2849
+
2850
+ /** @param {string} source @param {{tabId?:unknown, arg?:unknown, hasArg?:boolean}} [options] */
2851
+ async evaluate(source, { tabId, arg, hasArg = false } = {}) {
2852
+ const id = await this.#resolveTab(tabId);
2853
+ await this.attach(id);
2854
+ const checked = assertReadOnly(source);
2855
+ const serializedArg = arg === undefined ? "undefined" : JSON.stringify(arg);
2856
+ const expression = hasArg ? `(${checked})(${serializedArg})` : checked;
2857
+ const value = await this.#evaluateRaw(id, expression, { awaitPromise: true });
2858
+ return { tab_id: String(id), value: value ?? null };
2859
+ }
2860
+
2861
+ /**
2862
+ * Discover WebMCP tools registered via `navigator.modelContext` on the active document.
2863
+ * @param {unknown} [tabId]
2864
+ */
2865
+ async webmcpListTools(tabId) {
2866
+ const id = await this.#resolveTab(tabId);
2867
+ await this.attach(id);
2868
+ const expr = `(() => {
2869
+ const ctx = navigator.modelContext || window.__webmcp || null;
2870
+ if (!ctx) return { supported: false, tools: [] };
2871
+ const raw = typeof ctx.listTools === "function" ? ctx.listTools() : (Array.isArray(ctx.tools) ? ctx.tools : []);
2872
+ const tools = Array.isArray(raw) ? raw.map((t) => ({
2873
+ name: String(t?.name || ""),
2874
+ description: t?.description ? String(t.description) : "",
2875
+ inputSchema: t?.inputSchema ?? null,
2876
+ })).filter((t) => t.name) : [];
2877
+ return { supported: true, tools };
2878
+ })()`;
2879
+ const res = await this.#evaluateRaw(id, expr);
2880
+ return { tab_id: String(id), supported: Boolean(res?.supported), tools: Array.isArray(res?.tools) ? res.tools : [] };
2881
+ }
2882
+
2883
+ /**
2884
+ * Invoke a registered WebMCP tool on the active document.
2885
+ * @param {string} name
2886
+ * @param {Record<string, unknown>} [args]
2887
+ * @param {{tabId?:unknown}} [options]
2888
+ */
2889
+ async webmcpInvokeTool(name, args = {}, { tabId } = {}) {
2890
+ const id = await this.#resolveTab(tabId);
2891
+ await this.attach(id);
2892
+ const expr = `(async () => {
2893
+ const toolName = ${JSON.stringify(String(name))};
2894
+ const payload = ${JSON.stringify(args ?? {})};
2895
+ const ctx = navigator.modelContext || window.__webmcp || null;
2896
+ if (!ctx) throw new Error("WebMCP is not supported on this page");
2897
+ if (typeof ctx.invokeTool === "function") return await ctx.invokeTool(toolName, payload);
2898
+ if (typeof ctx.callTool === "function") return await ctx.callTool(toolName, payload);
2899
+ const raw = typeof ctx.listTools === "function" ? ctx.listTools() : (Array.isArray(ctx.tools) ? ctx.tools : []);
2900
+ const match = Array.isArray(raw) ? raw.find((t) => t?.name === toolName) : null;
2901
+ if (!match || typeof match.execute !== "function") throw new Error("WebMCP tool not found: " + toolName);
2902
+ return await match.execute(payload);
2903
+ })()`;
2904
+ const result = await this.#evaluateRaw(id, expr, { awaitPromise: true, userGesture: true });
2905
+ return { tab_id: String(id), name: String(name), result: result ?? null };
2906
+ }
2907
+
2908
+ /**
2909
+ * Inventory observable page assets (images, stylesheets, scripts, videos, fonts, inline SVGs).
2910
+ * @param {unknown} [tabId]
2911
+ * @param {{limit?:number}} [options]
2912
+ */
2913
+ async listPageAssets(tabId, { limit = 100 } = {}) {
2914
+ const id = await this.#resolveTab(tabId);
2915
+ await this.attach(id);
2916
+ const cap = Math.max(10, Math.min(500, Number(limit) || 100));
2917
+ const expr = `(() => {
2918
+ const cap = ${cap};
2919
+ const assets = [];
2920
+ const seen = new Set();
2921
+ const add = (kind, url, source) => {
2922
+ if (!url || seen.has(kind + "|" + url) || assets.length >= cap) return;
2923
+ seen.add(kind + "|" + url);
2924
+ assets.push({ kind, url: String(url).slice(0, 500), source });
2925
+ };
2926
+ for (const img of document.querySelectorAll("img[src]")) add("image", img.currentSrc || img.src, "img");
2927
+ for (const link of document.querySelectorAll('link[rel~="stylesheet"][href]')) add("stylesheet", link.href, "link");
2928
+ for (const sc of document.querySelectorAll("script[src]")) add("script", sc.src, "script");
2929
+ for (const vid of document.querySelectorAll("video[src], video source[src]")) add("video", vid.src, vid.tagName.toLowerCase());
2930
+ const fonts = document.fonts ? Array.from(document.fonts).slice(0, 30).map((f) => ({ family: f.family, status: f.status })) : [];
2931
+ const inlineSvgs = Array.from(document.querySelectorAll("svg")).slice(0, 20).map((svg, i) => ({
2932
+ index: i,
2933
+ id: svg.id || null,
2934
+ viewBox: svg.getAttribute("viewBox") || null,
2935
+ markupLength: (svg.outerHTML || "").length,
2936
+ }));
2937
+ return { url: location.href, assets, fonts, inlineSvgCount: document.querySelectorAll("svg").length, inlineSvgs };
2938
+ })()`;
2939
+ const res = await this.#evaluateRaw(id, expr);
2940
+ return { tab_id: String(id), ...(res ?? { assets: [], fonts: [], inlineSvgCount: 0, inlineSvgs: [] }) };
2941
+ }
2942
+
2943
+ /** @param {{tabId?:unknown, accept:boolean, promptText?:string}} options */
2944
+ async handleDialog({ tabId, accept, promptText }) {
2945
+ const id = await this.#resolveTab(tabId);
2946
+ await this.attach(id);
2947
+ await this.#cdp(id, "Page.handleJavaScriptDialog", {
2948
+ accept: Boolean(accept),
2949
+ ...(promptText === undefined ? {} : { promptText: String(promptText) }),
2950
+ });
2951
+ const state = this.tabStates.get(id);
2952
+ if (state) state.dialog = null;
2953
+ return { tab_id: String(id), ok: true, action: "handle_dialog", accepted: Boolean(accept) };
2954
+ }
2955
+
2956
+ /**
2957
+ * Execute a pipeline of browser actions in a single round-trip, settling between
2958
+ * navigation/click actions and optionally returning the resulting diff/full state/screenshot.
2959
+ * @param {Array<Record<string, any>>} steps
2960
+ * @param {{tabId?:unknown, returnState?:"diff"|"full"|"screenshot"|"both"|"none", mode?:"full"|"compact"|"interactive", maxLines?:number, stopOnError?:boolean}} [options]
2961
+ */
2962
+ async batch(steps, { tabId, returnState = "diff", mode = "full", maxLines = 1_500, stopOnError = true } = {}) {
2963
+ if (!Array.isArray(steps) || steps.length === 0) {
2964
+ throw new Error("batch requires a non-empty array of steps");
2965
+ }
2966
+ let currentTabId = tabId;
2967
+ const completed = [];
2968
+ for (let i = 0; i < steps.length; i++) {
2969
+ const step = steps[i] ?? {};
2970
+ const stepTab = step.tab_id ?? step.tabId ?? currentTabId;
2971
+ try {
2972
+ let result;
2973
+ switch (step.action) {
2974
+ case "new_tab":
2975
+ result = await this.newTab(step.url);
2976
+ currentTabId = result.tab_id;
2977
+ break;
2978
+ case "select_tab":
2979
+ result = await this.selectTab(step.tab_id);
2980
+ currentTabId = result.tab_id;
2981
+ break;
2982
+ case "close_tab":
2983
+ result = await this.closeTab(stepTab);
2984
+ if (String(stepTab) === String(currentTabId)) currentTabId = undefined;
2985
+ break;
2986
+ case "goto":
2987
+ result = await this.goto(step.url, stepTab, { waitUntil: step.wait_until ?? "load" });
2988
+ currentTabId = result.tab_id;
2989
+ break;
2990
+ case "back":
2991
+ result = await this.history("back", stepTab);
2992
+ break;
2993
+ case "forward":
2994
+ result = await this.history("forward", stepTab);
2995
+ break;
2996
+ case "reload":
2997
+ result = await this.reload(stepTab);
2998
+ break;
2999
+ case "click":
3000
+ result = await this.click(step.element_index, {
3001
+ tabId: stepTab,
3002
+ clickCount: step.click_count ?? 1,
3003
+ button: step.mouse_button ?? "left",
3004
+ modifiers: step.modifiers,
3005
+ x: step.x,
3006
+ y: step.y,
3007
+ settle: true,
3008
+ });
3009
+ break;
3010
+ case "set_value":
3011
+ result = await this.setValue(step.element_index, step.value, { tabId: stepTab, settle: true });
3012
+ break;
3013
+ case "type_text":
3014
+ result = await this.typeText(step.text, { tabId: stepTab, elementIndex: step.element_index, settle: true });
3015
+ break;
3016
+ case "press_key":
3017
+ result = await this.pressKey(step.key, { tabId: stepTab, elementIndex: step.element_index, settle: true });
3018
+ break;
3019
+ case "select_option":
3020
+ result = await this.selectOption({
3021
+ tabId: stepTab,
3022
+ elementIndex: step.element_index,
3023
+ selector: step.selector,
3024
+ frame: step.frame,
3025
+ value: step.value,
3026
+ label: step.label,
3027
+ index: step.index,
3028
+ });
3029
+ break;
3030
+ case "hover":
3031
+ result = await this.hover({
3032
+ tabId: stepTab,
3033
+ elementIndex: step.element_index,
3034
+ selector: step.selector,
3035
+ frame: step.frame,
3036
+ x: step.x,
3037
+ y: step.y,
3038
+ });
3039
+ break;
3040
+ case "drag":
3041
+ result = await this.drag({
3042
+ tabId: stepTab,
3043
+ fromIndex: step.from_index,
3044
+ toIndex: step.to_index,
3045
+ fromX: step.from_x,
3046
+ fromY: step.from_y,
3047
+ toX: step.to_x,
3048
+ toY: step.to_y,
3049
+ });
3050
+ break;
3051
+ case "scroll":
3052
+ result = await this.scroll(step.direction, {
3053
+ tabId: stepTab,
3054
+ pages: step.pages ?? 1,
3055
+ elementIndex: step.element_index,
3056
+ x: step.x,
3057
+ y: step.y,
3058
+ });
3059
+ break;
3060
+ case "locator_click":
3061
+ result = await this.locatorClick(step.selector, {
3062
+ tabId: stepTab,
3063
+ frame: step.frame,
3064
+ clickCount: step.click_count ?? 1,
3065
+ button: step.mouse_button ?? "left",
3066
+ modifiers: step.modifiers,
3067
+ force: step.force === true,
3068
+ timeoutMs: step.timeout_ms,
3069
+ settle: true,
3070
+ });
3071
+ break;
3072
+ case "locator_fill":
3073
+ result = await this.locatorFill(step.selector, step.value, {
3074
+ tabId: stepTab,
3075
+ frame: step.frame,
3076
+ force: step.force === true,
3077
+ timeoutMs: step.timeout_ms,
3078
+ settle: true,
3079
+ });
3080
+ break;
3081
+ case "set_viewport":
3082
+ result = await this.setViewport({
3083
+ tabId: stepTab,
3084
+ width: step.width,
3085
+ height: step.height,
3086
+ deviceScaleFactor: step.device_scale_factor ?? 1,
3087
+ mobile: step.mobile === true,
3088
+ });
3089
+ break;
3090
+ case "reset_viewport":
3091
+ result = await this.resetViewport(stepTab);
3092
+ break;
3093
+ case "upload_files":
3094
+ result = await this.uploadFiles(step.files, {
3095
+ tabId: stepTab,
3096
+ elementIndex: step.element_index,
3097
+ selector: step.selector,
3098
+ frame: step.frame,
3099
+ });
3100
+ break;
3101
+ case "wait":
3102
+ result = await this.waitFor({
3103
+ tabId: stepTab,
3104
+ selector: step.selector,
3105
+ text: step.text,
3106
+ url: step.url,
3107
+ loadState: step.load_state,
3108
+ state: step.state,
3109
+ frame: step.frame,
3110
+ timeoutMs: step.timeout_ms ?? 10_000,
3111
+ });
3112
+ break;
3113
+ case "handle_dialog":
3114
+ result = await this.handleDialog({ tabId: stepTab, accept: step.accept, promptText: step.prompt_text });
3115
+ break;
3116
+ case "name_session":
3117
+ result = await this.nameSession(step.name, { color: step.color ?? "blue" });
3118
+ break;
3119
+ case "get_state":
3120
+ result = await this.getState(stepTab, {
3121
+ screenshot: false,
3122
+ diff: step.mode ? true : true,
3123
+ mode: step.mode ?? mode,
3124
+ maxLines,
3125
+ });
3126
+ break;
3127
+ case "get_content":
3128
+ result = await this.getContent(stepTab, {
3129
+ ...(step.format ? { format: step.format } : {}),
3130
+ ...(step.max_chars !== undefined ? { maxChars: step.max_chars } : {}),
3131
+ });
3132
+ break;
3133
+ case "read_tab":
3134
+ result = await this.readTabContext(stepTab, {
3135
+ format: step.format === "text" ? "text" : "markdown",
3136
+ maxChars: step.max_chars ?? 16_000,
3137
+ });
3138
+ break;
3139
+ case "evaluate":
3140
+ result = await this.evaluate(step.expression, { tabId: stepTab });
3141
+ break;
3142
+ default:
3143
+ throw new Error(`Unsupported batch action: ${String(step.action)}`);
3144
+ }
3145
+ completed.push({ step: i, action: step.action, ok: true, result });
3146
+ } catch (error) {
3147
+ const errText = error instanceof Error ? error.message : String(error);
3148
+ completed.push({ step: i, action: step.action, ok: false, error: errText });
3149
+ if (stopOnError) {
3150
+ let state = null;
3151
+ if (returnState !== "none") {
3152
+ state = await this.getState(currentTabId, {
3153
+ screenshot: returnState === "screenshot" || returnState === "both",
3154
+ diff: returnState === "diff",
3155
+ full: returnState === "full" || returnState === "both",
3156
+ mode,
3157
+ maxLines,
3158
+ }).catch(() => null);
3159
+ }
3160
+ return {
3161
+ ok: false,
3162
+ failed_step: i,
3163
+ error: errText,
3164
+ completed_steps: completed,
3165
+ state,
3166
+ };
3167
+ }
3168
+ }
3169
+ }
3170
+
3171
+ let state = null;
3172
+ if (returnState !== "none") {
3173
+ const wantShot = returnState === "screenshot" || returnState === "both";
3174
+ const wantAx = returnState !== "screenshot";
3175
+ if (wantAx) {
3176
+ state = await this.getState(currentTabId, {
3177
+ screenshot: wantShot,
3178
+ diff: returnState === "diff",
3179
+ full: returnState === "full" || returnState === "both",
3180
+ mode,
3181
+ maxLines,
3182
+ }).catch(() => null);
3183
+ } else {
3184
+ const cap = await this.screenshot(currentTabId).catch(() => null);
3185
+ if (cap) state = { tab_id: cap.tab_id, screenshotBase64: cap.data, screenshotMimeType: cap.mimeType };
3186
+ }
3187
+ }
3188
+ return {
3189
+ ok: completed.every((c) => c.ok),
3190
+ completed_steps: completed,
3191
+ state,
3192
+ };
3193
+ }
3194
+
3195
+ /** @param {Array<{tab_id:unknown, mode?:string, focus?:boolean}>} [entries] */
3196
+ async markTabs(entries = []) {
3197
+ const marked = [];
3198
+ for (const entry of entries) {
3199
+ const id = await this.#resolveTab(entry?.tab_id);
3200
+ const mode = entry?.mode === "deliverable" ? "deliverable" : "handoff";
3201
+ if (mode === "deliverable" && entry?.focus === true && this.attached.has(id)) {
3202
+ await this.#cdp(id, "Page.bringToFront").catch(() => {});
3203
+ }
3204
+ await this.#rpc("markTab", {
3205
+ tabId: id,
3206
+ status: mode,
3207
+ ...(entry?.focus === true ? { focus: true } : {}),
3208
+ });
3209
+ marked.push({ tab_id: String(id), mode });
3210
+ }
3211
+ return marked;
3212
+ }
3213
+
3214
+ /** @param {{keep?:Array<{tab_id:unknown, mode?:string, focus?:boolean}>, ungroup?:boolean}} [options] */
3215
+ async endTurn({ keep = [], ungroup = false } = {}) {
3216
+ const handoffIds = new Set();
3217
+ for (const entry of keep) {
3218
+ const id = await this.#resolveTab(entry?.tab_id);
3219
+ const mode = entry?.mode === "deliverable" ? "deliverable" : "handoff";
3220
+ if (mode === "handoff") handoffIds.add(id);
3221
+ if (mode === "deliverable" && entry?.focus === true && this.attached.has(id)) {
3222
+ await this.#cdp(id, "Page.bringToFront").catch(() => {});
3223
+ }
3224
+ await this.#rpc("markTab", {
3225
+ tabId: id,
3226
+ status: mode,
3227
+ ...(entry?.focus === true ? { focus: true } : {}),
3228
+ });
3229
+ }
3230
+ await this.#rpc("turnEnded", { ...(ungroup === true ? { ungroup: true } : {}) });
3231
+ if (ungroup === true) {
3232
+ this.sessionName = null;
3233
+ }
3234
+ this.turnId = randomUUID();
3235
+ this.attached.clear();
3236
+ this.attaching.clear();
3237
+ this.axCache.clear();
3238
+ this.enabledDomains.clear();
3239
+ this.enablingDomains.clear();
3240
+ this.enabledChildAxSessions.clear();
3241
+ this.frameRouteCache.clear();
3242
+ this.lastAxSnapshots.clear();
3243
+ this.frameSessions.clear();
3244
+ this.autoAttached.clear();
3245
+ this.locatorRuntimeInstalled.clear();
3246
+ this.statelessEvalTabs.clear();
3247
+ for (const id of [...this.ownedTabs]) {
3248
+ if (!handoffIds.has(id)) {
3249
+ this.ownedTabs.delete(id);
3250
+ this.tabs.delete(id);
3251
+ this.tabStates.delete(id);
3252
+ }
3253
+ }
3254
+ if (this.activeTabId !== null && !this.ownedTabs.has(this.activeTabId)) {
3255
+ this.activeTabId = this.ownedTabs.values().next().value ?? null;
3256
+ }
3257
+ return { ok: true, ended: true, ...(ungroup === true ? { ungrouped: true } : {}), nextTurnId: this.turnId };
3258
+ }
3259
+
3260
+ /** @returns {Promise<Array<Record<string,unknown>>>} */
3261
+ async listTabGroups() {
3262
+ this.#assertOpen();
3263
+ const res = await this.#rpc("listTabGroups");
3264
+ return Array.isArray(res) ? res : [];
3265
+ }
3266
+
3267
+ /** @param {Array<unknown>} [tabIds] @returns {Promise<Record<string,unknown>>} */
3268
+ async ungroupTabs(tabIds) {
3269
+ this.#assertOpen();
3270
+ return await this.#rpc("ungroupTabs", {
3271
+ ...(Array.isArray(tabIds) ? { tabIds: tabIds.map(Number).filter(Number.isSafeInteger) } : {}),
3272
+ });
3273
+ }
3274
+
3275
+ /** @param {{ungroupFinished?:boolean, closeDuplicateDeliverables?:boolean, keepTabIds?:Array<unknown>}} [options] @returns {Promise<Record<string,unknown>>} */
3276
+ async cleanupGroups(options = {}) {
3277
+ this.#assertOpen();
3278
+ return await this.#rpc("cleanupGroups", {
3279
+ ungroupFinished: options?.ungroupFinished === true,
3280
+ closeDuplicateDeliverables: options?.closeDuplicateDeliverables !== false,
3281
+ ...(Array.isArray(options?.keepTabIds) ? { keepTabIds: options.keepTabIds.map(Number).filter(Number.isSafeInteger) } : {}),
3282
+ });
3283
+ }
3284
+
3285
+ async close() {
3286
+ if (this.closed) return;
3287
+ this.closed = true;
3288
+ await this.closeFn();
3289
+ }
3290
+
3291
+ #assertOpen() {
3292
+ if (this.closed) throw new Error("Browser session is closed");
3293
+ }
3294
+
3295
+ /** @param {number} tabId @param {unknown} index */
3296
+ #axNode(tabId, index) {
3297
+ const key = String(index).trim();
3298
+ const node = this.axCache.get(tabId)?.get(key);
3299
+ if (!node) throw new Error(`Element index ${key} not found in the current accessibility tree. Call browser_get_state first.`);
3300
+ return node;
3301
+ }
3302
+
3303
+ /** @param {number} tabId @param {{backendDOMNodeId:number|null}} node @param {string|null} [sessionId] */
3304
+ async #scrollIntoView(tabId, node, sessionId = null) {
3305
+ if (!Number.isSafeInteger(node.backendDOMNodeId)) return;
3306
+ await this.#cdpTarget(tabId, sessionId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: node.backendDOMNodeId });
3307
+ }
3308
+
3309
+ /** @param {number} tabId @param {{backendDOMNodeId:number|null}} node @param {string|null} [sessionId] */
3310
+ async #boxModel(tabId, node, sessionId = null) {
3311
+ await this.#scrollIntoView(tabId, node, sessionId).catch(() => {});
3312
+ const model = await this.#cdpTarget(tabId, sessionId, "DOM.getBoxModel", { backendNodeId: node.backendDOMNodeId });
3313
+ const quad = model?.model?.border;
3314
+ if (!Array.isArray(quad) || quad.length !== 8) throw new Error("Browser element has no visible box");
3315
+ const x = (quad[0] + quad[2]) / 2;
3316
+ const y = (quad[1] + quad[5]) / 2;
3317
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("Browser element has no visible box");
3318
+ return { x, y };
3319
+ }
3320
+
3321
+ /** @param {number} tabId @param {{backendDOMNodeId:number|null, role:string, name:string, sessionId?:string|null}} node @param {{clickCount:number, button:string, modifiers:number}} options */
3322
+ async #clickNode(tabId, node, { clickCount, button, modifiers }) {
3323
+ const sessionId = node.sessionId ?? null;
3324
+ if (sessionId) {
3325
+ // Cross-origin iframe AX node: scroll & trigger click inside its debugger session.
3326
+ await this.#scrollIntoView(tabId, node, sessionId).catch(() => {});
3327
+ const { object } = await this.#cdpIn(tabId, sessionId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
3328
+ if (!object?.objectId) throw new Error("Browser iframe element could not be resolved for clicking");
3329
+ await this.#cdpIn(tabId, sessionId, "Runtime.callFunctionOn", {
3330
+ objectId: object.objectId,
3331
+ functionDeclaration: "function () { this.focus?.(); this.click(); }",
3332
+ userGesture: true,
3333
+ });
3334
+ return;
3335
+ }
3336
+
3337
+ // Try fast Shadow-DOM-aware hit-test first; fall back cleanly to #boxModel on minimal mocks.
3338
+ let point = null;
3339
+ let resolvedObjectId = null;
3340
+ try {
3341
+ const quads = await this.#cdp(tabId, "DOM.getContentQuads", { backendNodeId: node.backendDOMNodeId });
3342
+ if (Array.isArray(quads?.quads) && quads.quads.length > 0) {
3343
+ const resolved = await this.#cdp(tabId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
3344
+ resolvedObjectId = resolved?.object?.objectId ?? null;
3345
+ if (resolvedObjectId) {
3346
+ let hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3347
+ objectId: resolvedObjectId,
3348
+ functionDeclaration: hitTestFunctionDeclaration(),
3349
+ returnByValue: true,
3350
+ });
3351
+ let val = hit?.result?.value;
3352
+ if (val && (val.offscreen || val.hitsTarget === false)) {
3353
+ await this.#scrollIntoView(tabId, node).catch(() => {});
3354
+ hit = await this.#cdp(tabId, "Runtime.callFunctionOn", {
3355
+ objectId: resolvedObjectId,
3356
+ functionDeclaration: hitTestFunctionDeclaration(),
3357
+ returnByValue: true,
3358
+ });
3359
+ val = hit?.result?.value;
3360
+ }
3361
+ if (val?.hitsTarget && val.point) {
3362
+ point = val.point;
3363
+ } else if (val && val.hitsTarget === false) {
3364
+ throw new Error(`Accessibility element (${node.role} "${node.name}") is covered by <${val.hitTag || "unknown"}> or not hittable`);
3365
+ }
3366
+ }
3367
+ }
3368
+ } catch (error) {
3369
+ if (error instanceof Error && error.message.includes("not hittable")) throw error;
3370
+ } finally {
3371
+ if (resolvedObjectId) {
3372
+ await this.#cdp(tabId, "Runtime.releaseObject", { objectId: resolvedObjectId }).catch(() => {});
3373
+ }
3374
+ }
3375
+
3376
+ if (!point) {
3377
+ try {
3378
+ point = await this.#boxModel(tabId, node);
3379
+ } catch {
3380
+ await this.#cdp(tabId, "DOM.focus", { backendNodeId: node.backendDOMNodeId });
3381
+ const { object } = await this.#cdp(tabId, "DOM.resolveNode", { backendNodeId: node.backendDOMNodeId });
3382
+ if (!object?.objectId) throw new Error("Browser element could not be resolved for clicking");
3383
+ await this.#cdp(tabId, "Runtime.callFunctionOn", {
3384
+ objectId: object.objectId,
3385
+ functionDeclaration: "function () { this.click(); }",
3386
+ });
3387
+ return;
3388
+ }
3389
+ }
3390
+
3391
+ await this.#clickPoint(tabId, point.x, point.y, { clickCount, button, modifiers });
3392
+ }
3393
+
3394
+ /** @param {number} tabId @param {number} x @param {number} y @param {{clickCount:number, button:string, modifiers?:number}} options */
3395
+ async #clickPoint(tabId, x, y, { clickCount, button, modifiers = 0 }) {
3396
+ const common = { x, y, button, clickCount, modifiers };
3397
+ await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", ...common, button: "none", buttons: 0, clickCount: 0 });
3398
+ await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mousePressed", ...common, buttons: buttonMask(button) });
3399
+ await this.#cdp(tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", ...common, buttons: 0 });
3400
+ }
3401
+
3402
+ /**
3403
+ * Build a classified Error preserving retryability and locator failure code.
3404
+ * @param {{error?:string, code?:string, retryable?:boolean}} result
3405
+ * @param {string} [fallback]
3406
+ */
3407
+ #locatorError(result, fallback = "Browser locator failed") {
3408
+ const err = new Error(String(result?.error || fallback));
3409
+ err.code = result?.code || "error";
3410
+ err.retryable = Boolean(result?.retryable);
3411
+ return err;
3412
+ }
3413
+
3414
+ /**
3415
+ * Retry transient locator failures (not_found, not_visible, disabled, covered) up to `timeoutMs` (default 3000ms).
3416
+ * Fails immediately on structural errors (strict-mode multiple match, invalid locator, readonly).
3417
+ * @param {number} tabId
3418
+ * @param {string} selector
3419
+ * @param {Record<string, any>} [options]
3420
+ */
3421
+ async #runLocatorWithAutoWait(tabId, selector, { timeoutMs, ...options } = {}) {
3422
+ const budget = timeoutMs !== undefined ? Math.max(0, Number(timeoutMs) || 0) : DEFAULT_LOCATOR_TIMEOUT_MS;
3423
+ if (budget === 0) {
3424
+ return await this.#runLocator(tabId, selector, options);
3425
+ }
3426
+ const deadline = Date.now() + budget;
3427
+ while (true) {
3428
+ const rem = deadline - Date.now();
3429
+ const attemptStart = Date.now();
3430
+ try {
3431
+ return await this.#runLocator(tabId, selector, { ...options, inPageWaitMs: Math.min(800, Math.max(1, rem)) });
3432
+ } catch (error) {
3433
+ const msg = error instanceof Error ? error.message : String(error);
3434
+ const contextLost = /Execution context was destroyed|Cannot find context/i.test(msg);
3435
+ if (!error?.retryable && !contextLost) throw error;
3436
+ const left = deadline - Date.now();
3437
+ if (left <= 0) {
3438
+ let hint = "";
3439
+ if (error?.code === "not_found" && !options.frame && this.locatorRuntimeInstalled.has(`${tabId}:main`)) {
3440
+ const cands = await Promise.race([
3441
+ this.#evaluateRaw(tabId, `(() => globalThis.__buRt?.suggestCandidates?.(${JSON.stringify(selector)}, 4) ?? [])()`).catch(() => []),
3442
+ sleep(250).then(() => []),
3443
+ ]);
3444
+ if (Array.isArray(cands) && cands.length > 0) {
3445
+ hint = ` | Closest visible matches: ${cands.join(", ")}`;
3446
+ }
3447
+ }
3448
+ const wrapped = new Error(`Timed out after ${budget}ms waiting for locator: ${msg}${hint}`);
3449
+ wrapped.code = error.code;
3450
+ throw wrapped;
3451
+ }
3452
+ if (Date.now() - attemptStart < 20) {
3453
+ await sleep(Math.min(50, left));
3454
+ }
3455
+ }
3456
+ }
3457
+ }
3458
+
3459
+ /**
3460
+ * Execute a locator expression once in the main frame, same-origin iframe chain, or cross-origin frame session.
3461
+ * @param {number} tabId
3462
+ * @param {string} selector
3463
+ * @param {{frame?:string, crossOriginMutation?:string, crossOriginOptions?:Record<string, any>, mutation?:string, value?:string, select?:unknown, state?:string, inPageWaitMs?:number}} [options]
3464
+ * @returns {Promise<{inCrossOriginFrame:boolean, sessionId?:string, result:any}>}
3465
+ */
3466
+ async #runLocatorOnce(tabId, selector, { frame, crossOriginMutation, crossOriginOptions, ...options } = {}) {
3467
+ if (!frame) {
3468
+ return { inCrossOriginFrame: false, result: await this.#locator(tabId, selector, options) };
3469
+ }
3470
+ const resolved = await this.#resolveFrameRoute(tabId, frame);
3471
+ if (resolved.kind === "same-origin") {
3472
+ return {
3473
+ inCrossOriginFrame: false,
3474
+ result: await this.#locator(tabId, selector, { ...options, sameOriginFrames: resolved.selectors }),
3475
+ };
3476
+ }
3477
+ return {
3478
+ inCrossOriginFrame: true,
3479
+ sessionId: resolved.sessionId,
3480
+ result: await this.#locatorInSession(tabId, resolved.sessionId, selector, {
3481
+ ...options,
3482
+ ...(crossOriginOptions ?? {}),
3483
+ mutation: crossOriginMutation ?? options.mutation,
3484
+ }),
3485
+ };
3486
+ }
3487
+
3488
+ /**
3489
+ * Execute a locator expression, invalidating cached frame routes once on stale frame/session errors.
3490
+ * @param {number} tabId
3491
+ * @param {string} selector
3492
+ * @param {Record<string, any>} [options]
3493
+ * @returns {Promise<{inCrossOriginFrame:boolean, sessionId?:string, result:any}>}
3494
+ */
3495
+ async #runLocator(tabId, selector, options = {}) {
3496
+ const frame = options.frame;
3497
+ if (!frame) return await this.#runLocatorOnce(tabId, selector, options);
3498
+ const hadCache = Boolean(this.frameRouteCache.get(tabId)?.routes?.has(String(frame)));
3499
+ try {
3500
+ return await this.#runLocatorOnce(tabId, selector, options);
3501
+ } catch (error) {
3502
+ if (hadCache) {
3503
+ const msg = error instanceof Error ? error.message : String(error);
3504
+ if (/frame|session|detach|unavailable/iu.test(msg)) {
3505
+ this.frameRouteCache.get(tabId)?.routes?.delete(String(frame));
3506
+ return await this.#runLocatorOnce(tabId, selector, options);
3507
+ }
3508
+ }
3509
+ throw error;
3510
+ }
3511
+ }
3512
+
3513
+ /** @param {number} tabId @param {string|null} sessionId @returns {Promise<boolean>} */
3514
+ async #ensureLocatorRuntime(tabId, sessionId = null) {
3515
+ const cacheKey = `${tabId}:${sessionId ?? "main"}`;
3516
+ if (this.statelessEvalTabs.has(cacheKey)) return false;
3517
+ const rev = sessionId ? 0 : this.#tabState(tabId).navRevision;
3518
+ if (this.locatorRuntimeInstalled.get(cacheKey) === rev) return true;
3519
+ const response = await this.#cdpTarget(tabId, sessionId, "Runtime.evaluate", {
3520
+ expression: locatorRuntimeInstallExpression(),
3521
+ returnByValue: true,
3522
+ awaitPromise: false,
3523
+ userGesture: false,
3524
+ includeCommandLineAPI: false,
3525
+ }).catch(() => null);
3526
+ if (response?.exceptionDetails) {
3527
+ this.statelessEvalTabs.add(cacheKey);
3528
+ return false;
3529
+ }
3530
+ const val = response?.result?.value;
3531
+ if (val && typeof val === "object" && val.installed === true && val.v === LOCATOR_RUNTIME_VERSION) {
3532
+ this.locatorRuntimeInstalled.set(cacheKey, rev);
3533
+ return true;
3534
+ }
3535
+ this.statelessEvalTabs.add(cacheKey);
3536
+ return false;
3537
+ }
3538
+
3539
+ /** @param {number} tabId @param {string|null} sessionId @param {string} selector @param {Record<string, any>} [options] */
3540
+ async #evaluateLocator(tabId, sessionId, selector, options = {}) {
3541
+ const userGesture = ["fill", "clear", "click", "select", "check", "uncheck"].includes(options.mutation);
3542
+ const awaitPromise = Boolean(
3543
+ options.asyncEval ||
3544
+ (options.inPageWaitMs ?? 0) > 0 ||
3545
+ options.mutation === "fill" ||
3546
+ options.mutation === "clear",
3547
+ );
3548
+ const cacheKey = `${tabId}:${sessionId ?? "main"}`;
3549
+ const runExpr = async (expression) => {
3550
+ const response = await this.#cdpTarget(tabId, sessionId, "Runtime.evaluate", {
3551
+ expression,
3552
+ returnByValue: true,
3553
+ awaitPromise,
3554
+ userGesture,
3555
+ includeCommandLineAPI: false,
3556
+ });
3557
+ if (response?.exceptionDetails) {
3558
+ const details = response.exceptionDetails;
3559
+ throw new Error(details.exception?.description || details.text || "Browser locator failed");
3560
+ }
3561
+ return response?.result?.value;
3562
+ };
3563
+
3564
+ let result;
3565
+ if (!this.statelessEvalTabs.has(cacheKey) && await this.#ensureLocatorRuntime(tabId, sessionId)) {
3566
+ result = await runExpr(locatorInvokeExpression(selector, options));
3567
+ if (result && result.__buRtMissing === true) {
3568
+ this.locatorRuntimeInstalled.delete(cacheKey);
3569
+ if (await this.#ensureLocatorRuntime(tabId, sessionId)) {
3570
+ result = await runExpr(locatorInvokeExpression(selector, options));
3571
+ }
3572
+ if (result && result.__buRtMissing === true) {
3573
+ this.statelessEvalTabs.add(cacheKey);
3574
+ result = await runExpr(locatorExpression(selector, options));
3575
+ }
3576
+ }
3577
+ } else {
3578
+ result = await runExpr(locatorExpression(selector, options));
3579
+ }
3580
+ if (result?.error) throw this.#locatorError(result);
3581
+ return result;
3582
+ }
3583
+
3584
+ /** @param {number} tabId @param {string} selector @param {Record<string, any>} [options] */
3585
+ async #locator(tabId, selector, options = {}) {
3586
+ return await this.#evaluateLocator(tabId, null, selector, options);
3587
+ }
3588
+
3589
+ /**
3590
+ * Resolve frame path into either same-origin CSS selector chain or cross-origin CDP sessionId, cached per navRevision.
3591
+ * @param {number} tabId
3592
+ * @param {string} framePath
3593
+ * @returns {Promise<{kind:"same-origin", selectors:string[]}|{kind:"cross-origin", sessionId:string}>}
3594
+ */
3595
+ async #resolveFrameRoute(tabId, framePath) {
3596
+ const normalizedPath = String(framePath);
3597
+ const state = this.#tabState(tabId);
3598
+ let tabCache = this.frameRouteCache.get(tabId);
3599
+ if (!tabCache || tabCache.navRevision !== state.navRevision) {
3600
+ tabCache = { navRevision: state.navRevision, routes: new Map() };
3601
+ this.frameRouteCache.set(tabId, tabCache);
3602
+ }
3603
+ const cached = tabCache.routes.get(normalizedPath);
3604
+ if (cached) {
3605
+ if (cached.kind === "same-origin") return cached;
3606
+ const frameMap = this.frameSessions.get(tabId);
3607
+ if (frameMap) {
3608
+ for (const sId of frameMap.values()) {
3609
+ if (sId === cached.sessionId) return cached;
3610
+ }
3611
+ }
3612
+ tabCache.routes.delete(normalizedPath);
3613
+ }
3614
+
3615
+ const parts = normalizedPath.split(">>").map((part) => part.trim()).filter(Boolean);
3616
+ if (parts.length === 0) throw new Error("A frame selector is required");
3617
+ await this.#ensureAutoAttach(tabId);
3618
+ let sessionId = null;
3619
+ let sameOriginOnly = true;
3620
+ for (const part of parts) {
3621
+ const exec = (method, params) => sessionId
3622
+ ? this.#cdpIn(tabId, sessionId, method, params)
3623
+ : this.#cdp(tabId, method, params);
3624
+ if (sessionId === null) {
3625
+ await this.#ensureDomain(tabId, "DOM", "DOM.enable");
3626
+ } else {
3627
+ await exec("DOM.enable", {});
3628
+ }
3629
+ const document = await exec("DOM.getDocument", { depth: 0 });
3630
+ const { nodeId } = await exec("DOM.querySelector", { nodeId: document.root.nodeId, selector: part });
3631
+ if (!nodeId) throw new Error(`No iframe matched: ${part}`);
3632
+ const described = await exec("DOM.describeNode", { nodeId });
3633
+ if (sameOriginOnly && described?.node?.contentDocument) {
3634
+ continue;
3635
+ }
3636
+ sameOriginOnly = false;
3637
+ const frameId = described?.node?.frameId;
3638
+ if (typeof frameId !== "string") throw new Error(`The element matched by ${part} is not a frame`);
3639
+ sessionId = await this.#waitForFrameSession(tabId, frameId);
3640
+ }
3641
+ const resolved = sameOriginOnly ? { kind: "same-origin", selectors: parts } : { kind: "cross-origin", sessionId };
3642
+ tabCache.routes.set(normalizedPath, resolved);
3643
+ return resolved;
3644
+ }
3645
+
3646
+ /** @param {number} tabId @param {string} frameId @returns {Promise<string>} */
3647
+ async #waitForFrameSession(tabId, frameId) {
3648
+ const deadline = Date.now() + 3_000;
3649
+ while (Date.now() < deadline) {
3650
+ const sessionId = this.frameSessions.get(tabId)?.get(frameId);
3651
+ if (typeof sessionId === "string") return sessionId;
3652
+ await this.#waitForTabWakeup(tabId, Math.min(80, Math.max(1, deadline - Date.now())));
3653
+ }
3654
+ throw new Error("The cross-origin frame session is unavailable; this iframe may be same-process");
3655
+ }
3656
+
3657
+ /** @param {number} tabId @param {string} sessionId @param {string} selector @param {Record<string, any>} [options] */
3658
+ async #locatorInSession(tabId, sessionId, selector, options = {}) {
3659
+ return await this.#evaluateLocator(tabId, sessionId, selector, options);
3660
+ }
3661
+
3662
+ /** @param {number} tabId @param {string} expression @param {{awaitPromise?:boolean, userGesture?:boolean}} [options] */
3663
+ async #evaluateRaw(tabId, expression, { awaitPromise = false, userGesture = false } = {}) {
3664
+ const response = await this.#cdp(tabId, "Runtime.evaluate", {
3665
+ expression,
3666
+ returnByValue: true,
3667
+ awaitPromise,
3668
+ userGesture,
3669
+ includeCommandLineAPI: false,
3670
+ });
3671
+ if (response?.exceptionDetails) {
3672
+ const details = response.exceptionDetails;
3673
+ throw new Error(details.exception?.description || details.text || "Browser evaluation failed");
3674
+ }
3675
+ return response?.result?.value;
3676
+ }
3677
+
3678
+ /**
3679
+ * Event-driven post-action settle: detects triggered navigations and waits briefly for
3680
+ * paint + AX quiet. Automatically a no-op when no event stream is active or a dialog is open.
3681
+ * @param {number} tabId
3682
+ * @param {{expectNavigation?:boolean, timeoutMs?:number}} [options]
3683
+ */
3684
+ async #waitForSettle(tabId, { expectNavigation = false, timeoutMs = DEFAULT_SETTLE_TIMEOUT_MS } = {}) {
3685
+ const state = this.tabStates.get(tabId);
3686
+ if (!state || !state.hasEvents || state.dialog) return;
3687
+
3688
+ const startRev = state.navRevision;
3689
+ if (expectNavigation && !state.loading) {
3690
+ const detectDeadline = Date.now() + 30;
3691
+ while (Date.now() < detectDeadline) {
3692
+ if (state.dialog || state.loading || state.navRevision !== startRev) break;
3693
+ await this.#waitForTabWakeup(tabId, Math.max(1, detectDeadline - Date.now()));
3694
+ }
3695
+ }
3696
+
3697
+ const navTriggered = state.loading || state.navRevision !== startRev;
3698
+ const effectiveWaitMs = navTriggered ? timeoutMs : Math.min(timeoutMs, 150);
3699
+ const deadline = Date.now() + effectiveWaitMs;
3700
+ while (state.loading && !state.dialog && Date.now() < deadline) {
3701
+ await this.#waitForTabWakeup(tabId, Math.min(35, Math.max(1, deadline - Date.now())));
3702
+ }
3703
+
3704
+ // Wait briefly for AX updates to settle (60ms quiet window).
3705
+ const quietCap = navTriggered ? 250 : 100;
3706
+ const quietDeadline = Math.min(deadline, Date.now() + quietCap);
3707
+ while (!state.dialog && Date.now() < quietDeadline) {
3708
+ const sinceAx = Date.now() - Math.max(state.lastAxUpdateMs, 0);
3709
+ if (state.lastAxUpdateMs === 0 || sinceAx >= 60) break;
3710
+ await this.#waitForTabWakeup(tabId, Math.min(60 - sinceAx, Math.max(1, quietDeadline - Date.now())));
3711
+ }
3712
+ }
3713
+
3714
+ /** @param {number} tabId @param {string} target @param {number} [timeoutMs] */
3715
+ async #waitForCommit(tabId, target, timeoutMs = DEFAULT_LOAD_TIMEOUT_MS) {
3716
+ const deadline = Date.now() + timeoutMs;
3717
+ const state = this.#tabState(tabId);
3718
+ let lastEvalAt = state.hasEvents ? Date.now() : 0;
3719
+ while (Date.now() < deadline) {
3720
+ if (state.committed && state.url && state.url !== "about:blank" && sameUrl(state.url, target)) return;
3721
+ const now = Date.now();
3722
+ if (!state.hasEvents || (!state.committed && now - lastEvalAt >= 400)) {
3723
+ lastEvalAt = now;
3724
+ const current = await this.#evaluateRaw(tabId, "location.href").catch(() => null);
3725
+ if (typeof current === "string" && current !== "about:blank" && sameUrl(current, target)) return;
3726
+ }
3727
+ await this.#waitForTabWakeup(tabId, Math.min(state.hasEvents ? 200 : 80, Math.max(1, deadline - Date.now())));
3728
+ }
3729
+ throw new Error(`Browser navigation did not commit to ${target} within ${timeoutMs}ms`);
3730
+ }
3731
+
3732
+ /** @param {number} tabId @param {string} target */
3733
+ async #navigateWithCdp(tabId, target) {
3734
+ const navigation = await this.#cdp(tabId, "Page.navigate", { url: target });
3735
+ if (navigation && typeof navigation === "object" && navigation.errorText) {
3736
+ let current = null;
3737
+ for (let attempt = 0; attempt < 20; attempt++) {
3738
+ current = await this.#evaluateRaw(tabId, "location.href").catch(() => null);
3739
+ if (typeof current === "string" && current !== "about:blank") break;
3740
+ await sleep(100);
3741
+ }
3742
+ const committed = typeof current === "string" && current !== "about:blank" &&
3743
+ (current === target || current.startsWith("data:"));
3744
+ if (!committed) throw new Error(`Browser navigation failed: ${navigation.errorText}`);
3745
+ }
3746
+ }
3747
+
3748
+ /** @param {number} tabId @param {{waitUntil?:string, timeoutMs?:number}} [options] */
3749
+ async #waitForLoad(tabId, { waitUntil = "load", timeoutMs = DEFAULT_LOAD_TIMEOUT_MS } = {}) {
3750
+ const deadline = Date.now() + timeoutMs;
3751
+ const state = this.#tabState(tabId);
3752
+ let quietStart = null;
3753
+ let lastEvalAt = state.hasEvents ? Date.now() : 0;
3754
+ while (Date.now() < deadline) {
3755
+ if (state.dialog) return;
3756
+ let ready = null;
3757
+ if (state.hasEvents) {
3758
+ if (state.loaded) ready = "complete";
3759
+ else if (state.domContentLoaded) ready = "interactive";
3760
+ }
3761
+ const now = Date.now();
3762
+ if (ready === null && (!state.hasEvents || now - lastEvalAt >= 500)) {
3763
+ try {
3764
+ lastEvalAt = now;
3765
+ ready = await this.#evaluateRaw(tabId, "document.readyState");
3766
+ } catch {
3767
+ // The navigation may have replaced the execution context; retry.
3768
+ }
3769
+ }
3770
+ if (waitUntil === "domcontentloaded" && (ready === "interactive" || ready === "complete")) return;
3771
+ if (waitUntil === "load" && ready === "complete") return;
3772
+ if (waitUntil === "networkidle" && ready === "complete") {
3773
+ const inFlight = state.inFlightRequests.size;
3774
+ if (inFlight === 0) {
3775
+ quietStart ??= Date.now();
3776
+ const remainingQuiet = 350 - (Date.now() - quietStart);
3777
+ if (remainingQuiet <= 0) return;
3778
+ await this.#waitForTabWakeup(tabId, Math.min(remainingQuiet, Math.max(1, deadline - Date.now())));
3779
+ continue;
3780
+ }
3781
+ quietStart = null;
3782
+ }
3783
+ await this.#waitForTabWakeup(tabId, Math.min(state.hasEvents ? 250 : 80, Math.max(1, deadline - Date.now())));
3784
+ }
3785
+ throw new Error(`Browser navigation did not reach ${waitUntil} within ${timeoutMs}ms`);
3786
+ }
3787
+ }