barebrowse 0.20.0 → 0.22.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/CHANGELOG.md CHANGED
@@ -1,6 +1,98 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.22.0] - 2026-10-14
4
+
5
+ ### Added
6
+
7
+ - **The MCP server releases its browser after an idle TTL.** A session left
8
+ open kept a Chromium/Firefox process and profile dir alive indefinitely.
9
+ `BAREBROWSE_IDLE_MINUTES` (default 15, `0` = off; blank or invalid falls back
10
+ to the default, values are capped at `setTimeout`'s maximum) closes the
11
+ browser once no tool call has arrived for that long. The timer pauses while a
12
+ call is in flight, so a long-running call is never cut off, and the next call
13
+ simply opens a fresh browser.
14
+
15
+ ### Fixed
16
+
17
+ - **MCP transient-error resets no longer orphan the running browser.** Five reset
18
+ sites set the page to `null` without closing it, so the next call launched a
19
+ second browser while the first kept running. They now go through
20
+ `resetPage()`, which closes the browser before forgetting it.
21
+ - **`close()` always runs hard cleanup, even when the browser is dead or hung.**
22
+ The polite tab close had no timeout and ran before cleanup, so a killed or
23
+ unresponsive browser leaked its process and temp profile dir. The polite close
24
+ is now bounded and cleanup runs in a `finally`, on both engines.
25
+ - **An ordinary `wait_for` timeout no longer resets the page.** The MCP retry
26
+ layer treated any "timed out" error as transient, which also matched
27
+ `waitFor`'s own not-found message, so a missed wait tore down the browser.
28
+ That message is now excluded.
29
+ - **`wait_for` with `timeout` of 60s or more is no longer cut off at 60s.** The
30
+ retry layer's fixed 60s outer deadline fired first and was treated as
31
+ transient, resetting the page and browser. The outer deadline is now
32
+ `max(60s, requested timeout + 5s)`.
33
+ - **The publish workflow now fails when `package-lock.json`'s version drifts from `package.json`.** npm writes that field on install, so a release that bumps `package.json` without running one leaves it behind — and nothing caught it: `npm ci` fails when the lockfile's *dependency* entries disagree, but never checks the lockfile's copy of the project's own version. `scripts/check-lockfile.mjs` (`npm run check:lockfile`) compares both places npm writes it and runs in the publish workflow. No lockfile is not a failure.
34
+
35
+ ## [0.21.0] - 2026-09-17
36
+
37
+ ### Added
38
+
39
+ - **`connect()` falls back to Firefox when no Chromium is installed.** With no
40
+ `engine` passed, it prefers Chromium but uses Firefox (over WebDriver BiDi)
41
+ if only Firefox is present, warning once to stderr; if neither is installed it
42
+ throws naming both. An explicit `engine` is still honored exactly — it errors
43
+ on a missing binary rather than silently switching — and attach mode (`port`)
44
+ stays Chromium-only. The decision is a pure, unit-tested `resolveEngine()`.
45
+ (`browse()` remains Chromium-only — separate.)
46
+ - **The MCP surface now advertises the active engine.** Firefox is selectable
47
+ only at server launch (`BAREBROWSE_ENGINE`), which a running agent can't see —
48
+ so agents concluded only Chromium existed. Three surfaces now expose it: the
49
+ `initialize` response carries `instructions` naming the active engine + that
50
+ both engines are supported; the `browse` tool description gets the active
51
+ engine appended at `tools/list` time; and a new **`capabilities`** MCP tool
52
+ reports the active engine, mode, both available engines, how to switch (a
53
+ server restart — the engine is fixed for a running session), and the live
54
+ capability flags if a page is open. `capabilities` is pure introspection: it
55
+ never launches a browser.
56
+ - **Session introspection: `page.engine` + `page.capabilities`.** Both engine
57
+ shapes now carry `page.engine` (`'chromium'` | `'firefox'`) and a
58
+ `page.capabilities` object (`engine`, `mode`, `attach`, `escapeHatch`,
59
+ `reloadIgnoreCache`, `downloads`, `stealth`, `cookieInjection`), so a caller
60
+ can ask "which engine am I on and what can it do?" without probing for a
61
+ `cdp`/`bidi` escape hatch. `engine` is a typed literal in each arm, so it also
62
+ works as a discriminant (`if (page.engine === 'firefox') …`) — cleaner than
63
+ the previous `'cdp' in page`. The CLI daemon persists both into
64
+ `session.json`, so `status`/`doctor` report the live session's feature set.
65
+ - **`barebrowse doctor` now reports the runtime environment**, not just MCP
66
+ config scope conflicts: the default engine/mode (incl. the `BAREBROWSE_ENGINE`
67
+ / `BAREBROWSE_MODE` / `BAREBROWSE_INCOGNITO` overrides that pick the engine at
68
+ launch), which Chromium and Firefox binaries are installed, which cookie
69
+ sources exist, and any live session's engine + capabilities. This closes the
70
+ discoverability gap where the Firefox engine — selectable only via a
71
+ server-launch env var — was invisible to a running session.
72
+ - **AX-fidelity harness (`test/integration/ax-fidelity.test.js`).** Drives the
73
+ same fixture pages through both engines and asserts the Firefox/BiDi
74
+ reconstruction never drops a semantic (role + name) node the CDP baseline
75
+ found — making repeatable the by-hand comparison that originally caught four
76
+ reconstruction bugs. Compares role+name only; property brackets and
77
+ `StaticText` echoes legitimately differ between engines.
78
+
79
+ ### Fixed
80
+
81
+ - **`page.capabilities.stealth` now correctly reflects live headed/headless
82
+ state.** It was computed once at `connect()`; after a hybrid bot-challenge
83
+ fallback relaunched a headed browser, `capabilities.stealth` (and the MCP
84
+ `capabilities` tool, and the CLI daemon's persisted `session.json`) kept
85
+ reporting the launch-time value. Now a getter on both engines that reads the
86
+ live state. JSDoc on both engine arms corrected to mark `stealth` live vs
87
+ the other launch-fixed fields, and a regression test asserts it is a real
88
+ getter (property descriptor has `get`), not a value captured at `connect()`
89
+ — a frozen field would have passed the previous test.
90
+ - **Corrected a stale doc line claiming Firefox "is not yet implemented."**
91
+ `barebrowse.context.md` note #10 still said the library was Chromium-only;
92
+ Firefox/BiDi has shipped since v0.15.0 (parity reached across v0.16–0.19).
93
+ The line now documents both engines and how to select Firefox — the same
94
+ false claim had led a session to conclude Firefox wasn't supported.
95
+ - **Adopter type-check gate no longer runs dependency install scripts next to the publish credential.** The gate installs the packed tarball into a throwaway consumer project, and that install ran inside the job holding `id-token: write` — the OIDC credential that can publish this package — with install scripts enabled, so any install script in the tarball's transitive dependency tree executed beside a live publish capability. Now `--ignore-scripts`. The gate only ever runs `tsc`, which reads `.d.ts` and nothing else, so nothing needs building: verified on a native-addon package that the addon is *not* compiled and the type check still passes green, while a broken dereference still fails it. `typescript` is also pinned to `@5` for the same reason `@types/node` is pinned — an unpinned compiler silently becomes a new major and fails the gate on its own schedule rather than on the commit's merits. CI only — no runtime or published-artifact change.
4
96
 
5
97
  ## [0.20.0] - 2026-08-30
6
98
 
package/README.md CHANGED
@@ -58,7 +58,7 @@ Outputs go to `.barebrowse/` as files -- agents read them with their file tools,
58
58
 
59
59
  **Other agents:** Copy `commands/barebrowse.md` to your agent's command/skill directory.
60
60
 
61
- For writing your own skill files for other CLI tools: [docs/skill-template.md](docs/skill-template.md).
61
+ For writing your own skill files for other CLI tools: [docs/product/skill-template.md](docs/product/skill-template.md).
62
62
 
63
63
  ### 2. MCP server -- for Claude Desktop, Cursor, and other MCP clients
64
64
 
@@ -96,11 +96,13 @@ Or manually add to your config (`claude_desktop_config.json`, `.cursor/mcp.json`
96
96
  }
97
97
  ```
98
98
 
99
- MCP tools: `browse`, `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`. Plus `assess` (privacy scan) if [wearehere](https://github.com/hamr0/wearehere) is installed. Plus opt-in `eval` (`BAREBROWSE_MCP_EVAL=1`) — runs JS in the authenticated session, off by default because it can read cookies/localStorage. Session runs in hybrid mode with automatic cookie injection. Per-tool timeouts (goto/reload/wait_for 60s, back/forward 30s, interactive ops 15s, pdf/screenshot/upload 45s) with auto-retry on transient failures (idempotent only — mutating tools fail loudly to avoid double-submits).
99
+ MCP tools: `browse`, `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`, `capabilities` (reports the active engine — chromium or firefox — and what the session can do; no side effects). Plus `assess` (privacy scan) if [wearehere](https://github.com/hamr0/wearehere) is installed. Plus opt-in `eval` (`BAREBROWSE_MCP_EVAL=1`) — runs JS in the authenticated session, off by default because it can read cookies/localStorage. Session runs in hybrid mode with automatic cookie injection. Per-tool timeouts (goto/reload/wait_for 60s, back/forward 30s, interactive ops 15s, pdf/screenshot/upload 45s) with auto-retry on transient failures (idempotent only — mutating tools fail loudly to avoid double-submits).
100
+
101
+ **Idle release.** An MCP server can outlive its conversation, so it closes its browser after `BAREBROWSE_IDLE_MINUTES` (default `15`, `0` = never, blank/invalid = default, fractional allowed, capped at ~24.8 days) with no tool call in flight. The next call opens a fresh browser (a new job, not a resume — a page left open, e.g. a solved captcha in the headed window, is gone). A transient browser error also closes the broken browser rather than orphaning it; an ordinary `wait_for` timeout does not reset the page.
100
102
 
101
103
  `browse` and `snapshot` accept `pruneMode: 'act'|'read'`. `act` (default) keeps interactive elements — best for clicking/filling. `read` keeps paragraphs, headings, and long text — best for articles, docs, and content extraction. If act-mode collapses a content-heavy page near-totally, the snapshot includes a `hint: …` line suggesting `pruneMode='read'` so the agent doesn't bail to a separate HTTP fetch.
102
104
 
103
- Troubleshooting MCP setup: `npx barebrowse doctor` scans every known config location and flags scope conflicts. `npx barebrowse install --force` overwrites an existing entry pointing at a different endpoint.
105
+ `npx barebrowse doctor` reports the runtime environment first — default engine/mode, installed Chromium/Firefox binaries, cookie sources, and any live session's engine + capabilities — then scans every known MCP config location and flags scope conflicts. `npx barebrowse install --force` overwrites an existing entry pointing at a different endpoint.
104
106
 
105
107
  ### 3. Library -- for agentic automation
106
108
 
@@ -152,7 +154,11 @@ Firefox is at practical parity with Chromium: stealth, consent auto-dismiss,
152
154
  ad/tracker blocking, JS dialogs, console/network capture, hybrid fallback,
153
155
  `saveState`, `waitForNavigation`, and download tracking all work the same way.
154
156
  Chromium (CDP) stays the default; the only remaining gap is
155
- `reload({ignoreCache})` (upstream BiDi limitation).
157
+ `reload({ignoreCache})` (upstream BiDi limitation). With no explicit `engine`,
158
+ `connect()` falls back to Firefox (warning once to stderr) if no Chromium
159
+ browser is installed, and throws naming both if neither is; an explicit
160
+ `engine` is always honored and errors on a missing binary instead of silently
161
+ switching.
156
162
 
157
163
  ### Incognito (clean session)
158
164
 
@@ -94,10 +94,12 @@ const snapshot = await browse('https://example.com', {
94
94
  | `downloads` | -- | Array<{guid, url, suggestedFilename, savedPath, state, totalBytes, receivedBytes}> | Live array of every `Content-Disposition: attachment` download captured during this session. `state`: `inProgress` → `completed` \| `canceled`. |
95
95
  | `cdp` | -- | object | Raw CDP session (getter — survives hybrid fallback and switchTab) for escape hatch: `page.cdp.send(method, params)` |
96
96
  | `createTab()` | -- | tab handle | New tab in same browser. Returns `{ goto, botBlocked, injectCookies, waitForNetworkIdle, cdp, close }`. Tab close doesn't affect session. |
97
- | `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless) |
97
+ | `engine` | -- | `'chromium'`\|`'firefox'` | Which engine drives this session. Always readable (both shapes carry it); a typed literal, so it also narrows the union: `if (page.engine === 'firefox') page.bidi.…`. |
98
+ | `capabilities` | -- | object | Feature introspection: `{ engine, mode, attach, escapeHatch, reloadIgnoreCache, downloads, stealth, cookieInjection }`. Ask "what can this session do?" without probing for `cdp`/`bidi`. All fields are launch-fixed except `stealth`, which is a live getter reflecting the session's current headed/headless state (it can flip mid-session after a hybrid bot-challenge relaunch). `reloadIgnoreCache` is false on Firefox (upstream BiDi gap); `downloads`/`stealth`/`cookieInjection` reflect mode + attach + incognito. |
99
+ | `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless). The tab close is bounded (2.5s), so a dead/hung browser still gets killed and its profile + owned download dir removed. Attach mode never kills your browser |
98
100
 
99
101
  **connect() options** (in addition to mode/port/consent):
100
- - `engine: 'chromium'|'firefox'` — Browser engine. Default `chromium` (CDP). `firefox` drives Firefox over WebDriver BiDi (CDP is deprecated there) — a separate transport with the same `page.*` API; the ARIA snapshot is reconstructed in-page since BiDi has no `getFullAXTree`. Consent auto-dismiss and stealth (headless anti-detection) work on Firefox as of v0.16.0; the CLI daemon's console/network capture and `waitForNetworkIdle` work as of v0.17.0; ad/tracker blocking (`blockAds`/`blockUrls`) and JS dialog handling (`dialogLog`/`onDialog`) work as of Phase 3; `hybrid` mode, `saveState`, `waitForNavigation`, and download tracking (`page.downloads`) work as of Phase 4. The only remaining Firefox gap is `reload()` ignoring `ignoreCache` (upstream BiDi limitation).
102
+ - `engine: 'chromium'|'firefox'` — Browser engine. Default `chromium` (CDP). When you don't pass `engine`, `connect()` prefers Chromium but **falls back to Firefox** (with a one-line `console.warn` to stderr) if no Chromium browser is installed; if neither engine is installed it throws naming both. An **explicit** `engine` is always honored — it errors if that engine's binary is missing rather than silently switching. Attach mode (`port`) is Chromium/CDP-only and never falls back. `firefox` drives Firefox over WebDriver BiDi (CDP is deprecated there) — a separate transport with the same `page.*` API; the ARIA snapshot is reconstructed in-page since BiDi has no `getFullAXTree`. Consent auto-dismiss and stealth (headless anti-detection) work on Firefox as of v0.16.0; the CLI daemon's console/network capture and `waitForNetworkIdle` work as of v0.17.0; ad/tracker blocking (`blockAds`/`blockUrls`) and JS dialog handling (`dialogLog`/`onDialog`) work as of Phase 3; `hybrid` mode, `saveState`, `waitForNavigation`, and download tracking (`page.downloads`) work as of Phase 4. The only remaining Firefox gap is `reload()` ignoring `ignoreCache` (upstream BiDi limitation).
101
103
  - `port: 9222` — Attach to a Chromium already running with `--remote-debugging-port=N` instead of spawning one. The browser keeps running on `close()`. Stealth + permission denial + download capture are skipped to avoid mutating the user's running browser.
102
104
  - `proxy: 'http://...'` — HTTP/SOCKS proxy for browser
103
105
  - `viewport: '1280x720'` — Set viewport dimensions
@@ -293,6 +295,8 @@ barebrowse ships an MCP server for direct use with Claude Desktop, Cursor, or an
293
295
 
294
296
  19 core tools: `browse` (one-shot), `goto`, `snapshot`, `readable`, `click`, `type`, `press`, `scroll`, `hover`, `select`, `back`, `forward`, `reload`, `drag`, `upload`, `pdf`, `screenshot`, `wait_for`, `tabs`. Plus `assess` (privacy scan) if `wearehere` is installed (`npm install wearehere`). Plus the **opt-in `eval` tool** gated by `BAREBROWSE_MCP_EVAL=1` (default OFF) — `Runtime.evaluate` in the user's authenticated session can read cookies/localStorage and hit any same-origin endpoint, so opt-in only.
295
297
 
298
+ **Idle release:** the MCP server closes its browser after `BAREBROWSE_IDLE_MINUTES` of no tool calls (default `15`; `0` = off; blank/invalid = default; capped at ~24.8 days; calls in flight postpone it). The next call opens a fresh browser — page state (open tabs, a solved captcha) is not resumed. Transient browser errors close the broken browser instead of orphaning it; a `wait_for` that merely times out keeps the page (its outer deadline is `max(60s, timeout+5s)`).
299
+
296
300
  Action tools return `'ok'` -- the agent calls `snapshot` explicitly to observe. This avoids double-token output since MCP tool calls are cheap to chain.
297
301
 
298
302
  `browse`, `snapshot`, and `readable` accept a `maxChars` param (default 30000). If the output exceeds the limit it's saved to `.barebrowse/` and a short message with the file path is returned instead (`page-<timestamp>.yml` for snapshots, `article-<timestamp>.txt` for `readable`). `screenshot` always saves to `.barebrowse/screenshot-<timestamp>.{png,jpeg,webp}` and returns the file path (raw base64 in a JSON-RPC response would blow `maxChars`). `tabs` returns the JSON array, or with `switchTo: N` it switches and returns `'ok'`. All files MCP writes are owner-only (`0600` in a `0700` dir) — they can hold authenticated page content, so they're not world-readable on a shared host.
@@ -382,7 +386,7 @@ Useful for agent threshold decisions: "skip sites above score 40", "warn if term
382
386
 
383
387
  9. **Screenshot returns base64.** Write to file with `fs.writeFileSync('shot.png', Buffer.from(base64, 'base64'))` or pass directly to a vision model.
384
388
 
385
- 10. **Chromium-only.** CDP protocol limits us to Chrome, Chromium, Edge, Brave, Vivaldi (~80% desktop share). Firefox support via WebDriver BiDi is not yet implemented.
389
+ 10. **Two engines.** The default is CDP, which drives Chrome, Chromium, Edge, Brave, Vivaldi (~80% desktop share). Firefox is driven over WebDriver BiDi (CDP is deprecated there) — select it with `connect({ engine: 'firefox' })`, CLI `--engine firefox`, or MCP `BAREBROWSE_ENGINE=firefox`. Same `page.*` API on both; feature parity reached in v0.19.x, with the only remaining gap being `reload()` ignoring `ignoreCache` (upstream BiDi limitation). Note the engine is chosen at launch, not per-call. See the `engine` connect() option below for the full parity timeline.
386
390
 
387
391
  11. **`--site-per-process` is on by default (v0.9.0).** Required for iframe support — without it, same-origin iframes stay in the parent process and `Input.dispatchMouseEvent` coords don't match `DOM.getBoxModel` coords for iframe-internal elements. Memory cost: +50-150MB per cross-origin frame. Real Chrome does this for cross-origin by default; we just extend it to all iframes. If you attach via `connect({port})`, the user's browser is whatever they launched it as — for iframe interaction reliability, start it with `--site-per-process` too.
388
392
 
package/cli.js CHANGED
@@ -25,7 +25,7 @@ if (args.includes('--daemon-internal')) {
25
25
  } else if (cmd === 'install') {
26
26
  install();
27
27
  } else if (cmd === 'doctor') {
28
- doctor();
28
+ await doctor();
29
29
  } else if (cmd === 'browse' && args[1]) {
30
30
  await oneShot();
31
31
  } else if (cmd === 'open') {
@@ -411,7 +411,75 @@ function readJsonOrEmpty(path) {
411
411
  * absolute endpoints across scopes — OAuth tokens are stored per-endpoint
412
412
  * so a split silently breaks auth.
413
413
  */
414
- function doctor() {
414
+ async function doctor() {
415
+ await doctorEnvironment();
416
+ doctorMcpConfig();
417
+ }
418
+
419
+ /**
420
+ * Report the runtime environment: which engine/mode a session would use, which
421
+ * browsers and cookie sources are actually installed, and whether a session is
422
+ * live in this directory. This is the "which engine am I on and what can it do?"
423
+ * answer — the gap that led a peer session to conclude Firefox wasn't supported
424
+ * when it is (selected via BAREBROWSE_ENGINE / --engine, not a per-tool flag).
425
+ */
426
+ async function doctorEnvironment() {
427
+ const { findBrowser } = await import('./src/chromium.js');
428
+ const { findFirefox } = await import('./src/firefox.js');
429
+ const { findChromiumCookieDb, findFirefoxCookieDb } = await import('./src/auth.js');
430
+
431
+ console.log('barebrowse doctor — runtime environment:\n');
432
+ console.log(` Node ${process.version} on ${platform()}`);
433
+
434
+ // Configured engine/mode/incognito. MCP selects the engine at server launch
435
+ // via these env vars (mcp-server.js), which a running session can't see —
436
+ // surfacing them here is the whole point.
437
+ const engine = process.env.BAREBROWSE_ENGINE === 'firefox' ? 'firefox' : 'chromium';
438
+ const modeEnv = process.env.BAREBROWSE_MODE;
439
+ const incognito = process.env.BAREBROWSE_INCOGNITO === '1';
440
+ console.log(` Default engine: ${engine} (override: BAREBROWSE_ENGINE=firefox | --engine firefox | connect({engine}))`);
441
+ // Mode default differs by surface: CLI `open` → headless, MCP → hybrid.
442
+ // BAREBROWSE_MODE overrides both, so report it directly when set.
443
+ console.log(` Default mode: ${modeEnv ? `${modeEnv} (BAREBROWSE_MODE)` : 'headless (CLI open) / hybrid (MCP)'}`);
444
+ console.log(` Incognito: ${incognito ? 'on (BAREBROWSE_INCOGNITO=1) — no cookie injection' : 'off'}`);
445
+
446
+ // Installed browsers — both engines. A missing one explains why an --engine
447
+ // choice would fail before it launches.
448
+ console.log('\n Installed browsers:');
449
+ let chromiumPath = null, firefoxPath = null;
450
+ try { chromiumPath = findBrowser(); } catch { /* none */ }
451
+ try { firefoxPath = findFirefox(); } catch { /* none */ }
452
+ console.log(` Chromium/CDP: ${chromiumPath || 'NOT FOUND — install chrome/chromium/brave/edge'}`);
453
+ console.log(` Firefox/BiDi: ${firefoxPath || 'NOT FOUND — install firefox (>= 121 for stable BiDi)'}`);
454
+
455
+ // Cookie sources — where authenticated sessions come from (skipped in incognito).
456
+ console.log('\n Cookie sources:');
457
+ const chromiumCookies = findChromiumCookieDb();
458
+ const firefoxCookies = findFirefoxCookieDb();
459
+ console.log(` Chromium: ${chromiumCookies ? `${chromiumCookies.browser} (${chromiumCookies.path})` : 'none found'}`);
460
+ console.log(` Firefox: ${firefoxCookies || 'none found'}`);
461
+
462
+ // Live session in this directory, if any — reports its actual engine +
463
+ // capabilities (persisted into session.json by the daemon).
464
+ const { readSession, isAlive } = await import('./src/session-client.js');
465
+ const outputDir = resolve('.barebrowse');
466
+ const session = readSession(outputDir);
467
+ console.log('\n Active session (this directory):');
468
+ if (!session) {
469
+ console.log(' none — run `barebrowse open [url]` to start one');
470
+ } else if (!(await isAlive(outputDir))) {
471
+ console.log(` stale (pid ${session.pid} not responding) — run \`barebrowse close\` to clean up`);
472
+ } else {
473
+ console.log(` running (pid ${session.pid}, port ${session.port}, engine ${session.engine || 'chromium'})`);
474
+ if (session.capabilities) {
475
+ const c = session.capabilities;
476
+ console.log(` mode=${c.mode} attach=${c.attach} downloads=${c.downloads} stealth=${c.stealth} cookies=${c.cookieInjection} reloadIgnoreCache=${c.reloadIgnoreCache}`);
477
+ }
478
+ }
479
+ console.log('');
480
+ }
481
+
482
+ function doctorMcpConfig() {
415
483
  const home = homedir();
416
484
  const cwd = process.cwd();
417
485
  const os = platform();
@@ -553,7 +621,8 @@ MCP:
553
621
  barebrowse mcp Start MCP server (JSON-RPC over stdio)
554
622
  barebrowse install [--force] Add barebrowse to detected MCP clients (--force replaces stale entries)
555
623
  barebrowse install --skill Install Claude Code skill file
556
- barebrowse doctor Scan MCP config locations for barebrowse entries + flag scope conflicts
624
+ barebrowse doctor Report engine/mode/browsers/cookie sources + active session,
625
+ then scan MCP config locations + flag scope conflicts
557
626
  barebrowse install Auto-configure MCP for Claude Desktop / Cursor
558
627
  barebrowse install --skill Install SKILL.md for Claude Code
559
628
 
package/mcp-server.js CHANGED
@@ -63,6 +63,8 @@ try {
63
63
 
64
64
  function isTransient(err) {
65
65
  const m = err.message || '';
66
+ // A wait_for that simply didn't find its text is a normal result, not a broken browser.
67
+ if (m.startsWith('waitFor timed out')) return false;
66
68
  return m.includes('WebSocket') || m.includes('Target closed') || m.includes('Session closed')
67
69
  || m.includes('CDP') || m.includes('Timeout waiting for CDP event') || m.includes('timed out');
68
70
  }
@@ -95,7 +97,7 @@ async function withRetry(fn, timeoutMs, { retry = true } = {}) {
95
97
  } catch (err) {
96
98
  if (!isTransient(err)) throw err;
97
99
  // Transient failure — reset session so the next request gets a fresh page.
98
- _page = null;
100
+ resetPage();
99
101
  if (!retry) throw err;
100
102
  return await attempt();
101
103
  }
@@ -118,6 +120,74 @@ export function saveSnapshot(text, { prefix = 'page', ext = 'yml' } = {}) {
118
120
  let _page = null;
119
121
  let _pageConnecting = null;
120
122
 
123
+ /**
124
+ * Forget the current session AND close its browser. A bare `_page = null`
125
+ * orphaned the browser (still running, holding GBs) — the next getPage() just
126
+ * launched a second one. Fire-and-forget: callers are on error paths.
127
+ */
128
+ function resetPage() {
129
+ const p = _page;
130
+ _page = null;
131
+ if (p) p.close().catch(() => {});
132
+ }
133
+
134
+ // Idle TTL: a server can outlive its conversation by days, holding a browser
135
+ // (GBs) the whole time. After BAREBROWSE_IDLE_MINUTES (default 15, 0 = off)
136
+ // with no tools/call in flight, release it; the next call opens a fresh one.
137
+ // Capped at setTimeout's max (2^31-1 ms, ~24.8 days): beyond it Node fires after 1ms.
138
+ /**
139
+ * Outer deadline for wait_for: follows the requested wait (page.waitFor
140
+ * defaults to 30000) plus 5s slack, never below TIMEOUTS.wait_for. Otherwise a
141
+ * wait >= the fixed deadline trips withRetry's transient "timed out" and resets
142
+ * the page.
143
+ */
144
+ export function waitForDeadline(timeout) {
145
+ return Math.max(TIMEOUTS.wait_for, (timeout || 30000) + 5000);
146
+ }
147
+
148
+ export function idleMs(raw) {
149
+ const DEFAULT = 15 * 60_000;
150
+ if (raw === undefined || String(raw).trim() === '') return DEFAULT;
151
+ const n = Number(raw);
152
+ if (!Number.isFinite(n) || n < 0) return DEFAULT;
153
+ return Math.min(n * 60_000, 2 ** 31 - 1);
154
+ }
155
+ const IDLE_MS = idleMs(process.env.BAREBROWSE_IDLE_MINUTES);
156
+ let _inflight = 0;
157
+ let _idleTimer = null;
158
+
159
+ function armIdle() {
160
+ clearTimeout(_idleTimer);
161
+ if (!IDLE_MS || _inflight) return;
162
+ _idleTimer = setTimeout(() => { if (!_inflight && _page) resetPage(); }, IDLE_MS);
163
+ _idleTimer.unref();
164
+ }
165
+
166
+ /**
167
+ * The engine + mode this server is configured to use, derived from env WITHOUT
168
+ * launching a browser. Both engines ship in the library; which one this server
169
+ * drives is fixed at launch by BAREBROWSE_ENGINE and cannot change mid-session
170
+ * (one browser is connected and reused across tool calls). Surfaced to the
171
+ * agent via `initialize.instructions`, the `capabilities` tool, and the `browse`
172
+ * tool description so the Firefox engine is discoverable — it was invisible
173
+ * before, and a session concluded (wrongly) that only Chromium was supported.
174
+ */
175
+ function engineInfo() {
176
+ const engine = process.env.BAREBROWSE_ENGINE === 'firefox' ? 'firefox' : 'chromium';
177
+ const mode = process.env.BAREBROWSE_MODE || 'hybrid';
178
+ const incognito = process.env.BAREBROWSE_INCOGNITO === '1';
179
+ return {
180
+ activeEngine: engine,
181
+ mode,
182
+ incognito,
183
+ availableEngines: ['chromium', 'firefox'],
184
+ // Engine is chosen once at server launch — the agent cannot switch it.
185
+ switchEngine:
186
+ "To use the other engine, restart the MCP server with BAREBROWSE_ENGINE=firefox "
187
+ + "(or unset it for the chromium default). It cannot be changed during a session.",
188
+ };
189
+ }
190
+
121
191
  async function getPage() {
122
192
  if (_page) return _page;
123
193
  if (_pageConnecting) return _pageConnecting;
@@ -363,6 +433,11 @@ export const TOOLS = [
363
433
  required: ['ref'],
364
434
  },
365
435
  },
436
+ {
437
+ name: 'capabilities',
438
+ description: 'Report which browser engine this session drives (chromium or firefox) and what it can do — no navigation, no side effects. Use it to answer "can this drive Firefox?" or "is this an authenticated session?". Returns the active engine + mode, that both engines are supported, how to switch (a server-restart env var; the engine is fixed for a running session), and, if a page is already open, its live capability flags.',
439
+ inputSchema: { type: 'object', properties: {} },
440
+ },
366
441
  ];
367
442
 
368
443
  // Powerful escape hatch — guarded behind an explicit env-var opt-in.
@@ -402,6 +477,19 @@ if (assessFn) {
402
477
 
403
478
  async function handleToolCall(name, args) {
404
479
  switch (name) {
480
+ case 'capabilities': {
481
+ // Introspection only — must NOT launch a browser. Report the configured
482
+ // engine from env; if a page is already connected, attach its live flags.
483
+ const info = engineInfo();
484
+ if (_page) {
485
+ info.connected = true;
486
+ info.capabilities = _page.capabilities;
487
+ } else {
488
+ info.connected = false;
489
+ info.capabilities = null; // populated on first navigation
490
+ }
491
+ return info;
492
+ }
405
493
  case 'browse': {
406
494
  let timer;
407
495
  const text = await Promise.race([
@@ -515,7 +603,7 @@ async function handleToolCall(name, args) {
515
603
  const page = await getPage();
516
604
  await page.waitFor({ text: args.text, selector: args.selector, timeout: args.timeout });
517
605
  return 'ok';
518
- }, TIMEOUTS.wait_for, { retry: false });
606
+ }, waitForDeadline(args.timeout), { retry: false });
519
607
  case 'tabs': return withRetry(async () => {
520
608
  const page = await getPage();
521
609
  if (typeof args.switchTo === 'number') {
@@ -596,7 +684,7 @@ async function handleToolCall(name, args) {
596
684
  } catch (err) {
597
685
  clearTimeout(timer);
598
686
  await tab.close().catch(() => {});
599
- if (isTransient(err)) _page = null;
687
+ if (isTransient(err)) resetPage();
600
688
  throw err;
601
689
  }
602
690
  } finally {
@@ -620,10 +708,17 @@ async function handleMessage(msg) {
620
708
  const { id, method, params } = msg;
621
709
 
622
710
  if (method === 'initialize') {
711
+ const e = engineInfo();
623
712
  return jsonrpcResponse(id, {
624
713
  protocolVersion: '2024-11-05',
625
714
  capabilities: { tools: {} },
626
715
  serverInfo: { name: 'barebrowse', version: PKG_VERSION },
716
+ // Tell the agent which engine is live + that the other exists. `instructions`
717
+ // is a standard MCP field clients may show to the model.
718
+ instructions:
719
+ `barebrowse drives a real browser. Active engine: ${e.activeEngine} (mode: ${e.mode}). `
720
+ + `Both chromium and firefox are supported; ${e.switchEngine} `
721
+ + `Call the "capabilities" tool for the live engine + feature set.`,
627
722
  });
628
723
  }
629
724
 
@@ -632,22 +727,33 @@ async function handleMessage(msg) {
632
727
  }
633
728
 
634
729
  if (method === 'tools/list') {
635
- return jsonrpcResponse(id, { tools: TOOLS });
730
+ // Append the live engine note to the `browse` entry-point description so the
731
+ // active engine (and that both are supported) is visible without a call.
732
+ const e = engineInfo();
733
+ const note = ` [Active engine: ${e.activeEngine}; chromium + firefox both supported — ${e.switchEngine}]`;
734
+ const tools = TOOLS.map((t) =>
735
+ t.name === 'browse' ? { ...t, description: t.description + note } : t);
736
+ return jsonrpcResponse(id, { tools });
636
737
  }
637
738
 
638
739
  if (method === 'tools/call') {
639
740
  const { name, arguments: args } = params;
741
+ _inflight++;
742
+ clearTimeout(_idleTimer);
640
743
  try {
641
744
  const result = await handleToolCall(name, args || {});
642
745
  return jsonrpcResponse(id, {
643
746
  content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }],
644
747
  });
645
748
  } catch (err) {
646
- if (isTransient(err)) _page = null;
749
+ if (isTransient(err)) resetPage();
647
750
  return jsonrpcResponse(id, {
648
751
  content: [{ type: 'text', text: `Error: ${err.message}` }],
649
752
  isError: true,
650
753
  });
754
+ } finally {
755
+ _inflight--;
756
+ armIdle();
651
757
  }
652
758
  }
653
759
 
@@ -703,8 +809,8 @@ export function runStdio() {
703
809
 
704
810
  // Prevent unhandled rejections and uncaught exceptions from crashing the server.
705
811
  // Browser OOM/crash rejects all pending CDP promises — some may not be awaited.
706
- process.on('unhandledRejection', () => { _page = null; });
707
- process.on('uncaughtException', () => { _page = null; });
812
+ process.on('unhandledRejection', () => { resetPage(); });
813
+ process.on('uncaughtException', () => { resetPage(); });
708
814
 
709
815
  // Clean up on exit
710
816
  process.on('SIGINT', async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebrowse",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Authenticated web browsing for autonomous agents via CDP. URL in, pruned ARIA snapshot out.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,7 +43,8 @@
43
43
  "test:integration": "node --test test/integration/*.test.js",
44
44
  "typecheck": "tsc --noEmit",
45
45
  "build:types": "tsc",
46
- "prepublishOnly": "npm run build:types"
46
+ "prepublishOnly": "npm run build:types",
47
+ "check:lockfile": "node scripts/check-lockfile.mjs"
47
48
  },
48
49
  "keywords": [
49
50
  "browser",
package/src/auth.js CHANGED
@@ -30,7 +30,7 @@ const CHROMIUM_PATHS = {
30
30
  * Find first available Chromium cookie database.
31
31
  * @returns {{ path: string, browser: string } | null}
32
32
  */
33
- function findChromiumCookieDb() {
33
+ export function findChromiumCookieDb() {
34
34
  for (const [browser, path] of Object.entries(CHROMIUM_PATHS)) {
35
35
  if (existsSync(path)) return { path, browser };
36
36
  }
@@ -41,7 +41,7 @@ function findChromiumCookieDb() {
41
41
  * Find Firefox default profile cookies.
42
42
  * @returns {string | null} Path to cookies.sqlite
43
43
  */
44
- function findFirefoxCookieDb() {
44
+ export function findFirefoxCookieDb() {
45
45
  const base = `${HOME}/.mozilla/firefox`;
46
46
  try {
47
47
  for (const entry of readdirSync(base)) {
package/src/daemon.js CHANGED
@@ -610,6 +610,10 @@ export async function runDaemon(opts, outputDir, initialUrl) {
610
610
  pid: process.pid,
611
611
  token: authToken,
612
612
  startedAt: new Date().toISOString(),
613
+ // Persisted so `status`/`doctor` can report the live engine + feature set
614
+ // without an HTTP round-trip (page.engine/capabilities, added in v0.21.0).
615
+ engine: page.engine,
616
+ capabilities: page.capabilities,
613
617
  }));
614
618
 
615
619
  // Handle SIGTERM gracefully
@@ -285,6 +285,28 @@ export async function createFirefoxPage(bidi, opts = {}) {
285
285
  /** Whether the last goto() landed on a bot-challenge page (parity w/ CDP). */
286
286
  get botBlocked() { return botBlocked; },
287
287
 
288
+ /** @type {'firefox'} Engine driving this session (see also `capabilities`). */
289
+ engine: 'firefox',
290
+
291
+ /**
292
+ * Introspection of this session's engine, mode, and feature support —
293
+ * mirrors connect()'s Chromium `page.capabilities`. Fields are launch-fixed
294
+ * except `stealth`, a live getter tracking the current headed/headless
295
+ * state. `reloadIgnoreCache` is false here (upstream BiDi gap); Firefox is
296
+ * never attach mode.
297
+ * @type {import('./index.js').Capabilities}
298
+ */
299
+ capabilities: {
300
+ engine: 'firefox',
301
+ mode: hybrid ? 'hybrid' : (opts.headed ? 'headed' : 'headless'),
302
+ attach: false,
303
+ escapeHatch: 'bidi',
304
+ reloadIgnoreCache: false,
305
+ downloads: true,
306
+ get stealth() { return !currentlyHeaded; },
307
+ cookieInjection: !incognito,
308
+ },
309
+
288
310
  async goto(url, timeout = 30000) {
289
311
  // Same navigation guard the CDP path enforces — block file:/chrome:/
290
312
  // view-source: and (optionally) private-network hosts before navigating.
@@ -620,8 +642,9 @@ export async function createFirefoxPage(bidi, opts = {}) {
620
642
  },
621
643
 
622
644
  async close() {
623
- try { await bidi.send('browsingContext.close', { context: topContext }); } catch {}
624
- bidi.close();
645
+ // Best-effort and bounded: a hung browser must not block the hard cleanup.
646
+ try { await withTimeout(bidi.send('browsingContext.close', { context: topContext }), 2500, 'close'); } catch {}
647
+ try { bidi.close(); } catch {}
625
648
  },
626
649
  };
627
650
 
package/src/index.js CHANGED
@@ -8,8 +8,8 @@
8
8
  * const snapshot = await browse('https://example.com');
9
9
  */
10
10
 
11
- import { launch, attach, cleanupBrowser } from './chromium.js';
12
- import { launchFirefox, cleanupFirefox } from './firefox.js';
11
+ import { launch, attach, cleanupBrowser, findBrowser } from './chromium.js';
12
+ import { launchFirefox, cleanupFirefox, findFirefox } from './firefox.js';
13
13
  import { createCDP } from './cdp.js';
14
14
  import { createBiDi } from './bidi.js';
15
15
  import { createFirefoxPage } from './firefox-page.js';
@@ -172,9 +172,34 @@ export async function browse(url, opts = {}) {
172
172
  * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
173
173
  * without narrowing; an engine-specific hatch requires knowing the engine
174
174
  * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
175
+ * Both shapes carry `page.engine` (`'chromium'`|`'firefox'`) and a
176
+ * `page.capabilities` object so a caller can introspect which engine drives
177
+ * the session and what it supports without probing for an escape hatch.
175
178
  * @typedef {Awaited<ReturnType<typeof connect>>} Page
176
179
  */
177
180
 
181
+ /**
182
+ * Description of what the current session can do — engine, mode, and the
183
+ * mode/engine-derived feature flags that actually differ between sessions. Read
184
+ * it via `page.capabilities` instead of inferring from the engine name. All
185
+ * fields are launch-fixed engine/mode facts except `stealth`, which reflects
186
+ * the CURRENT headed/headless state and can flip mid-session after a hybrid
187
+ * bot-challenge fallback relaunches a headed browser. `attach` is Chromium
188
+ * `connect({port})` (no stealth/downloads); `reloadIgnoreCache` is false on
189
+ * Firefox (upstream BiDi gap). Each remaining flag has its own driver:
190
+ * `downloads` is off when attached, `stealth` off when attached or headed,
191
+ * `cookieInjection` off in incognito.
192
+ * @typedef {object} Capabilities
193
+ * @property {'chromium'|'firefox'} engine - Engine driving this session
194
+ * @property {'headless'|'headed'|'hybrid'} mode - Launch mode
195
+ * @property {boolean} attach - Attached to a user-launched browser (Chromium only)
196
+ * @property {'cdp'|'bidi'} escapeHatch - Name of the raw-protocol escape-hatch property
197
+ * @property {boolean} reloadIgnoreCache - `reload({ignoreCache})` is honored
198
+ * @property {boolean} downloads - `page.downloads` is populated
199
+ * @property {boolean} stealth - Headless anti-detection is currently active (live — reflects present headed/headless state, not just launch mode)
200
+ * @property {boolean} cookieInjection - Cookie extraction/injection is active (off in incognito)
201
+ */
202
+
178
203
  /**
179
204
  * Options for `page.snapshot()`. Pass `false` instead of an object to skip
180
205
  * pruning and return the raw ARIA tree.
@@ -240,12 +265,52 @@ export async function browse(url, opts = {}) {
240
265
  * structurally from the returned object literals; annotating it as `Page`
241
266
  * would be a self-reference, since `Page` is `ReturnType<typeof connect>`.
242
267
  */
268
+ /** True if a browser finder resolves a binary; false if it throws (none found). */
269
+ function canFind(finder) {
270
+ try { finder(); return true; } catch { return false; }
271
+ }
272
+
273
+ /**
274
+ * Decide which engine connect() should use. Pure — the caller passes lazy
275
+ * probe thunks so this is unit-testable without launching a browser.
276
+ * An explicit `opts.engine` is always honored (existence is checked downstream
277
+ * by launch()/connectFirefox(), which throw a clear install message if missing).
278
+ * Attach mode (`opts.port`) is CDP/Chromium-only. Otherwise (no engine picked)
279
+ * prefer Chromium, fall back to Firefox, and if neither is installed throw.
280
+ * @param {{engine?: string, port?: number}} opts
281
+ * @param {{hasChromium: () => boolean, hasFirefox: () => boolean}} probe
282
+ * @returns {{engine: 'chromium'|'firefox', fellBack: boolean}}
283
+ */
284
+ export function resolveEngine(opts, probe) {
285
+ if (opts.engine === 'firefox') return { engine: 'firefox', fellBack: false };
286
+ if (opts.engine === 'chromium') return { engine: 'chromium', fellBack: false };
287
+ if (opts.port) return { engine: 'chromium', fellBack: false };
288
+ if (probe.hasChromium()) return { engine: 'chromium', fellBack: false };
289
+ if (probe.hasFirefox()) return { engine: 'firefox', fellBack: true };
290
+ throw new Error(
291
+ 'No supported browser found. Install a Chromium browser (chrome, chromium, '
292
+ + 'brave, or edge) or Firefox (>= 121 for stable WebDriver BiDi).',
293
+ );
294
+ }
295
+
243
296
  export async function connect(opts = {}) {
244
297
  // Firefox is driven over WebDriver BiDi (CDP is deprecated there) — a
245
298
  // separate transport with its own page object. It reuses prune.js/aria.js/
246
299
  // readable.js but none of the CDP page machinery below, so branch early.
247
- if (opts.engine === 'firefox') {
248
- return connectFirefox(opts);
300
+ const { engine: resolvedEngine, fellBack } = resolveEngine(opts, {
301
+ hasChromium: () => canFind(findBrowser),
302
+ hasFirefox: () => canFind(findFirefox),
303
+ });
304
+ if (resolvedEngine === 'firefox') {
305
+ if (fellBack) {
306
+ // Loud, to stderr (stdout is data on CLI/MCP). Only fires on the default
307
+ // path — an explicit engine never falls back, so never warns.
308
+ console.warn(
309
+ 'barebrowse: no Chromium browser found — falling back to Firefox over '
310
+ + 'WebDriver BiDi. Pass engine explicitly to silence this.',
311
+ );
312
+ }
313
+ return connectFirefox({ ...opts, engine: 'firefox' });
249
314
  }
250
315
 
251
316
  const mode = opts.mode || 'headless';
@@ -647,6 +712,28 @@ export async function connect(opts = {}) {
647
712
 
648
713
  get botBlocked() { return botBlocked; },
649
714
 
715
+ /** @type {'chromium'} Engine driving this session (see also `capabilities`) */
716
+ engine: 'chromium',
717
+
718
+ /**
719
+ * Introspection of this session's engine, mode, and feature support — see
720
+ * the `Capabilities` typedef. Fields are launch-fixed except `stealth`,
721
+ * which is a live getter tracking the current headed/headless state (flips
722
+ * after a hybrid headed relaunch). Lets a caller ask "which engine am I on
723
+ * and what can it do?" without probing for `cdp`/`bidi`.
724
+ * @type {Capabilities}
725
+ */
726
+ capabilities: {
727
+ engine: 'chromium',
728
+ mode,
729
+ attach: attachMode,
730
+ escapeHatch: 'cdp',
731
+ reloadIgnoreCache: true,
732
+ downloads: !attachMode,
733
+ get stealth() { return !attachMode && !currentlyHeaded; },
734
+ cookieInjection: !incognito,
735
+ },
736
+
650
737
  dialogLog,
651
738
 
652
739
  /**
@@ -722,16 +809,27 @@ export async function connect(opts = {}) {
722
809
  },
723
810
 
724
811
  async close() {
725
- await cdp.send('Target.closeTarget', { targetId: page.targetId });
726
- cdp.close();
727
- await cleanupBrowser(browser);
728
- // If we created the download dir ourselves, clean it up too. Caller-
729
- // supplied opts.downloadPath stays — the caller owns the lifecycle.
730
- if (ownedDownloadDir) {
731
- try {
732
- const { rmSync } = await import('node:fs');
733
- rmSync(ownedDownloadDir, { recursive: true, force: true });
734
- } catch {}
812
+ // Polite tab close is best-effort and bounded: a dead or hung browser
813
+ // must not skip the hard cleanup below (the profile dir / process leak).
814
+ let timer;
815
+ try {
816
+ await Promise.race([
817
+ cdp.send('Target.closeTarget', { targetId: page.targetId }),
818
+ new Promise((r) => { timer = setTimeout(r, 2500); }),
819
+ ]);
820
+ } catch {} finally { clearTimeout(timer); }
821
+ try { cdp.close(); } catch {}
822
+ try {
823
+ await cleanupBrowser(browser); // no-op in attach mode (process: null)
824
+ } finally {
825
+ // If we created the download dir ourselves, clean it up too. Caller-
826
+ // supplied opts.downloadPath stays — the caller owns the lifecycle.
827
+ if (ownedDownloadDir) {
828
+ try {
829
+ const { rmSync } = await import('node:fs');
830
+ rmSync(ownedDownloadDir, { recursive: true, force: true });
831
+ } catch {}
832
+ }
735
833
  }
736
834
  },
737
835
  };
@@ -842,13 +940,19 @@ async function connectFirefox(opts) {
842
940
  });
843
941
  const closePage = page.close.bind(page);
844
942
  page.close = async () => {
845
- await closePage();
846
- await cleanupFirefox(browser); // `browser` tracks the relaunched one if hybrid fired
847
- if (ownedDownloadDir) {
943
+ try {
944
+ await closePage();
945
+ } finally {
848
946
  try {
849
- const { rmSync } = await import('node:fs');
850
- rmSync(ownedDownloadDir, { recursive: true, force: true });
851
- } catch { /* best-effort reap */ }
947
+ await cleanupFirefox(browser); // `browser` tracks the relaunched one if hybrid fired
948
+ } finally {
949
+ if (ownedDownloadDir) {
950
+ try {
951
+ const { rmSync } = await import('node:fs');
952
+ rmSync(ownedDownloadDir, { recursive: true, force: true });
953
+ } catch { /* best-effort reap */ }
954
+ }
955
+ }
852
956
  }
853
957
  };
854
958
  return page;
package/types/auth.d.ts CHANGED
@@ -1,3 +1,16 @@
1
+ /**
2
+ * Find first available Chromium cookie database.
3
+ * @returns {{ path: string, browser: string } | null}
4
+ */
5
+ export function findChromiumCookieDb(): {
6
+ path: string;
7
+ browser: string;
8
+ } | null;
9
+ /**
10
+ * Find Firefox default profile cookies.
11
+ * @returns {string | null} Path to cookies.sqlite
12
+ */
13
+ export function findFirefoxCookieDb(): string | null;
1
14
  /**
2
15
  * Extract cookies from the user's browser, auto-detecting which browser to use.
3
16
  * @param {object} [opts]
@@ -33,6 +33,17 @@ export function createFirefoxPage(bidi: object, opts?: {
33
33
  readonly context: any;
34
34
  /** Whether the last goto() landed on a bot-challenge page (parity w/ CDP). */
35
35
  readonly botBlocked: boolean;
36
+ /** @type {'firefox'} Engine driving this session (see also `capabilities`). */
37
+ engine: "firefox";
38
+ /**
39
+ * Introspection of this session's engine, mode, and feature support —
40
+ * mirrors connect()'s Chromium `page.capabilities`. Fields are launch-fixed
41
+ * except `stealth`, a live getter tracking the current headed/headless
42
+ * state. `reloadIgnoreCache` is false here (upstream BiDi gap); Firefox is
43
+ * never attach mode.
44
+ * @type {import('./index.js').Capabilities}
45
+ */
46
+ capabilities: import("./index.js").Capabilities;
36
47
  goto(url: any, timeout?: number): Promise<void>;
37
48
  /** @param {import('./index.js').SnapshotOptions|false} [pruneOpts] */
38
49
  snapshot(pruneOpts?: import("./index.js").SnapshotOptions | false): Promise<string>;
package/types/index.d.ts CHANGED
@@ -29,7 +29,7 @@
29
29
  * @returns {Promise<string>} ARIA snapshot text
30
30
  */
31
31
  export function browse(url: string, opts?: {
32
- mode?: "headed" | "headless" | "hybrid" | undefined;
32
+ mode?: "headed" | "hybrid" | "headless" | undefined;
33
33
  cookies?: boolean | undefined;
34
34
  incognito?: boolean | undefined;
35
35
  prune?: boolean | undefined;
@@ -50,104 +50,32 @@ export function browse(url: string, opts?: {
50
50
  pruneMode?: "act" | "browse" | "navigate" | "full" | "read" | undefined;
51
51
  }): Promise<string>;
52
52
  /**
53
- * The interactive page handle returned by {@link connect}. Inferred structurally
54
- * from the returned object literals — no hand-maintained interface to drift.
55
- *
56
- * It is a union of the two engine page shapes (Chromium/CDP and Firefox/BiDi),
57
- * which share every interaction method (`goto`, `snapshot`, `click`, `type`,
58
- * `close`, …) but differ in their escape hatches — `cdp`/`createTab`/`dialogLog`
59
- * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
60
- * without narrowing; an engine-specific hatch requires knowing the engine
61
- * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
62
- * @typedef {Awaited<ReturnType<typeof connect>>} Page
63
- */
64
- /**
65
- * Options for `page.snapshot()`. Pass `false` instead of an object to skip
66
- * pruning and return the raw ARIA tree.
67
- * @typedef {{ mode?: 'act'|'browse'|'navigate'|'full'|'read' }} SnapshotOptions
68
- */
69
- /**
70
- * Options for `page.type()`.
71
- * @typedef {{ clear?: boolean, keyEvents?: boolean }} TypeOptions
72
- */
73
- /**
74
- * Options for `page.injectCookies()`.
75
- * @typedef {{ browser?: string }} CookieOptions
76
- */
77
- /**
78
- * Connect to a browser for a long-lived interactive session.
79
- *
80
- * @param {object} [opts]
81
- * @param {'headless'|'headed'|'hybrid'} [opts.mode='headless'] - Browser mode
82
- * @param {number} [opts.port] - Attach to an already-running Chromium at this
83
- * CDP port instead of launching a new one. The browser keeps running on
84
- * close(); only the tab we created is torn down. Use this to drive a
85
- * user's logged-in session (start Chromium with --remote-debugging-port=N).
86
- * @param {string} [opts.downloadPath] - Directory to save downloaded files.
87
- * Default: a per-session subdirectory under the OS temp dir. Downloads
88
- * land here as <guid>; check `page.downloads` for { url, suggestedFilename,
89
- * savedPath, state, totalBytes, receivedBytes } per file.
90
- * @param {boolean} [opts.blockAds] - Block ~120 common ad/tracker URL
91
- * patterns via CDP. Defaults to true for launched browsers, false in
92
- * attach mode (would affect any tab attached to the user's running
93
- * session). Setting blockAds:true explicitly in attach mode honors the
94
- * request — blocking applies to whichever tab the session is currently
95
- * attached to and follows the session across switchTab() until close.
96
- * @param {string[]} [opts.blockUrls] - Extra URL glob patterns to block,
97
- * merged with the default unless blockAds is false.
98
- * @param {boolean} [opts.allowLocalUrls=false] - Permit navigation to local-
99
- * resource schemes (file:, view-source:, chrome:, …). Blocked by default
100
- * because a prompt-injected agent could use them to read local files.
101
- * @param {boolean} [opts.blockPrivateNetwork=false] - Reject navigation to
102
- * loopback / RFC-1918 / link-local / cloud-metadata hosts (SSRF guard).
103
- * Off by default so localhost dev-server browsing keeps working.
104
- * @param {string} [opts.uploadDir] - When set, upload() rejects any file that
105
- * does not resolve (symlinks included) inside this directory. Sandboxes the
106
- * agent's file-upload capability. Default: no restriction.
107
- * @param {string} [opts.proxy] - Proxy server (e.g. 'http://host:port').
108
- * @param {string} [opts.binary] - Path to browser binary (auto-detected if omitted).
109
- * @param {string} [opts.userDataDir] - Browser profile directory.
110
- * @param {{width: number, height: number}} [opts.viewport] - Viewport dimensions.
111
- * @param {boolean} [opts.consent=true] - Auto-dismiss cookie consent dialogs.
112
- * @param {string} [opts.storageState] - Path to a storage-state JSON file
113
- * (cookies + localStorage) to load before navigation.
114
- * @param {boolean} [opts.incognito=false] - Clean, unauthenticated session:
115
- * skip storageState loading and make injectCookies() a no-op, so no auth
116
- * ever enters the session even if a caller injects unconditionally.
117
- * @param {'act'|'browse'|'navigate'|'full'|'read'} [opts.pruneMode='act'] - Pruning mode.
118
- * @param {'chromium'|'firefox'} [opts.engine='chromium'] - Browser engine.
119
- * 'firefox' drives over WebDriver BiDi (a separate transport / page object);
120
- * 'chromium' (default) uses CDP.
121
- * @returns The interactive page handle — see the exported `Page` typedef. The
122
- * return type is left uninferred here (no `{...}` tag) so tsc derives it
123
- * structurally from the returned object literals; annotating it as `Page`
124
- * would be a self-reference, since `Page` is `ReturnType<typeof connect>`.
53
+ * Decide which engine connect() should use. Pure — the caller passes lazy
54
+ * probe thunks so this is unit-testable without launching a browser.
55
+ * An explicit `opts.engine` is always honored (existence is checked downstream
56
+ * by launch()/connectFirefox(), which throw a clear install message if missing).
57
+ * Attach mode (`opts.port`) is CDP/Chromium-only. Otherwise (no engine picked)
58
+ * prefer Chromium, fall back to Firefox, and if neither is installed throw.
59
+ * @param {{engine?: string, port?: number}} opts
60
+ * @param {{hasChromium: () => boolean, hasFirefox: () => boolean}} probe
61
+ * @returns {{engine: 'chromium'|'firefox', fellBack: boolean}}
125
62
  */
126
- export function connect(opts?: {
127
- mode?: "headed" | "headless" | "hybrid" | undefined;
128
- port?: number | undefined;
129
- downloadPath?: string | undefined;
130
- blockAds?: boolean | undefined;
131
- blockUrls?: string[] | undefined;
132
- allowLocalUrls?: boolean | undefined;
133
- blockPrivateNetwork?: boolean | undefined;
134
- uploadDir?: string | undefined;
135
- proxy?: string | undefined;
136
- binary?: string | undefined;
137
- userDataDir?: string | undefined;
138
- viewport?: {
139
- width: number;
140
- height: number;
141
- } | undefined;
142
- consent?: boolean | undefined;
143
- storageState?: string | undefined;
144
- incognito?: boolean | undefined;
145
- pruneMode?: "act" | "browse" | "navigate" | "full" | "read" | undefined;
146
- engine?: "chromium" | "firefox" | undefined;
147
- }): Promise<{
63
+ export function resolveEngine(opts: {
64
+ engine?: string;
65
+ port?: number;
66
+ }, probe: {
67
+ hasChromium: () => boolean;
68
+ hasFirefox: () => boolean;
69
+ }): {
70
+ engine: "chromium" | "firefox";
71
+ fellBack: boolean;
72
+ };
73
+ export function connect(opts?: {}): Promise<{
148
74
  readonly bidi: any;
149
75
  readonly context: any;
150
76
  readonly botBlocked: boolean;
77
+ engine: "firefox";
78
+ capabilities: import("./index.js").Capabilities;
151
79
  goto(url: any, timeout?: number): Promise<void>;
152
80
  snapshot(pruneOpts?: import("./index.js").SnapshotOptions | false): Promise<string>;
153
81
  readable(): Promise<any>;
@@ -205,6 +133,17 @@ export function connect(opts?: {
205
133
  waitFor(waitOpts?: {}): Promise<void>;
206
134
  saveState(filePath: any): Promise<void>;
207
135
  readonly botBlocked: boolean;
136
+ /** @type {'chromium'} Engine driving this session (see also `capabilities`) */
137
+ engine: "chromium";
138
+ /**
139
+ * Introspection of this session's engine, mode, and feature support — see
140
+ * the `Capabilities` typedef. Fields are launch-fixed except `stealth`,
141
+ * which is a live getter tracking the current headed/headless state (flips
142
+ * after a hybrid headed relaunch). Lets a caller ask "which engine am I on
143
+ * and what can it do?" without probing for `cdp`/`bidi`.
144
+ * @type {Capabilities}
145
+ */
146
+ capabilities: Capabilities;
208
147
  dialogLog: any[];
209
148
  /**
210
149
  * Install a custom JS dialog handler. The handler is called with
@@ -253,8 +192,57 @@ export { isChallengePage };
253
192
  * on Chromium, `bidi`/`context` on Firefox. The shared methods dereference
254
193
  * without narrowing; an engine-specific hatch requires knowing the engine
255
194
  * (the default is Chromium), e.g. `if ('cdp' in page) page.cdp.send(...)`.
195
+ * Both shapes carry `page.engine` (`'chromium'`|`'firefox'`) and a
196
+ * `page.capabilities` object so a caller can introspect which engine drives
197
+ * the session and what it supports without probing for an escape hatch.
256
198
  */
257
199
  export type Page = Awaited<ReturnType<typeof connect>>;
200
+ /**
201
+ * Description of what the current session can do — engine, mode, and the
202
+ * mode/engine-derived feature flags that actually differ between sessions. Read
203
+ * it via `page.capabilities` instead of inferring from the engine name. All
204
+ * fields are launch-fixed engine/mode facts except `stealth`, which reflects
205
+ * the CURRENT headed/headless state and can flip mid-session after a hybrid
206
+ * bot-challenge fallback relaunches a headed browser. `attach` is Chromium
207
+ * `connect({port})` (no stealth/downloads); `reloadIgnoreCache` is false on
208
+ * Firefox (upstream BiDi gap). Each remaining flag has its own driver:
209
+ * `downloads` is off when attached, `stealth` off when attached or headed,
210
+ * `cookieInjection` off in incognito.
211
+ */
212
+ export type Capabilities = {
213
+ /**
214
+ * - Engine driving this session
215
+ */
216
+ engine: "chromium" | "firefox";
217
+ /**
218
+ * - Launch mode
219
+ */
220
+ mode: "headless" | "headed" | "hybrid";
221
+ /**
222
+ * - Attached to a user-launched browser (Chromium only)
223
+ */
224
+ attach: boolean;
225
+ /**
226
+ * - Name of the raw-protocol escape-hatch property
227
+ */
228
+ escapeHatch: "cdp" | "bidi";
229
+ /**
230
+ * - `reload({ignoreCache})` is honored
231
+ */
232
+ reloadIgnoreCache: boolean;
233
+ /**
234
+ * - `page.downloads` is populated
235
+ */
236
+ downloads: boolean;
237
+ /**
238
+ * - Headless anti-detection is currently active (live — reflects present headed/headless state, not just launch mode)
239
+ */
240
+ stealth: boolean;
241
+ /**
242
+ * - Cookie extraction/injection is active (off in incognito)
243
+ */
244
+ cookieInjection: boolean;
245
+ };
258
246
  /**
259
247
  * Options for `page.snapshot()`. Pass `false` instead of an object to skip
260
248
  * pruning and return the raw ARIA tree.