@yanzc/claude-pro 0.7.8 → 0.9.0

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.
@@ -1,18 +1,41 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import os from 'node:os';
3
4
 
4
5
  const isWin = process.platform === 'win32';
5
6
 
7
+ // Where Git for Windows is installed (its `/`), from the Git Bash the Bash tool uses; null when not found.
8
+ let gitRoot;
9
+ function gitBashRoot() {
10
+ 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; }
15
+ }
16
+ return gitRoot;
17
+ }
18
+
19
+ // A Git Bash path as Windows sees it, after its mount table (`mount`): /c/... is drive C:, /tmp is the Windows
20
+ // temp directory, /bin is /usr/bin, and anything else is under the Git installation. A command that wrote
21
+ // /tmp/out.txt can then be followed by a Read of /tmp/out.txt (it used to resolve to D:\tmp\out.txt).
22
+ export function msysPath(p) {
23
+ const drive = /^\/([a-zA-Z])(\/.*)?$/.exec(p);
24
+ if (drive) return `${drive[1].toUpperCase()}:${(drive[2] || '/').replace(/\//g, '\\')}`;
25
+ if (p === '/tmp' || p.startsWith('/tmp/')) return path.join(os.tmpdir(), p.slice(4));
26
+ const root = gitBashRoot();
27
+ if (!root) return p;
28
+ if (p === '/bin' || p.startsWith('/bin/')) return path.join(root, 'usr', 'bin', p.slice(4));
29
+ return path.join(root, p);
30
+ }
31
+
6
32
  // Resolve a path the model gave us. Accepts absolute, relative (to cwd), ~, and on Windows
7
- // also Git-Bash style paths such as /d/foo/bar or /c/Users/...
33
+ // also Git-Bash style paths such as /d/foo/bar, /c/Users/... or /tmp/x (see msysPath).
8
34
  export function resolvePath(p, cwd) {
9
35
  if (!p) return cwd;
10
36
  p = String(p).trim();
11
37
  if (p === '~' || p.startsWith('~/') || p.startsWith('~\\')) p = path.join(os.homedir(), p.slice(1));
12
- if (isWin) {
13
- const m = /^\/([a-zA-Z])(\/.*)?$/.exec(p);
14
- if (m) p = `${m[1].toUpperCase()}:${(m[2] || '/').replace(/\//g, '\\')}`;
15
- }
38
+ if (isWin && p.startsWith('/') && !p.startsWith('//')) p = msysPath(p);
16
39
  return path.resolve(cwd, p);
17
40
  }
18
41
 
@@ -35,3 +58,21 @@ export function isInside(child, parent) {
35
58
  export function samePath(a, b) {
36
59
  return isWin ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b);
37
60
  }
61
+
62
+ // `input` as an absolute directory: "" (or ~) is the home directory, "D:" is the root of D:, and forward slashes do
63
+ // on Windows too. null when it is not absolute.
64
+ export function normalizeDir(input, { platform = process.platform, home = os.homedir() } = {}) {
65
+ const p = platform === 'win32' ? path.win32 : path.posix;
66
+ let s = String(input ?? '').trim();
67
+ if (!s || s === '~') return home;
68
+ if (s.startsWith('~/') || s.startsWith('~\\')) s = p.join(home, s.slice(2));
69
+ if (platform === 'win32') {
70
+ s = s.replace(/\//g, '\\');
71
+ if (/^[A-Za-z]:$/.test(s)) s += '\\';
72
+ if (!/^([A-Za-z]:\\|\\\\[^\\]+\\[^\\]+)/.test(s)) return null;
73
+ s = s.replace(/^[a-z]:/, (d) => d.toUpperCase());
74
+ } else if (!s.startsWith('/')) {
75
+ return null;
76
+ }
77
+ return p.resolve(s);
78
+ }
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { spawn, spawnSync } from 'node:child_process';
5
+ import { OutputDecoder } from './encoding.js';
5
6
 
6
7
  const isWin = process.platform === 'win32';
7
8
  let shellCache;
@@ -98,25 +99,65 @@ function findPs() {
98
99
  }
99
100
 
100
101
  // Windows ids of the processes MSYS says are under the shell started by spawnShell (empty when unknown).
101
- function msysDescendants(child) {
102
+ // `sync`: with spawnSync (the exit path, which must not leave anything running); else without blocking.
103
+ function msysDescendants(child, { sync }) {
104
+ let root, ps;
102
105
  try {
103
- const root = parseInt(fs.readFileSync(child.claudeProPidFile, 'utf8'), 10);
104
- const ps = findPs();
105
- if (!Number.isFinite(root) || !ps) return [];
106
- const r = spawnSync(ps, ['-W'], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
107
- return r.status === 0 ? msysTree(parsePsRows(r.stdout), root) : [];
106
+ root = parseInt(fs.readFileSync(child.claudeProPidFile, 'utf8'), 10);
107
+ ps = findPs();
108
+ } catch { /* no pid file (yet) */ }
109
+ if (!Number.isFinite(root) || !ps) return sync ? [] : Promise.resolve([]);
110
+ if (sync) {
111
+ try {
112
+ const r = spawnSync(ps, ['-W'], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
113
+ return r.status === 0 ? msysTree(parsePsRows(r.stdout), root) : [];
114
+ } catch {
115
+ return [];
116
+ }
117
+ }
118
+ return runAsync(ps, ['-W'], { timeout: 5000 }).then((r) => (r.code === 0 ? msysTree(parsePsRows(r.out), root) : []));
119
+ }
120
+
121
+ // A command's exit code and output, without blocking the event loop. Never rejects.
122
+ function runAsync(cmd, args, { timeout = 5000 } = {}) {
123
+ return new Promise((resolve) => {
124
+ let out = '';
125
+ let child;
126
+ try { child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { resolve({ code: null, out }); return; }
127
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, timeout);
128
+ child.stdout.setEncoding('utf8');
129
+ child.stdout.on('data', (d) => { out += d; });
130
+ child.on('error', () => { clearTimeout(timer); resolve({ code: null, out }); });
131
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, out }); });
132
+ });
133
+ }
134
+
135
+ // Kill a process and all its children, without blocking the event loop (`ps -W` and taskkill take up to seconds,
136
+ // and Ctrl+C, a timeout or KillShell used to freeze the interface for that long). Resolves when done; never
137
+ // 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;
140
+ try {
141
+ if (isWin) {
142
+ const pids = new Set([child.pid, ...(child.claudeProPidFile ? await msysDescendants(child, { sync: false }) : [])]);
143
+ const args = ['/F', '/T'];
144
+ for (const pid of pids) args.push('/PID', String(pid));
145
+ await runAsync('taskkill', args);
146
+ if (child.claudeProPidFile) fs.rmSync(child.claudeProPidFile, { force: true });
147
+ } else {
148
+ process.kill(-child.pid, 'SIGKILL');
149
+ }
108
150
  } catch {
109
- return [];
151
+ try { child.kill('SIGKILL'); } catch { /* ignore */ }
110
152
  }
111
153
  }
112
154
 
113
- // Kill a process and all its children.
114
- export function killTree(child) {
155
+ // The same, done before it returns: for the exit, after which nothing would be left to finish the kill.
156
+ export function killTreeSync(child) {
115
157
  if (!child || child.exitCode !== null || child.killed) return;
116
158
  try {
117
159
  if (isWin) {
118
- // The tree has to be looked up before anything is killed: once its parents are gone the links are too.
119
- const pids = new Set([child.pid, ...(child.claudeProPidFile ? msysDescendants(child) : [])]);
160
+ const pids = new Set([child.pid, ...(child.claudeProPidFile ? msysDescendants(child, { sync: true }) : [])]);
120
161
  const args = ['/F', '/T'];
121
162
  for (const pid of pids) args.push('/PID', String(pid));
122
163
  spawnSync('taskkill', args, { windowsHide: true, stdio: 'ignore' });
@@ -141,17 +182,45 @@ export function run(cmd, args, { cwd, timeout = 5000 } = {}) {
141
182
  }
142
183
 
143
184
  const rgWorks = new Map();
144
- // The ripgrep binary to use: CLAUDE_PRO_RIPGREP_PATH if it runs, else `rg` on PATH, else null
145
- // (Grep then uses its JS scanner). CLAUDE_PRO_RIPGREP_PATH=off skips ripgrep altogether.
185
+ // The ripgrep binary to use: CLAUDE_PRO_RIPGREP_PATH if it runs, else `rg` on PATH, else the copy VS Code ships
186
+ // (Windows), else null (Grep then uses its JS scanner, about 4x slower). CLAUDE_PRO_RIPGREP_PATH=off skips
187
+ // ripgrep altogether.
146
188
  export function ripgrepPath(config) {
147
189
  const configured = String(config?.env?.CLAUDE_PRO_RIPGREP_PATH ?? process.env.CLAUDE_PRO_RIPGREP_PATH ?? '').trim();
148
190
  if (/^(off|none|false|0)$/i.test(configured)) return null;
149
- for (const c of [configured, 'rg'].filter(Boolean)) {
191
+ for (const c of [configured, 'rg', ...vscodeRipgreps()].filter(Boolean)) {
150
192
  if (!rgWorks.has(c)) rgWorks.set(c, run(c, ['--version']) !== null);
151
193
  if (rgWorks.get(c)) return c;
152
194
  }
153
195
  return null;
154
196
  }
197
+
198
+ // rg.exe inside VS Code installs, newest version first. Recent versions keep it under a folder named by a hash
199
+ // that changes with every update, so a path set by hand stops working after one.
200
+ let vscodeRg;
201
+ function vscodeRipgreps() {
202
+ if (vscodeRg) return vscodeRg;
203
+ vscodeRg = [];
204
+ if (!isWin) return vscodeRg;
205
+ const inside = [
206
+ 'resources/app/node_modules.asar.unpacked/@vscode/ripgrep-universal/bin/win32-x64/rg.exe',
207
+ 'resources/app/node_modules.asar.unpacked/@vscode/ripgrep/bin/rg.exe',
208
+ 'resources/app/node_modules/@vscode/ripgrep/bin/rg.exe',
209
+ ];
210
+ const bases = [process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'Microsoft VS Code'), process.env.ProgramFiles && path.join(process.env.ProgramFiles, 'Microsoft VS Code')].filter(Boolean);
211
+ for (const base of bases) {
212
+ let dirs = [];
213
+ try {
214
+ dirs = fs.readdirSync(base, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(base, d.name))
215
+ .map((dir) => ({ dir, t: fs.statSync(dir).mtimeMs })).sort((a, b) => b.t - a.t).map((d) => d.dir);
216
+ } catch { continue; }
217
+ for (const dir of [...dirs, base]) for (const rel of inside) {
218
+ const file = path.join(dir, rel);
219
+ if (fs.existsSync(file)) vscodeRg.push(file);
220
+ }
221
+ }
222
+ return vscodeRg;
223
+ }
155
224
  export function hasRipgrep(config) { return ripgrepPath(config) !== null; }
156
225
 
157
226
  // `stdin`: text to feed the command on standard input (hooks get their event JSON this way).
@@ -194,8 +263,8 @@ export function spawnShell(shell, command, { cwd, env, cwdFile, stdin }) {
194
263
  }
195
264
 
196
265
  // Collect the output of a shell started with spawnShell and report when it is finished:
197
- // onOutput(text, 'stdout' | 'stderr') for each piece (decoded as a stream, so a multi-byte character
198
- // split between two chunks survives) and done(code, error) exactly once.
266
+ // onOutput(text, 'stdout' | 'stderr') for each piece (decoded line by line, UTF-8 or the console code page,
267
+ // see OutputDecoder) and done(code, error) exactly once.
199
268
  //
200
269
  // A command that leaves a process running (`server &`) keeps the shell's output pipes open after the
201
270
  // shell itself has exited, and 'close' would not fire until that process ends. Waiting for it would hold
@@ -217,12 +286,14 @@ export function watchShell(child, { onOutput, done, idleMs = 500, graceMs = 3000
217
286
  const settleAfterExit = () => finish(child.exitCode);
218
287
  const armIdle = () => { clearTimeout(idleTimer); idleTimer = setTimeout(settleAfterExit, idleMs); };
219
288
  for (const stream of ['stdout', 'stderr']) {
220
- child[stream].setEncoding('utf8');
221
- child[stream].on('data', (text) => {
289
+ const decoder = new OutputDecoder();
290
+ const take = (text) => { if (text) onOutput(text, stream); };
291
+ child[stream].on('data', (chunk) => {
222
292
  if (finished) return; // late output of a process the command left running is drained, not kept
223
- onOutput(text, stream);
293
+ take(decoder.write(chunk));
224
294
  if (exited) armIdle();
225
295
  });
296
+ child[stream].on('end', () => { if (!finished) take(decoder.end()); });
226
297
  }
227
298
  child.on('error', (e) => finish(null, e));
228
299
  child.on('exit', () => {
package/src/attach.js DELETED
@@ -1,146 +0,0 @@
1
- // `claude-pro attach [name]`: a background session of this computer (claude-pro --headless, see vterm.js), used
2
- // here in this terminal with its whole interface, as tmux attach does. It goes through the session's own server on
3
- // 127.0.0.1 (peers.js), not the gateway: GET /attach upgraded to a connection of its own, the screen coming down as
4
- // it is drawn, the keys and the size of this terminal going up as JSON lines ({keys: base64}, {resize: [cols,
5
- // rows]}). ctrl+] detaches; the session goes on. Several terminals can be attached at once (the last one to attach
6
- // or resize sets the size), and the web page at the same time.
7
- //
8
- // A restart of the session (an update, /restart, /cd) ends the connection: this waits for the session to come back
9
- // under the same registry id and attaches again.
10
-
11
- import http from 'node:http';
12
- import readline from 'node:readline';
13
- import { listPeers } from './peers.js';
14
-
15
- const DETACH = '\x1d'; // ctrl+]
16
- const RESET = '\x1b[?1002l\x1b[?1006l\x1b[?1000l\x1b[?2004l\x1b[?1049l\x1b[?25h';
17
- const BACK_WITHIN_MS = 20_000; // a restart brings the session back within this
18
-
19
- const backgroundSessions = () => listPeers().filter((p) => p.kind === 'background');
20
-
21
- // The session `ref` names: its name, its id at the gateway, or the start of its registry id.
22
- export function findBackground(ref, sessions = backgroundSessions()) {
23
- const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
24
- if (!q) return null;
25
- return sessions.find((p) => p.name.toLowerCase() === q)
26
- || sessions.find((p) => String(p.remoteId || '').toLowerCase() === q)
27
- || sessions.find((p) => p.id.startsWith(q) || String(p.remoteId || '').toLowerCase().startsWith(q))
28
- || null;
29
- }
30
-
31
- function choose(sessions, io) {
32
- io.stdout.write('Background sessions on this computer:\n');
33
- sessions.forEach((p, i) => io.stdout.write(` ${i + 1}. &${p.name} ${p.cwd}${p.remoteId ? ` (${p.remoteId})` : ''}\n`));
34
- const rl = readline.createInterface({ input: io.stdin, output: io.stdout });
35
- return new Promise((resolve) => {
36
- rl.question(`Which one? [1-${sessions.length}, Enter for 1] `, (answer) => {
37
- rl.close();
38
- const n = answer.trim() ? Number(answer.trim()) : 1;
39
- resolve(Number.isInteger(n) && n >= 1 && n <= sessions.length ? sessions[n - 1] : findBackground(answer.trim(), sessions));
40
- });
41
- });
42
- }
43
-
44
- // One connection: resolves with how it ended, 'detached' or 'closed'.
45
- function connect(peer, io) {
46
- return new Promise((resolve, reject) => {
47
- const { columns = 100, rows = 30 } = io.stdout;
48
- const req = http.request({
49
- host: '127.0.0.1', port: peer.port, path: `/attach?cols=${columns}&rows=${rows}`,
50
- headers: { connection: 'Upgrade', upgrade: 'claude-pro-attach', authorization: `Bearer ${peer.token}` },
51
- });
52
- req.on('response', (res) => reject(new Error(res.statusCode === 404 ? 'this session cannot be attached to (a terminal session, or an older claude-pro)' : `HTTP ${res.statusCode}`)));
53
- req.on('error', reject);
54
- req.on('upgrade', (_res, socket, head) => {
55
- let ended = null;
56
- const finish = (how) => {
57
- if (ended) return;
58
- ended = how;
59
- io.stdin.off('data', onKeys);
60
- io.stdout.off('resize', onResize);
61
- socket.destroy();
62
- resolve(how);
63
- };
64
- const send = (msg) => { if (!socket.destroyed) socket.write(`${JSON.stringify(msg)}\n`); };
65
- const onKeys = (data) => {
66
- const i = data.indexOf(DETACH);
67
- if (i >= 0) {
68
- if (i > 0) send({ keys: data.subarray(0, i).toString('base64') });
69
- finish('detached');
70
- return;
71
- }
72
- send({ keys: data.toString('base64') });
73
- };
74
- const onResize = () => send({ resize: [io.stdout.columns, io.stdout.rows] });
75
- if (head?.length) io.stdout.write(head);
76
- socket.on('data', (d) => io.stdout.write(d));
77
- socket.on('close', () => finish('closed'));
78
- socket.on('error', () => finish('closed'));
79
- io.stdin.on('data', onKeys);
80
- io.stdout.on('resize', onResize);
81
- });
82
- req.end();
83
- });
84
- }
85
-
86
- // A window the computer service opened for it (--keep-open, see HostService.window): what went wrong, or that the
87
- // session ended, stays readable until a key is pressed (a window that closes at once says nothing).
88
- function keepOpen(args, io) {
89
- if (!args.includes('--keep-open') || !io.stdin.isTTY) return Promise.resolve();
90
- io.stdout.write('Press any key to close this window.');
91
- io.stdin.setRawMode(true);
92
- io.stdin.resume();
93
- return new Promise((resolve) => io.stdin.once('data', () => { io.stdin.setRawMode(false); io.stdin.pause(); resolve(); }));
94
- }
95
-
96
- // io: the terminal (process.stdin/stdout/stderr; the tests give their own).
97
- export async function attachCommand(args = [], io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
98
- if (!io.stdin.isTTY || !io.stdout.isTTY) {
99
- io.stderr.write('claude-pro attach needs a terminal.\n');
100
- return 2;
101
- }
102
- const sessions = backgroundSessions();
103
- if (!sessions.length) {
104
- io.stdout.write('No background session runs on this computer. The web page opens them (新建会话, without "open a terminal window").\n');
105
- await keepOpen(args, io);
106
- return 1;
107
- }
108
- const ref = args.find((a) => !a.startsWith('-'));
109
- let peer = ref ? findBackground(ref, sessions) : sessions.length === 1 ? sessions[0] : await choose(sessions, io);
110
- if (!peer) {
111
- io.stderr.write(`No background session called "${ref}". These run here: ${sessions.map((p) => `&${p.name}`).join(', ')}\n`);
112
- await keepOpen(args, io);
113
- return 1;
114
- }
115
- const label = `&${peer.name}`;
116
- io.stdin.setRawMode(true);
117
- io.stdin.resume();
118
- let how;
119
- try {
120
- for (;;) {
121
- how = await connect(peer, io);
122
- if (how === 'detached') break;
123
- // closed: the session restarting (it comes back under the same registry id), or ended
124
- const id = peer.id;
125
- let back = null;
126
- for (let t = 0; t < BACK_WITHIN_MS && !back; t += 300) {
127
- await new Promise((r) => setTimeout(r, 300));
128
- back = backgroundSessions().find((p) => p.id === id && p.pid !== peer.pid) || null;
129
- }
130
- if (!back) { how = 'ended'; break; }
131
- peer = back;
132
- }
133
- } catch (e) {
134
- io.stdout.write(RESET);
135
- io.stdin.setRawMode(false);
136
- io.stderr.write(`Could not attach to ${label}: ${e.message}\n`);
137
- await keepOpen(args, io);
138
- return 1;
139
- }
140
- io.stdout.write(RESET);
141
- io.stdin.setRawMode(false);
142
- io.stdin.pause();
143
- io.stdout.write(how === 'detached' ? `Detached from ${label}: it goes on in the background (claude-pro attach ${peer.name} comes back).\n` : `${label} has ended.\n`);
144
- if (how !== 'detached') await keepOpen(args, io);
145
- return 0;
146
- }