@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,948 @@
|
|
|
1
|
+
// The browser the Browser tool drives: one DevTools connection per claude-pro process, kept for the whole session,
|
|
2
|
+
// because a browser whose remote debugging was turned on in its settings asks the user to allow every new
|
|
3
|
+
// connection. Only the tabs it works in are attached (the others, asleep ones included, are never touched: tab
|
|
4
|
+
// titles come from the browser, not from the pages), and every command has a time limit.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import net from 'node:net';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { Cdp, CdpError, abortError } from './cdp.js';
|
|
12
|
+
import { closeRenderer } from './render.js';
|
|
13
|
+
import { CONFIG_DIR } from '../config.js';
|
|
14
|
+
import { runText } from '../utils/shell.js';
|
|
15
|
+
import { connectShared } from './broker.js';
|
|
16
|
+
|
|
17
|
+
export const browserLimits = {
|
|
18
|
+
connectMs: 120_000, // the user may take a while to click Allow
|
|
19
|
+
commandMs: 15_000,
|
|
20
|
+
settleMs: 5_000, // after an action: until the network is quiet, at most this long
|
|
21
|
+
quietMs: 400,
|
|
22
|
+
navigationMs: 20_000,
|
|
23
|
+
waitMs: 10_000,
|
|
24
|
+
waitMaxMs: 60_000,
|
|
25
|
+
evalMs: 30_000,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export class BrowserError extends Error {}
|
|
29
|
+
|
|
30
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
31
|
+
if (signal?.aborted) return reject(abortError());
|
|
32
|
+
const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
|
|
33
|
+
const onAbort = () => { clearTimeout(t); reject(abortError()); };
|
|
34
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// ---- Which browser
|
|
38
|
+
|
|
39
|
+
// The browsers whose own (default) profile can be connected to once the user has turned on remote debugging in
|
|
40
|
+
// it (chrome://inspect/#remote-debugging and the like, Chrome and Edge 144+): it then writes DevToolsActivePort.
|
|
41
|
+
export function knownBrowsers({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
|
|
42
|
+
const inspect = (scheme) => `${scheme}://inspect/#remote-debugging`;
|
|
43
|
+
if (platform === 'win32') {
|
|
44
|
+
const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
|
|
45
|
+
return [
|
|
46
|
+
{ name: 'edge', label: 'Microsoft Edge', dir: path.join(local, 'Microsoft', 'Edge', 'User Data'), inspect: inspect('edge') },
|
|
47
|
+
{ name: 'chrome', label: 'Google Chrome', dir: path.join(local, 'Google', 'Chrome', 'User Data'), inspect: inspect('chrome') },
|
|
48
|
+
{ name: 'brave', label: 'Brave', dir: path.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data'), inspect: inspect('brave') },
|
|
49
|
+
{ name: 'chromium', label: 'Chromium', dir: path.join(local, 'Chromium', 'User Data'), inspect: inspect('chrome') },
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
const mac = platform === 'darwin';
|
|
53
|
+
const base = mac ? path.join(home, 'Library', 'Application Support') : (env.XDG_CONFIG_HOME || path.join(home, '.config'));
|
|
54
|
+
return [
|
|
55
|
+
{ name: 'edge', label: 'Microsoft Edge', dir: path.join(base, mac ? 'Microsoft Edge' : 'microsoft-edge'), inspect: inspect('edge') },
|
|
56
|
+
{ name: 'chrome', label: 'Google Chrome', dir: path.join(base, mac ? path.join('Google', 'Chrome') : 'google-chrome'), inspect: inspect('chrome') },
|
|
57
|
+
{ name: 'brave', label: 'Brave', dir: path.join(base, 'BraveSoftware', 'Brave-Browser'), inspect: inspect('brave') },
|
|
58
|
+
{ name: 'chromium', label: 'Chromium', dir: path.join(base, mac ? 'Chromium' : 'chromium'), inspect: inspect('chrome') },
|
|
59
|
+
];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const OWN = { name: 'own', label: "claude-pro's own browser", get dir() { return path.join(CONFIG_DIR, 'browser-profile'); } };
|
|
63
|
+
|
|
64
|
+
function portOpen(port, ms = 400) {
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
const s = net.connect(port, '127.0.0.1');
|
|
67
|
+
const done = (v) => { s.destroy(); resolve(v); };
|
|
68
|
+
s.once('connect', () => done(true));
|
|
69
|
+
s.once('error', () => done(false));
|
|
70
|
+
s.setTimeout(ms, () => done(false));
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The DevTools address a running browser wrote into its profile, when its port answers.
|
|
75
|
+
async function readEndpoint(dir) {
|
|
76
|
+
let text;
|
|
77
|
+
try { text = fs.readFileSync(path.join(dir, 'DevToolsActivePort'), 'utf8'); } catch { return null; }
|
|
78
|
+
const [portLine, wsPath] = text.trim().split(/\r?\n/);
|
|
79
|
+
const port = Number(portLine);
|
|
80
|
+
if (!Number.isInteger(port) || port <= 0 || !wsPath?.startsWith('/')) return null;
|
|
81
|
+
return (await portOpen(port)) ? `ws://127.0.0.1:${port}${wsPath}` : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// A DevTools address given as ws://…, http://host:port or a port (a browser started with --remote-debugging-port).
|
|
85
|
+
async function explicitEndpoint(spec, signal) {
|
|
86
|
+
if (/^wss?:\/\//i.test(spec)) return spec;
|
|
87
|
+
const base = /^\d+$/.test(spec) ? `http://127.0.0.1:${spec}` : /^https?:\/\//i.test(spec) ? spec : null;
|
|
88
|
+
if (!base) return null;
|
|
89
|
+
let info;
|
|
90
|
+
try {
|
|
91
|
+
const res = await fetch(new URL('/json/version', base), { signal: AbortSignal.any([AbortSignal.timeout(5000), ...(signal ? [signal] : [])]) });
|
|
92
|
+
info = await res.json();
|
|
93
|
+
} catch (e) {
|
|
94
|
+
if (signal?.aborted) throw abortError();
|
|
95
|
+
throw new BrowserError(`no DevTools endpoint answers at ${base}: ${e.message}`);
|
|
96
|
+
}
|
|
97
|
+
if (!info?.webSocketDebuggerUrl) throw new BrowserError(`${base} is not a DevTools endpoint (no webSocketDebuggerUrl in /json/version)`);
|
|
98
|
+
return info.webSocketDebuggerUrl;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function onPath(cmd) {
|
|
102
|
+
for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
|
|
103
|
+
const p = path.join(dir, cmd);
|
|
104
|
+
if (dir && fs.existsSync(p)) return p;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Chrome before Edge: Edge signs a new profile in with the Windows account and syncs that account's data into it.
|
|
110
|
+
export function browserExecutables() {
|
|
111
|
+
if (process.platform === 'win32') {
|
|
112
|
+
const pf = process.env.PROGRAMFILES || 'C:\\Program Files';
|
|
113
|
+
const pf86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
|
|
114
|
+
const local = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
115
|
+
return [
|
|
116
|
+
path.join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
117
|
+
path.join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
118
|
+
path.join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
119
|
+
path.join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
|
|
120
|
+
path.join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
|
|
121
|
+
];
|
|
122
|
+
}
|
|
123
|
+
if (process.platform === 'darwin') {
|
|
124
|
+
return ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'];
|
|
125
|
+
}
|
|
126
|
+
return ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'microsoft-edge-stable'].map(onPath);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// claude-pro's own browser: a Chrome (or Edge) with its own profile under the config directory, started with
|
|
130
|
+
// --remote-debugging-port, so nobody is asked anything; it stays open when claude-pro exits, logins included.
|
|
131
|
+
async function ownEndpoint(signal) {
|
|
132
|
+
const dir = OWN.dir;
|
|
133
|
+
const running = await readEndpoint(dir);
|
|
134
|
+
if (running) return running;
|
|
135
|
+
const exe = browserExecutables().find((p) => p && fs.existsSync(p));
|
|
136
|
+
if (!exe) throw new BrowserError('no Chrome or Edge is installed to start claude-pro\'s own browser with');
|
|
137
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
138
|
+
try { fs.unlinkSync(path.join(dir, 'DevToolsActivePort')); } catch { /* none yet */ }
|
|
139
|
+
const child = spawn(exe, ['--remote-debugging-port=0', `--user-data-dir=${dir}`, '--no-first-run', '--no-default-browser-check', 'about:blank'], { detached: true, stdio: 'ignore' });
|
|
140
|
+
child.on('error', () => {});
|
|
141
|
+
child.unref();
|
|
142
|
+
const until = Date.now() + 20_000;
|
|
143
|
+
while (Date.now() < until) {
|
|
144
|
+
await sleep(250, signal);
|
|
145
|
+
const url = await readEndpoint(dir);
|
|
146
|
+
if (url) return url;
|
|
147
|
+
}
|
|
148
|
+
throw new BrowserError(`${path.basename(exe)} did not open its DevTools port within 20 s`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const howToTurnOn = (b) => `${b.label} does not allow remote debugging now. The user turns it on at ${b.inspect} (allow remote debugging for this browser instance; ${b.label} then asks once per session to allow the connection). Or use browser: "own".`;
|
|
152
|
+
|
|
153
|
+
// ---- Every browser instance that allows remote debugging
|
|
154
|
+
//
|
|
155
|
+
// A browser started with a profile directory of its own (--user-data-dir: an app that opens its window in Edge, a
|
|
156
|
+
// second profile kept apart) is another instance, with its own tabs and its own DevToolsActivePort in that
|
|
157
|
+
// directory, which the usual places do not have: /tabs edge listed the user's main Edge and not the one their
|
|
158
|
+
// mail was open in. The running browsers' command lines say where each one keeps its profile.
|
|
159
|
+
|
|
160
|
+
const samePath = (a, b) => {
|
|
161
|
+
const x = path.resolve(String(a));
|
|
162
|
+
const y = path.resolve(String(b));
|
|
163
|
+
return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
export const sameBrowser = (a, b) => Boolean(a && b) && ((a.dir && b.dir) ? samePath(a.dir, b.dir) : a.url === b.url);
|
|
167
|
+
|
|
168
|
+
// A browser process's --user-data-dir ("..." around the value, or around the whole argument), or null.
|
|
169
|
+
export function userDataDirOf(command) {
|
|
170
|
+
const s = String(command || '');
|
|
171
|
+
const m = /"--user-data-dir=([^"]*)"/.exec(s) || /--user-data-dir="([^"]*)"/.exec(s) || /--user-data-dir=(\S+)/.exec(s);
|
|
172
|
+
return m?.[1] || null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Where a browser installed at `exe` keeps its profile when it is not given one. Windows: the <vendor>\<product> of its
|
|
176
|
+
// <vendor>\<product>\Application\<exe>, under LOCALAPPDATA, then "User Data" (Microsoft\Edge, Google\Chrome,
|
|
177
|
+
// BraveSoftware\Brave-Browser, and their Beta, Dev and Canary installs alike). Elsewhere: the usual place of its kind.
|
|
178
|
+
export function defaultUserDataDir(exe, kind, { env = process.env, home = os.homedir() } = {}) {
|
|
179
|
+
if (process.platform !== 'win32') return knownBrowsers().find((b) => b.name === kind)?.dir || null;
|
|
180
|
+
const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
|
|
181
|
+
const appDir = path.dirname(exe);
|
|
182
|
+
if (path.basename(appDir).toLowerCase() !== 'application') return null;
|
|
183
|
+
const product = path.dirname(appDir);
|
|
184
|
+
const rel = product.toLowerCase().startsWith(`${local.toLowerCase()}${path.sep}`)
|
|
185
|
+
? path.relative(local, product) // installed for the user (Chromium, a per-user Chrome)
|
|
186
|
+
: path.join(path.basename(path.dirname(product)), path.basename(product));
|
|
187
|
+
return path.join(local, rel, 'User Data');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const kindOf = (exe) => {
|
|
191
|
+
const name = path.basename(String(exe || '')).toLowerCase();
|
|
192
|
+
if (/^msedge(\.exe)?$/.test(name) || /microsoft edge/i.test(exe)) return 'edge';
|
|
193
|
+
if (/^brave(\.exe)?$/.test(name) || /brave/i.test(exe)) return 'brave';
|
|
194
|
+
if (/chromium/i.test(exe)) return 'chromium';
|
|
195
|
+
if (/^chrome(\.exe)?$/.test(name) || /google chrome/i.test(exe)) return 'chrome';
|
|
196
|
+
return null;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// The running browsers' main processes: [{kind, dir}], the profile directory each one runs on.
|
|
200
|
+
async function runningBrowserDirs() {
|
|
201
|
+
if (process.platform === 'win32') {
|
|
202
|
+
const script = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process -Filter "Name=\'msedge.exe\' OR Name=\'chrome.exe\' OR Name=\'brave.exe\'" | Where-Object { $_.CommandLine -notmatch \'--type=\' } | Select-Object Name,ExecutablePath,CommandLine | ConvertTo-Json -Compress';
|
|
203
|
+
const out = await runText('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 15_000, maxChars: 4_000_000 });
|
|
204
|
+
let rows = [];
|
|
205
|
+
try { const j = out ? JSON.parse(out.replace(/^\uFEFF/, '')) : []; rows = Array.isArray(j) ? j : [j]; } catch { /* none */ }
|
|
206
|
+
return rows.map((r) => {
|
|
207
|
+
const exe = r.ExecutablePath || String(r.CommandLine || '').match(/^"([^"]+)"|^(\S+)/)?.slice(1).find(Boolean) || '';
|
|
208
|
+
const kind = kindOf(exe);
|
|
209
|
+
const dir = userDataDirOf(r.CommandLine) || (kind ? defaultUserDataDir(exe, kind) : null);
|
|
210
|
+
return kind && dir ? { kind, dir: path.resolve(dir) } : null;
|
|
211
|
+
}).filter(Boolean);
|
|
212
|
+
}
|
|
213
|
+
const out = await runText('ps', ['-axo', 'args='], { timeout: 10_000, maxChars: 4_000_000 });
|
|
214
|
+
return String(out || '').split('\n').filter((l) => l.trim() && !/--type=/.test(l)).map((l) => {
|
|
215
|
+
const kind = kindOf(l.trim().split(/\s+--/)[0]);
|
|
216
|
+
const dir = kind ? userDataDirOf(l) || defaultUserDataDir(l, kind) : null;
|
|
217
|
+
return kind && dir ? { kind, dir: path.resolve(dir) } : null;
|
|
218
|
+
}).filter(Boolean);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const portOf = (url) => Number(/:(\d+)\//.exec(url || '')?.[1]) || null;
|
|
222
|
+
|
|
223
|
+
// Where `dir` is, for a label: from LOCALAPPDATA or the home directory when it is under one.
|
|
224
|
+
function shortDir(dir) {
|
|
225
|
+
for (const base of [process.env.LOCALAPPDATA, os.homedir()].filter(Boolean)) {
|
|
226
|
+
const rel = path.relative(base, dir);
|
|
227
|
+
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
|
|
228
|
+
}
|
|
229
|
+
return dir;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// An instance found at `dir`, for /tabs and the Browser tool: {name, label, dir, url, port, isDefault, own?}.
|
|
233
|
+
function instance(kind, dir, url) {
|
|
234
|
+
if (kind === 'own' || samePath(dir, OWN.dir)) return { ...OWN, dir: OWN.dir, url, port: portOf(url), own: true };
|
|
235
|
+
const base = knownBrowsers().find((b) => b.name === kind) || { name: kind || 'chrome', label: 'Chromium browser', inspect: 'chrome://inspect/#remote-debugging' };
|
|
236
|
+
const isDefault = Boolean(base.dir) && samePath(dir, base.dir);
|
|
237
|
+
return { ...base, dir, url, port: portOf(url), isDefault, label: isDefault ? base.label : `${base.label} · ${shortDir(dir)}` };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// The browser instances that allow remote debugging now, each once: the usual profiles of Edge, Chrome, Brave and
|
|
241
|
+
// Chromium first, then the running ones on profile directories of their own, then claude-pro's own browser. The
|
|
242
|
+
// process list takes about a second on Windows (PowerShell); without it, the usual places only.
|
|
243
|
+
export async function browserInstances() {
|
|
244
|
+
const candidates = knownBrowsers().map((b) => ({ kind: b.name, dir: b.dir }));
|
|
245
|
+
try { candidates.push(...await runningBrowserDirs()); } catch { /* the usual places only */ }
|
|
246
|
+
candidates.push({ kind: 'own', dir: OWN.dir });
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
const unique = candidates.filter((c) => {
|
|
249
|
+
const key = process.platform === 'win32' ? c.dir.toLowerCase() : c.dir;
|
|
250
|
+
if (seen.has(key)) return false;
|
|
251
|
+
seen.add(key);
|
|
252
|
+
return true;
|
|
253
|
+
});
|
|
254
|
+
const found = await Promise.all(unique.map(async (c) => {
|
|
255
|
+
const url = await readEndpoint(c.dir);
|
|
256
|
+
return url ? instance(c.kind, c.dir, url) : null;
|
|
257
|
+
}));
|
|
258
|
+
return found.filter(Boolean);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// The instance the session used last (picked with /tabs, or the one before a restart), when it is still there and
|
|
262
|
+
// the call asks for no browser in particular or for one of its kind (`w`, the call's own browser field: the user's
|
|
263
|
+
// pick wins over the configured default): its tab ids are the ones the conversation knows.
|
|
264
|
+
async function preferredTarget(preferred, w) {
|
|
265
|
+
if (!preferred?.dir) return null;
|
|
266
|
+
if (w && w !== 'auto' && w !== preferred.name) return null;
|
|
267
|
+
const url = await readEndpoint(preferred.dir);
|
|
268
|
+
return url ? instance(preferred.own ? 'own' : preferred.name, preferred.dir, url) : null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The browser to connect to: the one used last when it is still there (see preferredTarget), else `spec` (the
|
|
272
|
+
// call's browser field), else CLAUDE_PRO_BROWSER, else the first known browser that allows remote debugging, else
|
|
273
|
+
// one on a profile directory of its own, else claude-pro's own when it is running. `spec` may also be a profile
|
|
274
|
+
// directory.
|
|
275
|
+
export async function resolveBrowser(spec, env, signal, preferred = null) {
|
|
276
|
+
const wanted = String(spec || env?.CLAUDE_PRO_BROWSER || '').trim();
|
|
277
|
+
const w = wanted.toLowerCase();
|
|
278
|
+
if (w === 'off') throw new BrowserError('the browser is turned off for claude-pro (CLAUDE_PRO_BROWSER=off)');
|
|
279
|
+
const again = await preferredTarget(preferred, String(spec || '').trim().toLowerCase());
|
|
280
|
+
if (again) return again;
|
|
281
|
+
if (w && w !== 'auto') {
|
|
282
|
+
if (w === 'own') return { ...OWN, dir: OWN.dir, url: await ownEndpoint(signal), own: true };
|
|
283
|
+
const known = knownBrowsers().find((b) => b.name === w);
|
|
284
|
+
if (known) {
|
|
285
|
+
const url = await readEndpoint(known.dir);
|
|
286
|
+
if (url) return { ...known, url, port: portOf(url), isDefault: true };
|
|
287
|
+
// not in its usual profile: one running on a profile directory of its own
|
|
288
|
+
const others = (await browserInstances()).filter((i) => i.name === w);
|
|
289
|
+
if (others.length === 1) return others[0];
|
|
290
|
+
if (others.length > 1) throw new BrowserError(`${known.label} allows remote debugging in ${others.length} profile directories: ${others.map((i) => i.dir).join('; ')}. Pass the one meant as browser (the user can pick one with /tabs)`);
|
|
291
|
+
throw new BrowserError(howToTurnOn(known));
|
|
292
|
+
}
|
|
293
|
+
if (/[\\/]/.test(wanted) && fs.existsSync(wanted) && fs.statSync(wanted).isDirectory()) {
|
|
294
|
+
const url = await readEndpoint(wanted);
|
|
295
|
+
if (!url) throw new BrowserError(`no browser with remote debugging runs on ${wanted} now`);
|
|
296
|
+
return instance(kindOf(wanted) || 'chrome', path.resolve(wanted), url);
|
|
297
|
+
}
|
|
298
|
+
const url = await explicitEndpoint(wanted, signal);
|
|
299
|
+
if (url) {
|
|
300
|
+
let where = wanted;
|
|
301
|
+
try { where = new URL(url).host; } catch { /* as given */ }
|
|
302
|
+
return { name: wanted, label: `the browser at ${where}`, url };
|
|
303
|
+
}
|
|
304
|
+
throw new BrowserError(`unknown browser "${wanted}": use edge, chrome, brave, chromium, own, or a DevTools address (ws://…, http://host:port, a port)`);
|
|
305
|
+
}
|
|
306
|
+
const found = [];
|
|
307
|
+
for (const b of knownBrowsers()) {
|
|
308
|
+
const url = await readEndpoint(b.dir);
|
|
309
|
+
if (url) found.push({ ...b, url, port: portOf(url), isDefault: true });
|
|
310
|
+
}
|
|
311
|
+
if (found.length) return { ...found[0], others: found.slice(1).map((b) => b.name) };
|
|
312
|
+
const elsewhere = (await browserInstances()).filter((i) => !i.own);
|
|
313
|
+
if (elsewhere.length) return { ...elsewhere[0], others: elsewhere.slice(1).map((i) => i.dir) };
|
|
314
|
+
const own = await readEndpoint(OWN.dir);
|
|
315
|
+
if (own) return { ...OWN, dir: OWN.dir, url: own, own: true };
|
|
316
|
+
const installed = knownBrowsers().filter((b) => fs.existsSync(b.dir));
|
|
317
|
+
throw new BrowserError(`no browser allows remote debugging. The user can turn it on in theirs (${(installed.length ? installed : knownBrowsers().slice(0, 2)).map((b) => `${b.label}: ${b.inspect}`).join('; ')}: allow remote debugging for this browser instance; the browser then asks once per session to allow the connection). Or use browser: "own" for claude-pro's own browser (its own profile: nothing to allow, but sites need a login there once).`);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---- Keys
|
|
321
|
+
|
|
322
|
+
const KEYS = {
|
|
323
|
+
Enter: [13, 'Enter', '\r'], Tab: [9, 'Tab'], Escape: [27, 'Escape'], Backspace: [8, 'Backspace'], Delete: [46, 'Delete'],
|
|
324
|
+
Space: [32, 'Space', ' '], ArrowUp: [38, 'ArrowUp'], ArrowDown: [40, 'ArrowDown'], ArrowLeft: [37, 'ArrowLeft'],
|
|
325
|
+
ArrowRight: [39, 'ArrowRight'], Home: [36, 'Home'], End: [35, 'End'], PageUp: [33, 'PageUp'], PageDown: [34, 'PageDown'],
|
|
326
|
+
Insert: [45, 'Insert'],
|
|
327
|
+
...Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`F${i + 1}`, [112 + i, `F${i + 1}`]])),
|
|
328
|
+
};
|
|
329
|
+
const ALIASES = { esc: 'Escape', return: 'Enter', del: 'Delete', up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight', ' ': 'Space', spacebar: 'Space' };
|
|
330
|
+
const MODIFIERS = { alt: [1, 'Alt', 'AltLeft', 18], option: [1, 'Alt', 'AltLeft', 18], control: [2, 'Control', 'ControlLeft', 17], ctrl: [2, 'Control', 'ControlLeft', 17], meta: [4, 'Meta', 'MetaLeft', 91], cmd: [4, 'Meta', 'MetaLeft', 91], command: [4, 'Meta', 'MetaLeft', 91], shift: [8, 'Shift', 'ShiftLeft', 16] };
|
|
331
|
+
// macOS takes editing shortcuts from its text system, which synthetic key events do not reach: they need commands.
|
|
332
|
+
const MAC_COMMANDS = { a: 'selectAll', c: 'copy', x: 'cut', v: 'paste', z: 'undo' };
|
|
333
|
+
|
|
334
|
+
function keyEvent(name) {
|
|
335
|
+
const named = KEYS[name] || KEYS[ALIASES[name.toLowerCase()]] || Object.entries(KEYS).find(([k]) => k.toLowerCase() === name.toLowerCase())?.[1];
|
|
336
|
+
if (named) return { keyCode: named[0], key: named[1] === 'Space' ? ' ' : named[1], code: named[1], text: named[2] };
|
|
337
|
+
if ([...name].length === 1) {
|
|
338
|
+
const upper = name.toUpperCase();
|
|
339
|
+
const code = /[a-z]/i.test(name) ? `Key${upper}` : /\d/.test(name) ? `Digit${name}` : undefined;
|
|
340
|
+
return { keyCode: /[a-z\d]/i.test(name) ? upper.charCodeAt(0) : 0, key: name, code, text: name };
|
|
341
|
+
}
|
|
342
|
+
throw new BrowserError(`unknown key "${name}": use a character or Enter, Tab, Escape, Backspace, Delete, Space, ArrowUp/Down/Left/Right, Home, End, PageUp, PageDown, F1-F12, with Control+, Shift+, Alt+, Meta+ (Mod+ is Meta on macOS, Control elsewhere)`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// What covers an element, for the model: the nearest ancestor with a role, a label or a landmark tag, and its text.
|
|
346
|
+
const COVER_LABEL = `function() {
|
|
347
|
+
let what = '';
|
|
348
|
+
for (let n = this, i = 0; n && n.nodeType === 1 && i < 10; n = n.parentElement || n.getRootNode().host, i++) {
|
|
349
|
+
const role = n.getAttribute('role');
|
|
350
|
+
const label = n.getAttribute('aria-label');
|
|
351
|
+
if (role || label || ['header', 'nav', 'dialog', 'footer', 'aside', 'form'].includes(n.localName)) {
|
|
352
|
+
what = (role || n.localName) + (label ? ' "' + label.slice(0, 50) + '"' : '');
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const text = (this.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 40);
|
|
357
|
+
return (what || '<' + this.localName + '>') + (text ? ' (text: "' + text + '")' : '');
|
|
358
|
+
}`;
|
|
359
|
+
|
|
360
|
+
const CONTAINS = `function(hit) {
|
|
361
|
+
for (let n = hit; n; n = n.parentNode || n.host) if (n === this) return true;
|
|
362
|
+
if (this.labels) for (const label of this.labels) for (let n = hit; n; n = n.parentNode || n.host) if (n === label) return true;
|
|
363
|
+
return false;
|
|
364
|
+
}`;
|
|
365
|
+
|
|
366
|
+
const quadArea = (q) => Math.abs((q[0] * q[3] - q[1] * q[2]) + (q[2] * q[5] - q[3] * q[4]) + (q[4] * q[7] - q[5] * q[6]) + (q[6] * q[1] - q[7] * q[0])) / 2;
|
|
367
|
+
|
|
368
|
+
export function refId(ref) {
|
|
369
|
+
const m = /^e?(\d+)$/.exec(String(ref ?? '').trim());
|
|
370
|
+
if (!m) throw new BrowserError(`"${ref}" is not a ref: use the [ref=e…] of a snapshot line`);
|
|
371
|
+
return Number(m[1]);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const exceptionText = (d) => (d.exception?.description || d.exception?.value || d.text || 'error').toString().split('\n').slice(0, 6).join('\n');
|
|
375
|
+
|
|
376
|
+
// ---- The session
|
|
377
|
+
|
|
378
|
+
class BrowserSession {
|
|
379
|
+
constructor() {
|
|
380
|
+
this.cdp = null;
|
|
381
|
+
this.browser = null;
|
|
382
|
+
this.preferred = null; // {name, dir, own}: the instance to connect to again (see resolveBrowser)
|
|
383
|
+
this.lock = Promise.resolve();
|
|
384
|
+
this.signal = null;
|
|
385
|
+
this.reset();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
reset() {
|
|
389
|
+
this.tabs = new Map(); // targetId -> tab
|
|
390
|
+
this.byId = new Map(); // t3f9a -> tab (see relabel)
|
|
391
|
+
this.sessions = new Map(); // sessionId -> tab
|
|
392
|
+
this.nextTab = 1;
|
|
393
|
+
this.current = null;
|
|
394
|
+
this.notes = [];
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
get connected() { return Boolean(this.cdp && !this.cdp.closed); }
|
|
398
|
+
|
|
399
|
+
// One call at a time (the main agent and sub-agents share the browser), with that call's abort signal.
|
|
400
|
+
run(signal, fn) {
|
|
401
|
+
const next = this.lock.then(async () => {
|
|
402
|
+
this.signal = signal;
|
|
403
|
+
try { return await fn(); } finally { this.signal = null; }
|
|
404
|
+
});
|
|
405
|
+
this.lock = next.catch(() => {});
|
|
406
|
+
return next;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// `spec`: what the call asked for (see resolveBrowser), or an instance from browserInstances (/tabs). The user's
|
|
410
|
+
// browsers are reached through the broker (broker.js), whose connection outlives this process: the user allows
|
|
411
|
+
// it once, not again at every restart and in every session. Another browser asked for is found and connected to
|
|
412
|
+
// before the one there is let go: a request for one that is not there (chrome, when only Edge allows it) cost
|
|
413
|
+
// the connection to Edge, and the user had to allow it again.
|
|
414
|
+
async connect(spec, env, onWaiting) {
|
|
415
|
+
const given = spec && typeof spec === 'object' ? spec : null;
|
|
416
|
+
if (this.connected) {
|
|
417
|
+
const w = given ? '' : String(spec || '').trim().toLowerCase();
|
|
418
|
+
if (given ? sameBrowser(given, this.browser) : (!w || w === this.browser.name || (this.browser.dir && /[\\/]/.test(w) && samePath(w, this.browser.dir)))) return null;
|
|
419
|
+
}
|
|
420
|
+
const target = given || await resolveBrowser(spec, env, this.signal, this.preferred);
|
|
421
|
+
if (this.connected && sameBrowser(target, this.browser)) return null; // the same one, by another name
|
|
422
|
+
const options = { signal: this.signal, timeoutMs: browserLimits.connectMs, onWaiting: target.own ? null : () => onWaiting?.(target) };
|
|
423
|
+
const cdp = target.own ? await Cdp.connect(target.url, options) : await connectShared(target.url, options);
|
|
424
|
+
this.close(); // the one before, now that the new one is there
|
|
425
|
+
this.reset();
|
|
426
|
+
this.cdp = cdp;
|
|
427
|
+
this.browser = target;
|
|
428
|
+
// the one to go back to after a reconnect or a restart (App keeps it in its restart state)
|
|
429
|
+
this.preferred = target.dir ? { name: target.own ? 'own' : target.name, dir: target.dir, own: Boolean(target.own) } : null;
|
|
430
|
+
cdp.on((method, params, sessionId) => this.onEvent(method, params, sessionId));
|
|
431
|
+
await cdp.send('Target.setDiscoverTargets', { discover: true }, { signal: this.signal });
|
|
432
|
+
const { targetInfos } = await cdp.send('Target.getTargets', {}, { signal: this.signal });
|
|
433
|
+
for (const t of targetInfos) this.track(t);
|
|
434
|
+
if (target.own) {
|
|
435
|
+
// claude-pro's own browser: its tabs are all the agent's
|
|
436
|
+
for (const tab of this.tabs.values()) tab.ours = true;
|
|
437
|
+
const pages = [...this.tabs.values()];
|
|
438
|
+
if (pages.length === 1) await this.select(pages[0]);
|
|
439
|
+
}
|
|
440
|
+
return target;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
close() {
|
|
444
|
+
const cdp = this.cdp;
|
|
445
|
+
this.cdp = null;
|
|
446
|
+
this.browser = null;
|
|
447
|
+
this.reset();
|
|
448
|
+
try { cdp?.close(); } catch { /* already gone */ }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
track(info) {
|
|
452
|
+
if (info.type !== 'page') return null;
|
|
453
|
+
let tab = this.tabs.get(info.targetId);
|
|
454
|
+
if (!tab) {
|
|
455
|
+
const hex = /^[0-9a-f]{8,}$/i.test(info.targetId) ? info.targetId.toLowerCase() : null;
|
|
456
|
+
tab = { id: hex ? null : `t${this.nextTab++}`, hex, targetId: info.targetId, ours: false, sessionId: null, frameId: null, net: new Map(), lastNet: 0, loading: false, navigations: 0, dialog: null, dialogWaiters: new Set(), lines: null };
|
|
457
|
+
this.tabs.set(info.targetId, tab);
|
|
458
|
+
this.relabel();
|
|
459
|
+
}
|
|
460
|
+
tab.title = info.title || '';
|
|
461
|
+
if (info.url) tab.url = info.url;
|
|
462
|
+
return tab;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// A tab's id is "t" and the start of its own id in the browser (its targetId, which it keeps while it is open),
|
|
466
|
+
// 4 hex digits or as many more as it takes to tell it from the other open tabs. Numbers given in the order of a
|
|
467
|
+
// connection (t1, t2...) started again at every reconnect and restart of claude-pro, so that an id in the
|
|
468
|
+
// conversation (one the user picked with /tabs, say) could then be another tab, the one the agent would click in
|
|
469
|
+
// or close. These ids mean the same tab in every connection and every session (see tab).
|
|
470
|
+
relabel() {
|
|
471
|
+
const hexTabs = [...this.tabs.values()].filter((t) => t.hex);
|
|
472
|
+
for (const tab of hexTabs) {
|
|
473
|
+
let len = 4;
|
|
474
|
+
while (len < tab.hex.length && hexTabs.some((o) => o !== tab && o.hex.startsWith(tab.hex.slice(0, len)))) len++;
|
|
475
|
+
tab.id = `t${tab.hex.slice(0, len)}`;
|
|
476
|
+
}
|
|
477
|
+
this.byId = new Map([...this.tabs.values()].map((t) => [t.id, t]));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
onEvent(method, params, sessionId) {
|
|
481
|
+
if (method === 'Cdp.closed') {
|
|
482
|
+
if (!this.cdp) return; // closed by us
|
|
483
|
+
const label = this.browser?.label || 'the browser';
|
|
484
|
+
this.cdp = null;
|
|
485
|
+
this.browser = null;
|
|
486
|
+
this.reset();
|
|
487
|
+
this.notes.push(`The connection to ${label} was lost (${params.reason}): the next call connects again.`);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (method === 'Target.targetCreated' || method === 'Target.targetInfoChanged') {
|
|
491
|
+
const fresh = method === 'Target.targetCreated' && !this.tabs.has(params.targetInfo.targetId);
|
|
492
|
+
const tab = this.track(params.targetInfo);
|
|
493
|
+
if (tab && fresh) {
|
|
494
|
+
const opener = params.targetInfo.openerId && this.tabs.get(params.targetInfo.openerId);
|
|
495
|
+
if (opener?.ours || (opener && opener === this.current)) {
|
|
496
|
+
tab.ours = true;
|
|
497
|
+
this.notes.push(`The page opened a new tab ${tab.id} (${safeUrl(tab.url)}): switch to it to work there.`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (method === 'Target.targetDestroyed') {
|
|
503
|
+
const tab = this.tabs.get(params.targetId);
|
|
504
|
+
if (!tab) return;
|
|
505
|
+
this.tabs.delete(params.targetId);
|
|
506
|
+
this.relabel();
|
|
507
|
+
if (tab.sessionId) this.sessions.delete(tab.sessionId);
|
|
508
|
+
if (this.current === tab) {
|
|
509
|
+
this.current = null;
|
|
510
|
+
this.notes.push(`Tab ${tab.id} was closed.`);
|
|
511
|
+
}
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
if (method === 'Target.detachedFromTarget') {
|
|
515
|
+
const tab = this.sessions.get(params.sessionId);
|
|
516
|
+
if (tab) { this.sessions.delete(params.sessionId); tab.sessionId = null; }
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const tab = sessionId && this.sessions.get(sessionId);
|
|
520
|
+
if (!tab) return;
|
|
521
|
+
const now = Date.now();
|
|
522
|
+
switch (method) {
|
|
523
|
+
case 'Network.requestWillBeSent': tab.net.set(params.requestId, now); tab.lastNet = now; break;
|
|
524
|
+
case 'Network.loadingFinished':
|
|
525
|
+
case 'Network.loadingFailed': tab.net.delete(params.requestId); tab.lastNet = now; break;
|
|
526
|
+
case 'Page.frameStartedLoading': if (params.frameId === tab.frameId) tab.loading = true; break;
|
|
527
|
+
case 'Page.frameStoppedLoading': if (params.frameId === tab.frameId) tab.loading = false; break;
|
|
528
|
+
case 'Page.loadEventFired': tab.loading = false; break;
|
|
529
|
+
case 'Page.frameNavigated':
|
|
530
|
+
if (!params.frame.parentId) { tab.frameId = params.frame.id; tab.url = params.frame.url; tab.navigations++; }
|
|
531
|
+
break;
|
|
532
|
+
case 'Page.navigatedWithinDocument': if (params.frameId === tab.frameId) tab.url = params.url; break;
|
|
533
|
+
case 'Page.javascriptDialogOpening':
|
|
534
|
+
tab.dialog = { type: params.type, message: params.message, defaultPrompt: params.defaultPrompt };
|
|
535
|
+
for (const w of [...tab.dialogWaiters]) w();
|
|
536
|
+
break;
|
|
537
|
+
case 'Page.javascriptDialogClosed': tab.dialog = null; break;
|
|
538
|
+
default: break;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
takeNotes() {
|
|
543
|
+
const notes = this.notes;
|
|
544
|
+
this.notes = [];
|
|
545
|
+
return notes;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
send(tab, method, params = {}, { timeoutMs = browserLimits.commandMs } = {}) {
|
|
549
|
+
if (!this.connected) return Promise.reject(new BrowserError('the browser connection is closed'));
|
|
550
|
+
return this.cdp.send(method, params, { sessionId: tab?.sessionId || undefined, signal: this.signal, timeoutMs });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// A command's reply, or null when the page opens an alert, confirm or prompt first: the page is then stopped in
|
|
554
|
+
// that dialog, and the reply (of the click that opened it, say) only comes once it is answered.
|
|
555
|
+
untilDialog(tab, promise) {
|
|
556
|
+
promise.catch(() => {});
|
|
557
|
+
if (tab.dialog) return Promise.resolve(null);
|
|
558
|
+
return new Promise((resolve, reject) => {
|
|
559
|
+
const onDialog = () => resolve(null);
|
|
560
|
+
tab.dialogWaiters.add(onDialog);
|
|
561
|
+
promise.then(resolve, reject).finally(() => tab.dialogWaiters.delete(onDialog));
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
input(tab, method, params) {
|
|
566
|
+
if (tab.dialog) return Promise.resolve(null);
|
|
567
|
+
return this.untilDialog(tab, this.send(tab, method, params));
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// A tab by its id. One shown earlier may be longer or shorter than the tab's id now (another tab with the same
|
|
571
|
+
// start was opened or closed meanwhile): any start of a tab's own id that only one open tab has is that tab's.
|
|
572
|
+
tab(id) {
|
|
573
|
+
if (id) {
|
|
574
|
+
const want = String(id).trim().toLowerCase();
|
|
575
|
+
const exact = this.byId.get(want);
|
|
576
|
+
if (exact) return exact;
|
|
577
|
+
const start = /^t([0-9a-f]{4,})$/.exec(want)?.[1];
|
|
578
|
+
const hits = start ? [...this.tabs.values()].filter((t) => t.hex?.startsWith(start)) : [];
|
|
579
|
+
if (hits.length === 1) return hits[0];
|
|
580
|
+
if (hits.length > 1) throw new BrowserError(`${id} could be any of ${hits.length} tabs now: ${hits.map((t) => `${t.id} ${String(t.title || '').slice(0, 40)}`).join('; ')}; pass the longer id`);
|
|
581
|
+
throw new BrowserError(`no tab ${id} (it was closed, or the id is from another browser): switch by words of its title or address, or list them with tabs`);
|
|
582
|
+
}
|
|
583
|
+
if (!this.current) throw new BrowserError('no tab is selected: switch (tab: its id, or words of its title or address) to the one the user means, or open (url) a new one');
|
|
584
|
+
return this.current;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async attach(tab) {
|
|
588
|
+
if (tab.sessionId) return;
|
|
589
|
+
const { sessionId } = await this.cdp.send('Target.attachToTarget', { targetId: tab.targetId, flatten: true }, { signal: this.signal, timeoutMs: browserLimits.commandMs });
|
|
590
|
+
tab.sessionId = sessionId;
|
|
591
|
+
this.sessions.set(sessionId, tab);
|
|
592
|
+
await Promise.all([
|
|
593
|
+
this.send(tab, 'Page.enable'),
|
|
594
|
+
this.send(tab, 'Network.enable'),
|
|
595
|
+
// the page behaves as if its window had the focus: the user is typing in the terminal
|
|
596
|
+
this.send(tab, 'Emulation.setFocusEmulationEnabled', { enabled: true }).catch(() => {}),
|
|
597
|
+
]);
|
|
598
|
+
try {
|
|
599
|
+
const { frameTree } = await this.send(tab, 'Page.getFrameTree');
|
|
600
|
+
tab.frameId = frameTree.frame.id;
|
|
601
|
+
tab.url = frameTree.frame.url;
|
|
602
|
+
} catch { /* known from the target */ }
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Make `tab` the one actions go to: attached, in front (a background tab may be asleep or throttled) and awake.
|
|
606
|
+
async select(tab) {
|
|
607
|
+
await this.attach(tab);
|
|
608
|
+
await this.cdp.send('Target.activateTarget', { targetId: tab.targetId }, { signal: this.signal, timeoutMs: 5000 }).catch(() => {});
|
|
609
|
+
await this.send(tab, 'Page.setWebLifecycleState', { state: 'active' }, { timeoutMs: 5000 }).catch(() => {});
|
|
610
|
+
this.current = tab;
|
|
611
|
+
if (tab.dialog) return; // Page.enable reports a dialog that was already open: the page runs nothing until it is answered
|
|
612
|
+
try {
|
|
613
|
+
await this.send(tab, 'Runtime.evaluate', { expression: '1', returnByValue: true }, { timeoutMs: 5000 });
|
|
614
|
+
} catch (e) {
|
|
615
|
+
if (this.signal?.aborted) throw abortError();
|
|
616
|
+
throw new BrowserError(`${tab.id} does not respond (${e.message}): it may be asleep or busy; ask the user to click on it, then try again`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
async open(url) {
|
|
621
|
+
const { targetId } = await this.cdp.send('Target.createTarget', { url: 'about:blank' }, { signal: this.signal });
|
|
622
|
+
const tab = this.tabs.get(targetId) || this.track({ targetId, type: 'page', title: '', url: 'about:blank' });
|
|
623
|
+
tab.ours = true;
|
|
624
|
+
await this.select(tab);
|
|
625
|
+
if (url) await this.navigate(tab, url);
|
|
626
|
+
return tab;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async navigate(tab, url) {
|
|
630
|
+
let target;
|
|
631
|
+
try { target = new URL(url).href; } catch { target = /^[\w-]+(\.[\w-]+)+/.test(url) ? `https://${url}` : url; }
|
|
632
|
+
const r = await this.send(tab, 'Page.navigate', { url: target }, { timeoutMs: browserLimits.navigationMs });
|
|
633
|
+
if (r.errorText) throw new BrowserError(`cannot open ${target}: ${r.errorText}`);
|
|
634
|
+
tab.loading = Boolean(r.loaderId); // a navigation inside the document has none
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
async history(tab, step) {
|
|
638
|
+
const { currentIndex, entries } = await this.send(tab, 'Page.getNavigationHistory');
|
|
639
|
+
const entry = entries[currentIndex + step];
|
|
640
|
+
if (!entry) throw new BrowserError(`there is no page to go ${step < 0 ? 'back' : 'forward'} to`);
|
|
641
|
+
tab.loading = true;
|
|
642
|
+
await this.send(tab, 'Page.navigateToHistoryEntry', { entryId: entry.id });
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async closeTab(tab, force) {
|
|
646
|
+
if (!tab.ours && !force) throw new BrowserError(`${tab.id} is one of the user's tabs, not one you opened: close it only when the user asks for it, with force: true`);
|
|
647
|
+
await this.cdp.send('Target.closeTarget', { targetId: tab.targetId }, { signal: this.signal });
|
|
648
|
+
this.tabs.delete(tab.targetId);
|
|
649
|
+
this.relabel();
|
|
650
|
+
if (tab.sessionId) this.sessions.delete(tab.sessionId);
|
|
651
|
+
if (this.current === tab) this.current = null;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// Wait until what an action started is done: a navigation's load, else a quiet network (requests running for
|
|
655
|
+
// more than 2 s, a long poll or a stream, do not count).
|
|
656
|
+
async settle(tab) {
|
|
657
|
+
const start = Date.now();
|
|
658
|
+
await sleep(150, this.signal);
|
|
659
|
+
for (;;) {
|
|
660
|
+
if (tab.dialog || !this.connected) return;
|
|
661
|
+
const now = Date.now();
|
|
662
|
+
for (const [id, t] of tab.net) if (now - t > 60_000) tab.net.delete(id);
|
|
663
|
+
const busy = [...tab.net.values()].some((t) => now - t < 2000);
|
|
664
|
+
if (!tab.loading && !busy && now - tab.lastNet >= browserLimits.quietMs) return;
|
|
665
|
+
if (now - start >= (tab.loading ? browserLimits.navigationMs : browserLimits.settleMs)) return;
|
|
666
|
+
await sleep(100, this.signal);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// The page's accessibility trees, for snapshotLines (see snapshot.js): the main frame's, and those of the iframes
|
|
671
|
+
// that run in the page's process (a cross-site one is 'remote').
|
|
672
|
+
async trees(tab) {
|
|
673
|
+
if (tab.dialog) throw new BrowserError(`a ${tab.dialog.type} dialog is open (${JSON.stringify(tab.dialog.message)}): answer it with dialog (accept, text) first`);
|
|
674
|
+
const { nodes } = await this.send(tab, 'Accessibility.getFullAXTree', {}, { timeoutMs: 20_000 });
|
|
675
|
+
const frames = new Map();
|
|
676
|
+
try {
|
|
677
|
+
const { frameTree } = await this.send(tab, 'Page.getFrameTree');
|
|
678
|
+
const walk = async (ft) => {
|
|
679
|
+
for (const child of ft.childFrames || []) {
|
|
680
|
+
try {
|
|
681
|
+
const { backendNodeId } = await this.send(tab, 'DOM.getFrameOwner', { frameId: child.frame.id });
|
|
682
|
+
try {
|
|
683
|
+
const t = await this.send(tab, 'Accessibility.getFullAXTree', { frameId: child.frame.id }, { timeoutMs: 10_000 });
|
|
684
|
+
frames.set(backendNodeId, t.nodes?.length ? t.nodes : 'remote');
|
|
685
|
+
} catch { frames.set(backendNodeId, 'remote'); }
|
|
686
|
+
} catch { /* a frame without an owner element here */ }
|
|
687
|
+
await walk(child);
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
await walk(frameTree);
|
|
691
|
+
} catch { /* the main tree is enough */ }
|
|
692
|
+
return { main: nodes, frames, baseUrl: tab.url };
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
async objectId(tab, backendNodeId, ref) {
|
|
696
|
+
try {
|
|
697
|
+
const { object } = await this.send(tab, 'DOM.resolveNode', { backendNodeId, objectGroup: 'claude-pro' });
|
|
698
|
+
return object.objectId;
|
|
699
|
+
} catch (e) {
|
|
700
|
+
throw this.gone(ref || `e${backendNodeId}`, e);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
gone(ref, e) {
|
|
705
|
+
if (e?.name === 'AbortError') return e;
|
|
706
|
+
const m = e?.message || '';
|
|
707
|
+
if (/layout object/i.test(m)) return new BrowserError(`${ref} is not shown on the page (it has no box): use another element, or scroll or open what contains it`);
|
|
708
|
+
return /No node|not found|detached|Could not compute|does not belong|Cannot find/i.test(m)
|
|
709
|
+
? new BrowserError(`${ref} is no longer on the page (it changed): take a new snapshot`)
|
|
710
|
+
: e;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async callOn(tab, ref, fn, args = []) {
|
|
714
|
+
const objectId = await this.objectId(tab, refId(ref), ref);
|
|
715
|
+
const r = await this.send(tab, 'Runtime.callFunctionOn', { objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise: true, userGesture: true }, { timeoutMs: browserLimits.evalMs });
|
|
716
|
+
if (r.exceptionDetails) throw new BrowserError(`the script threw: ${exceptionText(r.exceptionDetails)}`);
|
|
717
|
+
return r.result?.value;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// Where to click an element: scrolled into view, the middle of its first box.
|
|
721
|
+
async point(tab, ref) {
|
|
722
|
+
const backendNodeId = refId(ref);
|
|
723
|
+
let quads;
|
|
724
|
+
try {
|
|
725
|
+
await this.send(tab, 'DOM.scrollIntoViewIfNeeded', { backendNodeId });
|
|
726
|
+
({ quads } = await this.send(tab, 'DOM.getContentQuads', { backendNodeId }));
|
|
727
|
+
} catch (e) { throw this.gone(ref, e); }
|
|
728
|
+
const q = quads.find((x) => quadArea(x) > 1);
|
|
729
|
+
if (!q) throw new BrowserError(`${ref} takes no space on the page (hidden or collapsed)`);
|
|
730
|
+
return { backendNodeId, x: (q[0] + q[2] + q[4] + q[6]) / 4, y: (q[1] + q[3] + q[5] + q[7]) / 4 };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// What is on top at (x, y) when it is not the element (or inside it): a dialog, a banner, a cookie notice.
|
|
734
|
+
async coveredBy(tab, backendNodeId, x, y) {
|
|
735
|
+
let hit;
|
|
736
|
+
try {
|
|
737
|
+
// (x, y) is in the window, getNodeForLocation takes the document's coordinates: the page's scroll added
|
|
738
|
+
const { cssLayoutViewport: vp } = await this.send(tab, 'Page.getLayoutMetrics');
|
|
739
|
+
// (ignorePointerEventsNone would hit-test the see-through layers a click goes through: an editor's placeholder)
|
|
740
|
+
hit = await this.send(tab, 'DOM.getNodeForLocation', { x: Math.round(x + vp.pageX), y: Math.round(y + vp.pageY), includeUserAgentShadowDOM: false, ignorePointerEventsNone: false });
|
|
741
|
+
} catch { return null; } // cannot tell: click
|
|
742
|
+
if (!hit?.backendNodeId || hit.backendNodeId === backendNodeId) return null;
|
|
743
|
+
try {
|
|
744
|
+
const [own, other] = await Promise.all([this.objectId(tab, backendNodeId), this.objectId(tab, hit.backendNodeId)]);
|
|
745
|
+
const r = await this.send(tab, 'Runtime.callFunctionOn', { objectId: own, functionDeclaration: CONTAINS, arguments: [{ objectId: other }], returnByValue: true });
|
|
746
|
+
if (r.result?.value === true) return null;
|
|
747
|
+
} catch { /* in another frame: covered */ }
|
|
748
|
+
try {
|
|
749
|
+
const objectId = await this.objectId(tab, hit.backendNodeId);
|
|
750
|
+
const r = await this.send(tab, 'Runtime.callFunctionOn', { objectId, functionDeclaration: COVER_LABEL, returnByValue: true });
|
|
751
|
+
return r.result?.value || 'another element';
|
|
752
|
+
} catch { return 'another element'; }
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
async mouse(tab, x, y, { button = 'left', clickCount = 1 } = {}) {
|
|
756
|
+
const buttons = { left: 1, right: 2, middle: 4 }[button] ?? 1;
|
|
757
|
+
await this.input(tab, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
|
|
758
|
+
for (let i = 1; i <= clickCount; i++) {
|
|
759
|
+
await this.input(tab, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, buttons, clickCount: i });
|
|
760
|
+
await this.input(tab, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, buttons: 0, clickCount: i });
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
async click(tab, { ref, x, y, button, double, force }) {
|
|
765
|
+
if (ref === undefined || ref === null || ref === '') {
|
|
766
|
+
if (typeof x !== 'number' || typeof y !== 'number') throw new BrowserError('click needs a ref, or x and y (CSS pixels in the viewport)');
|
|
767
|
+
await this.mouse(tab, x, y, { button, clickCount: double ? 2 : 1 });
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
let p = await this.point(tab, ref);
|
|
771
|
+
if (!force) {
|
|
772
|
+
let cover = await this.coveredBy(tab, p.backendNodeId, p.x, p.y);
|
|
773
|
+
// Scrolled to the edge of the window, an element may be under a sticky header or footer: try it in the
|
|
774
|
+
// middle, then at the other edges (as Playwright does).
|
|
775
|
+
for (const block of ['center', 'end', 'start']) {
|
|
776
|
+
if (!cover) break;
|
|
777
|
+
await this.callOn(tab, ref, 'function(block) { this.scrollIntoView({ block, inline: "nearest", behavior: "instant" }); }', [block]);
|
|
778
|
+
p = await this.point(tab, ref);
|
|
779
|
+
cover = await this.coveredBy(tab, p.backendNodeId, p.x, p.y);
|
|
780
|
+
}
|
|
781
|
+
if (cover) throw new BrowserError(`${ref} is covered by ${cover}: close what covers it (a dialog, a banner, a menu), or pass force: true to click that point anyway`);
|
|
782
|
+
}
|
|
783
|
+
await this.mouse(tab, p.x, p.y, { button, clickCount: double ? 2 : 1 });
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async hover(tab, ref) {
|
|
787
|
+
const p = await this.point(tab, ref);
|
|
788
|
+
await this.input(tab, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: p.x, y: p.y, button: 'none' });
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
async press(tab, combo) {
|
|
792
|
+
const parts = String(combo).split('+');
|
|
793
|
+
const last = parts.pop();
|
|
794
|
+
const name = last === '' && parts.length ? '+' : last; // "Control++"
|
|
795
|
+
let mask = 0;
|
|
796
|
+
const down = [];
|
|
797
|
+
for (const raw of parts.filter(Boolean)) {
|
|
798
|
+
const m = raw.toLowerCase() === 'mod' ? (process.platform === 'darwin' ? MODIFIERS.meta : MODIFIERS.control) : MODIFIERS[raw.toLowerCase()];
|
|
799
|
+
if (!m) throw new BrowserError(`unknown modifier "${raw}" in "${combo}": use Control, Shift, Alt, Meta or Mod`);
|
|
800
|
+
mask |= m[0];
|
|
801
|
+
down.push(m);
|
|
802
|
+
await this.input(tab, 'Input.dispatchKeyEvent', { type: 'rawKeyDown', key: m[1], code: m[2], windowsVirtualKeyCode: m[3], modifiers: mask });
|
|
803
|
+
}
|
|
804
|
+
const k = keyEvent(name);
|
|
805
|
+
const shifted = mask & 8;
|
|
806
|
+
const text = mask & ~8 ? undefined : k.text && shifted && k.text.length === 1 ? k.text.toUpperCase() : k.text;
|
|
807
|
+
const key = shifted && k.key.length === 1 ? k.key.toUpperCase() : k.key;
|
|
808
|
+
const commands = process.platform === 'darwin' && mask & 4 && MAC_COMMANDS[k.key.toLowerCase()] ? [MAC_COMMANDS[k.key.toLowerCase()]] : undefined;
|
|
809
|
+
const base = { key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, modifiers: mask };
|
|
810
|
+
await this.input(tab, 'Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', ...base, ...(text ? { text, unmodifiedText: text } : {}), ...(commands ? { commands } : {}) });
|
|
811
|
+
await this.input(tab, 'Input.dispatchKeyEvent', { type: 'keyUp', ...base });
|
|
812
|
+
for (const m of down.reverse()) {
|
|
813
|
+
mask &= ~m[0];
|
|
814
|
+
await this.input(tab, 'Input.dispatchKeyEvent', { type: 'keyUp', key: m[1], code: m[2], windowsVirtualKeyCode: m[3], modifiers: mask });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// Typing goes in as the browser's own text input (what an input method sends): every script and editor sees it
|
|
819
|
+
// as typed, Chinese included.
|
|
820
|
+
async type(tab, { ref, text = '', clear, submit, force }) {
|
|
821
|
+
if (ref) await this.click(tab, { ref, force });
|
|
822
|
+
if (clear) {
|
|
823
|
+
const field = ref ? await this.callOn(tab, ref, 'function() { if (typeof this.select === "function" && "value" in this) { this.select(); return true; } return false; }') : false;
|
|
824
|
+
if (!field) await this.press(tab, 'Mod+a');
|
|
825
|
+
if (!text) await this.press(tab, 'Backspace');
|
|
826
|
+
}
|
|
827
|
+
if (text && !tab.dialog) await this.input(tab, 'Input.insertText', { text });
|
|
828
|
+
if (submit && !tab.dialog) await this.press(tab, 'Enter');
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
async scroll(tab, { ref, dy, dx }) {
|
|
832
|
+
if (ref && dy === undefined && dx === undefined) { await this.point(tab, ref); return; }
|
|
833
|
+
const { cssVisualViewport: vp } = await this.send(tab, 'Page.getLayoutMetrics');
|
|
834
|
+
let x = vp.clientWidth / 2;
|
|
835
|
+
let y = vp.clientHeight / 2;
|
|
836
|
+
if (ref) ({ x, y } = await this.point(tab, ref)); // scroll inside that element (a list, a panel)
|
|
837
|
+
await this.input(tab, 'Input.dispatchMouseEvent', { type: 'mouseWheel', x, y, deltaX: dx || 0, deltaY: dy ?? Math.round(vp.clientHeight * 0.8) });
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
async selectOption(tab, ref, value) {
|
|
841
|
+
const r = await this.callOn(tab, ref, `function(wanted) {
|
|
842
|
+
if (this.tagName !== 'SELECT') return { error: 'not a <select>: click it and then the option' };
|
|
843
|
+
const options = [...this.options];
|
|
844
|
+
const o = options.find((x) => x.value === wanted) || options.find((x) => x.label.trim() === wanted || x.textContent.trim() === wanted);
|
|
845
|
+
if (!o) return { error: 'no option ' + JSON.stringify(wanted) + '; the options: ' + options.map((x) => x.label.trim()).join(', ') };
|
|
846
|
+
this.value = o.value;
|
|
847
|
+
this.dispatchEvent(new Event('input', { bubbles: true }));
|
|
848
|
+
this.dispatchEvent(new Event('change', { bubbles: true }));
|
|
849
|
+
return { label: o.label.trim() };
|
|
850
|
+
}`, [String(value ?? '')]);
|
|
851
|
+
if (r?.error) throw new BrowserError(`${ref}: ${r.error}`);
|
|
852
|
+
return r?.label;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
async upload(tab, ref, files) {
|
|
856
|
+
await this.send(tab, 'DOM.setFileInputFiles', { files, backendNodeId: refId(ref) }).catch((e) => { throw this.gone(ref, e); });
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async evaluate(tab, script, ref) {
|
|
860
|
+
const isFn = /^\s*(async\s+)?(function\b|\([^)]*\)\s*=>|[\w$]+\s*=>)/.test(script);
|
|
861
|
+
let r;
|
|
862
|
+
if (ref) {
|
|
863
|
+
const objectId = await this.objectId(tab, refId(ref), ref);
|
|
864
|
+
const fn = isFn ? `function() { return (${script})(this); }` : `function() { return (${script}); }`;
|
|
865
|
+
r = await this.untilDialog(tab, this.send(tab, 'Runtime.callFunctionOn', { objectId, functionDeclaration: fn, returnByValue: true, awaitPromise: true, userGesture: true }, { timeoutMs: browserLimits.evalMs }));
|
|
866
|
+
} else {
|
|
867
|
+
r = await this.untilDialog(tab, this.send(tab, 'Runtime.evaluate', { expression: isFn ? `(${script})()` : script, returnByValue: true, awaitPromise: true, userGesture: true, replMode: !isFn }, { timeoutMs: browserLimits.evalMs }));
|
|
868
|
+
}
|
|
869
|
+
if (!r) return `(no value yet: the script opened ${tab.dialog?.type === 'alert' ? 'an' : 'a'} ${tab.dialog?.type || ''} dialog, ${JSON.stringify(tab.dialog?.message ?? '')}; answer it with dialog)`;
|
|
870
|
+
if (r.exceptionDetails) throw new BrowserError(`the script threw: ${exceptionText(r.exceptionDetails)}`);
|
|
871
|
+
const v = r.result;
|
|
872
|
+
if (v?.value !== undefined) return typeof v.value === 'string' ? v.value : JSON.stringify(v.value, null, 1);
|
|
873
|
+
return v?.description ?? String(v?.type ?? 'undefined');
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
async text(tab, ref) {
|
|
877
|
+
if (ref) return String(await this.callOn(tab, ref, 'function() { return this.innerText ?? this.textContent ?? ""; }') ?? '');
|
|
878
|
+
const r = await this.send(tab, 'Runtime.evaluate', { expression: 'document.body ? document.body.innerText : ""', returnByValue: true }, { timeoutMs: browserLimits.evalMs });
|
|
879
|
+
return String(r.result?.value ?? '');
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
async waitFor(tab, { text, gone, ms, timeout }) {
|
|
883
|
+
if (!text) {
|
|
884
|
+
await sleep(Math.min(Math.max(Number(ms) || 1000, 0), browserLimits.waitMaxMs), this.signal);
|
|
885
|
+
return `waited ${ms || 1000} ms`;
|
|
886
|
+
}
|
|
887
|
+
const limit = Math.min(Number(timeout) || browserLimits.waitMs, browserLimits.waitMaxMs);
|
|
888
|
+
const until = Date.now() + limit;
|
|
889
|
+
const wanted = String(text).toLowerCase();
|
|
890
|
+
for (;;) {
|
|
891
|
+
const body = (await this.text(tab).catch((e) => { if (e?.name === 'AbortError') throw e; return ''; })).toLowerCase();
|
|
892
|
+
if (body.includes(wanted) !== Boolean(gone)) return `${JSON.stringify(text)} ${gone ? 'is gone' : 'is on the page'}`;
|
|
893
|
+
if (tab.dialog) throw new BrowserError(`a ${tab.dialog.type} dialog opened (${JSON.stringify(tab.dialog.message)})`);
|
|
894
|
+
if (Date.now() >= until) throw new BrowserError(`${JSON.stringify(text)} ${gone ? 'is still on the page' : 'did not appear'} after ${limit / 1000} s`);
|
|
895
|
+
await sleep(300, this.signal);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
async screenshot(tab, { ref, full }) {
|
|
900
|
+
const params = { format: 'jpeg', quality: 80 };
|
|
901
|
+
if (ref) {
|
|
902
|
+
const p = await this.point(tab, ref);
|
|
903
|
+
const { quads } = await this.send(tab, 'DOM.getContentQuads', { backendNodeId: p.backendNodeId });
|
|
904
|
+
const xs = quads.flatMap((q) => [q[0], q[2], q[4], q[6]]);
|
|
905
|
+
const ys = quads.flatMap((q) => [q[1], q[3], q[5], q[7]]);
|
|
906
|
+
const { cssVisualViewport: vp } = await this.send(tab, 'Page.getLayoutMetrics');
|
|
907
|
+
const left = Math.min(...xs);
|
|
908
|
+
const top = Math.min(...ys);
|
|
909
|
+
params.clip = { x: left + vp.pageX, y: top + vp.pageY, width: Math.max(1, Math.max(...xs) - left), height: Math.max(1, Math.max(...ys) - top), scale: 1 };
|
|
910
|
+
params.captureBeyondViewport = true;
|
|
911
|
+
} else if (full) {
|
|
912
|
+
const { cssContentSize: size } = await this.send(tab, 'Page.getLayoutMetrics');
|
|
913
|
+
params.clip = { x: 0, y: 0, width: size.width, height: Math.min(size.height, 10_000), scale: 1 };
|
|
914
|
+
params.captureBeyondViewport = true;
|
|
915
|
+
}
|
|
916
|
+
await this.cdp.send('Target.activateTarget', { targetId: tab.targetId }, { signal: this.signal, timeoutMs: 5000 }).catch(() => {});
|
|
917
|
+
const { data } = await this.send(tab, 'Page.captureScreenshot', params, { timeoutMs: 30_000 });
|
|
918
|
+
return data;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
async dialog(tab, { accept = true, text }) {
|
|
922
|
+
if (!tab.dialog) throw new BrowserError('no dialog is open');
|
|
923
|
+
await this.send(tab, 'Page.handleJavaScriptDialog', { accept: accept !== false, ...(text !== undefined ? { promptText: String(text) } : {}) });
|
|
924
|
+
tab.dialog = null;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async release(tab) {
|
|
928
|
+
if (tab?.sessionId) await this.send(tab, 'Runtime.releaseObjectGroup', { objectGroup: 'claude-pro' }, { timeoutMs: 3000 }).catch(() => {});
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
export const safeUrl = (u) => {
|
|
933
|
+
try {
|
|
934
|
+
const x = new URL(u);
|
|
935
|
+
return x.protocol === 'http:' || x.protocol === 'https:' ? `${x.origin}${x.pathname}` : u;
|
|
936
|
+
} catch { return u; }
|
|
937
|
+
};
|
|
938
|
+
|
|
939
|
+
export const browserSession = new BrowserSession();
|
|
940
|
+
|
|
941
|
+
// For a process that ends by itself (claude-pro -p): an open connection would keep it alive, and so would the
|
|
942
|
+
// pipe of WebFetch's headless browser (render.js).
|
|
943
|
+
export function closeBrowser() {
|
|
944
|
+
browserSession.close();
|
|
945
|
+
closeRenderer();
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
export { CdpError };
|