forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstalledPluginsManager.ts
More file actions
1268 lines (1122 loc) · 40.4 KB
/
Copy pathinstalledPluginsManager.ts
File metadata and controls
1268 lines (1122 loc) · 40.4 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
/**
* Manages plugin installation metadata stored in installed_plugins.json
*
* This module separates plugin installation state (global) from enabled/disabled
* state (per-repository). The installed_plugins.json file tracks:
* - Which plugins are installed globally
* - Installation metadata (version, timestamps, paths)
*
* The enabled/disabled state remains in .claude/settings.json for per-repo control.
*
* Rationale: Installation is global (a plugin is either on disk or not), while
* enabled/disabled state is per-repository (different projects may want different
* plugins active).
*/
import { dirname, join } from 'path'
import { logForDebugging } from '../debug.js'
import { errorMessage, isENOENT, toError } from '../errors.js'
import { getFsImplementation } from '../fsOperations.js'
import { logError } from '../log.js'
import {
jsonParse,
jsonStringify,
writeFileSync_DEPRECATED,
} from '../slowOperations.js'
import { getPluginsDirectory } from './pluginDirectories.js'
import {
type InstalledPlugin,
InstalledPluginsFileSchemaV1,
InstalledPluginsFileSchemaV2,
type InstalledPluginsFileV1,
type InstalledPluginsFileV2,
type PluginInstallationEntry,
type PluginScope,
} from './schemas.js'
// Type alias for V2 plugins map
type InstalledPluginsMapV2 = Record<string, PluginInstallationEntry[]>
// Type for persistable scopes (excludes 'flag' which is session-only)
export type PersistableScope = Exclude<PluginScope, never> // All scopes are persistable in the schema
import { getOriginalCwd } from '../../bootstrap/state.js'
import { getCwd } from '../cwd.js'
import { getHeadForDir } from '../git/gitFilesystem.js'
import type { EditableSettingSource } from '../settings/constants.js'
import {
getSettings_DEPRECATED,
getSettingsForSource,
} from '../settings/settings.js'
import { getPluginById } from './marketplaceManager.js'
import {
parsePluginIdentifier,
settingSourceToScope,
} from './pluginIdentifier.js'
import { getPluginCachePath, getVersionedCachePath } from './pluginLoader.js'
// Migration state to prevent running migration multiple times per session
let migrationCompleted = false
/**
* Memoized cache of installed plugins data (V2 format)
* Cleared by clearInstalledPluginsCache() when file is modified.
* Prevents repeated filesystem reads within a single CLI session.
*/
let installedPluginsCacheV2: InstalledPluginsFileV2 | null = null
/**
* Session-level snapshot of installed plugins at startup.
* This is what the running session uses - it's NOT updated by background operations.
* Background updates modify the disk file only.
*/
let inMemoryInstalledPlugins: InstalledPluginsFileV2 | null = null
/**
* Get the path to the installed_plugins.json file
*/
export function getInstalledPluginsFilePath(): string {
return join(getPluginsDirectory(), 'installed_plugins.json')
}
/**
* Get the path to the legacy installed_plugins_v2.json file.
* Used only during migration to consolidate into single file.
*/
export function getInstalledPluginsV2FilePath(): string {
return join(getPluginsDirectory(), 'installed_plugins_v2.json')
}
/**
* Clear the installed plugins cache
* Call this when the file is modified to force a reload
*
* Note: This also clears the in-memory session state (inMemoryInstalledPlugins).
* In most cases, this is only called during initialization or testing.
* For background updates, use updateInstallationPathOnDisk() which preserves
* the in-memory state.
*/
export function clearInstalledPluginsCache(): void {
installedPluginsCacheV2 = null
inMemoryInstalledPlugins = null
logForDebugging('Cleared installed plugins cache')
}
/**
* Migrate to single plugin file format.
*
* This consolidates the V1/V2 dual-file system into a single file:
* 1. If installed_plugins_v2.json exists: copy to installed_plugins.json (version=2), delete V2 file
* 2. If only installed_plugins.json exists with version=1: convert to version=2 in-place
* 3. Clean up legacy non-versioned cache directories
*
* This migration runs once per session at startup.
*/
export function migrateToSinglePluginFile(): void {
if (migrationCompleted) {
return
}
const fs = getFsImplementation()
const mainFilePath = getInstalledPluginsFilePath()
const v2FilePath = getInstalledPluginsV2FilePath()
try {
// Case 1: Try renaming v2→main directly; ENOENT = v2 doesn't exist
try {
fs.renameSync(v2FilePath, mainFilePath)
logForDebugging(
`Renamed installed_plugins_v2.json to installed_plugins.json`,
)
// Clean up legacy cache directories
const v2Data = loadInstalledPluginsV2()
cleanupLegacyCache(v2Data)
migrationCompleted = true
return
} catch (e) {
if (!isENOENT(e)) throw e
}
// Case 2: v2 absent — try reading main; ENOENT = neither exists (case 3)
let mainContent: string
try {
mainContent = fs.readFileSync(mainFilePath, { encoding: 'utf-8' })
} catch (e) {
if (!isENOENT(e)) throw e
// Case 3: No file exists - nothing to migrate
migrationCompleted = true
return
}
const mainData = jsonParse(mainContent)
const version = typeof mainData?.version === 'number' ? mainData.version : 1
if (version === 1) {
// Convert V1 to V2 format in-place
const v1Data = InstalledPluginsFileSchemaV1().parse(mainData)
const v2Data = migrateV1ToV2(v1Data)
writeFileSync_DEPRECATED(mainFilePath, jsonStringify(v2Data, null, 2), {
encoding: 'utf-8',
flush: true,
})
logForDebugging(
`Converted installed_plugins.json from V1 to V2 format (${Object.keys(v1Data.plugins).length} plugins)`,
)
// Clean up legacy cache directories
cleanupLegacyCache(v2Data)
}
// If version=2, already in correct format, no action needed
migrationCompleted = true
} catch (error) {
const errorMsg = errorMessage(error)
logForDebugging(`Failed to migrate plugin files: ${errorMsg}`, {
level: 'error',
})
logError(toError(error))
// Mark as completed to avoid retrying failed migration
migrationCompleted = true
}
}
/**
* Clean up legacy non-versioned cache directories.
*
* Legacy cache structure: ~/.claude/plugins/cache/{plugin-name}/
* Versioned cache structure: ~/.claude/plugins/cache/{marketplace}/{plugin}/{version}/
*
* This function removes legacy directories that are not referenced by any installation.
*/
function cleanupLegacyCache(v2Data: InstalledPluginsFileV2): void {
const fs = getFsImplementation()
const cachePath = getPluginCachePath()
try {
// Collect all install paths that are referenced
const referencedPaths = new Set<string>()
for (const installations of Object.values(v2Data.plugins)) {
for (const entry of installations) {
referencedPaths.add(entry.installPath)
}
}
// List top-level directories in cache
const entries = fs.readdirSync(cachePath)
for (const dirent of entries) {
if (!dirent.isDirectory()) {
continue
}
const entry = dirent.name
const entryPath = join(cachePath, entry)
// Check if this is a versioned cache (marketplace dir with plugin/version subdirs)
// or a legacy cache (flat plugin directory)
const subEntries = fs.readdirSync(entryPath)
const hasVersionedStructure = subEntries.some(subDirent => {
if (!subDirent.isDirectory()) return false
const subPath = join(entryPath, subDirent.name)
// Check if subdir contains version directories (semver-like or hash)
const versionEntries = fs.readdirSync(subPath)
return versionEntries.some(vDirent => vDirent.isDirectory())
})
if (hasVersionedStructure) {
// This is a marketplace directory with versioned structure - skip
continue
}
// This is a legacy flat cache directory
// Check if it's referenced by any installation
if (!referencedPaths.has(entryPath)) {
// Not referenced - safe to delete
fs.rmSync(entryPath, { recursive: true, force: true })
logForDebugging(`Cleaned up legacy cache directory: ${entry}`)
}
}
} catch (error) {
const errorMsg = errorMessage(error)
logForDebugging(`Failed to clean up legacy cache: ${errorMsg}`, {
level: 'warn',
})
}
}
/**
* Reset migration state (for testing)
*/
export function resetMigrationState(): void {
migrationCompleted = false
}
/**
* Read raw file data from installed_plugins.json
* Returns null if file doesn't exist.
* Throws error if file exists but can't be parsed.
*/
function readInstalledPluginsFileRaw(): {
version: number
data: unknown
} | null {
const fs = getFsImplementation()
const filePath = getInstalledPluginsFilePath()
let fileContent: string
try {
fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' })
} catch (e) {
if (isENOENT(e)) {
return null
}
throw e
}
const data = jsonParse(fileContent)
const version = typeof data?.version === 'number' ? data.version : 1
return { version, data }
}
/**
* Migrate V1 data to V2 format.
* All V1 plugins are migrated to 'user' scope since V1 had no scope concept.
*/
function migrateV1ToV2(v1Data: InstalledPluginsFileV1): InstalledPluginsFileV2 {
const v2Plugins: InstalledPluginsMapV2 = {}
for (const [pluginId, plugin] of Object.entries(v1Data.plugins)) {
// V2 format uses versioned cache path: ~/.claude/plugins/cache/{marketplace}/{plugin}/{version}
// Compute it from pluginId and version instead of using the V1 installPath
const versionedCachePath = getVersionedCachePath(pluginId, plugin.version)
v2Plugins[pluginId] = [
{
scope: 'user', // Default all existing installs to user scope
installPath: versionedCachePath,
version: plugin.version,
installedAt: plugin.installedAt,
lastUpdated: plugin.lastUpdated,
gitCommitSha: plugin.gitCommitSha,
},
]
}
return { version: 2, plugins: v2Plugins }
}
/**
* Load installed plugins in V2 format.
*
* Reads from installed_plugins.json. If file has version=1,
* converts to V2 format in memory.
*
* @returns V2 format data with array-per-plugin structure
*/
export function loadInstalledPluginsV2(): InstalledPluginsFileV2 {
// Return cached V2 data if available
if (installedPluginsCacheV2 !== null) {
return installedPluginsCacheV2
}
const filePath = getInstalledPluginsFilePath()
try {
const rawData = readInstalledPluginsFileRaw()
if (rawData) {
if (rawData.version === 2) {
// V2 format - validate and return
const validated = InstalledPluginsFileSchemaV2().parse(rawData.data)
installedPluginsCacheV2 = validated
logForDebugging(
`Loaded ${Object.keys(validated.plugins).length} installed plugins from ${filePath}`,
)
return validated
}
// V1 format - convert to V2
const v1Validated = InstalledPluginsFileSchemaV1().parse(rawData.data)
const v2Data = migrateV1ToV2(v1Validated)
installedPluginsCacheV2 = v2Data
logForDebugging(
`Loaded and converted ${Object.keys(v1Validated.plugins).length} plugins from V1 format`,
)
return v2Data
}
// File doesn't exist - return empty V2
logForDebugging(
`installed_plugins.json doesn't exist, returning empty V2 object`,
)
installedPluginsCacheV2 = { version: 2, plugins: {} }
return installedPluginsCacheV2
} catch (error) {
const errorMsg = errorMessage(error)
logForDebugging(
`Failed to load installed_plugins.json: ${errorMsg}. Starting with empty state.`,
{ level: 'error' },
)
logError(toError(error))
installedPluginsCacheV2 = { version: 2, plugins: {} }
return installedPluginsCacheV2
}
}
/**
* Save installed plugins in V2 format to installed_plugins.json.
* This is the single source of truth after V1/V2 consolidation.
*/
function saveInstalledPluginsV2(data: InstalledPluginsFileV2): void {
const fs = getFsImplementation()
const filePath = getInstalledPluginsFilePath()
try {
fs.mkdirSync(getPluginsDirectory())
const jsonContent = jsonStringify(data, null, 2)
writeFileSync_DEPRECATED(filePath, jsonContent, {
encoding: 'utf-8',
flush: true,
})
// Update cache
installedPluginsCacheV2 = data
logForDebugging(
`Saved ${Object.keys(data.plugins).length} installed plugins to ${filePath}`,
)
} catch (error) {
const _errorMsg = errorMessage(error)
logError(toError(error))
throw error
}
}
/**
* Add or update a plugin installation entry at a specific scope.
* Used for V2 format where each plugin has an array of installations.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @param scope - Installation scope (managed/user/project/local)
* @param installPath - Path to versioned plugin directory
* @param metadata - Additional installation metadata
* @param projectPath - Project path (required for project/local scopes)
*/
export function addPluginInstallation(
pluginId: string,
scope: PersistableScope,
installPath: string,
metadata: Partial<PluginInstallationEntry>,
projectPath?: string,
): void {
const data = loadInstalledPluginsFromDisk()
// Get or create array for this plugin
const installations = data.plugins[pluginId] || []
// Find existing entry for this scope+projectPath
const existingIndex = installations.findIndex(
entry => entry.scope === scope && entry.projectPath === projectPath,
)
const newEntry: PluginInstallationEntry = {
scope,
installPath,
version: metadata.version,
installedAt: metadata.installedAt || new Date().toISOString(),
lastUpdated: new Date().toISOString(),
gitCommitSha: metadata.gitCommitSha,
...(projectPath && { projectPath }),
}
if (existingIndex >= 0) {
installations[existingIndex] = newEntry
logForDebugging(`Updated installation for ${pluginId} at scope ${scope}`)
} else {
installations.push(newEntry)
logForDebugging(`Added installation for ${pluginId} at scope ${scope}`)
}
data.plugins[pluginId] = installations
saveInstalledPluginsV2(data)
}
/**
* Remove a plugin installation entry from a specific scope.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @param scope - Installation scope to remove
* @param projectPath - Project path (for project/local scopes)
*/
export function removePluginInstallation(
pluginId: string,
scope: PersistableScope,
projectPath?: string,
): void {
const data = loadInstalledPluginsFromDisk()
const installations = data.plugins[pluginId]
if (!installations) {
return
}
data.plugins[pluginId] = installations.filter(
entry => !(entry.scope === scope && entry.projectPath === projectPath),
)
// Remove plugin entirely if no installations left
if (data.plugins[pluginId].length === 0) {
delete data.plugins[pluginId]
}
saveInstalledPluginsV2(data)
logForDebugging(`Removed installation for ${pluginId} at scope ${scope}`)
}
// =============================================================================
// In-Memory vs Disk State Management (for non-in-place updates)
// =============================================================================
/**
* Get the in-memory installed plugins (session state).
* This snapshot is loaded at startup and used for the entire session.
* It is NOT updated by background operations.
*
* @returns V2 format data representing the session's view of installed plugins
*/
export function getInMemoryInstalledPlugins(): InstalledPluginsFileV2 {
if (inMemoryInstalledPlugins === null) {
inMemoryInstalledPlugins = loadInstalledPluginsV2()
}
return inMemoryInstalledPlugins
}
/**
* Load installed plugins directly from disk, bypassing all caches.
* Used by background updater to check for changes without affecting
* the running session's view.
*
* @returns V2 format data read fresh from disk
*/
export function loadInstalledPluginsFromDisk(): InstalledPluginsFileV2 {
try {
// Read from main file
const rawData = readInstalledPluginsFileRaw()
if (rawData) {
if (rawData.version === 2) {
return InstalledPluginsFileSchemaV2().parse(rawData.data)
}
// V1 format - convert to V2
const v1Data = InstalledPluginsFileSchemaV1().parse(rawData.data)
return migrateV1ToV2(v1Data)
}
return { version: 2, plugins: {} }
} catch (error) {
const errorMsg = errorMessage(error)
logForDebugging(`Failed to load installed plugins from disk: ${errorMsg}`, {
level: 'error',
})
return { version: 2, plugins: {} }
}
}
/**
* Update a plugin's install path on disk only, without modifying in-memory state.
* Used by background updater to record new version on disk while session
* continues using the old version.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @param scope - Installation scope
* @param projectPath - Project path (for project/local scopes)
* @param newPath - New install path (to new version directory)
* @param newVersion - New version string
*/
export function updateInstallationPathOnDisk(
pluginId: string,
scope: PersistableScope,
projectPath: string | undefined,
newPath: string,
newVersion: string,
gitCommitSha?: string,
): void {
const diskData = loadInstalledPluginsFromDisk()
const installations = diskData.plugins[pluginId]
if (!installations) {
logForDebugging(
`Cannot update ${pluginId} on disk: plugin not found in installed plugins`,
)
return
}
const entry = installations.find(
e => e.scope === scope && e.projectPath === projectPath,
)
if (entry) {
entry.installPath = newPath
entry.version = newVersion
entry.lastUpdated = new Date().toISOString()
if (gitCommitSha !== undefined) {
entry.gitCommitSha = gitCommitSha
}
const filePath = getInstalledPluginsFilePath()
// Write to single file (V2 format with version=2)
writeFileSync_DEPRECATED(filePath, jsonStringify(diskData, null, 2), {
encoding: 'utf-8',
flush: true,
})
// Clear cache since disk changed, but do NOT update inMemoryInstalledPlugins
installedPluginsCacheV2 = null
logForDebugging(
`Updated ${pluginId} on disk to version ${newVersion} at ${newPath}`,
)
} else {
logForDebugging(
`Cannot update ${pluginId} on disk: no installation for scope ${scope}`,
)
}
// Note: inMemoryInstalledPlugins is NOT updated
}
/**
* Check if there are pending updates (disk differs from memory).
* This happens when background updater has downloaded new versions.
*
* @returns true if any plugin has a different install path on disk vs memory
*/
export function hasPendingUpdates(): boolean {
const memoryState = getInMemoryInstalledPlugins()
const diskState = loadInstalledPluginsFromDisk()
for (const [pluginId, diskInstallations] of Object.entries(
diskState.plugins,
)) {
const memoryInstallations = memoryState.plugins[pluginId]
if (!memoryInstallations) continue
for (const diskEntry of diskInstallations) {
const memoryEntry = memoryInstallations.find(
m =>
m.scope === diskEntry.scope &&
m.projectPath === diskEntry.projectPath,
)
if (memoryEntry && memoryEntry.installPath !== diskEntry.installPath) {
return true // Disk has different version than memory
}
}
}
return false
}
/**
* Get the count of pending updates (installations where disk differs from memory).
*
* @returns Number of installations with pending updates
*/
export function getPendingUpdateCount(): number {
let count = 0
const memoryState = getInMemoryInstalledPlugins()
const diskState = loadInstalledPluginsFromDisk()
for (const [pluginId, diskInstallations] of Object.entries(
diskState.plugins,
)) {
const memoryInstallations = memoryState.plugins[pluginId]
if (!memoryInstallations) continue
for (const diskEntry of diskInstallations) {
const memoryEntry = memoryInstallations.find(
m =>
m.scope === diskEntry.scope &&
m.projectPath === diskEntry.projectPath,
)
if (memoryEntry && memoryEntry.installPath !== diskEntry.installPath) {
count++
}
}
}
return count
}
/**
* Get details about pending updates for display.
*
* @returns Array of objects with pluginId, scope, oldVersion, newVersion
*/
export function getPendingUpdatesDetails(): Array<{
pluginId: string
scope: string
oldVersion: string
newVersion: string
}> {
const updates: Array<{
pluginId: string
scope: string
oldVersion: string
newVersion: string
}> = []
const memoryState = getInMemoryInstalledPlugins()
const diskState = loadInstalledPluginsFromDisk()
for (const [pluginId, diskInstallations] of Object.entries(
diskState.plugins,
)) {
const memoryInstallations = memoryState.plugins[pluginId]
if (!memoryInstallations) continue
for (const diskEntry of diskInstallations) {
const memoryEntry = memoryInstallations.find(
m =>
m.scope === diskEntry.scope &&
m.projectPath === diskEntry.projectPath,
)
if (memoryEntry && memoryEntry.installPath !== diskEntry.installPath) {
updates.push({
pluginId,
scope: diskEntry.scope,
oldVersion: memoryEntry.version || 'unknown',
newVersion: diskEntry.version || 'unknown',
})
}
}
}
return updates
}
/**
* Reset the in-memory session state.
* This should only be called at startup or for testing.
*/
export function resetInMemoryState(): void {
inMemoryInstalledPlugins = null
}
/**
* Initialize the versioned plugins system.
* This triggers V1→V2 migration and initializes the in-memory session state.
*
* This should be called early during startup in all modes (REPL and headless).
*
* @returns Promise that resolves when initialization is complete
*/
export async function initializeVersionedPlugins(): Promise<void> {
// Step 1: Migrate to single file format (consolidates V1/V2 files, cleans up legacy cache)
migrateToSinglePluginFile()
// Step 2: Sync enabledPlugins from settings.json to installed_plugins.json
// This must complete before CLI exits (especially in headless mode)
try {
await migrateFromEnabledPlugins()
} catch (error) {
logError(error)
}
// Step 3: Initialize in-memory session state
// Calling getInMemoryInstalledPlugins triggers:
// 1. Loading from disk
// 2. Caching in inMemoryInstalledPlugins for session state
const data = getInMemoryInstalledPlugins()
logForDebugging(
`Initialized versioned plugins system with ${Object.keys(data.plugins).length} plugins`,
)
}
/**
* Remove all plugin entries belonging to a specific marketplace from installed_plugins.json.
*
* Loads V2 data once, finds all plugin IDs matching the `@{marketplaceName}` suffix,
* collects their install paths, removes the entries, and saves once.
*
* @param marketplaceName - The marketplace name (matched against `@{name}` suffix)
* @returns orphanedPaths (for markPluginVersionOrphaned) and removedPluginIds
* (for deletePluginOptions) from the removed entries
*/
export function removeAllPluginsForMarketplace(marketplaceName: string): {
orphanedPaths: string[]
removedPluginIds: string[]
} {
if (!marketplaceName) {
return { orphanedPaths: [], removedPluginIds: [] }
}
const data = loadInstalledPluginsFromDisk()
const suffix = `@${marketplaceName}`
const orphanedPaths = new Set<string>()
const removedPluginIds: string[] = []
for (const pluginId of Object.keys(data.plugins)) {
if (!pluginId.endsWith(suffix)) {
continue
}
for (const entry of data.plugins[pluginId] ?? []) {
if (entry.installPath) {
orphanedPaths.add(entry.installPath)
}
}
delete data.plugins[pluginId]
removedPluginIds.push(pluginId)
logForDebugging(
`Removed installed plugin for marketplace removal: ${pluginId}`,
)
}
if (removedPluginIds.length > 0) {
saveInstalledPluginsV2(data)
}
return { orphanedPaths: Array.from(orphanedPaths), removedPluginIds }
}
/**
* Predicate: is this installation relevant to the current project context?
*
* V2 installed_plugins.json may contain project-scoped entries from OTHER
* projects (a single user-level file tracks all scopes). Callers asking
* "is this plugin installed" almost always mean "installed in a way that's
* active here" — not "installed anywhere on this machine". See #29608:
* DiscoverPlugins.tsx was hiding plugins that were only installed in an
* unrelated project.
*
* - user/managed scopes: always relevant (global)
* - project/local scopes: only if projectPath matches the current project
*
* getOriginalCwd() (not getCwd()) because "current project" is where Claude
* Code was launched from, not wherever the working directory has drifted to.
*/
export function isInstallationRelevantToCurrentProject(
inst: PluginInstallationEntry,
): boolean {
return (
inst.scope === 'user' ||
inst.scope === 'managed' ||
inst.projectPath === getOriginalCwd()
)
}
/**
* Check if a plugin is installed in a way relevant to the current project.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @returns True if the plugin has a user/managed-scoped installation, OR a
* project/local-scoped installation whose projectPath matches the current
* project. Returns false for plugins only installed in other projects.
*/
export function isPluginInstalled(pluginId: string): boolean {
const v2Data = loadInstalledPluginsV2()
const installations = v2Data.plugins[pluginId]
if (!installations || installations.length === 0) {
return false
}
if (!installations.some(isInstallationRelevantToCurrentProject)) {
return false
}
// Plugins are loaded from settings.enabledPlugins
// If settings.enabledPlugins and installed_plugins.json diverge
// (via settings.json clobber), return false
return getSettings_DEPRECATED().enabledPlugins?.[pluginId] !== undefined
}
/**
* True only if the plugin has a USER or MANAGED scope installation.
*
* Use this in UI flows that decide whether to offer installation at all.
* A user/managed-scope install means the plugin is available everywhere —
* there's nothing the user can add. A project/local-scope install means the
* user might still want to install at user scope to make it global.
*
* gh-29997 / gh-29240 / gh-29392: the browse UI was blocking on
* isPluginInstalled() which returns true for project-scope installs,
* preventing users from adding a user-scope entry for the same plugin.
* The backend (installPluginOp → addInstalledPlugin) already supports
* multiple scope entries per plugin — only the UI gate was wrong.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
*/
export function isPluginGloballyInstalled(pluginId: string): boolean {
const v2Data = loadInstalledPluginsV2()
const installations = v2Data.plugins[pluginId]
if (!installations || installations.length === 0) {
return false
}
const hasGlobalEntry = installations.some(
entry => entry.scope === 'user' || entry.scope === 'managed',
)
if (!hasGlobalEntry) return false
// Same settings divergence guard as isPluginInstalled — if enabledPlugins
// was clobbered, treat as not-installed so the user can re-enable.
return getSettings_DEPRECATED().enabledPlugins?.[pluginId] !== undefined
}
/**
* Add or update a plugin's installation metadata
*
* Implements double-write: updates both V1 and V2 files.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @param metadata - Installation metadata
* @param scope - Installation scope (defaults to 'user' for backward compatibility)
* @param projectPath - Project path (for project/local scopes)
*/
export function addInstalledPlugin(
pluginId: string,
metadata: InstalledPlugin,
scope: PersistableScope = 'user',
projectPath?: string,
): void {
const v2Data = loadInstalledPluginsFromDisk()
const v2Entry: PluginInstallationEntry = {
scope,
installPath: metadata.installPath,
version: metadata.version,
installedAt: metadata.installedAt,
lastUpdated: metadata.lastUpdated,
gitCommitSha: metadata.gitCommitSha,
...(projectPath && { projectPath }),
}
// Get or create array for this plugin (preserves other scope installations)
const installations = v2Data.plugins[pluginId] || []
// Find existing entry for this scope+projectPath
const existingIndex = installations.findIndex(
entry => entry.scope === scope && entry.projectPath === projectPath,
)
const isUpdate = existingIndex >= 0
if (isUpdate) {
installations[existingIndex] = v2Entry
} else {
installations.push(v2Entry)
}
v2Data.plugins[pluginId] = installations
saveInstalledPluginsV2(v2Data)
logForDebugging(
`${isUpdate ? 'Updated' : 'Added'} installed plugin: ${pluginId} (scope: ${scope})`,
)
}
/**
* Remove a plugin from the installed plugins registry
* This should be called when a plugin is uninstalled.
*
* Note: This function only updates the registry file. To fully uninstall,
* call deletePluginCache() afterward to remove the physical files.
*
* @param pluginId - Plugin ID in "plugin@marketplace" format
* @returns The removed plugin metadata, or undefined if it wasn't installed
*/
export function removeInstalledPlugin(
pluginId: string,
): InstalledPlugin | undefined {
const v2Data = loadInstalledPluginsFromDisk()
const installations = v2Data.plugins[pluginId]
if (!installations || installations.length === 0) {
return undefined
}
// Extract V1-compatible metadata from first installation for return value
const firstInstall = installations[0]
const metadata: InstalledPlugin | undefined = firstInstall
? {
version: firstInstall.version || 'unknown',
installedAt: firstInstall.installedAt || new Date().toISOString(),
lastUpdated: firstInstall.lastUpdated,
installPath: firstInstall.installPath,
gitCommitSha: firstInstall.gitCommitSha,
}
: undefined
delete v2Data.plugins[pluginId]
saveInstalledPluginsV2(v2Data)
logForDebugging(`Removed installed plugin: ${pluginId}`)
return metadata
}
/**
* Delete a plugin's cache directory
* This physically removes the plugin files from disk
*
* @param installPath - Absolute path to the plugin's cache directory
*/
/**
* Export getGitCommitSha for use by pluginInstallationHelpers
*/
export { getGitCommitSha }
export function deletePluginCache(installPath: string): void {
const fs = getFsImplementation()
try {
fs.rmSync(installPath, { recursive: true, force: true })
logForDebugging(`Deleted plugin cache at ${installPath}`)
// Clean up empty parent plugin directory (cache/{marketplace}/{plugin})
// Versioned paths have structure: cache/{marketplace}/{plugin}/{version}
const cachePath = getPluginCachePath()
if (installPath.includes('/cache/') && installPath.startsWith(cachePath)) {
const pluginDir = dirname(installPath) // e.g., cache/{marketplace}/{plugin}
if (pluginDir !== cachePath && pluginDir.startsWith(cachePath)) {
try {
const contents = fs.readdirSync(pluginDir)
if (contents.length === 0) {
fs.rmdirSync(pluginDir)
logForDebugging(`Deleted empty plugin directory at ${pluginDir}`)
}
} catch {
// Parent dir doesn't exist or isn't readable — skip cleanup
}
}
}
} catch (error) {
const errorMsg = errorMessage(error)
logError(toError(error))
throw new Error(
`Failed to delete plugin cache at ${installPath}: ${errorMsg}`,
)
}
}
/**
* Get the git commit SHA from a git repository directory
* Returns undefined if not a git repo or if operation fails