codex-browser-use 0.0.0-stage → 4.8.1

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,1546 @@
1
+ import vm from "node:vm";
2
+ import { mkdir, readFile as fsReadFile, writeFile as fsWriteFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { URL, URLSearchParams } from "node:url";
5
+ import { parse } from "acorn";
6
+
7
+ const RESERVED_PARAM_NAMES = new Set([
8
+ "browser", "page", "log", "sleep", "viewImage",
9
+ "saveFile", "readFile", "saveScreenshot", "nodeRepl", "console", "__scope",
10
+ ]);
11
+ const MAX_SCRIPT_WRITE_BYTES = 25 * 1024 * 1024;
12
+ const MAX_SCRIPT_READ_BYTES = 10 * 1024 * 1024;
13
+ const DEFAULT_SCRIPT_READ_BYTES = 2 * 1024 * 1024;
14
+ const IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
15
+
16
+ /**
17
+ * Determine whether a target string is a selector/locator rather than a numeric
18
+ * accessibility element_index (or comma-separated index chain).
19
+ * @param {unknown} target
20
+ * @returns {boolean}
21
+ */
22
+ function isLocatorLike(target) {
23
+ if (typeof target !== "string") return false;
24
+ return !/^\s*\d+(?:\s*,\s*\d+)*\s*$/u.test(target);
25
+ }
26
+
27
+ /** @param {unknown} arg @returns {string} */
28
+ function formatLogArg(arg) {
29
+ if (typeof arg === "string") return arg;
30
+ if (arg instanceof Error) return arg.message;
31
+ try {
32
+ return JSON.stringify(arg);
33
+ } catch {
34
+ return String(arg);
35
+ }
36
+ }
37
+
38
+ /** @param {unknown} value @param {number} maxChars @returns {unknown} */
39
+ function boundResult(value, maxChars) {
40
+ if (value === undefined) return undefined;
41
+ let encoded;
42
+ try {
43
+ encoded = JSON.stringify(value);
44
+ } catch {
45
+ return String(value).slice(0, maxChars);
46
+ }
47
+ if (encoded === undefined) return undefined;
48
+ if (encoded.length <= maxChars) return JSON.parse(encoded);
49
+ return `${encoded.slice(0, maxChars)}\n...(truncated)`;
50
+ }
51
+
52
+ /** @param {any} pattern @param {Set<string>} out */
53
+ function collectDeclaredIdentifiers(pattern, out) {
54
+ if (!pattern || typeof pattern !== "object") return;
55
+ switch (pattern.type) {
56
+ case "Identifier":
57
+ out.add(pattern.name);
58
+ break;
59
+ case "ObjectPattern":
60
+ for (const prop of pattern.properties ?? []) {
61
+ collectDeclaredIdentifiers(prop?.type === "Property" ? prop.value : prop, out);
62
+ }
63
+ break;
64
+ case "ArrayPattern":
65
+ for (const elem of pattern.elements ?? []) {
66
+ if (elem) collectDeclaredIdentifiers(elem, out);
67
+ }
68
+ break;
69
+ case "RestElement":
70
+ collectDeclaredIdentifiers(pattern.argument, out);
71
+ break;
72
+ case "AssignmentPattern":
73
+ collectDeclaredIdentifiers(pattern.left, out);
74
+ break;
75
+ default:
76
+ break;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Rewrite top-level `const`/`let`/`class` declarations to `var` so bindings persist
82
+ * across `browser_run` calls and can be redeclared safely across turns.
83
+ * @param {string} code
84
+ * @returns {{transformed:string, declaredNames:string[]}}
85
+ */
86
+ export function transformPersistentCode(code) {
87
+ const source = String(code ?? "");
88
+ const tree = parse(source, {
89
+ ecmaVersion: "latest",
90
+ sourceType: "script",
91
+ allowAwaitOutsideFunction: true,
92
+ allowReturnOutsideFunction: true,
93
+ });
94
+ const names = new Set();
95
+ /** @type {Array<{start:number, end:number, replacement:string}>} */
96
+ const edits = [];
97
+
98
+ for (const stmt of tree.body) {
99
+ if (stmt.type === "VariableDeclaration") {
100
+ if (stmt.kind !== "var") {
101
+ edits.push({ start: stmt.start, end: stmt.start + stmt.kind.length, replacement: "var" });
102
+ }
103
+ for (const decl of stmt.declarations ?? []) collectDeclaredIdentifiers(decl.id, names);
104
+ } else if (stmt.type === "FunctionDeclaration" && stmt.id?.name) {
105
+ names.add(stmt.id.name);
106
+ } else if (stmt.type === "ClassDeclaration" && stmt.id?.name) {
107
+ names.add(stmt.id.name);
108
+ edits.push({ start: stmt.start, end: stmt.start, replacement: `var ${stmt.id.name} = ` });
109
+ }
110
+ }
111
+
112
+ let transformed = source;
113
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
114
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
115
+ }
116
+ const declaredNames = [...names].filter((n) => IDENTIFIER_RE.test(n) && !RESERVED_PARAM_NAMES.has(n));
117
+ return { transformed, declaredNames };
118
+ }
119
+
120
+ /** @param {string} role @param {{name?:string|RegExp, exact?:boolean}} [opts] @returns {string} */
121
+ function buildRoleStep(role, opts = {}) {
122
+ let step = `role=${String(role)}`;
123
+ if (opts?.name instanceof RegExp) {
124
+ step += `[name=/${opts.name.source}/${opts.name.flags}]`;
125
+ } else if (opts?.name !== undefined) {
126
+ step += `[name=${JSON.stringify(String(opts.name))}][exact=${opts.exact ? "true" : "false"}]`;
127
+ }
128
+ return step;
129
+ }
130
+
131
+ /** @param {string|RegExp} text @param {{exact?:boolean}} [opts] @returns {string} */
132
+ function buildTextStep(text, opts = {}) {
133
+ if (text instanceof RegExp) return `text=/${text.source}/${text.flags}`;
134
+ const str = String(text);
135
+ return opts?.exact ? `text=${JSON.stringify(str)}` : `text=${str}`;
136
+ }
137
+
138
+ /** @param {unknown} value @returns {boolean} */
139
+ function isPlainObject(value) {
140
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
141
+ }
142
+
143
+ /** @param {unknown} obj @param {Set<string>} allowedKeys @returns {boolean} */
144
+ function hasOnlyKeys(obj, allowedKeys) {
145
+ if (!isPlainObject(obj)) return false;
146
+ const keys = Object.keys(obj);
147
+ return keys.length > 0 && keys.every((k) => allowedKeys.has(k));
148
+ }
149
+
150
+ const PAGE_EVAL_OPT_KEYS = new Set(["tabId", "tab_id", "timeoutMs", "timeout_ms"]);
151
+ const LOCATOR_EVAL_OPT_KEYS = new Set(["tabId", "tab_id", "frame", "timeoutMs", "timeout_ms"]);
152
+
153
+ /**
154
+ * Persistent VM session for `browser_run`, retaining top-level bindings and active tab
155
+ * state across turns while isolating host globals and enforcing read-only page evaluation.
156
+ */
157
+ export class BrowserScriptSession {
158
+ constructor() {
159
+ this.reset();
160
+ }
161
+
162
+ reset() {
163
+ this.scope = Object.create(null);
164
+ this.currentTabId = null;
165
+ this.activeRun = null;
166
+ this.context = vm.createContext(
167
+ { URL, URLSearchParams, setTimeout, clearTimeout },
168
+ { codeGeneration: { strings: false, wasm: false } },
169
+ );
170
+ }
171
+
172
+ /** @param {import("./bridge-browser.js").BridgeBrowser} browser */
173
+ syncActiveTab(browser) {
174
+ if (this.currentTabId != null) {
175
+ const num = Number(this.currentTabId);
176
+ if (!Number.isSafeInteger(num) || !browser?.ownedTabs?.has(num)) {
177
+ this.currentTabId = browser?.activeTabId != null && browser?.ownedTabs?.has(browser.activeTabId)
178
+ ? String(browser.activeTabId)
179
+ : null;
180
+ }
181
+ }
182
+ if (this.currentTabId === null && browser?.activeTabId != null && browser?.ownedTabs?.has(browser.activeTabId)) {
183
+ this.currentTabId = String(browser.activeTabId);
184
+ }
185
+ }
186
+
187
+ #timeoutMessage(run) {
188
+ const during = run?.lastAction ? ` (during ${run.lastAction})` : "";
189
+ return `browser_run timed out after ${run?.timeoutMs ?? 45_000}ms${during}`;
190
+ }
191
+
192
+ #requireRun() {
193
+ const run = this.activeRun;
194
+ if (!run || run.aborted || run.deadline - Date.now() <= 0) {
195
+ if (run) run.aborted = true;
196
+ throw new Error(this.#timeoutMessage(run));
197
+ }
198
+ return run;
199
+ }
200
+
201
+ #remainingMs() {
202
+ const run = this.activeRun;
203
+ return run ? Math.max(0, run.deadline - Date.now()) : 0;
204
+ }
205
+
206
+ #clampTimeout(requested) {
207
+ const rem = this.#remainingMs();
208
+ if (rem <= 0) return 100;
209
+ if (requested === 0) return 0;
210
+ return Math.min(rem, Math.max(100, Number(requested) || rem));
211
+ }
212
+
213
+ #resolveTabArg(opts, fixedTabId = null) {
214
+ if (opts && typeof opts === "object") {
215
+ const explicit = opts.tabId ?? opts.tab_id;
216
+ if (explicit !== undefined && explicit !== null && explicit !== "") return explicit;
217
+ }
218
+ if (fixedTabId !== null && fixedTabId !== undefined && fixedTabId !== "") return fixedTabId;
219
+ return this.currentTabId ?? undefined;
220
+ }
221
+
222
+ #activeTabId() {
223
+ const browser = this.activeRun?.browser;
224
+ return this.currentTabId ?? (browser?.activeTabId != null ? String(browser.activeTabId) : null);
225
+ }
226
+
227
+ async #guard(fn, label = null, { trackActiveTab = true } = {}) {
228
+ const run = this.#requireRun();
229
+ if (label) run.lastAction = label;
230
+ const res = await fn(run.browser);
231
+ if (run.aborted || run !== this.activeRun) {
232
+ throw new Error(this.#timeoutMessage(run));
233
+ }
234
+ if (res && typeof res === "object" && res.tab_id != null) {
235
+ const tid = String(res.tab_id);
236
+ run.touchedTabs.add(tid);
237
+ if (trackActiveTab) this.currentTabId = tid;
238
+ } else if (trackActiveTab && run.browser.activeTabId != null && this.currentTabId === null) {
239
+ this.currentTabId = String(run.browser.activeTabId);
240
+ }
241
+ return res;
242
+ }
243
+
244
+ #log(...args) {
245
+ const run = this.activeRun;
246
+ if (!run || run.logChars >= run.maxLogChars) return;
247
+ const line = args.map(formatLogArg).join(" ");
248
+ const remaining = run.maxLogChars - run.logChars;
249
+ const clipped = line.length > remaining ? `${line.slice(0, remaining)}...(truncated)` : line;
250
+ run.logs.push(clipped);
251
+ run.logChars += clipped.length;
252
+ }
253
+
254
+ #sleep(ms) {
255
+ const run = this.#requireRun();
256
+ return new Promise((resolve, reject) => {
257
+ const waitMs = Math.max(0, Number(ms) || 0);
258
+ const timer = setTimeout(() => {
259
+ run.activeTimers.delete(timer);
260
+ if (run.aborted) reject(new Error(this.#timeoutMessage(run)));
261
+ else resolve();
262
+ }, waitMs);
263
+ run.activeTimers.add(timer);
264
+ });
265
+ }
266
+
267
+ async #viewImage(captureOrOpts, fixedTabId = null) {
268
+ const run = this.#requireRun();
269
+ if (run.images.length >= run.maxImages) {
270
+ throw new Error(`Maximum ${run.maxImages} images per browser_run call exceeded`);
271
+ }
272
+ if (captureOrOpts && typeof captureOrOpts === "object" && typeof captureOrOpts.data === "string") {
273
+ run.images.push({
274
+ data: captureOrOpts.data,
275
+ mimeType: captureOrOpts.mimeType || "image/jpeg",
276
+ });
277
+ return { captured: true, count: run.images.length };
278
+ }
279
+ const opts = (captureOrOpts && typeof captureOrOpts === "object") ? captureOrOpts : {};
280
+ const cap = await this.#guard(
281
+ (b) => b.screenshot(this.#resolveTabArg(opts, fixedTabId), {
282
+ fullPage: opts.fullPage ?? opts.full_page ?? false,
283
+ format: opts.format ?? "jpeg",
284
+ quality: opts.quality ?? 80,
285
+ }),
286
+ "screenshot",
287
+ { trackActiveTab: fixedTabId === null },
288
+ );
289
+ run.images.push({ data: cap.data, mimeType: cap.mimeType });
290
+ return { captured: true, count: run.images.length };
291
+ }
292
+
293
+ /** @param {unknown} filePath @param {string} fnName @returns {string} */
294
+ #assertAbsolutePath(filePath, fnName) {
295
+ if (typeof filePath !== "string" || filePath.length === 0 || filePath.includes("\0") || !path.isAbsolute(filePath)) {
296
+ throw new Error(`${fnName} requires a non-empty absolute file path`);
297
+ }
298
+ return filePath;
299
+ }
300
+
301
+ /** @param {string} filePath @param {unknown} data */
302
+ async #saveFile(filePath, data) {
303
+ const run = this.#requireRun();
304
+ const target = this.#assertAbsolutePath(filePath, "saveFile");
305
+ const payload = Buffer.isBuffer(data)
306
+ ? data
307
+ : Buffer.from(typeof data === "string" ? data : `${JSON.stringify(data, null, 2)}\n`, "utf8");
308
+ if (payload.byteLength > MAX_SCRIPT_WRITE_BYTES) {
309
+ throw new Error(`saveFile payload exceeds ${MAX_SCRIPT_WRITE_BYTES} bytes limit`);
310
+ }
311
+ await mkdir(path.dirname(target), { recursive: true });
312
+ await fsWriteFile(target, payload);
313
+ run.savedFiles.set(target, { path: target, bytes: payload.byteLength, kind: "file" });
314
+ return { path: target, bytes: payload.byteLength };
315
+ }
316
+
317
+ /** @param {string} filePath @param {{encoding?:"utf8"|"base64", maxBytes?:number}} [opts] */
318
+ async #readFile(filePath, opts = {}) {
319
+ this.#requireRun();
320
+ const target = this.#assertAbsolutePath(filePath, "readFile");
321
+ const maxBytes = Math.max(1, Math.min(MAX_SCRIPT_READ_BYTES, Number(opts?.maxBytes ?? DEFAULT_SCRIPT_READ_BYTES)));
322
+ const raw = await fsReadFile(target);
323
+ const sliced = raw.subarray(0, maxBytes);
324
+ return opts?.encoding === "base64" ? sliced.toString("base64") : sliced.toString("utf8");
325
+ }
326
+
327
+ /** @param {string} filePath @param {Record<string, any>} [opts] @param {string|null} [fixedTabId] */
328
+ async #saveScreenshot(filePath, opts = {}, fixedTabId = null) {
329
+ const run = this.#requireRun();
330
+ const target = this.#assertAbsolutePath(filePath, "saveScreenshot");
331
+ const ext = path.extname(target).toLowerCase();
332
+ const format = opts.format ?? (ext === ".png" ? "png" : "jpeg");
333
+ const tabId = this.#resolveTabArg(opts, fixedTabId);
334
+ const cap = opts.selector
335
+ ? await this.#guard((b) => b.elementScreenshot(opts.selector, {
336
+ tabId,
337
+ frame: opts.frame,
338
+ force: opts.force === true,
339
+ padding: opts.padding,
340
+ format,
341
+ quality: opts.quality ?? 75,
342
+ scale: opts.scale ?? "css",
343
+ timeoutMs: opts.timeoutMs !== undefined || opts.timeout_ms !== undefined
344
+ ? this.#clampTimeout(opts.timeoutMs ?? opts.timeout_ms)
345
+ : undefined,
346
+ }), `saveScreenshot(${opts.selector})`, { trackActiveTab: fixedTabId === null })
347
+ : await this.#guard((b) => b.screenshot(tabId, {
348
+ fullPage: opts.fullPage ?? opts.full_page ?? false,
349
+ format,
350
+ quality: opts.quality ?? 75,
351
+ ...(opts.maxWidth !== undefined || opts.max_width !== undefined
352
+ ? { maxWidth: opts.maxWidth ?? opts.max_width }
353
+ : {}),
354
+ clip: opts.clip,
355
+ scale: opts.scale ?? "css",
356
+ }), "saveScreenshot", { trackActiveTab: fixedTabId === null });
357
+ const buf = Buffer.from(cap.data, "base64");
358
+ await mkdir(path.dirname(target), { recursive: true });
359
+ await fsWriteFile(target, buf);
360
+ run.savedFiles.set(target, { path: target, bytes: buf.byteLength, kind: "screenshot", mimeType: cap.mimeType });
361
+ if (opts.emit === true) {
362
+ if (run.images.length >= run.maxImages) {
363
+ throw new Error(`Maximum ${run.maxImages} images per browser_run call exceeded`);
364
+ }
365
+ run.images.push({ data: cap.data, mimeType: cap.mimeType });
366
+ }
367
+ return { path: target, bytes: buf.byteLength, mimeType: cap.mimeType, tab_id: cap.tab_id };
368
+ }
369
+
370
+ #keepTab(mode = "deliverable", idOrOpts, maybeOpts) {
371
+ const run = this.#requireRun();
372
+ let id = idOrOpts;
373
+ let opts = maybeOpts;
374
+ if (isPlainObject(idOrOpts)) {
375
+ opts = idOrOpts;
376
+ id = idOrOpts.tabId ?? idOrOpts.tab_id;
377
+ }
378
+ const resolved = id !== undefined && id !== null && id !== ""
379
+ ? String(id)
380
+ : this.#activeTabId();
381
+ if (!resolved) {
382
+ throw new Error("No browser tab is active to keep; navigate or open a tab first");
383
+ }
384
+ const normalized = mode === "handoff" ? "handoff" : "deliverable";
385
+ const focus = opts?.focus === true;
386
+ const prev = run.keptTabs.get(resolved);
387
+ const effectiveFocus = focus || (opts?.focus === undefined && prev?.focus === true);
388
+ run.keptTabs.set(resolved, { mode: normalized, ...(effectiveFocus ? { focus: true } : {}) });
389
+ return { tab_id: resolved, mode: normalized, ...(effectiveFocus ? { focus: true } : {}) };
390
+ }
391
+
392
+ #requestEndTurn(optsOrMode, fixedTabId = null) {
393
+ const run = this.#requireRun();
394
+ run.endTurnRequested = true;
395
+ if (isPlainObject(optsOrMode) && optsOrMode.ungroup === true) {
396
+ run.ungroupOnEndTurn = true;
397
+ }
398
+ const targetKeep = (optsOrMode && typeof optsOrMode === "object" && !Array.isArray(optsOrMode))
399
+ ? optsOrMode.keep
400
+ : optsOrMode;
401
+ if (typeof targetKeep === "string") {
402
+ this.#keepTab(targetKeep, fixedTabId, isPlainObject(optsOrMode) ? { focus: optsOrMode.focus } : undefined);
403
+ } else if (Array.isArray(targetKeep)) {
404
+ for (const entry of targetKeep) {
405
+ if (entry && typeof entry === "object" && entry.tab_id != null) {
406
+ this.#keepTab(entry.mode ?? "deliverable", entry.tab_id, { focus: entry.focus });
407
+ } else if (typeof entry === "string" || typeof entry === "number") {
408
+ this.#keepTab("deliverable", entry);
409
+ }
410
+ }
411
+ }
412
+ return {
413
+ scheduled: true,
414
+ keep: [...run.keptTabs.entries()].map(([tab_id, cfg]) => ({
415
+ tab_id,
416
+ mode: cfg.mode,
417
+ ...(cfg.focus === true ? { focus: true } : {}),
418
+ })),
419
+ };
420
+ }
421
+
422
+ #parseLocatorEvalArgs(fnOrExpr, argOrOpts, maybeOpts, extraLen) {
423
+ if (extraLen >= 3) {
424
+ return { arg: argOrOpts, hasArg: true, opts: isPlainObject(maybeOpts) ? maybeOpts : {} };
425
+ }
426
+ if (extraLen === 2) {
427
+ if (typeof fnOrExpr === "function" && fnOrExpr.length >= 2) {
428
+ return { arg: argOrOpts, hasArg: true, opts: {} };
429
+ }
430
+ if (hasOnlyKeys(argOrOpts, LOCATOR_EVAL_OPT_KEYS)) {
431
+ return { arg: undefined, hasArg: false, opts: argOrOpts };
432
+ }
433
+ return { arg: argOrOpts, hasArg: true, opts: {} };
434
+ }
435
+ return { arg: undefined, hasArg: false, opts: {} };
436
+ }
437
+
438
+ #parsePageEvalArgs(exprOrFn, argOrOpts, maybeOpts, extraLen) {
439
+ if (extraLen >= 3) {
440
+ return { arg: argOrOpts, hasArg: true, opts: isPlainObject(maybeOpts) ? maybeOpts : {} };
441
+ }
442
+ if (extraLen === 2) {
443
+ if (typeof exprOrFn === "function" && exprOrFn.length >= 1) {
444
+ return { arg: argOrOpts, hasArg: true, opts: {} };
445
+ }
446
+ if (hasOnlyKeys(argOrOpts, PAGE_EVAL_OPT_KEYS)) {
447
+ return { arg: undefined, hasArg: false, opts: argOrOpts };
448
+ }
449
+ return { arg: argOrOpts, hasArg: true, opts: {} };
450
+ }
451
+ return { arg: undefined, hasArg: false, opts: {} };
452
+ }
453
+
454
+ #createLocator(chain, frame = null, boundTabId = null) {
455
+ const selector = chain.filter(Boolean).join(" >> ");
456
+ const tabFor = (opts) => this.#resolveTabArg(opts, boundTabId);
457
+ const guardOpts = { trackActiveTab: boundTabId === null };
458
+ const timeoutOpt = (opts) => (
459
+ opts?.timeoutMs !== undefined || opts?.timeout_ms !== undefined
460
+ ? this.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms)
461
+ : undefined
462
+ );
463
+
464
+ const self = {
465
+ selector,
466
+ frame,
467
+ tabId: boundTabId,
468
+ locator: (sub, opts) => {
469
+ const loc = this.#createLocator([...chain, String(sub)], frame, boundTabId);
470
+ return isPlainObject(opts) ? loc.filter(opts) : loc;
471
+ },
472
+ getByRole: (role, opts) => this.#createLocator([...chain, buildRoleStep(role, opts)], frame, boundTabId),
473
+ getByText: (text, opts) => this.#createLocator([...chain, buildTextStep(text, opts)], frame, boundTabId),
474
+ getByLabel: (text) => this.#createLocator([...chain, `label=${JSON.stringify(String(text))}`], frame, boundTabId),
475
+ getByPlaceholder: (text) => this.#createLocator([...chain, `placeholder=${JSON.stringify(String(text))}`], frame, boundTabId),
476
+ getByTestId: (id) => this.#createLocator([...chain, `testid=${JSON.stringify(String(id))}`], frame, boundTabId),
477
+ filter: ({ visible, hasText, hasNotText, has, hasNot } = {}) => {
478
+ const steps = [];
479
+ if (visible === true) steps.push("visible=true");
480
+ else if (visible === false) steps.push("visible=false");
481
+ if (hasText instanceof RegExp) steps.push(`has-text=/${hasText.source}/${hasText.flags}`);
482
+ else if (hasText !== undefined) steps.push(`has-text=${JSON.stringify(String(hasText))}`);
483
+ if (hasNotText instanceof RegExp) steps.push(`has-not-text=/${hasNotText.source}/${hasNotText.flags}`);
484
+ else if (hasNotText !== undefined) steps.push(`has-not-text=${JSON.stringify(String(hasNotText))}`);
485
+ if (has) steps.push(`has=(${has?.selector ?? String(has)})`);
486
+ if (hasNot) steps.push(`has-not=(${hasNot?.selector ?? String(hasNot)})`);
487
+ return this.#createLocator([...chain, ...steps], frame, boundTabId);
488
+ },
489
+ and: (other) => this.#createLocator([...chain, `and=(${other?.selector ?? String(other)})`], frame, boundTabId),
490
+ or: (other) => this.#createLocator([...chain, `or=(${other?.selector ?? String(other)})`], frame, boundTabId),
491
+ first: () => this.#createLocator([...chain, "first"], frame, boundTabId),
492
+ last: () => this.#createLocator([...chain, "last"], frame, boundTabId),
493
+ nth: (idx) => this.#createLocator([...chain, `nth=${Number(idx)}`], frame, boundTabId),
494
+ inFrame: (frameSel) => this.#createLocator(chain, frame ? `${frame} >> ${frameSel}` : String(frameSel), boundTabId),
495
+ click: (opts = {}) => this.#guard((b) => b.locatorClick(selector, {
496
+ tabId: tabFor(opts),
497
+ frame: opts?.frame ?? frame ?? undefined,
498
+ clickCount: opts?.clickCount ?? opts?.click_count ?? 1,
499
+ button: opts?.button ?? opts?.mouse_button ?? "left",
500
+ modifiers: opts?.modifiers,
501
+ force: opts?.force === true,
502
+ timeoutMs: timeoutOpt(opts),
503
+ settle: opts?.settle ?? true,
504
+ }), `locator.click(${selector})`, guardOpts),
505
+ dblclick: (opts = {}) => self.click({ ...opts, clickCount: 2 }),
506
+ fill: (value, opts = {}) => this.#guard((b) => b.locatorFill(selector, String(value), {
507
+ tabId: tabFor(opts),
508
+ frame: opts?.frame ?? frame ?? undefined,
509
+ force: opts?.force === true,
510
+ timeoutMs: timeoutOpt(opts),
511
+ settle: opts?.settle ?? true,
512
+ }), `locator.fill(${selector})`, guardOpts),
513
+ clear: (opts = {}) => this.#guard((b) => b.locatorClear(selector, {
514
+ tabId: tabFor(opts),
515
+ frame: opts?.frame ?? frame ?? undefined,
516
+ force: opts?.force === true,
517
+ timeoutMs: timeoutOpt(opts),
518
+ settle: opts?.settle ?? true,
519
+ }), `locator.clear(${selector})`, guardOpts),
520
+ press: (key, opts = {}) => this.#guard((b) => b.locatorPress(selector, String(key), {
521
+ tabId: tabFor(opts),
522
+ frame: opts?.frame ?? frame ?? undefined,
523
+ force: opts?.force === true,
524
+ timeoutMs: timeoutOpt(opts),
525
+ settle: opts?.settle ?? true,
526
+ }), `locator.press(${selector})`, guardOpts),
527
+ type: (text, opts = {}) => this.#guard((b) => b.locatorType(selector, String(text), {
528
+ tabId: tabFor(opts),
529
+ frame: opts?.frame ?? frame ?? undefined,
530
+ force: opts?.force === true,
531
+ timeoutMs: timeoutOpt(opts),
532
+ sequentially: false,
533
+ settle: opts?.settle ?? true,
534
+ }), `locator.type(${selector})`, guardOpts),
535
+ pressSequentially: (text, opts = {}) => this.#guard((b) => b.locatorType(selector, String(text), {
536
+ tabId: tabFor(opts),
537
+ frame: opts?.frame ?? frame ?? undefined,
538
+ force: opts?.force === true,
539
+ timeoutMs: timeoutOpt(opts),
540
+ sequentially: true,
541
+ delayMs: opts?.delay ?? opts?.delayMs ?? 0,
542
+ settle: opts?.settle ?? true,
543
+ }), `locator.pressSequentially(${selector})`, guardOpts),
544
+ check: (opts = {}) => this.#guard((b) => b.locatorCheck(selector, true, {
545
+ tabId: tabFor(opts),
546
+ frame: opts?.frame ?? frame ?? undefined,
547
+ force: opts?.force === true,
548
+ timeoutMs: timeoutOpt(opts),
549
+ settle: opts?.settle ?? true,
550
+ }), `locator.check(${selector})`, guardOpts),
551
+ uncheck: (opts = {}) => this.#guard((b) => b.locatorCheck(selector, false, {
552
+ tabId: tabFor(opts),
553
+ frame: opts?.frame ?? frame ?? undefined,
554
+ force: opts?.force === true,
555
+ timeoutMs: timeoutOpt(opts),
556
+ settle: opts?.settle ?? true,
557
+ }), `locator.uncheck(${selector})`, guardOpts),
558
+ setChecked: (checked, opts = {}) => (checked ? self.check(opts) : self.uncheck(opts)),
559
+ selectOption: (spec, opts = {}) => {
560
+ const payload = (spec && typeof spec === "object" && !Array.isArray(spec))
561
+ ? { ...spec, ...opts }
562
+ : { value: spec, ...opts };
563
+ return this.#guard((b) => b.selectOption({
564
+ tabId: tabFor(payload),
565
+ selector,
566
+ frame: payload.frame ?? frame ?? undefined,
567
+ value: payload.value,
568
+ label: payload.label,
569
+ index: payload.index,
570
+ force: payload.force === true,
571
+ timeoutMs: timeoutOpt(payload),
572
+ }), `locator.selectOption(${selector})`, guardOpts);
573
+ },
574
+ hover: (opts = {}) => this.#guard((b) => b.hover({
575
+ tabId: tabFor(opts),
576
+ selector,
577
+ frame: opts?.frame ?? frame ?? undefined,
578
+ force: opts?.force === true,
579
+ timeoutMs: timeoutOpt(opts),
580
+ }), `locator.hover(${selector})`, guardOpts),
581
+ screenshot: (opts = {}) => {
582
+ const format = opts?.format ?? opts?.type ?? "jpeg";
583
+ if (typeof opts?.path === "string" && opts.path.length > 0) {
584
+ return this.#saveScreenshot(opts.path, {
585
+ ...opts,
586
+ format,
587
+ selector,
588
+ frame: opts?.frame ?? frame ?? undefined,
589
+ }, boundTabId);
590
+ }
591
+ return this.#guard((b) => b.elementScreenshot(selector, {
592
+ tabId: tabFor(opts),
593
+ frame: opts?.frame ?? frame ?? undefined,
594
+ force: opts?.force === true,
595
+ padding: opts?.padding,
596
+ format,
597
+ quality: opts?.quality ?? 75,
598
+ scale: opts?.scale ?? "css",
599
+ timeoutMs: timeoutOpt(opts),
600
+ }), `locator.screenshot(${selector})`, guardOpts);
601
+ },
602
+ saveScreenshot: (filePath, opts = {}) => this.#saveScreenshot(filePath, {
603
+ ...opts,
604
+ selector,
605
+ frame: opts?.frame ?? frame ?? undefined,
606
+ }, boundTabId),
607
+ scrollIntoViewIfNeeded: (opts = {}) => this.#guard((b) => b.locatorScrollIntoView(selector, {
608
+ tabId: tabFor(opts),
609
+ frame: opts?.frame ?? frame ?? undefined,
610
+ timeoutMs: timeoutOpt(opts),
611
+ }), `locator.scrollIntoViewIfNeeded(${selector})`, guardOpts),
612
+ setInputFiles: (files, opts = {}) => this.#guard((b) => b.uploadFiles(files, {
613
+ tabId: tabFor(opts),
614
+ selector,
615
+ frame: opts?.frame ?? frame ?? undefined,
616
+ timeoutMs: timeoutOpt(opts),
617
+ }), `locator.setInputFiles(${selector})`, guardOpts),
618
+ waitFor: (opts = {}) => this.#guard((b) => b.waitFor({
619
+ tabId: tabFor(opts),
620
+ selector,
621
+ frame: opts?.frame ?? frame ?? undefined,
622
+ state: opts?.state ?? "visible",
623
+ timeoutMs: this.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms ?? 10_000),
624
+ }), `locator.waitFor(${selector})`, guardOpts),
625
+ count: async (opts = {}) => (await this.#guard((b) => b.locatorCount(selector, {
626
+ tabId: tabFor(opts),
627
+ frame: opts?.frame ?? frame ?? undefined,
628
+ }), `locator.count(${selector})`, guardOpts)).count,
629
+ all: async (opts = {}) => {
630
+ const total = await self.count(opts);
631
+ return Array.from({ length: total }, (_, idx) => self.nth(idx));
632
+ },
633
+ textContent: async (opts = {}) => (await this.#guard((b) => b.locatorText(selector, {
634
+ tabId: tabFor(opts),
635
+ frame: opts?.frame ?? frame ?? undefined,
636
+ mode: "textContent",
637
+ timeoutMs: timeoutOpt(opts),
638
+ }), `locator.textContent(${selector})`, guardOpts)).text,
639
+ innerText: async (opts = {}) => (await this.#guard((b) => b.locatorText(selector, {
640
+ tabId: tabFor(opts),
641
+ frame: opts?.frame ?? frame ?? undefined,
642
+ mode: "innerText",
643
+ timeoutMs: timeoutOpt(opts),
644
+ }), `locator.innerText(${selector})`, guardOpts)).text,
645
+ allTextContents: async (opts = {}) => (await this.#guard((b) => b.locatorAllTexts(selector, {
646
+ tabId: tabFor(opts),
647
+ frame: opts?.frame ?? frame ?? undefined,
648
+ mode: "allTextContents",
649
+ }), `locator.allTextContents(${selector})`, guardOpts)).values,
650
+ allInnerTexts: async (opts = {}) => (await this.#guard((b) => b.locatorAllTexts(selector, {
651
+ tabId: tabFor(opts),
652
+ frame: opts?.frame ?? frame ?? undefined,
653
+ mode: "allInnerTexts",
654
+ }), `locator.allInnerTexts(${selector})`, guardOpts)).values,
655
+ getAttribute: async (name, opts = {}) => (await this.#guard((b) => b.locatorAttribute(selector, name, {
656
+ tabId: tabFor(opts),
657
+ frame: opts?.frame ?? frame ?? undefined,
658
+ timeoutMs: timeoutOpt(opts),
659
+ }), `locator.getAttribute(${selector})`, guardOpts)).value,
660
+ inputValue: async (opts = {}) => (await this.#guard((b) => b.locatorInputValue(selector, {
661
+ tabId: tabFor(opts),
662
+ frame: opts?.frame ?? frame ?? undefined,
663
+ timeoutMs: timeoutOpt(opts),
664
+ }), `locator.inputValue(${selector})`, guardOpts)).value,
665
+ isVisible: async (opts = {}) => (await this.#guard((b) => b.locatorState(selector, "isVisible", {
666
+ tabId: tabFor(opts),
667
+ frame: opts?.frame ?? frame ?? undefined,
668
+ }), `locator.isVisible(${selector})`, guardOpts)).value,
669
+ isEnabled: async (opts = {}) => (await this.#guard((b) => b.locatorState(selector, "isEnabled", {
670
+ tabId: tabFor(opts),
671
+ frame: opts?.frame ?? frame ?? undefined,
672
+ }), `locator.isEnabled(${selector})`, guardOpts)).value,
673
+ isChecked: async (opts = {}) => (await this.#guard((b) => b.locatorState(selector, "isChecked", {
674
+ tabId: tabFor(opts),
675
+ frame: opts?.frame ?? frame ?? undefined,
676
+ }), `locator.isChecked(${selector})`, guardOpts)).value,
677
+ evaluate: async (...args) => {
678
+ const [fnOrExpr, argOrOpts, maybeOpts] = args;
679
+ const parsed = this.#parseLocatorEvalArgs(fnOrExpr, argOrOpts, maybeOpts, args.length);
680
+ return (await this.#guard((b) => b.locatorEvaluate(selector, fnOrExpr, {
681
+ tabId: tabFor(parsed.opts),
682
+ frame: parsed.opts?.frame ?? frame ?? undefined,
683
+ all: false,
684
+ arg: parsed.arg,
685
+ hasArg: parsed.hasArg,
686
+ timeoutMs: timeoutOpt(parsed.opts),
687
+ }), `locator.evaluate(${selector})`, guardOpts)).value;
688
+ },
689
+ evaluateAll: async (...args) => {
690
+ const [fnOrExpr, argOrOpts, maybeOpts] = args;
691
+ const parsed = this.#parseLocatorEvalArgs(fnOrExpr, argOrOpts, maybeOpts, args.length);
692
+ return (await this.#guard((b) => b.locatorEvaluate(selector, fnOrExpr, {
693
+ tabId: tabFor(parsed.opts),
694
+ frame: parsed.opts?.frame ?? frame ?? undefined,
695
+ all: true,
696
+ arg: parsed.arg,
697
+ hasArg: parsed.hasArg,
698
+ }), `locator.evaluateAll(${selector})`, guardOpts)).value;
699
+ },
700
+ ariaSnapshot: async (opts = {}) => (await this.#guard((b) => b.locatorAriaSnapshot(selector, {
701
+ tabId: tabFor(opts),
702
+ frame: opts?.frame ?? frame ?? undefined,
703
+ maxLines: opts?.maxLines ?? opts?.max_lines ?? 2_000,
704
+ mode: opts?.mode ?? "compact",
705
+ timeoutMs: timeoutOpt(opts),
706
+ }), `locator.ariaSnapshot(${selector})`, guardOpts)).text,
707
+ };
708
+ return self;
709
+ }
710
+
711
+ #createFrameLocator(frameSelector, boundTabId = null) {
712
+ const sel = String(frameSelector);
713
+ return {
714
+ frameLocator: (sub) => this.#createFrameLocator(`${sel} >> ${String(sub)}`, boundTabId),
715
+ locator: (sub, opts) => {
716
+ const loc = this.#createLocator([String(sub)], sel, boundTabId);
717
+ return isPlainObject(opts) ? loc.filter(opts) : loc;
718
+ },
719
+ getByRole: (role, opts) => this.#createLocator([buildRoleStep(role, opts)], sel, boundTabId),
720
+ getByText: (text, opts) => this.#createLocator([buildTextStep(text, opts)], sel, boundTabId),
721
+ getByLabel: (text) => this.#createLocator([`label=${JSON.stringify(String(text))}`], sel, boundTabId),
722
+ getByPlaceholder: (text) => this.#createLocator([`placeholder=${JSON.stringify(String(text))}`], sel, boundTabId),
723
+ getByTestId: (id) => this.#createLocator([`testid=${JSON.stringify(String(id))}`], sel, boundTabId),
724
+ };
725
+ }
726
+
727
+ #createTabHandle(fixedTabId = null) {
728
+ const self = this;
729
+ const isBound = fixedTabId !== null && fixedTabId !== undefined && fixedTabId !== "";
730
+ const boundId = isBound ? String(fixedTabId) : null;
731
+ const resolveTab = (opts) => self.#resolveTabArg(opts, boundId);
732
+ const guardOpts = { trackActiveTab: !isBound };
733
+
734
+ const tabApi = {
735
+ get id() {
736
+ return boundId ?? self.#activeTabId();
737
+ },
738
+ get tab_id() {
739
+ return boundId ?? self.#activeTabId();
740
+ },
741
+ get activeTabId() {
742
+ return boundId ?? self.#activeTabId();
743
+ },
744
+ tab: (id) => {
745
+ if (id !== undefined && id !== null && id !== "") {
746
+ self.currentTabId = String(id);
747
+ return self.#createTabHandle(String(id));
748
+ }
749
+ return tabApi;
750
+ },
751
+ url: (opts) => self.#guard((b) => b.url(resolveTab(opts)), "url", guardOpts),
752
+ title: (opts) => self.#guard((b) => b.title(resolveTab(opts)), "title", guardOpts),
753
+ listTabs: () => self.#guard((b) => b.listTabs(), "listTabs", { trackActiveTab: false }),
754
+ newTab: (url) => self.#guard((b) => b.newTab(url), "newTab", { trackActiveTab: true }),
755
+ selectTab: (id) => self.#guard((b) => b.selectTab(id), "selectTab", { trackActiveTab: true }),
756
+ closeTab: async (id) => {
757
+ const target = id ?? boundId;
758
+ const res = await self.#guard((b) => b.closeTab(target), "closeTab", { trackActiveTab: false });
759
+ const closedId = String(res?.tab_id ?? target ?? "");
760
+ if (closedId && self.activeRun) self.activeRun.keptTabs.delete(closedId);
761
+ if (closedId && self.currentTabId === closedId) self.currentTabId = null;
762
+ return res;
763
+ },
764
+ close: () => tabApi.closeTab(boundId),
765
+ goto: (url, opts = {}) => self.#guard((b) => b.goto(url, resolveTab(opts), {
766
+ waitUntil: opts?.waitUntil ?? opts?.wait_until ?? "load",
767
+ timeoutMs: self.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms ?? 15_000),
768
+ }), `goto(${url})`, guardOpts),
769
+ back: (opts) => self.#guard((b) => b.history("back", resolveTab(opts)), "back", guardOpts),
770
+ forward: (opts) => self.#guard((b) => b.history("forward", resolveTab(opts)), "forward", guardOpts),
771
+ reload: (opts) => self.#guard((b) => b.reload(resolveTab(opts)), "reload", guardOpts),
772
+ expectNavigation: async (action, opts = {}) => {
773
+ const targetTab = resolveTab(opts);
774
+ return self.#guard((b) => b.expectNavigation(action, {
775
+ tabId: targetTab,
776
+ url: opts?.url,
777
+ waitUntil: opts?.waitUntil ?? opts?.wait_until ?? "load",
778
+ timeoutMs: self.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms ?? 15_000),
779
+ }), "expectNavigation", guardOpts);
780
+ },
781
+ getState: (opts = {}) => self.#guard((b) => b.getState(resolveTab(opts), {
782
+ screenshot: opts?.screenshot === true,
783
+ fullPage: opts?.fullPage ?? opts?.full_page ?? false,
784
+ format: opts?.format ?? "jpeg",
785
+ quality: opts?.quality ?? 75,
786
+ diff: opts?.full !== true && opts?.disableDiffing !== true,
787
+ full: opts?.full === true || opts?.disableDiffing === true,
788
+ mode: opts?.mode ?? "full",
789
+ maxLines: opts?.maxLines ?? opts?.max_lines ?? 2_000,
790
+ }), "getState", guardOpts),
791
+ state: (opts = {}) => tabApi.getState(opts),
792
+ ariaSnapshot: async (opts = {}) => {
793
+ if (opts && typeof opts === "object" && opts.selector) {
794
+ return tabApi.locator(String(opts.selector)).ariaSnapshot(opts);
795
+ }
796
+ return (await self.#guard((b) => b.ariaSnapshot({
797
+ tabId: resolveTab(opts),
798
+ maxLines: opts?.maxLines ?? opts?.max_lines ?? 2_000,
799
+ mode: opts?.mode ?? "compact",
800
+ }), "ariaSnapshot", guardOpts)).text;
801
+ },
802
+ screenshot: (opts = {}) => {
803
+ const format = opts?.format ?? opts?.type ?? "jpeg";
804
+ if (typeof opts?.path === "string" && opts.path.length > 0) {
805
+ return self.#saveScreenshot(opts.path, { ...opts, format }, boundId);
806
+ }
807
+ return self.#guard((b) => b.screenshot(resolveTab(opts), {
808
+ fullPage: opts?.fullPage ?? opts?.full_page ?? false,
809
+ format,
810
+ quality: opts?.quality ?? 75,
811
+ ...(opts?.maxWidth !== undefined || opts?.max_width !== undefined
812
+ ? { maxWidth: opts?.maxWidth ?? opts?.max_width }
813
+ : {}),
814
+ clip: opts?.clip,
815
+ scale: opts?.scale ?? "css",
816
+ }), "screenshot", guardOpts);
817
+ },
818
+ elementScreenshot: (selector, opts = {}) => self.#guard((b) => b.elementScreenshot(selector, {
819
+ tabId: resolveTab(opts),
820
+ frame: opts?.frame,
821
+ force: opts?.force === true,
822
+ padding: opts?.padding,
823
+ format: opts?.format ?? "jpeg",
824
+ quality: opts?.quality ?? 75,
825
+ scale: opts?.scale ?? "css",
826
+ timeoutMs: opts?.timeoutMs !== undefined || opts?.timeout_ms !== undefined
827
+ ? self.#clampTimeout(opts.timeoutMs ?? opts.timeout_ms)
828
+ : undefined,
829
+ }), `elementScreenshot(${selector})`, guardOpts),
830
+ saveScreenshot: (filePath, opts = {}) => self.#saveScreenshot(filePath, opts, boundId),
831
+ getContent: async (opts) => {
832
+ const format = typeof opts === "string" ? opts : opts?.format;
833
+ const maxChars = typeof opts === "object" && opts ? (opts.maxChars ?? opts.max_chars) : undefined;
834
+ const passOpts = (format || maxChars !== undefined)
835
+ ? { ...(format ? { format } : {}), ...(maxChars !== undefined ? { maxChars } : {}) }
836
+ : undefined;
837
+ const res = await self.#guard((b) => b.getContent(resolveTab(opts), passOpts), "getContent", guardOpts);
838
+ if (format === "tables" || format === "links") return res;
839
+ return res?.content ?? res?.text ?? "";
840
+ },
841
+ webmcp: {
842
+ listTools: (opts) => self.#guard((b) => b.webmcpListTools(resolveTab(opts)), "webmcp.listTools", guardOpts),
843
+ invokeTool: (name, args, opts) => self.#guard((b) => b.webmcpInvokeTool(name, args, { tabId: resolveTab(opts) }), "webmcp.invokeTool", guardOpts),
844
+ },
845
+ assets: {
846
+ list: (opts = {}) => self.#guard((b) => b.listPageAssets(resolveTab(opts), opts), "assets.list", guardOpts),
847
+ },
848
+ domSnapshot: (opts = {}) => self.#guard((b) => b.domSnapshot({
849
+ tabId: resolveTab(opts),
850
+ maxChars: opts?.maxChars ?? opts?.max_chars ?? 24_000,
851
+ maxLines: opts?.maxLines ?? opts?.max_lines ?? 2_000,
852
+ format: opts?.format ?? "dom",
853
+ }), "domSnapshot", guardOpts),
854
+ inspectElement: (x, y, opts) => self.#guard((b) => b.inspectElement(x, y, { tabId: resolveTab(opts) }), "inspectElement", guardOpts),
855
+ consoleLogs: (opts = {}) => self.#guard((b) => b.consoleLogs({
856
+ tabId: resolveTab(opts),
857
+ levels: opts?.levels,
858
+ filter: opts?.filter,
859
+ limit: opts?.limit ?? 100,
860
+ clear: opts?.clear === true,
861
+ }), "consoleLogs", guardOpts),
862
+ networkLogs: (opts = {}) => self.#guard((b) => b.networkLogs({
863
+ tabId: resolveTab(opts),
864
+ filter: opts?.filter,
865
+ statusMin: opts?.statusMin ?? opts?.status_min,
866
+ statusMax: opts?.statusMax ?? opts?.status_max,
867
+ failedOnly: opts?.failedOnly ?? opts?.failed_only ?? false,
868
+ resourceTypes: opts?.resourceTypes ?? opts?.resource_types,
869
+ limit: opts?.limit ?? 100,
870
+ clear: opts?.clear === true,
871
+ }), "networkLogs", guardOpts),
872
+ setViewport: (optsOrWidth = {}, maybeHeight, maybeOpts = {}) => {
873
+ const opts = typeof optsOrWidth === "number"
874
+ ? { ...(isPlainObject(maybeOpts) ? maybeOpts : {}), width: optsOrWidth, height: maybeHeight }
875
+ : (optsOrWidth || {});
876
+ return self.#guard((b) => b.setViewport({
877
+ tabId: resolveTab(opts),
878
+ width: opts.width,
879
+ height: opts.height,
880
+ deviceScaleFactor: opts.deviceScaleFactor ?? opts.device_scale_factor ?? 1,
881
+ mobile: opts.mobile === true,
882
+ }), "setViewport", guardOpts);
883
+ },
884
+ setViewportSize: (...args) => tabApi.setViewport(...args),
885
+ resetViewport: (opts = {}) => self.#guard((b) => b.resetViewport(resolveTab(opts)), "resetViewport", guardOpts),
886
+ keyboard: {
887
+ press: (key, opts) => tabApi.press(key, opts),
888
+ type: (text, opts) => tabApi.type(text, opts),
889
+ insertText: (text, opts) => tabApi.type(text, opts),
890
+ },
891
+ mouse: {
892
+ move: (x, y, opts) => tabApi.hover({ x, y }, opts),
893
+ click: (x, y, opts) => tabApi.click({ x, y }, opts),
894
+ wheel: (dx, dy, opts = {}) => tabApi.scroll((Number(dy) || 0) >= 0 ? "down" : "up", {
895
+ ...opts,
896
+ pages: Math.max(1, Math.round(Math.abs(Number(dy) || 500) / 500)),
897
+ }),
898
+ },
899
+ on: (eventName, handler) => {
900
+ if (eventName !== "console" && eventName !== "pageerror") {
901
+ throw new Error(`Unsupported page event listener: ${String(eventName)} (supported: console, pageerror)`);
902
+ }
903
+ if (typeof handler !== "function") return tabApi;
904
+ const run = self.#requireRun();
905
+ const unsub = run.browser.addEventListener((ev) => {
906
+ if (boundId != null && String(ev.tabId) !== String(boundId)) return;
907
+ if (boundId == null) {
908
+ const cur = self.#activeTabId();
909
+ if (cur != null && String(ev.tabId) !== String(cur)) return;
910
+ }
911
+ if (eventName === "console" && ev.kind === "console") {
912
+ handler({
913
+ type: () => ev.entry?.level ?? "log",
914
+ text: () => ev.entry?.message ?? "",
915
+ ...ev.entry,
916
+ });
917
+ } else if (eventName === "pageerror" && ev.kind === "pageerror") {
918
+ handler(ev.error ?? new Error(ev.entry?.message || "Page error"));
919
+ }
920
+ });
921
+ run.eventCleanups.set(handler, unsub);
922
+ const activeId = boundId ?? self.#activeTabId();
923
+ if (activeId != null && run.browser.attached.has(Number(activeId))) {
924
+ void run.browser.enableRuntime(activeId).catch(() => {});
925
+ }
926
+ return tabApi;
927
+ },
928
+ off: (_eventName, handler) => {
929
+ const run = self.activeRun;
930
+ const unsub = run?.eventCleanups?.get(handler);
931
+ if (typeof unsub === "function") {
932
+ unsub();
933
+ run.eventCleanups.delete(handler);
934
+ }
935
+ return tabApi;
936
+ },
937
+ evaluate: async (...args) => {
938
+ const [exprOrFn, argOrOpts, maybeOpts] = args;
939
+ const parsed = self.#parsePageEvalArgs(exprOrFn, argOrOpts, maybeOpts, args.length);
940
+ const expr = typeof exprOrFn === "function"
941
+ ? (parsed.hasArg ? exprOrFn.toString() : `(${exprOrFn.toString()})()`)
942
+ : String(exprOrFn);
943
+ const res = await self.#guard((b) => b.evaluate(expr, {
944
+ tabId: resolveTab(parsed.opts),
945
+ arg: parsed.arg,
946
+ hasArg: parsed.hasArg,
947
+ }), "evaluate", guardOpts);
948
+ return res?.value;
949
+ },
950
+ locator: (sel, opts) => {
951
+ const loc = self.#createLocator([String(sel)], null, boundId);
952
+ return isPlainObject(opts) ? loc.filter(opts) : loc;
953
+ },
954
+ frameLocator: (sel) => self.#createFrameLocator(sel, boundId),
955
+ getByRole: (role, opts) => self.#createLocator([buildRoleStep(role, opts)], null, boundId),
956
+ getByText: (text, opts) => self.#createLocator([buildTextStep(text, opts)], null, boundId),
957
+ getByLabel: (text) => self.#createLocator([`label=${JSON.stringify(String(text))}`], null, boundId),
958
+ getByPlaceholder: (text) => self.#createLocator([`placeholder=${JSON.stringify(String(text))}`], null, boundId),
959
+ getByTestId: (id) => self.#createLocator([`testid=${JSON.stringify(String(id))}`], null, boundId),
960
+ click: (target, opts = {}) => {
961
+ const tabId = resolveTab(opts);
962
+ if (target && typeof target === "object" && !Array.isArray(target) &&
963
+ Number.isFinite(target.x) && Number.isFinite(target.y)) {
964
+ return self.#guard((b) => b.click(undefined, {
965
+ tabId,
966
+ x: target.x,
967
+ y: target.y,
968
+ clickCount: opts?.clickCount ?? opts?.click_count ?? target.clickCount ?? 1,
969
+ button: opts?.button ?? opts?.mouse_button ?? "left",
970
+ modifiers: opts?.modifiers,
971
+ settle: opts?.settle ?? true,
972
+ }), "click(point)", guardOpts);
973
+ }
974
+ if (isLocatorLike(target)) {
975
+ return self.#guard((b) => b.locatorClick(target, {
976
+ tabId,
977
+ frame: opts?.frame,
978
+ clickCount: opts?.clickCount ?? opts?.click_count ?? 1,
979
+ button: opts?.button ?? opts?.mouse_button ?? "left",
980
+ modifiers: opts?.modifiers,
981
+ force: opts?.force === true,
982
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
983
+ settle: opts?.settle ?? true,
984
+ }), `click(${target})`, guardOpts);
985
+ }
986
+ return self.#guard((b) => b.click(target, {
987
+ tabId,
988
+ clickCount: opts?.clickCount ?? opts?.click_count ?? 1,
989
+ button: opts?.button ?? opts?.mouse_button ?? "left",
990
+ modifiers: opts?.modifiers,
991
+ settle: opts?.settle ?? true,
992
+ }), `click(${target})`, guardOpts);
993
+ },
994
+ locatorClick: (selector, opts = {}) => self.#guard((b) => b.locatorClick(selector, {
995
+ tabId: resolveTab(opts),
996
+ frame: opts?.frame,
997
+ clickCount: opts?.clickCount ?? opts?.click_count ?? 1,
998
+ button: opts?.button ?? opts?.mouse_button ?? "left",
999
+ modifiers: opts?.modifiers,
1000
+ force: opts?.force === true,
1001
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
1002
+ settle: opts?.settle ?? true,
1003
+ }), `locatorClick(${selector})`, guardOpts),
1004
+ fill: (target, value, opts = {}) => {
1005
+ const tabId = resolveTab(opts);
1006
+ if (isLocatorLike(target)) {
1007
+ return self.#guard((b) => b.locatorFill(target, String(value), {
1008
+ tabId,
1009
+ frame: opts?.frame,
1010
+ force: opts?.force === true,
1011
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
1012
+ settle: opts?.settle ?? true,
1013
+ }), `fill(${target})`, guardOpts);
1014
+ }
1015
+ return self.#guard((b) => b.setValue(target, String(value), {
1016
+ tabId,
1017
+ settle: opts?.settle ?? true,
1018
+ }), `setValue(${target})`, guardOpts);
1019
+ },
1020
+ locatorFill: (selector, value, opts = {}) => self.#guard((b) => b.locatorFill(selector, String(value), {
1021
+ tabId: resolveTab(opts),
1022
+ frame: opts?.frame,
1023
+ force: opts?.force === true,
1024
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
1025
+ settle: opts?.settle ?? true,
1026
+ }), `locatorFill(${selector})`, guardOpts),
1027
+ setValue: (index, value, opts = {}) => self.#guard((b) => b.setValue(index, String(value), {
1028
+ tabId: resolveTab(opts),
1029
+ settle: opts?.settle ?? true,
1030
+ }), `setValue(${index})`, guardOpts),
1031
+ type: (text, opts = {}) => self.#guard((b) => b.typeText(String(text), {
1032
+ tabId: resolveTab(opts),
1033
+ elementIndex: opts?.elementIndex ?? opts?.element_index,
1034
+ settle: opts?.settle ?? true,
1035
+ }), "typeText", guardOpts),
1036
+ typeText: (text, opts = {}) => tabApi.type(text, opts),
1037
+ press: (key, opts = {}) => self.#guard((b) => b.pressKey(String(key), {
1038
+ tabId: resolveTab(opts),
1039
+ elementIndex: opts?.elementIndex ?? opts?.element_index,
1040
+ settle: opts?.settle ?? true,
1041
+ }), `pressKey(${key})`, guardOpts),
1042
+ pressKey: (key, opts = {}) => tabApi.press(key, opts),
1043
+ hover: (target, opts = {}) => {
1044
+ const tabId = resolveTab(opts);
1045
+ if (target && typeof target === "object" && !Array.isArray(target) &&
1046
+ Number.isFinite(target.x) && Number.isFinite(target.y)) {
1047
+ return self.#guard((b) => b.hover({ tabId, x: target.x, y: target.y }), "hover(point)", guardOpts);
1048
+ }
1049
+ if (isLocatorLike(target)) {
1050
+ return self.#guard((b) => b.hover({
1051
+ tabId,
1052
+ selector: target,
1053
+ frame: opts?.frame,
1054
+ force: opts?.force === true,
1055
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
1056
+ }), `hover(${target})`, guardOpts);
1057
+ }
1058
+ return self.#guard((b) => b.hover({ tabId, elementIndex: target }), `hover(${target})`, guardOpts);
1059
+ },
1060
+ drag: (opts) => self.#guard((b) => b.drag({ tabId: resolveTab(opts), ...opts }), "drag", guardOpts),
1061
+ scroll: (dirOrOpts, optsOrPages = {}) => {
1062
+ if (isPlainObject(dirOrOpts)) {
1063
+ const opts = dirOrOpts;
1064
+ return self.#guard((b) => b.scroll(opts.direction ?? "down", {
1065
+ tabId: resolveTab(opts),
1066
+ elementIndex: opts.elementIndex ?? opts.element_index,
1067
+ pages: opts.pages ?? 1,
1068
+ x: opts.x,
1069
+ y: opts.y,
1070
+ }), `scroll(${opts.direction ?? "down"})`, guardOpts);
1071
+ }
1072
+ const opts = typeof optsOrPages === "number" ? { pages: optsOrPages } : (optsOrPages || {});
1073
+ return self.#guard((b) => b.scroll(dirOrOpts, {
1074
+ tabId: resolveTab(opts),
1075
+ elementIndex: opts?.elementIndex ?? opts?.element_index,
1076
+ pages: opts?.pages ?? 1,
1077
+ x: opts?.x,
1078
+ y: opts?.y,
1079
+ }), `scroll(${dirOrOpts})`, guardOpts);
1080
+ },
1081
+ selectOption: (targetOrOpts, valOrOpts) => {
1082
+ if (targetOrOpts && typeof targetOrOpts === "object" && !Array.isArray(targetOrOpts)) {
1083
+ return self.#guard((b) => b.selectOption({ tabId: resolveTab(targetOrOpts), ...targetOrOpts }), "selectOption", guardOpts);
1084
+ }
1085
+ const extra = (valOrOpts && typeof valOrOpts === "object" && !Array.isArray(valOrOpts))
1086
+ ? valOrOpts
1087
+ : { value: valOrOpts };
1088
+ const targetFields = isLocatorLike(targetOrOpts)
1089
+ ? { selector: targetOrOpts }
1090
+ : { elementIndex: targetOrOpts };
1091
+ return self.#guard((b) => b.selectOption({ tabId: resolveTab(extra), ...targetFields, ...extra }), "selectOption", guardOpts);
1092
+ },
1093
+ uploadFiles: (files, opts = {}) => self.#guard((b) => b.uploadFiles(files, {
1094
+ tabId: resolveTab(opts),
1095
+ elementIndex: opts?.elementIndex ?? opts?.element_index,
1096
+ selector: opts?.selector,
1097
+ frame: opts?.frame,
1098
+ timeoutMs: opts?.timeoutMs ?? opts?.timeout_ms,
1099
+ }), "uploadFiles", guardOpts),
1100
+ innerText: (selector, opts = {}) => {
1101
+ if (selector === undefined || selector === null || isPlainObject(selector)) {
1102
+ return tabApi.locator("css=body").innerText(isPlainObject(selector) ? selector : opts);
1103
+ }
1104
+ return tabApi.locator(selector).innerText(opts);
1105
+ },
1106
+ textContent: (selector, opts = {}) => {
1107
+ if (selector === undefined || selector === null || isPlainObject(selector)) {
1108
+ return tabApi.locator("css=body").textContent(isPlainObject(selector) ? selector : opts);
1109
+ }
1110
+ return tabApi.locator(selector).textContent(opts);
1111
+ },
1112
+ inputValue: (selector, opts = {}) => tabApi.locator(selector).inputValue(opts),
1113
+ getAttribute: (selector, name, opts = {}) => tabApi.locator(selector).getAttribute(name, opts),
1114
+ isVisible: (selector, opts = {}) => tabApi.locator(selector).isVisible(opts),
1115
+ isEnabled: (selector, opts = {}) => tabApi.locator(selector).isEnabled(opts),
1116
+ isChecked: (selector, opts = {}) => tabApi.locator(selector).isChecked(opts),
1117
+ check: (selector, opts = {}) => tabApi.locator(selector).check(opts),
1118
+ uncheck: (selector, opts = {}) => tabApi.locator(selector).uncheck(opts),
1119
+ waitFor: (optsOrMs) => {
1120
+ if (typeof optsOrMs === "number") return self.#sleep(optsOrMs);
1121
+ if (typeof optsOrMs === "string") {
1122
+ return self.#guard((b) => b.waitFor({
1123
+ tabId: resolveTab(),
1124
+ selector: optsOrMs,
1125
+ timeoutMs: self.#clampTimeout(10_000),
1126
+ }), `waitFor(${optsOrMs})`, guardOpts);
1127
+ }
1128
+ const opts = (optsOrMs && typeof optsOrMs === "object") ? optsOrMs : {};
1129
+ return self.#guard((b) => b.waitFor({
1130
+ tabId: resolveTab(opts),
1131
+ selector: opts.selector,
1132
+ text: opts.text,
1133
+ url: opts.url,
1134
+ loadState: opts.loadState ?? opts.load_state,
1135
+ state: opts.state,
1136
+ frame: opts.frame,
1137
+ timeoutMs: self.#clampTimeout(opts.timeoutMs ?? opts.timeout_ms ?? 10_000),
1138
+ }), "waitFor", guardOpts);
1139
+ },
1140
+ wait: (optsOrMs) => tabApi.waitFor(optsOrMs),
1141
+ waitForEvent: async (eventName, opts = {}) => {
1142
+ const res = await self.#guard((b) => b.waitForEvent(eventName, {
1143
+ tabId: resolveTab(opts),
1144
+ timeoutMs: self.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms ?? 30_000),
1145
+ }), `waitForEvent(${eventName})`, guardOpts);
1146
+ if (eventName === "popup" && res?.tab_id) {
1147
+ const handle = self.#createTabHandle(res.tab_id);
1148
+ handle.openerTabId = res.opener_tab_id;
1149
+ handle.opener_tab_id = res.opener_tab_id;
1150
+ handle.initialUrl = res.url;
1151
+ handle.initialTitle = res.title;
1152
+ return handle;
1153
+ }
1154
+ return res;
1155
+ },
1156
+ waitForLoadState: (stateOrOpts = "load", maybeOpts = {}) => {
1157
+ const opts = typeof stateOrOpts === "string"
1158
+ ? { ...maybeOpts, loadState: stateOrOpts }
1159
+ : (stateOrOpts || {});
1160
+ return tabApi.waitFor({
1161
+ ...opts,
1162
+ loadState: opts.loadState ?? opts.state ?? "load",
1163
+ });
1164
+ },
1165
+ waitForURL: (url, opts = {}) => tabApi.waitFor({ ...opts, url }),
1166
+ waitForTimeout: (ms) => self.#sleep(ms),
1167
+ handleDialog: (opts = {}) => self.#guard((b) => b.handleDialog({
1168
+ tabId: resolveTab(opts),
1169
+ accept: opts?.accept !== false,
1170
+ promptText: opts?.promptText ?? opts?.prompt_text,
1171
+ }), "handleDialog", guardOpts),
1172
+ getJsDialog: (opts = {}) => self.#guard((b) => b.getJsDialog(resolveTab(opts)), "getJsDialog", guardOpts),
1173
+ keepTab: (mode, idOrOpts, maybeOpts) => self.#keepTab(mode, idOrOpts ?? boundId, maybeOpts),
1174
+ markDeliverable: (idOrOpts, maybeOpts) => {
1175
+ if (isPlainObject(idOrOpts)) {
1176
+ return self.#keepTab("deliverable", idOrOpts.tabId ?? idOrOpts.tab_id ?? boundId, idOrOpts);
1177
+ }
1178
+ return self.#keepTab("deliverable", idOrOpts ?? boundId, maybeOpts);
1179
+ },
1180
+ markHandoff: (idOrOpts, maybeOpts) => {
1181
+ if (isPlainObject(idOrOpts)) {
1182
+ return self.#keepTab("handoff", idOrOpts.tabId ?? idOrOpts.tab_id ?? boundId, idOrOpts);
1183
+ }
1184
+ return self.#keepTab("handoff", idOrOpts ?? boundId, maybeOpts);
1185
+ },
1186
+ endTurn: (opts) => self.#requestEndTurn(opts, boundId),
1187
+ end_turn: (opts) => self.#requestEndTurn(opts, boundId),
1188
+ dev: {
1189
+ logs: async (opts = {}) => (await tabApi.consoleLogs(opts)).logs,
1190
+ network: async (opts = {}) => (await tabApi.networkLogs(opts)).requests,
1191
+ enableNetwork: (opts = {}) => self.#guard((b) => b.enableNetwork({
1192
+ tabId: resolveTab(opts),
1193
+ captureBodies: opts?.captureBodies !== false,
1194
+ }), "dev.enableNetwork", guardOpts),
1195
+ responseBody: (requestId, opts = {}) => self.#guard((b) => b.networkResponseBody(requestId, {
1196
+ tabId: resolveTab(opts),
1197
+ maxChars: opts?.maxChars ?? opts?.max_chars ?? 64_000,
1198
+ }), `dev.responseBody(${requestId})`, guardOpts),
1199
+ },
1200
+ ax: {
1201
+ getState: (opts = {}) => tabApi.getState(opts),
1202
+ get: async (modeOrOpts = {}, maybeOpts = {}) => {
1203
+ if (modeOrOpts === "screenshot") {
1204
+ return await tabApi.screenshot(maybeOpts);
1205
+ }
1206
+ if (modeOrOpts === "both") {
1207
+ const full = maybeOpts?.disableDiffing === true || maybeOpts?.full === true;
1208
+ const st = await tabApi.getState({ ...maybeOpts, screenshot: true, full, diff: !full });
1209
+ return {
1210
+ state: st.axText,
1211
+ screenshot: st.screenshotBase64
1212
+ ? { data: st.screenshotBase64, mimeType: st.screenshotMimeType || "image/jpeg" }
1213
+ : undefined,
1214
+ };
1215
+ }
1216
+ const opts = typeof modeOrOpts === "string" ? maybeOpts : (modeOrOpts || {});
1217
+ const full = opts.full === true || opts.disableDiffing === true;
1218
+ const st = await tabApi.getState({ ...opts, screenshot: false, full, diff: !full });
1219
+ return st.axText;
1220
+ },
1221
+ write: async (modeOrOpts = {}, maybeOpts = {}) => {
1222
+ if (modeOrOpts === "screenshot") {
1223
+ await self.#viewImage(maybeOpts, boundId);
1224
+ return;
1225
+ }
1226
+ if (modeOrOpts === "both") {
1227
+ const full = maybeOpts?.disableDiffing === true || maybeOpts?.full === true;
1228
+ const st = await tabApi.getState({ ...maybeOpts, screenshot: false, full, diff: !full });
1229
+ self.#log(st.axText);
1230
+ await self.#viewImage(maybeOpts, boundId);
1231
+ return st.axText;
1232
+ }
1233
+ const opts = typeof modeOrOpts === "string" ? maybeOpts : (modeOrOpts || {});
1234
+ const full = opts.full === true || opts.disableDiffing === true;
1235
+ const st = await tabApi.getState({ ...opts, screenshot: false, full, diff: !full });
1236
+ self.#log(st.axText);
1237
+ if (opts.screenshot === true) {
1238
+ await self.#viewImage(opts, boundId);
1239
+ }
1240
+ return st.axText;
1241
+ },
1242
+ click: (target, opts = {}) => {
1243
+ if (Array.isArray(target)) {
1244
+ return tabApi.click({ x: target[0], y: target[1] }, opts);
1245
+ }
1246
+ return tabApi.click(target, opts);
1247
+ },
1248
+ setValue: (idx, val, opts = {}) => tabApi.setValue(idx, val, opts),
1249
+ paste: (idxOrText, maybeText, opts = {}) => {
1250
+ if (typeof maybeText === "string") {
1251
+ return self.#guard((b) => b.pasteText(idxOrText, maybeText, {
1252
+ tabId: resolveTab(opts),
1253
+ settle: opts?.settle === true,
1254
+ }), "ax.paste", guardOpts);
1255
+ }
1256
+ const extra = isPlainObject(maybeText) ? maybeText : {};
1257
+ return self.#guard((b) => b.pasteText(undefined, String(idxOrText), {
1258
+ tabId: resolveTab(extra),
1259
+ settle: extra?.settle === true,
1260
+ }), "ax.paste", guardOpts);
1261
+ },
1262
+ selectText: (idx, text, opts = {}) => self.#guard((b) => b.selectText(idx, text, {
1263
+ tabId: resolveTab(opts),
1264
+ settle: opts?.settle === true,
1265
+ }), `ax.selectText(${idx})`, guardOpts),
1266
+ pressKey: (idxOrKey, maybeKey, opts = {}) => {
1267
+ if (typeof maybeKey === "string") {
1268
+ return tabApi.press(maybeKey, {
1269
+ ...opts,
1270
+ ...(idxOrKey !== null && idxOrKey !== undefined ? { elementIndex: idxOrKey } : {}),
1271
+ });
1272
+ }
1273
+ const extra = isPlainObject(maybeKey) ? maybeKey : {};
1274
+ return tabApi.press(String(idxOrKey), extra);
1275
+ },
1276
+ typeText: (idxOrText, maybeText, opts = {}) => {
1277
+ if (typeof maybeText === "string") {
1278
+ return tabApi.type(maybeText, {
1279
+ ...opts,
1280
+ ...(idxOrText !== null && idxOrText !== undefined ? { elementIndex: idxOrText } : {}),
1281
+ });
1282
+ }
1283
+ const extra = isPlainObject(maybeText) ? maybeText : {};
1284
+ return tabApi.type(String(idxOrText), extra);
1285
+ },
1286
+ scroll: (targetOrDir, dirOrOpts = "down", pagesOrOpts) => {
1287
+ if (typeof targetOrDir === "string") {
1288
+ const opts = typeof dirOrOpts === "number"
1289
+ ? { pages: dirOrOpts }
1290
+ : (isPlainObject(dirOrOpts) ? dirOrOpts : {});
1291
+ return tabApi.scroll(targetOrDir, opts);
1292
+ }
1293
+ const pages = typeof pagesOrOpts === "number" ? pagesOrOpts : (pagesOrOpts?.pages ?? 1);
1294
+ if (Array.isArray(targetOrDir)) {
1295
+ return tabApi.scroll(String(dirOrOpts), { x: targetOrDir[0], y: targetOrDir[1], pages });
1296
+ }
1297
+ return tabApi.scroll(String(dirOrOpts), { elementIndex: targetOrDir, pages });
1298
+ },
1299
+ drag: (fromOrOpts, to, opts = {}) => {
1300
+ if (isPlainObject(fromOrOpts)) return tabApi.drag(fromOrOpts);
1301
+ const payload = { ...opts };
1302
+ if (Array.isArray(fromOrOpts)) {
1303
+ payload.fromX = fromOrOpts[0];
1304
+ payload.fromY = fromOrOpts[1];
1305
+ } else {
1306
+ payload.fromIndex = fromOrOpts;
1307
+ }
1308
+ if (Array.isArray(to)) {
1309
+ payload.toX = to[0];
1310
+ payload.toY = to[1];
1311
+ } else {
1312
+ payload.toIndex = to;
1313
+ }
1314
+ return tabApi.drag(payload);
1315
+ },
1316
+ performSecondaryAction: (idx, action, opts = {}) => self.#guard((b) => b.performSecondaryAction(idx, action, {
1317
+ tabId: resolveTab(opts),
1318
+ settle: opts?.settle ?? true,
1319
+ }), `ax.performSecondaryAction(${idx}, ${action})`, guardOpts),
1320
+ ariaSnapshot: (opts = {}) => tabApi.ariaSnapshot(opts),
1321
+ },
1322
+ };
1323
+ tabApi.content = Object.assign(
1324
+ (opts) => tabApi.getContent(opts),
1325
+ {
1326
+ export: (opts = {}) => tabApi.getContent({ ...opts, format: opts?.format ?? "markdown" }),
1327
+ tables: (opts = {}) => tabApi.getContent({ ...opts, format: "tables" }),
1328
+ links: (opts = {}) => tabApi.getContent({ ...opts, format: "links" }),
1329
+ },
1330
+ );
1331
+ tabApi.playwright = tabApi;
1332
+ return tabApi;
1333
+ }
1334
+
1335
+ #createApi() {
1336
+ const self = this;
1337
+ const api = this.#createTabHandle(null);
1338
+ api.tabs = {
1339
+ new: async (url) => {
1340
+ const info = await self.#guard((b) => b.newTab(url), "tabs.new", { trackActiveTab: true });
1341
+ return self.#createTabHandle(info.tab_id);
1342
+ },
1343
+ get: async (id) => {
1344
+ const raw = isPlainObject(id) ? (id.tab_id ?? id.id) : id;
1345
+ const wanted = String(raw);
1346
+ const list = await self.#guard((b) => b.listTabs(), "tabs.get", { trackActiveTab: false });
1347
+ const match = list.find((t) => String(t.tab_id) === wanted);
1348
+ if (!match) {
1349
+ throw new Error(`Browser tab ${wanted} is unavailable to this session`);
1350
+ }
1351
+ if (match.owned === false) {
1352
+ await self.#guard((b) => b.claimTab(wanted), "tabs.claim", { trackActiveTab: false });
1353
+ }
1354
+ return self.#createTabHandle(wanted);
1355
+ },
1356
+ read: async (tabOrId, opts = {}) => {
1357
+ const raw = isPlainObject(tabOrId) ? (tabOrId.tab_id ?? tabOrId.id ?? tabOrId.providerTabId) : tabOrId;
1358
+ return await self.#guard((b) => b.readTabContext(raw, opts), "tabs.read", { trackActiveTab: false });
1359
+ },
1360
+ claim: async (tabOrId) => {
1361
+ const raw = isPlainObject(tabOrId) ? (tabOrId.tab_id ?? tabOrId.id) : tabOrId;
1362
+ const info = await self.#guard((b) => b.claimTab(raw), "tabs.claim", { trackActiveTab: true });
1363
+ return self.#createTabHandle(info.tab_id);
1364
+ },
1365
+ list: async () => {
1366
+ const list = await self.#guard((b) => b.listTabs(), "tabs.list", { trackActiveTab: false });
1367
+ return list.map((t) => ({ id: t.tab_id, ...t }));
1368
+ },
1369
+ selected: async () => {
1370
+ const list = await self.#guard((b) => b.listTabs(), "tabs.selected", { trackActiveTab: false });
1371
+ const target = list.find((t) => t.active) || list.find((t) => t.owned !== false) || list[0];
1372
+ if (!target) return undefined;
1373
+ if (target.owned === false) {
1374
+ await self.#guard((b) => b.claimTab(target.tab_id), "tabs.claim", { trackActiveTab: true });
1375
+ }
1376
+ return self.#createTabHandle(target.tab_id);
1377
+ },
1378
+ content: (urls, opts = {}) => self.#guard((b) => b.extractUrlsContent(urls, {
1379
+ format: opts?.format ?? "markdown",
1380
+ maxChars: opts?.maxChars ?? opts?.max_chars ?? 16_000,
1381
+ concurrency: opts?.concurrency ?? 3,
1382
+ waitUntil: opts?.waitUntil ?? opts?.wait_until ?? "domcontentloaded",
1383
+ timeoutMs: self.#clampTimeout(opts?.timeoutMs ?? opts?.timeout_ms ?? 15_000),
1384
+ }), "tabs.content", { trackActiveTab: false }),
1385
+ };
1386
+ api.user = {
1387
+ openTabs: async () => {
1388
+ const list = await self.#guard((b) => b.listTabs({ includeUserTabs: "force" }), "user.openTabs", { trackActiveTab: false });
1389
+ return list.map((t) => ({ id: t.tab_id, providerTabId: t.tab_id, ...t }));
1390
+ },
1391
+ claimTab: async (tabOrId) => {
1392
+ const raw = isPlainObject(tabOrId) ? (tabOrId.tab_id ?? tabOrId.id ?? tabOrId.providerTabId) : tabOrId;
1393
+ const info = await self.#guard((b) => b.claimTab(raw), "user.claimTab", { trackActiveTab: true });
1394
+ return self.#createTabHandle(info.tab_id);
1395
+ },
1396
+ getTabContext: async (tabOrId, opts = {}) => {
1397
+ const raw = isPlainObject(tabOrId) ? (tabOrId.tab_id ?? tabOrId.id ?? tabOrId.providerTabId) : tabOrId;
1398
+ return await self.#guard((b) => b.readTabContext(raw, opts), "user.getTabContext", { trackActiveTab: false });
1399
+ },
1400
+ };
1401
+ api.viewport = {
1402
+ set: (opts) => api.setViewport(opts),
1403
+ reset: (opts) => api.resetViewport(opts),
1404
+ };
1405
+ api.nameSession = (name, colorOrOpts) => {
1406
+ const opts = typeof colorOrOpts === "string" ? { color: colorOrOpts } : (colorOrOpts || {});
1407
+ return self.#guard((b) => b.nameSession(name, opts), "nameSession", { trackActiveTab: false });
1408
+ };
1409
+ api.groups = {
1410
+ list: () => self.#guard((b) => b.listTabGroups(), "groups.list", { trackActiveTab: false }),
1411
+ ungroup: (tabIds) => self.#guard((b) => b.ungroupTabs(tabIds), "groups.ungroup", { trackActiveTab: false }),
1412
+ cleanup: (opts = {}) => self.#guard((b) => b.cleanupGroups(opts), "groups.cleanup", { trackActiveTab: false }),
1413
+ };
1414
+ return api;
1415
+ }
1416
+
1417
+ /**
1418
+ * Execute an async multi-step browser script with `browser`/`page`, bound `Tab` handles,
1419
+ * fluent auto-waiting Locators, `ariaSnapshot()`, `log`, `sleep`, `viewImage`,
1420
+ * `saveFile`, `readFile`, `saveScreenshot`, `nodeRepl`, and persisted top-level variables.
1421
+ * @param {import("./bridge-browser.js").BridgeBrowser} browser
1422
+ * @param {string} code
1423
+ * @param {{tabId?:unknown, timeoutMs?:number, maxLogChars?:number, maxResultChars?:number, maxImages?:number}} [options]
1424
+ */
1425
+ async run(browser, code, options = {}) {
1426
+ const timeoutMs = Math.max(500, Math.min(300_000, Number(options.timeoutMs) || 45_000));
1427
+ const maxLogChars = options.maxLogChars ?? 16_000;
1428
+ const maxResultChars = options.maxResultChars ?? 32_000;
1429
+ const maxImages = options.maxImages ?? 4;
1430
+
1431
+ if (options.tabId !== undefined && options.tabId !== null && options.tabId !== "") {
1432
+ this.currentTabId = String(options.tabId);
1433
+ } else {
1434
+ this.syncActiveTab(browser);
1435
+ }
1436
+
1437
+ const run = {
1438
+ browser,
1439
+ deadline: Date.now() + timeoutMs,
1440
+ timeoutMs,
1441
+ aborted: false,
1442
+ lastAction: null,
1443
+ touchedTabs: new Set(this.currentTabId ? [this.currentTabId] : []),
1444
+ keptTabs: new Map(),
1445
+ savedFiles: new Map(),
1446
+ eventCleanups: new Map(),
1447
+ endTurnRequested: false,
1448
+ ungroupOnEndTurn: false,
1449
+ logs: [],
1450
+ logChars: 0,
1451
+ images: [],
1452
+ activeTimers: new Set(),
1453
+ maxLogChars,
1454
+ maxImages,
1455
+ };
1456
+ this.activeRun = run;
1457
+
1458
+ const api = this.#createApi();
1459
+ const log = (...args) => this.#log(...args);
1460
+ const sleep = (ms) => this.#sleep(ms);
1461
+ const viewImage = (captureOrOpts) => this.#viewImage(captureOrOpts);
1462
+ const saveFile = (filePath, data) => this.#saveFile(filePath, data);
1463
+ const readFile = (filePath, opts) => this.#readFile(filePath, opts);
1464
+ const saveScreenshot = (filePath, opts) => this.#saveScreenshot(filePath, opts);
1465
+ const nodeRepl = { write: log, emitImage: viewImage };
1466
+ const consoleFacade = {
1467
+ log,
1468
+ info: log,
1469
+ warn: (...args) => log("[warn]", ...args),
1470
+ error: (...args) => log("[error]", ...args),
1471
+ };
1472
+
1473
+ const { transformed, declaredNames } = transformPersistentCode(code);
1474
+ const existingKeys = Object.keys(this.scope).filter((k) => IDENTIFIER_RE.test(k) && !RESERVED_PARAM_NAMES.has(k));
1475
+ const preloadLines = existingKeys.map((k) => `var ${k} = __scope[${JSON.stringify(k)}];`).join("\n");
1476
+ const allSavedKeys = [...new Set([...existingKeys, ...declaredNames])];
1477
+ const saveLines = allSavedKeys
1478
+ .map((k) => `try { __scope[${JSON.stringify(k)}] = ${k}; } catch { /* uninitialized */ }`)
1479
+ .join("\n");
1480
+
1481
+ const wrapped = `(async function __browserRun(browser, page, log, sleep, viewImage, saveFile, readFile, saveScreenshot, nodeRepl, console, __scope) {\n${preloadLines}\ntry {\n${transformed}\n} finally {\n${saveLines}\n}\n})`;
1482
+ const script = new vm.Script(wrapped, { filename: "browser-run.js" });
1483
+ const runner = script.runInContext(this.context, { timeout: Math.min(timeoutMs, 5_000) });
1484
+
1485
+ let deadlineTimer;
1486
+ const timeoutPromise = new Promise((_, reject) => {
1487
+ deadlineTimer = setTimeout(() => {
1488
+ run.aborted = true;
1489
+ reject(new Error(this.#timeoutMessage(run)));
1490
+ }, timeoutMs);
1491
+ });
1492
+
1493
+ try {
1494
+ const rawValue = await Promise.race([
1495
+ runner(api, api, log, sleep, viewImage, saveFile, readFile, saveScreenshot, nodeRepl, consoleFacade, this.scope),
1496
+ timeoutPromise,
1497
+ ]);
1498
+ const notifications = [];
1499
+ const drainIds = new Set([...run.touchedTabs]);
1500
+ const finalActive = this.#activeTabId();
1501
+ if (finalActive != null) drainIds.add(String(finalActive));
1502
+ for (const tid of drainIds) {
1503
+ const num = Number(tid);
1504
+ if (Number.isSafeInteger(num)) {
1505
+ notifications.push(...browser.drainNotifications(num));
1506
+ }
1507
+ }
1508
+ return {
1509
+ value: boundResult(rawValue, maxResultChars),
1510
+ logs: run.logs,
1511
+ images: run.images,
1512
+ savedFiles: [...run.savedFiles.values()],
1513
+ notifications,
1514
+ activeTabId: finalActive,
1515
+ keptTabs: [...run.keptTabs.entries()].map(([tab_id, cfg]) => ({
1516
+ tab_id,
1517
+ mode: cfg.mode,
1518
+ ...(cfg.focus === true ? { focus: true } : {}),
1519
+ })),
1520
+ endTurnRequested: run.endTurnRequested,
1521
+ ungroupOnEndTurn: run.ungroupOnEndTurn,
1522
+ };
1523
+ } finally {
1524
+ run.aborted = true;
1525
+ clearTimeout(deadlineTimer);
1526
+ for (const timer of run.activeTimers) clearTimeout(timer);
1527
+ run.activeTimers.clear();
1528
+ for (const unsub of run.eventCleanups.values()) {
1529
+ try { unsub(); } catch { /* Ignore cleanup failure */ }
1530
+ }
1531
+ run.eventCleanups.clear();
1532
+ if (this.activeRun === run) this.activeRun = null;
1533
+ }
1534
+ }
1535
+ }
1536
+
1537
+ /**
1538
+ * Convenience stateless/session-aware helper for running a browser script.
1539
+ * @param {import("./bridge-browser.js").BridgeBrowser} browser
1540
+ * @param {string} code
1541
+ * @param {{session?:BrowserScriptSession, tabId?:unknown, timeoutMs?:number, maxLogChars?:number, maxResultChars?:number, maxImages?:number}} [options]
1542
+ */
1543
+ export async function runBrowserScript(browser, code, options = {}) {
1544
+ const session = options.session ?? new BrowserScriptSession();
1545
+ return session.run(browser, code, options);
1546
+ }