barebrowse 0.20.0 → 0.21.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,66 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.21.0] - 2026-09-17
4
+
5
+ ### Added
6
+
7
+ - **`connect()` falls back to Firefox when no Chromium is installed.** With no
8
+ `engine` passed, it prefers Chromium but uses Firefox (over WebDriver BiDi)
9
+ if only Firefox is present, warning once to stderr; if neither is installed it
10
+ throws naming both. An explicit `engine` is still honored exactly — it errors
11
+ on a missing binary rather than silently switching — and attach mode (`port`)
12
+ stays Chromium-only. The decision is a pure, unit-tested `resolveEngine()`.
13
+ (`browse()` remains Chromium-only — separate.)
14
+ - **The MCP surface now advertises the active engine.** Firefox is selectable
15
+ only at server launch (`BAREBROWSE_ENGINE`), which a running agent can't see —
16
+ so agents concluded only Chromium existed. Three surfaces now expose it: the
17
+ `initialize` response carries `instructions` naming the active engine + that
18
+ both engines are supported; the `browse` tool description gets the active
19
+ engine appended at `tools/list` time; and a new **`capabilities`** MCP tool
20
+ reports the active engine, mode, both available engines, how to switch (a
21
+ server restart — the engine is fixed for a running session), and the live
22
+ capability flags if a page is open. `capabilities` is pure introspection: it
23
+ never launches a browser.
24
+ - **Session introspection: `page.engine` + `page.capabilities`.** Both engine
25
+ shapes now carry `page.engine` (`'chromium'` | `'firefox'`) and a
26
+ `page.capabilities` object (`engine`, `mode`, `attach`, `escapeHatch`,
27
+ `reloadIgnoreCache`, `downloads`, `stealth`, `cookieInjection`), so a caller
28
+ can ask "which engine am I on and what can it do?" without probing for a
29
+ `cdp`/`bidi` escape hatch. `engine` is a typed literal in each arm, so it also
30
+ works as a discriminant (`if (page.engine === 'firefox') …`) — cleaner than
31
+ the previous `'cdp' in page`. The CLI daemon persists both into
32
+ `session.json`, so `status`/`doctor` report the live session's feature set.
33
+ - **`barebrowse doctor` now reports the runtime environment**, not just MCP
34
+ config scope conflicts: the default engine/mode (incl. the `BAREBROWSE_ENGINE`
35
+ / `BAREBROWSE_MODE` / `BAREBROWSE_INCOGNITO` overrides that pick the engine at
36
+ launch), which Chromium and Firefox binaries are installed, which cookie
37
+ sources exist, and any live session's engine + capabilities. This closes the
38
+ discoverability gap where the Firefox engine — selectable only via a
39
+ server-launch env var — was invisible to a running session.
40
+ - **AX-fidelity harness (`test/integration/ax-fidelity.test.js`).** Drives the
41
+ same fixture pages through both engines and asserts the Firefox/BiDi
42
+ reconstruction never drops a semantic (role + name) node the CDP baseline
43
+ found — making repeatable the by-hand comparison that originally caught four
44
+ reconstruction bugs. Compares role+name only; property brackets and
45
+ `StaticText` echoes legitimately differ between engines.
46
+
47
+ ### Fixed
48
+
49
+ - **`page.capabilities.stealth` now correctly reflects live headed/headless
50
+ state.** It was computed once at `connect()`; after a hybrid bot-challenge
51
+ fallback relaunched a headed browser, `capabilities.stealth` (and the MCP
52
+ `capabilities` tool, and the CLI daemon's persisted `session.json`) kept
53
+ reporting the launch-time value. Now a getter on both engines that reads the
54
+ live state. JSDoc on both engine arms corrected to mark `stealth` live vs
55
+ the other launch-fixed fields, and a regression test asserts it is a real
56
+ getter (property descriptor has `get`), not a value captured at `connect()`
57
+ — a frozen field would have passed the previous test.
58
+ - **Corrected a stale doc line claiming Firefox "is not yet implemented."**
59
+ `barebrowse.context.md` note #10 still said the library was Chromium-only;
60
+ Firefox/BiDi has shipped since v0.15.0 (parity reached across v0.16–0.19).
61
+ The line now documents both engines and how to select Firefox — the same
62
+ false claim had led a session to conclude Firefox wasn't supported.
63
+ - **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
64
 
5
65
  ## [0.20.0] - 2026-08-30
6
66
 
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,11 @@ 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
100
 
101
101
  `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
102
 
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.
103
+ `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
104
 
105
105
  ### 3. Library -- for agentic automation
106
106
 
@@ -152,7 +152,11 @@ Firefox is at practical parity with Chromium: stealth, consent auto-dismiss,
152
152
  ad/tracker blocking, JS dialogs, console/network capture, hybrid fallback,
153
153
  `saveState`, `waitForNavigation`, and download tracking all work the same way.
154
154
  Chromium (CDP) stays the default; the only remaining gap is
155
- `reload({ignoreCache})` (upstream BiDi limitation).
155
+ `reload({ignoreCache})` (upstream BiDi limitation). With no explicit `engine`,
156
+ `connect()` falls back to Firefox (warning once to stderr) if no Chromium
157
+ browser is installed, and throws naming both if neither is; an explicit
158
+ `engine` is always honored and errors on a missing binary instead of silently
159
+ switching.
156
160
 
157
161
  ### Incognito (clean session)
158
162
 
@@ -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
+ | `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. |
97
99
  | `close()` | -- | void | Close page, disconnect CDP, kill browser (if headless) |
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
@@ -382,7 +384,7 @@ Useful for agent threshold decisions: "skip sites above score 40", "warn if term
382
384
 
383
385
  9. **Screenshot returns base64.** Write to file with `fs.writeFileSync('shot.png', Buffer.from(base64, 'base64'))` or pass directly to a vision model.
384
386
 
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.
387
+ 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
388
 
387
389
  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
390
 
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
@@ -118,6 +118,31 @@ export function saveSnapshot(text, { prefix = 'page', ext = 'yml' } = {}) {
118
118
  let _page = null;
119
119
  let _pageConnecting = null;
120
120
 
121
+ /**
122
+ * The engine + mode this server is configured to use, derived from env WITHOUT
123
+ * launching a browser. Both engines ship in the library; which one this server
124
+ * drives is fixed at launch by BAREBROWSE_ENGINE and cannot change mid-session
125
+ * (one browser is connected and reused across tool calls). Surfaced to the
126
+ * agent via `initialize.instructions`, the `capabilities` tool, and the `browse`
127
+ * tool description so the Firefox engine is discoverable — it was invisible
128
+ * before, and a session concluded (wrongly) that only Chromium was supported.
129
+ */
130
+ function engineInfo() {
131
+ const engine = process.env.BAREBROWSE_ENGINE === 'firefox' ? 'firefox' : 'chromium';
132
+ const mode = process.env.BAREBROWSE_MODE || 'hybrid';
133
+ const incognito = process.env.BAREBROWSE_INCOGNITO === '1';
134
+ return {
135
+ activeEngine: engine,
136
+ mode,
137
+ incognito,
138
+ availableEngines: ['chromium', 'firefox'],
139
+ // Engine is chosen once at server launch — the agent cannot switch it.
140
+ switchEngine:
141
+ "To use the other engine, restart the MCP server with BAREBROWSE_ENGINE=firefox "
142
+ + "(or unset it for the chromium default). It cannot be changed during a session.",
143
+ };
144
+ }
145
+
121
146
  async function getPage() {
122
147
  if (_page) return _page;
123
148
  if (_pageConnecting) return _pageConnecting;
@@ -363,6 +388,11 @@ export const TOOLS = [
363
388
  required: ['ref'],
364
389
  },
365
390
  },
391
+ {
392
+ name: 'capabilities',
393
+ 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.',
394
+ inputSchema: { type: 'object', properties: {} },
395
+ },
366
396
  ];
367
397
 
368
398
  // Powerful escape hatch — guarded behind an explicit env-var opt-in.
@@ -402,6 +432,19 @@ if (assessFn) {
402
432
 
403
433
  async function handleToolCall(name, args) {
404
434
  switch (name) {
435
+ case 'capabilities': {
436
+ // Introspection only — must NOT launch a browser. Report the configured
437
+ // engine from env; if a page is already connected, attach its live flags.
438
+ const info = engineInfo();
439
+ if (_page) {
440
+ info.connected = true;
441
+ info.capabilities = _page.capabilities;
442
+ } else {
443
+ info.connected = false;
444
+ info.capabilities = null; // populated on first navigation
445
+ }
446
+ return info;
447
+ }
405
448
  case 'browse': {
406
449
  let timer;
407
450
  const text = await Promise.race([
@@ -620,10 +663,17 @@ async function handleMessage(msg) {
620
663
  const { id, method, params } = msg;
621
664
 
622
665
  if (method === 'initialize') {
666
+ const e = engineInfo();
623
667
  return jsonrpcResponse(id, {
624
668
  protocolVersion: '2024-11-05',
625
669
  capabilities: { tools: {} },
626
670
  serverInfo: { name: 'barebrowse', version: PKG_VERSION },
671
+ // Tell the agent which engine is live + that the other exists. `instructions`
672
+ // is a standard MCP field clients may show to the model.
673
+ instructions:
674
+ `barebrowse drives a real browser. Active engine: ${e.activeEngine} (mode: ${e.mode}). `
675
+ + `Both chromium and firefox are supported; ${e.switchEngine} `
676
+ + `Call the "capabilities" tool for the live engine + feature set.`,
627
677
  });
628
678
  }
629
679
 
@@ -632,7 +682,13 @@ async function handleMessage(msg) {
632
682
  }
633
683
 
634
684
  if (method === 'tools/list') {
635
- return jsonrpcResponse(id, { tools: TOOLS });
685
+ // Append the live engine note to the `browse` entry-point description so the
686
+ // active engine (and that both are supported) is visible without a call.
687
+ const e = engineInfo();
688
+ const note = ` [Active engine: ${e.activeEngine}; chromium + firefox both supported — ${e.switchEngine}]`;
689
+ const tools = TOOLS.map((t) =>
690
+ t.name === 'browse' ? { ...t, description: t.description + note } : t);
691
+ return jsonrpcResponse(id, { tools });
636
692
  }
637
693
 
638
694
  if (method === 'tools/call') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barebrowse",
3
- "version": "0.20.0",
3
+ "version": "0.21.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",
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.
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
  /**
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.