universal-plugin-hub 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/routes.js CHANGED
@@ -8,7 +8,7 @@ import { randomUUID } from 'node:crypto'
8
8
  import { join, dirname } from 'node:path'
9
9
  import { sendJson, readJsonBody, sameOrigin } from './http.js'
10
10
  import {
11
- readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir, sourceCacheDir, safeRmDir,
11
+ readState, writeState, sourceIdFromGitUrl, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir, sourceCacheDir, safeRmDir,
12
12
  } from './store.js'
13
13
  import { ensureSourceCloned, pullSource, safeSegment, materializePlugin } from './market.js'
14
14
  import { readMarketplace, readMarketplaceName, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
@@ -17,9 +17,9 @@ import {
17
17
  installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, installedPluginDetail, isScanDirRegistered, toolCallIconGroups,
18
18
  toggleConnector, isConnectorActive, isOAuthConnectorAuthenticated, verifyConnectorAuth, saveConnectorAuth, enableConnector, probeConnectorAuth, probeUserMcpUpdate,
19
19
  fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
20
- withPluginLock, withSourceLock, removeManagedDirAsync, cancelActivePluginProbes,
20
+ withPluginLock, withSourceLock, removeManagedDirAsync, cancelActivePluginProbes, requiredHostPackagesForPlugin,
21
21
  } from './install.js'
22
- import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, saveUploadedZip, saveUploadedStream, MAX_UPLOAD_BYTES } from './local.js'
22
+ import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, deleteLocalPlugin, saveUploadedZip, saveUploadedStream, MAX_UPLOAD_BYTES } from './local.js'
23
23
  import { uninstallUploadedSkill, uploadedSkillRecord } from './skill-uploads.js'
24
24
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
25
25
  import { remoteConfigFromEntry } from './oauth-config.js'
@@ -31,6 +31,67 @@ function scheduledIfOk(result, applyProfile, ids) {
31
31
  return scheduledResult(result, applyProfile, ids)
32
32
  }
33
33
 
34
+ async function ensurePluginHostPackages(ensureHostPackages, pluginName, result, enabled = true) {
35
+ if (!enabled || result?.ok === false || typeof ensureHostPackages !== 'function') return result
36
+ const needed = requiredHostPackagesForPlugin(pluginName)
37
+ if (needed.length > 0) await ensureHostPackages(needed).catch(() => {})
38
+ return result
39
+ }
40
+
41
+ function createNdjsonStream(req, res) {
42
+ const wantsStream = String(req?.headers?.accept || '').toLowerCase().includes('application/x-ndjson')
43
+ let started = false
44
+ let ended = false
45
+ const ensureStarted = () => {
46
+ if (started) return
47
+ started = true
48
+ res.writeHead(200, {
49
+ 'Content-Type': 'application/x-ndjson; charset=utf-8',
50
+ 'Cache-Control': 'no-cache, no-transform',
51
+ 'X-Accel-Buffering': 'no',
52
+ })
53
+ res.flushHeaders?.()
54
+ }
55
+ const writeLine = (payload) => {
56
+ res.write(JSON.stringify(payload) + '\n')
57
+ res.flush?.()
58
+ }
59
+ return {
60
+ wantsStream,
61
+ get started() { return started },
62
+ progress(event) {
63
+ if (!wantsStream || ended || res.writableEnded) return
64
+ ensureStarted()
65
+ writeLine({ type: 'progress', ...(event || {}) })
66
+ },
67
+ result(data) {
68
+ if (ended) return
69
+ ended = true
70
+ if (started) {
71
+ if (!res.writableEnded) {
72
+ writeLine({ type: 'result', percent: 100, data })
73
+ res.end()
74
+ }
75
+ return
76
+ }
77
+ sendJson(res, 200, data)
78
+ },
79
+ error(err) {
80
+ if (!started || ended) return false
81
+ ended = true
82
+ if (!res.writableEnded) {
83
+ writeLine({
84
+ type: 'error',
85
+ status: (err && typeof err === 'object' && err.status) ? err.status : 500,
86
+ error: err instanceof Error ? err.message : String(err),
87
+ })
88
+ res.end()
89
+ }
90
+ return true
91
+ },
92
+ }
93
+ }
94
+
34
95
  function withPluginDetail(outcome, pluginName) {
35
96
  return outcome && outcome.ok !== false ? { ...outcome, plugin: installedPluginDetail(pluginName) } : outcome
36
97
  }
@@ -105,11 +166,11 @@ async function resolveLocalImportTarget(body) {
105
166
  return { target: body?.path, stagedId: null, tempUploadDir: null }
106
167
  }
107
168
 
108
- export function mountRoutes(webServer, skills = null, applyProfile = null) {
169
+ export function mountRoutes(webServer, skills = null, applyProfile = null, ensureHostPackages = null) {
109
170
  const r = webServer.register({
110
171
  kind: 'prefix',
111
172
  path: API_PREFIX,
112
- handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
173
+ handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile, ensureHostPackages),
113
174
  })
114
175
  return () => {
115
176
  cleanupAllStagedUploads()
@@ -169,7 +230,7 @@ function resolvePluginIconDir(sourceId, name) {
169
230
  }
170
231
 
171
232
 
172
- async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
233
+ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null, ensureHostPackages = null) {
173
234
  const url = new URL(req.url, 'http://localhost')
174
235
  const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
175
236
  const method = req.method ?? 'GET'
@@ -337,7 +398,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
337
398
  throw new Error('请输入有效的 Git 仓库地址或 owner/repo(例如 anthropics/claude-plugins-community)')
338
399
  }
339
400
  const parsed = parseGitUrl(url)
340
- const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
401
+ const id = sourceIdFromGitUrl(url)
341
402
  if (!id) throw new Error('无法从该地址识别仓库')
342
403
 
343
404
  const { pluginCount, marketName } = await withSourceLock(id, async () => {
@@ -368,6 +429,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
368
429
  if (method === 'POST' && path === '/plugins/local/inspect') {
369
430
  requireSameOrigin(req)
370
431
  disableUploadTimeouts(req, res)
432
+ const stream = createNdjsonStream(req, res)
371
433
  const contentType = String(req.headers?.['content-type'] || '').toLowerCase()
372
434
  let target = ''
373
435
  let stagedUpload = null
@@ -389,22 +451,40 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
389
451
  target = body.path
390
452
  }
391
453
  }
454
+ const inspectStart = stagedUpload ? 30 : 5
455
+ if (stagedUpload) {
456
+ stream.progress({ stage: 'extracting', percent: 30, detail: '文件已就绪,开始解压…' })
457
+ } else {
458
+ stream.progress({ stage: 'extracting', percent: 5, detail: '正在解析本地路径与清单…' })
459
+ }
392
460
  let result
393
461
  try {
394
- result = await inspectLocalPlugin(target)
462
+ try {
463
+ result = await inspectLocalPlugin(target, {
464
+ onProgress: (evt) => {
465
+ const raw = Math.max(0, Math.min(100, Number(evt?.percent) || 0))
466
+ const scaled = inspectStart + Math.round((raw / 100) * (96 - inspectStart))
467
+ stream.progress({ ...evt, percent: scaled })
468
+ },
469
+ })
470
+ } catch (err) {
471
+ if (stagedUpload) safeRmDir(stagedUpload.uploadDir)
472
+ throw err
473
+ }
474
+ // The extraction is only for this preview: clean up the temp extract dir,
475
+ // while staging valid streamed uploads behind an opaque token so confirm does not re-upload.
476
+ stream.progress({ stage: 'finalizing', percent: 97, detail: '正在整理预览信息…' })
477
+ if (result.tempExtractDir) safeRmDir(result.tempExtractDir)
478
+ if (!result.ok && stagedUpload) {
479
+ safeRmDir(stagedUpload.uploadDir)
480
+ }
481
+ const uploadId = (result.ok && stagedUpload) ? registerStagedUpload(stagedUpload.file, stagedUpload.uploadDir) : undefined
482
+ const { tempExtractDir, effectiveDir, entries, ...preview } = result
483
+ return stream.result(uploadId ? { ...preview, uploadId } : preview)
395
484
  } catch (err) {
396
- if (stagedUpload) safeRmDir(stagedUpload.uploadDir)
485
+ if (stream.error(err)) return
397
486
  throw err
398
487
  }
399
- // The extraction is only for this preview: clean up the temp extract dir,
400
- // while staging valid streamed uploads behind an opaque token so confirm does not re-upload.
401
- if (result.tempExtractDir) safeRmDir(result.tempExtractDir)
402
- if (!result.ok && stagedUpload) {
403
- safeRmDir(stagedUpload.uploadDir)
404
- }
405
- const uploadId = (result.ok && stagedUpload) ? registerStagedUpload(stagedUpload.file, stagedUpload.uploadDir) : undefined
406
- const { tempExtractDir, effectiveDir, entries, ...preview } = result
407
- return sendJson(res, 200, uploadId ? { ...preview, uploadId } : preview)
408
488
  }
409
489
 
410
490
  if (method === 'POST' && path === '/plugins/local/upload-cancel') {
@@ -417,18 +497,36 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
417
497
  if (method === 'POST' && path === '/plugins/local/import') {
418
498
  requireSameOrigin(req)
419
499
  disableUploadTimeouts(req, res)
500
+ const stream = createNdjsonStream(req, res)
420
501
  const body = await readJsonBody(req, 30_000_000)
421
502
  const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
503
+ stream.progress({ stage: 'extracting', percent: 5, detail: '正在准备导入文件…' })
422
504
  let result
423
505
  try {
424
- result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
425
- } finally {
426
- if (tempUploadDir) safeRmDir(tempUploadDir)
506
+ try {
507
+ result = await importLocalPlugin({
508
+ path: target,
509
+ overwrite: body.overwrite,
510
+ sourceName: body.sourceName,
511
+ onProgress: (evt) => stream.progress(evt),
512
+ })
513
+ } finally {
514
+ if (tempUploadDir) safeRmDir(tempUploadDir)
515
+ }
516
+ if (stagedId) discardStagedUpload(stagedId)
517
+ invalidateLocalIconCache('local')
518
+ invalidateAtPluginsCache()
519
+ if (Array.isArray(result?.refreshed) && result.refreshed.length > 0) {
520
+ for (const refreshedName of result.refreshed) {
521
+ await ensurePluginHostPackages(ensureHostPackages, refreshedName, result)
522
+ }
523
+ return stream.result(scheduledIfOk(result, applyProfile))
524
+ }
525
+ return stream.result(result)
526
+ } catch (err) {
527
+ if (stream.error(err)) return
528
+ throw err
427
529
  }
428
- if (stagedId) discardStagedUpload(stagedId)
429
- invalidateLocalIconCache('local')
430
- invalidateAtPluginsCache()
431
- return sendJson(res, 200, result)
432
530
  }
433
531
 
434
532
  // Pure skill packages bypass the plugin pipeline: upload, private copy,
@@ -436,40 +534,66 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
436
534
  if (method === 'POST' && path === '/skills/import') {
437
535
  requireSameOrigin(req)
438
536
  disableUploadTimeouts(req, res)
537
+ const stream = createNdjsonStream(req, res)
439
538
  const body = await readJsonBody(req, 30_000_000)
440
539
  const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
540
+ stream.progress({ stage: 'extracting', percent: 5, detail: '正在准备导入 Skill…' })
441
541
  let result
442
542
  try {
443
- result = await importLocalSkills(target, {
444
- overwrite: body.overwrite === true,
445
- overwriteNames: Array.isArray(body.overwriteNames) ? body.overwriteNames.map(String) : null,
446
- })
447
- } finally {
448
- if (tempUploadDir) safeRmDir(tempUploadDir)
543
+ try {
544
+ result = await importLocalSkills(target, {
545
+ overwrite: body.overwrite === true,
546
+ overwriteNames: Array.isArray(body.overwriteNames) ? body.overwriteNames.map(String) : null,
547
+ onProgress: (evt) => stream.progress(evt),
548
+ })
549
+ } finally {
550
+ if (tempUploadDir) safeRmDir(tempUploadDir)
551
+ }
552
+ if (stagedId) discardStagedUpload(stagedId)
553
+ skills?.refresh()
554
+ return stream.result(result)
555
+ } catch (err) {
556
+ if (stream.error(err)) return
557
+ throw err
449
558
  }
450
- if (stagedId) discardStagedUpload(stagedId)
451
- skills?.refresh()
452
- return sendJson(res, 200, result)
453
559
  }
454
560
 
455
561
  // An uploaded marketplace becomes its own plugin source tab.
456
562
  if (method === 'POST' && path === '/marketplaces/import') {
457
563
  requireSameOrigin(req)
458
564
  disableUploadTimeouts(req, res)
565
+ const stream = createNdjsonStream(req, res)
459
566
  const body = await readJsonBody(req, 30_000_000)
460
567
  const { target, stagedId, tempUploadDir } = await resolveLocalImportTarget(body)
568
+ stream.progress({ stage: 'extracting', percent: 5, detail: '正在准备导入插件市场…' })
461
569
  let result
462
570
  try {
463
- result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true, target: body.target })
464
- } finally {
465
- if (tempUploadDir) safeRmDir(tempUploadDir)
466
- }
467
- if (stagedId) discardStagedUpload(stagedId)
468
- if (result?.sourceId) {
469
- invalidateLocalIconCache(result.sourceId)
571
+ try {
572
+ result = await importLocalMarketplace(target, {
573
+ sourceName: body.sourceName,
574
+ overwrite: body.overwrite === true,
575
+ target: body.target,
576
+ onProgress: (evt) => stream.progress(evt),
577
+ })
578
+ } finally {
579
+ if (tempUploadDir) safeRmDir(tempUploadDir)
580
+ }
581
+ if (stagedId) discardStagedUpload(stagedId)
582
+ if (result?.sourceId) {
583
+ invalidateLocalIconCache(result.sourceId)
584
+ }
585
+ invalidateAtPluginsCache()
586
+ if (Array.isArray(result?.refreshed) && result.refreshed.length > 0) {
587
+ for (const refreshedName of result.refreshed) {
588
+ await ensurePluginHostPackages(ensureHostPackages, refreshedName, result)
589
+ }
590
+ return stream.result(scheduledIfOk(result, applyProfile))
591
+ }
592
+ return stream.result(result)
593
+ } catch (err) {
594
+ if (stream.error(err)) return
595
+ throw err
470
596
  }
471
- invalidateAtPluginsCache()
472
- return sendJson(res, 200, result)
473
597
  }
474
598
 
475
599
  if (method === 'POST' && path === '/sources') {
@@ -482,8 +606,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
482
606
  if (!url || !/^https?:\/\//i.test(url)) {
483
607
  throw new Error('请输入有效的 Git 仓库地址或 owner/repo')
484
608
  }
485
- const parsed = parseGitUrl(url)
486
- const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
609
+ const id = sourceIdFromGitUrl(url)
487
610
  if (!id) throw new Error('无法从该地址识别仓库')
488
611
 
489
612
  const validateUnique = (state) => {
@@ -517,14 +640,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
517
640
  const sourceIds = Array.isArray(body.sourceIds) ? body.sourceIds : []
518
641
  if (sourceIds.length === 0) throw new Error('无效的插件源列表')
519
642
  const state = readState()
520
- const order = sourceIds.filter((id, index) => typeof id === 'string' && sourceIds.indexOf(id) === index)
643
+ const sourceMap = new Map(state.sources.map((s) => [s.id, s]))
644
+ const order = [...new Set(sourceIds.filter((id) => id === 'skills-local' || sourceMap.has(id)))]
521
645
  if (!order.includes('skills-local') && state.tabOrder?.includes('skills-local')) {
522
646
  order.splice(Math.min(state.tabOrder.indexOf('skills-local'), order.length), 0, 'skills-local')
523
647
  }
524
648
  state.tabOrder = order
525
- const sourceMap = new Map(state.sources.map((s) => [s.id, s]))
526
649
  const reordered = []
527
- for (const id of sourceIds) {
650
+ for (const id of order) {
528
651
  if (sourceMap.has(id)) {
529
652
  reordered.push(sourceMap.get(id))
530
653
  sourceMap.delete(id)
@@ -533,7 +656,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
533
656
  // append any remaining sources not in the list
534
657
  for (const s of sourceMap.values()) {
535
658
  reordered.push(s)
659
+ order.push(s.id)
536
660
  }
661
+ state.tabOrder = order
537
662
  state.sources = reordered
538
663
  writeState(state)
539
664
  return sendJson(res, 200, { ok: true, sources: state.sources })
@@ -546,7 +671,6 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
546
671
  const state = readState()
547
672
  const source = state.sources.find((s) => s.id === sourceId)
548
673
  if (!source) throw new Error('插件源不存在')
549
- if (source.builtin) throw new Error('内置源不可删除')
550
674
  const used = state.plugins.some((p) => p.sourceId === sourceId)
551
675
  if (used) throw new Error('该源下仍有已安装插件,请先卸载')
552
676
  // The remote checkout pool is shared by marketplaces. Only remove this
@@ -929,6 +1053,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
929
1053
  invalidateMarketplaceCache(sourceId)
930
1054
  invalidateLocalIconCache(sourceId)
931
1055
  invalidateAtPluginsCache()
1056
+ await ensurePluginHostPackages(ensureHostPackages, pluginName, result)
932
1057
  return sendJson(res, 200, scheduledIfOk(result, applyProfile))
933
1058
  }
934
1059
 
@@ -937,7 +1062,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
937
1062
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
938
1063
  const body = await readJsonBody(req)
939
1064
  const result = await togglePlugin(pluginName, body.enabled === true, { onConnectorReady: (id) => applyProfile?.([id]) })
940
- const payload = scheduledIfOk(withPluginDetail(result, pluginName), applyProfile)
1065
+ const payload = scheduledIfOk(withPluginDetail(await ensurePluginHostPackages(ensureHostPackages, pluginName, result, body.enabled === true), pluginName), applyProfile)
941
1066
  invalidateAtPluginsCache()
942
1067
  return sendJson(res, 200, payload)
943
1068
  }
@@ -949,6 +1074,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
949
1074
  invalidateMarketplaceCache()
950
1075
  invalidateLocalIconCache()
951
1076
  invalidateAtPluginsCache()
1077
+ await ensurePluginHostPackages(ensureHostPackages, pluginName, result)
952
1078
  return sendJson(res, 200, scheduledIfOk(result, applyProfile))
953
1079
  }
954
1080
 
@@ -987,6 +1113,27 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
987
1113
  }
988
1114
  }
989
1115
 
1116
+ if (method === 'DELETE' && path.startsWith('/plugins/local/')) {
1117
+ requireSameOrigin(req)
1118
+ let rawName = path.slice('/plugins/local/'.length)
1119
+ try {
1120
+ rawName = decodeURIComponent(rawName)
1121
+ } catch {
1122
+ const err = new Error('invalid plugin name encoding')
1123
+ err.status = 400
1124
+ throw err
1125
+ }
1126
+ const pluginName = safeSegment(rawName, 'plugin name')
1127
+ const result = await deleteLocalPlugin(pluginName, {
1128
+ hasActiveStagedUploads: () => {
1129
+ sweepStagedUploads()
1130
+ return STAGED_UPLOADS.size > 0
1131
+ },
1132
+ cleanupStagedUploads: cleanupAllStagedUploads,
1133
+ })
1134
+ return sendJson(res, 200, result)
1135
+ }
1136
+
990
1137
  if (method === 'DELETE' && path.startsWith('/plugins/')) {
991
1138
  requireSameOrigin(req)
992
1139
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
package/src/store.js CHANGED
@@ -49,6 +49,18 @@ function moveToTrash(dir, quarantineRoot) {
49
49
  return trashed
50
50
  }
51
51
 
52
+ /** Move a locked file out of place so a replacement can be written immediately. */
53
+ export function quarantineFileToTrash(filePath, quarantineRoot = trashRoot()) {
54
+ if (!filePath) return false
55
+ try {
56
+ const trashed = moveToTrash(filePath, quarantineRoot)
57
+ scheduleTrashSweep(trashed)
58
+ return true
59
+ } catch {
60
+ return false
61
+ }
62
+ }
63
+
52
64
  function unlinkReparsePointsSync(dir) {
53
65
  let entries
54
66
  try {
@@ -66,6 +78,16 @@ function unlinkReparsePointsSync(dir) {
66
78
  }
67
79
  }
68
80
 
81
+ function unlinkSymlinkPath(dir) {
82
+ try {
83
+ unlinkSync(dir)
84
+ } catch {
85
+ try { rmdirSync(dir) } catch {
86
+ try { rmSync(dir, { recursive: true, force: true }) } catch {}
87
+ }
88
+ }
89
+ }
90
+
69
91
  /** Robust directory deletion handling Windows readonly/locked files. */
70
92
  export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot() } = {}) {
71
93
  if (!dir) return
@@ -75,13 +97,7 @@ export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot()
75
97
  let lstatErr = null
76
98
  try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch (err) { lstatErr = err }
77
99
  if (entry?.isSymbolicLink()) {
78
- try {
79
- unlinkSync(dir)
80
- } catch {
81
- try { rmdirSync(dir) } catch {
82
- try { rmSync(dir, { recursive: true, force: true }) } catch {}
83
- }
84
- }
100
+ unlinkSymlinkPath(dir)
85
101
  return
86
102
  }
87
103
  if (!entry && !lstatErr && !existsSync(dir)) return
@@ -130,23 +146,45 @@ export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot()
130
146
  /** Remove managed files before forgetting the record needed to retry cleanup. */
131
147
  export function removeManagedDir(dir, { allowTrash = false, deferCleanup = false } = {}) {
132
148
  if (deferCleanup) {
133
- try {
134
- if (!lstatSync(dir, { throwIfNoEntry: false })) return
135
- // Detach the checkout as a unit. An open Windows handle can block the
136
- // move, in which case the caller retries while the checkout stays intact.
137
- const quarantineRoot = trashRoot()
138
- const trashed = moveToTrash(dir, quarantineRoot)
139
- void rm(trashed, { recursive: true, force: true }).then(
140
- () => { try { rmdirSync(quarantineRoot) } catch {} },
141
- () => scheduleTrashSweep(trashed),
142
- )
143
- return
144
- } catch (cause) {
145
- throw Object.assign(new Error(`无法清理目录:${dir}`, { cause }), {
146
- code: cause.code,
147
- syscall: cause.syscall,
148
- path: dir,
149
- })
149
+ let entry
150
+ let lstatErr = null
151
+ try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch (err) { lstatErr = err }
152
+ if (!entry && !lstatErr) return
153
+ if (entry?.isSymbolicLink()) {
154
+ unlinkSymlinkPath(dir)
155
+ try {
156
+ if (!lstatSync(dir, { throwIfNoEntry: false })) return
157
+ } catch {}
158
+ }
159
+ const quarantineRoot = trashRoot()
160
+ if (
161
+ !lstatErr &&
162
+ entry?.isDirectory() &&
163
+ !isSameOrInsidePath(dir, quarantineRoot) &&
164
+ !isSameOrInsidePath(quarantineRoot, dir)
165
+ ) {
166
+ try {
167
+ // Detach the checkout as a unit. An open Windows handle can block the
168
+ // move, in which case the caller retries while the checkout stays intact.
169
+ const trashed = moveToTrash(dir, quarantineRoot)
170
+ PENDING_TRASH_PATHS.add(trashed)
171
+ void rm(trashed, { recursive: true, force: true }).then(
172
+ () => {
173
+ PENDING_TRASH_PATHS.delete(trashed)
174
+ try { rmdirSync(quarantineRoot) } catch {}
175
+ },
176
+ () => scheduleTrashSweep(trashed),
177
+ )
178
+ return
179
+ } catch (cause) {
180
+ if (cause?.code !== 'EXDEV') {
181
+ throw Object.assign(new Error(`无法清理目录:${dir}`, { cause }), {
182
+ code: cause.code,
183
+ syscall: cause.syscall,
184
+ path: dir,
185
+ })
186
+ }
187
+ }
150
188
  }
151
189
  }
152
190
  safeRmDir(dir, { allowTrash })
@@ -262,7 +300,9 @@ export function sweepTrash() {
262
300
  }
263
301
  }
264
302
 
265
- /** Default state: the built-in Anthropic source. */
303
+ const ANTHROPIC_MARKETPLACE_URL = 'https://github.com/anthropics/claude-plugins-official.git'
304
+
305
+ /** Seed Anthropic in a fresh state. */
266
306
  export function defaultState() {
267
307
  return {
268
308
  version: 1,
@@ -270,8 +310,7 @@ export function defaultState() {
270
310
  {
271
311
  id: 'anthropic',
272
312
  name: 'Anthropic',
273
- url: 'https://github.com/anthropics/claude-plugins-official.git',
274
- builtin: true,
313
+ url: ANTHROPIC_MARKETPLACE_URL,
275
314
  addedAt: Date.now(),
276
315
  },
277
316
  ],
@@ -311,6 +350,10 @@ export function readState() {
311
350
  sources: Array.isArray(parsed.sources) ? parsed.sources : base.sources,
312
351
  plugins: Array.isArray(parsed.plugins) ? parsed.plugins : [],
313
352
  }
353
+ // Older state files marked the seeded source as undeletable.
354
+ for (const source of merged.sources) {
355
+ if (source && typeof source === 'object') delete source.builtin
356
+ }
314
357
  STATE_CACHE = merged
315
358
  STATE_CACHE_PATH = path
316
359
  STATE_CACHE_MTIME = stat.mtimeMs
@@ -360,6 +403,9 @@ export function slugify(value) {
360
403
  export function normalizeGitRepoUrl(raw) {
361
404
  let s = String(raw || '').trim().replace(/^['"]|['"]$/g, '')
362
405
  if (!s) return ''
406
+ if (!/^https?:\/\/$/i.test(s)) {
407
+ s = s.replace(/\/+$/, '')
408
+ }
363
409
 
364
410
  // 1. SSH format: git@github.com:owner/repo.git -> https://github.com/owner/repo.git
365
411
  const sshMatch = s.match(/^git@([^:]+):([^/]+)\/(.+?)(\.git)?$/)
@@ -409,6 +455,14 @@ export function parseGitUrl(url) {
409
455
  return null
410
456
  }
411
457
 
458
+ /** Keep the official marketplace's source ID stable when added again. */
459
+ export function sourceIdFromGitUrl(url) {
460
+ const norm = normalizeGitRepoUrl(url)
461
+ if (norm.toLowerCase().replace(/^http:/, 'https:') === ANTHROPIC_MARKETPLACE_URL) return 'anthropic'
462
+ const repo = parseGitUrl(norm)
463
+ return slugify(repo ? `${repo.owner}-${repo.repo}` : norm)
464
+ }
465
+
412
466
  function formatMarketLabel(name) {
413
467
  // Keep spaced labels intact and preserve casing within each slug word.
414
468
  if (/\s/.test(name)) return name
Binary file
package/assets/MCP.png DELETED
Binary file
Binary file
Binary file
package/assets/Skills.png DELETED
Binary file
package/screenshots.json DELETED
@@ -1,7 +0,0 @@
1
- [
2
- "assets/Plugins-official.png",
3
- "assets/Plugin-management.png",
4
- "assets/Skills.png",
5
- "assets/MCP.png",
6
- "assets/Add-plugin-source.png"
7
- ]