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.
- package/LICENSE +21 -0
- package/README.md +343 -0
- package/dist/bin.d.ts +6 -0
- package/dist/bin.js +37 -0
- package/dist/config.d.ts +6 -0
- package/dist/config.js +122 -0
- package/dist/connection/bidi-client.d.ts +29 -0
- package/dist/connection/bidi-client.js +298 -0
- package/dist/connection/browser-discovery.d.ts +30 -0
- package/dist/connection/browser-discovery.js +393 -0
- package/dist/connection/chromium-mapper.d.ts +55 -0
- package/dist/connection/chromium-mapper.js +293 -0
- package/dist/connection/event-pipeline.d.ts +37 -0
- package/dist/connection/event-pipeline.js +167 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +66 -0
- package/dist/profile/profile-store.d.ts +88 -0
- package/dist/profile/profile-store.js +350 -0
- package/dist/session/context-manager.d.ts +17 -0
- package/dist/session/context-manager.js +179 -0
- package/dist/session/session-manager.d.ts +31 -0
- package/dist/session/session-manager.js +366 -0
- package/dist/snapshot/cache.d.ts +15 -0
- package/dist/snapshot/cache.js +37 -0
- package/dist/snapshot/dom-snapshot.d.ts +5 -0
- package/dist/snapshot/dom-snapshot.js +270 -0
- package/dist/snapshot/element-resolver.d.ts +13 -0
- package/dist/snapshot/element-resolver.js +25 -0
- package/dist/snapshot/token-optimizer.d.ts +16 -0
- package/dist/snapshot/token-optimizer.js +103 -0
- package/dist/tools/base-tool.d.ts +34 -0
- package/dist/tools/base-tool.js +55 -0
- package/dist/tools/browser.d.ts +1 -0
- package/dist/tools/browser.js +75 -0
- package/dist/tools/cleanup.d.ts +1 -0
- package/dist/tools/cleanup.js +64 -0
- package/dist/tools/console.d.ts +1 -0
- package/dist/tools/console.js +87 -0
- package/dist/tools/context.d.ts +1 -0
- package/dist/tools/context.js +156 -0
- package/dist/tools/observe.d.ts +1 -0
- package/dist/tools/observe.js +92 -0
- package/dist/tools/page.d.ts +1 -0
- package/dist/tools/page.js +139 -0
- package/dist/tools/ping.d.ts +1 -0
- package/dist/tools/ping.js +71 -0
- package/dist/tools/registry.d.ts +13 -0
- package/dist/tools/registry.js +47 -0
- package/dist/tools/spaces.d.ts +1 -0
- package/dist/tools/spaces.js +98 -0
- package/dist/tools/tabs.d.ts +1 -0
- package/dist/tools/tabs.js +155 -0
- package/dist/types.d.ts +277 -0
- package/dist/types.js +5 -0
- package/dist/utils/assert.d.ts +12 -0
- package/dist/utils/assert.js +74 -0
- package/dist/utils/errors.d.ts +24 -0
- package/dist/utils/errors.js +60 -0
- package/dist/utils/result.d.ts +14 -0
- package/dist/utils/result.js +37 -0
- package/package.json +86 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { WebSocket } from 'ws';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
/** Firefox 403s the first upgrade while finishing initialization; retry. */
|
|
4
|
+
const HANDSHAKE_RETRIES = 3;
|
|
5
|
+
const HANDSHAKE_RETRY_DELAY_MS = 500;
|
|
6
|
+
const HANDSHAKE_RETRY_STATUSES = ['403', '429', '503'];
|
|
7
|
+
/**
|
|
8
|
+
* Minimal BiDi WebSocket client. One command at a time is not required, but
|
|
9
|
+
* request IDs are unique and pending commands are always settled.
|
|
10
|
+
*/
|
|
11
|
+
export class BiDiClient {
|
|
12
|
+
url;
|
|
13
|
+
#timeoutMs;
|
|
14
|
+
#openSocketFn;
|
|
15
|
+
#pending = new Map();
|
|
16
|
+
#eventHandlers = new Set();
|
|
17
|
+
#closeHandlers = new Set();
|
|
18
|
+
#closeHandlersFired = false;
|
|
19
|
+
#socket;
|
|
20
|
+
#state = 'disconnected';
|
|
21
|
+
#nextId = 1;
|
|
22
|
+
#generation = 0;
|
|
23
|
+
constructor(options) {
|
|
24
|
+
this.url = options.url;
|
|
25
|
+
this.#timeoutMs = options.timeoutMs;
|
|
26
|
+
this.#openSocketFn = options.openSocket;
|
|
27
|
+
}
|
|
28
|
+
get state() {
|
|
29
|
+
return this.#state;
|
|
30
|
+
}
|
|
31
|
+
onEvent(handler) {
|
|
32
|
+
this.#eventHandlers.add(handler);
|
|
33
|
+
return () => {
|
|
34
|
+
this.#eventHandlers.delete(handler);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Fires when the socket drops for any reason. One-shot semantics. */
|
|
38
|
+
onClose(handler) {
|
|
39
|
+
this.#closeHandlers.add(handler);
|
|
40
|
+
return () => {
|
|
41
|
+
this.#closeHandlers.delete(handler);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
async connect() {
|
|
45
|
+
if (this.#state === 'connected') {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (this.#state === 'connecting') {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const timer = setTimeout(() => {
|
|
51
|
+
reject(new ActionableError('CONNECTION_FAILED', 'Timed out waiting for BiDi connect.'));
|
|
52
|
+
}, this.#timeoutMs);
|
|
53
|
+
const check = () => {
|
|
54
|
+
if (this.#state === 'connected') {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
resolve();
|
|
57
|
+
}
|
|
58
|
+
else if (this.#state === 'disconnected') {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
reject(new ActionableError('CONNECTION_FAILED', 'BiDi connection closed during connect.'));
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
setTimeout(check, 25);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
check();
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
this.#state = 'connecting';
|
|
70
|
+
// Firefox's Remote Agent occasionally 403s the first WebSocket upgrade
|
|
71
|
+
// while the browser is still initializing (verified on Zen/Firefox 158).
|
|
72
|
+
// A failed upgrade never creates a session, so a bounded retry is safe.
|
|
73
|
+
let lastError;
|
|
74
|
+
for (let attempt = 0; attempt < HANDSHAKE_RETRIES + 1; attempt++) {
|
|
75
|
+
try {
|
|
76
|
+
await this.#openSocket();
|
|
77
|
+
// The socket can drop between 'open' and this line (e.g. the mapper
|
|
78
|
+
// dies immediately): never report a connection that owns a dead socket.
|
|
79
|
+
if (this.#state !== 'connecting') {
|
|
80
|
+
throw new ActionableError('CONNECTION_FAILED', 'BiDi connection closed during connect.');
|
|
81
|
+
}
|
|
82
|
+
this.#state = 'connected';
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
lastError = error;
|
|
87
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
88
|
+
const retryable = HANDSHAKE_RETRY_STATUSES.some((status) => message.includes(`Unexpected server response: ${status}`)) && attempt < HANDSHAKE_RETRIES;
|
|
89
|
+
if (!retryable) {
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
await new Promise((resolve) => setTimeout(resolve, HANDSHAKE_RETRY_DELAY_MS));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
this.#state = 'disconnected';
|
|
96
|
+
throw lastError;
|
|
97
|
+
}
|
|
98
|
+
/** One full socket-open attempt (WebSocket or mapper facade). */
|
|
99
|
+
#openSocket() {
|
|
100
|
+
this.#closeHandlersFired = false;
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
let socket;
|
|
103
|
+
// Invalidates async socket creation if this attempt is abandoned.
|
|
104
|
+
const generation = ++this.#generation;
|
|
105
|
+
const settle = (state, code, message, cause) => {
|
|
106
|
+
clearTimeout(timer);
|
|
107
|
+
this.#generation += 1;
|
|
108
|
+
if (socket !== undefined) {
|
|
109
|
+
if (this.#socket === socket) {
|
|
110
|
+
this.#socket = undefined;
|
|
111
|
+
}
|
|
112
|
+
socket.removeAllListeners();
|
|
113
|
+
// ws emits the handshake-abort error asynchronously; without a
|
|
114
|
+
// listener the 'error' event crashes the process.
|
|
115
|
+
socket.on('error', () => { });
|
|
116
|
+
try {
|
|
117
|
+
socket.terminate();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// Ignore terminate errors.
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
this.#state = state;
|
|
124
|
+
this.#failPending(code, message);
|
|
125
|
+
reject(new ActionableError(code, message, cause === undefined ? undefined : { cause }));
|
|
126
|
+
};
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
settle('disconnected', 'CONNECTION_FAILED', `Timed out connecting to ${this.url}.`);
|
|
129
|
+
}, this.#timeoutMs);
|
|
130
|
+
void this.#createSocket().then((created) => {
|
|
131
|
+
// The attempt may have timed out or been superseded while the
|
|
132
|
+
// custom opener was still working.
|
|
133
|
+
if (generation !== this.#generation || this.#state !== 'connecting') {
|
|
134
|
+
try {
|
|
135
|
+
created.terminate();
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Ignore terminate errors.
|
|
139
|
+
}
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
socket = created;
|
|
143
|
+
// Identity guard: after a timeout (or a retry) abandons this socket, a
|
|
144
|
+
// late 'open' must never flip the client back to 'connected'. Without
|
|
145
|
+
// this, a low BIDI_TIMEOUT could report a connection that owns nothing.
|
|
146
|
+
const abandoned = () => this.#socket !== socket;
|
|
147
|
+
this.#socket = socket;
|
|
148
|
+
socket.on('error', (error) => {
|
|
149
|
+
if (abandoned()) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
settle('disconnected', 'CONNECTION_FAILED', error.message, error);
|
|
153
|
+
});
|
|
154
|
+
socket.on('open', () => {
|
|
155
|
+
if (abandoned()) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
clearTimeout(timer);
|
|
159
|
+
resolve();
|
|
160
|
+
});
|
|
161
|
+
socket.on('message', (data) => {
|
|
162
|
+
this.#handleMessage(String(data));
|
|
163
|
+
});
|
|
164
|
+
socket.on('close', () => {
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
this.#state = 'disconnected';
|
|
167
|
+
this.#failPending('CONNECTION_CLOSED', 'BiDi connection closed.');
|
|
168
|
+
this.#fireClose();
|
|
169
|
+
});
|
|
170
|
+
}, (error) => {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
settle('disconnected', 'CONNECTION_FAILED', error instanceof Error ? error.message : String(error), error);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Create the raw socket: a plain WebSocket for Firefox-family BiDi
|
|
178
|
+
* endpoints, or the mapper facade for Chromium.
|
|
179
|
+
*/
|
|
180
|
+
#createSocket() {
|
|
181
|
+
if (this.#openSocketFn === undefined) {
|
|
182
|
+
return Promise.resolve(new WebSocket(this.url));
|
|
183
|
+
}
|
|
184
|
+
// The facade satisfies the ws surface this client uses; the cast keeps
|
|
185
|
+
// the single socket field untyped-union free.
|
|
186
|
+
return this.#openSocketFn().then((facade) => facade);
|
|
187
|
+
}
|
|
188
|
+
async request(method, params = {}) {
|
|
189
|
+
const socket = this.#socket;
|
|
190
|
+
if (socket === undefined || this.#state !== 'connected') {
|
|
191
|
+
throw new ActionableError('CONNECTION_FAILED', 'Not connected to a BiDi endpoint.');
|
|
192
|
+
}
|
|
193
|
+
const id = this.#nextId++;
|
|
194
|
+
const message = { id, method, params };
|
|
195
|
+
const timer = setTimeout(() => {
|
|
196
|
+
const pending = this.#pending.get(id);
|
|
197
|
+
if (pending !== undefined) {
|
|
198
|
+
this.#pending.delete(id);
|
|
199
|
+
pending.reject(new ActionableError('TIMEOUT', `Timed out waiting for ${method}.`));
|
|
200
|
+
}
|
|
201
|
+
}, this.#timeoutMs);
|
|
202
|
+
return new Promise((resolve, reject) => {
|
|
203
|
+
this.#pending.set(id, { resolve, reject, timer });
|
|
204
|
+
socket.send(JSON.stringify(message));
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
async close() {
|
|
208
|
+
const socket = this.#socket;
|
|
209
|
+
this.#socket = undefined;
|
|
210
|
+
this.#state = 'disconnected';
|
|
211
|
+
this.#failPending('CONNECTION_CLOSED', 'BiDi connection closed.');
|
|
212
|
+
if (socket === undefined) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
await new Promise((resolve) => {
|
|
216
|
+
if (socket.readyState === socket.CLOSED) {
|
|
217
|
+
resolve();
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
socket.once('close', () => resolve());
|
|
221
|
+
// `close()` throws synchronously on a CONNECTING socket; the 'error'
|
|
222
|
+
// and 'close' events still arrive and resolve the promise. The
|
|
223
|
+
// listener goes first so a synchronous emit cannot be missed.
|
|
224
|
+
try {
|
|
225
|
+
socket.close();
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// Socket is still handshaking; the close events will follow.
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
#handleMessage(raw) {
|
|
233
|
+
let message;
|
|
234
|
+
try {
|
|
235
|
+
message = JSON.parse(raw);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (message.type === 'event') {
|
|
241
|
+
for (const handler of this.#eventHandlers) {
|
|
242
|
+
handler(message);
|
|
243
|
+
}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const pending = this.#pending.get(message.id);
|
|
247
|
+
if (pending === undefined) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
this.#pending.delete(message.id);
|
|
251
|
+
clearTimeout(pending.timer);
|
|
252
|
+
if (message.type === 'success') {
|
|
253
|
+
pending.resolve(message.result);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
// Per the BiDi spec, error frames carry `error` as a flat string code and
|
|
257
|
+
// `message` as a sibling string. Some endpoints nest them instead; accept
|
|
258
|
+
// both shapes and never dereference a field that may not exist.
|
|
259
|
+
const rawError = message.error;
|
|
260
|
+
const nested = rawError;
|
|
261
|
+
const errorMessage = typeof message.message === 'string' && message.message !== ''
|
|
262
|
+
? message.message
|
|
263
|
+
: typeof nested?.message === 'string'
|
|
264
|
+
? nested.message
|
|
265
|
+
: undefined;
|
|
266
|
+
const biDiCode = typeof rawError === 'string'
|
|
267
|
+
? rawError
|
|
268
|
+
: typeof nested?.code === 'string'
|
|
269
|
+
? nested.code
|
|
270
|
+
: undefined;
|
|
271
|
+
// Real Firefox/Zen reports the one-session conflict as
|
|
272
|
+
// `session not created` / "Maximum number of active sessions".
|
|
273
|
+
const isBusy = biDiCode === 'session not created' ||
|
|
274
|
+
(errorMessage !== undefined &&
|
|
275
|
+
/maximum number (of )?active sessions/i.test(errorMessage));
|
|
276
|
+
const code = isBusy ? 'SESSION_BUSY' : 'SESSION_FAILED';
|
|
277
|
+
pending.reject(new ActionableError(code, errorMessage ??
|
|
278
|
+
`Malformed BiDi error frame for request ${String(message.id)}.`, { details: biDiCode === undefined ? undefined : { biDiCode } }));
|
|
279
|
+
}
|
|
280
|
+
#failPending(code, message) {
|
|
281
|
+
this.#fireClose();
|
|
282
|
+
for (const pending of this.#pending.values()) {
|
|
283
|
+
clearTimeout(pending.timer);
|
|
284
|
+
pending.reject(new ActionableError(code, message));
|
|
285
|
+
}
|
|
286
|
+
this.#pending.clear();
|
|
287
|
+
}
|
|
288
|
+
#fireClose() {
|
|
289
|
+
if (this.#closeHandlersFired) {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
this.#closeHandlersFired = true;
|
|
293
|
+
for (const handler of this.#closeHandlers) {
|
|
294
|
+
handler();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
//# sourceMappingURL=bidi-client.js.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Config, DiscoveryCandidate } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Parse `--remote-debugging-port` from a process command line.
|
|
4
|
+
* Supports `--remote-debugging-port`, `--remote-debugging-port 9223`, and
|
|
5
|
+
* `--remote-debugging-port=9223`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function extractRemoteDebuggingPort(commandLine: string): number | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Parse `--user-data-dir` from a Chromium command line. Portable installs (and
|
|
10
|
+
* custom profiles) only expose their CDP URL through the DevToolsActivePort
|
|
11
|
+
* file in that directory, so this is how Chromium is found without config.
|
|
12
|
+
*/
|
|
13
|
+
export declare function extractUserDataDir(commandLine: string): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Read `DevToolsActivePort`: first line is the port, second is the browser
|
|
16
|
+
* WebSocket path (`/devtools/browser/<id>`). Returns a CDP endpoint the mapper
|
|
17
|
+
* can attach to; the browser must already be running.
|
|
18
|
+
*/
|
|
19
|
+
export declare function chromiumEndpointFromDataDir(dataDir: string): string | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Gate every discovered candidate against BIDI_ALLOW_REMOTE, not just the
|
|
22
|
+
* explicit BIDI_WS_URL case. Profile files are user-writable data — a tampered
|
|
23
|
+
* or rogue WebDriverBiDiServer.json must not point the server at a remote host.
|
|
24
|
+
*/
|
|
25
|
+
export declare function endpointAllowed(config: Config, endpoint: string): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Return discovery candidates without probing them. Callers must verify the
|
|
28
|
+
* endpoint themselves before using it.
|
|
29
|
+
*/
|
|
30
|
+
export declare function discoverBrowsers(config: Config): Promise<readonly DiscoveryCandidate[]>;
|