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
@@ -0,0 +1,393 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { homedir, platform } from 'node:os';
3
+ import { join, resolve } from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { ActionableError } from '../utils/errors.js';
7
+ const execFileAsync = promisify(execFile);
8
+ const DISCOVERY_FILE = 'WebDriverBiDiServer.json';
9
+ const FIREFOX_FAMILY_PROCESSES = [
10
+ 'firefox',
11
+ 'zen',
12
+ 'librewolf',
13
+ 'waterfox',
14
+ 'floorp',
15
+ ];
16
+ /** Chromium-family binaries. They expose CDP, never a BiDi `/session` path. */
17
+ const CHROMIUM_FAMILY_PROCESSES = [
18
+ 'chrome',
19
+ 'chromium',
20
+ 'brave',
21
+ 'msedge',
22
+ 'vivaldi',
23
+ 'thorium',
24
+ 'yandex',
25
+ 'opera',
26
+ ];
27
+ const KNOWN_PROCESSES = [
28
+ ...FIREFOX_FAMILY_PROCESSES,
29
+ ...CHROMIUM_FAMILY_PROCESSES,
30
+ ];
31
+ /**
32
+ * Parse `--remote-debugging-port` from a process command line.
33
+ * Supports `--remote-debugging-port`, `--remote-debugging-port 9223`, and
34
+ * `--remote-debugging-port=9223`.
35
+ */
36
+ export function extractRemoteDebuggingPort(commandLine) {
37
+ const withValue = /--remote-debugging-port(?:=|\s+)(\d+)/.exec(commandLine);
38
+ if (withValue !== null) {
39
+ const port = Number(withValue[1]);
40
+ return Number.isSafeInteger(port) && port > 0 ? port : undefined;
41
+ }
42
+ return /--remote-debugging-port(?:\s|$)/.test(commandLine) ? 9222 : undefined;
43
+ }
44
+ /**
45
+ * Parse `--user-data-dir` from a Chromium command line. Portable installs (and
46
+ * custom profiles) only expose their CDP URL through the DevToolsActivePort
47
+ * file in that directory, so this is how Chromium is found without config.
48
+ */
49
+ export function extractUserDataDir(commandLine) {
50
+ // Accepts --user-data-dir="…", --user-data-dir=…, and --user-data-dir "…".
51
+ // An unquoted path with spaces is not recoverable; \S+ keeps the first token.
52
+ const match = /--user-data-dir(?:=|\s+)("([^"]+)"|((?!--)\S+))/.exec(commandLine);
53
+ return match?.[2] ?? match?.[3];
54
+ }
55
+ function isChromiumProcess(name) {
56
+ const base = name.toLowerCase().replace(/\.exe$/, '');
57
+ return CHROMIUM_FAMILY_PROCESSES.some((candidate) => base === candidate || base.includes(candidate));
58
+ }
59
+ function profileRoots(config) {
60
+ const home = homedir();
61
+ const roots = [...config.discoveryRoots];
62
+ if (platform() === 'win32') {
63
+ const appData = config.appDataRoot;
64
+ roots.push(join(appData, 'Mozilla', 'Firefox'));
65
+ roots.push(join(appData, 'Zen Browser'));
66
+ roots.push(join(appData, 'zen'));
67
+ }
68
+ else if (platform() === 'darwin') {
69
+ const base = join(home, 'Library', 'Application Support');
70
+ roots.push(join(base, 'Firefox'));
71
+ roots.push(join(base, 'Zen Browser'));
72
+ roots.push(join(base, 'zen'));
73
+ }
74
+ else {
75
+ roots.push(join(home, '.mozilla', 'firefox'));
76
+ roots.push(join(home, '.zen'));
77
+ }
78
+ return [...new Set(roots.map((root) => resolve(root)))].filter((root) => existsSync(root));
79
+ }
80
+ function parseProfilesIni(text) {
81
+ const sections = [];
82
+ let section;
83
+ for (const rawLine of text.split(/\r?\n/)) {
84
+ const line = rawLine.trim();
85
+ if (line === '' || line.startsWith(';') || line.startsWith('#')) {
86
+ continue;
87
+ }
88
+ if (line.startsWith('[') && line.endsWith(']')) {
89
+ section = {};
90
+ sections.push(section);
91
+ continue;
92
+ }
93
+ if (section !== undefined) {
94
+ const separatorIndex = line.indexOf('=');
95
+ if (separatorIndex > 0) {
96
+ section[line.slice(0, separatorIndex).trim()] = line.slice(separatorIndex + 1).trim();
97
+ }
98
+ }
99
+ }
100
+ return sections;
101
+ }
102
+ function profileDirsFromIni(root) {
103
+ const iniPath = join(root, 'profiles.ini');
104
+ if (!existsSync(iniPath)) {
105
+ return [];
106
+ }
107
+ try {
108
+ const sections = parseProfilesIni(readFileSync(iniPath, 'utf8'));
109
+ const dirs = [];
110
+ for (const section of sections) {
111
+ const path = section.Path ?? section.path;
112
+ if (path === undefined) {
113
+ continue;
114
+ }
115
+ const isRelative = section.IsRelative === '1' || section.isRelative === '1';
116
+ dirs.push(isRelative ? join(root, path) : resolve(path));
117
+ }
118
+ return dirs;
119
+ }
120
+ catch {
121
+ return [];
122
+ }
123
+ }
124
+ function profileDirsFromRoot(root) {
125
+ const profilesDir = join(root, 'Profiles');
126
+ if (!existsSync(profilesDir)) {
127
+ return [];
128
+ }
129
+ try {
130
+ return readdirSync(profilesDir, { withFileTypes: true })
131
+ .filter((entry) => entry.isDirectory())
132
+ .map((entry) => join(profilesDir, entry.name));
133
+ }
134
+ catch {
135
+ return [];
136
+ }
137
+ }
138
+ function discoveryUrlFor(profileDir) {
139
+ const path = join(profileDir, DISCOVERY_FILE);
140
+ if (!existsSync(path)) {
141
+ return undefined;
142
+ }
143
+ try {
144
+ const discovery = JSON.parse(readFileSync(path, 'utf8'));
145
+ if (typeof discovery.ws_host === 'string' &&
146
+ typeof discovery.ws_port === 'number' &&
147
+ Number.isInteger(discovery.ws_port) &&
148
+ discovery.ws_port >= 1 &&
149
+ discovery.ws_port <= 65535) {
150
+ return `ws://${discovery.ws_host}:${discovery.ws_port}/session`;
151
+ }
152
+ }
153
+ catch {
154
+ // Ignore malformed discovery files.
155
+ }
156
+ return undefined;
157
+ }
158
+ /**
159
+ * Chromium-family user-data directories that write a `DevToolsActivePort`
160
+ * file (port + browser WebSocket path) when started with
161
+ * `--remote-debugging-port`. Extra dirs come from BIDI_CHROMIUM_DATA_DIR.
162
+ */
163
+ function chromiumDataDirs(config) {
164
+ const home = homedir();
165
+ const dirs = [...config.chromiumDataDirs];
166
+ if (platform() === 'win32') {
167
+ const local = config.localAppDataRoot;
168
+ dirs.push(join(local, 'Google', 'Chrome', 'User Data'), join(local, 'BraveSoftware', 'Brave-Browser', 'User Data'), join(local, 'Microsoft', 'Edge', 'User Data'), join(local, 'Chromium', 'User Data'), join(local, 'Vivaldi', 'User Data'));
169
+ }
170
+ else if (platform() === 'darwin') {
171
+ const base = join(home, 'Library', 'Application Support');
172
+ dirs.push(join(base, 'Google', 'Chrome'), join(base, 'BraveSoftware', 'Brave-Browser'), join(base, 'Microsoft Edge'), join(base, 'Chromium'), join(base, 'Vivaldi'));
173
+ }
174
+ else {
175
+ const base = join(home, '.config');
176
+ dirs.push(join(base, 'google-chrome'), join(base, 'BraveSoftware', 'Brave-Browser'), join(base, 'microsoft-edge'), join(base, 'chromium'), join(base, 'vivaldi'));
177
+ }
178
+ return [...new Set(dirs.map((dir) => resolve(dir)))].filter((dir) => existsSync(dir));
179
+ }
180
+ /**
181
+ * Read `DevToolsActivePort`: first line is the port, second is the browser
182
+ * WebSocket path (`/devtools/browser/<id>`). Returns a CDP endpoint the mapper
183
+ * can attach to; the browser must already be running.
184
+ */
185
+ export function chromiumEndpointFromDataDir(dataDir) {
186
+ const file = join(dataDir, 'DevToolsActivePort');
187
+ if (!existsSync(file)) {
188
+ return undefined;
189
+ }
190
+ try {
191
+ const [portLine, pathLine] = readFileSync(file, 'utf8').split(/\r?\n/);
192
+ const port = Number((portLine ?? '').trim());
193
+ const wsPath = (pathLine ?? '').trim();
194
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
195
+ return undefined;
196
+ }
197
+ if (!wsPath.startsWith('/devtools/browser/')) {
198
+ return undefined;
199
+ }
200
+ return `ws://127.0.0.1:${port}${wsPath}`;
201
+ }
202
+ catch {
203
+ return undefined;
204
+ }
205
+ }
206
+ /**
207
+ * Gate every discovered candidate against BIDI_ALLOW_REMOTE, not just the
208
+ * explicit BIDI_WS_URL case. Profile files are user-writable data — a tampered
209
+ * or rogue WebDriverBiDiServer.json must not point the server at a remote host.
210
+ */
211
+ export function endpointAllowed(config, endpoint) {
212
+ return config.allowRemote || isLoopback(endpoint);
213
+ }
214
+ function isLoopback(url) {
215
+ try {
216
+ const parsed = new URL(url);
217
+ return ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname);
218
+ }
219
+ catch {
220
+ return false;
221
+ }
222
+ }
223
+ function addCandidate(candidates, candidate) {
224
+ if (!candidates.some((existing) => existing.endpoint === candidate.endpoint)) {
225
+ candidates.push(candidate);
226
+ }
227
+ }
228
+ async function processCommandLines() {
229
+ try {
230
+ if (platform() === 'win32') {
231
+ const script = `Get-CimInstance Win32_Process | Where-Object { $_.Name -match '${KNOWN_PROCESSES.join('|')}' } | Select-Object ProcessId,Name,CommandLine | ConvertTo-Json -Compress`;
232
+ const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-Command', script], { timeout: 5_000, maxBuffer: 10 * 1024 * 1024 });
233
+ const parsed = JSON.parse(stdout);
234
+ const normalized = Array.isArray(parsed) ? parsed : [parsed];
235
+ return normalized
236
+ .filter((item) => typeof item.CommandLine === 'string' && typeof item.Name === 'string')
237
+ .map((item) => ({
238
+ processId: typeof item.ProcessId === 'number' ? item.ProcessId : 0,
239
+ name: item.Name,
240
+ commandLine: item.CommandLine,
241
+ }));
242
+ }
243
+ const { stdout } = await execFileAsync('ps', ['-axo', 'pid=,command='], {
244
+ timeout: 5_000,
245
+ maxBuffer: 10 * 1024 * 1024,
246
+ });
247
+ return stdout
248
+ .split(/\r?\n/)
249
+ .map((line) => /^\s*(\d+)\s+(.*)$/.exec(line.trim()))
250
+ .filter((match) => match !== null)
251
+ .flatMap((match) => {
252
+ const commandLine = match[2];
253
+ const name = KNOWN_PROCESSES.find((candidate) => commandLine.toLowerCase().includes(candidate));
254
+ return name === undefined
255
+ ? []
256
+ : [{ processId: Number(match[1]), name, commandLine }];
257
+ });
258
+ }
259
+ catch {
260
+ return [];
261
+ }
262
+ }
263
+ function addChromiumPort(ports, endpoint) {
264
+ const port = Number(new URL(endpoint).port);
265
+ if (Number.isInteger(port) && port > 0) {
266
+ ports.add(port);
267
+ }
268
+ }
269
+ async function processCandidates() {
270
+ const processes = await processCommandLines();
271
+ const candidates = [];
272
+ const chromiumPorts = new Set();
273
+ const seenDataDirs = new Set();
274
+ for (const item of processes) {
275
+ if (isChromiumProcess(item.name)) {
276
+ // Chromium answers `/session` with 403; the usable attach point is the
277
+ // CDP browser WebSocket recorded in its DevToolsActivePort file. Portable
278
+ // launchers often hide the port flag, so key on --user-data-dir instead.
279
+ const dataDir = extractUserDataDir(item.commandLine);
280
+ if (dataDir === undefined || seenDataDirs.has(dataDir)) {
281
+ continue;
282
+ }
283
+ seenDataDirs.add(dataDir);
284
+ const endpoint = chromiumEndpointFromDataDir(dataDir);
285
+ if (endpoint === undefined) {
286
+ continue;
287
+ }
288
+ addChromiumPort(chromiumPorts, endpoint);
289
+ addCandidate(candidates, {
290
+ endpoint,
291
+ source: 'chromium-devtools-port',
292
+ processId: item.processId,
293
+ profilePath: dataDir,
294
+ browserFamily: 'chromium',
295
+ });
296
+ continue;
297
+ }
298
+ const port = extractRemoteDebuggingPort(item.commandLine);
299
+ if (port === undefined) {
300
+ continue;
301
+ }
302
+ addCandidate(candidates, {
303
+ endpoint: `ws://127.0.0.1:${port}/session`,
304
+ source: 'process-cmdline',
305
+ processId: item.processId,
306
+ });
307
+ }
308
+ return { candidates, chromiumPorts };
309
+ }
310
+ function portCandidates(config, chromiumPorts) {
311
+ const ports = [...new Set([config.port, 9222, 9223])].filter((port) => !chromiumPorts.has(port));
312
+ return ports.map((port) => ({
313
+ endpoint: `ws://127.0.0.1:${port}/session`,
314
+ source: 'port-probe',
315
+ }));
316
+ }
317
+ /**
318
+ * Return discovery candidates without probing them. Callers must verify the
319
+ * endpoint themselves before using it.
320
+ */
321
+ export async function discoverBrowsers(config) {
322
+ const candidates = [];
323
+ let blockedNonLoopback = 0;
324
+ const addEndpoint = (endpoint, source, extra) => {
325
+ if (!endpointAllowed(config, endpoint)) {
326
+ blockedNonLoopback += 1;
327
+ return false;
328
+ }
329
+ addCandidate(candidates, { endpoint, source, ...extra });
330
+ return true;
331
+ };
332
+ if (config.wsUrl !== undefined) {
333
+ if (!config.allowRemote && !isLoopback(config.wsUrl)) {
334
+ throw new ActionableError('INVALID_CONFIG', 'Non-loopback BIDI_WS_URL requires BIDI_ALLOW_REMOTE=1.', {
335
+ fix: 'Set BIDI_ALLOW_REMOTE=1 or use ws://127.0.0.1:<port>/session.',
336
+ });
337
+ }
338
+ addCandidate(candidates, {
339
+ endpoint: config.wsUrl,
340
+ source: 'env',
341
+ // A DevTools browser WebSocket URL means Chromium: it speaks CDP, so
342
+ // the session layer must start the in-process mapper.
343
+ ...(/\/devtools\/browser\//.test(config.wsUrl)
344
+ ? { browserFamily: 'chromium' }
345
+ : {}),
346
+ });
347
+ return candidates;
348
+ }
349
+ if (config.profileDir !== undefined && existsSync(config.profileDir)) {
350
+ const url = discoveryUrlFor(resolve(config.profileDir));
351
+ if (url !== undefined) {
352
+ addEndpoint(url, 'profile-file', {
353
+ profilePath: resolve(config.profileDir),
354
+ });
355
+ }
356
+ }
357
+ for (const root of profileRoots(config)) {
358
+ for (const dir of [...profileDirsFromIni(root), ...profileDirsFromRoot(root), root]) {
359
+ const url = discoveryUrlFor(dir);
360
+ if (url !== undefined) {
361
+ addEndpoint(url, 'profiles-ini', { profilePath: dir });
362
+ }
363
+ }
364
+ }
365
+ const chromiumPorts = new Set();
366
+ for (const dir of chromiumDataDirs(config)) {
367
+ const endpoint = chromiumEndpointFromDataDir(dir);
368
+ if (endpoint !== undefined) {
369
+ addChromiumPort(chromiumPorts, endpoint);
370
+ addEndpoint(endpoint, 'chromium-devtools-port', {
371
+ profilePath: dir,
372
+ browserFamily: 'chromium',
373
+ });
374
+ }
375
+ }
376
+ const { candidates: processFound, chromiumPorts: processPorts } = await processCandidates();
377
+ for (const candidate of processFound) {
378
+ addEndpoint(candidate.endpoint, candidate.source, candidate);
379
+ }
380
+ for (const port of processPorts) {
381
+ chromiumPorts.add(port);
382
+ }
383
+ for (const candidate of portCandidates(config, chromiumPorts)) {
384
+ addEndpoint(candidate.endpoint, candidate.source, candidate);
385
+ }
386
+ if (blockedNonLoopback > 0 && candidates.length === 0) {
387
+ throw new ActionableError('INVALID_CONFIG', `${blockedNonLoopback} discovered BiDi endpoint(s) are non-loopback and BIDI_ALLOW_REMOTE is off.`, {
388
+ fix: 'Use a loopback endpoint, or set BIDI_ALLOW_REMOTE=1 to allow remote hosts.',
389
+ });
390
+ }
391
+ return candidates;
392
+ }
393
+ //# sourceMappingURL=browser-discovery.js.map
@@ -0,0 +1,55 @@
1
+ import { EventEmitter } from 'node:events';
2
+ /**
3
+ * Chromium support without chromedriver: host the `chromium-bidi` mapper in
4
+ * this process and hand it a CDP connection to the browser. Our BiDi client
5
+ * speaks BiDi to the mapper over an in-process facade; the mapper translates
6
+ * to CDP. The mapper is an optional dependency - when absent we fail with an
7
+ * actionable install hint instead of crashing.
8
+ */
9
+ /** Subset of the `ws` WebSocket surface BiDiClient relies on. */
10
+ export interface BiDiSocket {
11
+ readonly readyState: number;
12
+ readonly CLOSED: number;
13
+ send(data: string): void;
14
+ close(): void;
15
+ terminate(): void;
16
+ removeAllListeners(): void;
17
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
18
+ once(event: string, listener: (...args: unknown[]) => void): unknown;
19
+ }
20
+ /** True when this Node version satisfies chromium-bidi's engines range. */
21
+ export declare function nodeSupportsMapper(version?: string): boolean;
22
+ export declare function isModuleNotFound(error: unknown): boolean;
23
+ /**
24
+ * ws-compatible facade. BiDiClient drives it exactly like a real WebSocket:
25
+ * every `send()` is a BiDi command routed into the mapper, every mapper
26
+ * reply is re-emitted as a 'message' event, and the CDP side dropping is
27
+ * surfaced as a socket close.
28
+ */
29
+ export declare class MapperSocket extends EventEmitter implements BiDiSocket {
30
+ #private;
31
+ readonly CLOSED = 3;
32
+ readyState: number;
33
+ /** Registered by the BidiServer transport wrapper. */
34
+ setCommandHandler(handler: (command: unknown) => Promise<void> | void): void;
35
+ /** Mapper outgoing message -> BiDiClient 'message' event. */
36
+ pushMessage(message: unknown): void;
37
+ /** Schedule 'open' and register the teardown for close paths. */
38
+ attach(teardown: () => void): void;
39
+ /** BiDi JSON from BiDiClient; forward into the mapper. */
40
+ send(data: string): void;
41
+ close(): void;
42
+ terminate(): void;
43
+ /** The CDP side dropped: surface as a socket close so sessions reset. */
44
+ notifyCdpDrop(): void;
45
+ }
46
+ export interface ChromiumMapperOptions {
47
+ /** CDP browser WebSocket URL, e.g. from Chromium's DevToolsActivePort. */
48
+ readonly cdpUrl: string;
49
+ readonly timeoutMs: number;
50
+ }
51
+ /**
52
+ * Connect to a Chromium CDP endpoint and start the in-process mapper.
53
+ * Resolves with a ws-compatible socket that speaks WebDriver BiDi.
54
+ */
55
+ export declare function openChromiumMapperSocket(options: ChromiumMapperOptions): Promise<BiDiSocket>;