forked from 777genius/claude-code-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstaller.ts
More file actions
1709 lines (1544 loc) · 53.5 KB
/
Copy pathinstaller.ts
File metadata and controls
1709 lines (1544 loc) · 53.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Native Installer Implementation
*
* This module implements the file-based native installer system described in
* docs/native-installer.md. It provides:
* - Directory structure management with symlinks
* - Version installation and activation
* - Multi-process safety with locking
* - Simple fallback mechanism using modification time
* - Support for both JS and native builds
*/
import { constants as fsConstants, type Stats } from 'fs'
import {
access,
chmod,
copyFile,
lstat,
mkdir,
readdir,
readlink,
realpath,
rename,
rm,
rmdir,
stat,
symlink,
unlink,
writeFile,
} from 'fs/promises'
import { homedir } from 'os'
import { basename, delimiter, dirname, join, resolve } from 'path'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { getMaxVersion, shouldSkipVersion } from '../autoUpdater.js'
import { registerCleanup } from '../cleanupRegistry.js'
import { getGlobalConfig, saveGlobalConfig } from '../config.js'
import { logForDebugging } from '../debug.js'
import { getCurrentInstallationType } from '../doctorDiagnostic.js'
import { env } from '../env.js'
import { envDynamic } from '../envDynamic.js'
import { isEnvTruthy } from '../envUtils.js'
import { errorMessage, getErrnoCode, isENOENT, toError } from '../errors.js'
import { execFileNoThrowWithCwd } from '../execFileNoThrow.js'
import { getShellType } from '../localInstaller.js'
import * as lockfile from '../lockfile.js'
import { logError } from '../log.js'
import { gt, gte } from '../semver.js'
import {
filterClaudeAliases,
getShellConfigPaths,
readFileLines,
writeFileLines,
} from '../shellConfig.js'
import { sleep } from '../sleep.js'
import {
getUserBinDir,
getXDGCacheHome,
getXDGDataHome,
getXDGStateHome,
} from '../xdg.js'
import { downloadVersion, getLatestVersion } from './download.js'
import {
acquireProcessLifetimeLock,
cleanupStaleLocks,
isLockActive,
isPidBasedLockingEnabled,
readLockContent,
withLock,
} from './pidLock.js'
export const VERSION_RETENTION_COUNT = 2
// 7 days in milliseconds - used for mtime-based lock stale timeout.
// This is long enough to survive laptop sleep durations while still
// allowing cleanup of abandoned locks from crashed processes within a reasonable time.
const LOCK_STALE_MS = 7 * 24 * 60 * 60 * 1000
export type SetupMessage = {
message: string
userActionRequired: boolean
type: 'path' | 'alias' | 'info' | 'error'
}
export function getPlatform(): string {
// Use env.platform which already handles platform detection and defaults to 'linux'
const os = env.platform
const arch =
process.arch === 'x64' ? 'x64' : process.arch === 'arm64' ? 'arm64' : null
if (!arch) {
const error = new Error(`Unsupported architecture: ${process.arch}`)
logForDebugging(
`Native installer does not support architecture: ${process.arch}`,
{ level: 'error' },
)
throw error
}
// Check for musl on Linux and adjust platform accordingly
if (os === 'linux' && envDynamic.isMuslEnvironment()) {
return `linux-${arch}-musl`
}
return `${os}-${arch}`
}
export function getBinaryName(platform: string): string {
return platform.startsWith('win32') ? 'claude.exe' : 'claude'
}
function getBaseDirectories() {
const platform = getPlatform()
const executableName = getBinaryName(platform)
return {
// Data directories (permanent storage)
versions: join(getXDGDataHome(), 'claude', 'versions'),
// Cache directories (can be deleted)
staging: join(getXDGCacheHome(), 'claude', 'staging'),
// State directories
locks: join(getXDGStateHome(), 'claude', 'locks'),
// User bin
executable: join(getUserBinDir(), executableName),
}
}
async function isPossibleClaudeBinary(filePath: string): Promise<boolean> {
try {
const stats = await stat(filePath)
// before download, the version lock file (located at the same filePath) will be size 0
// also, we allow small sizes because we want to treat small wrapper scripts as valid
if (!stats.isFile() || stats.size === 0) {
return false
}
// Check if file is executable. Note: On Windows, this relies on file extensions
// (.exe, .bat, .cmd) and ACL permissions rather than Unix permission bits,
// so it may not work perfectly for all executable files on Windows.
await access(filePath, fsConstants.X_OK)
return true
} catch {
return false
}
}
async function getVersionPaths(version: string) {
const dirs = getBaseDirectories()
// Create directories, but not the executable path (which is a file)
const dirsToCreate = [dirs.versions, dirs.staging, dirs.locks]
await Promise.all(dirsToCreate.map(dir => mkdir(dir, { recursive: true })))
// Ensure parent directory of executable exists
const executableParentDir = dirname(dirs.executable)
await mkdir(executableParentDir, { recursive: true })
const installPath = join(dirs.versions, version)
// Create an empty file if it doesn't exist
try {
await stat(installPath)
} catch {
await writeFile(installPath, '', { encoding: 'utf8' })
}
return {
stagingPath: join(dirs.staging, version),
installPath,
}
}
// Execute a callback while holding a lock on a version file
// Returns false if the file is already locked, true if callback executed
async function tryWithVersionLock(
versionFilePath: string,
callback: () => void | Promise<void>,
retries = 0,
): Promise<boolean> {
const dirs = getBaseDirectories()
const lockfilePath = getLockFilePathFromVersionPath(dirs, versionFilePath)
// Ensure the locks directory exists
await mkdir(dirs.locks, { recursive: true })
if (isPidBasedLockingEnabled()) {
// Use PID-based locking with optional retries
let attempts = 0
const maxAttempts = retries + 1
const minTimeout = retries > 0 ? 1000 : 100
const maxTimeout = retries > 0 ? 5000 : 500
while (attempts < maxAttempts) {
const success = await withLock(
versionFilePath,
lockfilePath,
async () => {
try {
await callback()
} catch (error) {
logError(error)
throw error
}
},
)
if (success) {
logEvent('tengu_version_lock_acquired', {
is_pid_based: true,
is_lifetime_lock: false,
attempts: attempts + 1,
})
return true
}
attempts++
if (attempts < maxAttempts) {
// Wait before retrying with exponential backoff
const timeout = Math.min(
minTimeout * Math.pow(2, attempts - 1),
maxTimeout,
)
await sleep(timeout)
}
}
logEvent('tengu_version_lock_failed', {
is_pid_based: true,
is_lifetime_lock: false,
attempts: maxAttempts,
})
logLockAcquisitionError(
versionFilePath,
new Error('Lock held by another process'),
)
return false
}
// Use mtime-based locking (proper-lockfile) with 30-day stale timeout
let release: (() => Promise<void>) | null = null
try {
// Lock acquisition phase - catch lock errors and return false
// Use 30 days for stale to match lockCurrentVersion() - this ensures we never
// consider a running process's lock as stale during normal usage (including
// laptop sleep). 30 days allows eventual cleanup of abandoned locks from
// crashed processes while being long enough for any realistic session.
try {
release = await lockfile.lock(versionFilePath, {
stale: LOCK_STALE_MS,
retries: {
retries,
minTimeout: retries > 0 ? 1000 : 100,
maxTimeout: retries > 0 ? 5000 : 500,
},
lockfilePath,
// Handle lock compromise gracefully to prevent unhandled rejections
// This can happen if another process deletes the lock directory while we hold it
onCompromised: (err: Error) => {
logForDebugging(
`NON-FATAL: Version lock was compromised during operation: ${err.message}`,
{ level: 'info' },
)
},
})
} catch (lockError) {
logEvent('tengu_version_lock_failed', {
is_pid_based: false,
is_lifetime_lock: false,
})
logLockAcquisitionError(versionFilePath, lockError)
return false
}
// Operation phase - log errors but let them propagate
try {
await callback()
logEvent('tengu_version_lock_acquired', {
is_pid_based: false,
is_lifetime_lock: false,
})
return true
} catch (error) {
logError(error)
throw error
}
} finally {
if (release) {
await release()
}
}
}
async function atomicMoveToInstallPath(
stagedBinaryPath: string,
installPath: string,
) {
// Create installation directory if it doesn't exist
await mkdir(dirname(installPath), { recursive: true })
// Move from staging to final location atomically
const tempInstallPath = `${installPath}.tmp.${process.pid}.${Date.now()}`
try {
// Copy to temp next to install path, then rename. A direct rename from staging
// would fail with EXDEV if staging and install are on different filesystems.
await copyFile(stagedBinaryPath, tempInstallPath)
await chmod(tempInstallPath, 0o755)
await rename(tempInstallPath, installPath)
logForDebugging(`Atomically installed binary to ${installPath}`)
} catch (error) {
// Clean up temp file if it exists
try {
await unlink(tempInstallPath)
} catch {
// Ignore cleanup errors
}
throw error
}
}
async function installVersionFromPackage(
stagingPath: string,
installPath: string,
) {
try {
// Extract binary from npm package structure in staging
const nodeModulesDir = join(stagingPath, 'node_modules', '@anthropic-ai')
const entries = await readdir(nodeModulesDir)
const nativePackage = entries.find((entry: string) =>
entry.startsWith('claude-cli-native-'),
)
if (!nativePackage) {
logEvent('tengu_native_install_package_failure', {
stage_find_package: true,
error_package_not_found: true,
})
const error = new Error('Could not find platform-specific native package')
throw error
}
const stagedBinaryPath = join(nodeModulesDir, nativePackage, 'cli')
try {
await stat(stagedBinaryPath)
} catch {
logEvent('tengu_native_install_package_failure', {
stage_binary_exists: true,
error_binary_not_found: true,
})
const error = new Error('Native binary not found in staged package')
throw error
}
await atomicMoveToInstallPath(stagedBinaryPath, installPath)
// Clean up staging directory
await rm(stagingPath, { recursive: true, force: true })
logEvent('tengu_native_install_package_success', {})
} catch (error) {
// Log if not already logged above
const msg = errorMessage(error)
if (
!msg.includes('Could not find platform-specific') &&
!msg.includes('Native binary not found')
) {
logEvent('tengu_native_install_package_failure', {
stage_atomic_move: true,
error_move_failed: true,
})
}
logError(toError(error))
throw error
}
}
async function installVersionFromBinary(
stagingPath: string,
installPath: string,
) {
try {
// For direct binary downloads (GCS, generic bucket), the binary is directly in staging
const platform = getPlatform()
const binaryName = getBinaryName(platform)
const stagedBinaryPath = join(stagingPath, binaryName)
try {
await stat(stagedBinaryPath)
} catch {
logEvent('tengu_native_install_binary_failure', {
stage_binary_exists: true,
error_binary_not_found: true,
})
const error = new Error('Staged binary not found')
throw error
}
await atomicMoveToInstallPath(stagedBinaryPath, installPath)
// Clean up staging directory
await rm(stagingPath, { recursive: true, force: true })
logEvent('tengu_native_install_binary_success', {})
} catch (error) {
if (!errorMessage(error).includes('Staged binary not found')) {
logEvent('tengu_native_install_binary_failure', {
stage_atomic_move: true,
error_move_failed: true,
})
}
logError(toError(error))
throw error
}
}
async function installVersion(
stagingPath: string,
installPath: string,
downloadType: 'npm' | 'binary',
) {
// Use the explicit download type instead of guessing
if (downloadType === 'npm') {
await installVersionFromPackage(stagingPath, installPath)
} else {
await installVersionFromBinary(stagingPath, installPath)
}
}
/**
* Performs the core update operation: download (if needed), install, and update symlink.
* Returns whether a new install was performed (vs just updating symlink).
*/
async function performVersionUpdate(
version: string,
forceReinstall: boolean,
): Promise<boolean> {
const { stagingPath: baseStagingPath, installPath } =
await getVersionPaths(version)
const { executable: executablePath } = getBaseDirectories()
// For lockless updates, use a unique staging path to avoid conflicts between concurrent downloads
const stagingPath = isEnvTruthy(process.env.ENABLE_LOCKLESS_UPDATES)
? `${baseStagingPath}.${process.pid}.${Date.now()}`
: baseStagingPath
// Only download if not already installed (or if force reinstall)
const needsInstall = !(await versionIsAvailable(version)) || forceReinstall
if (needsInstall) {
logForDebugging(
forceReinstall
? `Force reinstalling native installer version ${version}`
: `Downloading native installer version ${version}`,
)
const downloadType = await downloadVersion(version, stagingPath)
await installVersion(stagingPath, installPath, downloadType)
} else {
logForDebugging(`Version ${version} already installed, updating symlink`)
}
// Create direct symlink from ~/.local/bin/claude to the version binary
await removeDirectoryIfEmpty(executablePath)
await updateSymlink(executablePath, installPath)
// Verify the executable was actually created/updated
if (!(await isPossibleClaudeBinary(executablePath))) {
let installPathExists = false
try {
await stat(installPath)
installPathExists = true
} catch {
// installPath doesn't exist
}
throw new Error(
`Failed to create executable at ${executablePath}. ` +
`Source file exists: ${installPathExists}. ` +
`Check write permissions to ${executablePath}.`,
)
}
return needsInstall
}
async function versionIsAvailable(version: string): Promise<boolean> {
const { installPath } = await getVersionPaths(version)
return isPossibleClaudeBinary(installPath)
}
async function updateLatest(
channelOrVersion: string,
forceReinstall: boolean = false,
): Promise<{
success: boolean
latestVersion: string
lockFailed?: boolean
lockHolderPid?: number
}> {
const startTime = Date.now()
let version = await getLatestVersion(channelOrVersion)
const { executable: executablePath } = getBaseDirectories()
logForDebugging(`Checking for native installer update to version ${version}`)
// Check if max version is set (server-side kill switch for auto-updates)
if (!forceReinstall) {
const maxVersion = await getMaxVersion()
if (maxVersion && gt(version, maxVersion)) {
logForDebugging(
`Native installer: maxVersion ${maxVersion} is set, capping update from ${version} to ${maxVersion}`,
)
// If we're already at or above maxVersion, skip the update entirely
if (gte(MACRO.VERSION, maxVersion)) {
logForDebugging(
`Native installer: current version ${MACRO.VERSION} is already at or above maxVersion ${maxVersion}, skipping update`,
)
logEvent('tengu_native_update_skipped_max_version', {
latency_ms: Date.now() - startTime,
max_version:
maxVersion as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
available_version:
version as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return { success: true, latestVersion: version }
}
version = maxVersion
}
}
// Early exit: if we're already running this exact version AND both the version binary
// and executable exist and are valid. We need to proceed if the executable doesn't exist,
// is invalid (e.g., empty/corrupted from a failed install), or we're running via npx.
if (
!forceReinstall &&
version === MACRO.VERSION &&
(await versionIsAvailable(version)) &&
(await isPossibleClaudeBinary(executablePath))
) {
logForDebugging(`Found ${version} at ${executablePath}, skipping install`)
logEvent('tengu_native_update_complete', {
latency_ms: Date.now() - startTime,
was_new_install: false,
was_force_reinstall: false,
was_already_running: true,
})
return { success: true, latestVersion: version }
}
// Check if this version should be skipped due to minimumVersion setting
if (!forceReinstall && shouldSkipVersion(version)) {
logEvent('tengu_native_update_skipped_minimum_version', {
latency_ms: Date.now() - startTime,
target_version:
version as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return { success: true, latestVersion: version }
}
// Track if we're actually installing or just symlinking
let wasNewInstall = false
let latencyMs: number
if (isEnvTruthy(process.env.ENABLE_LOCKLESS_UPDATES)) {
// Lockless: rely on atomic operations, errors propagate
wasNewInstall = await performVersionUpdate(version, forceReinstall)
latencyMs = Date.now() - startTime
} else {
// Lock-based updates
const { installPath } = await getVersionPaths(version)
// If force reinstall, remove any existing lock to bypass stale locks
if (forceReinstall) {
await forceRemoveLock(installPath)
}
const lockAcquired = await tryWithVersionLock(
installPath,
async () => {
wasNewInstall = await performVersionUpdate(version, forceReinstall)
},
3, // retries
)
latencyMs = Date.now() - startTime
// Lock acquisition failed - get lock holder PID for error message
if (!lockAcquired) {
const dirs = getBaseDirectories()
let lockHolderPid: number | undefined
if (isPidBasedLockingEnabled()) {
const lockfilePath = getLockFilePathFromVersionPath(dirs, installPath)
if (isLockActive(lockfilePath)) {
lockHolderPid = readLockContent(lockfilePath)?.pid
}
}
logEvent('tengu_native_update_lock_failed', {
latency_ms: latencyMs,
lock_holder_pid: lockHolderPid,
})
return {
success: false,
latestVersion: version,
lockFailed: true,
lockHolderPid,
}
}
}
logEvent('tengu_native_update_complete', {
latency_ms: latencyMs,
was_new_install: wasNewInstall,
was_force_reinstall: forceReinstall,
})
logForDebugging(`Successfully updated to version ${version}`)
return { success: true, latestVersion: version }
}
// Exported for testing
export async function removeDirectoryIfEmpty(path: string): Promise<void> {
// rmdir alone handles all cases: ENOTDIR if path is a file, ENOTEMPTY if
// directory is non-empty, ENOENT if missing. No need to stat+readdir first.
try {
await rmdir(path)
logForDebugging(`Removed empty directory at ${path}`)
} catch (error) {
const code = getErrnoCode(error)
// Expected cases (not-a-dir, missing, not-empty) — silently skip.
// ENOTDIR is the normal path: executablePath is typically a symlink.
if (code !== 'ENOTDIR' && code !== 'ENOENT' && code !== 'ENOTEMPTY') {
logForDebugging(`Could not remove directory at ${path}: ${error}`)
}
}
}
async function updateSymlink(
symlinkPath: string,
targetPath: string,
): Promise<boolean> {
const platform = getPlatform()
const isWindows = platform.startsWith('win32')
// On Windows, directly copy the executable instead of creating a symlink
if (isWindows) {
try {
// Ensure parent directory exists
const parentDir = dirname(symlinkPath)
await mkdir(parentDir, { recursive: true })
// Check if file already exists and has same content
let existingStats: Stats | undefined
try {
existingStats = await stat(symlinkPath)
} catch {
// symlinkPath doesn't exist
}
if (existingStats) {
try {
const targetStats = await stat(targetPath)
// If sizes match, assume files are the same (avoid reading large files)
if (existingStats.size === targetStats.size) {
return false
}
} catch {
// Continue with copy if we can't compare
}
// Use rename strategy to handle file locking on Windows
// Rename always works even for running executables, unlike delete
const oldFileName = `${symlinkPath}.old.${Date.now()}`
await rename(symlinkPath, oldFileName)
// Try to copy new executable, with rollback on failure
try {
await copyFile(targetPath, symlinkPath)
// Success - try immediate cleanup of old file (non-blocking)
try {
await unlink(oldFileName)
} catch {
// File still running - ignore, Windows will clean up eventually
}
} catch (copyError) {
// Copy failed - restore the old executable
try {
await rename(oldFileName, symlinkPath)
} catch (restoreError) {
// Critical: User left without working executable - prioritize restore error
const errorWithCause = new Error(
`Failed to restore old executable: ${restoreError}`,
{ cause: copyError },
)
logError(errorWithCause)
throw errorWithCause
}
throw copyError
}
} else {
// First-time installation (no existing file to rename)
// Copy the executable directly; handle ENOENT from copyFile itself
// rather than a stat() pre-check (avoids TOCTOU + extra syscall)
try {
await copyFile(targetPath, symlinkPath)
} catch (e) {
if (isENOENT(e)) {
throw new Error(`Source file does not exist: ${targetPath}`)
}
throw e
}
}
// chmod is not needed on Windows - executability is determined by .exe extension
return true
} catch (error) {
logError(
new Error(
`Failed to copy executable from ${targetPath} to ${symlinkPath}: ${error}`,
),
)
return false
}
}
// For non-Windows platforms, use symlinks as before
// Ensure parent directory exists (same as Windows path above)
const parentDir = dirname(symlinkPath)
try {
await mkdir(parentDir, { recursive: true })
logForDebugging(`Created directory ${parentDir} for symlink`)
} catch (mkdirError) {
logError(
new Error(`Failed to create directory ${parentDir}: ${mkdirError}`),
)
return false
}
// Check if symlink already exists and points to the correct target
try {
let symlinkExists = false
try {
await stat(symlinkPath)
symlinkExists = true
} catch {
// symlinkPath doesn't exist
}
if (symlinkExists) {
try {
const currentTarget = await readlink(symlinkPath)
const resolvedCurrentTarget = resolve(
dirname(symlinkPath),
currentTarget,
)
const resolvedTargetPath = resolve(targetPath)
if (resolvedCurrentTarget === resolvedTargetPath) {
return false
}
} catch {
// Path exists but is not a symlink - will remove it below
}
// Remove existing file/symlink before creating new one
await unlink(symlinkPath)
}
} catch (error) {
logError(new Error(`Failed to check/remove existing symlink: ${error}`))
}
// Use atomic rename to avoid race conditions. Create symlink with temporary name
// then atomically rename to final name. This ensures the symlink always exists
// and is always valid, even with concurrent updates.
const tempSymlink = `${symlinkPath}.tmp.${process.pid}.${Date.now()}`
try {
await symlink(targetPath, tempSymlink)
// Atomically rename to final name (replaces existing)
await rename(tempSymlink, symlinkPath)
logForDebugging(
`Atomically updated symlink ${symlinkPath} -> ${targetPath}`,
)
return true
} catch (error) {
// Clean up temp symlink if it exists
try {
await unlink(tempSymlink)
} catch {
// Ignore cleanup errors
}
logError(
new Error(
`Failed to create symlink from ${symlinkPath} to ${targetPath}: ${error}`,
),
)
return false
}
}
export async function checkInstall(
force: boolean = false,
): Promise<SetupMessage[]> {
// Skip all installation checks if disabled via environment variable
if (isEnvTruthy(process.env.DISABLE_INSTALLATION_CHECKS)) {
return []
}
// Get the actual installation type and config
const installationType = await getCurrentInstallationType()
// Skip checks for development builds - config.installMethod from a previous
// native installation shouldn't trigger warnings when running dev builds
if (installationType === 'development') {
return []
}
const config = getGlobalConfig()
// Only show warnings if:
// 1. User is actually running from native installation, OR
// 2. User has explicitly set installMethod to 'native' in config (they're trying to use native)
// 3. force is true (used during installation process)
const shouldCheckNative =
force || installationType === 'native' || config.installMethod === 'native'
if (!shouldCheckNative) {
return []
}
const dirs = getBaseDirectories()
const messages: SetupMessage[] = []
const localBinDir = dirname(dirs.executable)
const resolvedLocalBinPath = resolve(localBinDir)
const platform = getPlatform()
const isWindows = platform.startsWith('win32')
// Check if bin directory exists
try {
await access(localBinDir)
} catch {
messages.push({
message: `installMethod is native, but directory ${localBinDir} does not exist`,
userActionRequired: true,
type: 'error',
})
}
// Check if claude executable exists and is valid.
// On non-Windows, call readlink directly and route errno — ENOENT means
// the executable is missing, EINVAL means it exists but isn't a symlink.
// This avoids an access()→readlink() TOCTOU where deletion between the
// two calls produces a misleading "Not a symlink" diagnostic.
// isPossibleClaudeBinary stats the path internally, so we don't pre-check
// with access() — that would be a TOCTOU between access and the stat.
if (isWindows) {
// On Windows it's a copied executable, not a symlink
if (!(await isPossibleClaudeBinary(dirs.executable))) {
messages.push({
message: `installMethod is native, but claude command is missing or invalid at ${dirs.executable}`,
userActionRequired: true,
type: 'error',
})
}
} else {
try {
const target = await readlink(dirs.executable)
const absoluteTarget = resolve(dirname(dirs.executable), target)
if (!(await isPossibleClaudeBinary(absoluteTarget))) {
messages.push({
message: `Claude symlink points to missing or invalid binary: ${target}`,
userActionRequired: true,
type: 'error',
})
}
} catch (e) {
if (isENOENT(e)) {
messages.push({
message: `installMethod is native, but claude command not found at ${dirs.executable}`,
userActionRequired: true,
type: 'error',
})
} else {
// EINVAL (not a symlink) or other — check as regular binary
if (!(await isPossibleClaudeBinary(dirs.executable))) {
messages.push({
message: `${dirs.executable} exists but is not a valid Claude binary`,
userActionRequired: true,
type: 'error',
})
}
}
}
}
// Check if bin directory is in PATH
const isInCurrentPath = (process.env.PATH || '')
.split(delimiter)
.some(entry => {
try {
const resolvedEntry = resolve(entry)
// On Windows, perform case-insensitive comparison for paths
if (isWindows) {
return (
resolvedEntry.toLowerCase() === resolvedLocalBinPath.toLowerCase()
)
}
return resolvedEntry === resolvedLocalBinPath
} catch {
return false
}
})
if (!isInCurrentPath) {
if (isWindows) {
// Windows-specific PATH instructions
const windowsBinPath = localBinDir.replace(/\//g, '\\')
messages.push({
message: `Native installation exists but ${windowsBinPath} is not in your PATH. Add it by opening: System Properties → Environment Variables → Edit User PATH → New → Add the path above. Then restart your terminal.`,
userActionRequired: true,
type: 'path',
})
} else {
// Unix-style PATH instructions
const shellType = getShellType()
const configPaths = getShellConfigPaths()
const configFile = configPaths[shellType as keyof typeof configPaths]
const displayPath = configFile
? configFile.replace(homedir(), '~')
: 'your shell config file'
messages.push({
message: `Native installation exists but ~/.local/bin is not in your PATH. Run:\n\necho 'export PATH="$HOME/.local/bin:$PATH"' >> ${displayPath} && source ${displayPath}`,
userActionRequired: true,
type: 'path',
})
}
}
return messages
}
type InstallLatestResult = {
latestVersion: string | null
wasUpdated: boolean
lockFailed?: boolean
lockHolderPid?: number
}
// In-process singleflight guard. NativeAutoUpdater remounts whenever the
// prompt suggestions overlay toggles (PromptInput.tsx:2916), and the
// isUpdating guard does not survive the remount. Each remount kicked off a
// fresh 271MB binary download while previous ones were still in flight.
// Telemetry: session 42fed33f saw arrayBuffers climb to 91GB at ~650MB/s.
let inFlightInstall: Promise<InstallLatestResult> | null = null
export function installLatest(
channelOrVersion: string,
forceReinstall: boolean = false,
): Promise<InstallLatestResult> {
if (forceReinstall) {
return installLatestImpl(channelOrVersion, forceReinstall)
}
if (inFlightInstall) {
logForDebugging('installLatest: joining in-flight call')
return inFlightInstall
}
const promise = installLatestImpl(channelOrVersion, forceReinstall)
inFlightInstall = promise
const clear = (): void => {
inFlightInstall = null
}
void promise.then(clear, clear)
return promise
}
async function installLatestImpl(
channelOrVersion: string,
forceReinstall: boolean = false,
): Promise<InstallLatestResult> {
const updateResult = await updateLatest(channelOrVersion, forceReinstall)
if (!updateResult.success) {
return {
latestVersion: null,
wasUpdated: false,
lockFailed: updateResult.lockFailed,
lockHolderPid: updateResult.lockHolderPid,
}
}
// Installation succeeded (early return above covers failure). Mark as native
// and disable legacy auto-updater to protect symlinks.
const config = getGlobalConfig()
if (config.installMethod !== 'native') {
saveGlobalConfig(current => ({
...current,
installMethod: 'native',
// Disable legacy auto-updater to prevent npm sessions from deleting native symlinks.
// Native installations use NativeAutoUpdater instead, which respects native installation.
autoUpdates: false,