@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
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`
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
|
-
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
if (!
|
|
134
|
-
|
|
135
|
-
|
|
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
|
+
}
|
package/src/utils/clipboard.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Directories of this computer for the gateway's web page: what it shows to choose a working directory from
|
|
2
|
+
// (/cd from the page, see App.remoteList). Moved here from the computer service (host.js, removed in 0.8.0), whose
|
|
3
|
+
// listing the page was built for: the fields and the messages (Chinese, as the page is) are the same.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import fsp from 'node:fs/promises';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { normalizeDir } from './paths.js';
|
|
10
|
+
|
|
11
|
+
const MAX_ENTRIES = 1000;
|
|
12
|
+
const MAX_RECENT = 15;
|
|
13
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
14
|
+
|
|
15
|
+
const describeFsError = (e, dir) => (e.code === 'ENOENT' || e.code === 'ENOTDIR' ? `目录不存在:${dir}`
|
|
16
|
+
: e.code === 'EACCES' || e.code === 'EPERM' ? `没有权限读取:${dir}`
|
|
17
|
+
: `读取 ${dir} 失败:${e.message}`);
|
|
18
|
+
|
|
19
|
+
let rootsCache = { at: 0, roots: [] };
|
|
20
|
+
async function roots(platform = process.platform) {
|
|
21
|
+
if (platform !== 'win32') return ['/'];
|
|
22
|
+
if (Date.now() - rootsCache.at < 30_000) return rootsCache.roots;
|
|
23
|
+
// a disconnected network drive can take long to answer: 1.5 seconds each, all at once
|
|
24
|
+
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
|
25
|
+
const found = await Promise.all(letters.map((l) => Promise.race([
|
|
26
|
+
fsp.access(`${l}:\\`).then(() => `${l}:\\`, () => null),
|
|
27
|
+
sleep(1500).then(() => null),
|
|
28
|
+
])));
|
|
29
|
+
rootsCache = { at: Date.now(), roots: found.filter(Boolean) };
|
|
30
|
+
return rootsCache.roots;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The directories in `input` (only directories, links to them included), for the page to choose from:
|
|
34
|
+
// {path, parent, sep, entries: [{name, path}], truncated, home, roots, recent}.
|
|
35
|
+
export async function listDirectory(input, { home = os.homedir(), recent = () => [] } = {}) {
|
|
36
|
+
const dir = normalizeDir(input, { home });
|
|
37
|
+
if (!dir) throw new Error(`不是绝对路径:${input}`);
|
|
38
|
+
let st;
|
|
39
|
+
try { st = await fsp.stat(dir); } catch (e) { throw new Error(describeFsError(e, dir)); }
|
|
40
|
+
if (!st.isDirectory()) throw new Error(`不是目录:${dir}`);
|
|
41
|
+
let dirents;
|
|
42
|
+
try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { throw new Error(describeFsError(e, dir)); }
|
|
43
|
+
const entries = [];
|
|
44
|
+
for (const d of dirents) {
|
|
45
|
+
const full = path.join(dir, d.name);
|
|
46
|
+
let isDir = d.isDirectory();
|
|
47
|
+
if (!isDir && d.isSymbolicLink()) {
|
|
48
|
+
// a link to a directory counts, unless it cannot be opened (Windows' old junctions in the profile:
|
|
49
|
+
// "My Documents", "Application Data" ... refuse to be listed)
|
|
50
|
+
try { isDir = (await fsp.stat(full)).isDirectory(); } catch { isDir = false; }
|
|
51
|
+
if (isDir) {
|
|
52
|
+
let handle = null;
|
|
53
|
+
try {
|
|
54
|
+
handle = await fsp.opendir(full);
|
|
55
|
+
await handle.read(); // Windows checks the access at the first read, not at the opening
|
|
56
|
+
} catch {
|
|
57
|
+
isDir = false;
|
|
58
|
+
} finally {
|
|
59
|
+
await handle?.close().catch(() => {});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// ... and the profile's other compatibility junctions ("Application Data", "Recent", the Start Menu in the
|
|
63
|
+
// system's language ...), which Explorer hides: all lead into AppData
|
|
64
|
+
if (isDir && process.platform === 'win32' && dir.toLowerCase() === path.resolve(home).toLowerCase()) {
|
|
65
|
+
try {
|
|
66
|
+
if ((await fsp.realpath(full)).toLowerCase().startsWith(`${path.join(home, 'AppData').toLowerCase()}\\`)) isDir = false;
|
|
67
|
+
} catch { isDir = false; }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (isDir) entries.push({ name: d.name, path: full });
|
|
71
|
+
}
|
|
72
|
+
const hidden = (name) => (name.startsWith('.') ? 1 : 0);
|
|
73
|
+
entries.sort((a, b) => hidden(a.name) - hidden(b.name) || a.name.localeCompare(b.name, undefined, { sensitivity: 'accent', numeric: true }));
|
|
74
|
+
const parent = path.dirname(dir);
|
|
75
|
+
return {
|
|
76
|
+
path: dir,
|
|
77
|
+
parent: parent === dir ? null : parent,
|
|
78
|
+
sep: path.sep,
|
|
79
|
+
entries: entries.slice(0, MAX_ENTRIES),
|
|
80
|
+
truncated: entries.length > MAX_ENTRIES,
|
|
81
|
+
home,
|
|
82
|
+
roots: await roots(),
|
|
83
|
+
recent: recent(),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// The first line of a session file is {type: 'meta', cwd, ...} (see SessionStore.append).
|
|
88
|
+
function sessionCwd(file) {
|
|
89
|
+
let fd = null;
|
|
90
|
+
try {
|
|
91
|
+
fd = fs.openSync(file, 'r');
|
|
92
|
+
const buf = Buffer.alloc(16 * 1024);
|
|
93
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
94
|
+
const meta = JSON.parse(buf.subarray(0, n).toString('utf8').split('\n')[0]);
|
|
95
|
+
return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
} finally {
|
|
99
|
+
if (fd !== null) fs.closeSync(fd);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Where claude-pro sessions ran lately on this computer, newest first: [{path, at}] of the directories that are
|
|
104
|
+
// still there. `projects`: the config directory's projects folder. One line read per project (its newest session's
|
|
105
|
+
// first line).
|
|
106
|
+
export function recentDirectories({ projects, max = MAX_RECENT }) {
|
|
107
|
+
let dirs = [];
|
|
108
|
+
try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
|
|
109
|
+
const found = [];
|
|
110
|
+
for (const d of dirs) {
|
|
111
|
+
const sub = path.join(projects, d.name);
|
|
112
|
+
let newest = null;
|
|
113
|
+
try {
|
|
114
|
+
for (const f of fs.readdirSync(sub)) {
|
|
115
|
+
if (!f.endsWith('.jsonl')) continue;
|
|
116
|
+
const m = fs.statSync(path.join(sub, f)).mtimeMs;
|
|
117
|
+
if (!newest || m > newest.m) newest = { f, m };
|
|
118
|
+
}
|
|
119
|
+
} catch { continue; }
|
|
120
|
+
if (!newest) continue;
|
|
121
|
+
const cwd = sessionCwd(path.join(sub, newest.f));
|
|
122
|
+
if (cwd) found.push({ path: path.resolve(cwd), at: newest.m });
|
|
123
|
+
}
|
|
124
|
+
found.sort((a, b) => b.at - a.at);
|
|
125
|
+
const seen = new Set();
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const r of found) {
|
|
128
|
+
const key = process.platform === 'win32' ? r.path.toLowerCase() : r.path;
|
|
129
|
+
if (seen.has(key)) continue;
|
|
130
|
+
seen.add(key);
|
|
131
|
+
try { if (!fs.statSync(r.path).isDirectory()) continue; } catch { continue; }
|
|
132
|
+
out.push({ path: r.path, at: new Date(r.at).toISOString() });
|
|
133
|
+
if (out.length >= max) break;
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
package/src/utils/encoding.js
CHANGED
|
@@ -10,6 +10,27 @@ const strictUtf8 = new TextDecoder('utf-8', { fatal: true });
|
|
|
10
10
|
const lenientUtf8 = new TextDecoder('utf-8');
|
|
11
11
|
const strictGbk = new TextDecoder('gbk', { fatal: true }); // the WHATWG gbk decoder, which is the gb18030 one
|
|
12
12
|
|
|
13
|
+
// Whether bytes that are not valid UTF-8 as a whole are still UTF-8 text with a few bad bytes (a character cut at
|
|
14
|
+
// the end of a line by `cut -c` or `head -c`, a stray Latin-1 byte), rather than text in another encoding. Chinese
|
|
15
|
+
// UTF-8 is often valid GBK by chance (E4 B8 AD E6 96 87, "中文", reads as "涓枃"), so trying GBK first turned such
|
|
16
|
+
// a line or file into mojibake; GBK text read as UTF-8, the other way round, is mostly invalid sequences, with a
|
|
17
|
+
// valid two-byte character here and there by chance. An incomplete sequence counts once, however long.
|
|
18
|
+
export function mostlyUtf8(buf) {
|
|
19
|
+
let good = 0;
|
|
20
|
+
let bad = 0;
|
|
21
|
+
for (let i = 0; i < buf.length;) {
|
|
22
|
+
const b = buf[i];
|
|
23
|
+
if (b < 0x80) { i++; continue; }
|
|
24
|
+
const n = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0;
|
|
25
|
+
let k = 1;
|
|
26
|
+
while (n && k < n && i + k < buf.length && (buf[i + k] & 0xc0) === 0x80) k++;
|
|
27
|
+
if (n && k === n) good++;
|
|
28
|
+
else bad++;
|
|
29
|
+
i += n ? k : 1;
|
|
30
|
+
}
|
|
31
|
+
return bad === 0 || good >= 4 * bad;
|
|
32
|
+
}
|
|
33
|
+
|
|
13
34
|
// {text, encoding: 'utf8'|'utf16le'|'utf16be'|'gbk', bom, lossy}, or null for binary data. `lossy`: writing the
|
|
14
35
|
// text back would not give these bytes (undecodable bytes became U+FFFD, or GB18030 forms GBK cannot write).
|
|
15
36
|
// `writable: false` skips that check for a GBK file, for a caller that only reads (Grep).
|
|
@@ -20,7 +41,7 @@ export function decodeText(buf, { writable = true } = {}) {
|
|
|
20
41
|
const body = bom ? buf.subarray(3) : buf;
|
|
21
42
|
if (body.subarray(0, 8000).includes(0)) return null;
|
|
22
43
|
try { return { text: strictUtf8.decode(body), encoding: 'utf8', bom, lossy: false }; } catch { /* not UTF-8 */ }
|
|
23
|
-
if (!bom) {
|
|
44
|
+
if (!bom && !mostlyUtf8(body)) {
|
|
24
45
|
let text = null;
|
|
25
46
|
try { text = strictGbk.decode(body); } catch { /* not GBK either */ }
|
|
26
47
|
// Writable only when the text turns back into exactly these bytes (GB18030's four-byte forms do not).
|
|
@@ -124,7 +145,7 @@ export function decodeOutput(buf) {
|
|
|
124
145
|
const line = buf.subarray(start, end);
|
|
125
146
|
let text = null;
|
|
126
147
|
try { text = strictUtf8.decode(line); } catch {
|
|
127
|
-
const legacy = consoleDecoder();
|
|
148
|
+
const legacy = mostlyUtf8(line) ? null : consoleDecoder();
|
|
128
149
|
if (legacy) { try { text = legacy.decode(line); } catch { /* neither */ } }
|
|
129
150
|
}
|
|
130
151
|
out += text ?? lenientUtf8.decode(line);
|
package/src/utils/paths.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
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
|
-
|
|
49
|
-
|
|
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() } = {}) {
|