forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarketplaceManager.ts
More file actions
2643 lines (2440 loc) · 91.1 KB
/
Copy pathmarketplaceManager.ts
File metadata and controls
2643 lines (2440 loc) · 91.1 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
/**
* Marketplace manager for Claude Code plugins
*
* This module provides functionality to:
* - Manage known marketplace sources (URLs, GitHub repos, npm packages, local files)
* - Cache marketplace manifests locally for offline access
* - Install plugins from marketplace entries
* - Track and update marketplace configurations
*
* File structure managed by this module:
* ~/.claude/
* └── plugins/
* ├── known_marketplaces.json # Configuration of all known marketplaces
* └── marketplaces/ # Cache directory for marketplace data
* ├── my-marketplace.json # Cached marketplace from URL source
* └── github-marketplace/ # Cloned repository for GitHub source
* └── .claude-plugin/
* └── marketplace.json
*/
import axios from 'axios'
import { writeFile } from 'fs/promises'
import isEqual from 'lodash-es/isEqual.js'
import memoize from 'lodash-es/memoize.js'
import { basename, dirname, isAbsolute, join, resolve, sep } from 'path'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import { logForDebugging } from '../debug.js'
import { isEnvTruthy } from '../envUtils.js'
import {
ConfigParseError,
errorMessage,
getErrnoCode,
isENOENT,
toError,
} from '../errors.js'
import { execFileNoThrow, execFileNoThrowWithCwd } from '../execFileNoThrow.js'
import { getFsImplementation } from '../fsOperations.js'
import { gitExe } from '../git.js'
import { logError } from '../log.js'
import {
getInitialSettings,
getSettingsForSource,
updateSettingsForSource,
} from '../settings/settings.js'
import type { SettingsJson } from '../settings/types.js'
import {
jsonParse,
jsonStringify,
writeFileSync_DEPRECATED,
} from '../slowOperations.js'
import {
getAddDirEnabledPlugins,
getAddDirExtraMarketplaces,
} from './addDirPluginSettings.js'
import { markPluginVersionOrphaned } from './cacheUtils.js'
import { classifyFetchError, logPluginFetch } from './fetchTelemetry.js'
import { removeAllPluginsForMarketplace } from './installedPluginsManager.js'
import {
extractHostFromSource,
formatSourceForDisplay,
getHostPatternsFromAllowlist,
getStrictKnownMarketplaces,
isSourceAllowedByPolicy,
isSourceInBlocklist,
} from './marketplaceHelpers.js'
import {
OFFICIAL_MARKETPLACE_NAME,
OFFICIAL_MARKETPLACE_SOURCE,
} from './officialMarketplace.js'
import { fetchOfficialMarketplaceFromGcs } from './officialMarketplaceGcs.js'
import {
deletePluginDataDir,
getPluginSeedDirs,
getPluginsDirectory,
} from './pluginDirectories.js'
import { parsePluginIdentifier } from './pluginIdentifier.js'
import { deletePluginOptions } from './pluginOptionsStorage.js'
import {
isLocalMarketplaceSource,
type KnownMarketplace,
type KnownMarketplacesFile,
KnownMarketplacesFileSchema,
type MarketplaceSource,
type PluginMarketplace,
type PluginMarketplaceEntry,
PluginMarketplaceSchema,
validateOfficialNameSource,
} from './schemas.js'
/**
* Result of loading and caching a marketplace
*/
type LoadedPluginMarketplace = {
marketplace: PluginMarketplace
cachePath: string
}
/**
* Get the path to the known marketplaces configuration file
* Using a function instead of a constant allows proper mocking in tests
*/
function getKnownMarketplacesFile(): string {
return join(getPluginsDirectory(), 'known_marketplaces.json')
}
/**
* Get the path to the marketplaces cache directory
* Using a function instead of a constant allows proper mocking in tests
*/
export function getMarketplacesCacheDir(): string {
return join(getPluginsDirectory(), 'marketplaces')
}
/**
* Memoized inner function to get marketplace data.
* This caches the marketplace in memory after loading from disk or network.
*/
/**
* Clear all cached marketplace data (for testing)
*/
export function clearMarketplacesCache(): void {
getMarketplace.cache?.clear?.()
}
/**
* Configuration for known marketplaces
*/
export type KnownMarketplacesConfig = KnownMarketplacesFile
/**
* Declared marketplace entry (intent layer).
*
* Structurally compatible with settings `extraKnownMarketplaces` entries, but
* adds `sourceIsFallback` for implicit built-in declarations. This is NOT a
* settings-schema field — it's only ever set in code (never parsed from JSON).
*/
export type DeclaredMarketplace = {
source: MarketplaceSource
installLocation?: string
autoUpdate?: boolean
/**
* Presence suffices. When set, diffMarketplaces treats an already-materialized
* entry as upToDate regardless of source shape — never reports sourceChanged.
*
* Used for the implicit official-marketplace declaration: we want "clone from
* GitHub if missing", not "replace with GitHub if present under a different
* source". Without this, a seed dir that registers the official marketplace
* under e.g. an internal-mirror source would be stomped by a GitHub re-clone.
*/
sourceIsFallback?: boolean
}
/**
* Get declared marketplace intent from merged settings and --add-dir sources.
* This is what SHOULD exist — used by the reconciler to find gaps.
*
* The official marketplace is implicitly declared with `sourceIsFallback: true`
* when any enabled plugin references it.
*/
export function getDeclaredMarketplaces(): Record<string, DeclaredMarketplace> {
const implicit: Record<string, DeclaredMarketplace> = {}
// Only the official marketplace can be implicitly declared — it's the one
// built-in source we know. Other marketplaces have no default source to inject.
// Explicitly-disabled entries (value: false) don't count.
const enabledPlugins = {
...getAddDirEnabledPlugins(),
...(getInitialSettings().enabledPlugins ?? {}),
}
for (const [pluginId, value] of Object.entries(enabledPlugins)) {
if (
value &&
parsePluginIdentifier(pluginId).marketplace === OFFICIAL_MARKETPLACE_NAME
) {
implicit[OFFICIAL_MARKETPLACE_NAME] = {
source: OFFICIAL_MARKETPLACE_SOURCE,
sourceIsFallback: true,
}
break
}
}
// Lowest precedence: implicit < --add-dir < merged settings.
// An explicit extraKnownMarketplaces entry for claude-plugins-official
// in --add-dir or settings wins.
return {
...implicit,
...getAddDirExtraMarketplaces(),
...(getInitialSettings().extraKnownMarketplaces ?? {}),
}
}
/**
* Find which editable settings source declared a marketplace.
* Checks in reverse precedence order (highest priority last) so the
* result is the source that "wins" in the merged view.
* Returns null if the marketplace isn't declared in any editable source.
*/
export function getMarketplaceDeclaringSource(
name: string,
): 'userSettings' | 'projectSettings' | 'localSettings' | null {
// Check highest-precedence editable sources first — the one that wins
// in the merged view is the one we should write back to.
const editableSources: Array<
'localSettings' | 'projectSettings' | 'userSettings'
> = ['localSettings', 'projectSettings', 'userSettings']
for (const source of editableSources) {
const settings = getSettingsForSource(source)
if (settings?.extraKnownMarketplaces?.[name]) {
return source
}
}
return null
}
/**
* Save a marketplace entry to settings (intent layer).
* Does NOT touch known_marketplaces.json (state layer).
*
* @param name - The marketplace name
* @param entry - The marketplace config
* @param settingSource - Which settings source to write to (defaults to userSettings)
*/
export function saveMarketplaceToSettings(
name: string,
entry: DeclaredMarketplace,
settingSource:
| 'userSettings'
| 'projectSettings'
| 'localSettings' = 'userSettings',
): void {
const existing = getSettingsForSource(settingSource) ?? {}
const current = { ...existing.extraKnownMarketplaces }
current[name] = entry
updateSettingsForSource(settingSource, { extraKnownMarketplaces: current })
}
/**
* Load known marketplaces configuration from disk
*
* Reads the configuration file at ~/.claude/plugins/known_marketplaces.json
* which contains a mapping of marketplace names to their sources and metadata.
*
* Example configuration file content:
* ```json
* {
* "official-marketplace": {
* "source": { "source": "url", "url": "https://example.com/marketplace.json" },
* "installLocation": "/Users/me/.claude/plugins/marketplaces/official-marketplace.json",
* "lastUpdated": "2024-01-15T10:30:00.000Z"
* },
* "company-plugins": {
* "source": { "source": "github", "repo": "mycompany/plugins" },
* "installLocation": "/Users/me/.claude/plugins/marketplaces/company-plugins",
* "lastUpdated": "2024-01-14T15:45:00.000Z"
* }
* }
* ```
*
* @returns Configuration object mapping marketplace names to their metadata
*/
export async function loadKnownMarketplacesConfig(): Promise<KnownMarketplacesConfig> {
const fs = getFsImplementation()
const configFile = getKnownMarketplacesFile()
try {
const content = await fs.readFile(configFile, {
encoding: 'utf-8',
})
const data = jsonParse(content)
// Validate against schema
const parsed = KnownMarketplacesFileSchema().safeParse(data)
if (!parsed.success) {
const errorMsg = `Marketplace configuration file is corrupted: ${parsed.error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`
logForDebugging(errorMsg, {
level: 'error',
})
throw new ConfigParseError(errorMsg, configFile, data)
}
return parsed.data
} catch (error) {
if (isENOENT(error)) {
return {}
}
// If it's already a ConfigParseError, re-throw it
if (error instanceof ConfigParseError) {
throw error
}
// For JSON parse errors or I/O errors, throw with helpful message
const errorMsg = `Failed to load marketplace configuration: ${errorMessage(error)}`
logForDebugging(errorMsg, {
level: 'error',
})
throw new Error(errorMsg)
}
}
/**
* Load known marketplaces config, returning {} on any error instead of throwing.
*
* Use this on read-only paths (plugin loading, feature checks) where a corrupted
* config should degrade gracefully rather than crash. DO NOT use on load→mutate→save
* paths — returning {} there would cause the save to overwrite the corrupted file
* with just the new entry, permanently destroying the user's other entries. The
* throwing variant preserves the file so the user can fix the corruption and recover.
*/
export async function loadKnownMarketplacesConfigSafe(): Promise<KnownMarketplacesConfig> {
try {
return await loadKnownMarketplacesConfig()
} catch {
// Inner function already logged via logForDebugging. Don't logError here —
// corrupted user config isn't a Claude Code bug, shouldn't hit the error file.
return {}
}
}
/**
* Save known marketplaces configuration to disk
*
* Writes the configuration to ~/.claude/plugins/known_marketplaces.json,
* creating the directory structure if it doesn't exist.
*
* @param config - The marketplace configuration to save
*/
export async function saveKnownMarketplacesConfig(
config: KnownMarketplacesConfig,
): Promise<void> {
// Validate before saving
const parsed = KnownMarketplacesFileSchema().safeParse(config)
const configFile = getKnownMarketplacesFile()
if (!parsed.success) {
throw new ConfigParseError(
`Invalid marketplace config: ${parsed.error.message}`,
configFile,
config,
)
}
const fs = getFsImplementation()
// Get directory from config file path to ensure consistency
const dir = join(configFile, '..')
await fs.mkdir(dir)
writeFileSync_DEPRECATED(configFile, jsonStringify(parsed.data, null, 2), {
encoding: 'utf-8',
flush: true,
})
}
/**
* Register marketplaces from the read-only seed directories into the primary
* known_marketplaces.json.
*
* The seed's known_marketplaces.json contains installLocation paths pointing
* into the seed dir itself. Registering those entries into the primary JSON
* makes them visible to all marketplace readers (getMarketplaceCacheOnly,
* getPluginByIdCacheOnly, etc.) without any loader changes — they just follow
* the installLocation wherever it points.
*
* Seed entries always win for marketplaces declared in the seed — the seed is
* admin-managed (baked into the container image). If admin updates the seed
* in a new image, those changes propagate on next boot. Users opt out of seed
* plugins via `plugin disable`, not by removing the marketplace.
*
* With multiple seed dirs (path-delimiter-separated), first-seed-wins: a
* marketplace name claimed by an earlier seed is skipped by later seeds.
*
* autoUpdate is forced to false since the seed is read-only and git-pull would
* fail. installLocation is computed from the runtime seedDir, not trusted from
* the seed's JSON (handles multi-stage Docker mount-path drift).
*
* Idempotent: second call with unchanged seed writes nothing.
*
* @returns true if any marketplace entries were written/changed (caller should
* clear caches so earlier plugin-load passes don't keep stale "marketplace
* not found" state)
*/
export async function registerSeedMarketplaces(): Promise<boolean> {
const seedDirs = getPluginSeedDirs()
if (seedDirs.length === 0) return false
const primary = await loadKnownMarketplacesConfig()
// First-seed-wins across this registration pass. Can't use the isEqual check
// alone — two seeds with the same name will have different installLocations.
const claimed = new Set<string>()
let changed = 0
for (const seedDir of seedDirs) {
const seedConfig = await readSeedKnownMarketplaces(seedDir)
if (!seedConfig) continue
for (const [name, seedEntry] of Object.entries(seedConfig)) {
if (claimed.has(name)) continue
// Compute installLocation relative to THIS seedDir, not the build-time
// path baked into the seed's JSON. Handles multi-stage Docker builds
// where the seed is mounted at a different path than where it was built.
const resolvedLocation = await findSeedMarketplaceLocation(seedDir, name)
if (!resolvedLocation) {
// Seed content missing (incomplete build) — leave primary alone, but
// don't claim the name either: a later seed may have working content.
logForDebugging(
`Seed marketplace '${name}' not found under ${seedDir}/marketplaces/, skipping`,
{ level: 'warn' },
)
continue
}
claimed.add(name)
const desired: KnownMarketplace = {
source: seedEntry.source,
installLocation: resolvedLocation,
lastUpdated: seedEntry.lastUpdated,
autoUpdate: false,
}
// Skip if primary already matches — idempotent no-op, no write.
if (isEqual(primary[name], desired)) continue
// Seed wins — admin-managed. Overwrite any existing primary entry.
primary[name] = desired
changed++
}
}
if (changed > 0) {
await saveKnownMarketplacesConfig(primary)
logForDebugging(`Synced ${changed} marketplace(s) from seed dir(s)`)
return true
}
return false
}
async function readSeedKnownMarketplaces(
seedDir: string,
): Promise<KnownMarketplacesConfig | null> {
const seedJsonPath = join(seedDir, 'known_marketplaces.json')
try {
const content = await getFsImplementation().readFile(seedJsonPath, {
encoding: 'utf-8',
})
const parsed = KnownMarketplacesFileSchema().safeParse(jsonParse(content))
if (!parsed.success) {
logForDebugging(
`Seed known_marketplaces.json invalid at ${seedDir}: ${parsed.error.message}`,
{ level: 'warn' },
)
return null
}
return parsed.data
} catch (e) {
if (!isENOENT(e)) {
logForDebugging(
`Failed to read seed known_marketplaces.json at ${seedDir}: ${e}`,
{ level: 'warn' },
)
}
return null
}
}
/**
* Locate a marketplace in the seed directory by name.
*
* Probes the canonical locations under seedDir/marketplaces/ rather than
* trusting the seed's stored installLocation (which may have a stale absolute
* path from a different build-time mount point).
*
* @returns Readable location, or null if neither format exists/validates
*/
async function findSeedMarketplaceLocation(
seedDir: string,
name: string,
): Promise<string | null> {
const dirCandidate = join(seedDir, 'marketplaces', name)
const jsonCandidate = join(seedDir, 'marketplaces', `${name}.json`)
for (const candidate of [dirCandidate, jsonCandidate]) {
try {
await readCachedMarketplace(candidate)
return candidate
} catch {
// Try next candidate
}
}
return null
}
/**
* If installLocation points into a configured seed directory, return that seed
* directory. Seed-managed entries are admin-controlled — users can't
* remove/refresh/modify them (they'd be overwritten by registerSeedMarketplaces
* on next startup). Returning the specific seed lets error messages name it.
*/
function seedDirFor(installLocation: string): string | undefined {
return getPluginSeedDirs().find(
d => installLocation === d || installLocation.startsWith(d + sep),
)
}
/**
* Git pull operation (exported for testing)
*
* Pulls latest changes with a configurable timeout (default 120s, override via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS).
* Provides helpful error messages for common failure scenarios.
* If a ref is specified, fetches and checks out that specific branch or tag.
*/
// Environment variables to prevent git from prompting for credentials
const GIT_NO_PROMPT_ENV = {
GIT_TERMINAL_PROMPT: '0', // Prevent terminal credential prompts
GIT_ASKPASS: '', // Disable askpass GUI programs
}
const DEFAULT_PLUGIN_GIT_TIMEOUT_MS = 120 * 1000
function getPluginGitTimeoutMs(): number {
const envValue = process.env.CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS
if (envValue) {
const parsed = parseInt(envValue, 10)
if (!isNaN(parsed) && parsed > 0) {
return parsed
}
}
return DEFAULT_PLUGIN_GIT_TIMEOUT_MS
}
export async function gitPull(
cwd: string,
ref?: string,
options?: { disableCredentialHelper?: boolean; sparsePaths?: string[] },
): Promise<{ code: number; stderr: string }> {
logForDebugging(`git pull: cwd=${cwd} ref=${ref ?? 'default'}`)
const env = { ...process.env, ...GIT_NO_PROMPT_ENV }
const credentialArgs = options?.disableCredentialHelper
? ['-c', 'credential.helper=']
: []
if (ref) {
const fetchResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'fetch', 'origin', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (fetchResult.code !== 0) {
return enhanceGitPullErrorMessages(fetchResult)
}
const checkoutResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'checkout', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (checkoutResult.code !== 0) {
return enhanceGitPullErrorMessages(checkoutResult)
}
const pullResult = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'pull', 'origin', ref],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (pullResult.code !== 0) {
return enhanceGitPullErrorMessages(pullResult)
}
await gitSubmoduleUpdate(cwd, credentialArgs, env, options?.sparsePaths)
return pullResult
}
const result = await execFileNoThrowWithCwd(
gitExe(),
[...credentialArgs, 'pull', 'origin', 'HEAD'],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (result.code !== 0) {
return enhanceGitPullErrorMessages(result)
}
await gitSubmoduleUpdate(cwd, credentialArgs, env, options?.sparsePaths)
return result
}
/**
* Sync submodule working dirs after a successful pull. gitClone() uses
* --recurse-submodules, but gitPull() didn't — the parent repo's submodule
* pointer would advance while the working dir stayed at the old commit,
* making plugin sources in submodules unresolvable after marketplace update.
* Non-fatal: a failed submodule update logs a warning; most marketplaces
* don't use submodules at all. (gh-30696)
*
* Skipped for sparse clones — gitClone's sparse path intentionally omits
* --recurse-submodules to preserve partial-clone bandwidth savings, and
* .gitmodules is a root file that cone-mode sparse-checkout always
* materializes, so the .gitmodules gate alone can't distinguish sparse repos.
*
* Perf: git-submodule is a bash script that spawns ~20 subprocesses (~35ms+)
* even when no submodules exist. .gitmodules is a tracked file — pull
* materializes it iff the repo has submodules — so gate on its presence to
* skip the spawn for the common case.
*
* --init performs first-contact clone of newly-added submodules, so maintain
* parity with gitClone's non-sparse path: StrictHostKeyChecking=yes for
* fail-closed SSH (unknown hosts reject rather than silently populate
* known_hosts), and --depth 1 for shallow clone (matching --shallow-submodules).
* --depth only affects not-yet-initialized submodules; existing shallow
* submodules are unaffected.
*/
async function gitSubmoduleUpdate(
cwd: string,
credentialArgs: string[],
env: NodeJS.ProcessEnv,
sparsePaths: string[] | undefined,
): Promise<void> {
if (sparsePaths && sparsePaths.length > 0) return
const hasGitmodules = await getFsImplementation()
.stat(join(cwd, '.gitmodules'))
.then(
() => true,
() => false,
)
if (!hasGitmodules) return
const result = await execFileNoThrowWithCwd(
gitExe(),
[
'-c',
'core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes',
...credentialArgs,
'submodule',
'update',
'--init',
'--recursive',
'--depth',
'1',
],
{ cwd, timeout: getPluginGitTimeoutMs(), stdin: 'ignore', env },
)
if (result.code !== 0) {
logForDebugging(
`git submodule update failed (non-fatal): ${result.stderr}`,
{ level: 'warn' },
)
}
}
/**
* Enhance error messages for git pull failures
*/
function enhanceGitPullErrorMessages(result: {
code: number
stderr: string
error?: string
}): { code: number; stderr: string } {
if (result.code === 0) {
return result
}
// Detect execa timeout kills via the error field (stderr won't contain "timed out"
// when the process is killed by SIGTERM — the timeout info is only in error)
if (result.error?.includes('timed out')) {
const timeoutSec = Math.round(getPluginGitTimeoutMs() / 1000)
return {
...result,
stderr: `Git pull timed out after ${timeoutSec}s. Try increasing the timeout via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS environment variable.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect SSH host key verification failures (check before the generic
// 'Could not read from remote' catch — that string appears in both cases).
// OpenSSH emits "Host key verification failed" for BOTH host-not-in-known_hosts
// and host-key-has-changed — the latter also includes the "REMOTE HOST
// IDENTIFICATION HAS CHANGED" banner, which needs different remediation.
if (result.stderr.includes('REMOTE HOST IDENTIFICATION HAS CHANGED')) {
return {
...result,
stderr: `SSH host key for this marketplace's git host has changed (server key rotation or possible MITM). Remove the stale entry with: ssh-keygen -R <host>\nThen connect once manually to accept the new key.\n\nOriginal error: ${result.stderr}`,
}
}
if (result.stderr.includes('Host key verification failed')) {
return {
...result,
stderr: `SSH host key verification failed while updating marketplace. The host key is not in your known_hosts file. Connect once manually to add it (e.g., ssh -T git@<host>), or remove and re-add the marketplace with an HTTPS URL.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect SSH authentication failures
if (
result.stderr.includes('Permission denied (publickey)') ||
result.stderr.includes('Could not read from remote repository')
) {
return {
...result,
stderr: `SSH authentication failed while updating marketplace. Please ensure your SSH keys are configured.\n\nOriginal error: ${result.stderr}`,
}
}
// Detect network issues
if (
result.stderr.includes('timed out') ||
result.stderr.includes('Could not resolve host')
) {
return {
...result,
stderr: `Network error while updating marketplace. Please check your internet connection.\n\nOriginal error: ${result.stderr}`,
}
}
return result
}
/**
* Check if SSH is likely to work for GitHub
* This is a quick heuristic check that avoids the full clone timeout
*
* Uses StrictHostKeyChecking=yes (not accept-new) so an unknown github.com
* host key fails closed rather than being silently added to known_hosts.
* This prevents a network-level MITM from poisoning known_hosts on first
* contact. Users who already have github.com in known_hosts see no change;
* users who don't are routed to the HTTPS clone path.
*
* @returns true if SSH auth succeeds and github.com is already trusted
*/
async function isGitHubSshLikelyConfigured(): Promise<boolean> {
try {
// Quick SSH connection test with 2 second timeout
// This fails fast if SSH isn't configured
const result = await execFileNoThrow(
'ssh',
[
'-T',
'-o',
'BatchMode=yes',
'-o',
'ConnectTimeout=2',
'-o',
'StrictHostKeyChecking=yes',
'git@github.com',
],
{
timeout: 3000, // 3 second total timeout
},
)
// SSH to github.com always returns exit code 1 with "successfully authenticated"
// or exit code 255 with "Permission denied" - we want the former
const configured =
result.code === 1 &&
(result.stderr?.includes('successfully authenticated') ||
result.stdout?.includes('successfully authenticated'))
logForDebugging(
`SSH config check: code=${result.code} configured=${configured}`,
)
return configured
} catch (error) {
// Any error means SSH isn't configured properly
logForDebugging(`SSH configuration check failed: ${errorMessage(error)}`, {
level: 'warn',
})
return false
}
}
/**
* Check if a git error indicates authentication failure.
* Used to provide enhanced error messages for auth failures.
*/
function isAuthenticationError(stderr: string): boolean {
return (
stderr.includes('Authentication failed') ||
stderr.includes('could not read Username') ||
stderr.includes('terminal prompts disabled') ||
stderr.includes('403') ||
stderr.includes('401')
)
}
/**
* Extract the SSH host from a git URL for error messaging.
* Matches the SSH format user@host:path (e.g., git@github.com:owner/repo.git).
*/
function extractSshHost(gitUrl: string): string | null {
const match = gitUrl.match(/^[^@]+@([^:]+):/)
return match?.[1] ?? null
}
/**
* Git clone operation (exported for testing)
*
* Clones a git repository with a configurable timeout (default 120s, override via CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS)
* and larger repositories. Provides helpful error messages for common failure scenarios.
* Optionally checks out a specific branch or tag.
*
* Does NOT disable credential helpers — this allows the user's existing auth setup
* (gh auth, keychain, git-credential-store, etc.) to work natively for private repos.
* Interactive prompts are still prevented via GIT_TERMINAL_PROMPT=0, GIT_ASKPASS='',
* stdin: 'ignore', and BatchMode=yes for SSH.
*
* Uses StrictHostKeyChecking=yes (not accept-new): unknown SSH hosts fail closed
* with a clear message rather than being silently trusted on first contact. For
* the github source type, the preflight check routes unknown-host users to HTTPS
* automatically; for explicit git@host:… URLs, users see an actionable error.
*/
export async function gitClone(
gitUrl: string,
targetPath: string,
ref?: string,
sparsePaths?: string[],
): Promise<{ code: number; stderr: string }> {
const useSparse = sparsePaths && sparsePaths.length > 0
const args = [
'-c',
'core.sshCommand=ssh -o BatchMode=yes -o StrictHostKeyChecking=yes',
'clone',
'--depth',
'1',
]
if (useSparse) {
// Partial clone: skip blob download until checkout, defer checkout until
// after sparse-checkout is configured. Submodules are intentionally dropped
// for sparse clones — sparse monorepos rarely need them, and recursing
// submodules would defeat the partial-clone bandwidth savings.
args.push('--filter=blob:none', '--no-checkout')
} else {
args.push('--recurse-submodules', '--shallow-submodules')
}
if (ref) {
args.push('--branch', ref)
}
args.push(gitUrl, targetPath)
const timeoutMs = getPluginGitTimeoutMs()
logForDebugging(
`git clone: url=${redactUrlCredentials(gitUrl)} ref=${ref ?? 'default'} timeout=${timeoutMs}ms`,
)
const result = await execFileNoThrowWithCwd(gitExe(), args, {
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
})
// Scrub credentials from execa's error/stderr fields before any logging or
// returning. execa's shortMessage embeds the full command line (including
// the credentialed URL), and result.stderr may also contain it on some git
// versions.
const redacted = redactUrlCredentials(gitUrl)
if (gitUrl !== redacted) {
if (result.error) result.error = result.error.replaceAll(gitUrl, redacted)
if (result.stderr)
result.stderr = result.stderr.replaceAll(gitUrl, redacted)
}
if (result.code === 0) {
if (useSparse) {
// Configure the sparse cone, then materialize only those paths.
// `sparse-checkout set --cone` handles both init and path selection
// in a single step on git >= 2.25.
const sparseResult = await execFileNoThrowWithCwd(
gitExe(),
['sparse-checkout', 'set', '--cone', '--', ...sparsePaths],
{
cwd: targetPath,
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
},
)
if (sparseResult.code !== 0) {
return {
code: sparseResult.code,
stderr: `git sparse-checkout set failed: ${sparseResult.stderr}`,
}
}
const checkoutResult = await execFileNoThrowWithCwd(
gitExe(),
// ref was already passed to clone via --branch, so HEAD points to it;
// if no ref, HEAD points to the remote's default branch.
['checkout', 'HEAD'],
{
cwd: targetPath,
timeout: timeoutMs,
stdin: 'ignore',
env: { ...process.env, ...GIT_NO_PROMPT_ENV },
},
)
if (checkoutResult.code !== 0) {
return {
code: checkoutResult.code,
stderr: `git checkout after sparse-checkout failed: ${checkoutResult.stderr}`,
}
}
}
logForDebugging(`git clone succeeded: ${redactUrlCredentials(gitUrl)}`)
return result
}
logForDebugging(
`git clone failed: url=${redactUrlCredentials(gitUrl)} code=${result.code} error=${result.error ?? 'none'} stderr=${result.stderr}`,
{ level: 'warn' },
)
// Detect timeout kills — when execFileNoThrowWithCwd kills the process via SIGTERM,
// stderr may only contain partial output (e.g. "Cloning into '...'") with no
// "timed out" string. Check the error field from execa which contains the
// timeout message.
if (result.error?.includes('timed out')) {
return {
...result,
stderr: `Git clone timed out after ${Math.round(timeoutMs / 1000)}s. The repository may be too large for the current timeout. Set CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to increase it (e.g., 300000 for 5 minutes).\n\nOriginal error: ${result.stderr}`,
}
}
// Enhance error messages for common scenarios
if (result.stderr) {
// Host key verification failure — check FIRST, before the generic
// 'Could not read from remote repository' catch (that string appears
// in both stderr outputs, so order matters). OpenSSH emits
// "Host key verification failed" for BOTH host-not-in-known_hosts and
// host-key-has-changed; distinguish them by the key-change banner.
if (result.stderr.includes('REMOTE HOST IDENTIFICATION HAS CHANGED')) {
const host = extractSshHost(gitUrl)
const removeHint = host ? `ssh-keygen -R ${host}` : 'ssh-keygen -R <host>'
return {
...result,
stderr: `SSH host key has changed (server key rotation or possible MITM). Remove the stale known_hosts entry:\n ${removeHint}\nThen connect once manually to verify and accept the new key.\n\nOriginal error: ${result.stderr}`,
}
}
if (result.stderr.includes('Host key verification failed')) {
const host = extractSshHost(gitUrl)
const connectHint = host ? `ssh -T git@${host}` : 'ssh -T git@<host>'
return {
...result,
stderr: `SSH host key is not in your known_hosts file. To add it, connect once manually (this will show the fingerprint for you to verify):\n ${connectHint}\n\nOr use an HTTPS URL instead (recommended for public repos).\n\nOriginal error: ${result.stderr}`,
}
}
if (
result.stderr.includes('Permission denied (publickey)') ||
result.stderr.includes('Could not read from remote repository')
) {
return {
...result,
stderr: `SSH authentication failed. Please ensure your SSH keys are configured for GitHub, or use an HTTPS URL instead.\n\nOriginal error: ${result.stderr}`,
}
}
if (isAuthenticationError(result.stderr)) {
return {
...result,
stderr: `HTTPS authentication failed. Please ensure your credential helper is configured (e.g., gh auth login).\n\nOriginal error: ${result.stderr}`,
}
}
if (
result.stderr.includes('timed out') ||
result.stderr.includes('timeout') ||
result.stderr.includes('Could not resolve host')
) {
return {
...result,
stderr: `Network error or timeout while cloning repository. Please check your internet connection and try again.\n\nOriginal error: ${result.stderr}`,
}
}
}
// Fallback for empty stderr — gh-28373: user saw "Failed to clone
// marketplace repository:" with nothing after the colon. Git CAN fail
// without writing to stderr (stdout instead, or output swallowed by
// credential helper / signal). execa's error field has the execa-level
// message (command, exit code, signal); exit code is the minimum.
if (!result.stderr) {
return {
code: result.code,
stderr:
result.error ||
`git clone exited with code ${result.code} (no stderr output). Run with --debug to see the full command.`,
}
}
return result
}
/**
* Progress callback for marketplace operations.
*
* This callback is invoked at various stages during marketplace operations
* (downloading, git operations, validation, etc.) to provide user feedback.
*
* IMPORTANT: Implementations should handle errors internally and not throw exceptions.
* If a callback throws, it will be caught and logged but won't abort the operation.
*
* @param message - Human-readable progress message to display to the user
*/
export type MarketplaceProgressCallback = (message: string) => void
/**