@yanzc/claude-pro 0.8.0 → 0.9.1
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/README.md +342 -318
- package/package.json +1 -2
- package/src/agent.js +80 -14
- package/src/agents.js +3 -2
- package/src/api.js +39 -34
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +169 -67
- package/src/compaction.js +75 -0
- package/src/config.js +145 -144
- package/src/context.js +45 -18
- package/src/filestate.js +3 -2
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +7 -63
- package/src/ratelimit.js +2 -4
- package/src/remote.js +76 -14
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +18 -17
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +368 -45
- package/src/tools/index.js +9 -1
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +33 -8
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +335 -101
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +23 -2
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +66 -11
- package/.env.example +0 -29
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
// The connections to the user's own browsers, held by one process for every claude-pro session of this user.
|
|
2
|
+
//
|
|
3
|
+
// A browser whose remote debugging was turned on in its settings (edge://inspect, chrome://inspect) asks the user to
|
|
4
|
+
// allow every new connection, and has no "always allow". With a connection per claude-pro process, every restart
|
|
5
|
+
// (one after every change to claude-pro's own source, in every open session) and every other session asked again:
|
|
6
|
+
// the user had to click Allow over and over. The broker keeps one connection per browser instance and lends it to
|
|
7
|
+
// the sessions over a local pipe, passing the DevTools messages through: their ids renumbered, the events of an
|
|
8
|
+
// attached tab sent to the session that attached it, the browser's own events to all. It closes a connection ten
|
|
9
|
+
// minutes after the last session let go of it (a restart takes seconds), and exits when it has none.
|
|
10
|
+
//
|
|
11
|
+
// It runs as `node broker.js --serve`, started by the first session that needs it (connectShared); a session that
|
|
12
|
+
// cannot reach it connects on its own, as before. Only browsers on this computer are connected to, and a session
|
|
13
|
+
// must show the token the broker wrote into the config directory.
|
|
14
|
+
|
|
15
|
+
import net from 'node:net';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
import { spawn } from 'node:child_process';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { Cdp, CdpError, abortError } from './cdp.js';
|
|
22
|
+
import { CONFIG_DIR } from '../config.js';
|
|
23
|
+
|
|
24
|
+
export const brokerLimits = {
|
|
25
|
+
keepMs: 10 * 60_000, // a connection no session uses any more stays this long
|
|
26
|
+
exitMs: 30_000, // the broker exits after this long with no connection and no session
|
|
27
|
+
openMs: 120_000, // the user may take a while to click Allow
|
|
28
|
+
startMs: 5_000, // for a new broker to start listening
|
|
29
|
+
};
|
|
30
|
+
const PROTOCOL = 1;
|
|
31
|
+
|
|
32
|
+
const pipePath = (dir) => (process.platform === 'win32'
|
|
33
|
+
? `\\\\.\\pipe\\claude-pro-browser-${crypto.createHash('sha1').update(path.resolve(dir).toLowerCase()).digest('hex').slice(0, 12)}`
|
|
34
|
+
: path.join(dir, 'browser-broker.sock'));
|
|
35
|
+
const stateFile = (dir) => path.join(dir, 'browser-broker.json');
|
|
36
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
37
|
+
|
|
38
|
+
const onThisComputer = (url) => {
|
|
39
|
+
try {
|
|
40
|
+
const u = new URL(url);
|
|
41
|
+
return /^wss?:$/.test(u.protocol) && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
42
|
+
} catch { return false; }
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Newline-separated JSON on a socket: `onLine(text)` for each line.
|
|
46
|
+
function lines(sock, onLine) {
|
|
47
|
+
let buf = '';
|
|
48
|
+
sock.setEncoding('utf8');
|
|
49
|
+
sock.on('data', (d) => {
|
|
50
|
+
buf += d;
|
|
51
|
+
for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
|
|
52
|
+
const line = buf.slice(0, i);
|
|
53
|
+
buf = buf.slice(i + 1);
|
|
54
|
+
if (line) onLine(line);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---- The broker
|
|
60
|
+
|
|
61
|
+
// One browser connection, shared by the sessions (`clients`) that use it.
|
|
62
|
+
class Upstream {
|
|
63
|
+
constructor(url, onGone) {
|
|
64
|
+
this.url = url;
|
|
65
|
+
this.onGone = onGone;
|
|
66
|
+
this.ws = null;
|
|
67
|
+
this.connecting = null;
|
|
68
|
+
this.clients = new Set();
|
|
69
|
+
this.pending = new Map(); // id sent to the browser -> {client, id: the client's own, method}
|
|
70
|
+
this.owners = new Map(); // sessionId of an attached tab -> the client that attached it
|
|
71
|
+
this.nextId = 1;
|
|
72
|
+
this.opens = 0; // connections made (each one the user had to allow)
|
|
73
|
+
this.keep = null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
get open() { return this.ws?.readyState === 1; }
|
|
77
|
+
|
|
78
|
+
connect() {
|
|
79
|
+
if (this.open) return Promise.resolve();
|
|
80
|
+
this.connecting ??= new Promise((resolve, reject) => {
|
|
81
|
+
const ws = new WebSocket(this.url);
|
|
82
|
+
let settled = false;
|
|
83
|
+
const fail = (err) => {
|
|
84
|
+
if (settled) return;
|
|
85
|
+
settled = true;
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
this.connecting = null;
|
|
88
|
+
try { ws.close(); } catch { /* not open */ }
|
|
89
|
+
reject(err);
|
|
90
|
+
};
|
|
91
|
+
const timer = setTimeout(() => fail(new Error(`the browser did not accept the connection within ${brokerLimits.openMs / 1000} s (nobody allowed remote debugging?)`)), brokerLimits.openMs);
|
|
92
|
+
ws.onopen = () => {
|
|
93
|
+
if (settled) { try { ws.close(); } catch { /* gone */ } return; }
|
|
94
|
+
settled = true;
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
this.connecting = null;
|
|
97
|
+
this.ws = ws;
|
|
98
|
+
this.opens++;
|
|
99
|
+
ws.onmessage = (m) => this.receive(m.data);
|
|
100
|
+
ws.onclose = () => this.lost('the browser closed the connection');
|
|
101
|
+
ws.onerror = () => {};
|
|
102
|
+
resolve();
|
|
103
|
+
};
|
|
104
|
+
ws.onerror = (e) => fail(new Error(`cannot connect to the browser: ${e?.message || e?.error?.message || 'connection refused or declined'}`));
|
|
105
|
+
ws.onclose = (e) => fail(new Error(`the browser refused the connection${e?.code && e.code !== 1006 ? ` (${e.code}${e.reason ? ` ${e.reason}` : ''})` : ''}: remote debugging was declined or turned off`));
|
|
106
|
+
});
|
|
107
|
+
return this.connecting;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
add(client) {
|
|
111
|
+
this.clients.add(client);
|
|
112
|
+
clearTimeout(this.keep);
|
|
113
|
+
this.keep = null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A session let go: its tabs are detached, and the connection is kept a while for the next one.
|
|
117
|
+
remove(client) {
|
|
118
|
+
if (!this.clients.delete(client)) return;
|
|
119
|
+
for (const [sessionId, owner] of this.owners) {
|
|
120
|
+
if (owner !== client) continue;
|
|
121
|
+
this.owners.delete(sessionId);
|
|
122
|
+
if (this.open) this.ws.send(JSON.stringify({ id: this.nextId++, method: 'Target.detachFromTarget', params: { sessionId } }));
|
|
123
|
+
}
|
|
124
|
+
for (const [id, p] of this.pending) if (p.client === client) this.pending.delete(id);
|
|
125
|
+
if (!this.clients.size) {
|
|
126
|
+
clearTimeout(this.keep);
|
|
127
|
+
this.keep = setTimeout(() => this.close(), brokerLimits.keepMs);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
send(client, msg) {
|
|
132
|
+
if (!this.open) {
|
|
133
|
+
if (msg.id !== undefined) client.write({ id: msg.id, error: { code: -32000, message: 'the browser connection is closed' } });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const id = this.nextId++;
|
|
137
|
+
this.pending.set(id, { client, id: msg.id, method: msg.method });
|
|
138
|
+
this.ws.send(JSON.stringify({ ...msg, id }));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
receive(data) {
|
|
142
|
+
let msg;
|
|
143
|
+
try { msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8')); } catch { return; }
|
|
144
|
+
if (msg.id !== undefined) {
|
|
145
|
+
const p = this.pending.get(msg.id);
|
|
146
|
+
if (!p) return; // a detach of the broker's own
|
|
147
|
+
this.pending.delete(msg.id);
|
|
148
|
+
if (p.method === 'Target.attachToTarget' && msg.result?.sessionId) this.owners.set(msg.result.sessionId, p.client);
|
|
149
|
+
p.client.write({ ...msg, id: p.id });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (msg.sessionId) { this.owners.get(msg.sessionId)?.write(msg); return; }
|
|
153
|
+
if (msg.method === 'Target.detachedFromTarget') this.owners.delete(msg.params?.sessionId);
|
|
154
|
+
for (const c of this.clients) c.write(msg);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
lost(reason) {
|
|
158
|
+
this.ws = null;
|
|
159
|
+
for (const c of [...this.clients]) c.end(reason);
|
|
160
|
+
this.clients.clear();
|
|
161
|
+
this.gone();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
close() {
|
|
165
|
+
const ws = this.ws;
|
|
166
|
+
this.ws = null;
|
|
167
|
+
if (ws) {
|
|
168
|
+
ws.onclose = null;
|
|
169
|
+
try { ws.close(); } catch { /* gone */ }
|
|
170
|
+
}
|
|
171
|
+
this.gone();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
gone() {
|
|
175
|
+
clearTimeout(this.keep);
|
|
176
|
+
this.keep = null;
|
|
177
|
+
this.onGone(this);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function serve(dir = CONFIG_DIR) {
|
|
182
|
+
const token = crypto.randomBytes(24).toString('hex');
|
|
183
|
+
const upstreams = new Map(); // url -> Upstream
|
|
184
|
+
let sessions = 0;
|
|
185
|
+
let exitTimer = null;
|
|
186
|
+
const maybeExit = () => {
|
|
187
|
+
clearTimeout(exitTimer);
|
|
188
|
+
if (!sessions && !upstreams.size) exitTimer = setTimeout(() => process.exit(0), brokerLimits.exitMs);
|
|
189
|
+
};
|
|
190
|
+
const server = net.createServer((sock) => {
|
|
191
|
+
sessions++;
|
|
192
|
+
clearTimeout(exitTimer);
|
|
193
|
+
let upstream = null;
|
|
194
|
+
let greeted = false;
|
|
195
|
+
const client = {
|
|
196
|
+
write: (msg) => { if (!sock.destroyed) sock.write(`${JSON.stringify(msg)}\n`); },
|
|
197
|
+
end: (reason) => { client.write({ t: 'closed', reason }); sock.end(); },
|
|
198
|
+
};
|
|
199
|
+
const refuse = (message, extra = {}) => { client.write({ t: 'error', message, ...extra }); sock.end(); };
|
|
200
|
+
const hello = async (msg) => {
|
|
201
|
+
if (msg.token !== token) return refuse('not allowed');
|
|
202
|
+
if (msg.protocol !== PROTOCOL) return refuse(`the broker speaks protocol ${PROTOCOL}`, { protocol: PROTOCOL });
|
|
203
|
+
if (msg.t === 'status') {
|
|
204
|
+
client.write({ t: 'status', pid: process.pid, upstreams: [...upstreams.values()].map((u) => ({ url: u.url, sessions: u.clients.size, opens: u.opens, open: u.open })) });
|
|
205
|
+
return sock.end();
|
|
206
|
+
}
|
|
207
|
+
if (!onThisComputer(msg.url)) return refuse('only a browser on this computer');
|
|
208
|
+
let u = upstreams.get(msg.url);
|
|
209
|
+
if (!u) {
|
|
210
|
+
u = new Upstream(msg.url, (gone) => { if (upstreams.get(gone.url) === gone) upstreams.delete(gone.url); maybeExit(); });
|
|
211
|
+
upstreams.set(msg.url, u);
|
|
212
|
+
}
|
|
213
|
+
upstream = u;
|
|
214
|
+
u.add(client);
|
|
215
|
+
const waiting = setTimeout(() => client.write({ t: 'waiting' }), 1500);
|
|
216
|
+
try {
|
|
217
|
+
await u.connect();
|
|
218
|
+
clearTimeout(waiting);
|
|
219
|
+
client.write({ t: 'open' });
|
|
220
|
+
} catch (e) {
|
|
221
|
+
clearTimeout(waiting);
|
|
222
|
+
u.remove(client);
|
|
223
|
+
if (!u.clients.size && !u.open) u.gone();
|
|
224
|
+
refuse(e.message);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
lines(sock, (line) => {
|
|
228
|
+
let msg;
|
|
229
|
+
try { msg = JSON.parse(line); } catch { return; }
|
|
230
|
+
if (!greeted) { greeted = true; hello(msg); return; }
|
|
231
|
+
if (upstream?.open) upstream.send(client, msg);
|
|
232
|
+
});
|
|
233
|
+
sock.on('close', () => {
|
|
234
|
+
sessions--;
|
|
235
|
+
upstream?.remove(client);
|
|
236
|
+
maybeExit();
|
|
237
|
+
});
|
|
238
|
+
sock.on('error', () => {});
|
|
239
|
+
});
|
|
240
|
+
server.on('error', () => process.exit(0)); // another broker has the pipe: it serves
|
|
241
|
+
server.listen(pipePath(dir), () => {
|
|
242
|
+
try { fs.writeFileSync(stateFile(dir), JSON.stringify({ pid: process.pid, pipe: pipePath(dir), token, protocol: PROTOCOL }), { mode: 0o600 }); } catch { process.exit(1); }
|
|
243
|
+
maybeExit();
|
|
244
|
+
});
|
|
245
|
+
return server;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---- A session's side
|
|
249
|
+
|
|
250
|
+
function readState(dir) {
|
|
251
|
+
try { return JSON.parse(fs.readFileSync(stateFile(dir), 'utf8')); } catch { return null; }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function dial(pipe) {
|
|
255
|
+
return new Promise((resolve, reject) => {
|
|
256
|
+
const sock = net.connect(pipe);
|
|
257
|
+
sock.once('connect', () => { sock.removeListener('error', reject); resolve(sock); });
|
|
258
|
+
sock.once('error', reject);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function startBroker() {
|
|
263
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--serve'], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
|
|
264
|
+
child.on('error', () => {});
|
|
265
|
+
child.unref();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// A socket to the broker, and the token to show it: the running one, else one started now.
|
|
269
|
+
async function reach(dir) {
|
|
270
|
+
let state = readState(dir);
|
|
271
|
+
if (state?.pipe) {
|
|
272
|
+
try { return { sock: await dial(state.pipe), state }; } catch { /* gone */ }
|
|
273
|
+
}
|
|
274
|
+
startBroker();
|
|
275
|
+
for (const until = Date.now() + brokerLimits.startMs; Date.now() < until;) {
|
|
276
|
+
await sleep(100);
|
|
277
|
+
state = readState(dir);
|
|
278
|
+
if (!state?.pipe) continue;
|
|
279
|
+
try { return { sock: await dial(state.pipe), state }; } catch { /* not listening yet, or the old one's file */ }
|
|
280
|
+
}
|
|
281
|
+
throw new Error('the browser broker did not start');
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// The broker's connection to the browser at `url`, in the shape Cdp takes (send, close, onmessage, onclose). Rejects
|
|
285
|
+
// with a CdpError when the browser refuses or nobody allows it (as Cdp.connect), with another error when the broker
|
|
286
|
+
// cannot be had.
|
|
287
|
+
export async function brokerSocket(url, { signal, timeoutMs = brokerLimits.openMs, onWaiting, dir = CONFIG_DIR } = {}) {
|
|
288
|
+
if (signal?.aborted) throw abortError();
|
|
289
|
+
const { sock, state } = await reach(dir);
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
let settled = false;
|
|
292
|
+
let handler = null;
|
|
293
|
+
const queue = []; // what comes before Cdp takes over
|
|
294
|
+
const socket = {
|
|
295
|
+
onclose: null,
|
|
296
|
+
onerror: null,
|
|
297
|
+
get onmessage() { return handler; },
|
|
298
|
+
set onmessage(h) { handler = h; while (handler && queue.length) handler({ data: queue.shift() }); },
|
|
299
|
+
send: (text) => { if (!sock.destroyed) sock.write(`${text}\n`); },
|
|
300
|
+
close: () => sock.end(),
|
|
301
|
+
};
|
|
302
|
+
const fail = (err) => {
|
|
303
|
+
if (settled) return;
|
|
304
|
+
settled = true;
|
|
305
|
+
clearTimeout(timer);
|
|
306
|
+
signal?.removeEventListener('abort', onAbort);
|
|
307
|
+
sock.destroy();
|
|
308
|
+
reject(err);
|
|
309
|
+
};
|
|
310
|
+
const timer = setTimeout(() => fail(new CdpError(`the browser did not accept the connection within ${timeoutMs / 1000} s (nobody allowed remote debugging?)`)), timeoutMs);
|
|
311
|
+
const onAbort = () => fail(abortError());
|
|
312
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
313
|
+
lines(sock, (line) => {
|
|
314
|
+
if (!settled) {
|
|
315
|
+
let msg;
|
|
316
|
+
try { msg = JSON.parse(line); } catch { return; }
|
|
317
|
+
if (msg.t === 'waiting') { onWaiting?.(); return; }
|
|
318
|
+
if (msg.t === 'open') {
|
|
319
|
+
settled = true;
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
signal?.removeEventListener('abort', onAbort);
|
|
322
|
+
resolve(socket);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (msg.t === 'error') {
|
|
326
|
+
// the browser's answer is the browser's; the broker's own trouble (another protocol) is not
|
|
327
|
+
fail(msg.protocol ? new Error(msg.message) : new CdpError(msg.message));
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (line.startsWith('{"t":"closed"')) { sock.end(); return; }
|
|
333
|
+
if (handler) handler({ data: line }); else queue.push(line);
|
|
334
|
+
});
|
|
335
|
+
sock.on('close', () => { if (settled) socket.onclose?.({}); else fail(new Error('the browser broker went away')); });
|
|
336
|
+
sock.on('error', () => {});
|
|
337
|
+
sock.write(`${JSON.stringify({ t: 'hello', token: state.token, protocol: PROTOCOL, url })}\n`);
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// A Cdp to the browser at `url` through the broker, so that the user allows it once for all sessions and restarts;
|
|
342
|
+
// one of this process's own when the broker cannot be had.
|
|
343
|
+
export async function connectShared(url, opts = {}) {
|
|
344
|
+
let socket;
|
|
345
|
+
try {
|
|
346
|
+
socket = await brokerSocket(url, opts);
|
|
347
|
+
} catch (e) {
|
|
348
|
+
if (e?.name === 'AbortError' || e instanceof CdpError) throw e;
|
|
349
|
+
return Cdp.connect(url, opts);
|
|
350
|
+
}
|
|
351
|
+
return new Cdp(socket);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// What the broker holds (for tests and diagnosis): {pid, upstreams: [{url, sessions, opens, open}]}, or null.
|
|
355
|
+
export async function brokerStatus(dir = CONFIG_DIR) {
|
|
356
|
+
const state = readState(dir);
|
|
357
|
+
if (!state?.pipe) return null;
|
|
358
|
+
let sock;
|
|
359
|
+
try { sock = await dial(state.pipe); } catch { return null; }
|
|
360
|
+
return new Promise((resolve) => {
|
|
361
|
+
lines(sock, (line) => { try { resolve(JSON.parse(line)); } catch { resolve(null); } sock.end(); });
|
|
362
|
+
sock.on('close', () => resolve(null));
|
|
363
|
+
sock.write(`${JSON.stringify({ t: 'status', token: state.token, protocol: PROTOCOL })}\n`);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (process.argv.includes('--serve') && process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) serve();
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// One Chrome DevTools Protocol connection over Node's own WebSocket: commands with their replies, events, and the
|
|
2
|
+
// sessions of attached targets (flatten mode, one socket for all of them). No dependency.
|
|
3
|
+
|
|
4
|
+
export class CdpError extends Error {}
|
|
5
|
+
|
|
6
|
+
export const abortError = () => Object.assign(new Error('aborted'), { name: 'AbortError' });
|
|
7
|
+
|
|
8
|
+
export class Cdp {
|
|
9
|
+
// Opens the socket. A browser whose remote debugging was turned on in its settings (edge://inspect,
|
|
10
|
+
// chrome://inspect, Chrome and Edge 144+) holds the handshake until the user allows it in a dialog: `onWaiting`
|
|
11
|
+
// is called when it takes longer than a moment, so the user can be told what to click.
|
|
12
|
+
static connect(url, { signal, timeoutMs = 120_000, onWaiting } = {}) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
if (signal?.aborted) return reject(abortError());
|
|
15
|
+
const ws = new WebSocket(url);
|
|
16
|
+
let settled = false;
|
|
17
|
+
const waiting = setTimeout(() => onWaiting?.(), 1500);
|
|
18
|
+
const timer = setTimeout(() => fail(new CdpError(`the browser did not accept the connection within ${timeoutMs / 1000} s (nobody allowed remote debugging?)`)), timeoutMs);
|
|
19
|
+
const onAbort = () => fail(abortError());
|
|
20
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
21
|
+
function cleanup() { clearTimeout(waiting); clearTimeout(timer); signal?.removeEventListener('abort', onAbort); }
|
|
22
|
+
function fail(err) {
|
|
23
|
+
if (settled) return;
|
|
24
|
+
settled = true;
|
|
25
|
+
cleanup();
|
|
26
|
+
try { ws.close(); } catch { /* not open */ }
|
|
27
|
+
reject(err);
|
|
28
|
+
}
|
|
29
|
+
ws.onopen = () => {
|
|
30
|
+
if (settled) { try { ws.close(); } catch { /* gone */ } return; }
|
|
31
|
+
settled = true;
|
|
32
|
+
cleanup();
|
|
33
|
+
resolve(new Cdp(ws));
|
|
34
|
+
};
|
|
35
|
+
ws.onerror = (e) => fail(new CdpError(`cannot connect to the browser: ${e?.message || e?.error?.message || 'connection refused or declined'}`));
|
|
36
|
+
ws.onclose = (e) => fail(new CdpError(`the browser refused the connection${e?.code && e.code !== 1006 ? ` (${e.code}${e.reason ? ` ${e.reason}` : ''})` : ''}: remote debugging was declined or turned off`));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
constructor(ws) {
|
|
41
|
+
this.ws = ws;
|
|
42
|
+
this.nextId = 1;
|
|
43
|
+
this.pending = new Map(); // id -> {resolve, reject, done, method}
|
|
44
|
+
this.handlers = new Set(); // (method, params, sessionId) => void
|
|
45
|
+
this.closed = false;
|
|
46
|
+
this.closeReason = '';
|
|
47
|
+
ws.onmessage = (m) => this.receive(m.data);
|
|
48
|
+
ws.onclose = () => this.shutdown('the browser closed the connection');
|
|
49
|
+
ws.onerror = () => {};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
receive(data) {
|
|
53
|
+
let msg;
|
|
54
|
+
try { msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8')); } catch { return; }
|
|
55
|
+
if (msg.id !== undefined) {
|
|
56
|
+
const p = this.pending.get(msg.id);
|
|
57
|
+
if (!p) return;
|
|
58
|
+
this.pending.delete(msg.id);
|
|
59
|
+
p.done();
|
|
60
|
+
if (msg.error) p.reject(new CdpError(`${p.method}: ${msg.error.message}${msg.error.data ? ` (${msg.error.data})` : ''}`));
|
|
61
|
+
else p.resolve(msg.result || {});
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const h of [...this.handlers]) {
|
|
65
|
+
try { h(msg.method, msg.params || {}, msg.sessionId); } catch { /* one handler's bug must not stop the others */ }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// A command; `sessionId` sends it to an attached target. Rejects when the reply does not come in `timeoutMs`
|
|
70
|
+
// (0: no limit), when `signal` aborts, or when the connection closes.
|
|
71
|
+
send(method, params = {}, { sessionId, timeoutMs = 30_000, signal } = {}) {
|
|
72
|
+
if (this.closed) return Promise.reject(new CdpError(`${method}: ${this.closeReason}`));
|
|
73
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
74
|
+
const id = this.nextId++;
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
let timer = null;
|
|
77
|
+
const onAbort = () => { this.pending.delete(id); done(); reject(abortError()); };
|
|
78
|
+
const done = () => { if (timer) clearTimeout(timer); signal?.removeEventListener('abort', onAbort); };
|
|
79
|
+
if (timeoutMs) timer = setTimeout(() => { this.pending.delete(id); done(); reject(new CdpError(`${method}: no reply within ${timeoutMs / 1000} s`)); }, timeoutMs);
|
|
80
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
81
|
+
this.pending.set(id, { resolve, reject, done, method });
|
|
82
|
+
try {
|
|
83
|
+
this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
|
84
|
+
} catch (e) {
|
|
85
|
+
this.pending.delete(id);
|
|
86
|
+
done();
|
|
87
|
+
reject(new CdpError(`${method}: ${e.message}`));
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Events of the browser and of every attached session; returns the function that removes the handler.
|
|
93
|
+
// When the connection closes, handlers get ('Cdp.closed', {reason}).
|
|
94
|
+
on(handler) {
|
|
95
|
+
this.handlers.add(handler);
|
|
96
|
+
return () => this.handlers.delete(handler);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
shutdown(reason) {
|
|
100
|
+
if (this.closed) return;
|
|
101
|
+
this.closed = true;
|
|
102
|
+
this.closeReason = reason;
|
|
103
|
+
for (const p of this.pending.values()) { p.done(); p.reject(new CdpError(`${p.method}: ${reason}`)); }
|
|
104
|
+
this.pending.clear();
|
|
105
|
+
for (const h of [...this.handlers]) {
|
|
106
|
+
try { h('Cdp.closed', { reason }); } catch { /* closing anyway */ }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
close() {
|
|
111
|
+
try { this.ws.close(); } catch { /* already closed */ }
|
|
112
|
+
this.shutdown('closed by claude-pro');
|
|
113
|
+
}
|
|
114
|
+
}
|