universal-plugin-hub 1.5.0 → 1.5.5

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/install.js CHANGED
@@ -21,8 +21,8 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
21
21
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
22
22
  import { ErrorCode } from '@modelcontextprotocol/sdk/types.js'
23
23
  import { installedDir, pluginDataDir, compiledHooksPath, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, removeManagedDir, sourceCacheDir, trashRoot, isSameOrInsidePath } from './store.js'
24
- import { materializePlugin, pullSource } from './market.js'
25
- import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, readPluginShortDescription, formatDisplayName, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName, PLUGIN_RUNTIME_ENV_KEYS, hasUnresolvedVarPlaceholder, isDotRelativePath, expandPluginVars, resolvePluginCommand, resolvePluginCwd, resolvePluginSpecPath, resolveConnectorDisplay, resolvePluginCommandEntries, compileResolvedHooks, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
24
+ import { materializePlugin, pullSource, sourceRepositoryDir, normalizeRemotePluginSource, remoteCheckoutDir, pluginPath } from './market.js'
25
+ import { copyDir, copyDirAsync, normalizeVersion, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, readPluginShortDescription, formatDisplayName, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName, PLUGIN_RUNTIME_ENV_KEYS, hasUnresolvedVarPlaceholder, isDotRelativePath, expandPluginVars, resolvePluginCommand, resolvePluginCwd, resolvePluginSpecPath, resolveConnectorDisplay, resolvePluginCommandEntries, compileResolvedHooks, mergeManifestWithRow, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
26
26
  import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
27
27
  import { isUploadedSkillTarget } from './skill-uploads.js'
28
28
  import { buildPluginIcons } from './icons.js'
@@ -50,6 +50,50 @@ export function cordisPatchPath() {
50
50
  return profilePatch
51
51
  }
52
52
 
53
+ /** Sentinel wrapper distinguishing DSH `!!js` YAML expressions from plain objects. */
54
+ class CordisJsExpr {
55
+ constructor(expr) {
56
+ this.expr = expr
57
+ }
58
+ }
59
+
60
+ // DSH's Cordis loader (@deepseek-ai/cordis-plugin-include) extends YAML with `!!js` scalar expressions.
61
+ const CORDIS_JS_TAG = yaml.defineScalarTag('tag:yaml.org,2002:js', {
62
+ resolve: (source) => new CordisJsExpr(source),
63
+ identify: (value) => value instanceof CordisJsExpr,
64
+ represent: (value) => value.expr,
65
+ })
66
+
67
+ const CORDIS_LOAD_SCHEMA = yaml.CORE_SCHEMA.withTags(CORDIS_JS_TAG)
68
+ const CORDIS_DUMP_SCHEMA = yaml.DUMP_SCHEMA.withTags(CORDIS_JS_TAG)
69
+
70
+ // js-yaml v4 (used by DSH's loader) rejects unquoted empty `!!js` scalars; force single quotes when empty.
71
+ // js-yaml 5.3 uses a Style object while 5.4+ uses numeric SCALAR_STYLE values.
72
+ function quoteEmptyJsTags(docs) {
73
+ yaml.visit(docs, (node) => {
74
+ if (node.kind === 'scalar' && (node.tag === '!!js' || node.tag === 'tag:yaml.org,2002:js') && node.value === '') {
75
+ if (node.style && typeof node.style === 'object') {
76
+ node.style.singleQuoted = true
77
+ } else {
78
+ node.style = yaml.SCALAR_STYLE.SINGLE_QUOTED
79
+ }
80
+ }
81
+ })
82
+ }
83
+
84
+ /** Extract a concise single-line YAML parse location and reason for UI error toasts. */
85
+ function formatCordisYamlError(error) {
86
+ const reason = typeof error?.reason === 'string' && error.reason.trim()
87
+ ? error.reason.trim()
88
+ : String(error?.message || error || '').split(/\r?\n/)[0].trim()
89
+ const mark = error?.mark
90
+ if (mark && Number.isInteger(mark.line) && Number.isInteger(mark.column)) {
91
+ const loc = `第 ${mark.line + 1} 行第 ${mark.column + 1} 列`
92
+ return reason ? `${loc}:${reason}` : loc
93
+ }
94
+ return reason
95
+ }
96
+
53
97
  function loadCordisPatch(file) {
54
98
  let source
55
99
  try {
@@ -58,14 +102,18 @@ function loadCordisPatch(file) {
58
102
  if (error.code === 'ENOENT') return []
59
103
  throw new Error(`无法读取 ${file},已中止写入以保护现有配置。`, { cause: error })
60
104
  }
105
+ // Strip UTF-8 BOM once: Windows Notepad writes one, and js-yaml v5 rejects BOM before comments.
106
+ const text = source.charCodeAt(0) === 0xFEFF ? source.slice(1) : source
61
107
  // js-yaml can reject an empty stream. An explicit null value is still a document.
62
- if (source.replace(/^\uFEFF/, '').split(/\r\n?|\n/).every((line) => /^[ \t]*(?:#.*)?$/.test(line))) return []
108
+ if (text.split(/\r\n?|\n/).every((line) => /^[ \t]*(?:#.*)?$/.test(line))) return []
63
109
 
64
110
  let parsed
65
111
  try {
66
- parsed = yaml.load(source)
112
+ parsed = yaml.load(text, { schema: CORDIS_LOAD_SCHEMA })
67
113
  } catch (error) {
68
- throw new Error(`无法解析 ${file},已中止写入以保护现有配置。请通过 DSH 配置文件手动修改。`, { cause: error })
114
+ const detail = formatCordisYamlError(error)
115
+ const suffix = detail ? `(${detail})` : ''
116
+ throw new Error(`无法解析 ${file}${suffix},已中止写入以保护现有配置。请通过 DSH 配置文件手动修改。`, { cause: error })
69
117
  }
70
118
  if (!Array.isArray(parsed)) {
71
119
  throw new Error(`${file} 的顶层必须是数组,已中止写入以保护现有配置。`)
@@ -86,11 +134,16 @@ function readCordisPatchRaw() {
86
134
 
87
135
  function writeCordisPatchRaw(patch) {
88
136
  const file = cordisPatchPath()
89
- // A tolerant read can return [] for a DSH-specific or damaged document.
137
+ // A tolerant read can return [] for a damaged document.
90
138
  // Check the on-disk document before any mutation can replace it.
91
139
  loadCordisPatch(file)
92
140
  mkdirSync(dirname(file), { recursive: true })
93
- const content = yaml.dump(patch, { indent: 2, lineWidth: -1 })
141
+ const content = yaml.dump(patch, {
142
+ schema: CORDIS_DUMP_SCHEMA,
143
+ indent: 2,
144
+ lineWidth: -1,
145
+ transform: quoteEmptyJsTags,
146
+ })
94
147
  const seq = (PATCH_TMP_SEQ = (PATCH_TMP_SEQ + 1) & 0xffffff).toString(36)
95
148
  const tmp = join(dirname(file), `.cordis.patch.${process.pid}.${Date.now().toString(36)}.${seq}.tmp`)
96
149
  try {
@@ -1254,7 +1307,7 @@ export function unregisterPluginLsp(pluginName) {
1254
1307
  for (const block of patch) {
1255
1308
  if (block && Array.isArray(block.insert)) {
1256
1309
  const before = block.insert.length
1257
- block.insert = block.insert.filter((item) => !(item && item.id && item.id.startsWith(prefix)))
1310
+ block.insert = block.insert.filter((item) => !(item && typeof item.id === 'string' && item.id.startsWith(prefix)))
1258
1311
  if (block.insert.length !== before) changed = true
1259
1312
  }
1260
1313
  }
@@ -1290,18 +1343,8 @@ export function getHookBridgeId(pluginName) {
1290
1343
  return `hooks-${slugify(pluginName)}`
1291
1344
  }
1292
1345
 
1293
- /**
1294
- * Register an installed plugin's Claude/Codex hooks into DSH by inserting a
1295
- * `@deepseek-ai/dsh-hooks-claude-code` bridge entry into cordis.patch.yml. The
1296
- * bridge runs an unmodified Claude Code hooks.json on DSH's interception points
1297
- * (SessionStart / UserPromptSubmit / PreToolUse / PostToolUse / Stop /
1298
- * SubagentStart / SubagentStop), with `${CLAUDE_PLUGIN_ROOT}` substituted from
1299
- * `pluginRoot`. DSH's HMR re-applies the tree within ~1s, no restart needed.
1300
- *
1301
- * The bridge and its hook-protocol peer are pre-provisioned by the hub's
1302
- * `apply()` on DSH startup, so a per-plugin install is a single patch write.
1303
- */
1304
- export async function registerPluginHooks(pluginName) {
1346
+ /** Synchronously compile and register a plugin's hooks inside an active cordis patch batch. */
1347
+ function registerPluginHooksSync(pluginName) {
1305
1348
  const target = installedDir(pluginName)
1306
1349
  const dataDir = pluginDataDir(pluginName)
1307
1350
  const compiled = compileResolvedHooks(target, readPluginManifest(target), dataDir)
@@ -1333,6 +1376,21 @@ export async function registerPluginHooks(pluginName) {
1333
1376
  return { ok: true, registered: [outPath] }
1334
1377
  }
1335
1378
 
1379
+ /**
1380
+ * Register an installed plugin's Claude/Codex hooks into DSH by inserting a
1381
+ * `@deepseek-ai/dsh-hooks-claude-code` bridge entry into cordis.patch.yml. The
1382
+ * bridge runs an unmodified Claude Code hooks.json on DSH's interception points
1383
+ * (SessionStart / UserPromptSubmit / PreToolUse / PostToolUse / Stop /
1384
+ * SubagentStart / SubagentStop), with `${CLAUDE_PLUGIN_ROOT}` substituted from
1385
+ * `pluginRoot`. DSH's HMR re-applies the tree within ~1s, no restart needed.
1386
+ *
1387
+ * The bridge and its hook-protocol peer are pre-provisioned by the hub's
1388
+ * `apply()` on DSH startup, so a per-plugin install is a single patch write.
1389
+ */
1390
+ export async function registerPluginHooks(pluginName) {
1391
+ return registerPluginHooksSync(pluginName)
1392
+ }
1393
+
1336
1394
  /** Remove a plugin's hooks bridge entry from cordis.patch.yml. */
1337
1395
  export function unregisterPluginHooks(pluginName) {
1338
1396
  const patch = readCordisPatch()
@@ -2219,7 +2277,7 @@ export async function syncPluginSkillsToDsh(pluginName, shouldSync = () => true,
2219
2277
  }
2220
2278
 
2221
2279
  const settled = await Promise.allSettled(candidates.map(async (item) => {
2222
- if (await replaceManagedDir(item.srcSkillDir, item.destSkillDir, keepExisting, false, { allowTrash: true })) {
2280
+ if (await replaceManagedDirAsync(item.srcSkillDir, item.destSkillDir, keepExisting, false, { allowTrash: true, deferCleanup: true })) {
2223
2281
  synced.push(item.name)
2224
2282
  }
2225
2283
  }))
@@ -2253,13 +2311,18 @@ const PLUGIN_LOCKS = new Map()
2253
2311
  const SOURCE_LOCKS = new Map()
2254
2312
  const PLUGIN_EPOCHS = new Map()
2255
2313
 
2314
+ function pluginLockKey(pluginName) {
2315
+ return pluginName == null ? '' : String(pluginName).toLowerCase()
2316
+ }
2317
+
2256
2318
  function currentPluginEpoch(pluginName) {
2257
- return PLUGIN_EPOCHS.get(pluginName) || 0
2319
+ return PLUGIN_EPOCHS.get(pluginLockKey(pluginName)) || 0
2258
2320
  }
2259
2321
 
2260
2322
  function bumpPluginEpoch(pluginName) {
2261
- const next = currentPluginEpoch(pluginName) + 1
2262
- PLUGIN_EPOCHS.set(pluginName, next)
2323
+ const key = pluginLockKey(pluginName)
2324
+ const next = (PLUGIN_EPOCHS.get(key) || 0) + 1
2325
+ PLUGIN_EPOCHS.set(key, next)
2263
2326
  return next
2264
2327
  }
2265
2328
 
@@ -2283,7 +2346,7 @@ async function acquireKeyedLock(locks, key, fn) {
2283
2346
  * when the lock is idle so startup repair reaches its first fs attempt synchronously.
2284
2347
  */
2285
2348
  export function withPluginLock(pluginName, fn) {
2286
- return acquireKeyedLock(PLUGIN_LOCKS, pluginName, fn)
2349
+ return acquireKeyedLock(PLUGIN_LOCKS, pluginLockKey(pluginName), fn)
2287
2350
  }
2288
2351
 
2289
2352
  /**
@@ -2297,7 +2360,7 @@ export function withSourceLock(sourceId, fn) {
2297
2360
  async function retryManagedDirOperation(operation, destination) {
2298
2361
  for (let attempt = 0; ; attempt++) {
2299
2362
  try {
2300
- return operation()
2363
+ return await operation()
2301
2364
  } catch (err) {
2302
2365
  // Windows can keep a deleted directory name reserved until the last
2303
2366
  // handle closes. Keep retries scoped to directory cleanup and creation.
@@ -2324,6 +2387,16 @@ function replaceManagedDir(from, to, keepExisting, repairOnly = false, { allowTr
2324
2387
  }, to)
2325
2388
  }
2326
2389
 
2390
+ function replaceManagedDirAsync(from, to, keepExisting, repairOnly = false, { allowTrash = false, deferCleanup = false, excludeNames = null } = {}) {
2391
+ return retryManagedDirOperation(async () => {
2392
+ if (keepExisting?.(to)) return false
2393
+ if (repairOnly && hasMatchingSkillCopy(from, to)) return true
2394
+ removeManagedDir(to, { allowTrash, deferCleanup })
2395
+ await copyDirAsync(from, to, { excludeNames })
2396
+ return true
2397
+ }, to)
2398
+ }
2399
+
2327
2400
  /**
2328
2401
  * Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
2329
2402
  */
@@ -2347,7 +2420,7 @@ function skillOwnedByOtherEnabledPlugin(pluginName, skillName, plugins = readSta
2347
2420
  return false
2348
2421
  }
2349
2422
 
2350
- export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine = true, preserveOtherEnabled = true } = {}) {
2423
+ export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine = true, preserveOtherEnabled = true, deferCleanup = false } = {}) {
2351
2424
  const target = installedDir(pluginName)
2352
2425
  const pluginSkillsDir = join(target, 'skills')
2353
2426
  const dshSkills = dshSkillsDir()
@@ -2377,7 +2450,7 @@ export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine =
2377
2450
  const settled = await Promise.allSettled(targets.map(async ({ name, dest }) => {
2378
2451
  const didRemove = await retryManagedDirOperation(() => {
2379
2452
  if (isUploadedSkillTarget(dest)) return false
2380
- removeManagedDir(dest, { allowTrash: allowQuarantine })
2453
+ removeManagedDir(dest, { allowTrash: allowQuarantine, deferCleanup })
2381
2454
  return true
2382
2455
  }, dest)
2383
2456
  if (didRemove) removed.push(name)
@@ -2417,17 +2490,24 @@ export async function syncAllInstalledSkillsToDsh() {
2417
2490
  * Returns a result summary for the UI.
2418
2491
  */
2419
2492
  const marketplaceInstalls = new Set()
2493
+ const activePluginUpdates = new Set()
2420
2494
 
2421
2495
  export async function installPlugin(options) {
2422
2496
  const { pluginName } = options
2423
- if (marketplaceInstalls.has(pluginName)) throw new Error(`插件 ${pluginName} 正在安装`)
2424
- marketplaceInstalls.add(pluginName)
2497
+ const lockKey = pluginLockKey(pluginName)
2498
+ if (marketplaceInstalls.has(lockKey)) {
2499
+ throw Object.assign(new Error(`插件 ${pluginName} 正在安装`), { status: 409 })
2500
+ }
2501
+ if (activePluginUpdates.has(lockKey)) {
2502
+ throw Object.assign(new Error(`插件 ${pluginName} 正在更新`), { status: 409 })
2503
+ }
2504
+ marketplaceInstalls.add(lockKey)
2425
2505
  bumpPluginEpoch(pluginName)
2426
2506
  cancelActivePluginProbes(pluginName)
2427
2507
  try {
2428
2508
  return await withPluginLock(pluginName, () => installMarketplacePluginUnlocked(options))
2429
2509
  } finally {
2430
- marketplaceInstalls.delete(pluginName)
2510
+ marketplaceInstalls.delete(lockKey)
2431
2511
  }
2432
2512
  }
2433
2513
 
@@ -2435,7 +2515,49 @@ async function installMarketplacePluginUnlocked(options) {
2435
2515
  return withSourceLock(options.sourceId, () => installMarketplacePluginFromSourceLocked(options))
2436
2516
  }
2437
2517
 
2438
- async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName, refresh = false, initialEnabled = true }) {
2518
+ /** Return true when at least one declared LSP server passes pre-flight resolution. */
2519
+ function canRegisterAnyLsp(pluginRoot, dataDir, servers) {
2520
+ for (const s of servers) {
2521
+ const resolved = substitutePluginRoot(s || {}, pluginRoot, dataDir)
2522
+ const resolvedCmd = resolvePluginCommand(s?.command, pluginRoot, dataDir)
2523
+ if (!resolvedCmd || typeof resolvedCmd !== 'string' || !resolvedCmd.trim()) continue
2524
+ if (!resolved.extensionToLanguage || typeof resolved.extensionToLanguage !== 'object' || Object.keys(resolved.extensionToLanguage).length === 0) continue
2525
+ if (resolveCommandPath(resolvedCmd, process.env, { cwd: pluginRoot })) return true
2526
+ }
2527
+ return false
2528
+ }
2529
+
2530
+ /** Return true when installing/updating this plugin may mutate cordis.patch.yml. */
2531
+ function installMayWriteCordisPatch(pluginName, dir, row, target, prevConnectors, initialEnabled) {
2532
+ const incomingManifest = mergeManifestWithRow(readPluginManifest(dir), row)
2533
+ const incomingConnectors = listConnectors(dir, incomingManifest)
2534
+ if (prevConnectors.some((name) => !incomingConnectors.some((c) => c.name === name))) return true
2535
+
2536
+ const dataDir = pluginDataDir(pluginName)
2537
+ if (existsSync(target)) {
2538
+ if (listLspServers(target).length > 0 || existsSync(compiledHooksPath(pluginName))) return true
2539
+ if (!initialEnabled && prevConnectors.length > 0) return true
2540
+ }
2541
+ if (!initialEnabled) return false
2542
+
2543
+ if (compileResolvedHooks(dir, incomingManifest, dataDir) !== null) return true
2544
+ return canRegisterAnyLsp(dir, dataDir, listLspServers(dir, incomingManifest))
2545
+ }
2546
+
2547
+ /** Best-effort cleanup of files and registrations written during a failed fresh install. */
2548
+ async function rollbackFreshInstall(pluginName, target) {
2549
+ try { unregisterPluginHooks(pluginName) } catch {}
2550
+ try { unregisterPluginLsp(pluginName) } catch {}
2551
+ const rolledBackConnectors = existsSync(target) ? getPluginConnectors(target) : []
2552
+ for (const c of rolledBackConnectors) {
2553
+ try { unregisterConnector(pluginName, c.name) } catch {}
2554
+ }
2555
+ await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true }).catch(() => {})
2556
+ try { rmSync(compiledHooksPath(pluginName), { force: true }) } catch {}
2557
+ await removeManagedDirAsync(target, { allowTrash: true }).catch(() => {})
2558
+ }
2559
+
2560
+ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName, refresh = false, sourcePulled = false, initialEnabled = true }) {
2439
2561
  const state = readState()
2440
2562
  const source = state.sources.find((s) => s.id === sourceId)
2441
2563
  if (!source) throw new Error(`unknown source: ${sourceId}`)
@@ -2448,17 +2570,103 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2448
2570
  const row = await findMarketRow(sourceId, pluginName)
2449
2571
  if (!row) throw new Error(`plugin not found in marketplace: ${pluginName}`)
2450
2572
 
2451
- const { dir } = await materializePlugin(sourceId, pluginName, row.source, { refresh })
2573
+ let effectiveRefresh = refresh
2574
+ let allowStaleFallback = false
2575
+ if (!effectiveRefresh && row.source && typeof row.source === 'object' && row.version) {
2576
+ const normalizedSource = normalizeRemotePluginSource(row.source)
2577
+ if (
2578
+ normalizedSource &&
2579
+ ['url', 'git-subdir', 'github'].includes(normalizedSource.source) &&
2580
+ typeof normalizedSource.url === 'string' &&
2581
+ /^https?:\/\//.test(normalizedSource.url) &&
2582
+ !normalizedSource.sha &&
2583
+ !sourceRepositoryDir(sourceCacheDir(sourceId), normalizedSource)
2584
+ ) {
2585
+ const checkout = remoteCheckoutDir(normalizedSource.url, normalizedSource.ref)
2586
+ if (existsSync(join(checkout, '.git'))) {
2587
+ try {
2588
+ const cachedPluginDir = normalizedSource.path ? pluginPath(checkout, normalizedSource.path) : checkout
2589
+ const cachedVersion = normalizeVersion(readPluginManifest(cachedPluginDir, false)?.version)
2590
+ const rowVersion = normalizeVersion(row.version)
2591
+ if (rowVersion && cachedVersion && semverGt(rowVersion, cachedVersion)) {
2592
+ effectiveRefresh = true
2593
+ allowStaleFallback = true
2594
+ }
2595
+ } catch {}
2596
+ }
2597
+ }
2598
+ }
2599
+
2600
+ const { dir } = await materializePlugin(sourceId, pluginName, row.source, {
2601
+ refresh: effectiveRefresh,
2602
+ sourcePulled,
2603
+ allowStaleFallback,
2604
+ })
2452
2605
  const target = installedDir(pluginName)
2453
2606
 
2454
2607
  // Reinstalling must not inherit the previous copy's registrations: skills it
2455
2608
  // no longer ships and MCP servers it dropped would otherwise stay visible.
2456
2609
  await abortPluginConnectorProbes(pluginName)
2457
2610
  const prevConnectors = existsSync(target) ? getPluginConnectors(target).map((c) => c.name) : []
2458
- if (existsSync(target)) await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true })
2611
+ if (installMayWriteCordisPatch(pluginName, dir, row, target, prevConnectors, initialEnabled)) {
2612
+ loadCordisPatch(cordisPatchPath())
2613
+ }
2614
+
2615
+ try {
2616
+ return await materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, target, installed, prevConnectors, initialEnabled })
2617
+ } catch (error) {
2618
+ if (!installed) await rollbackFreshInstall(pluginName, target)
2619
+ throw error
2620
+ }
2621
+ }
2622
+
2623
+ function isPureSkillPackage(target, manifest) {
2624
+ return (
2625
+ listPrompts(target, manifest).length === 0 &&
2626
+ listConnectors(target, manifest).length === 0 &&
2627
+ listHooks(target, manifest).length === 0 &&
2628
+ listLspServers(target, manifest).length === 0 &&
2629
+ listAgents(target, manifest).length === 0 &&
2630
+ resolvePluginCommandEntries(target, manifest).entries.length === 0
2631
+ )
2632
+ }
2633
+
2634
+ function canMoveTopLevelSkillDir(target, skillDir, manifestOrPure) {
2635
+ const isPure = typeof manifestOrPure === 'boolean'
2636
+ ? manifestOrPure
2637
+ : isPureSkillPackage(target, manifestOrPure)
2638
+ if (!isPure) return false
2639
+ if (resolve(dirname(skillDir)) !== resolve(target)) return false
2640
+ for (const name of ['SKILL.md', 'skill.md']) {
2641
+ const skillMdPath = join(skillDir, name)
2642
+ if (!existsSync(skillMdPath)) continue
2643
+ try {
2644
+ return !/\$\{(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\}|\$(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\b/.test(readFileSync(skillMdPath, 'utf8'))
2645
+ } catch {
2646
+ return false
2647
+ }
2648
+ }
2649
+ return false
2650
+ }
2651
+
2652
+ async function mirrorSkillDir(target, skillDir, dest, pureSkill) {
2653
+ if (resolve(dest) === resolve(skillDir)) return
2654
+ if (!existsSync(dest) && canMoveTopLevelSkillDir(target, skillDir, pureSkill)) {
2655
+ try {
2656
+ renameSync(skillDir, dest)
2657
+ return
2658
+ } catch {}
2659
+ }
2660
+ await copyDirAsync(skillDir, dest)
2661
+ }
2662
+
2663
+ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, target, installed, prevConnectors, initialEnabled }) {
2664
+ if (existsSync(target)) {
2665
+ await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true, deferCleanup: true })
2666
+ }
2459
2667
 
2460
2668
  // Idempotent reinstall: clear the previous copy first.
2461
- await replaceManagedDir(dir, target)
2669
+ await replaceManagedDirAsync(dir, target, undefined, false, { deferCleanup: true, excludeNames: new Set(['.git']) })
2462
2670
 
2463
2671
  // Persist marketplace-declared components into the installed copy's manifest
2464
2672
  // when `strict: false` or when absent on disk, preserving any existing
@@ -2493,7 +2701,10 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2493
2701
  'skills', 'commands', 'agents', '.agents', '.claude-plugin', '.codex-plugin', '.well-known',
2494
2702
  'hooks', 'prompts', 'mcp', 'lsp', 'scripts', 'server', 'node_modules', '.git', 'assets', 'docs',
2495
2703
  ])
2496
- const declaredSkills = readPluginManifest(target)?.skills
2704
+ const installedManifest = readPluginManifest(target)
2705
+ const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(target, f)).find(existsSync)
2706
+ const pureSkill = !rootSkillMd && isPureSkillPackage(target, installedManifest)
2707
+ const declaredSkills = installedManifest?.skills
2497
2708
  const skillPaths = typeof declaredSkills === 'string'
2498
2709
  ? (isDotRelativePath(declaredSkills) ? [declaredSkills] : [])
2499
2710
  : (Array.isArray(declaredSkills) ? declaredSkills.filter((p) => typeof p === 'string' && isDotRelativePath(p)) : [])
@@ -2506,7 +2717,7 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2506
2717
  const parent = dirname(root)
2507
2718
  if (resolve(parent) !== resolve(target)) {
2508
2719
  const dest = join(skillsDir, basename(parent))
2509
- if (resolve(dest) !== resolve(parent)) copyDir(parent, dest)
2720
+ await mirrorSkillDir(target, parent, dest, pureSkill)
2510
2721
  }
2511
2722
  } else if (/\.md$/i.test(base) && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(base)) {
2512
2723
  const skillName = base.replace(/\.md$/i, '')
@@ -2528,19 +2739,19 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2528
2739
  if (resolve(dir) === resolve(target)) continue // handled as a root skill below
2529
2740
  if (!existsSync(join(dir, 'SKILL.md')) && !existsSync(join(dir, 'skill.md'))) continue
2530
2741
  const dest = join(skillsDir, basename(dir))
2531
- if (resolve(dest) !== resolve(dir)) copyDir(dir, dest)
2742
+ await mirrorSkillDir(target, dir, dest, pureSkill)
2532
2743
  }
2533
2744
  }
2534
2745
 
2535
2746
  // 1. Mirror commands/ (nested subdirs, manifest string/array/object paths & inline commands) into skills/
2536
- const { entries: commandEntries } = resolvePluginCommandEntries(target, readPluginManifest(target))
2747
+ const { entries: commandEntries } = resolvePluginCommandEntries(target, installedManifest)
2537
2748
  for (const cmd of commandEntries) {
2538
2749
  const cmdSkillDir = join(skillsDir, cmd.name)
2539
2750
  if (existsSync(cmdSkillDir)) continue
2540
2751
  if (cmd.filePath) {
2541
2752
  if (/^skill\.md$/i.test(basename(cmd.filePath))) {
2542
2753
  mkdirSync(cmdSkillDir, { recursive: true })
2543
- copyDir(dirname(cmd.filePath), cmdSkillDir)
2754
+ await copyDirAsync(dirname(cmd.filePath), cmdSkillDir)
2544
2755
  } else {
2545
2756
  mkdirSync(cmdSkillDir, { recursive: true })
2546
2757
  const rawContent = readFileSync(cmd.filePath, 'utf8')
@@ -2555,14 +2766,13 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2555
2766
  }
2556
2767
 
2557
2768
  // 2. If the plugin has a root SKILL.md, mirror it into skills/<pluginName>/SKILL.md
2558
- const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(target, f)).find(existsSync)
2559
2769
  if (rootSkillMd) {
2560
2770
  const rootSkillDir = join(skillsDir, pluginName)
2561
2771
  if (!existsSync(rootSkillDir)) {
2562
2772
  mkdirSync(rootSkillDir, { recursive: true })
2563
2773
  // Keep relative scripts/references/assets usable when DSH copies the skill.
2564
2774
  for (const entry of readdirSync(target, { withFileTypes: true })) {
2565
- if (entry.isDirectory() && !['skills', '.git', 'node_modules'].includes(entry.name)) copyDir(join(target, entry.name), join(rootSkillDir, entry.name))
2775
+ if (entry.isDirectory() && !['skills', '.git', 'node_modules'].includes(entry.name)) await copyDirAsync(join(target, entry.name), join(rootSkillDir, entry.name))
2566
2776
  else if (entry.isFile()) copyFileSync(join(target, entry.name), join(rootSkillDir, entry.name))
2567
2777
  }
2568
2778
  const rawContent = readFileSync(rootSkillMd, 'utf8')
@@ -2587,8 +2797,7 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2587
2797
  const sMd = join(target, entry.name, 'SKILL.md')
2588
2798
  if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
2589
2799
  const subDir = join(skillsDir, entry.name)
2590
- mkdirSync(subDir, { recursive: true })
2591
- copyDir(join(target, entry.name), subDir)
2800
+ await mirrorSkillDir(target, join(target, entry.name), subDir, pureSkill)
2592
2801
  }
2593
2802
  }
2594
2803
  }
@@ -2662,9 +2871,6 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2662
2871
 
2663
2872
  // Auto-register and connect any MCP connectors defined in the plugin that do NOT require auth and have valid URLs/commands.
2664
2873
  const pluginConnectors = getPluginConnectors(target)
2665
- for (const name of prevConnectors) {
2666
- if (!pluginConnectors.some((c) => c.name === name)) unregisterConnector(pluginName, name)
2667
- }
2668
2874
  if (installed) {
2669
2875
  // The new copy may ship different tools behind an unchanged command/URL.
2670
2876
  const toolsState = readMcpToolsState()
@@ -2687,29 +2893,34 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2687
2893
 
2688
2894
  const lspServers = listLspServers(target)
2689
2895
  const lspErrors = []
2690
- unregisterPluginLsp(pluginName)
2691
- if (initialEnabled) {
2692
- // Auto-register LSP servers declared by the plugin. The host packages
2693
- // (dsh-lsp / dsh-lsp-stdio / dsh-tool-lsp) were pre-provisioned by the
2694
- // hub's `apply()` at DSH startup — this step is a single, race-free
2695
- // patch write. `lspErrors` still surface other failures (the user-installed
2696
- // language server binary not on PATH, missing extensionToLanguage, etc.).
2697
- // Drop the previous version's server entries; the loop re-adds the ones this
2698
- // version still declares, so removed servers stop loading.
2699
- for (const r of registerPluginLsp(pluginName)) {
2700
- if (!r.ok && r.error) lspErrors.push(r.error)
2701
- }
2702
-
2703
- // Register the plugin's Claude/Codex hooks into DSH via the hooks bridge.
2704
- // The bridge package was pre-provisioned by the hub's `apply()`; this is a
2705
- // single patch write.
2706
- await registerPluginHooks(pluginName)
2707
- } else {
2708
- for (const c of pluginConnectors) {
2709
- toggleConnector(pluginName, c.name, false)
2896
+ withCordisPatchBatch(() => {
2897
+ for (const name of prevConnectors) {
2898
+ if (!pluginConnectors.some((c) => c.name === name)) unregisterConnector(pluginName, name)
2899
+ }
2900
+ unregisterPluginLsp(pluginName)
2901
+ if (initialEnabled) {
2902
+ // Auto-register LSP servers declared by the plugin. The host packages
2903
+ // (dsh-lsp / dsh-lsp-stdio / dsh-tool-lsp) were pre-provisioned by the
2904
+ // hub's `apply()` at DSH startup — this step is a single, race-free
2905
+ // patch write. `lspErrors` still surface other failures (the user-installed
2906
+ // language server binary not on PATH, missing extensionToLanguage, etc.).
2907
+ // Drop the previous version's server entries; the loop re-adds the ones this
2908
+ // version still declares, so removed servers stop loading.
2909
+ for (const r of registerPluginLsp(pluginName)) {
2910
+ if (!r.ok && r.error) lspErrors.push(r.error)
2911
+ }
2912
+
2913
+ // Register the plugin's Claude/Codex hooks into DSH via the hooks bridge.
2914
+ // The bridge package was pre-provisioned by the hub's `apply()`; this is a
2915
+ // single patch write.
2916
+ registerPluginHooksSync(pluginName)
2917
+ } else {
2918
+ for (const c of pluginConnectors) {
2919
+ toggleConnector(pluginName, c.name, false)
2920
+ }
2921
+ unregisterPluginHooks(pluginName)
2710
2922
  }
2711
- unregisterPluginHooks(pluginName)
2712
- }
2923
+ })
2713
2924
 
2714
2925
  const record = {
2715
2926
  id: `${sourceId}/${pluginName}`,
@@ -2907,8 +3118,8 @@ async function togglePluginUnlocked(pluginName, enabled, epoch, options = {}) {
2907
3118
  for (const r of registerPluginLsp(pluginName)) {
2908
3119
  if (!r.ok && r.error) lspErrors.push(r.error)
2909
3120
  }
3121
+ registerPluginHooksSync(pluginName)
2910
3122
  })
2911
- await registerPluginHooks(pluginName)
2912
3123
  } catch (err) {
2913
3124
  if (rec.enabled === false) await rollbackEnable()
2914
3125
  throw err
@@ -3002,46 +3213,61 @@ async function togglePluginUnlocked(pluginName, enabled, epoch, options = {}) {
3002
3213
  * reinstall the plugin copy and re-run conversions.
3003
3214
  */
3004
3215
  export async function updatePlugin(pluginName) {
3216
+ const lockKey = pluginLockKey(pluginName)
3217
+ if (activePluginUpdates.has(lockKey)) {
3218
+ throw Object.assign(new Error(`插件 ${pluginName} 正在更新`), { status: 409 })
3219
+ }
3220
+ if (marketplaceInstalls.has(lockKey)) {
3221
+ throw Object.assign(new Error(`插件 ${pluginName} 正在安装`), { status: 409 })
3222
+ }
3223
+ activePluginUpdates.add(lockKey)
3005
3224
  bumpPluginEpoch(pluginName)
3006
3225
  cancelActivePluginProbes(pluginName)
3007
- return withPluginLock(pluginName, async () => {
3008
- const initialRec = readState().plugins.find((p) => p.name === pluginName)
3009
- if (!initialRec) throw new Error(`plugin not installed: ${pluginName}`)
3010
- return withSourceLock(initialRec.sourceId, async () => {
3011
- const state = readState()
3012
- const rec = state.plugins.find((p) => p.name === pluginName)
3013
- if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
3014
- if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
3015
- throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
3016
- }
3017
- const source = state.sources.find((s) => s.id === rec.sourceId)
3018
- if (source && typeof source.url === 'string') {
3019
- const cacheDir = sourceCacheDir(rec.sourceId)
3020
- if (existsSync(join(cacheDir, '.git'))) {
3021
- await pullSource(rec.sourceId)
3226
+ try {
3227
+ return await withPluginLock(pluginName, async () => {
3228
+ const initialRec = readState().plugins.find((p) => p.name === pluginName)
3229
+ if (!initialRec) throw new Error(`plugin not installed: ${pluginName}`)
3230
+ return withSourceLock(initialRec.sourceId, async () => {
3231
+ const state = readState()
3232
+ const rec = state.plugins.find((p) => p.name === pluginName)
3233
+ if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
3234
+ if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
3235
+ throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
3236
+ }
3237
+ const source = state.sources.find((s) => s.id === rec.sourceId)
3238
+ let sourcePulled = false
3239
+ if (source && typeof source.url === 'string') {
3240
+ const cacheDir = sourceCacheDir(rec.sourceId)
3241
+ if (existsSync(join(cacheDir, '.git'))) {
3242
+ await pullSource(rec.sourceId)
3243
+ sourcePulled = true
3244
+ }
3022
3245
  }
3023
- }
3024
3246
 
3025
- // Clear memory cache so fresh MCP tool lists can be queried
3026
- for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
3027
- if (k.startsWith(`${pluginName}::`)) {
3028
- MEMORY_TOOLS_CACHE.delete(k)
3247
+ // Clear memory cache so fresh MCP tool lists can be queried
3248
+ for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
3249
+ if (k.startsWith(`${pluginName}::`)) {
3250
+ MEMORY_TOOLS_CACHE.delete(k)
3251
+ }
3029
3252
  }
3030
- }
3031
3253
 
3032
- // The marketplace rows are cached for 30s; without this the install below
3033
- // re-reads the pre-pull catalog and installs the old revision.
3034
- invalidateMarketplaceCache(rec.sourceId)
3254
+ // The marketplace rows are cached for 30s; without this the install below
3255
+ // re-reads the pre-pull catalog and installs the old revision.
3256
+ invalidateMarketplaceCache(rec.sourceId)
3035
3257
 
3036
- // Freshly materialized install (re-copies, re-registers, re-converts).
3037
- return installMarketplacePluginFromSourceLocked({
3038
- sourceId: rec.sourceId,
3039
- pluginName,
3040
- refresh: true,
3041
- initialEnabled: rec.enabled !== false,
3258
+ // Freshly materialized install (re-copies, re-registers, re-converts).
3259
+ return installMarketplacePluginFromSourceLocked({
3260
+ sourceId: rec.sourceId,
3261
+ pluginName,
3262
+ refresh: true,
3263
+ sourcePulled,
3264
+ initialEnabled: rec.enabled !== false,
3265
+ })
3042
3266
  })
3043
3267
  })
3044
- })
3268
+ } finally {
3269
+ activePluginUpdates.delete(lockKey)
3270
+ }
3045
3271
  }
3046
3272
 
3047
3273
  /**
@@ -3126,7 +3352,7 @@ function mcpPublicToolName(server, rawName) {
3126
3352
  /** Public branding only. Connector configuration and tool arguments stay out of this response. */
3127
3353
  export function toolCallIconGroups() {
3128
3354
  const registrations = readCordisPatch().flatMap(block => block?.insert || [])
3129
- .filter(entry => entry?.name === '@deepseek-ai/dsh-mcp-client' && /^[A-Za-z0-9_-]{1,32}$/.test(entry.config?.serverName || ''))
3355
+ .filter(entry => entry?.name === '@deepseek-ai/dsh-mcp-client' && typeof entry.config?.serverName === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(entry.config.serverName))
3130
3356
  const byServer = new Map()
3131
3357
  for (const entry of registrations) {
3132
3358
  const server = entry.config.serverName
@@ -3226,7 +3452,7 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3226
3452
 
3227
3453
  const target = installedDir(rec.name)
3228
3454
  const installed = existsSync(target)
3229
- if (installed && !PLUGIN_LOCKS.has(rec.name)) {
3455
+ if (installed && !PLUGIN_LOCKS.has(pluginLockKey(rec.name))) {
3230
3456
  const skillsDir = join(target, 'skills')
3231
3457
  try {
3232
3458
  for (const entry of readdirSync(target, { withFileTypes: true })) {
@@ -3375,8 +3601,8 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3375
3601
  connectors,
3376
3602
  hooks: listHooks(target, targetManifest),
3377
3603
  lspServers,
3378
- version: targetManifest?.version ?? null,
3379
- } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
3604
+ version: targetManifest?.version ?? rec.version ?? null,
3605
+ } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: rec.version ?? null }
3380
3606
  const shortDescription = rec.shortDescription || (installed ? readPluginShortDescription(target) : '') || marketRow?.shortDescription || ''
3381
3607
  return {
3382
3608
  ...rec,