@yanzc/claude-pro 0.9.0 → 0.9.2

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 (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  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 +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  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 +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/updater.js CHANGED
@@ -1,165 +1,135 @@
1
- // Manual update support for `npm i -g claude-pro`: the interactive session checks npm and installs a release only
2
- // when `/update` calls App.autoUpdate({ force: true }). Installation is serialized by a lock file and the session
3
- // loads the new package with a restart (the conversation carries over). A git checkout (the development copy) is
4
- // never touched. The environment switches remain for callers that want to disable even manual checks.
5
-
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
- import https from 'node:https';
9
- import { spawn } from 'node:child_process';
10
- import { CONFIG_DIR, INSTALL_DIR, VERSION } from './config.js';
11
- import { killTree } from './utils/shell.js';
12
-
13
- // The name on npm (scoped: npm refused plain `claude-pro` as too close to another package's name).
14
- export const PACKAGE_NAME = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).name;
15
- const STATE_FILE = path.join(CONFIG_DIR, 'update-check.json');
16
- const LOCK_FILE = path.join(CONFIG_DIR, 'update.lock');
17
- const LOCK_STALE_MS = 15 * 60_000;
18
- export const CHECK_EVERY_MS = 5 * 60_000; // a release reaches the running sessions within minutes
19
- const RETRY_FAILED_MS = 60_000; // a release's tarball can take minutes to be downloadable after it is published
20
-
21
- export function autoUpdateEnabled(env = process.env) {
22
- if (/^(1|true|yes)$/i.test(env.DISABLE_AUTOUPDATER || '')) return false;
23
- return !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_AUTO_UPDATE || '');
24
- }
25
-
26
- // The node_modules directory a package is installed in: one level up, or two for a scoped (@scope/name) package.
27
- export function modulesDir(dir = INSTALL_DIR) {
28
- const up = path.dirname(dir);
29
- return path.basename(up).startsWith('@') ? path.dirname(up) : up;
30
- }
31
-
32
- // Installed by npm (a package in some node_modules), not run from a source checkout.
33
- export function installedByNpm(dir = INSTALL_DIR) {
34
- return path.basename(modulesDir(dir)) === 'node_modules' && !fs.existsSync(path.join(dir, '.git')) && !/[\\/]_npx[\\/]/.test(dir);
35
- }
36
-
37
- // 1.2.10 > 1.2.9; a prerelease (1.3.0-beta) is never taken for newer.
38
- export function isNewer(latest, current) {
39
- if (!/^\d+\.\d+\.\d+$/.test(String(latest))) return false;
40
- const a = latest.split('.').map(Number);
41
- const b = String(current).split('-')[0].split('.').map(Number);
42
- for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > (b[i] || 0);
43
- return false;
44
- }
45
-
46
- // The version installed on disk now (another session may have updated it since this one started).
47
- export function installedVersion(dir = INSTALL_DIR) {
48
- try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version; } catch { return VERSION; }
49
- }
50
-
51
- function alive(pid) {
52
- try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
53
- }
54
-
55
- // One session of the machine installs at a time. A lock left by a session that died, or one that is very old, is taken over.
56
- function takeLock() {
57
- for (let attempt = 0; attempt < 2; attempt++) {
58
- try {
59
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
60
- fs.writeFileSync(LOCK_FILE, JSON.stringify({ pid: process.pid, at: Date.now() }), { flag: 'wx' });
61
- return true;
62
- } catch (e) {
63
- if (e.code !== 'EEXIST') return false;
64
- let held = {};
65
- try { held = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8')); } catch { /* unreadable: stale */ }
66
- if (alive(held.pid) && Date.now() - (held.at || 0) < LOCK_STALE_MS) return false;
67
- try { fs.unlinkSync(LOCK_FILE); } catch { /* someone else took it over */ }
68
- }
69
- }
70
- return false;
71
- }
72
-
73
- function releaseLock() {
74
- try {
75
- const held = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
76
- if (held.pid === process.pid) fs.unlinkSync(LOCK_FILE);
77
- } catch { /* gone already */ }
78
- }
79
-
80
- function readState() { try { return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')); } catch { return {}; } }
81
- function writeState(s) { try { fs.mkdirSync(CONFIG_DIR, { recursive: true }); fs.writeFileSync(STATE_FILE, JSON.stringify(s)); } catch { /* ignore */ } }
82
-
83
- export function latestVersion({ timeoutMs = 10_000 } = {}) {
84
- return new Promise((resolve, reject) => {
85
- // past the registry's CDN cache, which can answer with the version before the one just published
86
- const url = `https://registry.npmjs.org/${PACKAGE_NAME.replace('/', '%2f')}/latest?t=${Date.now()}`;
87
- const req = https.get(url, { headers: { accept: 'application/json', 'cache-control': 'no-cache' }, timeout: timeoutMs }, (res) => {
88
- let body = '';
89
- res.setEncoding('utf8');
90
- res.on('data', (d) => { body += d; });
91
- res.on('end', () => {
92
- if (res.statusCode !== 200) return reject(new Error(`npm registry: HTTP ${res.statusCode}`));
93
- try { resolve(JSON.parse(body).version); } catch (e) { reject(e); }
94
- });
95
- });
96
- req.on('timeout', () => req.destroy(new Error('npm registry did not answer')));
97
- req.on('error', reject);
98
- });
99
- }
100
-
101
- function runNpm(args, { timeoutMs = 300_000 } = {}) {
102
- return new Promise((resolve) => {
103
- const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { shell: process.platform === 'win32', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
104
- let out = '';
105
- const take = (d) => { out = (out + d).slice(-200_000); };
106
- child.stdout.on('data', take);
107
- child.stderr.on('data', take);
108
- // With shell: true, child.kill() ends only cmd.exe: npm kept the pipes open, 'close' never came and the
109
- // timeout did nothing. The whole tree goes.
110
- const timer = setTimeout(() => { killTree(child); }, timeoutMs);
111
- child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
112
- child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
113
- });
114
- }
115
-
116
- // Look for a newer version. Resolves with {status: 'disabled'|'dev'|'skipped'|'current'|'available'|'installed', version}:
117
- // 'available' to be installed (installUpdate), 'installed' when it is on disk already (another session installed
118
- // it: a restart loads it). Within the interval the registry is not asked again, but what another session found is
119
- // still 'available'. `force`: ask now, whatever the last check was (the /update command).
120
- export async function checkForUpdate({ force = false, env = process.env } = {}) {
121
- if (!force && !autoUpdateEnabled(env)) return { status: 'disabled' };
122
- if (!installedByNpm()) return { status: 'dev' };
123
- const state = readState();
124
- let latest;
125
- if (!force && state.checkedAt && Date.now() - state.checkedAt < CHECK_EVERY_MS) {
126
- if (!state.available) return { status: 'skipped' };
127
- latest = state.available;
128
- } else {
129
- writeState({ ...state, checkedAt: Date.now() });
130
- latest = await latestVersion();
131
- writeState({ ...readState(), available: latest });
132
- }
133
- if (!isNewer(latest, VERSION)) return { status: 'current', version: latest };
134
- if (!isNewer(latest, installedVersion())) return { status: 'installed', version: installedVersion() };
135
- return { status: 'available', version: latest };
136
- }
137
-
138
- // Install `version` with npm. Resolves with {status: 'updated'|'installed'|'locked'|'failed', version, error}:
139
- // 'locked' while another session of the machine is installing.
140
- export async function installUpdate(version, { onInstalling } = {}) {
141
- if (!takeLock()) return { status: 'locked', version };
142
- try {
143
- if (!isNewer(version, installedVersion())) return { status: 'installed', version: installedVersion() };
144
- return await install(version, onInstalling);
145
- } finally {
146
- releaseLock();
147
- }
148
- }
149
-
150
- async function install(latest, onInstalling) {
151
- // Only a global install is updated by `npm i -g`: one in a project's node_modules belongs to that project.
152
- const root = await runNpm(['root', '-g'], { timeoutMs: 30_000 });
153
- if (!root.ok || path.resolve(root.output.split(/\r?\n/).pop()) !== path.resolve(modulesDir())) {
154
- return { status: 'failed', version: latest, error: `this copy (${INSTALL_DIR}) is not the global npm install; update it with npm yourself` };
155
- }
156
- onInstalling?.(latest);
157
- // --prefer-online: not npm's own cache of the package's versions, which may not know this one yet
158
- const r = await runNpm(['install', '-g', '--prefer-online', `${PACKAGE_NAME}@${latest}`]);
159
- if (!r.ok) {
160
- writeState({ ...readState(), checkedAt: Date.now() - CHECK_EVERY_MS + RETRY_FAILED_MS }); // again in a minute
161
- return { status: 'failed', version: latest, error: r.output.split('\n').slice(-5).join('\n') };
162
- }
163
- writeState({ ...readState(), installed: latest });
164
- return { status: 'updated', version: latest };
165
- }
1
+ // Manual update support for `npm i -g claude-pro`: the interactive session checks npm and installs a release only
2
+ // when `/update` asks for it (App.updateFromNpm). Installation is serialized by a lock file and the session loads
3
+ // the new package with a restart (the conversation carries over). A git checkout (the development copy) is never
4
+ // touched.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import https from 'node:https';
9
+ import { spawn } from 'node:child_process';
10
+ import { CONFIG_DIR, INSTALL_DIR, VERSION } from './config.js';
11
+ import { killTree, processAlive as alive } from './utils/shell.js';
12
+
13
+ // The name on npm (scoped: npm refused plain `claude-pro` as too close to another package's name).
14
+ const PACKAGE_NAME = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).name;
15
+ const LOCK_FILE = path.join(CONFIG_DIR, 'update.lock');
16
+ const LOCK_STALE_MS = 15 * 60_000;
17
+
18
+ // The node_modules directory a package is installed in: one level up, or two for a scoped (@scope/name) package.
19
+ function modulesDir(dir = INSTALL_DIR) {
20
+ const up = path.dirname(dir);
21
+ return path.basename(up).startsWith('@') ? path.dirname(up) : up;
22
+ }
23
+
24
+ // Installed by npm (a package in some node_modules), not run from a source checkout.
25
+ export function installedByNpm(dir = INSTALL_DIR) {
26
+ return path.basename(modulesDir(dir)) === 'node_modules' && !fs.existsSync(path.join(dir, '.git')) && !/[\\/]_npx[\\/]/.test(dir);
27
+ }
28
+
29
+ // 1.2.10 > 1.2.9; a prerelease (1.3.0-beta) is never taken for newer.
30
+ export function isNewer(latest, current) {
31
+ if (!/^\d+\.\d+\.\d+$/.test(String(latest))) return false;
32
+ const a = latest.split('.').map(Number);
33
+ const b = String(current).split('-')[0].split('.').map(Number);
34
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > (b[i] || 0);
35
+ return false;
36
+ }
37
+
38
+ // The version installed on disk now (another session may have updated it since this one started).
39
+ export function installedVersion(dir = INSTALL_DIR) {
40
+ try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version; } catch { return VERSION; }
41
+ }
42
+
43
+ // One session of the machine installs at a time. A lock left by a session that died, or one that is very old, is taken over.
44
+ function takeLock() {
45
+ for (let attempt = 0; attempt < 2; attempt++) {
46
+ try {
47
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
48
+ fs.writeFileSync(LOCK_FILE, JSON.stringify({ pid: process.pid, at: Date.now() }), { flag: 'wx' });
49
+ return true;
50
+ } catch (e) {
51
+ if (e.code !== 'EEXIST') return false;
52
+ let held = {};
53
+ try { held = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8')); } catch { /* unreadable: stale */ }
54
+ if (alive(held.pid) && Date.now() - (held.at || 0) < LOCK_STALE_MS) return false;
55
+ try { fs.unlinkSync(LOCK_FILE); } catch { /* someone else took it over */ }
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+
61
+ function releaseLock() {
62
+ try {
63
+ const held = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
64
+ if (held.pid === process.pid) fs.unlinkSync(LOCK_FILE);
65
+ } catch { /* gone already */ }
66
+ }
67
+
68
+ function latestVersion({ timeoutMs = 10_000 } = {}) {
69
+ return new Promise((resolve, reject) => {
70
+ // past the registry's CDN cache, which can answer with the version before the one just published
71
+ const url = `https://registry.npmjs.org/${PACKAGE_NAME.replace('/', '%2f')}/latest?t=${Date.now()}`;
72
+ const req = https.get(url, { headers: { accept: 'application/json', 'cache-control': 'no-cache' }, timeout: timeoutMs }, (res) => {
73
+ let body = '';
74
+ res.setEncoding('utf8');
75
+ res.on('data', (d) => { body += d; });
76
+ res.on('end', () => {
77
+ if (res.statusCode !== 200) return reject(new Error(`npm registry: HTTP ${res.statusCode}`));
78
+ try { resolve(JSON.parse(body).version); } catch (e) { reject(e); }
79
+ });
80
+ });
81
+ req.on('timeout', () => req.destroy(new Error('npm registry did not answer')));
82
+ req.on('error', reject);
83
+ });
84
+ }
85
+
86
+ function runNpm(args, { timeoutMs = 300_000 } = {}) {
87
+ return new Promise((resolve) => {
88
+ const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { shell: process.platform === 'win32', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
89
+ let out = '';
90
+ const take = (d) => { out = (out + d).slice(-200_000); };
91
+ child.stdout.on('data', take);
92
+ child.stderr.on('data', take);
93
+ // With shell: true, child.kill() ends only cmd.exe: npm kept the pipes open, 'close' never came and the
94
+ // timeout did nothing. The whole tree goes.
95
+ const timer = setTimeout(() => { killTree(child); }, timeoutMs);
96
+ child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
97
+ child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
98
+ });
99
+ }
100
+
101
+ // Look for a newer version on npm. Resolves with {status: 'dev'|'current'|'available'|'installed', version}:
102
+ // 'available' to be installed (installUpdate), 'installed' when it is on disk already (another session installed
103
+ // it: a restart loads it). (The background checks every few minutes, with their state file and switches, are gone:
104
+ // /update is the only caller.)
105
+ export async function checkForUpdate() {
106
+ if (!installedByNpm()) return { status: 'dev' };
107
+ const latest = await latestVersion();
108
+ if (!isNewer(latest, VERSION)) return { status: 'current', version: latest };
109
+ if (!isNewer(latest, installedVersion())) return { status: 'installed', version: installedVersion() };
110
+ return { status: 'available', version: latest };
111
+ }
112
+
113
+ // Install `version` with npm. Resolves with {status: 'updated'|'installed'|'locked'|'failed', version, error}:
114
+ // 'locked' while another session of the machine is installing.
115
+ export async function installUpdate(version) {
116
+ if (!takeLock()) return { status: 'locked', version };
117
+ try {
118
+ if (!isNewer(version, installedVersion())) return { status: 'installed', version: installedVersion() };
119
+ return await install(version);
120
+ } finally {
121
+ releaseLock();
122
+ }
123
+ }
124
+
125
+ async function install(latest) {
126
+ // Only a global install is updated by `npm i -g`: one in a project's node_modules belongs to that project.
127
+ const root = await runNpm(['root', '-g'], { timeoutMs: 30_000 });
128
+ if (!root.ok || path.resolve(root.output.split(/\r?\n/).pop()) !== path.resolve(modulesDir())) {
129
+ return { status: 'failed', version: latest, error: `this copy (${INSTALL_DIR}) is not the global npm install; update it with npm yourself` };
130
+ }
131
+ // --prefer-online: not npm's own cache of the package's versions, which may not know this one yet
132
+ const r = await runNpm(['install', '-g', '--prefer-online', `${PACKAGE_NAME}@${latest}`]);
133
+ if (!r.ok) return { status: 'failed', version: latest, error: r.output.split('\n').slice(-5).join('\n') };
134
+ return { status: 'updated', version: latest };
135
+ }
@@ -5,8 +5,8 @@ import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import { spawn } from 'node:child_process';
8
+ import { MAX_IMAGE_BYTES } from './images.js';
8
9
 
9
- export const MAX_IMAGE_BYTES = 3_750_000; // ~5MB once base64 encoded
10
10
  const IMAGE_EXT = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
11
11
 
12
12
  function run(cmd, args, { env, timeout = 15_000 } = {}) {
@@ -75,7 +75,8 @@ export function imageFromFile(file) {
75
75
  let st;
76
76
  try { st = fs.statSync(file); } catch { return { error: `File not found: ${file}` }; }
77
77
  if (!st.isFile()) return { error: `Not a file: ${file}` };
78
- if (st.size > MAX_IMAGE_BYTES) return { error: `Image is too large (${(st.size / 1e6).toFixed(1)}MB, max 3.7MB)` };
78
+ // the turn scales it down to what the API takes (fitImagesIn), as it does a Read image: a 5 MB phone photo is fine
79
+ if (st.size > 30 * 1024 * 1024) return { error: `Image is too large (${(st.size / 1e6).toFixed(1)}MB, max 30MB)` };
79
80
  return { image: { media_type: media, data: fs.readFileSync(file).toString('base64'), bytes: st.size, source: file } };
80
81
  }
81
82
 
@@ -125,7 +126,8 @@ async function readLinux() {
125
126
  child.on('close', (code) => { clearTimeout(timer); resolve(code === 0 ? Buffer.concat(chunks) : null); });
126
127
  });
127
128
  if (r?.length) {
128
- if (r.length > MAX_IMAGE_BYTES) return { error: 'Image is too large (max 3.7MB)' };
129
+ // scaled down when it is sent (fitImagesIn), as a dropped image file is
130
+ if (r.length > 30 * 1024 * 1024) return { error: `Image is too large (${(r.length / 1e6).toFixed(1)}MB, max 30MB)` };
129
131
  return { image: { media_type: 'image/png', data: r.toString('base64'), bytes: r.length } };
130
132
  }
131
133
  }
@@ -1,19 +1,24 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
+ import { knownShell } from './shell.js';
4
5
 
5
6
  const isWin = process.platform === 'win32';
6
7
 
7
- // Where Git for Windows is installed (its `/`), from the Git Bash the Bash tool uses; null when not found.
8
+ // Where Git for Windows is installed (its `/`), from the Git Bash the Bash tool uses (findShell: also where `where
9
+ // git` and the settings point, so a Git in another place than Program Files counts too); before that one is known,
10
+ // from the usual places. null when not found.
8
11
  let gitRoot;
9
12
  function gitBashRoot() {
10
13
  if (gitRoot !== undefined) return gitRoot;
11
- gitRoot = null;
12
- const configured = process.env.CLAUDE_CODE_GIT_BASH_PATH;
13
- for (const bash of [configured, 'C:\\Program Files\\Git\\bin\\bash.exe', 'C:\\Program Files (x86)\\Git\\bin\\bash.exe']) {
14
- if (bash && fs.existsSync(bash)) { gitRoot = path.dirname(path.dirname(bash)); break; }
14
+ const shell = knownShell();
15
+ const candidates = shell ? [shell.kind === 'bash' ? shell.path : null] : [process.env.CLAUDE_CODE_GIT_BASH_PATH, 'C:\\Program Files\\Git\\bin\\bash.exe', 'C:\\Program Files (x86)\\Git\\bin\\bash.exe'];
16
+ let root = null;
17
+ for (const bash of candidates) {
18
+ if (bash && fs.existsSync(bash)) { root = path.dirname(path.dirname(bash)); break; }
15
19
  }
16
- return gitRoot;
20
+ if (shell) gitRoot = root; // kept once the shell is known; looked for again until then
21
+ return root;
17
22
  }
18
23
 
19
24
  // A Git Bash path as Windows sees it, after its mount table (`mount`): /c/... is drive C:, /tmp is the Windows
@@ -45,20 +50,13 @@ export function displayPath(p, cwd) {
45
50
  const rel = path.relative(cwd, p);
46
51
  if (!rel) return '.';
47
52
  if (!rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
48
- const home = os.homedir();
49
- if (p.startsWith(home)) return '~' + p.slice(home.length);
53
+ // inside the home directory (C:\Users\yzc2 is not, and the drive letter may be in either case)
54
+ const fromHome = path.relative(os.homedir(), p);
55
+ if (!fromHome) return '~';
56
+ if (!fromHome.startsWith('..') && !path.isAbsolute(fromHome)) return `~${path.sep}${fromHome}`;
50
57
  return p;
51
58
  }
52
59
 
53
- export function isInside(child, parent) {
54
- const rel = path.relative(parent, child);
55
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
56
- }
57
-
58
- export function samePath(a, b) {
59
- return isWin ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b);
60
- }
61
-
62
60
  // `input` as an absolute directory: "" (or ~) is the home directory, "D:" is the root of D:, and forward slashes do
63
61
  // on Windows too. null when it is not absolute.
64
62
  export function normalizeDir(input, { platform = process.platform, home = os.homedir() } = {}) {
@@ -7,23 +7,30 @@ import { OutputDecoder } from './encoding.js';
7
7
  const isWin = process.platform === 'win32';
8
8
  let shellCache;
9
9
 
10
+ // The shell findShell found, or undefined before it was looked for.
11
+ export const knownShell = () => shellCache;
12
+
13
+ // Whether a process with this id runs (EPERM: it does, but is not ours to signal).
14
+ export function processAlive(pid) {
15
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
16
+ }
17
+
10
18
  // Locate the shell used by the Bash tool. On Windows we need Git Bash, like Claude Code.
11
19
  export function findShell(config) {
12
20
  if (shellCache) return shellCache;
13
21
  const candidates = [];
14
22
  if (isWin) {
15
23
  if (config?.env.CLAUDE_CODE_GIT_BASH_PATH) candidates.push(config.env.CLAUDE_CODE_GIT_BASH_PATH);
16
- try {
17
- const where = spawnSync('where', ['git'], { encoding: 'utf8', windowsHide: true });
18
- for (const line of (where.stdout || '').split(/\r?\n/).filter(Boolean)) {
19
- // ...\Git\cmd\git.exe or ...\Git\bin\git.exe or ...\Git\mingw64\bin\git.exe
20
- let dir = path.dirname(line.trim());
21
- for (let i = 0; i < 3; i++) {
22
- candidates.push(path.join(dir, 'bin', 'bash.exe'));
23
- dir = path.dirname(dir);
24
- }
24
+ // Where git is on the PATH, looked up here (`where git` in a process of its own took 75 ms of every start):
25
+ // ...\Git\cmd\git.exe or ...\Git\bin\git.exe or ...\Git\mingw64\bin\git.exe
26
+ for (const entry of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
27
+ if (!['git.exe', 'git.cmd'].some((name) => fs.existsSync(path.join(entry, name)))) continue;
28
+ let dir = entry;
29
+ for (let i = 0; i < 3; i++) {
30
+ candidates.push(path.join(dir, 'bin', 'bash.exe'));
31
+ dir = path.dirname(dir);
25
32
  }
26
- } catch { /* ignore */ }
33
+ }
27
34
  candidates.push('C:\\Program Files\\Git\\bin\\bash.exe', 'C:\\Program Files (x86)\\Git\\bin\\bash.exe');
28
35
  for (const c of candidates) {
29
36
  if (c && fs.existsSync(c)) return (shellCache = { path: c, kind: 'bash', name: 'bash (Git Bash)' });
@@ -63,7 +70,18 @@ export function parsePsRows(text) {
63
70
  // member of its process group (a child whose parent already exited is no longer linked to it).
64
71
  export function msysTree(rows, rootPid) {
65
72
  const root = rows.find((r) => r.pid === rootPid);
66
- if (!root) return [];
73
+ if (!root) {
74
+ // The shell has ended. What it left running in the background stays in its process group, which it led, and has
75
+ // no parent any more (PPID 1): those, and what they started. A group that only has the same number by now is
76
+ // not taken: its leader has a parent.
77
+ const group = rows.filter((r) => r.pgid === rootPid);
78
+ const take = new Set(group.filter((r) => r.ppid === 1).map((r) => r.pid));
79
+ for (let grew = true; grew;) {
80
+ grew = false;
81
+ for (const r of group) if (!take.has(r.pid) && take.has(r.ppid)) { take.add(r.pid); grew = true; }
82
+ }
83
+ return group.filter((r) => take.has(r.pid)).map((r) => r.winpid);
84
+ }
67
85
  const children = new Map();
68
86
  for (const r of rows) {
69
87
  if (!children.has(r.ppid)) children.set(r.ppid, []);
@@ -118,6 +136,22 @@ function msysDescendants(child, { sync }) {
118
136
  return runAsync(ps, ['-W'], { timeout: 5000 }).then((r) => (r.code === 0 ? msysTree(parsePsRows(r.out), root) : []));
119
137
  }
120
138
 
139
+ // The trimmed output of a command that succeeded, or null, as run() gives it, without blocking the event loop. An
140
+ // output past maxChars is null too. Never rejects.
141
+ export function runText(cmd, args, { cwd, timeout = 5000, maxChars = 1024 * 1024 } = {}) {
142
+ return new Promise((resolve) => {
143
+ let out = '';
144
+ let child;
145
+ try { child = spawn(cmd, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { resolve(null); return; }
146
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, timeout);
147
+ const done = (value) => { clearTimeout(timer); resolve(value); };
148
+ child.stdout.setEncoding('utf8');
149
+ child.stdout.on('data', (d) => { out += d; if (out.length > maxChars) try { child.kill(); } catch { /* gone */ } });
150
+ child.on('error', () => done(null));
151
+ child.on('close', (code) => done(code === 0 && out.length <= maxChars ? out.trim() : null));
152
+ });
153
+ }
154
+
121
155
  // A command's exit code and output, without blocking the event loop. Never rejects.
122
156
  function runAsync(cmd, args, { timeout = 5000 } = {}) {
123
157
  return new Promise((resolve) => {
@@ -135,11 +169,17 @@ function runAsync(cmd, args, { timeout = 5000 } = {}) {
135
169
  // Kill a process and all its children, without blocking the event loop (`ps -W` and taskkill take up to seconds,
136
170
  // and Ctrl+C, a timeout or KillShell used to freeze the interface for that long). Resolves when done; never
137
171
  // rejects. The tree has to be looked up before anything is killed: once its parents are gone the links are too.
138
- export async function killTree(child) {
139
- if (!child || child.exitCode !== null || child.killed) return;
172
+ // `orphans`: also when the process itself has ended, for what it left running (a background shell whose `server &`
173
+ // still holds its output open): only the processes found through it then, never its own pid, which may be another
174
+ // process's by now. Only for callers that know something of it still runs (a background shell not closed yet).
175
+ export async function killTree(child, { orphans = false } = {}) {
176
+ if (!child || child.killed) return;
177
+ const ended = child.exitCode !== null || child.signalCode !== null;
178
+ if (ended && !orphans) return;
140
179
  try {
141
180
  if (isWin) {
142
- const pids = new Set([child.pid, ...(child.claudeProPidFile ? await msysDescendants(child, { sync: false }) : [])]);
181
+ const pids = new Set([...(ended ? [] : [child.pid]), ...(child.claudeProPidFile ? await msysDescendants(child, { sync: false }) : [])]);
182
+ if (!pids.size) return;
143
183
  const args = ['/F', '/T'];
144
184
  for (const pid of pids) args.push('/PID', String(pid));
145
185
  await runAsync('taskkill', args);
@@ -148,16 +188,19 @@ export async function killTree(child) {
148
188
  process.kill(-child.pid, 'SIGKILL');
149
189
  }
150
190
  } catch {
151
- try { child.kill('SIGKILL'); } catch { /* ignore */ }
191
+ if (!ended) { try { child.kill('SIGKILL'); } catch { /* ignore */ } }
152
192
  }
153
193
  }
154
194
 
155
195
  // The same, done before it returns: for the exit, after which nothing would be left to finish the kill.
156
- export function killTreeSync(child) {
157
- if (!child || child.exitCode !== null || child.killed) return;
196
+ export function killTreeSync(child, { orphans = false } = {}) {
197
+ if (!child || child.killed) return;
198
+ const ended = child.exitCode !== null || child.signalCode !== null;
199
+ if (ended && !orphans) return;
158
200
  try {
159
201
  if (isWin) {
160
- const pids = new Set([child.pid, ...(child.claudeProPidFile ? msysDescendants(child, { sync: true }) : [])]);
202
+ const pids = new Set([...(ended ? [] : [child.pid]), ...(child.claudeProPidFile ? msysDescendants(child, { sync: true }) : [])]);
203
+ if (!pids.size) return;
161
204
  const args = ['/F', '/T'];
162
205
  for (const pid of pids) args.push('/PID', String(pid));
163
206
  spawnSync('taskkill', args, { windowsHide: true, stdio: 'ignore' });
@@ -166,14 +209,25 @@ export function killTreeSync(child) {
166
209
  process.kill(-child.pid, 'SIGKILL');
167
210
  }
168
211
  } catch {
169
- try { child.kill('SIGKILL'); } catch { /* ignore */ }
212
+ if (!ended) { try { child.kill('SIGKILL'); } catch { /* ignore */ } }
170
213
  }
171
214
  }
172
215
 
173
216
  // Run a quick command and return stdout (used for git info etc.). Never throws.
174
- export function run(cmd, args, { cwd, timeout = 5000 } = {}) {
217
+ // The environment of what the program starts (Bash, REPL, hooks, MCP servers): non-interactive and colour free, and
218
+ // without what makes a process a restartable session of this program (a hook that ran `claude-pro -p` was given the
219
+ // Restart tool and the prompt about its own source).
220
+ export function childEnv() {
221
+ const env = { ...process.env };
222
+ Object.assign(env, { GIT_EDITOR: 'true', GIT_PAGER: 'cat', PAGER: 'cat', NO_COLOR: '1', CLAUDE_PRO: '1' });
223
+ delete env.FORCE_COLOR;
224
+ for (const key of ['CLAUDE_PRO_SUPERVISED', 'CLAUDE_PRO_RESTART_FILE', 'CLAUDE_PRO_RESTARTED']) delete env[key];
225
+ return env;
226
+ }
227
+
228
+ export function run(cmd, args, { cwd, timeout = 5000, maxBuffer = 1024 * 1024 } = {}) {
175
229
  try {
176
- const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
230
+ const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', timeout, maxBuffer, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
177
231
  if (r.status !== 0) return null;
178
232
  return r.stdout.trim();
179
233
  } catch {
package/.env.example DELETED
@@ -1,29 +0,0 @@
1
- # Optional gateway configuration. /login normally saves the key in
2
- # ~/.claude-pro/gateway.json, so CLAUDE_PRO_GATEWAY_API_KEY is only needed for
3
- # headless or automated runs.
4
- CLAUDE_PRO_PROVIDER=gateway
5
- CLAUDE_PRO_GATEWAY_URL=https://gw.predix.icu
6
- CLAUDE_PRO_GATEWAY_API_KEY=gw-your-key
7
- CLAUDE_PRO_GATEWAY_MODEL=opus
8
-
9
- # Reasoning and context tuning
10
- # CLAUDE_CODE_EFFORT_LEVEL=high # default: the model's own
11
- # CLAUDE_CODE_AUTO_COMPACT_WINDOW=250000 # default: the model's whole window
12
- # CLAUDE_CODE_MAX_OUTPUT_TOKENS=48000 # gateway default
13
- # MAX_THINKING_TOKENS=0 # 0 = disable thinking
14
- # CLAUDE_CODE_PROMPT_CACHE_TTL=1h # 5m or 1h for the main conversation
15
- # CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL=5m # sub-agents, compaction and side queries
16
- # ENABLE_PROMPT_CACHING_1H=1 # 1h for both buckets
17
- # FORCE_PROMPT_CACHING_5M=1 # force 5m for both buckets
18
- # DISABLE_PROMPT_CACHING=1 # send no cache_control markers
19
- # CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=90
20
- # DISABLE_AUTOCOMPACT=1
21
-
22
- # Request and tool limits
23
- # API_TIMEOUT_MS=600000
24
- # CLAUDE_PRO_MAX_RETRIES=6
25
- # CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS=21600000 # 0 = fail instead of waiting
26
- # BASH_DEFAULT_TIMEOUT_MS=600000
27
- # BASH_MAX_TIMEOUT_MS=3600000
28
- # BASH_MAX_OUTPUT_LENGTH=60000
29
- # CLAUDE_CODE_GIT_BASH_PATH=C:\Program Files\Git\bin\bash.exe