@yanzc/claude-pro 0.9.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.
Files changed (55) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +79 -13
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +143 -143
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +5 -61
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +26 -10
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +92 -19
  38. package/src/tools/index.js +6 -0
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +185 -104
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/paths.js +15 -17
  54. package/src/utils/shell.js +66 -11
  55. package/.env.example +0 -29
@@ -0,0 +1,242 @@
1
+ // Pages for WebFetch that a plain request does not get: a page that needs JavaScript to show its text, or a server
2
+ // that refuses what is not a browser (Akamai's "Access Denied"). They are opened in a headless Chrome (or Edge), one
3
+ // per claude-pro process, started with the first such page and closed after a minute without one. It talks over a
4
+ // pipe (--remote-debugging-pipe), not a port: no other program can drive it, and it exits by itself when this
5
+ // process ends, however that happens (two seconds after a hard kill, measured). Its profile is a fresh one in the
6
+ // temp directory: no cookies or logins of the user's.
7
+ // A check that wants a person (Cloudflare's "Just a moment...", a CAPTCHA) is not got past: such a page comes back
8
+ // with `challenge` set, for the caller to send the model to the Browser tool, where the user can pass it.
9
+
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { spawn } from 'node:child_process';
14
+ import { Cdp, abortError } from './cdp.js';
15
+ import { browserExecutables } from './session.js';
16
+ import { killTree, killTreeSync, processAlive } from '../utils/shell.js';
17
+
18
+ export const renderLimits = {
19
+ startMs: 20_000,
20
+ navigationMs: 25_000, // until the server answers
21
+ loadMs: 15_000, // then until the load event, at most (some pages never stop loading)
22
+ challengeMs: 15_000, // a browser check that runs by itself (a script that sets a cookie and reloads)
23
+ settleMs: 5_000, // then until the network is quiet, for a page that builds itself with scripts
24
+ idleMs: 60_000, // the browser closes after this long without a page
25
+ };
26
+
27
+ const PROFILE_PREFIX = 'claude-pro-render-';
28
+ // The title of a check page: one that goes on to the page by itself, or that wants a person.
29
+ export const CHECK_TITLE = /^\s*(?:just a moment|attention required|checking (?:your|if the site connection is secure)|please wait|one more step|ddos-guard)/i;
30
+ // What the page shows, and whether it is a check page (Cloudflare's, or one with the same title).
31
+ const PAGE_STATE = `JSON.stringify({
32
+ title: document.title,
33
+ check: ${CHECK_TITLE}.test(document.title)
34
+ || !!document.querySelector('#challenge-form, #challenge-running, #cf-challenge-running, script[src*="/cdn-cgi/challenge-platform/"], iframe[src*="challenges.cloudflare.com"]'),
35
+ })`;
36
+
37
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
38
+ if (signal?.aborted) return reject(abortError());
39
+ const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
40
+ const onAbort = () => { clearTimeout(t); reject(abortError()); };
41
+ signal?.addEventListener('abort', onAbort, { once: true });
42
+ });
43
+
44
+ // Until `done()` or `ms` have passed (not an error: what the page shows then is taken).
45
+ async function until(done, ms, signal) {
46
+ for (const end = Date.now() + ms; !done() && Date.now() < end;) await sleep(100, signal);
47
+ }
48
+
49
+ // The DevTools protocol over the browser's pipe, as the WebSocket Cdp expects: messages separated by NUL bytes,
50
+ // fd 3 to the browser and fd 4 from it.
51
+ class PipeSocket {
52
+ constructor(input, output) {
53
+ this.input = input;
54
+ this.onmessage = null;
55
+ this.onclose = null;
56
+ this.onerror = null;
57
+ let buf = '';
58
+ output.setEncoding('utf8');
59
+ output.on('data', (d) => {
60
+ buf += d;
61
+ for (let i = buf.indexOf('\0'); i >= 0; i = buf.indexOf('\0')) {
62
+ const msg = buf.slice(0, i);
63
+ buf = buf.slice(i + 1);
64
+ this.onmessage?.({ data: msg });
65
+ }
66
+ });
67
+ const closed = () => { if (this.closed) return; this.closed = true; this.onclose?.({}); };
68
+ output.on('close', closed);
69
+ output.on('error', closed);
70
+ input.on('error', closed);
71
+ }
72
+
73
+ send(text) { this.input.write(`${text}\0`); }
74
+ close() { try { this.input.end(); } catch { /* gone */ } }
75
+ }
76
+
77
+ // A profile removed; while a file of it is still held (a browser whose end Windows holds up, below), tried again
78
+ // every 15 s for two minutes, then left to the next browser's sweep.
79
+ function removeDir(dir, tries = 8) {
80
+ fs.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }, (err) => {
81
+ if (err && tries > 1) setTimeout(() => removeDir(dir, tries - 1), 15_000).unref();
82
+ });
83
+ }
84
+
85
+ // Profiles left behind: those of processes that are gone (one killed outright, or one that exited before its
86
+ // browser had let go of the files), and this process's own earlier ones (its browser is not running now).
87
+ function sweepProfiles() {
88
+ let names = [];
89
+ try { names = fs.readdirSync(os.tmpdir()); } catch { return; }
90
+ for (const name of names) {
91
+ const pid = Number(new RegExp(`^${PROFILE_PREFIX}(\\d+)-`).exec(name)?.[1]);
92
+ if (!pid || (pid !== process.pid && processAlive(pid))) continue;
93
+ removeDir(path.join(os.tmpdir(), name));
94
+ }
95
+ }
96
+
97
+ let browser = null; // {child, cdp, dir, ua, meta, busy, idleTimer}
98
+ let starting = null;
99
+ let exitHook = false;
100
+
101
+ async function launch(signal) {
102
+ const exe = browserExecutables().find((p) => p && fs.existsSync(p));
103
+ if (!exe) throw new Error('no Chrome or Edge is installed to open it in');
104
+ sweepProfiles();
105
+ if (!exitHook) {
106
+ // A process that exits on purpose (a restart, the end of a -p run) ends it at once, crash reporter included
107
+ // (see closeRenderer). Its profile goes with the next browser's sweep.
108
+ exitHook = true;
109
+ process.once('exit', () => { if (browser) killTreeSync(browser.child); });
110
+ }
111
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${PROFILE_PREFIX}${process.pid}-`));
112
+ const child = spawn(exe, [
113
+ '--headless=new', '--remote-debugging-pipe', `--user-data-dir=${dir}`, '--no-first-run', '--no-default-browser-check',
114
+ '--disable-blink-features=AutomationControlled', '--disable-extensions', '--mute-audio', '--hide-scrollbars',
115
+ // nothing of its own in the background (component and safe-browsing downloads, sync, translation): a throwaway
116
+ // browser for pages, which then also has less to finish when it is closed
117
+ '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-default-apps',
118
+ '--disable-features=OptimizationHints,Translate,MediaRouter', '--metrics-recording-only',
119
+ '--window-size=1366,900', 'about:blank',
120
+ ], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'], windowsHide: true });
121
+ const failed = new Promise((_, reject) => child.once('error', (e) => reject(new Error(`could not start ${path.basename(exe)}: ${e.message}`))));
122
+ failed.catch(() => {});
123
+ const cdp = new Cdp(new PipeSocket(child.stdio[3], child.stdio[4]));
124
+ try {
125
+ const version = await Promise.race([failed, cdp.send('Browser.getVersion', {}, { timeoutMs: renderLimits.startMs, signal })]);
126
+ await cdp.send('Browser.setDownloadBehavior', { behavior: 'deny' }, { timeoutMs: 5000 }).catch(() => {});
127
+ // As the browser it is: without "Headless" in its name, which servers turn away (in the client hints too).
128
+ const ua = version.userAgent.replace(/Headless(?=Chrome|Edg)/g, '');
129
+ const full = /\/([\d.]+)/.exec(version.product)?.[1] || '0';
130
+ const major = full.split('.')[0];
131
+ const brand = /msedge/i.test(exe) ? 'Microsoft Edge' : /chrome/i.test(exe) ? 'Google Chrome' : null;
132
+ const brands = (v) => [{ brand: 'Chromium', version: v }, ...(brand ? [{ brand, version: v }] : []), { brand: 'Not_A Brand', version: v === major ? '24' : '24.0.0.0' }];
133
+ const platform = process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux';
134
+ const meta = { brands: brands(major), fullVersionList: brands(full), platform, platformVersion: '', architecture: process.arch === 'arm64' ? 'arm' : 'x86', bitness: '64', model: '', mobile: false };
135
+ return { child, cdp, dir, ua, meta, busy: 0, idleTimer: null };
136
+ } catch (e) {
137
+ cdp.close();
138
+ killTree(child).finally(() => removeDir(dir));
139
+ throw e;
140
+ }
141
+ }
142
+
143
+ async function ensureBrowser(signal) {
144
+ if (browser && !browser.cdp.closed) return browser;
145
+ browser = null;
146
+ starting ??= launch(signal).then((b) => {
147
+ browser = b;
148
+ // its pipe broke (the browser crashed, or it stopped answering): whatever is left of it goes, the next page
149
+ // starts another
150
+ b.cdp.on((method) => {
151
+ if (method !== 'Cdp.closed' || browser !== b) return;
152
+ browser = null;
153
+ killTree(b.child).finally(() => removeDir(b.dir));
154
+ });
155
+ return b;
156
+ }).finally(() => { starting = null; });
157
+ return starting;
158
+ }
159
+
160
+ function scheduleClose(b) {
161
+ clearTimeout(b.idleTimer);
162
+ if (b.busy) return;
163
+ b.idleTimer = setTimeout(() => { if (browser === b && !b.busy) closeRenderer(); }, renderLimits.idleMs);
164
+ b.idleTimer.unref?.();
165
+ }
166
+
167
+ // The headless browser, closed now: after a minute without a page, or when the program ends (a -p run would wait
168
+ // for its pipe).
169
+ export function closeRenderer() {
170
+ const b = browser;
171
+ browser = null;
172
+ if (!b) return;
173
+ clearTimeout(b.idleTimer);
174
+ b.cdp.close();
175
+ // Its whole process tree at once: a throwaway browser has nothing to save, and its crash reporter (started on
176
+ // Windows whatever the switches) otherwise stayed, at times, for many seconds after the browser, holding a file of
177
+ // the profile. Even killed, a browser may take Windows 20 to 60 s to end (seen in about one run in five: its
178
+ // termination waits for file I/O, likely the virus scanner on the new profile's files); the profile is removed
179
+ // once it has (removeDir).
180
+ killTree(b.child).finally(() => removeDir(b.dir));
181
+ }
182
+
183
+ // `url` opened in the headless browser: {html, finalUrl, title, status, statusText, challenge}. `status` is the
184
+ // main document's (a check page's 403 that went on to the page by itself is the page's 200 by then); `challenge`:
185
+ // the page is still a check page, one that wants a person. Throws when the page cannot be opened at all (a network
186
+ // error the browser reports, no browser installed).
187
+ export async function renderPage(url, { signal } = {}) {
188
+ const b = await ensureBrowser(signal);
189
+ b.busy++;
190
+ clearTimeout(b.idleTimer);
191
+ let targetId = null;
192
+ let off = null;
193
+ try {
194
+ ({ targetId } = await b.cdp.send('Target.createTarget', { url: 'about:blank' }, { signal, timeoutMs: 10_000 }));
195
+ const { sessionId } = await b.cdp.send('Target.attachToTarget', { targetId, flatten: true }, { signal, timeoutMs: 10_000 });
196
+ const send = (method, params = {}, timeoutMs = 15_000) => b.cdp.send(method, params, { sessionId, signal, timeoutMs });
197
+ let status = null;
198
+ let statusText = '';
199
+ let loaded = false;
200
+ let quiet = false;
201
+ off = b.cdp.on((method, params, sid) => {
202
+ if (sid !== sessionId) return;
203
+ if (method === 'Network.responseReceived' && params.type === 'Document' && params.frameId === targetId) {
204
+ status = params.response?.status ?? status;
205
+ statusText = params.response?.statusText || '';
206
+ } else if (method === 'Page.loadEventFired') loaded = true;
207
+ else if (method === 'Page.lifecycleEvent' && params.frameId === targetId) {
208
+ if (params.name === 'init') quiet = false; // a new document (a check page that reloads to the page)
209
+ else if (params.name === 'networkIdle') quiet = true;
210
+ }
211
+ });
212
+ await send('Network.enable');
213
+ await send('Network.setUserAgentOverride', { userAgent: b.ua, acceptLanguage: 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7', userAgentMetadata: b.meta });
214
+ await send('Page.enable');
215
+ await send('Page.setLifecycleEventsEnabled', { enabled: true });
216
+ const nav = await send('Page.navigate', { url }, renderLimits.navigationMs);
217
+ if (nav.errorText) throw new Error(`the browser could not open it: ${nav.errorText}`);
218
+ await until(() => loaded, renderLimits.loadMs, signal);
219
+ // null between two documents (a check page reloading to the page): the state is not known then
220
+ const state = async () => {
221
+ try { return JSON.parse((await send('Runtime.evaluate', { expression: PAGE_STATE, returnByValue: true })).result.value); } catch (e) {
222
+ if (signal?.aborted) throw e;
223
+ return null;
224
+ }
225
+ };
226
+ let page = (await state()) || { title: '', check: false };
227
+ for (const end = Date.now() + renderLimits.challengeMs; page.check && Date.now() < end;) {
228
+ await sleep(500, signal);
229
+ page = (await state()) || page;
230
+ }
231
+ await until(() => quiet, renderLimits.settleMs, signal);
232
+ const { result } = await send('Runtime.evaluate', { expression: `JSON.stringify({ html: document.documentElement ? document.documentElement.outerHTML : '', url: location.href, state: ${PAGE_STATE} })`, returnByValue: true }, 30_000);
233
+ const out = JSON.parse(result.value);
234
+ const last = JSON.parse(out.state);
235
+ return { html: out.html, finalUrl: out.url, title: last.title, status: status ?? 200, statusText, challenge: last.check };
236
+ } finally {
237
+ off?.();
238
+ if (targetId) b.cdp.send('Target.closeTarget', { targetId }, { timeoutMs: 5000 }).catch(() => {});
239
+ b.busy--;
240
+ scheduleClose(b);
241
+ }
242
+ }