forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplatform.ts
More file actions
362 lines (334 loc) · 11.5 KB
/
platform.ts
File metadata and controls
362 lines (334 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import { execFileSync, execFile } from 'child_process';
import fs from 'fs';
import { promisify } from 'util';
import os from 'os';
import path from 'path';
const execFileAsync = promisify(execFile);
export const isWindows = process.platform === 'win32';
export const isMac = process.platform === 'darwin';
/**
* Whether the given binary path requires shell execution.
* On Windows, .cmd/.bat files cannot be executed directly by execFileSync.
*/
function needsShell(binPath: string): boolean {
return isWindows && /\.(cmd|bat)$/i.test(binPath);
}
/**
* Extra PATH directories to search for Claude CLI and other tools.
*/
export function getExtraPathDirs(): string[] {
const home = os.homedir();
if (isWindows) {
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
return [
path.join(home, '.local', 'bin'),
path.join(home, '.claude', 'bin'),
path.join(home, '.bun', 'bin'),
path.join(appData, 'npm'),
path.join(localAppData, 'npm'),
path.join(home, '.npm-global', 'bin'),
path.join(home, '.nvm', 'current', 'bin'),
];
}
return [
path.join(home, '.local', 'bin'),
path.join(home, '.claude', 'bin'),
path.join(home, '.bun', 'bin'),
'/usr/local/bin',
'/opt/homebrew/bin',
'/usr/bin',
'/bin',
path.join(home, '.npm-global', 'bin'),
path.join(home, '.nvm', 'current', 'bin'),
];
}
/**
* Classify a Claude CLI binary path by installation method.
*/
export type ClaudeInstallType = 'native' | 'homebrew' | 'npm' | 'bun' | 'unknown';
export function classifyClaudePath(binPath: string): ClaudeInstallType {
const home = os.homedir();
const normalized = binPath.replace(/\\/g, '/');
// Native installer: ~/.local/bin/claude or ~/.claude/bin/claude
if (normalized.includes('/.local/bin/')) return 'native';
if (normalized.includes('/.claude/bin/')) return 'native';
// Bun: ~/.bun/bin/claude
if (normalized.includes('/.bun/bin/') || normalized.includes('/.bun/install/')) return 'bun';
// Homebrew: /opt/homebrew/bin or /usr/local/Cellar or homebrew in path
if (normalized.includes('/homebrew/') || normalized.includes('/Cellar/')) return 'homebrew';
// npm: npm-global, .npm, AppData/npm
if (normalized.includes('/npm') || normalized.includes('npm-global')) return 'npm';
if (normalized === '/usr/local/bin/claude') {
// /usr/local/bin could be npm or homebrew — check symlink target
try {
const real = fs.realpathSync(binPath);
if (real.includes('node_modules')) return 'npm';
if (real.includes('homebrew') || real.includes('Cellar')) return 'homebrew';
if (real.includes('.bun')) return 'bun';
} catch { /* ignore */ }
return 'unknown';
}
if (isWindows) {
const appData = (process.env.APPDATA || '').replace(/\\/g, '/');
const localAppData = (process.env.LOCALAPPDATA || '').replace(/\\/g, '/');
if (appData && normalized.startsWith(appData + '/npm')) return 'npm';
if (localAppData && normalized.startsWith(localAppData + '/npm')) return 'npm';
if (normalized.includes(home.replace(/\\/g, '/') + '/.local/bin')) return 'native';
}
return 'unknown';
}
/**
* Claude CLI candidate installation paths.
* Priority: native install > homebrew > npm (deprecated).
*/
export function getClaudeCandidatePaths(): string[] {
const home = os.homedir();
if (isWindows) {
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
const exts = ['.cmd', '.exe', '.bat', ''];
// Native first, then bun, then npm paths
const baseDirs = [
path.join(home, '.local', 'bin'),
path.join(home, '.claude', 'bin'),
path.join(home, '.bun', 'bin'),
path.join(appData, 'npm'),
path.join(localAppData, 'npm'),
path.join(home, '.npm-global', 'bin'),
];
const candidates: string[] = [];
for (const dir of baseDirs) {
for (const ext of exts) {
candidates.push(path.join(dir, 'claude' + ext));
}
}
return candidates;
}
// macOS/Linux: native first, then bun, then homebrew, then npm paths
return [
path.join(home, '.local', 'bin', 'claude'), // native installer
path.join(home, '.claude', 'bin', 'claude'), // native alt
path.join(home, '.bun', 'bin', 'claude'), // bun global
'/opt/homebrew/bin/claude', // homebrew (Apple Silicon)
'/usr/local/bin/claude', // homebrew (Intel) or npm global
path.join(home, '.npm-global', 'bin', 'claude'), // npm custom prefix
];
}
export interface ClaudeInstallInfo {
path: string;
version: string | null;
type: ClaudeInstallType;
}
/**
* Detect ALL Claude CLI installations on the system.
* Used to warn about conflicts when multiple versions coexist.
*/
export function findAllClaudeBinaries(): ClaudeInstallInfo[] {
const results: ClaudeInstallInfo[] = [];
const seenReal = new Set<string>();
function tryAdd(p: string) {
try {
let realPath: string;
try { realPath = fs.realpathSync(p); } catch { realPath = p; }
if (seenReal.has(realPath)) return;
// On Windows, installers create multiple variants in the same directory:
// native: claude.exe + claude (shell script), npm: claude.cmd + claude, etc.
// Deduplicate by dir + base name stripped of all executable extensions.
// Only record the dirKey AFTER --version succeeds, so a broken .cmd
// wrapper doesn't hide a working .exe in the same directory.
let winDirKey: string | undefined;
if (isWindows) {
winDirKey = path.join(path.dirname(realPath), path.basename(realPath).replace(/\.(exe|cmd|bat)$/i, '')).toLowerCase();
if (seenReal.has(winDirKey)) return;
}
const out = execFileSync(p, ['--version'], {
timeout: 3000,
stdio: 'pipe',
shell: needsShell(p),
encoding: 'utf-8',
});
seenReal.add(realPath);
if (winDirKey) seenReal.add(winDirKey);
results.push({ path: p, version: out.trim() || null, type: classifyClaudePath(p) });
} catch {
// not found at this path
}
}
// Check all known candidate paths
for (const p of getClaudeCandidatePaths()) {
tryAdd(p);
}
// Also scan PATH via which/where to catch bun, custom, or other non-standard installs
try {
const cmd = isWindows ? 'where' : '/usr/bin/which';
const args = isWindows ? ['claude'] : ['-a', 'claude']; // -a = show ALL matches
const result = execFileSync(cmd, args, {
timeout: 3000,
stdio: 'pipe',
env: { ...process.env, PATH: getExpandedPath() },
shell: isWindows,
encoding: 'utf-8',
});
for (const line of result.trim().split(/\r?\n/)) {
const candidate = line.trim();
if (candidate) tryAdd(candidate);
}
} catch {
// which/where failed
}
return results;
}
/**
* Build an expanded PATH string with extra directories, deduped and filtered.
*/
export function getExpandedPath(): string {
const current = process.env.PATH || '';
const parts = current.split(path.delimiter).filter(Boolean);
const seen = new Set(parts);
for (const p of getExtraPathDirs()) {
if (p && !seen.has(p)) {
parts.push(p);
seen.add(p);
}
}
return parts.join(path.delimiter);
}
// TTL cache for findClaudeBinary to avoid repeated filesystem probes.
// Only caches "found" results; "not found" is never cached so a fresh
// install is detected immediately on the next check.
let _cachedBinaryPath: string | undefined | null = null; // null = not cached
let _cachedBinaryTimestamp = 0;
const BINARY_CACHE_TTL = 60_000; // 60 seconds
/**
* Invalidate all cached binary paths.
* Must be called after a new installation so that subsequent SDK calls
* pick up the freshly-installed binary instead of a stale npm/bun path.
*/
export function invalidateClaudePathCache(): void {
_cachedBinaryPath = null;
_cachedBinaryTimestamp = 0;
}
/**
* Find and validate the Claude CLI binary.
* Positive results are cached for 60s; negative results are never cached.
*/
export function findClaudeBinary(): string | undefined {
const now = Date.now();
if (_cachedBinaryPath !== null && now - _cachedBinaryTimestamp < BINARY_CACHE_TTL) {
return _cachedBinaryPath;
}
const found = _findClaudeBinaryUncached();
if (found) {
_cachedBinaryPath = found;
_cachedBinaryTimestamp = now;
} else {
// Don't cache "not found" — user may install CLI any moment
_cachedBinaryPath = null;
}
return found;
}
function _findClaudeBinaryUncached(): string | undefined {
// Try known candidate paths first
for (const p of getClaudeCandidatePaths()) {
try {
execFileSync(p, ['--version'], {
timeout: 3000,
stdio: 'pipe',
shell: needsShell(p),
});
return p;
} catch {
// not found, try next
}
}
// Fallback: use `where` (Windows) or `which` (Unix) with expanded PATH
try {
const cmd = isWindows ? 'where' : '/usr/bin/which';
const args = isWindows ? ['claude'] : ['claude'];
const result = execFileSync(cmd, args, {
timeout: 3000,
stdio: 'pipe',
env: { ...process.env, PATH: getExpandedPath() },
shell: isWindows,
});
// where.exe may return multiple lines; try each with --version validation
const lines = result.toString().trim().split(/\r?\n/);
for (const line of lines) {
const candidate = line.trim();
if (!candidate) continue;
try {
execFileSync(candidate, ['--version'], {
timeout: 3000,
stdio: 'pipe',
shell: needsShell(candidate),
});
return candidate;
} catch {
continue;
}
}
} catch {
// not found
}
return undefined;
}
/**
* Execute claude --version and return the version string.
* Handles .cmd shell execution on Windows.
*/
export async function getClaudeVersion(claudePath: string): Promise<string | null> {
try {
const { stdout } = await execFileAsync(claudePath, ['--version'], {
timeout: 5000,
env: { ...process.env, PATH: getExpandedPath() },
shell: needsShell(claudePath),
});
return stdout.trim() || null;
} catch {
return null;
}
}
/**
* Find Git Bash (bash.exe) on Windows.
* Returns the path to bash.exe or null if not found.
*/
export function findGitBash(): string | null {
// 1. Check user-specified environment variable
const envPath = process.env.CLAUDE_CODE_GIT_BASH_PATH;
if (envPath && fs.existsSync(envPath)) {
return envPath;
}
// 2. Check common installation paths
const commonPaths = [
'C:\\Program Files\\Git\\bin\\bash.exe',
'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
];
for (const p of commonPaths) {
if (fs.existsSync(p)) {
return p;
}
}
// 3. Try to locate git.exe via `where git` and derive bash.exe path
try {
const result = execFileSync('where', ['git'], {
timeout: 3000,
stdio: 'pipe',
shell: true,
});
const lines = result.toString().trim().split(/\r?\n/);
for (const line of lines) {
const gitExe = line.trim();
if (!gitExe) continue;
// git.exe is typically at <GitDir>\cmd\git.exe or <GitDir>\bin\git.exe
const gitDir = path.dirname(path.dirname(gitExe));
const bashPath = path.join(gitDir, 'bin', 'bash.exe');
if (fs.existsSync(bashPath)) {
return bashPath;
}
}
} catch {
// where git failed or timed out
}
return null;
}