bidi-browser-mcp 0.1.9

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.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -0
  3. package/dist/bin.d.ts +6 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/config.d.ts +6 -0
  6. package/dist/config.js +122 -0
  7. package/dist/connection/bidi-client.d.ts +29 -0
  8. package/dist/connection/bidi-client.js +298 -0
  9. package/dist/connection/browser-discovery.d.ts +30 -0
  10. package/dist/connection/browser-discovery.js +393 -0
  11. package/dist/connection/chromium-mapper.d.ts +55 -0
  12. package/dist/connection/chromium-mapper.js +293 -0
  13. package/dist/connection/event-pipeline.d.ts +37 -0
  14. package/dist/connection/event-pipeline.js +167 -0
  15. package/dist/index.d.ts +19 -0
  16. package/dist/index.js +66 -0
  17. package/dist/profile/profile-store.d.ts +88 -0
  18. package/dist/profile/profile-store.js +350 -0
  19. package/dist/session/context-manager.d.ts +17 -0
  20. package/dist/session/context-manager.js +179 -0
  21. package/dist/session/session-manager.d.ts +31 -0
  22. package/dist/session/session-manager.js +366 -0
  23. package/dist/snapshot/cache.d.ts +15 -0
  24. package/dist/snapshot/cache.js +37 -0
  25. package/dist/snapshot/dom-snapshot.d.ts +5 -0
  26. package/dist/snapshot/dom-snapshot.js +270 -0
  27. package/dist/snapshot/element-resolver.d.ts +13 -0
  28. package/dist/snapshot/element-resolver.js +25 -0
  29. package/dist/snapshot/token-optimizer.d.ts +16 -0
  30. package/dist/snapshot/token-optimizer.js +103 -0
  31. package/dist/tools/base-tool.d.ts +34 -0
  32. package/dist/tools/base-tool.js +55 -0
  33. package/dist/tools/browser.d.ts +1 -0
  34. package/dist/tools/browser.js +75 -0
  35. package/dist/tools/cleanup.d.ts +1 -0
  36. package/dist/tools/cleanup.js +64 -0
  37. package/dist/tools/console.d.ts +1 -0
  38. package/dist/tools/console.js +87 -0
  39. package/dist/tools/context.d.ts +1 -0
  40. package/dist/tools/context.js +156 -0
  41. package/dist/tools/observe.d.ts +1 -0
  42. package/dist/tools/observe.js +92 -0
  43. package/dist/tools/page.d.ts +1 -0
  44. package/dist/tools/page.js +139 -0
  45. package/dist/tools/ping.d.ts +1 -0
  46. package/dist/tools/ping.js +71 -0
  47. package/dist/tools/registry.d.ts +13 -0
  48. package/dist/tools/registry.js +47 -0
  49. package/dist/tools/spaces.d.ts +1 -0
  50. package/dist/tools/spaces.js +98 -0
  51. package/dist/tools/tabs.d.ts +1 -0
  52. package/dist/tools/tabs.js +155 -0
  53. package/dist/types.d.ts +277 -0
  54. package/dist/types.js +5 -0
  55. package/dist/utils/assert.d.ts +12 -0
  56. package/dist/utils/assert.js +74 -0
  57. package/dist/utils/errors.d.ts +24 -0
  58. package/dist/utils/errors.js +60 -0
  59. package/dist/utils/result.d.ts +14 -0
  60. package/dist/utils/result.js +37 -0
  61. package/package.json +86 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tushar Agarwal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,343 @@
1
+ <p align="center">
2
+ <h1 align="center">BiDi Browser MCP Server</h1>
3
+ <p align="center">
4
+ <strong>Control your real Firefox over the W3C standard protocol.</strong><br>
5
+ Keep your cookies. Keep your sessions. Keep your containers.
6
+ </p>
7
+ </p>
8
+
9
+ <p align="center">
10
+ <img src="https://img.shields.io/badge/version-0.1.7-blue" alt="Version">
11
+ <img src="https://img.shields.io/badge/status-connect-orange" alt="Status">
12
+ <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="Node">
13
+ <img src="https://img.shields.io/badge/license-MIT-yellow" alt="License">
14
+ </p>
15
+
16
+ ---
17
+
18
+ ## Status
19
+
20
+ v0.1.9 — first public npm release. The stdio MCP server exposes `ping`,
21
+ `browser`, `tabs`, `page` (snapshot/content), `console`, `observe`, `context`
22
+ (containers), `spaces` (Zen), and `cleanup`. Socket drops clear session state
23
+ honestly and the next connect recovers. Chromium browsers are supported without
24
+ chromedriver: the `chromium-bidi` mapper runs inside this server and translates
25
+ BiDi to CDP, with Firefox-only tools gated by a clear `UNSUPPORTED` error.
26
+
27
+ v1 attaches to a Firefox you start; it does not launch, profile-manage, or close
28
+ the browser. Launch/private/incognito control is future work.
29
+
30
+ The full design and protocol research ship on the `dev` branch. `main` carries
31
+ product code and release artifacts only.
32
+
33
+ ## Why BiDi
34
+
35
+ Firefox removed CDP in Firefox 141. WebDriver BiDi is the W3C standard that
36
+ replaced it, and it is native in Firefox 129+ — no driver binary, no
37
+ Puppeteer/Playwright, no browser download.
38
+
39
+ Firefox-family browsers such as Zen, LibreWolf, Waterfox, and Floorp should work
40
+ once their Remote Agent is enabled; profile discovery still needs testing per
41
+ browser.
42
+
43
+ This server connects to an **already-running Firefox** over its native BiDi
44
+ WebSocket. Your logins, cookies, extensions, and containers stay intact.
45
+
46
+ ## Tool surface
47
+
48
+ Nine tools ship today (`core`): `ping` · `browser` · `tabs` · `page` ·
49
+ `console` · `observe` · `context` · `spaces` · `cleanup`.
50
+
51
+ Next (0.2.0) — the automation loop:
52
+
53
+ - `interact` — click, type, clear, press, select, check, upload, scroll
54
+ - `page.navigate` with `wait: none | domContentLoaded | load`
55
+ - `network` (opt-in, read-only): wait for request/response metadata
56
+ - gated `script.evaluate`
57
+
58
+ Later — state and environment:
59
+
60
+ - `storage` — cookies first, then web storage
61
+ - `emulate` — locale, timezone, geolocation (tested null-reset only)
62
+ - network intercepts with scoped, auto-removed handlers
63
+ - `extensions` — Firefox, install gated by `BIDI_ALLOW_EXTENSION_INSTALL`
64
+ - opt-in `devtools` — `moz:debugging` (Firefox 153+) and `moz:profiler`
65
+ (Firefox 154+), screencast (Firefox 154+), preload scripts and realms
66
+ - `BIDI_OUTPUT_MODE=file`, health monitor
67
+
68
+ Firefox-specific capabilities:
69
+
70
+ - **User contexts** - isolated containers / storage (not the same as a private
71
+ window)
72
+ - **Web extension install/list/uninstall** (install is opt-in and path-gated)
73
+ - **Preload scripts** and script realms
74
+ - **Debugger and profiler** - `moz:debugging` (Firefox 153+) and
75
+ `moz:profiler` (Firefox 154+), opt-in `devtools` toolset
76
+ - **Screencast** - Firefox 154+
77
+
78
+ Not available in BiDi (compared with CDP): full accessibility tree, CSS domain,
79
+ heap snapshots, network/CPU throttling, touch emulation. Debugger and profiler
80
+ are Firefox vendor modules, not part of the core W3C command set, and do not
81
+ exist in every browser.
82
+
83
+ ## Cross-browser roadmap
84
+
85
+ Firefox-family browsers expose a native BiDi endpoint; this server attaches to
86
+ it directly. Chromium browsers (Chrome, Brave, Edge, Vivaldi, Chromium) expose
87
+ CDP only, so this server hosts the
88
+ [chromium-bidi mapper](https://github.com/GoogleChromeLabs/chromium-bidi)
89
+ in-process — no chromedriver and no driver binary. Safari is experimental and
90
+ partial, and is not supported yet.
91
+
92
+ ## Requirements
93
+
94
+ - Node.js 20.19+
95
+ - Firefox 129+ for the core surface; 153 ESR recommended; 158+ for the full
96
+ surface (debugger, profiler, screencast, newer emulation)
97
+ - Two runtime dependencies: `ws`, `@modelcontextprotocol/sdk`
98
+ - Optional: `chromium-bidi` for Chromium support. Its own `engines` range is
99
+ Node 20.19+, 21.x, or 22.12+ (22.0–22.11 are excluded); Firefox works on the
100
+ wider Node range either way.
101
+
102
+ ## Chromium browsers (Chrome, Brave, Edge, …)
103
+
104
+ Chromium does not speak WebDriver BiDi natively: `--remote-debugging-port`
105
+ exposes CDP, a different protocol. When this server discovers a Chromium
106
+ endpoint it starts the **chromium-bidi mapper inside its own process**, hands
107
+ it a CDP connection, and keeps speaking BiDi to the tool layer. No chromedriver,
108
+ no extension, no browser restart.
109
+
110
+ 1. Launch Chromium with `--remote-debugging-port=<port>`.
111
+ 2. Approve the debugging permission dialog in the browser window when the
112
+ server connects (Chromium asks once per connection).
113
+ 3. The optional mapper is installed together with this package. If it is
114
+ missing — an install that omitted optional dependencies, or Node outside
115
+ the mapper's range — Chromium sessions fail with `MISSING_DEPENDENCY` and
116
+ the fix names the exact command. npm users can install it beside the
117
+ server:
118
+
119
+ ```bash
120
+ npm install -g chromium-bidi@158.0.8123-0 # global npm server
121
+ npm install chromium-bidi@158.0.8123-0 # project npm server
122
+ ```
123
+
124
+ pnpm isolates global packages, so a separately installed global
125
+ `chromium-bidi` is not visible to the server; reinstall the server itself
126
+ (`pnpm add -g bidi-browser-mcp`) or run it through `pnpm dlx` instead.
127
+ The version is pinned because the mapper's deep import is a build artifact.
128
+ It also pulls `devtools-protocol` (about 30 MB on disk).
129
+
130
+ Discovery finds a running Chromium browser two ways: it reads
131
+ `DevToolsActivePort` from the standard Chrome, Brave, Edge, Chromium, and
132
+ Vivaldi user-data directories, and it resolves the `--user-data-dir` of a
133
+ running Chromium process — so portable installs work with no configuration.
134
+ `BIDI_CHROMIUM_DATA_DIR` adds directories explicitly (`;`-separated), and
135
+ `BIDI_WS_URL` can name the browser's
136
+ `ws://127.0.0.1:<port>/devtools/browser/<id>` URL. Chromium ports are never
137
+ probed as BiDi `/session` endpoints (they always answer 403).
138
+
139
+ `ping`, `browser`, `tabs`, `page`, `console`, `observe`, and `cleanup` work
140
+ through the mapper. Firefox-family features (`context`, `spaces`) refuse with
141
+ a clear `UNSUPPORTED` error on non-Firefox sessions. Firefox endpoints are
142
+ preferred when both browser families are running; set `BIDI_WS_URL` to force a
143
+ specific browser.
144
+
145
+ ## Start Firefox with BiDi
146
+
147
+ ```powershell
148
+ # Windows
149
+ & "C:\Program Files\Mozilla Firefox\firefox.exe" --remote-debugging-port=9222
150
+ ```
151
+
152
+ ```bash
153
+ # macOS / Linux
154
+ firefox --remote-debugging-port=9222
155
+ ```
156
+
157
+ BiDi endpoint: `ws://127.0.0.1:9222/session`
158
+
159
+ Firefox sets `navigator.webdriver === true` whenever the Remote Agent is
160
+ enabled. This is not a stealth or anti-detection tool; some sites may challenge
161
+ the session. There is no spoofing layer.
162
+
163
+ ## Test it now
164
+
165
+ For a quick endpoint check, use [`TESTING.md`](./TESTING.md). Short version:
166
+
167
+ ```powershell
168
+ & "C:\Program Files\Mozilla Firefox\firefox.exe" --remote-debugging-port=9223
169
+ pnpm build
170
+ pnpm smoke
171
+ ```
172
+
173
+ The smoke script calls `session.status` only; it does not take over the session.
174
+ `about:debugging` is not used by this MCP server.
175
+
176
+ To see whether a running Firefox-family process has the Remote Agent on:
177
+
178
+ ```powershell
179
+ pnpm detect
180
+ ```
181
+
182
+ ## Install
183
+
184
+ v0.1.9 is the first public release. Install globally with npm or pnpm:
185
+
186
+ ```bash
187
+ npm install -g bidi-browser-mcp
188
+ pnpm add -g bidi-browser-mcp
189
+ ```
190
+
191
+ A global install is the simplest MCP setup. For Chromium, avoid
192
+ `--omit=optional` (see Chromium browsers above).
193
+
194
+ Or reference it from an MCP client without a global install:
195
+
196
+ ```json
197
+ {
198
+ "mcpServers": {
199
+ "bidi-browser": {
200
+ "command": "npx",
201
+ "args": ["-y", "bidi-browser-mcp@latest"]
202
+ }
203
+ }
204
+ }
205
+ ```
206
+
207
+ The pnpm equivalent:
208
+
209
+ ```json
210
+ {
211
+ "mcpServers": {
212
+ "bidi-browser": {
213
+ "command": "pnpm",
214
+ "args": ["dlx", "bidi-browser-mcp@latest"]
215
+ }
216
+ }
217
+ }
218
+ ```
219
+
220
+ The published package contains only compiled `dist/` plus `README`, `LICENSE`,
221
+ and `package.json`. Repository docs, tests, and build scripts are not installed.
222
+
223
+ ## Setup
224
+
225
+ One-shot install/build/test/verify:
226
+
227
+ ```bash
228
+ pnpm setup
229
+ ```
230
+
231
+ If Firefox or Zen is running with `--remote-debugging-port`, this also probes the
232
+ BiDi endpoint automatically. No env vars are required for the common case.
233
+
234
+ Process-based discovery finds a running Firefox or Zen without env vars. There
235
+ is no supported in-browser toggle to start the Remote Agent.
236
+
237
+ ## Build from source
238
+
239
+ ```bash
240
+ pnpm install
241
+ pnpm build
242
+ pnpm typecheck
243
+ pnpm test
244
+ ```
245
+
246
+ Point your MCP client at `dist/bin.js` while developing. Use an absolute path in
247
+ your local client config; do not commit it:
248
+
249
+ ```json
250
+ {
251
+ "mcpServers": {
252
+ "bidi-browser": {
253
+ "command": "node",
254
+ "args": ["<absolute-path-to-repo>/dist/bin.js"]
255
+ }
256
+ }
257
+ }
258
+ ```
259
+
260
+ After `pnpm build`, restart the MCP server so it loads the new `dist/`. Once the
261
+ package is published, replace the dev entry with
262
+ `pnpm dlx bidi-browser-mcp@latest` (or a global install).
263
+
264
+ ## Troubleshooting
265
+
266
+ - **`MISSING_DEPENDENCY` on Chromium** — the optional `chromium-bidi` mapper is
267
+ not resolvable from the server. npm: install the exact pin beside the server
268
+ (`npm install -g chromium-bidi@158.0.8123-0`) or reinstall without
269
+ `--omit=optional`. pnpm: reinstall the server itself (`pnpm add -g
270
+ bidi-browser-mcp`) or use `pnpm dlx`; pnpm's global installs are isolated.
271
+ - **Chromium connect times out / hangs** — approve the in-browser debugging
272
+ permission dialog; Chromium stalls the connection until it is allowed.
273
+ - **`SESSION_BUSY` on Firefox/Zen** — Firefox allows one BiDi session. Close the
274
+ other client (another MCP server, a test script, DevTools) and retry; the
275
+ session is not released until the browser or the client ends it.
276
+ - **No Firefox endpoint found** — start the browser with
277
+ `--remote-debugging-port=9222` (Firefox/Zen) or set `BIDI_WS_URL`.
278
+
279
+ ## Configuration
280
+
281
+ `BIDI_OUTPUT_MODE=file` is not implemented yet and is rejected at startup; the
282
+ allow flags are reserved for later waves.
283
+
284
+ | Variable | Default | Description |
285
+ |---|---|---|
286
+ | `BIDI_HOST` | `127.0.0.1` | BiDi WebSocket host |
287
+ | `BIDI_PORT` | `9222` | BiDi WebSocket port |
288
+ | `BIDI_WS_URL` | auto | Override full WebSocket URL |
289
+ | `BIDI_PROFILE_DIR` | auto | Firefox profile directory for discovery |
290
+ | `BIDI_APP_DATA_ROOT` | `%APPDATA%` | App-data root used for profile discovery |
291
+ | `BIDI_LOCAL_APP_DATA_ROOT` | `%LOCALAPPDATA%` | Local app-data root used to find Chromium user-data dirs |
292
+ | `BIDI_CHROMIUM_DATA_DIR` | auto | Extra Chromium user-data dirs (one or more, `;`-separated) for `DevToolsActivePort` discovery |
293
+ | `BIDI_TIMEOUT` | `30000` | Command timeout (ms) |
294
+ | `BIDI_TOOLSET` | `core` | `core`, `network`, or `devtools` |
295
+ | `BIDI_OUTPUT_MODE` | `full` | `full` (no inline cut; snapshots capped at 1 MiB) or `inline` (fit `BIDI_MAX_INLINE_LEN`); `file` is rejected |
296
+ | `BIDI_MAX_INLINE_LEN` | `60000` | Max inline response chars |
297
+ | `BIDI_TEMP_DIR` | `.temp` | Temp file directory — parsed and validated, but no temp files are written yet (reserved for later waves) |
298
+ | `BIDI_ALLOW_EXTENSION_INSTALL` | `false` | Gate extension install |
299
+ | `BIDI_ALLOW_BROWSER_CLOSE` | `false` | Gate `browser.close` |
300
+
301
+ ## Safety limits
302
+
303
+ - Snapshots never read live field values. Passwords, tokens, and typed text
304
+ stay out of the snapshot, the agent context, and client logs.
305
+ - `tabs.new` opens `http:`, `https:`, and `about:blank` only. `file:`, `data:`,
306
+ `javascript:`, and `blob:` are rejected — they would turn the browser into a
307
+ local-file or script reader.
308
+ - `context.remove` needs `confirm: true`; it deletes the container with its
309
+ tabs, cookies, and storage.
310
+ - Non-loopback endpoints need `BIDI_ALLOW_REMOTE=1` — the gate covers every
311
+ discovered candidate, including profile files.
312
+
313
+ ## Architecture
314
+
315
+ ```
316
+ src/
317
+ ├── bin.ts # CLI entry (shebang) → dist/bin.js
318
+ ├── index.ts # public API: createServer(), VERSION
319
+ ├── config.ts # env-based config (only env reader)
320
+ ├── types.ts # shared contracts
321
+ ├── connection/ # planned: BiDi client, discovery, health, event pipeline
322
+ ├── session/ # planned: single-session manager, context manager
323
+ ├── snapshot/ # planned: JS DOM snapshots, cache, refs, token optimizer
324
+ ├── tools/ # defineTool, registry, ping, browser, tabs, page, console, observe, cleanup
325
+ ├── utils/ # errors, result envelope, argument guards
326
+ └── __tests__/ # hermetic unit tests + MockBiDiServer
327
+ ```
328
+
329
+ Firefox allows only one BiDi session at a time, so the server reuses a single
330
+ session instead of copying CDP's multi-session model. A second client gets
331
+ `BIDI_SESSION_BUSY`, not a retry loop. All tools in **one server process** share
332
+ the session; separate MCP server processes need the future broker. BiDi has no
333
+ full accessibility-tree API, so snapshots are built with `script.evaluate` plus
334
+ DOM traversal.
335
+
336
+ ## Contributing
337
+
338
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) and [AGENTS.md](./AGENTS.md). Work
339
+ happens on `dev`; PRs target `dev`, and releases are cut from `main`.
340
+
341
+ ## License
342
+
343
+ MIT © 2026 Tushar Agarwal
package/dist/bin.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI entry point: boot the MCP server over stdio.
4
+ * The shebang must stay on line 1 and use LF line endings.
5
+ */
6
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI entry point: boot the MCP server over stdio.
4
+ * The shebang must stay on line 1 and use LF line endings.
5
+ */
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { createServer, VERSION } from './index.js';
8
+ async function main() {
9
+ const { server, session } = createServer();
10
+ const transport = new StdioServerTransport();
11
+ await server.connect(transport);
12
+ console.error(`bidi-browser-mcp v${VERSION} ready (stdio)`);
13
+ // The browser's BiDi session must never outlive this process: end it when
14
+ // the client closes stdio or sends a termination signal. (SIGKILL cannot be
15
+ // handled anywhere.)
16
+ let shuttingDown = false;
17
+ const shutdown = () => {
18
+ if (shuttingDown) {
19
+ return;
20
+ }
21
+ shuttingDown = true;
22
+ void session
23
+ .disconnect()
24
+ .catch(() => { })
25
+ .finally(() => process.exit(0));
26
+ };
27
+ process.once('SIGINT', shutdown);
28
+ process.once('SIGTERM', shutdown);
29
+ process.once('SIGHUP', shutdown);
30
+ process.stdin.once('close', shutdown);
31
+ }
32
+ main().catch((error) => {
33
+ const message = error instanceof Error ? error.message : String(error);
34
+ console.error(`bidi-browser-mcp failed to start: ${message}`);
35
+ process.exit(1);
36
+ });
37
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1,6 @@
1
+ import type { Config } from './types.js';
2
+ /**
3
+ * The only module allowed to read environment variables.
4
+ * Pass an env object in tests; never read process.env elsewhere.
5
+ */
6
+ export declare function loadConfig(env?: NodeJS.ProcessEnv): Config;
package/dist/config.js ADDED
@@ -0,0 +1,122 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ import { ActionableError } from './utils/errors.js';
4
+ const TOOLSETS = ['core', 'network', 'devtools'];
5
+ const OUTPUT_MODES = ['full', 'inline', 'file'];
6
+ /**
7
+ * The only module allowed to read environment variables.
8
+ * Pass an env object in tests; never read process.env elsewhere.
9
+ */
10
+ export function loadConfig(env = process.env) {
11
+ const host = readString(env, 'BIDI_HOST') ?? '127.0.0.1';
12
+ const port = readInt(env, 'BIDI_PORT', 9222, 1, 65535);
13
+ const timeoutMs = readInt(env, 'BIDI_TIMEOUT', 30_000, 1);
14
+ const maxInlineLen = readInt(env, 'BIDI_MAX_INLINE_LEN', 60_000, 1);
15
+ const toolset = readEnum(env, 'BIDI_TOOLSET', 'core', TOOLSETS);
16
+ const outputMode = readEnum(env, 'BIDI_OUTPUT_MODE', 'full', OUTPUT_MODES);
17
+ const wsUrl = readString(env, 'BIDI_WS_URL');
18
+ const profileDir = readString(env, 'BIDI_PROFILE_DIR');
19
+ const tempDir = resolve(readString(env, 'BIDI_TEMP_DIR') ?? '.temp');
20
+ // Absolute app-data root, used by discovery on Windows so that no other
21
+ // module ever reads process.env directly.
22
+ const appDataRoot = resolve(readString(env, 'BIDI_APP_DATA_ROOT') ??
23
+ readString(env, 'APPDATA') ??
24
+ join(homedir(), 'AppData', 'Roaming'));
25
+ const allowRemote = readBoolean(env, 'BIDI_ALLOW_REMOTE', false);
26
+ const localAppDataRoot = resolve(readString(env, 'BIDI_LOCAL_APP_DATA_ROOT') ??
27
+ readString(env, 'LOCALAPPDATA') ??
28
+ join(homedir(), 'AppData', 'Local'));
29
+ const discoveryRoots = readStringList(env, 'BIDI_DISCOVERY_ROOTS');
30
+ const chromiumDataDirs = readStringList(env, 'BIDI_CHROMIUM_DATA_DIR');
31
+ if (wsUrl !== undefined) {
32
+ validateWebSocketUrl(wsUrl);
33
+ }
34
+ return Object.freeze({
35
+ host,
36
+ port,
37
+ ...(wsUrl === undefined ? {} : { wsUrl }),
38
+ ...(profileDir === undefined ? {} : { profileDir }),
39
+ timeoutMs,
40
+ toolset,
41
+ outputMode,
42
+ maxInlineLen,
43
+ tempDir,
44
+ appDataRoot,
45
+ localAppDataRoot,
46
+ allowExtensionInstall: readBoolean(env, 'BIDI_ALLOW_EXTENSION_INSTALL', false),
47
+ allowBrowserClose: readBoolean(env, 'BIDI_ALLOW_BROWSER_CLOSE', false),
48
+ allowRemote,
49
+ discoveryRoots: Object.freeze(discoveryRoots),
50
+ chromiumDataDirs: Object.freeze(chromiumDataDirs),
51
+ });
52
+ }
53
+ function readString(env, key) {
54
+ const value = env[key]?.trim();
55
+ return value === undefined || value === '' ? undefined : value;
56
+ }
57
+ function readInt(env, key, fallback, min, max = Number.MAX_SAFE_INTEGER) {
58
+ const raw = readString(env, key);
59
+ if (raw === undefined) {
60
+ return fallback;
61
+ }
62
+ if (!/^\d+$/.test(raw)) {
63
+ throw invalidConfig(key, `must be an integer between ${min} and ${max}`, `got "${raw}"`);
64
+ }
65
+ const value = Number(raw);
66
+ if (!Number.isSafeInteger(value) || value < min || value > max) {
67
+ throw invalidConfig(key, `must be an integer between ${min} and ${max}`, `got ${value}`);
68
+ }
69
+ return value;
70
+ }
71
+ function readStringList(env, key) {
72
+ const raw = readString(env, key);
73
+ if (raw === undefined) {
74
+ return [];
75
+ }
76
+ const values = raw
77
+ .split(/[;,\n]/)
78
+ .map((value) => value.trim())
79
+ .filter((value) => value !== '');
80
+ return values;
81
+ }
82
+ function readBoolean(env, key, fallback) {
83
+ const raw = readString(env, key)?.toLowerCase();
84
+ if (raw === undefined) {
85
+ return fallback;
86
+ }
87
+ if (['1', 'true', 'yes', 'on'].includes(raw)) {
88
+ return true;
89
+ }
90
+ if (['0', 'false', 'no', 'off'].includes(raw)) {
91
+ return false;
92
+ }
93
+ throw invalidConfig(key, 'must be a boolean (1/0, true/false, yes/no, on/off)', `got "${raw}"`);
94
+ }
95
+ function readEnum(env, key, fallback, allowed) {
96
+ const raw = readString(env, key);
97
+ if (raw === undefined) {
98
+ return fallback;
99
+ }
100
+ if (!allowed.includes(raw)) {
101
+ throw invalidConfig(key, `must be one of: ${allowed.join(', ')}`, `got "${raw}"`);
102
+ }
103
+ return raw;
104
+ }
105
+ function validateWebSocketUrl(value) {
106
+ let parsed;
107
+ try {
108
+ parsed = new URL(value);
109
+ }
110
+ catch {
111
+ throw invalidConfig('BIDI_WS_URL', 'must be a valid WebSocket URL', `got "${value}"`);
112
+ }
113
+ if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
114
+ throw invalidConfig('BIDI_WS_URL', 'must use ws:// or wss://', `got "${parsed.protocol}"`);
115
+ }
116
+ }
117
+ function invalidConfig(key, expectation, detail) {
118
+ return new ActionableError('INVALID_CONFIG', `${key} ${expectation}; ${detail}.`, {
119
+ fix: `Set ${key} to a valid value, or remove it to use the default.`,
120
+ });
121
+ }
122
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,29 @@
1
+ import type { BiDiEvent } from '../types.js';
2
+ import type { BiDiSocket } from './chromium-mapper.js';
3
+ export type BiDiClientState = 'disconnected' | 'connecting' | 'connected';
4
+ export interface BiDiClientOptions {
5
+ readonly url: string;
6
+ readonly timeoutMs: number;
7
+ /**
8
+ * Custom socket opener for transports that are not a plain WebSocket —
9
+ * the Chromium mapper facade. Must satisfy the `ws`-like BiDiSocket
10
+ * surface; the returned socket is treated as a WebSocket internally.
11
+ */
12
+ readonly openSocket?: () => Promise<BiDiSocket>;
13
+ }
14
+ /**
15
+ * Minimal BiDi WebSocket client. One command at a time is not required, but
16
+ * request IDs are unique and pending commands are always settled.
17
+ */
18
+ export declare class BiDiClient {
19
+ #private;
20
+ readonly url: string;
21
+ constructor(options: BiDiClientOptions);
22
+ get state(): BiDiClientState;
23
+ onEvent(handler: (event: BiDiEvent) => void): () => void;
24
+ /** Fires when the socket drops for any reason. One-shot semantics. */
25
+ onClose(handler: () => void): () => void;
26
+ connect(): Promise<void>;
27
+ request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
28
+ close(): Promise<void>;
29
+ }