dsh-embedded-browser-next 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/browser.js ADDED
@@ -0,0 +1,2634 @@
1
+ /**
2
+ * Browser lifecycle and per-session page operations.
3
+ *
4
+ * One Chrome instance per DSH host process, launched against a persistent
5
+ * `--user-data-dir` so a human login survives restarts — with **one tab per DSH
6
+ * session**. Every session drives its own page; sessions deliberately share the
7
+ * profile, and therefore the login state, because logging in once and using it
8
+ * everywhere is the point of the plugin.
9
+ *
10
+ * Two invariants are load-bearing (both measured on the production binary, see
11
+ * `references/PITFALLS.md` #11/#12):
12
+ *
13
+ * - a target must be **activated once** after creation, or it silently discards
14
+ * every injected input event for the rest of its life;
15
+ * - only the **active** tab emits screencast frames, so the hub, not this class,
16
+ * decides which tab stays in front once a session tab exists.
17
+ *
18
+ * @module dsh-embedded-browser/browser
19
+ */
20
+
21
+ import { spawn } from 'node:child_process'
22
+ import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'
23
+ import { homedir } from 'node:os'
24
+ import { delimiter, join } from 'node:path'
25
+ import { createServer } from 'node:net'
26
+ import { Cdp, fetchVersion } from './cdp.js'
27
+ import { assertDownloadDir, assertUploadAllowed } from './paths.js'
28
+ import { SNAPSHOT_BUDGET_CHARS, SNAPSHOT_CAP, SNAPSHOT_FLOOR } from './snapshot-window.js'
29
+
30
+ /**
31
+ * Folders searched for a Chromium-family binary, in order.
32
+ *
33
+ * Windows has no `chrome` on PATH worth relying on, so it gets the well-known
34
+ * absolute locations instead; POSIX keeps the command names.
35
+ */
36
+ const PATH_CANDIDATES = process.platform === 'win32'
37
+ ? ['chrome.exe', 'msedge.exe', 'chromium.exe']
38
+ : ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser', 'chrome']
39
+
40
+ /** Windows install roots, tried before any cache. Empty elsewhere. */
41
+ const WINDOWS_ROOTS = process.platform === 'win32'
42
+ ? [
43
+ join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Google', 'Chrome', 'Application', 'chrome.exe'),
44
+ join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe'),
45
+ join(process.env.LOCALAPPDATA ?? '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
46
+ join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
47
+ join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
48
+ join(process.env.LOCALAPPDATA ?? '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
49
+ ].filter((candidate) => candidate !== '' && !candidate.startsWith('\\'))
50
+ : []
51
+
52
+ /** Cache roots of the Node browser drivers, searched when no system Chrome exists. */
53
+ const CACHE_ROOTS = [
54
+ join(homedir(), '.cache', 'ms-playwright'),
55
+ join(homedir(), '.cache', 'puppeteer'),
56
+ join(homedir(), 'Library', 'Caches', 'ms-playwright'),
57
+ ...(process.env.LOCALAPPDATA === undefined
58
+ ? []
59
+ : [join(process.env.LOCALAPPDATA, 'ms-playwright'), join(process.env.LOCALAPPDATA, 'puppeteer')]),
60
+ ]
61
+
62
+ /** Executables inside a driver cache, newest layout first, per platform. */
63
+ const CACHE_INNER = [
64
+ 'chrome-win/chrome.exe',
65
+ 'chrome-linux64/chrome',
66
+ 'chrome-linux/chrome',
67
+ 'chrome-linux/headless_shell',
68
+ 'chrome-mac/Chromium.app/Contents/MacOS/Chromium',
69
+ ]
70
+
71
+ /** Keys understood by {@link BrowserManager#press}. */
72
+ const KEYS = {
73
+ Enter: { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' },
74
+ Tab: { key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 },
75
+ Escape: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
76
+ Backspace: { key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 },
77
+ Delete: { key: 'Delete', code: 'Delete', windowsVirtualKeyCode: 46 },
78
+ ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', windowsVirtualKeyCode: 38 },
79
+ ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 },
80
+ ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 },
81
+ ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 },
82
+ Home: { key: 'Home', code: 'Home', windowsVirtualKeyCode: 36 },
83
+ End: { key: 'End', code: 'End', windowsVirtualKeyCode: 35 },
84
+ PageUp: { key: 'PageUp', code: 'PageUp', windowsVirtualKeyCode: 33 },
85
+ PageDown: { key: 'PageDown', code: 'PageDown', windowsVirtualKeyCode: 34 },
86
+ Space: { key: ' ', code: 'Space', windowsVirtualKeyCode: 32, text: ' ' },
87
+ EscapeSequence: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
88
+ }
89
+
90
+ /** Sleep helper. */
91
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
92
+
93
+ /**
94
+ * What counts as "something a person can operate".
95
+ *
96
+ * `lib/client.js` carries a byte-identical copy: the panel's guest is a plain
97
+ * browser script with no build step, so the two cannot import one another. The
98
+ * suite (`test/click-text.test.mjs`) asserts the copies stay equal — without
99
+ * that, the same label resolves in the panel and vanishes headless.
100
+ */
101
+ const INTERACTIVE_SELECTOR =
102
+ 'a[href],button,input:not([type=hidden]),select,textarea,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[contenteditable=""],[contenteditable=true],[onclick]'
103
+
104
+ /**
105
+ * Find the thing a person would click when they read a label.
106
+ *
107
+ * Runs unchanged in both worlds (the panel's guest and the headless tab) so the
108
+ * two can never disagree about what "the element that says X" means. It returns
109
+ * a JSON string because that is the one shape both evaluators hand back whole:
110
+ * Electron's `executeJavaScript` and CDP's `Runtime.evaluate`.
111
+ *
112
+ * Two layers, in this order:
113
+ *
114
+ * 1. **semantic controls** — the same selector the snapshot uses. Every page
115
+ * that already worked keeps working, and a heading that repeats a button's
116
+ * label cannot hijack it.
117
+ * 2. **any visible element whose text matches, innermost first** — this is the
118
+ * layer that catches `<span class="btn">`, which is how most sites build a
119
+ * button. Without it, click-by-label simply never sees them and reports
120
+ * "no clickable element matching" on a page where the button is right there.
121
+ *
122
+ * A fallback match is only clicked when it *looks* clickable (a pointer cursor,
123
+ * or inside something that is). Pure display text — a heading, a paragraph — is
124
+ * reported with its selector instead of being clicked blind: clicking the words
125
+ * of a label does nothing, and "I clicked something" is a worse answer than
126
+ * "here is what I saw, and here is how to name it".
127
+ */
128
+ // #region click-text-probe
129
+ const CLICK_TEXT_PROBE = `(() => {
130
+ const INTERACTIVE = __INTERACTIVE__;
131
+ const want = __WANT__;
132
+ const needle = __NEEDLE__;
133
+ const norm = (value) => String(value == null ? '' : value).replace(/\\s+/g, ' ').trim();
134
+ const labelOf = (el) => norm(el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('title') || el.innerText || el.textContent || '');
135
+ const shown = (el) => {
136
+ const style = getComputedStyle(el);
137
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
138
+ const rect = el.getBoundingClientRect();
139
+ return !(rect.width === 0 && rect.height === 0);
140
+ };
141
+ const cssOf = (el) => {
142
+ if (el.id) return '#' + CSS.escape(el.id);
143
+ const parts = [];
144
+ let at = el;
145
+ while (at && at.nodeType === 1 && parts.length < 6) {
146
+ if (at.id) { parts.unshift('#' + CSS.escape(at.id)); break; }
147
+ let part = at.tagName.toLowerCase();
148
+ const parent = at.parentElement;
149
+ if (parent) part += ':nth-child(' + ([].indexOf.call(parent.children, at) + 1) + ')';
150
+ parts.unshift(part);
151
+ at = parent;
152
+ }
153
+ return parts.join(' > ');
154
+ };
155
+ const describe = (el) => ({ tag: el.tagName.toLowerCase(), label: labelOf(el).slice(0, 60), selector: cssOf(el) });
156
+ // A wrapper's innerText is the same string as the button's, so without this
157
+ // every button inside a div would come back "ambiguous" — wrapper and button
158
+ // both counted. Keep the innermost, drop every ancestor of a kept one.
159
+ const innermost = (list) => list.filter((el) => !list.some((other) => other !== el && el.contains(other)));
160
+ const narrow = (list) => {
161
+ const labelled = list.map((el) => ({ el: el, label: labelOf(el).toLowerCase() }));
162
+ const exact = labelled.filter((one) => one.label === needle);
163
+ const pool = exact.length > 0 ? exact : labelled.filter((one) => one.label.indexOf(needle) !== -1);
164
+ return pool.map((one) => one.el);
165
+ };
166
+ const looksClickable = (el) => {
167
+ if (el.closest('a[href],button,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[tabindex]') !== null) return true;
168
+ return getComputedStyle(el).cursor === 'pointer';
169
+ };
170
+ const answer = (match, el, pool) => {
171
+ el.scrollIntoView({ block: 'center', inline: 'center' });
172
+ const rect = el.getBoundingClientRect();
173
+ const out = {
174
+ ok: true,
175
+ match: match,
176
+ tag: el.tagName.toLowerCase(),
177
+ label: labelOf(el).slice(0, 80),
178
+ x: Math.round(rect.left + rect.width / 2),
179
+ y: Math.round(rect.top + rect.height / 2),
180
+ matches: pool.length,
181
+ };
182
+ if (pool.length > 1) {
183
+ out.ambiguous = true;
184
+ out.candidates = pool.slice(0, 5).map(describe);
185
+ }
186
+ return JSON.stringify(out);
187
+ };
188
+ const semantic = [];
189
+ for (const node of document.querySelectorAll(INTERACTIVE)) if (shown(node)) semantic.push(node);
190
+ let pool = narrow(innermost(semantic));
191
+ if (pool.length > 0) return answer('semantic', pool[0], pool);
192
+ // textContent is cheap; only the survivors pay for a layout read.
193
+ const loose = [];
194
+ for (const node of document.querySelectorAll('body *')) {
195
+ const tag = node.tagName;
196
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') continue;
197
+ if (String(node.textContent || '').toLowerCase().indexOf(needle) === -1) continue;
198
+ if (labelOf(node) === '') continue;
199
+ if (!shown(node)) continue;
200
+ // Past this many candidates the page is not answering a text search; a
201
+ // selector is. Capping keeps the scan bounded instead of quadratic.
202
+ if (loose.length >= 800) break;
203
+ loose.push(node);
204
+ }
205
+ pool = narrow(innermost(loose));
206
+ const clickable = pool.filter(looksClickable);
207
+ if (clickable.length > 0) return answer('fallback', clickable[0], clickable);
208
+ if (pool.length > 0) {
209
+ const where = pool.slice(0, 3).map((el) => { const one = describe(el); return one.tag + ' ' + one.selector; }).join(', ');
210
+ return JSON.stringify({
211
+ ok: false,
212
+ match: 'fallback',
213
+ reason: 'no clickable element matching ' + JSON.stringify(want) + ' — the page shows ' + pool.length + ' matching text(s) (' + where + ') but none of them looks clickable; pass selector or x/y instead',
214
+ candidates: pool.slice(0, 5).map(describe),
215
+ });
216
+ }
217
+ return JSON.stringify({
218
+ ok: false,
219
+ match: 'none',
220
+ reason: 'no clickable element matching ' + JSON.stringify(want) + ' — nothing visible on this page contains that text; call browser_embedded_snapshot to see what is there',
221
+ });
222
+ })()`
223
+ // #endregion click-text-probe
224
+
225
+ /** Ask the OS for a currently free TCP port. */
226
+ async function freePort() {
227
+ return new Promise((resolve, reject) => {
228
+ const server = createServer()
229
+ server.on('error', reject)
230
+ server.listen(0, '127.0.0.1', () => {
231
+ const { port } = server.address()
232
+ server.close(() => resolve(port))
233
+ })
234
+ })
235
+ }
236
+
237
+ /** Resolve a Chromium-family executable: explicit config first, then PATH, then caches. */
238
+ export function resolveBrowserPath(configured) {
239
+ if (configured !== undefined && configured !== '') {
240
+ if (!existsSync(configured)) throw new Error(`browser executable not found: ${configured}`)
241
+ return configured
242
+ }
243
+ // Windows first: its install root is deterministic, so a hit here beats a
244
+ // PATH scan that would only ever find a launcher shim.
245
+ for (const candidate of WINDOWS_ROOTS) {
246
+ if (existsSync(candidate)) return candidate
247
+ }
248
+ for (const name of PATH_CANDIDATES) {
249
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
250
+ if (dir === '') continue
251
+ const candidate = join(dir, name)
252
+ if (existsSync(candidate)) return candidate
253
+ }
254
+ }
255
+ for (const root of CACHE_ROOTS) {
256
+ if (!existsSync(root)) continue
257
+ for (const entry of readdirSync(root).sort().reverse()) {
258
+ if (!entry.startsWith('chromium') && !entry.startsWith('chrome')) continue
259
+ for (const inner of CACHE_INNER) {
260
+ const candidate = join(root, entry, inner)
261
+ if (existsSync(candidate) && !candidate.endsWith('headless_shell')) return candidate
262
+ }
263
+ }
264
+ }
265
+ throw new Error(
266
+ 'no Chrome/Chromium binary found — install a Chromium-family browser, or set browserPath in the plugin config',
267
+ )
268
+ }
269
+
270
+ /** Whether an XVFB display lock is free. */
271
+ function displayAvailable(display) {
272
+ const number = display.replace(/^:/, '').split('.')[0]
273
+ return !existsSync(`/tmp/.X${number}-lock`)
274
+ }
275
+
276
+ /** Find Xvfb on PATH (any directory). */
277
+ function resolveXvfb() {
278
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
279
+ if (dir === '') continue
280
+ const candidate = join(dir, 'Xvfb')
281
+ if (existsSync(candidate)) return candidate
282
+ }
283
+ return undefined
284
+ }
285
+
286
+ /**
287
+ * Owns the Chrome process, its virtual display, and one attached tab per session.
288
+ */
289
+ /**
290
+ * Normalize the two ways a tool may name an element: a snapshot index, or a CSS
291
+ * selector that survives renumbering.
292
+ *
293
+ * Snapshot indices are positional, so any DOM change between the read and the
294
+ * action invalidates them. A selector is resolved fresh at action time, which is
295
+ * why the tools accept both.
296
+ *
297
+ * @param target - a number (snapshot index), or `{ index }` / `{ selector }`.
298
+ * @returns `{ index }` or `{ selector }`.
299
+ */
300
+ export function normalizeTarget(target) {
301
+ if (typeof target === 'number' && Number.isInteger(target) && target >= 0) return { index: target }
302
+ if (target !== null && typeof target === 'object') {
303
+ if (typeof target.selector === 'string' && target.selector.trim() !== '') return { selector: target.selector.trim() }
304
+ if (typeof target.index === 'number' && Number.isInteger(target.index) && target.index >= 0) return { index: target.index }
305
+ }
306
+ throw new Error('name the element with an index from browser_embedded_snapshot, or with a CSS selector')
307
+ }
308
+
309
+ /** The DOM lookup for a target: the selector itself, or the snapshot attribute. */
310
+ export function elementKey(target) {
311
+ const { index, selector } = normalizeTarget(target)
312
+ return selector !== undefined ? selector : `[data-dsh-bp-index="${index}"]`
313
+ }
314
+
315
+ /** What to call the target in an error message. */
316
+ function describeTarget(target) {
317
+ const { index, selector } = normalizeTarget(target)
318
+ return selector !== undefined ? JSON.stringify(selector) : `#${index}`
319
+ }
320
+
321
+ /**
322
+ * A snapshot `loc` value as a CSS selector, or undefined when it is not one.
323
+ *
324
+ * `loc` is the durable handle the snapshot prints next to each entry, in one of
325
+ * three shapes: `href:<url>`, `css:#<id>`, `css:<path>`. Only the last two (and
326
+ * the href form, as an attribute selector) can be queried; anything else stays
327
+ * undefined so a caller falls back to asking for a fresh snapshot.
328
+ */
329
+ export function selectorOfLoc(loc) {
330
+ if (loc.startsWith('css:')) return loc.slice(4)
331
+ if (loc.startsWith('href:')) {
332
+ const escaped = loc.slice(5).replace(/\\/g, '\\\\').replace(/"/g, '\\"')
333
+ return `a[href="${escaped}"]`
334
+ }
335
+ return undefined
336
+ }
337
+
338
+ export class BrowserManager {
339
+ /**
340
+ * @param options - resolved plugin config plus a logger and a change notifier.
341
+ */
342
+ constructor({ config, logger, onEvent }) {
343
+ this.config = config
344
+ this.logger = logger
345
+ this.onEvent = onEvent ?? (() => {})
346
+ this.cdp = undefined
347
+ /** sessionId -> { id, label, page, targetId, createdAt, lastUsedAt, url, title } */
348
+ this.sessions = new Map()
349
+ this.chrome = undefined
350
+ this.xvfb = undefined
351
+ this.display = undefined
352
+ this.port = undefined
353
+ this.executable = undefined
354
+ this.mode = undefined
355
+ /** One-off mode override from `restart({ mode })`; wins over the config. */
356
+ this.forceMode = undefined
357
+ this.startedAt = undefined
358
+ this.lastUsedAt = Date.now()
359
+ this.starting = undefined
360
+ this.stopping = false
361
+ /**
362
+ * Serializes process start/stop.
363
+ *
364
+ * Two callers can ask for a restart at the same time — the panel's
365
+ * 「独立窗口」 button and an agent tool, a window close and an idle reclaim —
366
+ * and interleaved `stop()`/`start()` pairs leave a half-started browser, an
367
+ * orphan process or a `restart` that reports success over the other one's
368
+ * shutdown. `lifecycleDepth` makes the lock re-entrant for the internal
369
+ * calls (`ensureBrowser` restarting a closed wire, `restart` calling
370
+ * `stopNow`), which must not queue behind their own caller.
371
+ */
372
+ this.lifecycle = Promise.resolve()
373
+ this.lifecycleDepth = 0
374
+ this.idleTimer = undefined
375
+ /**
376
+ * Asked before the idle timer stops the browser. Wired by the plugin to "is a
377
+ * panel socket attached right now", because a human watching the native panel is
378
+ * the one thing this process must not shut down behind their back.
379
+ */
380
+ this.watchGuard = undefined
381
+ /** Last page of every session seen in this process, so a browser restart can
382
+ * reopen it instead of dropping the session back to about:blank. */
383
+ this.lastUrls = new Map()
384
+ /** Guards the "the window was closed, come back headless" recovery. */
385
+ this.restoring = false
386
+ /**
387
+ * sessionId -> Map(index -> { loc, tag, label }), recorded by the last
388
+ * snapshot. A page that re-renders (React and friends) drops the marker
389
+ * attribute the index lives on, and a caller acting on `#14` then hits
390
+ * "is gone" even though the element itself is still there. These let a
391
+ * vanished index be re-found through its selector and verified by tag and
392
+ * label before the click goes anywhere.
393
+ */
394
+ this.refLocs = new Map()
395
+ /** Chromium stderr patterns already logged, so per-frame noise cannot flood the log. */
396
+ this.stderrSeen = new Map()
397
+ /** Session whose tab the hub currently keeps in front, for `/state`. */
398
+ this.watchedSessionId = undefined
399
+ }
400
+
401
+ /**
402
+ * Everything the panel needs to render a status line.
403
+ *
404
+ * @param sessionId - optional session whose own page state is included.
405
+ * @returns browser-level state, plus `session` when an id was given.
406
+ */
407
+ async status(sessionId) {
408
+ const base = {
409
+ running: this.cdp !== undefined,
410
+ mode: this.mode ?? null,
411
+ executable: this.executable ?? null,
412
+ profileDir: this.profileDir(),
413
+ port: this.port ?? null,
414
+ display: this.display ?? null,
415
+ startedAt: this.startedAt ?? null,
416
+ sessions: this.sessions.size,
417
+ watched: this.watchedSessionId ?? null,
418
+ }
419
+ if (sessionId === undefined) return base
420
+ const record = this.sessions.get(sessionId)
421
+ if (record === undefined) {
422
+ return {
423
+ ...base,
424
+ session: { id: sessionId, open: false, url: null, title: null, viewport: null, watched: false, createdAt: null },
425
+ }
426
+ }
427
+ let url
428
+ let title
429
+ let viewport
430
+ try {
431
+ const info = await record.page.evaluate(
432
+ 'JSON.stringify({url: location.href, title: document.title, w: innerWidth, h: innerHeight})',
433
+ )
434
+ const parsed = JSON.parse(info)
435
+ url = parsed.url
436
+ title = parsed.title
437
+ viewport = { width: parsed.w, height: parsed.h }
438
+ record.url = url
439
+ record.title = title
440
+ if (typeof url === 'string' && url !== '' && url !== 'about:blank') this.lastUrls.set(sessionId, url)
441
+ } catch {
442
+ /* the page may be navigating; report what we last saw */
443
+ url = record.url
444
+ title = record.title
445
+ }
446
+ return {
447
+ ...base,
448
+ session: {
449
+ id: sessionId,
450
+ open: true,
451
+ label: record.label ?? null,
452
+ url: url ?? null,
453
+ title: title ?? null,
454
+ viewport: viewport ?? null,
455
+ createdAt: record.createdAt,
456
+ lastUsedAt: record.lastUsedAt,
457
+ watched: this.watchedSessionId === sessionId,
458
+ },
459
+ }
460
+ }
461
+
462
+ /** Every open session tab, newest first — the sidebar overview's data. */
463
+ listSessions() {
464
+ const entries = [...this.sessions.values()].map((record) => ({
465
+ id: record.id,
466
+ label: record.label ?? null,
467
+ url: record.url ?? null,
468
+ title: record.title ?? null,
469
+ createdAt: record.createdAt,
470
+ lastUsedAt: record.lastUsedAt,
471
+ watched: this.watchedSessionId === record.id,
472
+ }))
473
+ entries.sort((a, b) => b.lastUsedAt - a.lastUsedAt)
474
+ return entries
475
+ }
476
+
477
+ /** Absolute path of the persistent Chrome profile. */
478
+ profileDir() {
479
+ const configured = this.config.profileDir
480
+ if (configured !== undefined && configured !== '') return configured.replace(/^~(?=\/)/, homedir())
481
+ const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
482
+ return join(home, 'embedded-browser', 'profile')
483
+ }
484
+
485
+ /** The live record for one session, or undefined when it has no tab. */
486
+ session(sessionId) {
487
+ return this.sessions.get(sessionId)
488
+ }
489
+
490
+ /** Start (or reuse) the browser process. */
491
+ async ensureBrowser() {
492
+ this.lastUsedAt = Date.now()
493
+ if (this.cdp !== undefined) {
494
+ if (this.cdp.closed !== true) return
495
+ // A closed wire with a live process is the worst state to be in: every
496
+ // command rejects with `cdp: connection is closed` forever, because
497
+ // nothing else notices — Chrome is healthy and therefore never fires
498
+ // `exit`. The panel just says「连不上」 with no reason and no recovery.
499
+ // Edge drops this socket on its own (endpoint restart, renderer crash),
500
+ // so the only way out is a clean restart of the pair.
501
+ this.logger?.warn?.('cdp wire is closed while the browser process is alive — restarting it')
502
+ await this.stop().catch(() => {})
503
+ }
504
+ if (this.starting !== undefined) return this.starting
505
+ this.starting = this.start().finally(() => {
506
+ this.starting = undefined
507
+ })
508
+ return this.starting
509
+ }
510
+
511
+ /**
512
+ * The tab belonging to one session, created on first use.
513
+ *
514
+ * Creation activates the tab once — without it the target never receives
515
+ * injected input (see the module header) — and records it so the hub can put
516
+ * the foreground back where a watching human expects it.
517
+ *
518
+ * @param sessionId - the calling DSH session.
519
+ * @param options - optional display label and first URL.
520
+ * @returns the session record.
521
+ */
522
+ async ensureSession(sessionId, { label, url } = {}) {
523
+ const existing = this.sessions.get(sessionId)
524
+ if (existing !== undefined) {
525
+ existing.lastUsedAt = Date.now()
526
+ this.touch()
527
+ return existing
528
+ }
529
+ await this.ensureBrowser()
530
+ const target = url ?? this.lastUrls.get(sessionId) ?? this.config.startUrl ?? 'about:blank'
531
+ const page = await this.cdp.newPage(target)
532
+ try {
533
+ await page.enable()
534
+ await this.applyViewport(page)
535
+ // A link that opens its own tab would take the foreground and freeze the
536
+ // panel's picture; see `installLinkGuard`.
537
+ await this.installLinkGuard(page)
538
+ // The one activation that matters: a target that was never activated drops
539
+ // every Input.* call for the rest of its life.
540
+ await this.cdp.activate(page.targetId).catch(() => {})
541
+ } catch (error) {
542
+ await page.close().catch(() => {})
543
+ throw error
544
+ }
545
+ const record = {
546
+ id: sessionId,
547
+ label: label ?? undefined,
548
+ page,
549
+ targetId: page.targetId,
550
+ createdAt: Date.now(),
551
+ lastUsedAt: Date.now(),
552
+ url: target,
553
+ title: undefined,
554
+ // The last viewport this tab was shaped to; `fitViewport` overwrites it and
555
+ // `restoreViewport` replays it after a navigation clears the override.
556
+ viewport: this.viewportSize(),
557
+ }
558
+ this.sessions.set(sessionId, record)
559
+ // A page-level dialog blocks every later CDP call on this target, so keep
560
+ // the last one it raised; `dialog()` resolves it on the human's behalf.
561
+ page.on('Page.javascriptDialogOpening', (params) => {
562
+ record.pendingDialog = {
563
+ type: params.type,
564
+ message: params.message,
565
+ defaultPrompt: params.defaultPrompt ?? null,
566
+ openedAt: Date.now(),
567
+ }
568
+ })
569
+ this.touch()
570
+ this.logger?.info?.(`session tab opened (${sessionId}${label !== undefined ? `, ${label}` : ''})`)
571
+ this.onEvent({ type: 'session-created', sessionId })
572
+ // A real window would otherwise show the blank tab Chromium was launched
573
+ // with, sitting in front of the page the session actually opened.
574
+ await this.dropLaunchTab()
575
+ return record
576
+ }
577
+
578
+ /**
579
+ * Remove the blank tab Chromium is launched with.
580
+ *
581
+ * Chromium refuses to start with zero page targets, so `start()` appends
582
+ * `about:blank` as scaffolding. Nobody sees it headless; a real window shows
583
+ * it as a second, useless tab beside the session's own page — and every
584
+ * headed restart brings it back, so it reappeared each time the panel
585
+ * promoted a page into a window. Sessions create their own tabs, so once a
586
+ * real one exists the scaffolding has no job left.
587
+ *
588
+ * Two pages are the floor: closing Chromium's last tab terminates the process
589
+ * and takes every session's page with it, so a lone page is never touched.
590
+ * A tab that belongs to a session is left alone even when it shows
591
+ * `about:blank`, because that is a page the session asked for.
592
+ *
593
+ * Headless is deliberately untouched: the tab is invisible there, and the
594
+ * request it would cost buys nothing.
595
+ *
596
+ * @returns how many tabs were actually closed.
597
+ */
598
+ async dropLaunchTab() {
599
+ if (this.mode !== 'headed' || this.cdp === undefined) return 0
600
+ const entries = await this.cdp.pages().catch(() => [])
601
+ if (entries.length < 2) return 0
602
+ const own = new Set()
603
+ for (const record of this.sessions.values()) own.add(record.targetId)
604
+ const strays = entries.filter((entry) => {
605
+ if (own.has(entry.id)) return false
606
+ const url = typeof entry.url === 'string' ? entry.url : ''
607
+ return url === 'about:blank' || url === 'chrome://newtab/'
608
+ })
609
+ if (strays.length === 0 || entries.length - strays.length < 1) return 0
610
+ let closed = 0
611
+ for (const stray of strays) {
612
+ try {
613
+ await this.cdp.closeTarget(stray.id)
614
+ closed += 1
615
+ } catch {
616
+ /* the tab may already be gone */
617
+ }
618
+ }
619
+ if (closed > 0) this.logger?.debug?.(`dropped ${closed} launch tab(s)`)
620
+ return closed
621
+ }
622
+
623
+ /**
624
+ * Keep a link that wants its own tab inside this one.
625
+ *
626
+ * The panel renders exactly one tab, and Chrome streams only the *front* tab.
627
+ * A new tab therefore takes the foreground, the screencast of the tab the panel
628
+ * is showing stops, and the picture freezes on its last frame — while the new
629
+ * tab has no way to be seen or closed from the panel. That is a dead end, and it
630
+ * is one click away on most sites: Bilibili's video cards, GitHub's file links,
631
+ * every search result and every "open in new window" button.
632
+ *
633
+ * Measured before the guard existed: clicking a Bilibili card left a frozen home
634
+ * page plus an orphan video tab whose CDP answered `Page.enable failed: timeout`
635
+ * (the playing video had the renderer busy), and the panel offered no way back.
636
+ *
637
+ * So `window.open` and `target="_blank"` links navigate **in place**. That is a
638
+ * deliberate behaviour change: a second tab has nowhere to be shown, and
639
+ * navigating in place is the only outcome the viewer can actually see. It also
640
+ * survives same-document and cross-document navigations, because the guard is
641
+ * registered with `addScriptToEvaluateOnNewDocument` (and applied once to the
642
+ * page that is already open).
643
+ *
644
+ * @param page - the session's attached page.
645
+ */
646
+ async installLinkGuard(page) {
647
+ const source = `(() => {
648
+ if (window.__dshSameTabGuard === true) return
649
+ window.__dshSameTabGuard = true
650
+ const go = (url) => {
651
+ try { window.location.assign(String(url)) } catch (error) { /* bad URL: leave it alone */ }
652
+ }
653
+ const nativeOpen = window.open
654
+ window.open = function (url, ...rest) {
655
+ // No URL means a blank popup the page intends to fill in itself; that one is
656
+ // rare and cannot be shown either way, so let it behave as it did.
657
+ if (url === undefined || url === null || url === '') return nativeOpen.call(this, url, ...rest)
658
+ go(url)
659
+ return null
660
+ }
661
+ document.addEventListener('click', (event) => {
662
+ const node = event.target
663
+ const anchor = node && typeof node.closest === 'function' ? node.closest('a[href]') : null
664
+ if (anchor === null) return
665
+ if (anchor.target !== '_blank' && anchor.target !== '_new') return
666
+ const href = anchor.href
667
+ if (typeof href !== 'string' || !/^(https?|file):/i.test(href)) return
668
+ // Rewrite the attribute **before** the default action runs, so the browser
669
+ // never enters the "open a new tab" path at all. Cancelling the click with
670
+ // preventDefault() was tried first and was not enough: on the CDP-injected
671
+ // input path the target was created anyway (measured tab count 2 → 3 while
672
+ // the page also navigated in place).
673
+ anchor.target = '_self'
674
+ }, true)
675
+ })()`
676
+ // Register first so the guard survives every later navigation, then apply it
677
+ // to the document that is already open.
678
+ await page.send('Page.addScriptToEvaluateOnNewDocument', { source }).catch(() => {})
679
+ await page.send('Runtime.evaluate', { expression: source }).catch(() => {})
680
+ }
681
+
682
+ /** Apply the emulated viewport so the panel's canvas space matches the page. */
683
+ async applyViewport(page, viewport = this.viewportSize()) {
684
+ /**
685
+ * A visible window is resized by the person using it.
686
+ *
687
+ * Pinning the page to 1440×900 inside a window they then drag wider would fill
688
+ * the extra space with nothing and ignore every resize — the exact opposite of
689
+ * "a real browser window". So in headed mode the window decides the shape and
690
+ * the emulation override is cleared; the tools read the real viewport instead
691
+ * of assuming one.
692
+ */
693
+ if (this.mode === 'headed') {
694
+ await page.send('Emulation.clearDeviceMetricsOverride').catch(() => {})
695
+ return
696
+ }
697
+ await page
698
+ .send('Emulation.setDeviceMetricsOverride', {
699
+ width: viewport.width,
700
+ height: viewport.height,
701
+ // Rasterizing above CSS size is what keeps text sharp on a HiDPI
702
+ // display: the frame arrives larger and the panel downscales it. CDP
703
+ // input coordinates stay in CSS pixels either way, so hit-testing is
704
+ // unaffected — but the panel must divide bitmap coordinates by this.
705
+ deviceScaleFactor: this.renderScale(),
706
+ mobile: false,
707
+ })
708
+ .catch(() => {})
709
+ }
710
+
711
+ /**
712
+ * Render multiplier of the emulated viewport (the `renderScale` setting).
713
+ *
714
+ * @returns A multiplier between 1 and 2.
715
+ */
716
+ renderScale() {
717
+ const numeric = Number(this.config.renderScale)
718
+ if (!Number.isFinite(numeric)) return 1.5
719
+ return Math.min(2, Math.max(1, numeric))
720
+ }
721
+
722
+ /**
723
+ * Reshape the emulated viewport to the panel's aspect ratio, keeping the
724
+ * configured width.
725
+ *
726
+ * The Sidebar is tall and narrow, so a fixed 1440×900 viewport is letter-boxed
727
+ * into it — the frame fills the width and wastes the rest of the height. Making
728
+ * the *width* follow the panel would fix the waste but collapse desktop pages
729
+ * into a single narrow column. Stretching only the height keeps the page's
730
+ * desktop layout and still fills the panel: the page simply thinks it is a
731
+ * very tall window.
732
+ *
733
+ * @param sessionId - the calling session.
734
+ * @param aspect - panel width ÷ height, as a positive number.
735
+ * @returns The applied viewport, or undefined when the request is unusable.
736
+ */
737
+ async fitViewport(sessionId, aspect) {
738
+ const record = this.sessions.get(sessionId)
739
+ if (record === undefined) return undefined
740
+ const numeric = Number(aspect)
741
+ if (!Number.isFinite(numeric) || numeric <= 0.05 || numeric > 20) return undefined
742
+ const width = this.viewportSize().width
743
+ // Clamp so a dragged-to-extremes panel cannot ask for a 20000px page.
744
+ //
745
+ // The **upper** clamp is not cosmetic. Shaping the viewport to a tall panel
746
+ // means telling the page it is 1700 px tall; a site that loads more content on
747
+ // scroll then decides one screen is plenty, its document height ends up equal
748
+ // to the viewport, and the wheel has nothing to scroll — so the scroll handler
749
+ // that would have loaded the next batch never fires. Measured on Bilibili:
750
+ // innerHeight 1726, scrollHeight 1726, maxScroll 0, feed stuck on skeletons.
751
+ // A ceiling just above every common desktop viewport keeps the panel filled
752
+ // without ever telling a page it is looking at a wall-sized screen.
753
+ const ceiling = this.maxFitHeight()
754
+ const wanted = Math.round(width / numeric)
755
+ const height = Math.min(ceiling, Math.max(400, wanted))
756
+ if (record.viewport?.width === width && record.viewport?.height === height) {
757
+ return { width, height, changed: false }
758
+ }
759
+ await this.applyViewport(record.page, { width, height })
760
+ record.viewport = { width, height }
761
+ return { width, height, changed: true }
762
+ }
763
+
764
+ /**
765
+ * The tallest viewport `fitViewport` will ask for.
766
+ *
767
+ * Configured by `maxViewportHeight`; 1000 by default — taller than any ordinary
768
+ * desktop window, shorter than the point where a feed stops overflowing.
769
+ *
770
+ * @returns a positive pixel height.
771
+ */
772
+ maxFitHeight() {
773
+ const configured = Number(this.config?.maxViewportHeight)
774
+ if (Number.isFinite(configured) && configured >= 400) return Math.min(4000, configured)
775
+ return 1000
776
+ }
777
+
778
+ /** Configured emulated viewport, falling back to the window size. */
779
+ viewportSize() {
780
+ const raw = String(this.config.viewport ?? this.config.windowSize ?? '1440x900')
781
+ const match = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw.trim())
782
+ if (match === null) return { width: 1440, height: 900 }
783
+ return { width: Number(match[1]), height: Number(match[2]) }
784
+ }
785
+
786
+ /** Bring one session's tab to the front (the hub does this for watched panels). */
787
+ async activateSession(sessionId) {
788
+ const record = this.sessions.get(sessionId)
789
+ if (record === undefined || this.cdp === undefined) return false
790
+ await this.cdp.activate(record.targetId).catch(() => {})
791
+ return true
792
+ }
793
+
794
+ /** Remember which session the hub is streaming, so `/state` can report it. */
795
+ setWatched(sessionId) {
796
+ this.watchedSessionId = sessionId
797
+ }
798
+
799
+ /**
800
+ * Close one session's tab and forget it.
801
+ *
802
+ * @param sessionId - the session to tear down.
803
+ * @param options - reason recorded in the log and returned to callers.
804
+ * @returns whether a tab was actually closed.
805
+ */
806
+ async closeSession(sessionId, { reason = 'closed' } = {}) {
807
+ const record = this.sessions.get(sessionId)
808
+ if (record === undefined) return false
809
+ this.sessions.delete(sessionId)
810
+ if (this.watchedSessionId === sessionId) this.watchedSessionId = undefined
811
+ await record.page.close().catch(() => {})
812
+ await this.cdp?.closeTarget(record.targetId).catch(() => {})
813
+ this.lastUrls.delete(sessionId)
814
+ this.refLocs.delete(sessionId)
815
+ this.logger?.info?.(`session tab closed (${sessionId}, ${reason})`)
816
+ this.onEvent({ type: 'session-closed', sessionId, reason })
817
+ return true
818
+ }
819
+
820
+ /** Close every session tab, keeping the browser process alive. */
821
+ async closeAllSessions(reason = 'closed') {
822
+ for (const sessionId of [...this.sessions.keys()]) {
823
+ await this.closeSession(sessionId, { reason }).catch(() => {})
824
+ }
825
+ }
826
+
827
+ async start() {
828
+ this.executable = resolveBrowserPath(this.config.browserPath)
829
+ const profileDir = this.profileDir()
830
+ mkdirSync(profileDir, { recursive: true })
831
+
832
+ const wanted = this.forceMode ?? this.config.mode ?? 'auto'
833
+ const xvfb = resolveXvfb()
834
+ let mode = 'headless'
835
+ let display = process.env.DISPLAY
836
+ /**
837
+ * X11 is a Linux story.
838
+ *
839
+ * On Windows and macOS a headed browser is just the same launch **without**
840
+ * `--headless`: there is no display to allocate, so requiring `$DISPLAY` or
841
+ * Xvfb there made `mode: headed` throw on every desktop host — the one place a
842
+ * person actually wants to see the window. `auto` keeps its old meaning
843
+ * everywhere (headless unless a display exists), because silently opening
844
+ * windows for callers who never asked would be a worse surprise than the throw
845
+ * it replaces.
846
+ */
847
+ const windowedHost = process.platform === 'win32' || process.platform === 'darwin'
848
+ if (wanted === 'headed' && windowedHost) {
849
+ mode = 'headed'
850
+ } else if (wanted === 'auto' || wanted === 'headed') {
851
+ if (display !== undefined && display !== '') {
852
+ mode = 'headed'
853
+ } else if (xvfb !== undefined) {
854
+ const base = Number((this.config.xvfbDisplay ?? ':99').replace(/^:/, '')) || 99
855
+ for (let offset = 0; offset < 12; offset += 1) {
856
+ const candidate = `:${base + offset}`
857
+ if (!displayAvailable(candidate)) continue
858
+ await this.startXvfb(xvfb, candidate)
859
+ display = candidate
860
+ mode = 'headed'
861
+ break
862
+ }
863
+ if (mode !== 'headed' && wanted === 'headed') throw new Error('no free X display for the headed browser')
864
+ } else if (wanted === 'headed') {
865
+ throw new Error('headed mode requested but neither $DISPLAY nor Xvfb is available')
866
+ }
867
+ }
868
+
869
+ const port = this.config.port !== undefined && this.config.port > 0 ? this.config.port : await freePort()
870
+ const args = [
871
+ `--user-data-dir=${profileDir}`,
872
+ `--remote-debugging-port=${port}`,
873
+ '--remote-allow-origins=*',
874
+ '--no-first-run',
875
+ '--no-default-browser-check',
876
+ '--disable-dev-shm-usage',
877
+ '--disable-features=Translate,OptimizationHints,MediaRouter',
878
+ '--password-store=basic',
879
+ '--use-mock-keychain',
880
+ '--hide-crash-restore-bubble',
881
+ `--window-size=${(this.config.windowSize ?? '1440x900').replace('x', ',')}`,
882
+ '--window-position=0,0',
883
+ ]
884
+ if (mode === 'headless') args.push('--headless=new')
885
+ // A hidden window has no business making noise: the host follows the human's
886
+ // clicks, so a video page loads back here too — and without these two flags it
887
+ // plays its audio out loud, in a window nobody can see, lagging behind the page
888
+ // the human is actually watching. A **visible** window is the opposite case:
889
+ // the person asked to see the browser, so muting it would be the surprise.
890
+ if (mode === 'headless') args.push('--mute-audio')
891
+ args.push('--autoplay-policy=document-user-activation-required')
892
+ /**
893
+ * This profile is the agent's, and it must never act as a member of the
894
+ * human's browser account.
895
+ *
896
+ * Measured, not theorised: this profile carried a signed-in Edge account
897
+ * (`account_info` in its `Local State`) with Sync on, and Edge Sync moved
898
+ * browsing history in **both** directions — the agent's visit to the same URL
899
+ * showed up in the human's `History` with the very same timestamp, to the
900
+ * second. A page an agent opened must not become part of a person's browsing
901
+ * history; the reverse is just as wrong.
902
+ *
903
+ * The site logins this profile holds are the whole point of it and stay — a
904
+ * cookie is not an account link. `--disable-sync` only stops the sync engine
905
+ * from joining the account's data set; it does not touch cookies.
906
+ *
907
+ * One caveat worth knowing: this flag stops the agent's side from pushing.
908
+ * Anything already pushed lives in the account's data and has to be removed
909
+ * from the account itself — no local switch can retract it.
910
+ */
911
+ args.push('--disable-sync')
912
+ // No background service registration either: an agent's throwaway browser
913
+ // should not install anything that starts itself later.
914
+ args.push('--no-service-autorun')
915
+ args.push('--disable-background-mode')
916
+ /**
917
+ * Keep cross-origin frames in their parent's renderer process.
918
+ *
919
+ * Measured, not guessed: with site isolation on, about one browser instance in
920
+ * six drops **every** input event aimed at a cross-origin frame. The top
921
+ * document honestly reports the point as the frame element, `inFrame: true`
922
+ * says so, and the frame's own document never receives a single mousedown — a
923
+ * coordinate click that silently does nothing and returns success. With
924
+ * isolation off the frame shares its parent's renderer and the dispatch is a
925
+ * plain in-process hit test (measured: stable across runs).
926
+ *
927
+ * The security boundary that matters here does not move: a cross-origin
928
+ * frame's DOM stays unreadable from the top document either way, which is the
929
+ * whole reason coordinate clicks exist. What is given up is process isolation
930
+ * of untrusted frames — in the agent's own throwaway browser, on pages it was
931
+ * told to visit.
932
+ */
933
+ args.push('--disable-site-isolation-trials')
934
+ args.push('--disable-features=IsolateOrigins,site-per-process')
935
+ if (typeof process.getuid === 'function' && process.getuid() === 0) args.push('--no-sandbox')
936
+ if (Array.isArray(this.config.extraArgs)) args.push(...this.config.extraArgs)
937
+ // Chrome always needs at least one page target; sessions open their own.
938
+ args.push('about:blank')
939
+
940
+ const env = { ...process.env }
941
+ if (mode === 'headed' && display !== undefined) env.DISPLAY = display
942
+ this.chrome = spawn(this.executable, args, { env, stdio: ['ignore', 'pipe', 'pipe'] })
943
+ // Chromium emits a page-load metric line per frame while a page paints
944
+ // (`Invalid first_paint ...`), and every line used to reach the boot log
945
+ // through a synchronous append — thousands of writes per page load. Pattern,
946
+ // not message, is what repeats: strip the numbers, keep one line per pattern
947
+ // per window, and fold the rest into a count.
948
+ const stderrLine = (text) => {
949
+ if (text === '') return
950
+ const now = Date.now()
951
+ const key = text.replace(/\d+(\.\d+)?/g, '#').slice(0, 140)
952
+ const seen = this.stderrSeen.get(key)
953
+ if (seen !== undefined && now - seen.at < 15_000) {
954
+ seen.muted += 1
955
+ return
956
+ }
957
+ const muted = seen?.muted ?? 0
958
+ this.stderrSeen.set(key, { at: now, muted: 0 })
959
+ this.logger?.debug?.(`chrome: ${text}${muted > 0 ? ` (muted ${muted} similar lines)` : ''}`)
960
+ // One entry per distinct message would itself become a leak.
961
+ if (this.stderrSeen.size > 200) this.stderrSeen.clear()
962
+ }
963
+ const pipeChrome = (chunk) => {
964
+ for (const line of String(chunk).split('\n')) stderrLine(line.trim())
965
+ }
966
+ this.chrome.stdout.on('data', pipeChrome)
967
+ this.chrome.stderr.on('data', pipeChrome)
968
+ this.chrome.on('exit', (code, signal) => {
969
+ this.logger?.info?.(`chrome exited (code=${code} signal=${signal})`)
970
+ // Closing the last window of a headed browser ends the process, and every
971
+ // session page goes with it. The URLs are the only thing that survives, and
972
+ // keeping them is what lets a page come *back* instead of starting over on
973
+ // about:blank. `lastUrls` is the source of truth here: by the time this event
974
+ // runs, the CDP socket has already closed and cleared the session records.
975
+ for (const record of this.sessions.values()) {
976
+ if (typeof record.url === 'string' && record.url !== '' && record.url !== 'about:blank') {
977
+ this.lastUrls.set(record.id, record.url)
978
+ }
979
+ }
980
+ const entries = [...this.lastUrls.entries()]
981
+ for (const [id, url] of entries) this.lastUrls.set(id, url)
982
+ const wasHeaded = this.mode === 'headed'
983
+ // `stopping` is set by `stop()` while it waits for this very event; that is a
984
+ // deliberate shutdown (restart, idle reclaim), not somebody closing a window.
985
+ const deliberate = this.stopping === true
986
+ void this.settleExit({ wasHeaded, entries, deliberate })
987
+ })
988
+
989
+ this.port = port
990
+ this.handedOver = false
991
+ this.mode = mode
992
+ this.display = mode === 'headed' ? display : undefined
993
+
994
+ const version = await fetchVersion(port, this.config.startTimeoutMs ?? 20_000)
995
+ this.cdp = await Cdp.connect(port, { version })
996
+ this.cdp.onClose(() => {
997
+ // Closing the window breaks the CDP socket **before** the process exit
998
+ // event arrives, and clearing the sessions here would leave the exit handler
999
+ // with no page to reopen (measured in the live probe 2026-11-29: the fallback
1000
+ // started headless and then had nothing to restore). Record the addresses
1001
+ // first; `lastUrls` is the durable copy.
1002
+ for (const record of this.sessions.values()) {
1003
+ if (typeof record.url === 'string' && record.url !== '' && record.url !== 'about:blank') {
1004
+ this.lastUrls.set(record.id, record.url)
1005
+ }
1006
+ }
1007
+ const entries = [...this.lastUrls.entries()]
1008
+ // A handover left `chrome` unset while the browser lived on under another
1009
+ // pid; this close is then the real death, and nothing else is looking for it.
1010
+ const afterHandover = this.handedOver === true
1011
+ this.sessions.clear()
1012
+ // `stopping` is the second guard: a deliberate stop closes this socket
1013
+ // itself, and that close is not the browser dying.
1014
+ if (!afterHandover || this.stopping === true) return
1015
+ this.handedOver = false
1016
+ const wasHeaded = this.mode === 'headed'
1017
+ this.cdp = undefined
1018
+ this.watchedSessionId = undefined
1019
+ this.onEvent({ type: 'browser-stopped', windowClosed: wasHeaded })
1020
+ if (wasHeaded) void this.recoverHeadless(entries)
1021
+ })
1022
+ this.startedAt = Date.now()
1023
+ this.logger?.info?.(`browser ready (mode=${mode} port=${port} profile=${profileDir})`)
1024
+ this.scheduleIdleShutdown()
1025
+ this.onEvent({ type: 'browser-started' })
1026
+ }
1027
+
1028
+ /**
1029
+ * Decide whether an exit event means the browser died or merely handed over.
1030
+ *
1031
+ * On Windows, Edge hands the launch to a second process: the one we spawned
1032
+ * reports `exit` while the browser keeps answering DevTools under a different
1033
+ * pid. Believing the exit used to tear down a live browser — sessions cleared,
1034
+ * `recoverHeadless` started a second copy, and the first one kept the profile
1035
+ * locked so the next launch died with `code=21`.
1036
+ *
1037
+ * @param options - what the exit handler already worked out.
1038
+ */
1039
+ async settleExit({ wasHeaded, entries, deliberate }) {
1040
+ if (deliberate !== true && (await this.devToolsAlive()) === true) {
1041
+ this.handedOver = true
1042
+ this.logger?.info?.('chrome exited but its DevTools endpoint still answers — process handover, keeping the session')
1043
+ this.chrome = undefined
1044
+ return
1045
+ }
1046
+ this.cdp?.close()
1047
+ this.cdp = undefined
1048
+ this.sessions.clear()
1049
+ this.watchedSessionId = undefined
1050
+ this.chrome = undefined
1051
+ this.onEvent({ type: 'browser-stopped', windowClosed: wasHeaded && !deliberate })
1052
+ // A closed window must not mean "every page is gone". Falling back to the
1053
+ // invisible browser keeps the conversation's pages alive and the panel usable
1054
+ // — the human only closed the *visible* copy of it.
1055
+ if (wasHeaded && !deliberate) void this.recoverHeadless(entries)
1056
+ }
1057
+
1058
+ /**
1059
+ * Is the DevTools endpoint of the port we launched still answering?
1060
+ *
1061
+ * Short timeout on purpose: this runs inside an exit handler, and a hung probe
1062
+ * would hold the state machine instead of resolving it.
1063
+ *
1064
+ * @returns true when the endpoint answered.
1065
+ */
1066
+ async devToolsAlive() {
1067
+ if (typeof this.port !== 'number' || this.port <= 0) return false
1068
+ try {
1069
+ const response = await fetch(`http://127.0.0.1:${this.port}/json/version`, {
1070
+ signal: AbortSignal.timeout(1_500),
1071
+ })
1072
+ return response.ok
1073
+ } catch {
1074
+ return false
1075
+ }
1076
+ }
1077
+
1078
+ async startXvfb(xvfb, display) {
1079
+ const screen = this.config.screen ?? '1440x900x24'
1080
+ this.xvfb = spawn(xvfb, [display, '-screen', '0', screen, '-nolisten', 'tcp', '-noreset'], {
1081
+ stdio: ['ignore', 'ignore', 'pipe'],
1082
+ })
1083
+ this.xvfb.stderr.on('data', (chunk) => this.logger?.debug?.(`xvfb: ${String(chunk).trim()}`))
1084
+ this.xvfb.on('exit', () => {
1085
+ this.xvfb = undefined
1086
+ })
1087
+ for (let attempt = 0; attempt < 60; attempt += 1) {
1088
+ if (existsSync(`/tmp/.X${display.replace(/^:/, '')}-lock`)) {
1089
+ await sleep(150)
1090
+ return
1091
+ }
1092
+ await sleep(100)
1093
+ }
1094
+ this.logger?.warn?.(`xvfb ${display} did not report a lock file; continuing`)
1095
+ }
1096
+
1097
+ /**
1098
+ * Run one process operation at a time.
1099
+ *
1100
+ * Re-entrant by depth rather than by identity: the body may call `stop()` or
1101
+ * `restart()` again (`ensureBrowser` does when the CDP wire died), and those
1102
+ * internal calls must run inline instead of deadlocking behind the caller that
1103
+ * already holds the lock.
1104
+ *
1105
+ * @param body - the operation to serialize.
1106
+ */
1107
+ async exclusive(body) {
1108
+ if (this.lifecycleDepth > 0) return body()
1109
+ const run = this.lifecycle.then(async () => {
1110
+ this.lifecycleDepth += 1
1111
+ try {
1112
+ return await body()
1113
+ } finally {
1114
+ this.lifecycleDepth -= 1
1115
+ }
1116
+ })
1117
+ // The chain must survive a rejection, or one failed restart poisons every
1118
+ // later stop.
1119
+ this.lifecycle = run.then(() => {}, () => {})
1120
+ return run
1121
+ }
1122
+
1123
+ /** Stop Chrome (and the private Xvfb) and drop every session tab. */
1124
+ stop(options = {}) {
1125
+ return this.exclusive(() => this.stopNow(options))
1126
+ }
1127
+
1128
+ /** The stop itself. Callers that already hold {@link exclusive} use this. */
1129
+ async stopNow({ keepProfile = true } = {}) {
1130
+ this.stopping = true
1131
+ // A deliberate stop is not a handover. Leaving this set would let our own
1132
+ // socket close look like the browser dying and send a bogus
1133
+ // `browser-stopped` + `recoverHeadless` on top of the stop that is already
1134
+ // running.
1135
+ this.handedOver = false
1136
+ clearTimeout(this.idleTimer)
1137
+ this.idleTimer = undefined
1138
+ const records = [...this.sessions.values()]
1139
+ for (const record of records) {
1140
+ if (typeof record.url === 'string' && record.url !== '' && record.url !== 'about:blank') this.lastUrls.set(record.id, record.url)
1141
+ }
1142
+ this.sessions.clear()
1143
+ this.watchedSessionId = undefined
1144
+ for (const record of records) await record.page.close().catch(() => {})
1145
+ if (this.cdp !== undefined) {
1146
+ // Ask Chrome to exit gracefully: cookies and storage only flush on a clean
1147
+ // shutdown, and a lost flush would log the human out.
1148
+ const wire = this.cdp
1149
+ // Register the wait **before** asking. `Browser.close` answers as soon as
1150
+ // the browser accepts the command, long before the process has flushed and
1151
+ // released the profile; a deliberate stop after a handover has no child to
1152
+ // wait on, so the socket going away is the only signal there is.
1153
+ let waitTimer
1154
+ const closed = new Promise((resolve) => {
1155
+ waitTimer = setTimeout(resolve, 3000)
1156
+ wire.onClose(() => {
1157
+ clearTimeout(waitTimer)
1158
+ resolve()
1159
+ })
1160
+ })
1161
+ await wire.send('Browser.close', undefined, 3000).catch(() => {})
1162
+ // Wait for the browser to hang up. Closing the socket ourselves at this point
1163
+ // would resolve in a millisecond and hand the next launch a profile the old
1164
+ // process still holds — that is exactly the `code=21` race.
1165
+ await closed
1166
+ // Only a socket that never closed on its own is forced shut.
1167
+ wire.close()
1168
+ this.cdp = undefined
1169
+ }
1170
+ if (this.chrome !== undefined) {
1171
+ const chrome = this.chrome
1172
+ const exited = new Promise((resolve) => chrome.once('exit', resolve))
1173
+ const timer = setTimeout(() => this.killTree(chrome), 4000)
1174
+ await exited.catch(() => {})
1175
+ clearTimeout(timer)
1176
+ this.chrome = undefined
1177
+ }
1178
+ if (this.xvfb !== undefined) {
1179
+ this.xvfb.kill('SIGTERM')
1180
+ this.xvfb = undefined
1181
+ }
1182
+ if (!keepProfile) {
1183
+ const dir = this.profileDir()
1184
+ rmSync(dir, { recursive: true, force: true })
1185
+ }
1186
+ this.stopping = false
1187
+ this.startedAt = undefined
1188
+ this.onEvent({ type: 'browser-stopped' })
1189
+ }
1190
+
1191
+ /**
1192
+ * Last resort when Chrome ignores `Browser.close`.
1193
+ *
1194
+ * On Windows a `SIGKILL` terminates the browser process while its renderer and
1195
+ * GPU children keep the profile locked, so the next start fails with "the
1196
+ * profile appears to be in use" until they die on their own. `taskkill /T`
1197
+ * takes the whole tree down. Measured 2026-11-30 while hammering restart.
1198
+ *
1199
+ * @param child - the Chrome process handle.
1200
+ */
1201
+ killTree(child) {
1202
+ const pid = child?.pid
1203
+ if (process.platform === 'win32' && typeof pid === 'number') {
1204
+ try {
1205
+ const killer = spawn('taskkill', ['/F', '/T', '/PID', String(pid)], {
1206
+ windowsHide: true,
1207
+ stdio: 'ignore',
1208
+ })
1209
+ killer.on('error', () => {
1210
+ try {
1211
+ child.kill('SIGKILL')
1212
+ } catch {
1213
+ /* already gone */
1214
+ }
1215
+ })
1216
+ killer.unref?.()
1217
+ } catch {
1218
+ try {
1219
+ child.kill('SIGKILL')
1220
+ } catch {
1221
+ /* already gone */
1222
+ }
1223
+ }
1224
+ return
1225
+ }
1226
+ try {
1227
+ child?.kill('SIGKILL')
1228
+ } catch {
1229
+ /* already gone */
1230
+ }
1231
+ }
1232
+
1233
+ /** Restart the browser process, keeping the profile (and every login in it). */
1234
+ restart({ mode } = {}) {
1235
+ return this.exclusive(async () => {
1236
+ await this.stopNow()
1237
+ // A one-off override is how the panel's 「独立窗口」 button turns a headless
1238
+ // deployment into a windowed one without rewriting the deployment's config.
1239
+ if (mode !== undefined) this.forceMode = mode
1240
+ return this.ensureBrowser()
1241
+ })
1242
+ }
1243
+
1244
+ /**
1245
+ * Bring the browser back after its window was closed by a person.
1246
+ *
1247
+ * Closing a headed browser's last window terminates the process: the pages are
1248
+ * gone even though nothing in this plugin failed. Restarting headless and
1249
+ * reopening the recorded URLs turns "I closed the window and lost everything"
1250
+ * into "the window went away, the pages are still there" — the panel reattaches
1251
+ * to them the same way it does after any browser restart.
1252
+ *
1253
+ * The list is bounded on purpose: coming back from a stray window close is not
1254
+ * the moment to spawn dozens of tabs.
1255
+ */
1256
+ async recoverHeadless(entries = []) {
1257
+ if (this.restoring === true) return
1258
+ this.restoring = true
1259
+ try {
1260
+ this.forceMode = 'headless'
1261
+ await this.ensureBrowser()
1262
+ for (const [sessionId, url] of entries.slice(0, 8)) {
1263
+ await this.ensureSession(sessionId, { url }).catch((error) => {
1264
+ this.logger?.debug?.(`restore ${sessionId} failed: ${error?.message ?? error}`)
1265
+ })
1266
+ }
1267
+ this.onEvent({ type: 'browser-restored', sessions: Math.min(entries.length, 8) })
1268
+ } catch (error) {
1269
+ this.logger?.warn?.(`could not fall back to the headless browser: ${error?.message ?? error}`)
1270
+ } finally {
1271
+ this.restoring = false
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * Put the browser back on the invisible layer, keeping every page address.
1277
+ *
1278
+ * This is the way back from a real window: the page moves into the panel (a
1279
+ * different browser), so this one has to stop being visible and become a
1280
+ * headless tab again — otherwise the panel and the window would show the same
1281
+ * page twice and tool routing would have to pick one.
1282
+ *
1283
+ * @returns the pages that were open, so the caller can reopen them.
1284
+ */
1285
+ async closeWindow() {
1286
+ const entries = [...this.sessions.values()]
1287
+ .filter((record) => typeof record.url === 'string' && record.url !== '' && record.url !== 'about:blank')
1288
+ .map((record) => [record.id, record.url])
1289
+ for (const [id, url] of entries) this.lastUrls.set(id, url)
1290
+ if (this.mode !== 'headed') return { restarted: false, entries }
1291
+ await this.restart({ mode: 'headless' })
1292
+ return { restarted: true, entries }
1293
+ }
1294
+
1295
+ /**
1296
+ * Show one session's page in a real browser window.
1297
+ *
1298
+ * A window is a property of the **process**, not of a tab: a headless Chromium
1299
+ * has none, so the first call restarts it with `--headless` gone. The profile
1300
+ * survives (logins included), the page URL is carried across, and every session
1301
+ * tab is reopened on that URL.
1302
+ *
1303
+ * @param sessionId - which session's page should be in front.
1304
+ * @param options - `url` to open instead of the session's current page.
1305
+ * @returns the layer now in force, the URL, and whether a restart happened.
1306
+ */
1307
+ async openWindow(sessionId, { url } = {}) {
1308
+ let target = typeof url === 'string' && url !== '' ? url : undefined
1309
+ if (target === undefined) {
1310
+ const info = await this.pageInfo(sessionId).catch(() => undefined)
1311
+ if (typeof info?.url === 'string' && info.url !== '') target = info.url
1312
+ }
1313
+ let restarted = false
1314
+ if (this.mode !== 'headed') {
1315
+ await this.restart({ mode: 'headed' })
1316
+ restarted = true
1317
+ }
1318
+ await this.ensureSession(sessionId, { url: target })
1319
+ await this.activateSession(sessionId)
1320
+ const page = await this.pageFor(sessionId)
1321
+ await page.send('Page.bringToFront').catch(() => {})
1322
+ return { ok: true, layer: 'window', url: target ?? null, restarted }
1323
+ }
1324
+
1325
+ scheduleIdleShutdown() {
1326
+ const minutes = this.config.idleShutdownMinutes ?? 0
1327
+ clearTimeout(this.idleTimer)
1328
+ if (!(minutes > 0)) return
1329
+ this.idleTimer = setTimeout(() => {
1330
+ // A person looking at the panel is *using* this browser even when no tool has
1331
+ // been called for a while. Stopping here drops every session, and the panel
1332
+ // reads "this session has no tab" as "the browser is gone" — which tears the
1333
+ // guest down and blanks the page the human was watching.
1334
+ const watched = typeof this.watchGuard === 'function' && this.watchGuard() === true
1335
+ if (watched) {
1336
+ this.lastUsedAt = Date.now()
1337
+ this.scheduleIdleShutdown()
1338
+ return
1339
+ }
1340
+ const idleFor = Date.now() - this.lastUsedAt
1341
+ if (idleFor >= minutes * 60_000) void this.stop()
1342
+ else this.scheduleIdleShutdown()
1343
+ }, Math.min(minutes * 60_000, 5 * 60_000))
1344
+ this.idleTimer.unref?.()
1345
+ }
1346
+
1347
+ /** Record activity so the idle timer does not fire mid-use. */
1348
+ touch() {
1349
+ this.lastUsedAt = Date.now()
1350
+ this.scheduleIdleShutdown()
1351
+ }
1352
+
1353
+ // ---------------------------------------------------------------- page ops
1354
+
1355
+ /** Resolve a session's page, creating its tab when needed. */
1356
+ async pageFor(sessionId, { label, url } = {}) {
1357
+ const record = await this.ensureSession(sessionId, { label, url })
1358
+ this.touch()
1359
+ this.assertNoPendingDialog(sessionId)
1360
+ return record.page
1361
+ }
1362
+
1363
+ /**
1364
+ * Fail fast when a page-level dialog is holding the renderer.
1365
+ *
1366
+ * While a dialog is open Chromium stops answering `Input.*`, so every input
1367
+ * tool used to sit there until CDP timed out and then report the meaningless
1368
+ * `Input.dispatchMouseEvent failed: timeout`. Naming the dialog turns that
1369
+ * dead end into an instruction.
1370
+ */
1371
+ assertNoPendingDialog(sessionId) {
1372
+ const open = this.sessions.get(sessionId)?.pendingDialog
1373
+ if (open === undefined) return
1374
+ const what = open.message ? `${open.type} ${JSON.stringify(open.message)}` : open.type
1375
+ throw new Error(
1376
+ `the page is blocked by an open ${what}; answer it with browser_embedded_dialog (accept or dismiss) and retry`,
1377
+ )
1378
+ }
1379
+
1380
+ /** Evaluate an expression in one session's page. */
1381
+ async evaluate(sessionId, expression) {
1382
+ const page = await this.pageFor(sessionId)
1383
+ return page.evaluate(expression)
1384
+ }
1385
+
1386
+ /**
1387
+ * Navigate one session's page, tolerating a swallowed load event.
1388
+ *
1389
+ * Some pages never fire `Page.loadEventFired` (streaming documents, a
1390
+ * same-document navigation, a redirect chain whose last hop is a download).
1391
+ * Before declaring failure, check whether the page actually arrived.
1392
+ *
1393
+ * @param sessionId - the calling session.
1394
+ * @param url - absolute http(s) URL.
1395
+ * @param options - `waitMs` bounds the load wait.
1396
+ */
1397
+ async navigate(sessionId, url, options = {}) {
1398
+ const page = await this.pageFor(sessionId)
1399
+ // A panel that shows a native guest must not follow this browser blindly: when
1400
+ // the human clicks a link in the guest, this browser follows *them*, and its
1401
+ // own URL can then bounce (a site redirecting a headless tab back to its home
1402
+ // page). Pushing that URL at the panel would drag the human back. So only a
1403
+ // navigation the AI asked for is announced as a new "AI navigation"; a follow
1404
+ // is silent.
1405
+ if (options.intent !== 'follow') this.navSeq = (this.navSeq ?? 0) + 1
1406
+ try {
1407
+ await page.navigate(url, options)
1408
+ } catch (error) {
1409
+ if (!/timeout/i.test(String(error?.message ?? ''))) throw error
1410
+ const current = await page.evaluate('location.href').catch(() => '')
1411
+ const wanted = String(url).split('#')[0]
1412
+ const landed = typeof current === 'string'
1413
+ && current !== ''
1414
+ && (current === wanted || current.startsWith(wanted) || current.startsWith('http'))
1415
+ if (!landed) throw error
1416
+ this.logger?.debug?.(`navigate recovered after a swallowed load event: ${current}`)
1417
+ }
1418
+ // `Emulation.setDeviceMetricsOverride` does not survive a cross-document
1419
+ // navigation: the tab falls back to the window size, which is exactly the
1420
+ // letter-boxed 16:10 shape a tall panel had already paid to get rid of.
1421
+ await this.restoreViewport(sessionId)
1422
+ const status = await this.status(sessionId)
1423
+ // Some failures do not raise at all: the command resolves and the tab simply
1424
+ // lands on the browser's error screen. Reporting that as a successful
1425
+ // navigation is worse than failing, because the caller then reads an empty
1426
+ // page and blames the reader.
1427
+ const landedUrl = String(status?.session?.url ?? '')
1428
+ if (landedUrl.startsWith('chrome-error://')) {
1429
+ throw new Error(
1430
+ `navigation failed: the browser could not reach ${url} — it ended on a network error page `
1431
+ + '(DNS, proxy, firewall, or the site is unreachable from this machine)',
1432
+ )
1433
+ }
1434
+ return status
1435
+ }
1436
+
1437
+ /** Replace a session's tab with a fresh one (the old page is discarded). */
1438
+ async replaceTab(sessionId, url) {
1439
+ await this.closeSession(sessionId, { reason: 'replaced' })
1440
+ const record = await this.ensureSession(sessionId, { url })
1441
+ return this.status(record.id)
1442
+ }
1443
+
1444
+ /**
1445
+ * Re-apply the session's own viewport after a navigation cleared the override.
1446
+ *
1447
+ * A session that never had its shape fitted has no recorded viewport, and one
1448
+ * whose tab is gone cannot be reached; both are silent no-ops.
1449
+ *
1450
+ * @param sessionId - the calling session.
1451
+ */
1452
+ async restoreViewport(sessionId) {
1453
+ const record = this.sessions.get(sessionId)
1454
+ if (record?.viewport === undefined) return
1455
+ const page = await this.pageFor(sessionId).catch(() => undefined)
1456
+ if (page === undefined) return
1457
+ await this.applyViewport(page, record.viewport)
1458
+ }
1459
+
1460
+ async goBack(sessionId) {
1461
+ const page = await this.pageFor(sessionId)
1462
+ await page.evaluate('history.back()')
1463
+ await sleep(600)
1464
+ await this.restoreViewport(sessionId)
1465
+ return this.status(sessionId)
1466
+ }
1467
+
1468
+ async goForward(sessionId) {
1469
+ const page = await this.pageFor(sessionId)
1470
+ await page.evaluate('history.forward()')
1471
+ await sleep(600)
1472
+ await this.restoreViewport(sessionId)
1473
+ return this.status(sessionId)
1474
+ }
1475
+
1476
+ async reload(sessionId) {
1477
+ const page = await this.pageFor(sessionId)
1478
+ await page.send('Page.reload')
1479
+ await sleep(600)
1480
+ return this.status(sessionId)
1481
+ }
1482
+
1483
+ /** Structured page read: text plus a numbered inventory of actionable elements. */
1484
+ async snapshot(sessionId, { maxChars, maxElements, offset = 0, floor: floorHint, cap: capHint, budget: budgetHint } = {}) {
1485
+ const page = await this.pageFor(sessionId)
1486
+ const textLimit = maxChars ?? this.config.snapshotMaxChars ?? 4000
1487
+ // An explicit count is honoured exactly (a script needs predictable numbers);
1488
+ // otherwise the size of the page decides, within the floor and the cap.
1489
+ const asked = Number(maxElements ?? this.config.maxElements ?? 0)
1490
+ const limitAsked = Number.isFinite(asked) && asked > 0 ? Math.floor(asked) : 0
1491
+ const floor = Math.max(1, Math.floor(Number(floorHint) || SNAPSHOT_FLOOR))
1492
+ const cap = Math.max(floor, Math.floor(Number(capHint) || SNAPSHOT_CAP))
1493
+ const budget = Math.max(500, Math.floor(Number(budgetHint) || SNAPSHOT_BUDGET_CHARS))
1494
+ const startAt = Math.max(0, Math.floor(Number(offset) || 0))
1495
+ const raw = await page.evaluate(`(() => {
1496
+ const requested = ${limitAsked};
1497
+ const floor = ${floor};
1498
+ const cap = ${cap};
1499
+ const budget = ${budget};
1500
+ const offset = ${startAt};
1501
+ const selector = ${JSON.stringify(INTERACTIVE_SELECTOR)};
1502
+ for (const stale of document.querySelectorAll('[data-dsh-bp-index]')) stale.removeAttribute('data-dsh-bp-index');
1503
+ const visible = (el) => {
1504
+ const rect = el.getBoundingClientRect();
1505
+ if (rect.width < 1 && rect.height < 1) return false;
1506
+ const style = getComputedStyle(el);
1507
+ return style.visibility !== 'hidden' && style.display !== 'none';
1508
+ };
1509
+ const label = (el) => {
1510
+ const raw = el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.innerText || el.value || el.getAttribute('title') || el.getAttribute('name') || '';
1511
+ return String(raw).replace(/\\s+/g, ' ').trim().slice(0, 100);
1512
+ };
1513
+ // A stable way back to this element across calls: index numbers are
1514
+ // renumbered by every snapshot, so callers that need to act on element N
1515
+ // in a *later* turn must use this instead. Prefer an id, else a short
1516
+ // :nth-child() path (bounded depth keeps it readable).
1517
+ const cssPath = (el) => {
1518
+ if (el.id) return '#' + CSS.escape(el.id);
1519
+ const parts = [];
1520
+ let node = el;
1521
+ while (node && node.nodeType === 1 && parts.length < 8) {
1522
+ if (node.id) { parts.unshift('#' + CSS.escape(node.id)); break; }
1523
+ let part = node.tagName.toLowerCase();
1524
+ const parent = node.parentElement;
1525
+ if (parent) part += ':nth-child(' + ([...parent.children].indexOf(node) + 1) + ')';
1526
+ parts.unshift(part);
1527
+ node = parent;
1528
+ }
1529
+ return parts.join(' > ');
1530
+ };
1531
+ const loc = (el) => {
1532
+ const href = el.getAttribute('href');
1533
+ if (href && el.tagName === 'A') return 'href:' + href;
1534
+ if (el.id) return 'css:#' + CSS.escape(el.id);
1535
+ return 'css:' + cssPath(el);
1536
+ };
1537
+ const all = [...document.querySelectorAll(selector)].filter(visible);
1538
+ const total = all.length;
1539
+ const limit = requested > 0 ? requested : Math.min(cap, Math.max(floor, total));
1540
+ // On-screen first, but only when the list is going to be cut: reordering a
1541
+ // page that fits would move every number for nothing.
1542
+ const view = { left: 0, top: 0, right: innerWidth, bottom: innerHeight };
1543
+ const onScreen = (el) => {
1544
+ const rect = el.getBoundingClientRect();
1545
+ return rect.bottom > view.top && rect.top < view.bottom && rect.right > view.left && rect.left < view.right;
1546
+ };
1547
+ const start = Math.min(Math.max(0, offset), total);
1548
+ // Document order, always. Paging is a contract — "these, and no others, once" —
1549
+ // and promoting what is on screen breaks it: the next page starts at a
1550
+ // document index, so the promoted run gets listed twice and the entries it
1551
+ // skipped are never listed at all. Being on screen is reported per entry.
1552
+ const ordered = all;
1553
+ const screenSet = new Set();
1554
+ const elements = [];
1555
+ let used = 0;
1556
+ for (let cursor = start; cursor < ordered.length && elements.length < limit; cursor += 1) {
1557
+ const candidate = ordered[cursor];
1558
+ const text = label(candidate);
1559
+ const handle = loc(candidate);
1560
+ const cost = text.length + handle.length + 40;
1561
+ // The budget is the ceiling that matters: an inventory is prose, and a
1562
+ // dense page must not turn one read into a context dump. One entry always
1563
+ // goes out, so a single enormous label cannot return an empty list.
1564
+ if (elements.length > 0 && used + cost > budget) break;
1565
+ used += cost;
1566
+ if (onScreen(candidate)) screenSet.add(candidate);
1567
+ elements.push(candidate);
1568
+ }
1569
+ elements.forEach((el, index) => el.setAttribute('data-dsh-bp-index', String(index)));
1570
+ // Frames are reported even though their contents are not, because "there is a
1571
+ // dialog here and you cannot see into it" is the difference between an agent
1572
+ // clicking the right spot and an agent reporting that clicking is impossible.
1573
+ // A cross-origin frame is a hard wall for the top document: no selector, no
1574
+ // snapshot, no JavaScript reaches inside. Real input at these coordinates does.
1575
+ const frames = [];
1576
+ for (const node of document.querySelectorAll('iframe,frame')) {
1577
+ const rect = node.getBoundingClientRect();
1578
+ const style = getComputedStyle(node);
1579
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
1580
+ if (rect.width === 0 && rect.height === 0) continue;
1581
+ if (frames.length >= 12) break;
1582
+ let src = '';
1583
+ try { src = String(node.src || node.getAttribute('src') || '').slice(0, 200); } catch (error) { src = ''; }
1584
+ let origin = '';
1585
+ try { origin = src === '' ? '' : new URL(src, location.href).origin; } catch (error) { origin = ''; }
1586
+ let readable = false;
1587
+ try {
1588
+ // A frame whose src has been set but whose navigation has not committed
1589
+ // still holds the initial about:blank document — same-origin, readable,
1590
+ // and completely useless to describe. Requiring a real document keeps the
1591
+ // flag from saying "you can read this" during the load window.
1592
+ const doc = node.contentDocument;
1593
+ readable = Boolean(doc && doc.body && !/^about:/.test(String((doc.location && doc.location.href) || '')));
1594
+ } catch (error) { readable = false; }
1595
+ frames.push({
1596
+ x: Math.round(rect.x), y: Math.round(rect.y),
1597
+ w: Math.round(rect.width), h: Math.round(rect.height),
1598
+ origin: origin === '' ? undefined : origin === location.origin ? 'same' : origin,
1599
+ readable,
1600
+ src: src === '' ? undefined : src,
1601
+ });
1602
+ }
1603
+ return JSON.stringify({
1604
+ title: document.title,
1605
+ url: location.href,
1606
+ // A collapsed (0x0) page still answers every DOM question, so a snapshot
1607
+ // looks healthy while every click is refused. The caller has to be told
1608
+ // which kind of page it is reading.
1609
+ collapsed: innerWidth <= 0 || innerHeight <= 0,
1610
+ text: String(document.body ? document.body.innerText : '').replace(/\\n{3,}/g, '\\n\\n').slice(0, ${textLimit}),
1611
+ // total counts everything that matched, not just what fits under the
1612
+ // limit — the same contract the panel's guest returns. Without it a caller
1613
+ // cannot tell "this page has 25 interactive elements" from "this page has
1614
+ // 114 and you are looking at the first 25", which is exactly the state a
1615
+ // model has to be warned about before it indexes into a truncated list.
1616
+ total: all.length,
1617
+ // Where this slice starts and whether the list continues, so a caller can
1618
+ // page through a page with more interactive elements than one answer holds
1619
+ // instead of concluding that the missing ones do not exist.
1620
+ offset: start,
1621
+ more: start + elements.length < total,
1622
+ frames: frames.length === 0 ? undefined : frames,
1623
+ elements: elements.map((el, index) => ({
1624
+ index,
1625
+ loc: loc(el),
1626
+ tag: el.tagName.toLowerCase(),
1627
+ type: el.getAttribute('type') || undefined,
1628
+ label: label(el),
1629
+ value: el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' ? String(el.value || '').slice(0, 100) : undefined,
1630
+ disabled: el.disabled === true ? true : undefined,
1631
+ onScreen: screenSet.has(el) ? true : undefined,
1632
+ })),
1633
+ });
1634
+ })()`)
1635
+ const parsed = JSON.parse(raw)
1636
+ // The index markers live on the page and die with the next re-render; these
1637
+ // entries are what lets a caller keep using `#14` across one. Recorded here,
1638
+ // where the snapshot that numbered them still knows every selector.
1639
+ const memo = new Map()
1640
+ for (const element of parsed.elements ?? []) {
1641
+ if (typeof element?.index === 'number') {
1642
+ memo.set(element.index, { loc: element.loc, tag: element.tag, label: element.label ?? '' })
1643
+ }
1644
+ }
1645
+ if (memo.size > 0) this.refLocs.set(sessionId, memo)
1646
+ return parsed
1647
+ }
1648
+
1649
+ /**
1650
+ * Re-find a snapshot index whose marker attribute disappeared.
1651
+ *
1652
+ * The page re-rendered (a framework replaced the node) or a newer snapshot
1653
+ * renumbered the markers; the element itself is usually still there, and the
1654
+ * last snapshot that numbered it recorded its selector, tag and label. Only a
1655
+ * match on the selector plus the tag — and the label, when both sides have
1656
+ * one — is accepted: pointing at a neighbour is worse than asking the caller
1657
+ * to read the page again.
1658
+ *
1659
+ * @returns the located element, or undefined when no honest match exists.
1660
+ */
1661
+ async recoverIndex(sessionId, index) {
1662
+ const memo = this.refLocs.get(sessionId)?.get(index)
1663
+ if (memo === undefined || typeof memo.loc !== 'string' || memo.loc === '') return undefined
1664
+ const selector = selectorOfLoc(memo.loc)
1665
+ if (selector === undefined) return undefined
1666
+ let located
1667
+ try {
1668
+ located = await this.locateSelector(sessionId, selector)
1669
+ } catch {
1670
+ return undefined
1671
+ }
1672
+ if (located.tag !== memo.tag) return undefined
1673
+ if (memo.label !== '' && located.label !== '') {
1674
+ // Snapshot labels are capped; compare the readable head rather than all of it.
1675
+ const head = memo.label.slice(0, 24)
1676
+ if (!located.label.startsWith(head) && !memo.label.startsWith(located.label.slice(0, 24))) return undefined
1677
+ }
1678
+ // Restore the marker so the next target on this index resolves directly.
1679
+ await this.evaluate(
1680
+ sessionId,
1681
+ `(() => { const el = document.querySelectorAll(${JSON.stringify(selector)})[0]; if (el) el.setAttribute('data-dsh-bp-index', ${JSON.stringify(String(index))}); })()`,
1682
+ ).catch(() => {})
1683
+ return { ...located, recovered: true }
1684
+ }
1685
+
1686
+ /** Screen-space centre of an indexed element, scrolled into view. */
1687
+ async locate(sessionId, index) {
1688
+ const page = await this.pageFor(sessionId)
1689
+ const raw = await page.evaluate(`(() => {
1690
+ const el = document.querySelector('[data-dsh-bp-index="${index}"]');
1691
+ if (!el) return JSON.stringify({ found: false });
1692
+ el.scrollIntoView({ block: 'center', inline: 'center' });
1693
+ const rect = el.getBoundingClientRect();
1694
+ if (rect.width === 0 && rect.height === 0) return JSON.stringify({ found: false, hidden: true });
1695
+ return JSON.stringify({
1696
+ found: true,
1697
+ x: Math.round(rect.x + rect.width / 2),
1698
+ y: Math.round(rect.y + rect.height / 2),
1699
+ tag: el.tagName.toLowerCase(),
1700
+ label: String(el.getAttribute('aria-label') || el.innerText || el.value || '').replace(/\\s+/g, ' ').trim().slice(0, 80),
1701
+ });
1702
+ })()`)
1703
+ const located = JSON.parse(raw)
1704
+ if (located.found !== true) {
1705
+ if (located.hidden === true) throw new Error(`element #${index} has zero size — it is hidden (display:none or collapsed), so a click would land on whatever is behind it`)
1706
+ const recovered = await this.recoverIndex(sessionId, index)
1707
+ if (recovered !== undefined) return recovered
1708
+ throw new Error(`element #${index} is gone — the page changed after the snapshot that numbered it (a navigation, a re-render, or a newer snapshot renumbered them); call browser_embedded_snapshot again`)
1709
+ }
1710
+ return located
1711
+ }
1712
+
1713
+ /** Screen-space centre of a CSS-selected element, scrolled into view. */
1714
+ async locateSelector(sessionId, selector) {
1715
+ const page = await this.pageFor(sessionId)
1716
+ // `matches` is carried out on purpose. A selector that names several elements
1717
+ // used to resolve to the first one and report success, which reads to a model
1718
+ // as "I clicked the thing" when it may have clicked a neighbour. Returning to
1719
+ // the first match is still the behaviour (it is what a browser does), but the
1720
+ // count travels back so the caller can be told.
1721
+ const raw = await page.evaluate(`(() => {
1722
+ const needle = ${JSON.stringify(String(selector))};
1723
+ const all = document.querySelectorAll(needle);
1724
+ const el = all[0];
1725
+ if (!el) return JSON.stringify({ found: false, matches: 0 });
1726
+ el.scrollIntoView({ block: 'center', inline: 'center' });
1727
+ const rect = el.getBoundingClientRect();
1728
+ if (rect.width === 0 && rect.height === 0) return JSON.stringify({ found: false, hidden: true, matches: all.length });
1729
+ return JSON.stringify({
1730
+ found: true,
1731
+ matches: all.length,
1732
+ x: Math.round(rect.x + rect.width / 2),
1733
+ y: Math.round(rect.y + rect.height / 2),
1734
+ tag: el.tagName.toLowerCase(),
1735
+ label: String(el.getAttribute('aria-label') || el.innerText || el.value || '').replace(/\\s+/g, ' ').trim().slice(0, 80),
1736
+ });
1737
+ })()`)
1738
+ const located = JSON.parse(raw)
1739
+ if (located.found !== true) {
1740
+ if (located.hidden === true) throw new Error(`element ${JSON.stringify(selector)} has zero size — it is hidden (display:none or collapsed), so a click would land on whatever is behind it`)
1741
+ throw new Error(`no element matches ${JSON.stringify(selector)}`)
1742
+ }
1743
+ return located
1744
+ }
1745
+
1746
+ /** Screen-space centre of whatever a target names, index or selector alike. */
1747
+ async locateTarget(sessionId, target) {
1748
+ const { index, selector } = normalizeTarget(target)
1749
+ return selector !== undefined ? this.locateSelector(sessionId, selector) : this.locate(sessionId, index)
1750
+ }
1751
+
1752
+ /**
1753
+ * Does the measured point still land on the target?
1754
+ *
1755
+ * Measuring and dispatching are separate round-trips. A page that inserts or
1756
+ * reflows content between them moves the element out from under the
1757
+ * coordinates, and the click lands on whatever slid into that spot — on a
1758
+ * busy page that is a neighbouring button, not a failure. `elementFromPoint`
1759
+ * is the cheap way to notice before the click goes somewhere unintended.
1760
+ */
1761
+ async pointHitsTarget(sessionId, x, y, target) {
1762
+ const key = elementKey(target)
1763
+ return this.evaluate(
1764
+ sessionId,
1765
+ `(() => {
1766
+ const want = document.querySelector(${JSON.stringify(key)});
1767
+ if (want === null) return false;
1768
+ const hit = document.elementFromPoint(${x}, ${y});
1769
+ if (hit === null) return false;
1770
+ return hit === want || want.contains(hit) || hit.contains(want);
1771
+ })()`,
1772
+ )
1773
+ }
1774
+
1775
+ /**
1776
+ * Locate a target, re-measuring while the point no longer lands on it.
1777
+ *
1778
+ * @param sessionId - the calling session.
1779
+ * @param target - index or CSS selector.
1780
+ * @param attempts - how many measurements to spend before trusting the last.
1781
+ * @returns the located point.
1782
+ */
1783
+ async locateStable(sessionId, target, attempts = 3) {
1784
+ let located = await this.locateTarget(sessionId, target)
1785
+ for (let attempt = 1; attempt < attempts; attempt += 1) {
1786
+ if (await this.pointHitsTarget(sessionId, located.x, located.y, target)) return located
1787
+ await sleep(30)
1788
+ located = await this.locateTarget(sessionId, target)
1789
+ }
1790
+ return located
1791
+ }
1792
+
1793
+ /** Click one targeted element with real input events. */
1794
+ async click(sessionId, target, { double = false } = {}) {
1795
+ const located = await this.locateStable(sessionId, target)
1796
+ const result = await this.clickAt(sessionId, located, { double })
1797
+ // Confirming where the click landed is worth one extra round-trip: on a page
1798
+ // that reflows between measure and dispatch the click can still land on a
1799
+ // neighbour, and the caller deserves to know rather than assume.
1800
+ let verified = true
1801
+ try {
1802
+ verified = await this.pointHitsTarget(sessionId, located.x, located.y, target)
1803
+ } catch {
1804
+ verified = false
1805
+ }
1806
+ // A selector that names several elements is not an error — it is an ambiguity
1807
+ // the caller has to be able to see. Reporting the count is what turns "it
1808
+ // clicked something" into "it clicked the first of five". The count always
1809
+ // travels back; `ambiguous` only when there is more than one.
1810
+ const matches = Number(located.matches)
1811
+ if (Number.isFinite(matches) && matches > 1) {
1812
+ return {
1813
+ ...result,
1814
+ verified,
1815
+ matches,
1816
+ ambiguous: true,
1817
+ hint: `the selector matched ${matches} elements; the first one was clicked — pass a more specific selector (or an index) to choose another`,
1818
+ }
1819
+ }
1820
+ return { ...result, verified }
1821
+ }
1822
+
1823
+ /** Click a CSS-selected element — the stable path across snapshot renumbering. */
1824
+ async clickSelector(sessionId, selector, { double = false } = {}) {
1825
+ // Routed through `click` on purpose: that is where the stale-point guard and
1826
+ // the post-click `verified` report live. Re-implementing the dispatch here
1827
+ // silently skipped both.
1828
+ return this.click(sessionId, { selector }, { double })
1829
+ }
1830
+
1831
+ /** Dispatch a real pointer click at an already-resolved screen point. */
1832
+ async clickAt(sessionId, located, { double = false } = {}) {
1833
+ const page = await this.pageFor(sessionId)
1834
+ const point = { x: located.x, y: located.y, button: 'left' }
1835
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: located.x, y: located.y, buttons: 0 })
1836
+ // No pause between move and press: every millisecond here is a window in
1837
+ // which a live page can reflow the element out from under the coordinates.
1838
+ // `locateStable` already confirmed the point lands on the target.
1839
+ // `clickCount` drives how the renderer interprets the gesture: a real double
1840
+ // click is press/release at 1 followed by press/release at 2. Sending two
1841
+ // count=2 pairs instead makes Chromium fire `dblclick` twice.
1842
+ const counts = double ? [1, 2] : [1]
1843
+ for (const [i, clickCount] of counts.entries()) {
1844
+ if (i > 0) await sleep(40)
1845
+ await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, clickCount, buttons: 1 })
1846
+ await sleep(8)
1847
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, clickCount, buttons: 0 })
1848
+ }
1849
+ await sleep(120)
1850
+ return located
1851
+ }
1852
+
1853
+ /**
1854
+ * What sits under a viewport point.
1855
+ *
1856
+ * `elementFromPoint` answers for the top document only, so a point inside a
1857
+ * cross-origin frame reports the frame element itself. That is not a failure of
1858
+ * this probe: it is the fact the caller needs — the click went somewhere the
1859
+ * page is not allowed to let anyone read.
1860
+ */
1861
+ async hitTest(sessionId, x, y) {
1862
+ const raw = await this.evaluate(
1863
+ sessionId,
1864
+ `(() => {
1865
+ const hit = document.elementFromPoint(${Number(x)}, ${Number(y)});
1866
+ if (hit === null) return null;
1867
+ const tag = hit.tagName.toLowerCase();
1868
+ return {
1869
+ hit: tag,
1870
+ label: String(hit.getAttribute('aria-label') || hit.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 60),
1871
+ inFrame: tag === 'iframe' || tag === 'frame' ? true : undefined,
1872
+ };
1873
+ })()`,
1874
+ )
1875
+ return raw ?? undefined
1876
+ }
1877
+
1878
+ /**
1879
+ * Validate a hand-supplied viewport point.
1880
+ *
1881
+ * Coordinates are CSS pixels of the page viewport, which is not the screenshot
1882
+ * when the panel is narrow: a 1440-wide page inside a 700 px panel has a 700 px
1883
+ * viewport. Saying so beats silently clicking the wrong place.
1884
+ */
1885
+ async checkPoint(sessionId, x, y) {
1886
+ const px = Math.round(Number(x))
1887
+ const py = Math.round(Number(y))
1888
+ if (!Number.isFinite(px) || !Number.isFinite(py)) {
1889
+ throw new Error('x and y must be finite numbers: pass viewport CSS pixels')
1890
+ }
1891
+ const size = await this.evaluate(sessionId, '({ w: innerWidth, h: innerHeight })')
1892
+ const w = Number(size?.w)
1893
+ const h = Number(size?.h)
1894
+ if (px < 0 || py < 0 || px >= w || py >= h) {
1895
+ throw new Error(`${px},${py} is outside the ${w}x${h} viewport — x and y are viewport CSS pixels, not screenshot pixels`)
1896
+ }
1897
+ return { x: px, y: py }
1898
+ }
1899
+
1900
+ /**
1901
+ * Click a raw viewport point with real input.
1902
+ *
1903
+ * This is the only way into a cross-origin frame: its document cannot be
1904
+ * queried, but input is dispatched by the browser at a point, so it reaches
1905
+ * whatever renderer owns that point — including an out-of-process frame.
1906
+ */
1907
+ async clickPoint(sessionId, { x, y, double = false } = {}) {
1908
+ const point = await this.checkPoint(sessionId, x, y)
1909
+ // Measured before the click: afterwards the page may have navigated away from
1910
+ // under the pointer and the answer would describe the new page.
1911
+ const spot = await this.hitTest(sessionId, point.x, point.y).catch(() => undefined)
1912
+ await this.clickAt(sessionId, point, { double })
1913
+ return {
1914
+ x: point.x,
1915
+ y: point.y,
1916
+ ...(double === true ? { double: true } : {}),
1917
+ ...(spot === undefined
1918
+ ? {}
1919
+ : { hit: spot.hit, ...(spot.label === '' ? {} : { label: spot.label }), ...(spot.inFrame === true ? { inFrame: true } : {}) }),
1920
+ }
1921
+ }
1922
+
1923
+ /** Move the pointer to a raw viewport point (see clickPoint for why). */
1924
+ async hoverPoint(sessionId, { x, y } = {}) {
1925
+ const point = await this.checkPoint(sessionId, x, y)
1926
+ const page = await this.pageFor(sessionId)
1927
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y, buttons: 0 })
1928
+ const spot = await this.hitTest(sessionId, point.x, point.y).catch(() => undefined)
1929
+ return {
1930
+ x: point.x,
1931
+ y: point.y,
1932
+ hovered: true,
1933
+ ...(spot === undefined ? {} : { hit: spot.hit, ...(spot.inFrame === true ? { inFrame: true } : {}) }),
1934
+ }
1935
+ }
1936
+
1937
+ /** Click a raw viewport point and insert text — the frame-capable typing path. */
1938
+ async typePoint(sessionId, { x, y } = {}, text, { submit = false } = {}) {
1939
+ const point = await this.checkPoint(sessionId, x, y)
1940
+ const page = await this.pageFor(sessionId)
1941
+ const base = { x: point.x, y: point.y, button: 'left', clickCount: 1 }
1942
+ await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 })
1943
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 })
1944
+ await sleep(60)
1945
+ if (text !== undefined && text !== '') await page.send('Input.insertText', { text })
1946
+ await sleep(60)
1947
+ if (submit) await this.press(sessionId, 'Enter')
1948
+ return { ...point, typed: text ?? '', submitted: submit === true }
1949
+ }
1950
+
1951
+ /**
1952
+ * Click by the text a person can see.
1953
+ *
1954
+ * The search runs *in the page* (see {@link CLICK_TEXT_PROBE}) instead of over a
1955
+ * snapshot, because a snapshot is a reading view: it lists semantic controls
1956
+ * only, and the button a site built out of a `<span>` is not one. Reading is
1957
+ * capped on purpose — a page is not a prompt dump — and finding must not be, or
1958
+ * the answer would depend on how big the page happens to be.
1959
+ */
1960
+ async clickText(sessionId, text) {
1961
+ const want = String(text ?? '').trim()
1962
+ if (want === '') throw new Error('clickText needs some text to look for')
1963
+ const page = await this.pageFor(sessionId)
1964
+ // Function replacements: the needle is caller text, and `$&`/`$1` in it would
1965
+ // otherwise be read as a substitution pattern.
1966
+ const raw = await page.evaluate(
1967
+ CLICK_TEXT_PROBE.replace('__INTERACTIVE__', () => JSON.stringify(INTERACTIVE_SELECTOR))
1968
+ .replace('__WANT__', () => JSON.stringify(want))
1969
+ .replace('__NEEDLE__', () => JSON.stringify(want.toLowerCase())),
1970
+ )
1971
+ const found = typeof raw === 'string' ? JSON.parse(raw) : raw
1972
+ if (found?.ok !== true) throw new Error(found?.reason ?? `no clickable element matching ${JSON.stringify(want)}`)
1973
+ // Measured before the click: afterwards the page may have navigated away from
1974
+ // under the pointer and the answer would describe the new page.
1975
+ const spot = await this.hitTest(sessionId, found.x, found.y).catch(() => undefined)
1976
+ await this.clickAt(sessionId, { x: found.x, y: found.y }, {})
1977
+ return {
1978
+ found: true,
1979
+ label: found.label,
1980
+ tag: found.tag,
1981
+ match: found.match,
1982
+ x: found.x,
1983
+ y: found.y,
1984
+ matches: found.matches,
1985
+ ...(found.ambiguous === true ? { ambiguous: true, candidates: found.candidates } : {}),
1986
+ verified: true,
1987
+ ...(spot === undefined ? {} : { hit: spot.hit }),
1988
+ }
1989
+ }
1990
+
1991
+ /**
1992
+ * Focus an indexed field and insert text.
1993
+ *
1994
+ * The click is not decoration: `Input.insertText` is a silent no-op unless the
1995
+ * renderer has a focused text-accepting element (references/PITFALLS.md #12).
1996
+ */
1997
+ async type(sessionId, target, text, { submit = false } = {}) {
1998
+ const page = await this.pageFor(sessionId)
1999
+ const located = await this.locateStable(sessionId, target)
2000
+ const base = { x: located.x, y: located.y, button: 'left', clickCount: 1 }
2001
+ await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 })
2002
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 })
2003
+ await sleep(60)
2004
+ if (text !== undefined && text !== '') await page.send('Input.insertText', { text })
2005
+ await sleep(60)
2006
+ if (submit) await this.press(sessionId, 'Enter')
2007
+ return { ...located, submitted: submit === true }
2008
+ }
2009
+
2010
+ /**
2011
+ * Replace a field's value outright, React/Vue controlled inputs included.
2012
+ *
2013
+ * Goes through the native value setter so the framework's synthetic event
2014
+ * system observes the change; `insertText` appends and would leave the old
2015
+ * value behind.
2016
+ *
2017
+ * @param sessionId - the calling session.
2018
+ * @param target - field index from the latest snapshot, or a CSS selector.
2019
+ * @param text - the value to end up with (empty string clears the field).
2020
+ * @returns the value now in the field.
2021
+ */
2022
+ async fill(sessionId, target, text) {
2023
+ const page = await this.pageFor(sessionId)
2024
+ const key = elementKey(target)
2025
+ const raw = await page.evaluate(`(() => {
2026
+ const el = document.querySelector(${JSON.stringify(key)});
2027
+ if (!el) return JSON.stringify({ ok: false, reason: ${JSON.stringify(`no element matches ${key}`)} });
2028
+ if (el.isContentEditable) {
2029
+ el.focus();
2030
+ el.textContent = ${JSON.stringify(String(text))};
2031
+ el.dispatchEvent(new Event('input', { bubbles: true }));
2032
+ return JSON.stringify({ ok: true, value: el.textContent, mode: 'contenteditable' });
2033
+ }
2034
+ if (!('value' in el)) return JSON.stringify({ ok: false, reason: 'element has no value property: ' + el.tagName.toLowerCase() });
2035
+ const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
2036
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
2037
+ el.focus();
2038
+ if (setter) setter.call(el, ${JSON.stringify(String(text))});
2039
+ else el.value = ${JSON.stringify(String(text))};
2040
+ el.dispatchEvent(new Event('input', { bubbles: true }));
2041
+ el.dispatchEvent(new Event('change', { bubbles: true }));
2042
+ return JSON.stringify({ ok: true, value: el.value, mode: 'value' });
2043
+ })()`)
2044
+ const parsed = JSON.parse(raw)
2045
+ if (parsed.ok !== true) throw new Error(parsed.reason)
2046
+ await sleep(60)
2047
+ return parsed
2048
+ }
2049
+
2050
+ /** Dispatch one named key press. */
2051
+ async press(sessionId, key) {
2052
+ const page = await this.pageFor(sessionId)
2053
+ const spec = KEYS[key]
2054
+ if (spec === undefined) throw new Error(`unsupported key ${JSON.stringify(key)}; use one of ${Object.keys(KEYS).join(', ')}`)
2055
+ const common = {
2056
+ key: spec.key,
2057
+ code: spec.code,
2058
+ windowsVirtualKeyCode: spec.windowsVirtualKeyCode,
2059
+ nativeVirtualKeyCode: spec.windowsVirtualKeyCode,
2060
+ }
2061
+ await page.send('Input.dispatchKeyEvent', { type: spec.text === undefined ? 'rawKeyDown' : 'keyDown', ...common, text: spec.text })
2062
+ await page.send('Input.dispatchKeyEvent', { type: 'keyUp', ...common })
2063
+ await sleep(80)
2064
+ return { key }
2065
+ }
2066
+
2067
+ /** Scroll the viewport, either in whole pages or by an explicit delta. */
2068
+ async scroll(sessionId, direction, { pixels } = {}) {
2069
+ const page = await this.pageFor(sessionId)
2070
+ const viewport = await page.viewport()
2071
+ const step = pixels ?? Math.round(viewport.height * 0.85)
2072
+ const deltas = {
2073
+ down: { deltaX: 0, deltaY: step },
2074
+ up: { deltaX: 0, deltaY: -step },
2075
+ left: { deltaX: -step, deltaY: 0 },
2076
+ right: { deltaX: step, deltaY: 0 },
2077
+ top: { deltaX: 0, deltaY: -1_000_000 },
2078
+ bottom: { deltaX: 0, deltaY: 1_000_000 },
2079
+ }
2080
+ const delta = deltas[direction]
2081
+ if (delta === undefined) throw new Error(`unsupported direction ${JSON.stringify(direction)}`)
2082
+ await page.send('Input.dispatchMouseEvent', {
2083
+ type: 'mouseWheel',
2084
+ x: Math.round(viewport.width / 2),
2085
+ y: Math.round(viewport.height / 2),
2086
+ ...delta,
2087
+ })
2088
+ await sleep(350)
2089
+ return this.status(sessionId)
2090
+ }
2091
+
2092
+ /**
2093
+ * Pixels per CSS pixel on the live page.
2094
+ *
2095
+ * Headless pins this through emulation (`renderScale`), so the configured value
2096
+ * is the truth. Headed clears the override — the page then follows the real
2097
+ * window and reports the operating system's scaling, which on a 135% display is
2098
+ * 1.35. A capture is multiplied by this ratio, so without dividing it back out
2099
+ * the model's screenshot pixels and the page's CSS pixels disagree, and every
2100
+ * coordinate read off the picture lands 1.35× off target.
2101
+ */
2102
+ async deviceScaleFactor(page) {
2103
+ if (this.mode !== 'headed') return this.renderScale()
2104
+ try {
2105
+ const raw = await page.evaluate('window.devicePixelRatio || 1')
2106
+ const ratio = Number(raw)
2107
+ return Number.isFinite(ratio) && ratio > 0 ? ratio : 1
2108
+ } catch {
2109
+ return 1
2110
+ }
2111
+ }
2112
+
2113
+ /**
2114
+ * The page's live CSS viewport.
2115
+ *
2116
+ * Headless keeps an emulated viewport that the plugin itself sets, so the stored
2117
+ * size is authoritative. Headed clears the override — the page follows the real
2118
+ * window — and the stored size is then just the configured one. Clipping a
2119
+ * capture to it silently cuts the window's actual page down to 1280×800.
2120
+ */
2121
+ async liveViewport(page) {
2122
+ try {
2123
+ const raw = await page.evaluate('JSON.stringify({ width: window.innerWidth, height: window.innerHeight })')
2124
+ const size = JSON.parse(raw)
2125
+ if (Number(size?.width) > 0 && Number(size?.height) > 0) {
2126
+ return { width: Number(size.width), height: Number(size.height) }
2127
+ }
2128
+ } catch {
2129
+ /* fall through to the configured size */
2130
+ }
2131
+ return this.viewportSize()
2132
+ }
2133
+
2134
+ /** PNG screenshot as raw bytes; `selector` clips to one element. */
2135
+ async screenshot(sessionId, { format = 'png', fullPage = false, selector } = {}) {
2136
+ const page = await this.pageFor(sessionId)
2137
+ const scaleFactor = await this.deviceScaleFactor(page)
2138
+ let clip
2139
+ if (typeof selector === 'string' && selector !== '') {
2140
+ const raw = await page.evaluate(`(() => {
2141
+ const el = document.querySelector(${JSON.stringify(selector)});
2142
+ if (!el) return 'null';
2143
+ el.scrollIntoView({ block: 'center', inline: 'center' });
2144
+ const rect = el.getBoundingClientRect();
2145
+ return JSON.stringify({ x: rect.x, y: rect.y, width: rect.width, height: rect.height });
2146
+ })()`)
2147
+ if (raw === 'null') throw new Error(`no element matches ${JSON.stringify(selector)}`)
2148
+ const rect = JSON.parse(raw)
2149
+ clip = {
2150
+ x: Math.max(0, Math.round(rect.x)),
2151
+ y: Math.max(0, Math.round(rect.y)),
2152
+ width: Math.max(1, Math.round(rect.width)),
2153
+ height: Math.max(1, Math.round(rect.height)),
2154
+ scale: 1 / scaleFactor,
2155
+ }
2156
+ }
2157
+ // The panel may have reshaped this session's viewport (see `fitViewport`), so
2158
+ // the ceiling of an unclipped capture is the *live* viewport, not the
2159
+ // configured one — otherwise a tall panel would silently lose the bottom of
2160
+ // every model-facing screenshot. In headed mode "live" is the real window.
2161
+ const viewport =
2162
+ this.mode === 'headed' ? await this.liveViewport(page) : this.sessions.get(sessionId)?.viewport ?? this.viewportSize()
2163
+ // Chrome multiplies a clip's output by the live device scale factor, so a
2164
+ // `scale` of 1 yields `width × dpr` pixels. Divide it back out: the model has
2165
+ // no use for a frame larger than the page's CSS size, it only costs tokens and
2166
+ // (in headed mode) breaks its coordinate arithmetic. The panel, which must look
2167
+ // sharp on screen, takes the multiplier straight from the stream.
2168
+ const modelScale = 1 / scaleFactor
2169
+ const modelClip =
2170
+ clip !== undefined
2171
+ ? clip
2172
+ : fullPage
2173
+ ? undefined
2174
+ : { x: 0, y: 0, width: viewport.width, height: viewport.height, scale: modelScale }
2175
+ const result = await page.send('Page.captureScreenshot', {
2176
+ format,
2177
+ captureBeyondViewport: fullPage,
2178
+ ...(modelClip === undefined ? {} : { clip: modelClip }),
2179
+ })
2180
+ return { data: Buffer.from(result.data, 'base64'), mediaType: format === 'jpeg' ? 'image/jpeg' : 'image/png' }
2181
+ }
2182
+
2183
+ // ------------------------------------------------------ dialogs, network, tabs
2184
+
2185
+ /**
2186
+ * Answer the page-level dialog this session most recently raised.
2187
+ *
2188
+ * @param sessionId - the calling session.
2189
+ * @param options - `accept` maps to OK/Cancel, `text` fills a prompt.
2190
+ * @returns what was answered, plus the dialog that was open.
2191
+ */
2192
+ async dialog(sessionId, { accept = true, text } = {}) {
2193
+ const record = this.sessions.get(sessionId)
2194
+ if (record === undefined) throw new Error('this session has no open browser tab')
2195
+ const open = record.pendingDialog
2196
+ const params = { accept: accept === true }
2197
+ if (typeof text === 'string' && text !== '') params.promptText = text
2198
+ await record.page.send('Page.handleJavaScriptDialog', params)
2199
+ record.pendingDialog = undefined
2200
+ return { accepted: accept === true, promptText: params.promptText ?? null, saw: open ?? null }
2201
+ }
2202
+
2203
+ /** The dialog currently blocking this session's page, if any. */
2204
+ pendingDialog(sessionId) {
2205
+ return this.sessions.get(sessionId)?.pendingDialog
2206
+ }
2207
+
2208
+ /**
2209
+ * Fetch from inside the page, so the request carries the profile's cookies.
2210
+ *
2211
+ * Bound by the page's CORS rules: a cross-origin request the page itself could
2212
+ * not make fails here too. Same-origin is always safe.
2213
+ *
2214
+ * @param sessionId - the calling session.
2215
+ * @param options - URL, method, headers, body and a response size cap.
2216
+ * @returns the response, with the body truncated rather than refused.
2217
+ */
2218
+ async httpFetch(sessionId, { url, method = 'GET', headers, body, maxBytes = 200_000 } = {}) {
2219
+ const page = await this.pageFor(sessionId)
2220
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) throw new Error('url must start with http:// or https://')
2221
+ const cap = Math.max(1000, Number(maxBytes) || 200_000)
2222
+ const raw = await page.evaluate(`(async () => {
2223
+ try {
2224
+ const response = await fetch(${JSON.stringify(url)}, {
2225
+ method: ${JSON.stringify(String(method))},
2226
+ headers: ${JSON.stringify(headers ?? {})},
2227
+ ${body === undefined ? '' : `body: ${JSON.stringify(typeof body === 'string' ? body : JSON.stringify(body))},`}
2228
+ credentials: 'include',
2229
+ });
2230
+ const text = await response.text();
2231
+ return JSON.stringify({
2232
+ ok: true,
2233
+ status: response.status,
2234
+ statusText: response.statusText,
2235
+ url: response.url,
2236
+ contentType: response.headers.get('content-type'),
2237
+ truncated: text.length > ${cap},
2238
+ body: text.slice(0, ${cap}),
2239
+ });
2240
+ } catch (error) {
2241
+ return JSON.stringify({ ok: false, reason: String((error && error.message) || error) });
2242
+ }
2243
+ })()`, { awaitPromise: true })
2244
+ const parsed = JSON.parse(raw)
2245
+ if (parsed.ok !== true) throw new Error(`fetch failed: ${parsed.reason}`)
2246
+ return parsed
2247
+ }
2248
+
2249
+ /** Every page target in this browser, annotated with the owning session. */
2250
+ async listTabs() {
2251
+ if (this.cdp === undefined) return []
2252
+ const result = await this.cdp.send('Target.getTargets').catch(() => ({ targetInfos: [] }))
2253
+ const owner = new Map([...this.sessions.values()].map((record) => [record.targetId, record.id]))
2254
+ return (result.targetInfos ?? [])
2255
+ .filter((target) => target.type === 'page')
2256
+ .map((target) => ({
2257
+ targetId: target.targetId,
2258
+ url: target.url,
2259
+ title: target.title,
2260
+ attached: target.attached === true,
2261
+ session: owner.get(target.targetId) ?? null,
2262
+ }))
2263
+ }
2264
+
2265
+ /**
2266
+ * Point this session's tab at a different existing target.
2267
+ *
2268
+ * The previous tab stays open — it may belong to another session — so this is
2269
+ * a rebind, not a close.
2270
+ *
2271
+ * @param sessionId - the calling session.
2272
+ * @param targetId - a `targetId` reported by {@link listTabs}.
2273
+ */
2274
+ async bindTab(sessionId, targetId) {
2275
+ const record = this.sessions.get(sessionId)
2276
+ if (record === undefined) throw new Error('this session has no open browser tab')
2277
+ if (this.cdp === undefined) throw new Error('the browser is not running')
2278
+ const page = await this.cdp.attach(targetId)
2279
+ try {
2280
+ await page.enable()
2281
+ await this.applyViewport(page)
2282
+ await this.cdp.activate(targetId).catch(() => {})
2283
+ } catch (error) {
2284
+ await page.close().catch(() => {})
2285
+ throw error
2286
+ }
2287
+ await record.page.close().catch(() => {})
2288
+ record.page = page
2289
+ record.targetId = targetId
2290
+ record.pendingDialog = undefined
2291
+ this.touch()
2292
+ return this.status(sessionId)
2293
+ }
2294
+
2295
+ /** Close one page target by id; a session-owned tab is torn down through it. */
2296
+ async closeTab(targetId) {
2297
+ if (this.cdp === undefined) return false
2298
+ const owner = [...this.sessions.values()].find((record) => record.targetId === targetId)
2299
+ if (owner !== undefined) return this.closeSession(owner.id, { reason: 'tab closed by agent' })
2300
+ await this.cdp.closeTarget(targetId).catch(() => {})
2301
+ return true
2302
+ }
2303
+
2304
+ /**
2305
+ * Attach files to a file input, bypassing the native picker entirely.
2306
+ *
2307
+ * @param sessionId - the calling session.
2308
+ * @param index - element number of the file input.
2309
+ * @param files - absolute paths to attach.
2310
+ */
2311
+ async upload(sessionId, target, files) {
2312
+ const page = await this.pageFor(sessionId)
2313
+ // A page is untrusted input: it can name any path, and a prompt injection
2314
+ // would love `~/.ssh/id_rsa`. Refuse protected locations before CDP sees
2315
+ // the path, so nothing is attached even for a moment.
2316
+ const paths = (Array.isArray(files) ? files : [files]).map((file) => assertUploadAllowed(file))
2317
+ if (paths.length === 0) throw new Error('upload needs at least one file path')
2318
+ const key = elementKey(target)
2319
+ const { root } = await page.send('DOM.getDocument', { depth: 0 })
2320
+ const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: key })
2321
+ if (nodeId === undefined || nodeId === 0) throw new Error(`no element matches ${describeTarget(target)} — call browser_embedded_snapshot again`)
2322
+ await page.send('DOM.setFileInputFiles', { files: paths, nodeId })
2323
+ await sleep(120)
2324
+ return { files: paths, target: describeTarget(target) }
2325
+ }
2326
+
2327
+ /**
2328
+ * Choose where downloads land, creating the directory if needed.
2329
+ *
2330
+ * `Browser.setDownloadBehavior` is browser-scoped, so one call covers every
2331
+ * session tab.
2332
+ *
2333
+ * @param downloadPath - absolute directory, defaulting to ~/Downloads/dsh-embedded-browser.
2334
+ */
2335
+ /**
2336
+ * Point downloads somewhere, and optionally start one.
2337
+ *
2338
+ * On the headless tab a download is a real download: `Browser.setDownloadBehavior`
2339
+ * names the directory and the navigation triggers it. The panel cannot do this — the
2340
+ * host cancels `will-download` for that session — which is why the router intercepts
2341
+ * this call and fetches the bytes in the page instead.
2342
+ *
2343
+ * @param sessionId - the calling session.
2344
+ * @param options - `downloadPath`, and `url` to start one immediately.
2345
+ * @returns the directory, plus what was started when a URL was given.
2346
+ */
2347
+ async download(sessionId, { url, downloadPath } = {}) {
2348
+ const configured = await this.setDownloadPath(downloadPath)
2349
+ if (typeof url !== 'string' || url.trim() === '') return configured
2350
+ const page = await this.pageFor(sessionId)
2351
+ await page.send('Page.navigate', { url: url.trim() })
2352
+ return { url: url.trim(), downloadPath: configured.downloadPath, via: 'headless' }
2353
+ }
2354
+
2355
+ async setDownloadPath(downloadPath) {
2356
+ if (this.cdp === undefined) throw new Error('the browser is not running')
2357
+ // Confined on purpose: a tool call must not be able to overwrite an arbitrary
2358
+ // file just because a page talked the agent into it.
2359
+ const dir = assertDownloadDir(downloadPath)
2360
+ mkdirSync(dir, { recursive: true })
2361
+ await this.cdp.send('Browser.setDownloadBehavior', {
2362
+ behavior: 'allow',
2363
+ downloadPath: dir,
2364
+ eventsEnabled: true,
2365
+ })
2366
+ this.downloadPath = dir
2367
+ return { downloadPath: dir }
2368
+ }
2369
+
2370
+ /** Current cookies (names and domains only — values are truncated). */
2371
+ async cookies(sessionId) {
2372
+ const page = await this.pageFor(sessionId)
2373
+ const result = await page.send('Network.getAllCookies')
2374
+ return (result.cookies ?? []).map((cookie) => ({
2375
+ name: cookie.name,
2376
+ domain: cookie.domain,
2377
+ path: cookie.path,
2378
+ expires: cookie.expires,
2379
+ httpOnly: cookie.httpOnly,
2380
+ secure: cookie.secure,
2381
+ session: cookie.session,
2382
+ }))
2383
+ }
2384
+
2385
+ // ------------------------------------------------------- extended page ops
2386
+
2387
+ /**
2388
+ * Evaluate an arbitrary expression in one session's page.
2389
+ *
2390
+ * `returnByValue` means only JSON-serializable values survive — a DOM node
2391
+ * comes back as `undefined`, so callers extract what they need in-page.
2392
+ *
2393
+ * @param sessionId - the calling session.
2394
+ * @param expression - the expression to evaluate.
2395
+ * @param options - whether to await a returned promise.
2396
+ * @returns the value the expression produced.
2397
+ */
2398
+ async evalJs(sessionId, expression, { awaitPromise = true } = {}) {
2399
+ const page = await this.pageFor(sessionId)
2400
+ const value = await page.evaluate(String(expression), { awaitPromise })
2401
+ return { ok: true, value: value === undefined ? null : value }
2402
+ }
2403
+
2404
+ /**
2405
+ * Cheap page state: URL, title, readiness, viewport and scroll offsets.
2406
+ *
2407
+ * Also reports a coarse CAPTCHA signal (iframe/host fingerprints) so a caller
2408
+ * can decide to hand over to the human *before* typing into a bot-check page.
2409
+ *
2410
+ * @param sessionId - the calling session.
2411
+ * @returns page metadata.
2412
+ */
2413
+ async pageInfo(sessionId) {
2414
+ const page = await this.pageFor(sessionId)
2415
+ const raw = await page.evaluate(`(() => {
2416
+ const frames = [...document.querySelectorAll('iframe')].map((f) => String(f.src || ''));
2417
+ const captcha = frames.some((src) => /recaptcha|hcaptcha|turnstile|geetest|captcha/i.test(src))
2418
+ || document.querySelector('[class*=captcha],[id*=captcha],[class*=verify]') !== null;
2419
+ return JSON.stringify({
2420
+ url: location.href,
2421
+ title: document.title,
2422
+ readyState: document.readyState,
2423
+ viewport: { width: innerWidth, height: innerHeight },
2424
+ scroll: { x: Math.round(scrollX), y: Math.round(scrollY), height: Math.round(document.documentElement.scrollHeight) },
2425
+ humanCheck: { detected: captcha, kind: captcha ? 'captcha-fingerprint' : null },
2426
+ });
2427
+ })()`)
2428
+ return JSON.parse(raw)
2429
+ }
2430
+
2431
+ /**
2432
+ * Read one element by CSS selector without taking a whole snapshot.
2433
+ *
2434
+ * @param sessionId - the calling session.
2435
+ * @param selector - CSS selector (first match wins).
2436
+ * @param what - one of text, html, value, attribute, visible, enabled, count.
2437
+ * @param attribute - attribute name when `what` is `attribute`.
2438
+ * @returns a small object carrying the requested field.
2439
+ */
2440
+ async readElement(sessionId, selector, what = 'text', attribute) {
2441
+ const page = await this.pageFor(sessionId)
2442
+ const raw = await page.evaluate(`(() => {
2443
+ const all = document.querySelectorAll(${JSON.stringify(String(selector))});
2444
+ const el = all[0];
2445
+ if (!el) return JSON.stringify({ ok: false, what: ${JSON.stringify(String(what))}, reason: 'no match' });
2446
+ const style = getComputedStyle(el);
2447
+ const value = (${JSON.stringify(String(what))});
2448
+ const pick = (name) => {
2449
+ if (name === 'html') return String(el.innerHTML || '').slice(0, 20000);
2450
+ if (name === 'value') return el.value !== undefined ? String(el.value) : '';
2451
+ if (name === 'attribute') return el.getAttribute(${JSON.stringify(attribute ?? '')}) ?? null;
2452
+ if (name === 'visible') return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length) && style.visibility !== 'hidden';
2453
+ if (name === 'enabled') return el.disabled !== true;
2454
+ if (name === 'count') return all.length;
2455
+ return String(el.innerText ?? el.textContent ?? '').replace(/\\s+/g, ' ').trim().slice(0, 20000);
2456
+ };
2457
+ return JSON.stringify({ ok: true, what: value, count: all.length, tag: el.tagName.toLowerCase(), result: pick(value) });
2458
+ })()`)
2459
+ const parsed = JSON.parse(raw)
2460
+ if (parsed.ok !== true) throw new Error(`no element matches ${JSON.stringify(selector)}`)
2461
+ return parsed
2462
+ }
2463
+
2464
+ /**
2465
+ * Move the pointer over an indexed element without clicking it.
2466
+ *
2467
+ * A bare `mouseMoved` is what opens CSS `:hover` menus; Chrome drops later
2468
+ * `mousePressed` events on a menu that was never hovered first.
2469
+ *
2470
+ * @param sessionId - the calling session.
2471
+ * @param index - element number from the latest snapshot.
2472
+ * @returns where the pointer landed.
2473
+ */
2474
+ async hover(sessionId, target) {
2475
+ const page = await this.pageFor(sessionId)
2476
+ const located = await this.locateStable(sessionId, target)
2477
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: located.x, y: located.y, buttons: 0 })
2478
+ await sleep(120)
2479
+ return located
2480
+ }
2481
+
2482
+ /**
2483
+ * Poll the page until a condition holds, or throw on timeout.
2484
+ *
2485
+ * @param sessionId - the calling session.
2486
+ * @param options - `op` selects the condition; `timeoutMs` bounds the wait.
2487
+ * @returns the observation that satisfied the condition.
2488
+ */
2489
+ async waitFor(sessionId, { op = 'delay', selector, pattern, expression, timeoutMs = 10_000, ms } = {}) {
2490
+ const page = await this.pageFor(sessionId)
2491
+ const deadline = Date.now() + Math.max(0, Number(timeoutMs) || 10_000)
2492
+ const budget = () => Math.max(50, deadline - Date.now())
2493
+ if (op === 'delay') {
2494
+ const delay = Math.max(0, Number(ms ?? timeoutMs) || 0)
2495
+ await sleep(delay)
2496
+ return { op, waited: true, waitedMs: delay }
2497
+ }
2498
+ if (op === 'selector') {
2499
+ if (typeof selector !== 'string' || selector === '') throw new Error('op=selector needs a selector')
2500
+ for (;;) {
2501
+ const state = await page.evaluate(`(() => {
2502
+ const el = document.querySelector(${JSON.stringify(selector)});
2503
+ if (!el) return JSON.stringify({ found: false });
2504
+ const style = getComputedStyle(el);
2505
+ const visible = !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length) && style.visibility !== 'hidden';
2506
+ return JSON.stringify({ found: true, visible });
2507
+ })()`)
2508
+ const parsed = JSON.parse(state)
2509
+ if (parsed.found === true && parsed.visible === true) return { op, selector, waited: true, state: 'visible' }
2510
+ if (Date.now() >= deadline) throw new Error(`wait for ${JSON.stringify(selector)} timed out after ${timeoutMs}ms`)
2511
+ await sleep(Math.min(budget(), 200))
2512
+ }
2513
+ }
2514
+ if (op === 'url') {
2515
+ const matcher = pattern === undefined ? '' : String(pattern)
2516
+ if (matcher === '') throw new Error('op=url needs a pattern')
2517
+ const regex = matcher.startsWith('/') && matcher.endsWith('/') ? new RegExp(matcher.slice(1, -1)) : undefined
2518
+ for (;;) {
2519
+ const current = await page.evaluate('location.href')
2520
+ const hit = regex !== undefined ? regex.test(current) : current.includes(matcher)
2521
+ if (hit) return { op, pattern: matcher, waited: true, url: current }
2522
+ if (Date.now() >= deadline) throw new Error(`wait for url ${matcher} timed out after ${timeoutMs}ms`)
2523
+ await sleep(Math.min(budget(), 200))
2524
+ }
2525
+ }
2526
+ if (op === 'function') {
2527
+ if (typeof expression !== 'string' || expression === '') throw new Error('op=function needs an expression')
2528
+ for (;;) {
2529
+ const value = await page.evaluate(`(() => { try { return !!(${expression}); } catch { return false; } })()`)
2530
+ if (value === true) return { op, expression, waited: true }
2531
+ if (Date.now() >= deadline) throw new Error(`wait for expression ${expression} timed out after ${timeoutMs}ms`)
2532
+ await sleep(Math.min(budget(), 200))
2533
+ }
2534
+ }
2535
+ if (op === 'load') {
2536
+ for (;;) {
2537
+ const state = await page.evaluate('document.readyState')
2538
+ if (state === 'complete') return { op, waited: true, readyState: state }
2539
+ if (Date.now() >= deadline) throw new Error(`wait for load timed out after ${timeoutMs}ms (readyState=${state})`)
2540
+ await sleep(Math.min(budget(), 200))
2541
+ }
2542
+ }
2543
+ throw new Error(`unsupported wait op ${JSON.stringify(op)}; use delay, selector, url, function or load`)
2544
+ }
2545
+
2546
+ /**
2547
+ * Choose an option in a native `<select>`, firing input/change like a human.
2548
+ *
2549
+ * @param sessionId - the calling session.
2550
+ * @param target - the select's index, or a CSS selector.
2551
+ * @param value - option value or visible label.
2552
+ * @returns the selected value.
2553
+ */
2554
+ async select(sessionId, target, value) {
2555
+ const page = await this.pageFor(sessionId)
2556
+ const key = elementKey(target)
2557
+ const raw = await page.evaluate(`(() => {
2558
+ const el = document.querySelector(${JSON.stringify(key)});
2559
+ if (!el) return JSON.stringify({ ok: false, reason: ${JSON.stringify(`no element matches ${key}`)} });
2560
+ if (el.tagName !== 'SELECT') return JSON.stringify({ ok: false, reason: 'not a <select> element: ' + el.tagName.toLowerCase() });
2561
+ if (el.disabled) return JSON.stringify({ ok: false, reason: 'select is disabled' });
2562
+ const wanted = ${JSON.stringify(String(value))};
2563
+ const options = [...el.options];
2564
+ const hit = options.find((option) => option.value === wanted)
2565
+ ?? options.find((option) => String(option.text).trim() === wanted)
2566
+ ?? options.find((option) => String(option.text).includes(wanted));
2567
+ if (!hit) return JSON.stringify({ ok: false, reason: 'no such option', options: options.slice(0, 40).map((o) => ({ value: o.value, text: String(o.text).trim().slice(0, 60) })) });
2568
+ el.value = hit.value;
2569
+ el.dispatchEvent(new Event('input', { bubbles: true }));
2570
+ el.dispatchEvent(new Event('change', { bubbles: true }));
2571
+ return JSON.stringify({ ok: true, value: hit.value, text: String(hit.text).trim() });
2572
+ })()`)
2573
+ const parsed = JSON.parse(raw)
2574
+ if (parsed.ok !== true) throw new Error(parsed.options === undefined ? parsed.reason : `${parsed.reason}: ${JSON.stringify(parsed.options)}`)
2575
+ return parsed
2576
+ }
2577
+
2578
+ /**
2579
+ * Set a checkbox/radio to a wanted state, doing nothing when already there.
2580
+ *
2581
+ * @param sessionId - the calling session.
2582
+ * @param target - the box's index, or a CSS selector.
2583
+ * @param checked - the state to end up in.
2584
+ * @returns whether a click was needed.
2585
+ */
2586
+ async check(sessionId, target, checked = true) {
2587
+ const page = await this.pageFor(sessionId)
2588
+ const key = elementKey(target)
2589
+ const name = describeTarget(target)
2590
+ const raw = await page.evaluate(`(() => {
2591
+ const el = document.querySelector(${JSON.stringify(key)});
2592
+ if (!el) return JSON.stringify({ found: false });
2593
+ return JSON.stringify({
2594
+ found: true,
2595
+ tag: el.tagName.toLowerCase(),
2596
+ type: el.type ?? null,
2597
+ checked: el.checked === true || el.getAttribute('aria-checked') === 'true',
2598
+ disabled: el.disabled === true,
2599
+ });
2600
+ })()`)
2601
+ const state = JSON.parse(raw)
2602
+ if (state.found !== true) throw new Error(`no element matches ${name} — call browser_embedded_snapshot again`)
2603
+ if (state.disabled === true) throw new Error(`element ${name} is disabled`)
2604
+ if (state.checked === (checked === true)) return { changed: false, checked: state.checked, target: name }
2605
+ const located = await this.click(sessionId, target)
2606
+ return { changed: true, checked: checked === true, target: name, ...located }
2607
+ }
2608
+
2609
+ /**
2610
+ * Drag from one indexed element to another with a real pointer path.
2611
+ *
2612
+ * @param sessionId - the calling session.
2613
+ * @param from - element to pick up: index or CSS selector.
2614
+ * @param to - element to drop on: index or CSS selector.
2615
+ * @returns both endpoints.
2616
+ */
2617
+ async drag(sessionId, from, to) {
2618
+ const page = await this.pageFor(sessionId)
2619
+ const start = await this.locateStable(sessionId, from)
2620
+ const end = await this.locateStable(sessionId, to)
2621
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: start.x, y: start.y, buttons: 0 })
2622
+ await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: start.x, y: start.y, button: 'left', buttons: 1, clickCount: 1 })
2623
+ const steps = 12
2624
+ for (let step = 1; step <= steps; step += 1) {
2625
+ const x = Math.round(start.x + ((end.x - start.x) * step) / steps)
2626
+ const y = Math.round(start.y + ((end.y - start.y) * step) / steps)
2627
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'left', buttons: 1 })
2628
+ await sleep(20)
2629
+ }
2630
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: end.x, y: end.y, button: 'left', buttons: 0, clickCount: 1 })
2631
+ await sleep(120)
2632
+ return { from: start, to: end }
2633
+ }
2634
+ }