bidi-browser-mcp 0.1.9 → 0.2.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/LICENSE +21 -21
- package/README.md +398 -343
- package/dist/bin.js +3 -2
- package/dist/config.js +4 -0
- package/dist/connection/bidi-client.d.ts +13 -1
- package/dist/connection/bidi-client.js +59 -8
- package/dist/connection/browser-discovery.d.ts +20 -0
- package/dist/connection/browser-discovery.js +76 -12
- package/dist/connection/chromium-mapper.d.ts +9 -0
- package/dist/connection/chromium-mapper.js +24 -0
- package/dist/connection/event-pipeline.d.ts +15 -2
- package/dist/connection/event-pipeline.js +45 -3
- package/dist/connection/protocol-probe.d.ts +43 -0
- package/dist/connection/protocol-probe.js +112 -0
- package/dist/index.js +6 -0
- package/dist/session/session-manager.d.ts +26 -1
- package/dist/session/session-manager.js +262 -6
- package/dist/snapshot/cache.d.ts +4 -0
- package/dist/snapshot/cache.js +8 -0
- package/dist/snapshot/dom-snapshot.js +190 -181
- package/dist/snapshot/element-script.d.ts +23 -0
- package/dist/snapshot/element-script.js +70 -0
- package/dist/snapshot/token-optimizer.js +26 -8
- package/dist/snapshot/uid-verify.d.ts +43 -0
- package/dist/snapshot/uid-verify.js +154 -0
- package/dist/tools/browser.js +21 -6
- package/dist/tools/context.js +4 -6
- package/dist/tools/interact.d.ts +1 -0
- package/dist/tools/interact.js +593 -0
- package/dist/tools/network.d.ts +1 -0
- package/dist/tools/network.js +166 -0
- package/dist/tools/page.js +53 -2
- package/dist/tools/ping.js +5 -1
- package/dist/tools/script.d.ts +1 -0
- package/dist/tools/script.js +166 -0
- package/dist/types.d.ts +50 -1
- package/dist/utils/bidi-value.d.ts +10 -0
- package/dist/utils/bidi-value.js +56 -0
- package/dist/utils/errors.d.ts +3 -1
- package/dist/utils/errors.js +13 -7
- package/dist/utils/redact.d.ts +16 -0
- package/dist/utils/redact.js +47 -0
- package/package.json +86 -86
package/dist/bin.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
7
|
import { createServer, VERSION } from './index.js';
|
|
8
|
+
import { formatError } from './utils/errors.js';
|
|
8
9
|
async function main() {
|
|
9
10
|
const { server, session } = createServer();
|
|
10
11
|
const transport = new StdioServerTransport();
|
|
@@ -30,8 +31,8 @@ async function main() {
|
|
|
30
31
|
process.stdin.once('close', shutdown);
|
|
31
32
|
}
|
|
32
33
|
main().catch((error) => {
|
|
33
|
-
|
|
34
|
-
console.error(`bidi-browser-mcp failed to start: ${
|
|
34
|
+
// Code + fix, not just the message: a startup failure must be actionable.
|
|
35
|
+
console.error(`bidi-browser-mcp failed to start: ${formatError(error)}`);
|
|
35
36
|
process.exit(1);
|
|
36
37
|
});
|
|
37
38
|
//# sourceMappingURL=bin.js.map
|
package/dist/config.js
CHANGED
|
@@ -46,6 +46,10 @@ export function loadConfig(env = process.env) {
|
|
|
46
46
|
allowExtensionInstall: readBoolean(env, 'BIDI_ALLOW_EXTENSION_INSTALL', false),
|
|
47
47
|
allowBrowserClose: readBoolean(env, 'BIDI_ALLOW_BROWSER_CLOSE', false),
|
|
48
48
|
allowRemote,
|
|
49
|
+
/** Opt-in for the read-only network waits (0.2.0 gate). */
|
|
50
|
+
enableNetwork: readBoolean(env, 'BIDI_ENABLE_NETWORK', false),
|
|
51
|
+
/** Opt-in for free-form script.evaluate (credential-unsafe). */
|
|
52
|
+
allowScriptEval: readBoolean(env, 'BIDI_ALLOW_SCRIPT_EVAL', false),
|
|
49
53
|
discoveryRoots: Object.freeze(discoveryRoots),
|
|
50
54
|
chromiumDataDirs: Object.freeze(chromiumDataDirs),
|
|
51
55
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BiDiEvent } from '../types.js';
|
|
1
|
+
import type { ActionableErrorCode, BiDiEvent } from '../types.js';
|
|
2
2
|
import type { BiDiSocket } from './chromium-mapper.js';
|
|
3
3
|
export type BiDiClientState = 'disconnected' | 'connecting' | 'connected';
|
|
4
4
|
export interface BiDiClientOptions {
|
|
@@ -11,6 +11,18 @@ export interface BiDiClientOptions {
|
|
|
11
11
|
*/
|
|
12
12
|
readonly openSocket?: () => Promise<BiDiSocket>;
|
|
13
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* Translate a BiDi error frame into our taxonomy (decisions §1 of the 0.2.0
|
|
16
|
+
* plan). Only unambiguous cases map; everything unknown stays SESSION_FAILED
|
|
17
|
+
* with the raw code preserved in details.biDiCode. Codes are additive for
|
|
18
|
+
* 0.1.x clients.
|
|
19
|
+
*
|
|
20
|
+
* Method-aware step (verified live on Firefox/Zen): the browser reports both
|
|
21
|
+
* an unknown browsing context and a missing frame as `no such frame`. Agent
|
|
22
|
+
* taxonomy wants the distinction: browsingContext.* → CONTEXT_NOT_FOUND
|
|
23
|
+
* ("no such tab/context"), script/frame-context scopes → FRAME_NOT_FOUND.
|
|
24
|
+
*/
|
|
25
|
+
export declare function translateBiDiError(biDiCode: string | undefined, errorMessage: string | undefined, method?: string): ActionableErrorCode;
|
|
14
26
|
/**
|
|
15
27
|
* Minimal BiDi WebSocket client. One command at a time is not required, but
|
|
16
28
|
* request IDs are unique and pending commands are always settled.
|
|
@@ -4,6 +4,56 @@ import { ActionableError } from '../utils/errors.js';
|
|
|
4
4
|
const HANDSHAKE_RETRIES = 3;
|
|
5
5
|
const HANDSHAKE_RETRY_DELAY_MS = 500;
|
|
6
6
|
const HANDSHAKE_RETRY_STATUSES = ['403', '429', '503'];
|
|
7
|
+
/**
|
|
8
|
+
* Translate a BiDi error frame into our taxonomy (decisions §1 of the 0.2.0
|
|
9
|
+
* plan). Only unambiguous cases map; everything unknown stays SESSION_FAILED
|
|
10
|
+
* with the raw code preserved in details.biDiCode. Codes are additive for
|
|
11
|
+
* 0.1.x clients.
|
|
12
|
+
*
|
|
13
|
+
* Method-aware step (verified live on Firefox/Zen): the browser reports both
|
|
14
|
+
* an unknown browsing context and a missing frame as `no such frame`. Agent
|
|
15
|
+
* taxonomy wants the distinction: browsingContext.* → CONTEXT_NOT_FOUND
|
|
16
|
+
* ("no such tab/context"), script/frame-context scopes → FRAME_NOT_FOUND.
|
|
17
|
+
*/
|
|
18
|
+
export function translateBiDiError(biDiCode, errorMessage, method) {
|
|
19
|
+
if (biDiCode === 'session not created' ||
|
|
20
|
+
(errorMessage !== undefined &&
|
|
21
|
+
/maximum number (of )?active sessions/i.test(errorMessage))) {
|
|
22
|
+
return 'SESSION_BUSY';
|
|
23
|
+
}
|
|
24
|
+
if (biDiCode === 'no such frame') {
|
|
25
|
+
return method?.startsWith('browsingContext.') === true
|
|
26
|
+
? 'CONTEXT_NOT_FOUND'
|
|
27
|
+
: 'FRAME_NOT_FOUND';
|
|
28
|
+
}
|
|
29
|
+
switch (biDiCode) {
|
|
30
|
+
case 'no such element':
|
|
31
|
+
case 'no such node':
|
|
32
|
+
case 'detached shadow root':
|
|
33
|
+
return 'STALE_UID';
|
|
34
|
+
case 'unknown command':
|
|
35
|
+
case 'unsupported operation':
|
|
36
|
+
return 'UNSUPPORTED';
|
|
37
|
+
case 'no such request':
|
|
38
|
+
return 'NETWORK_ERROR';
|
|
39
|
+
case 'move target out of bounds':
|
|
40
|
+
case 'element not interactable':
|
|
41
|
+
return 'NOT_INTERACTABLE';
|
|
42
|
+
case 'invalid argument':
|
|
43
|
+
case 'invalid selector':
|
|
44
|
+
return 'INVALID_ARGUMENT';
|
|
45
|
+
default:
|
|
46
|
+
return 'SESSION_FAILED';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The raw BiDi code plus the request's method, for agent diagnostics. */
|
|
50
|
+
function failureDetails(method, biDiCode) {
|
|
51
|
+
const details = { method };
|
|
52
|
+
if (biDiCode !== undefined) {
|
|
53
|
+
details.biDiCode = biDiCode;
|
|
54
|
+
}
|
|
55
|
+
return details;
|
|
56
|
+
}
|
|
7
57
|
/**
|
|
8
58
|
* Minimal BiDi WebSocket client. One command at a time is not required, but
|
|
9
59
|
* request IDs are unique and pending commands are always settled.
|
|
@@ -196,11 +246,13 @@ export class BiDiClient {
|
|
|
196
246
|
const pending = this.#pending.get(id);
|
|
197
247
|
if (pending !== undefined) {
|
|
198
248
|
this.#pending.delete(id);
|
|
199
|
-
pending.reject(new ActionableError('TIMEOUT', `Timed out waiting for ${method}
|
|
249
|
+
pending.reject(new ActionableError('TIMEOUT', `Timed out waiting for ${method}.`, {
|
|
250
|
+
details: failureDetails(method, undefined),
|
|
251
|
+
}));
|
|
200
252
|
}
|
|
201
253
|
}, this.#timeoutMs);
|
|
202
254
|
return new Promise((resolve, reject) => {
|
|
203
|
-
this.#pending.set(id, { resolve, reject, timer });
|
|
255
|
+
this.#pending.set(id, { resolve, reject, timer, method });
|
|
204
256
|
socket.send(JSON.stringify(message));
|
|
205
257
|
});
|
|
206
258
|
}
|
|
@@ -270,18 +322,17 @@ export class BiDiClient {
|
|
|
270
322
|
: undefined;
|
|
271
323
|
// Real Firefox/Zen reports the one-session conflict as
|
|
272
324
|
// `session not created` / "Maximum number of active sessions".
|
|
273
|
-
const
|
|
274
|
-
(errorMessage !== undefined &&
|
|
275
|
-
/maximum number (of )?active sessions/i.test(errorMessage));
|
|
276
|
-
const code = isBusy ? 'SESSION_BUSY' : 'SESSION_FAILED';
|
|
325
|
+
const code = translateBiDiError(biDiCode, errorMessage, pending.method);
|
|
277
326
|
pending.reject(new ActionableError(code, errorMessage ??
|
|
278
|
-
`Malformed BiDi error frame for request ${String(message.id)}.`, { details:
|
|
327
|
+
`Malformed BiDi error frame for request ${String(message.id)}.`, { details: failureDetails(pending.method, biDiCode) }));
|
|
279
328
|
}
|
|
280
329
|
#failPending(code, message) {
|
|
281
330
|
this.#fireClose();
|
|
282
331
|
for (const pending of this.#pending.values()) {
|
|
283
332
|
clearTimeout(pending.timer);
|
|
284
|
-
pending.reject(new ActionableError(code, message
|
|
333
|
+
pending.reject(new ActionableError(code, message, {
|
|
334
|
+
details: failureDetails(pending.method, undefined),
|
|
335
|
+
}));
|
|
285
336
|
}
|
|
286
337
|
this.#pending.clear();
|
|
287
338
|
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import type { Config, DiscoveryCandidate } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Match a process basename against the known families exactly: `brave`,
|
|
4
|
+
* `brave.exe`, or the macOS bundle executable `brave browser`. Substring
|
|
5
|
+
* matching would misclassify `frozen.exe`/`citizen.exe` (they contain `zen`)
|
|
6
|
+
* and helper processes like `zen portal`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function matchesKnownProcess(name: string): string | undefined;
|
|
2
9
|
/**
|
|
3
10
|
* Parse `--remote-debugging-port` from a process command line.
|
|
4
11
|
* Supports `--remote-debugging-port`, `--remote-debugging-port 9223`, and
|
|
@@ -23,6 +30,19 @@ export declare function chromiumEndpointFromDataDir(dataDir: string): string | u
|
|
|
23
30
|
* or rogue WebDriverBiDiServer.json must not point the server at a remote host.
|
|
24
31
|
*/
|
|
25
32
|
export declare function endpointAllowed(config: Config, endpoint: string): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Cheap CDP liveness confirm: a `DevToolsActivePort`-recorded port is only
|
|
35
|
+
* excluded from BiDi port probes while a Chromium actually answers there.
|
|
36
|
+
* A dead profile's recorded port must not shadow a Firefox listening on the
|
|
37
|
+
* same port (0.2.0 leftover §6).
|
|
38
|
+
*
|
|
39
|
+
* Modern Chromium removed the `/json` HTTP endpoints (Brave 153 answers 404
|
|
40
|
+
* on every path), so liveness is "the port answers HTTP and is NOT Firefox's
|
|
41
|
+
* Remote Agent": Firefox's httpd.js index page is the fingerprint that keeps
|
|
42
|
+
* a live Firefox on a recorded port probeable. Plain node:http — undici's
|
|
43
|
+
* fetch has proven flaky to loopback servers inside worker threads.
|
|
44
|
+
*/
|
|
45
|
+
export declare function chromiumPortLive(port: number, timeoutMs?: number): Promise<boolean>;
|
|
26
46
|
/**
|
|
27
47
|
* Return discovery candidates without probing them. Callers must verify the
|
|
28
48
|
* endpoint themselves before using it.
|
|
@@ -4,6 +4,7 @@ import { join, resolve } from 'node:path';
|
|
|
4
4
|
import { execFile } from 'node:child_process';
|
|
5
5
|
import { promisify } from 'node:util';
|
|
6
6
|
import { ActionableError } from '../utils/errors.js';
|
|
7
|
+
import { fingerprintHttpPort, isFirefoxAgentFingerprint, } from './protocol-probe.js';
|
|
7
8
|
const execFileAsync = promisify(execFile);
|
|
8
9
|
const DISCOVERY_FILE = 'WebDriverBiDiServer.json';
|
|
9
10
|
const FIREFOX_FAMILY_PROCESSES = [
|
|
@@ -23,7 +24,23 @@ const CHROMIUM_FAMILY_PROCESSES = [
|
|
|
23
24
|
'thorium',
|
|
24
25
|
'yandex',
|
|
25
26
|
'opera',
|
|
27
|
+
'google-chrome',
|
|
26
28
|
];
|
|
29
|
+
/**
|
|
30
|
+
* Match a process basename against the known families exactly: `brave`,
|
|
31
|
+
* `brave.exe`, or the macOS bundle executable `brave browser`. Substring
|
|
32
|
+
* matching would misclassify `frozen.exe`/`citizen.exe` (they contain `zen`)
|
|
33
|
+
* and helper processes like `zen portal`.
|
|
34
|
+
*/
|
|
35
|
+
export function matchesKnownProcess(name) {
|
|
36
|
+
const base = name.trim().replace(/\.exe$/, '').toLowerCase();
|
|
37
|
+
const exact = KNOWN_PROCESSES.find((candidate) => base === candidate);
|
|
38
|
+
if (exact !== undefined) {
|
|
39
|
+
return exact;
|
|
40
|
+
}
|
|
41
|
+
const spaced = KNOWN_PROCESSES.find((candidate) => base === `${candidate} browser`);
|
|
42
|
+
return spaced;
|
|
43
|
+
}
|
|
27
44
|
const KNOWN_PROCESSES = [
|
|
28
45
|
...FIREFOX_FAMILY_PROCESSES,
|
|
29
46
|
...CHROMIUM_FAMILY_PROCESSES,
|
|
@@ -228,17 +245,24 @@ function addCandidate(candidates, candidate) {
|
|
|
228
245
|
async function processCommandLines() {
|
|
229
246
|
try {
|
|
230
247
|
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 });
|
|
248
|
+
const script = `Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^(${KNOWN_PROCESSES.map((name) => `${name}\\.exe`).join('|')})$' } | Select-Object ProcessId,Name,CommandLine | ConvertTo-Json -Compress`;
|
|
249
|
+
const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 5_000, maxBuffer: 10 * 1024 * 1024 });
|
|
233
250
|
const parsed = JSON.parse(stdout);
|
|
234
251
|
const normalized = Array.isArray(parsed) ? parsed : [parsed];
|
|
235
252
|
return normalized
|
|
236
253
|
.filter((item) => typeof item.CommandLine === 'string' && typeof item.Name === 'string')
|
|
237
|
-
.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
254
|
+
.flatMap((item) => {
|
|
255
|
+
const family = matchesKnownProcess(item.Name);
|
|
256
|
+
return family === undefined
|
|
257
|
+
? []
|
|
258
|
+
: [
|
|
259
|
+
{
|
|
260
|
+
processId: typeof item.ProcessId === 'number' ? item.ProcessId : 0,
|
|
261
|
+
name: family,
|
|
262
|
+
commandLine: item.CommandLine,
|
|
263
|
+
},
|
|
264
|
+
];
|
|
265
|
+
});
|
|
242
266
|
}
|
|
243
267
|
const { stdout } = await execFileAsync('ps', ['-axo', 'pid=,command='], {
|
|
244
268
|
timeout: 5_000,
|
|
@@ -250,7 +274,12 @@ async function processCommandLines() {
|
|
|
250
274
|
.filter((match) => match !== null)
|
|
251
275
|
.flatMap((match) => {
|
|
252
276
|
const commandLine = match[2];
|
|
253
|
-
|
|
277
|
+
// Match the executable's basename, not the whole command line:
|
|
278
|
+
// substring matching would pull in tools that merely mention a
|
|
279
|
+
// browser name, and frozen.exe/citizen.exe on Windows.
|
|
280
|
+
const argv0 = commandLine.split(/\s+/)[0] ?? '';
|
|
281
|
+
const basename = argv0.slice(argv0.lastIndexOf('/') + 1);
|
|
282
|
+
const name = matchesKnownProcess(basename);
|
|
254
283
|
return name === undefined
|
|
255
284
|
? []
|
|
256
285
|
: [{ processId: Number(match[1]), name, commandLine }];
|
|
@@ -303,6 +332,9 @@ async function processCandidates() {
|
|
|
303
332
|
endpoint: `ws://127.0.0.1:${port}/session`,
|
|
304
333
|
source: 'process-cmdline',
|
|
305
334
|
processId: item.processId,
|
|
335
|
+
// Chromium processes were handled above, so everything here is a
|
|
336
|
+
// Firefox-family binary serving the WebDriver BiDi Remote Agent.
|
|
337
|
+
browserFamily: 'firefox',
|
|
306
338
|
});
|
|
307
339
|
}
|
|
308
340
|
return { candidates, chromiumPorts };
|
|
@@ -314,6 +346,25 @@ function portCandidates(config, chromiumPorts) {
|
|
|
314
346
|
source: 'port-probe',
|
|
315
347
|
}));
|
|
316
348
|
}
|
|
349
|
+
/**
|
|
350
|
+
* Cheap CDP liveness confirm: a `DevToolsActivePort`-recorded port is only
|
|
351
|
+
* excluded from BiDi port probes while a Chromium actually answers there.
|
|
352
|
+
* A dead profile's recorded port must not shadow a Firefox listening on the
|
|
353
|
+
* same port (0.2.0 leftover §6).
|
|
354
|
+
*
|
|
355
|
+
* Modern Chromium removed the `/json` HTTP endpoints (Brave 153 answers 404
|
|
356
|
+
* on every path), so liveness is "the port answers HTTP and is NOT Firefox's
|
|
357
|
+
* Remote Agent": Firefox's httpd.js index page is the fingerprint that keeps
|
|
358
|
+
* a live Firefox on a recorded port probeable. Plain node:http — undici's
|
|
359
|
+
* fetch has proven flaky to loopback servers inside worker threads.
|
|
360
|
+
*/
|
|
361
|
+
export async function chromiumPortLive(port, timeoutMs = 1500) {
|
|
362
|
+
const fingerprint = await fingerprintHttpPort(port, timeoutMs);
|
|
363
|
+
if (!fingerprint.answered) {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
return !isFirefoxAgentFingerprint(fingerprint);
|
|
367
|
+
}
|
|
317
368
|
/**
|
|
318
369
|
* Return discovery candidates without probing them. Callers must verify the
|
|
319
370
|
* endpoint themselves before using it.
|
|
@@ -339,10 +390,11 @@ export async function discoverBrowsers(config) {
|
|
|
339
390
|
endpoint: config.wsUrl,
|
|
340
391
|
source: 'env',
|
|
341
392
|
// A DevTools browser WebSocket URL means Chromium: it speaks CDP, so
|
|
342
|
-
// the session layer must start the in-process mapper.
|
|
393
|
+
// the session layer must start the in-process mapper. Any other env
|
|
394
|
+
// URL is a BiDi endpoint the operator named explicitly.
|
|
343
395
|
...(/\/devtools\/browser\//.test(config.wsUrl)
|
|
344
396
|
? { browserFamily: 'chromium' }
|
|
345
|
-
: {}),
|
|
397
|
+
: { browserFamily: 'firefox' }),
|
|
346
398
|
});
|
|
347
399
|
return candidates;
|
|
348
400
|
}
|
|
@@ -351,6 +403,7 @@ export async function discoverBrowsers(config) {
|
|
|
351
403
|
if (url !== undefined) {
|
|
352
404
|
addEndpoint(url, 'profile-file', {
|
|
353
405
|
profilePath: resolve(config.profileDir),
|
|
406
|
+
browserFamily: 'firefox',
|
|
354
407
|
});
|
|
355
408
|
}
|
|
356
409
|
}
|
|
@@ -358,7 +411,10 @@ export async function discoverBrowsers(config) {
|
|
|
358
411
|
for (const dir of [...profileDirsFromIni(root), ...profileDirsFromRoot(root), root]) {
|
|
359
412
|
const url = discoveryUrlFor(dir);
|
|
360
413
|
if (url !== undefined) {
|
|
361
|
-
addEndpoint(url, 'profiles-ini', {
|
|
414
|
+
addEndpoint(url, 'profiles-ini', {
|
|
415
|
+
profilePath: dir,
|
|
416
|
+
browserFamily: 'firefox',
|
|
417
|
+
});
|
|
362
418
|
}
|
|
363
419
|
}
|
|
364
420
|
}
|
|
@@ -380,7 +436,15 @@ export async function discoverBrowsers(config) {
|
|
|
380
436
|
for (const port of processPorts) {
|
|
381
437
|
chromiumPorts.add(port);
|
|
382
438
|
}
|
|
383
|
-
|
|
439
|
+
// Only live Chromium ports suppress BiDi probes; a dead profile's recorded
|
|
440
|
+
// port must not shadow a Firefox that listens there (§6).
|
|
441
|
+
const liveChromiumPorts = new Set();
|
|
442
|
+
for (const port of chromiumPorts) {
|
|
443
|
+
if (await chromiumPortLive(port)) {
|
|
444
|
+
liveChromiumPorts.add(port);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
for (const candidate of portCandidates(config, liveChromiumPorts)) {
|
|
384
448
|
addEndpoint(candidate.endpoint, candidate.source, candidate);
|
|
385
449
|
}
|
|
386
450
|
if (blockedNonLoopback > 0 && candidates.length === 0) {
|
|
@@ -26,10 +26,19 @@ export declare function isModuleNotFound(error: unknown): boolean;
|
|
|
26
26
|
* reply is re-emitted as a 'message' event, and the CDP side dropping is
|
|
27
27
|
* surfaced as a socket close.
|
|
28
28
|
*/
|
|
29
|
+
/**
|
|
30
|
+
* BiDiWeSocket facade for the in-browser BiDi proxy: every `send` is a
|
|
31
|
+
* browser message, and pre-`open` receives are buffered until attach.
|
|
32
|
+
*
|
|
33
|
+
* Exported for unit tests (startup buffering, close-before-open). It is not
|
|
34
|
+
* part of the package's public surface — reachable only from the mapper.
|
|
35
|
+
*/
|
|
29
36
|
export declare class MapperSocket extends EventEmitter implements BiDiSocket {
|
|
30
37
|
#private;
|
|
31
38
|
readonly CLOSED = 3;
|
|
32
39
|
readyState: number;
|
|
40
|
+
/** Bounded signal for the silent-drop path (0.2.0 leftover §6). */
|
|
41
|
+
get droppedPendingMessages(): number;
|
|
33
42
|
/** Registered by the BidiServer transport wrapper. */
|
|
34
43
|
setCommandHandler(handler: (command: unknown) => Promise<void> | void): void;
|
|
35
44
|
/** Mapper outgoing message -> BiDiClient 'message' event. */
|
|
@@ -95,6 +95,13 @@ const CLOSED = 3;
|
|
|
95
95
|
* reply is re-emitted as a 'message' event, and the CDP side dropping is
|
|
96
96
|
* surfaced as a socket close.
|
|
97
97
|
*/
|
|
98
|
+
/**
|
|
99
|
+
* BiDiWeSocket facade for the in-browser BiDi proxy: every `send` is a
|
|
100
|
+
* browser message, and pre-`open` receives are buffered until attach.
|
|
101
|
+
*
|
|
102
|
+
* Exported for unit tests (startup buffering, close-before-open). It is not
|
|
103
|
+
* part of the package's public surface — reachable only from the mapper.
|
|
104
|
+
*/
|
|
98
105
|
export class MapperSocket extends EventEmitter {
|
|
99
106
|
CLOSED = CLOSED;
|
|
100
107
|
readyState = CONNECTING;
|
|
@@ -107,6 +114,13 @@ export class MapperSocket extends EventEmitter {
|
|
|
107
114
|
*/
|
|
108
115
|
#pendingMessages = [];
|
|
109
116
|
static #MAX_PENDING_MESSAGES = 500;
|
|
117
|
+
/** Dropped-message count; surfaced once so startup overload is not silent. */
|
|
118
|
+
#droppedPending = 0;
|
|
119
|
+
#overflowWarned = false;
|
|
120
|
+
/** Bounded signal for the silent-drop path (0.2.0 leftover §6). */
|
|
121
|
+
get droppedPendingMessages() {
|
|
122
|
+
return this.#droppedPending;
|
|
123
|
+
}
|
|
110
124
|
/** Registered by the BidiServer transport wrapper. */
|
|
111
125
|
setCommandHandler(handler) {
|
|
112
126
|
this.#commandHandler = handler;
|
|
@@ -120,6 +134,16 @@ export class MapperSocket extends EventEmitter {
|
|
|
120
134
|
if (this.readyState === CONNECTING &&
|
|
121
135
|
this.#pendingMessages.length < MapperSocket.#MAX_PENDING_MESSAGES) {
|
|
122
136
|
this.#pendingMessages.push(message);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (this.readyState === CONNECTING) {
|
|
140
|
+
// The cap stays (bounded memory on purpose), but the drop is counted
|
|
141
|
+
// and warned once — a silently starved startup is undebuggable.
|
|
142
|
+
this.#droppedPending += 1;
|
|
143
|
+
if (!this.#overflowWarned) {
|
|
144
|
+
this.#overflowWarned = true;
|
|
145
|
+
console.error(`MapperSocket startup buffer overflow: dropped ${this.#droppedPending}+ mapper messages (cap ${MapperSocket.#MAX_PENDING_MESSAGES} stays).`);
|
|
146
|
+
}
|
|
123
147
|
}
|
|
124
148
|
}
|
|
125
149
|
/** Schedule 'open' and register the teardown for close paths. */
|
|
@@ -4,14 +4,20 @@ import type { BiDiClientLike, BiDiEvent, ConsoleEntry, EventFilter, EventPipelin
|
|
|
4
4
|
* and download events join when their tools land, keeping buffers small.
|
|
5
5
|
*/
|
|
6
6
|
export declare const SUBSCRIBED_EVENTS: readonly ["browsingContext.contextCreated", "browsingContext.contextDestroyed", "browsingContext.domContentLoaded", "log.entryAdded"];
|
|
7
|
+
/**
|
|
8
|
+
* Network events (0.2.0): subscribed additively when the opt-in network tool
|
|
9
|
+
* first runs — the base subscription stays small until someone needs them.
|
|
10
|
+
*/
|
|
11
|
+
export declare const NETWORK_SUBSCRIBED_EVENTS: readonly ["network.beforeRequestSent", "network.responseStarted", "network.responseCompleted", "network.fetchError"];
|
|
7
12
|
export interface EventPipelineOptions {
|
|
8
13
|
/** Max buffered events per method; oldest are dropped and counted. */
|
|
9
14
|
readonly bufferLimitPerMethod?: number;
|
|
10
15
|
}
|
|
11
16
|
type Sink = (event: BiDiEvent) => void;
|
|
12
17
|
/**
|
|
13
|
-
* Routes BiDi events to sinks and keeps bounded per-method buffers.
|
|
14
|
-
*
|
|
18
|
+
* Routes BiDi events to sinks and keeps bounded per-method buffers. One
|
|
19
|
+
* `session.subscribe` at attach; additive subscriptions can be appended
|
|
20
|
+
* mid-session (network gate) and are tracked like the base set.
|
|
15
21
|
*/
|
|
16
22
|
export declare class EventPipeline implements EventPipelineLike {
|
|
17
23
|
#private;
|
|
@@ -21,6 +27,13 @@ export declare class EventPipeline implements EventPipelineLike {
|
|
|
21
27
|
* connected; `session.subscribe` is a plain command here.
|
|
22
28
|
*/
|
|
23
29
|
attach(client: BiDiClientLike): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Add a second, additive subscription mid-session (0.2.0 network gate).
|
|
32
|
+
* Idempotent per pipeline instance; methods already subscribed are skipped.
|
|
33
|
+
*/
|
|
34
|
+
addSubscription(events: readonly string[]): Promise<void>;
|
|
35
|
+
/** Methods this pipeline currently subscribes to (base + additive). */
|
|
36
|
+
subscribedMethods(): readonly string[];
|
|
24
37
|
registerSink(sink: Sink): () => void;
|
|
25
38
|
/** Called directly by sinks that were registered before the router. */
|
|
26
39
|
record(event: BiDiEvent): void;
|
|
@@ -9,19 +9,37 @@ export const SUBSCRIBED_EVENTS = [
|
|
|
9
9
|
'browsingContext.domContentLoaded',
|
|
10
10
|
'log.entryAdded',
|
|
11
11
|
];
|
|
12
|
+
/**
|
|
13
|
+
* Network events (0.2.0): subscribed additively when the opt-in network tool
|
|
14
|
+
* first runs — the base subscription stays small until someone needs them.
|
|
15
|
+
*/
|
|
16
|
+
export const NETWORK_SUBSCRIBED_EVENTS = [
|
|
17
|
+
'network.beforeRequestSent',
|
|
18
|
+
'network.responseStarted',
|
|
19
|
+
'network.responseCompleted',
|
|
20
|
+
'network.fetchError',
|
|
21
|
+
];
|
|
12
22
|
const DEFAULT_BUFFER_LIMIT = 200;
|
|
13
23
|
/**
|
|
14
|
-
* Routes BiDi events to sinks and keeps bounded per-method buffers.
|
|
15
|
-
*
|
|
24
|
+
* Routes BiDi events to sinks and keeps bounded per-method buffers. One
|
|
25
|
+
* `session.subscribe` at attach; additive subscriptions can be appended
|
|
26
|
+
* mid-session (network gate) and are tracked like the base set.
|
|
16
27
|
*/
|
|
17
28
|
export class EventPipeline {
|
|
18
29
|
#bufferLimit;
|
|
19
30
|
#buffers = new Map();
|
|
20
31
|
#dropped = new Map();
|
|
21
32
|
#sinks = new Set();
|
|
33
|
+
#subscribed = new Set();
|
|
22
34
|
#offClient;
|
|
35
|
+
#client;
|
|
23
36
|
constructor(options = {}) {
|
|
24
37
|
this.#bufferLimit = options.bufferLimitPerMethod ?? DEFAULT_BUFFER_LIMIT;
|
|
38
|
+
// The base set is declared up front so stats are honest before attach;
|
|
39
|
+
// attach sends exactly these methods to the browser.
|
|
40
|
+
for (const method of SUBSCRIBED_EVENTS) {
|
|
41
|
+
this.#subscribed.add(method);
|
|
42
|
+
}
|
|
25
43
|
}
|
|
26
44
|
/**
|
|
27
45
|
* Subscribe once and start routing. Must be called after the client is
|
|
@@ -31,11 +49,35 @@ export class EventPipeline {
|
|
|
31
49
|
if (this.#offClient !== undefined) {
|
|
32
50
|
return;
|
|
33
51
|
}
|
|
52
|
+
this.#client = client;
|
|
34
53
|
await client.request('session.subscribe', { events: [...SUBSCRIBED_EVENTS] });
|
|
54
|
+
for (const method of SUBSCRIBED_EVENTS) {
|
|
55
|
+
this.#subscribed.add(method);
|
|
56
|
+
}
|
|
35
57
|
this.#offClient = client.onEvent((event) => {
|
|
36
58
|
this.#route(event);
|
|
37
59
|
});
|
|
38
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Add a second, additive subscription mid-session (0.2.0 network gate).
|
|
63
|
+
* Idempotent per pipeline instance; methods already subscribed are skipped.
|
|
64
|
+
*/
|
|
65
|
+
async addSubscription(events) {
|
|
66
|
+
const fresh = events.filter((method) => !this.#subscribed.has(method));
|
|
67
|
+
if (fresh.length === 0) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (this.#client !== undefined) {
|
|
71
|
+
await this.#client.request('session.subscribe', { events: fresh });
|
|
72
|
+
}
|
|
73
|
+
for (const method of fresh) {
|
|
74
|
+
this.#subscribed.add(method);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Methods this pipeline currently subscribes to (base + additive). */
|
|
78
|
+
subscribedMethods() {
|
|
79
|
+
return [...this.#subscribed];
|
|
80
|
+
}
|
|
39
81
|
registerSink(sink) {
|
|
40
82
|
this.#sinks.add(sink);
|
|
41
83
|
return () => {
|
|
@@ -141,7 +183,7 @@ export class EventPipeline {
|
|
|
141
183
|
for (const [method, count] of this.#dropped) {
|
|
142
184
|
dropped[method] = count;
|
|
143
185
|
}
|
|
144
|
-
return { subscribed:
|
|
186
|
+
return { subscribed: this.subscribedMethods(), buffered, dropped };
|
|
145
187
|
}
|
|
146
188
|
detach() {
|
|
147
189
|
this.#offClient?.();
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Protocol-level probes for the discovery listing. Both are read-only by
|
|
3
|
+
* construction:
|
|
4
|
+
* - the HTTP fingerprint sends one GET and reads the answer;
|
|
5
|
+
* - the BiDi handshake sends `session.status`, which never creates a session,
|
|
6
|
+
* so probing cannot take Firefox's single-session slot (verified live
|
|
7
|
+
* against a browser that already holds one).
|
|
8
|
+
*
|
|
9
|
+
* Chromium is deliberately NOT probed at the WebSocket level: its browser
|
|
10
|
+
* endpoint may require the user to approve a new debugging client
|
|
11
|
+
* ("Allow remote debugging?"), and the handshake blocks until that is
|
|
12
|
+
* granted — a listing must never pop that dialog or hang on it.
|
|
13
|
+
*/
|
|
14
|
+
/** What an HTTP server on a candidate port answered with. */
|
|
15
|
+
export interface HttpFingerprint {
|
|
16
|
+
readonly answered: boolean;
|
|
17
|
+
readonly status?: number;
|
|
18
|
+
readonly server?: string;
|
|
19
|
+
readonly body?: string;
|
|
20
|
+
}
|
|
21
|
+
/** Plain node:http GET — undici's fetch has proven flaky to loopback servers. */
|
|
22
|
+
export declare function fingerprintHttpPort(port: number, timeoutMs?: number): Promise<HttpFingerprint>;
|
|
23
|
+
/**
|
|
24
|
+
* Firefox's Remote Agent serves its httpd.js index page at `/` — a stable
|
|
25
|
+
* protocol fingerprint that separates a live Firefox from Chromium's DevTools
|
|
26
|
+
* server (which answers 404 on every HTTP path since the `/json` endpoints
|
|
27
|
+
* were removed).
|
|
28
|
+
*/
|
|
29
|
+
export declare function isFirefoxAgentFingerprint(fingerprint: HttpFingerprint): boolean;
|
|
30
|
+
export interface BiDiHandshakeResult {
|
|
31
|
+
/** The endpoint answered a WebDriver BiDi command. */
|
|
32
|
+
readonly ok: boolean;
|
|
33
|
+
/** `session.status` verdict; absent when the handshake never got that far. */
|
|
34
|
+
readonly ready?: boolean;
|
|
35
|
+
/** Why the handshake failed; absent on success. */
|
|
36
|
+
readonly error?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Real WebDriver BiDi handshake: open the socket, send `session.status`, read
|
|
40
|
+
* the reply, close. This is what "connectable" means for a Firefox-family
|
|
41
|
+
* endpoint — a TCP port being open proves nothing about the protocol.
|
|
42
|
+
*/
|
|
43
|
+
export declare function probeBiDiHandshake(endpoint: string, timeoutMs?: number): Promise<BiDiHandshakeResult>;
|