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/install.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * agents.
9
9
  */
10
10
  import { existsSync, lstatSync, mkdirSync, rmSync, readFileSync, writeFileSync, renameSync, readdirSync, copyFileSync, statSync, accessSync, constants as fsConstants } from 'node:fs'
11
+ import { copyFile, lstat, readdir, readlink, stat, symlink, unlink } from 'node:fs/promises'
11
12
  import { fileURLToPath } from 'node:url'
12
13
  import { dirname, join, basename, isAbsolute, resolve, extname, delimiter, sep } from 'node:path'
13
14
  import { execFile, execFileSync } from 'node:child_process'
@@ -15,20 +16,22 @@ import { gunzipSync } from 'node:zlib'
15
16
  import { createHash } from 'node:crypto'
16
17
  import { homedir } from 'node:os'
17
18
  import { setImmediate as yieldToHost, setTimeout as delay } from 'node:timers/promises'
19
+ import semver from 'semver'
18
20
  import * as yaml from 'js-yaml'
19
21
  import { Client } from '@modelcontextprotocol/sdk/client/index.js'
20
22
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
21
23
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
22
24
  import { ErrorCode } from '@modelcontextprotocol/sdk/types.js'
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, mergeManifestWithRow, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
25
+ import { installedDir, pluginDataDir, compiledHooksPath, marketRoot, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, removeManagedDir, quarantineFileToTrash, sourceCacheDir, trashRoot, isSameOrInsidePath } from './store.js'
26
+ import { materializePlugin, pullSource, sourceRepositoryDir, normalizeRemotePluginSource, remoteCheckoutDir, pluginPath } from './market.js'
27
+ 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
28
  import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
27
29
  import { isUploadedSkillTarget } from './skill-uploads.js'
28
30
  import { buildPluginIcons } from './icons.js'
29
31
  import { beginOAuthVerification, completeOAuthVerification, cancelPluginOAuthVerifications, standaloneOAuthConnectorNames, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
30
32
  import { bridgeRuntimeEnv, encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
31
33
  import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord, openOAuthRecordWriter } from './oauth-store.js'
34
+ import { invalidateHooksCache } from './hooks.js'
32
35
 
33
36
  const OAUTH_BRIDGE_PATH = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
34
37
 
@@ -350,9 +353,11 @@ function setRemoteVerification(pluginName, connectorName, payload, verified) {
350
353
  if (live && remoteConfigFingerprint(remoteConfigFromEntry(live) || live) !== fingerprint) return
351
354
  const key = `${pluginName}::${connectorName}`
352
355
  const state = readMcpToolsState()
356
+ const nextFingerprint = verified ? fingerprint : null
357
+ if (state[key]?.verifiedRemoteConfig === nextFingerprint) return
353
358
  state[key] = {
354
359
  ...(state[key] || {}),
355
- verifiedRemoteConfig: verified ? fingerprint : null,
360
+ verifiedRemoteConfig: nextFingerprint,
356
361
  }
357
362
  writeMcpToolsState(state)
358
363
  }
@@ -826,10 +831,8 @@ const LSP_TOOL_PKG = '@deepseek-ai/dsh-tool-lsp'
826
831
  /** Host-side packages that LSP registration depends on (installed into the DSH installation). */
827
832
  export const LSP_HOST_PACKAGES = [LSP_DEF_PKG, LSP_STDIO_PKG, LSP_TOOL_PKG]
828
833
 
829
- /** DSH's Claude Code hook bridge + its wire-protocol peer, provisioned like LSP packages. */
830
- const HOOK_BRIDGE_PKG = '@deepseek-ai/dsh-hooks-claude-code'
831
- const HOOK_PROTOCOL_PKG = '@deepseek-ai/dsh-hook-protocol'
832
- export const HOOK_HOST_PACKAGES = [HOOK_BRIDGE_PKG, HOOK_PROTOCOL_PKG]
834
+ /** Legacy external Claude Code hook bridge package name (used only to migrate old cordis.patch.yml entries). */
835
+ const LEGACY_HOOK_BRIDGE_PKG = '@deepseek-ai/dsh-hooks-claude-code'
833
836
 
834
837
  const NPM_BIN = process.platform === 'win32' ? 'npm.cmd' : 'npm'
835
838
 
@@ -985,6 +988,186 @@ function versionLine(v) {
985
988
  return String(v).split('-')[0].split('.').slice(0, 2).join('.')
986
989
  }
987
990
 
991
+ /** Major.minor.patch line of a semver string (e.g. "1.2.3-rc.1" -> "1.2.3"). */
992
+ function patchLine(v) {
993
+ return String(v).split('-')[0].split('.').slice(0, 3).join('.')
994
+ }
995
+
996
+ function isAsarPath(targetPath) {
997
+ return /(?:^|[\\/])[^\\/]+\.asar(?:[\\/]|$)/i.test(String(targetPath || ''))
998
+ }
999
+
1000
+ function isInsideDesktopBundle(targetPath) {
1001
+ if (!targetPath) return false
1002
+ for (const base of resolveDesktopCandidateDirs()) {
1003
+ const resourcesDir = basename(base).toLowerCase() === 'resources' ? base : join(base, 'resources')
1004
+ if (isSameOrInsidePath(targetPath, resourcesDir)) return true
1005
+ }
1006
+ return false
1007
+ }
1008
+
1009
+ function isWritableDir(dir) {
1010
+ try {
1011
+ accessSync(dir, fsConstants.W_OK)
1012
+ return true
1013
+ } catch {
1014
+ return false
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * Writable `node_modules` root where provisioned host packages should be extracted.
1020
+ * Desktop Electron builds locate `app.asar/dsh/node_modules` as a read-only virtual
1021
+ * directory; DSH's runtime interception layer resolves profile fallback packages from
1022
+ * `$DSH_HOME/profiles/node_modules` above `profiles/<name>/node_modules`, keeping them
1023
+ * isolated from pnpm pruning.
1024
+ */
1025
+ export function resolveHostPackageRoot(runtimeModules = findDshMainNodeModules()) {
1026
+ if (
1027
+ runtimeModules &&
1028
+ !isAsarPath(runtimeModules) &&
1029
+ !isInsideDesktopBundle(runtimeModules) &&
1030
+ isWritableDir(runtimeModules)
1031
+ ) {
1032
+ return runtimeModules
1033
+ }
1034
+ return join(dshHome(), 'profiles', 'node_modules')
1035
+ }
1036
+
1037
+ function readInstalledManifest(rootDir, packageName) {
1038
+ if (!rootDir || !packageName) return null
1039
+ const manifestPath = join(rootDir, packageName, 'package.json')
1040
+ if (!existsSync(manifestPath)) return null
1041
+ try {
1042
+ const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'))
1043
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null
1044
+ } catch {
1045
+ return null
1046
+ }
1047
+ }
1048
+
1049
+ /**
1050
+ * Evaluate whether a host package manifest is compatible with the running DSH version,
1051
+ * mirroring `@deepseek-ai/dsh-app-boot`'s preflight gate (`engines.dsh`, else
1052
+ * `@deepseek-ai/dsh*` peerDependencies, else exact version fallback).
1053
+ */
1054
+ export function evaluateHostPackageCompatibility(manifest, dshVersion) {
1055
+ const target = typeof dshVersion === 'string' ? dshVersion.trim() : ''
1056
+ if (!target) return { compatible: true, explicit: false }
1057
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
1058
+ return { compatible: false, explicit: false }
1059
+ }
1060
+ const validDsh = semver.valid(target) || semver.coerce(target)?.version || ''
1061
+ const satisfiesDsh = (range) =>
1062
+ typeof range === 'string' &&
1063
+ range.trim() !== '' &&
1064
+ Boolean(validDsh) &&
1065
+ semver.satisfies(validDsh, range, { includePrerelease: true })
1066
+
1067
+ const engines = manifest.engines && typeof manifest.engines === 'object' && !Array.isArray(manifest.engines)
1068
+ ? manifest.engines
1069
+ : null
1070
+ if (engines && Object.hasOwn(engines, 'dsh')) {
1071
+ return { compatible: satisfiesDsh(engines.dsh), explicit: true }
1072
+ }
1073
+
1074
+ const peers = manifest.peerDependencies && typeof manifest.peerDependencies === 'object' && !Array.isArray(manifest.peerDependencies)
1075
+ ? manifest.peerDependencies
1076
+ : null
1077
+ if (peers) {
1078
+ const dshPeers = Object.entries(peers).filter(([dep]) => dep === '@deepseek-ai/dsh' || dep.startsWith('@deepseek-ai/dsh-'))
1079
+ if (dshPeers.length > 0) {
1080
+ for (const [, range] of dshPeers) {
1081
+ if (typeof range !== 'string' || !range.trim()) return { compatible: false, explicit: true }
1082
+ const req = ['workspace:^', 'workspace:~', 'workspace:*'].includes(range) ? validDsh : range
1083
+ if (!satisfiesDsh(req)) return { compatible: false, explicit: true }
1084
+ }
1085
+ return { compatible: true, explicit: true }
1086
+ }
1087
+ }
1088
+
1089
+ const present = typeof manifest.version === 'string' ? manifest.version.trim() : ''
1090
+ return { compatible: present === target, explicit: false }
1091
+ }
1092
+
1093
+ /**
1094
+ * True when every listed host package is installed and compatible with the running DSH release
1095
+ * in the writable host root (or native runtime when not shadowed by an incompatible copy).
1096
+ */
1097
+ export function hasHostPackagesInstalled(packageNames, runtimeModules = findDshMainNodeModules(), dshVersion = undefined) {
1098
+ const names = Array.from(new Set((packageNames || []).filter((n) => typeof n === 'string' && n.trim())))
1099
+ if (names.length === 0) return true
1100
+ const main = resolveHostPackageRoot(runtimeModules)
1101
+ const sharedNm = join(dshHome(), 'profiles', 'node_modules')
1102
+ const targetVersion = dshVersion !== undefined ? dshVersion : findDshVersion(runtimeModules)
1103
+ return names.every((name) => {
1104
+ if (sharedNm !== main && existsSync(join(sharedNm, name))) {
1105
+ const sharedManifest = readInstalledManifest(sharedNm, name)
1106
+ if (!sharedManifest || !evaluateHostPackageCompatibility(sharedManifest, targetVersion).compatible) {
1107
+ return false
1108
+ }
1109
+ }
1110
+ const localManifest = readInstalledManifest(main, name)
1111
+ if (localManifest) {
1112
+ return evaluateHostPackageCompatibility(localManifest, targetVersion).compatible
1113
+ }
1114
+ if (existsSync(join(main, name))) return false
1115
+ if (runtimeModules && runtimeModules !== main) {
1116
+ const nativeManifest = readInstalledManifest(runtimeModules, name)
1117
+ return Boolean(nativeManifest && evaluateHostPackageCompatibility(nativeManifest, targetVersion).compatible)
1118
+ }
1119
+ return false
1120
+ })
1121
+ }
1122
+
1123
+ /**
1124
+ * Pick the published package version most compatible with the running DSH release:
1125
+ * exact compatible release -> highest contract-compatible version -> same patch/minor/latest fallback.
1126
+ */
1127
+ export function selectMatchingVersion(versionsOrMap, dshVersion) {
1128
+ const manifests = versionsOrMap && !Array.isArray(versionsOrMap) && typeof versionsOrMap === 'object'
1129
+ ? versionsOrMap
1130
+ : null
1131
+ const rawList = manifests ? Object.keys(manifests) : (Array.isArray(versionsOrMap) ? versionsOrMap : [])
1132
+ const list = rawList.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim())
1133
+ if (list.length === 0) return ''
1134
+
1135
+ const target = String(dshVersion || '').trim()
1136
+ if (target && list.includes(target)) {
1137
+ const meta = manifests?.[target]
1138
+ const ok = !manifests || (meta && typeof meta === 'object' && evaluateHostPackageCompatibility({ ...meta, version: meta.version || target }, target).compatible)
1139
+ if (ok) return target
1140
+ }
1141
+
1142
+ if (manifests && target) {
1143
+ const compatiblePool = list.filter((v) => {
1144
+ const meta = manifests[v]
1145
+ if (!meta || typeof meta !== 'object') return false
1146
+ const res = evaluateHostPackageCompatibility({ ...meta, version: meta.version || v }, target)
1147
+ return res.explicit && res.compatible
1148
+ })
1149
+ if (compatiblePool.length > 0) {
1150
+ let best = ''
1151
+ for (const v of compatiblePool) {
1152
+ if (semverGt(v, best)) best = v
1153
+ }
1154
+ return best
1155
+ }
1156
+ }
1157
+
1158
+ const pLine = target ? patchLine(target) : ''
1159
+ const patchPool = pLine ? list.filter((v) => patchLine(v) === pLine) : []
1160
+ const mLine = target ? versionLine(target) : ''
1161
+ const minorPool = mLine ? list.filter((v) => versionLine(v) === mLine) : []
1162
+ const candidates = patchPool.length > 0 ? patchPool : (minorPool.length > 0 ? minorPool : list)
1163
+
1164
+ let best = ''
1165
+ for (const v of candidates) {
1166
+ if (semverGt(v, best)) best = v
1167
+ }
1168
+ return best
1169
+ }
1170
+
988
1171
  /** Read the running DSH release version from its installation, or '' when unknown. */
989
1172
  export function findDshVersion(main = findDshMainNodeModules()) {
990
1173
  if (main) {
@@ -1008,127 +1191,128 @@ export function findDshVersion(main = findDshMainNodeModules()) {
1008
1191
  return ''
1009
1192
  }
1010
1193
 
1011
- /**
1012
- * Highest published version of a package whose major.minor line matches the
1013
- * running DSH release — the host bridge packages the hub provisions
1014
- * (@deepseek-ai/dsh-hooks-claude-code, dsh-lsp-stdio, ...) are published in
1015
- * lockstep with DSH, so the same line is the compatible one. Falls back to the
1016
- * highest overall when the running DSH's line has no published match. This is
1017
- * deliberately neither the `latest` dist-tag (which can lag behind — e.g. the
1018
- * hooks bridge latest=0.0.1-rc.5 while 0.1.1-rc.2 exists) nor a hard pin (which
1019
- * would break once the user's DSH moves to a new line).
1020
- */
1021
- export async function matchingPublishedVersion(packageName, dshVersion) {
1194
+ async function fetchPackageRegistryMeta(packageName) {
1022
1195
  try {
1023
1196
  const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageName)}`, { headers: { accept: 'application/json' } })
1024
- let versions = []
1025
1197
  if (res.ok) {
1026
1198
  const data = await res.json()
1027
- versions = Object.keys(data.versions || {})
1028
- } else {
1029
- const out = await runNpm(['view', packageName, 'versions', '--json'], dirname(cordisPatchPath()))
1030
- const parsed = JSON.parse(out)
1031
- if (Array.isArray(parsed)) versions = parsed.filter((v) => typeof v === 'string')
1032
- }
1033
- if (versions.length === 0) return ''
1034
- const line = versionLine(dshVersion ?? findDshVersion())
1035
- const pool = line ? versions.filter((v) => versionLine(v) === line) : []
1036
- const candidates = pool.length > 0 ? pool : versions
1037
- let best = ''
1038
- for (const v of candidates) {
1039
- if (semverGt(v, best)) best = v
1040
- }
1041
- return best
1199
+ const versionsMap = data?.versions && typeof data.versions === 'object' && !Array.isArray(data.versions) ? data.versions : {}
1200
+ return { versionsMap, versions: Object.keys(versionsMap) }
1201
+ }
1202
+ } catch {}
1203
+ try {
1204
+ const out = await runNpm(['view', packageName, 'versions', '--json'], dirname(cordisPatchPath()))
1205
+ const parsed = JSON.parse(out)
1206
+ const versions = Array.isArray(parsed) ? parsed.filter((v) => typeof v === 'string') : []
1207
+ return { versionsMap: null, versions }
1042
1208
  } catch {
1043
- return ''
1209
+ return { versionsMap: null, versions: [] }
1044
1210
  }
1045
1211
  }
1046
1212
 
1047
- /** Compare two semver strings (prerelease-aware). */
1213
+ /**
1214
+ * Highest published version of a package compatible with the running DSH release
1215
+ * according to its declared `engines.dsh` / `@deepseek-ai/dsh*` peerDependencies
1216
+ * contract, falling back to patch/minor release-line matching when no compatible
1217
+ * build is published yet.
1218
+ */
1219
+ export async function matchingPublishedVersion(packageName, dshVersion) {
1220
+ const meta = await fetchPackageRegistryMeta(packageName)
1221
+ if (meta.versions.length === 0) return ''
1222
+ return selectMatchingVersion(meta.versionsMap || meta.versions, dshVersion ?? findDshVersion())
1223
+ }
1224
+
1225
+ /** Compare two version strings using SemVer 2.0 (with loose coercion fallback for marketplace metadata). */
1048
1226
  function semverGt(a, b) {
1049
- if (!b) return true
1050
- const parse = (v) => {
1051
- const [core, pre] = String(v).split('-')
1052
- const [maj, min, pat] = core.split('.').map((n) => parseInt(n, 10) || 0)
1053
- return { maj, min, pat, pre: pre || '' }
1054
- }
1055
- const pa = parse(a)
1056
- const pb = parse(b)
1057
- for (const k of ['maj', 'min', 'pat']) {
1058
- if (pa[k] !== pb[k]) return pa[k] > pb[k]
1059
- }
1060
- if (!pa.pre && !pb.pre) return false
1061
- if (!pa.pre) return true
1062
- if (!pb.pre) return false
1063
- return pa.pre > pb.pre
1227
+ if (!b) return Boolean(a)
1228
+ if (!a) return false
1229
+ const va = semver.valid(a) || semver.coerce(a)
1230
+ const vb = semver.valid(b) || semver.coerce(b)
1231
+ if (va && vb) return semver.gt(va, vb)
1232
+ return String(a) > String(b)
1064
1233
  }
1065
1234
 
1066
1235
  /**
1067
- * Provision host-side packages into the DSH installation's node_modules,
1068
- * pinned to the newest published version. Packages already present are left
1069
- * untouched. This mirrors what installing a forum plugin does — the plugin
1070
- * brings its host dependencies with it, and DSH picks them up on restart.
1236
+ * Provision host-side packages into the writable DSH host root, validating
1237
+ * installed packages against the running DSH compatibility contract so rc/stable
1238
+ * upgrades automatically repair stale host bridges without affecting unrelated
1239
+ * runtime packages.
1071
1240
  */
1072
- export async function installProfilePackages(packageNames) {
1241
+ export async function installProfilePackages(packageNames, options = {}) {
1073
1242
  const names = Array.from(new Set((packageNames || []).filter((n) => typeof n === 'string' && n.trim())))
1074
1243
  if (names.length === 0) return { ok: true, installed: [] }
1075
1244
 
1076
- const runtimeModules = findDshMainNodeModules()
1077
- let main = runtimeModules
1078
- if (!main) {
1079
- const sharedNm = join(dshHome(), 'profiles', 'node_modules')
1080
- const activeNm = join(dshHome(), 'profiles', resolveActiveProfileName(), 'node_modules')
1081
- // The shared tree is the loader's primary runtime directory; prefer it
1082
- // whenever it exists. `findDshMainNodeModules` can miss it when its
1083
- // dsh-app-boot probe is a dangling symlink (e.g. left by an npx cache wipe).
1084
- main = existsSync(sharedNm) ? sharedNm : activeNm
1085
- try { mkdirSync(main, { recursive: true }) } catch {}
1086
- }
1087
-
1088
- // A host package from a different major.minor line than the running DSH
1089
- // release is stale: skipping it because the directory exists left the hooks
1090
- // and LSP bridges pinned to whatever line was current at first provision.
1091
- const dshVersion = findDshVersion(runtimeModules)
1245
+ const runtimeModules = options.runtimeModules !== undefined ? options.runtimeModules : findDshMainNodeModules()
1246
+ const main = resolveHostPackageRoot(runtimeModules)
1247
+ try { mkdirSync(main, { recursive: true }) } catch {}
1248
+
1249
+ const dshVersion = options.dshVersion !== undefined ? options.dshVersion : findDshVersion(runtimeModules)
1092
1250
  const dshLine = versionLine(dshVersion)
1251
+ const dshPatchLine = patchLine(dshVersion)
1252
+ const sharedNm = join(dshHome(), 'profiles', 'node_modules')
1253
+ const removeIncompatibleShadow = (rootDir, pkgName) => {
1254
+ if (!rootDir || !existsSync(join(rootDir, pkgName))) return
1255
+ const manifest = readInstalledManifest(rootDir, pkgName)
1256
+ if (!manifest || !evaluateHostPackageCompatibility(manifest, dshVersion).compatible) {
1257
+ safeRmDir(join(rootDir, pkgName))
1258
+ }
1259
+ }
1093
1260
  const need = new Map()
1094
1261
  for (const name of names) {
1095
- const installedManifest = join(main, name, 'package.json')
1096
- if (!existsSync(installedManifest)) {
1097
- need.set(name, '')
1262
+ if (runtimeModules) {
1263
+ const nativeManifest = readInstalledManifest(runtimeModules, name)
1264
+ if (nativeManifest && evaluateHostPackageCompatibility(nativeManifest, dshVersion).compatible) {
1265
+ if (main !== runtimeModules) removeIncompatibleShadow(main, name)
1266
+ if (sharedNm !== runtimeModules && sharedNm !== main) removeIncompatibleShadow(sharedNm, name)
1267
+ continue
1268
+ }
1269
+ }
1270
+ const localManifest = readInstalledManifest(main, name)
1271
+ if (!localManifest) {
1272
+ need.set(name, null)
1098
1273
  continue
1099
1274
  }
1100
- if (!dshLine) continue
1101
- try {
1102
- const present = JSON.parse(readFileSync(installedManifest, 'utf8')).version
1103
- if (typeof present !== 'string' || versionLine(present) === dshLine) continue
1104
- // Re-provision only when a build for the running line actually exists;
1105
- // otherwise the same mismatched version would be reinstalled every start.
1106
- const version = await matchingPublishedVersion(name, dshVersion)
1107
- if (versionLine(version) === dshLine) need.set(name, version)
1108
- } catch {}
1275
+ if (!dshVersion) continue
1276
+ if (evaluateHostPackageCompatibility(localManifest, dshVersion).compatible) continue
1277
+
1278
+ // Re-provision only when a compatible or running-line build exists;
1279
+ // otherwise an unpublished canary/local DSH would reinstall on every start.
1280
+ const present = typeof localManifest.version === 'string' ? localManifest.version.trim() : ''
1281
+ const meta = await fetchPackageRegistryMeta(name)
1282
+ const version = selectMatchingVersion(meta.versionsMap || meta.versions, dshVersion)
1283
+ const candidateManifest = version && meta.versionsMap?.[version]
1284
+ ? { ...meta.versionsMap[version], version: meta.versionsMap[version].version || version }
1285
+ : null
1286
+ const candidateCompatible = candidateManifest
1287
+ ? evaluateHostPackageCompatibility(candidateManifest, dshVersion).compatible
1288
+ : false
1289
+ if (
1290
+ version &&
1291
+ version !== present &&
1292
+ (
1293
+ version === dshVersion ||
1294
+ candidateCompatible ||
1295
+ (dshPatchLine && patchLine(version) === dshPatchLine) ||
1296
+ (dshLine && versionLine(version) === dshLine)
1297
+ )
1298
+ ) {
1299
+ need.set(name, { version, meta })
1300
+ }
1109
1301
  }
1110
1302
  if (need.size === 0) return { ok: true, installed: [] }
1111
1303
 
1112
1304
  // Install each package by downloading its tarball and extracting it into the
1113
- // installation's node_modules. Do NOT run `npm install` against the DSH
1305
+ // writable host node_modules root. Do NOT run `npm install` against the DSH
1114
1306
  // installation root: npm's reify re-resolves the whole tree and prunes
1115
1307
  // packages that are not in the manifest, which has deleted DSH runtime
1116
1308
  // packages in the wild. A raw tarball extract has zero side effects.
1117
1309
  const installed = []
1118
- for (const [name, version] of need) {
1310
+ for (const [name, planned] of need) {
1119
1311
  try {
1120
- // Resolve a version compatible with the running DSH release (same major.minor
1121
- // line as the installed DSH), not the `latest` dist-tag which can lag behind.
1122
- const ver = version || await matchingPublishedVersion(name, dshVersion)
1312
+ const meta = planned?.meta || await fetchPackageRegistryMeta(name)
1313
+ const ver = planned?.version || selectMatchingVersion(meta.versionsMap || meta.versions, dshVersion)
1123
1314
  if (!ver) return { ok: false, error: `无法确定 ${name} 的匹配版本`, installed }
1124
- let url = null
1125
- try {
1126
- const resMeta = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`, { headers: { accept: 'application/json' } })
1127
- if (resMeta.ok) {
1128
- const meta = await resMeta.json()
1129
- url = meta.versions?.[ver]?.dist?.tarball
1130
- }
1131
- } catch {}
1315
+ let url = meta.versionsMap?.[ver]?.dist?.tarball || null
1132
1316
  if (!url) {
1133
1317
  try {
1134
1318
  const tarballOut = await runNpm(['view', `${name}@${ver}`, 'dist.tarball'], dirname(main))
@@ -1338,17 +1522,60 @@ export function registerPluginLsp(pluginName) {
1338
1522
  return results
1339
1523
  }
1340
1524
 
1341
- /** Patch id of a plugin's Claude hooks bridge entry. */
1525
+ /** Legacy patch id of a plugin's external hooks bridge entry. */
1342
1526
  export function getHookBridgeId(pluginName) {
1343
1527
  return `hooks-${slugify(pluginName)}`
1344
1528
  }
1345
1529
 
1346
- /** Synchronously compile and register a plugin's hooks inside an active cordis patch batch. */
1530
+ function hasLegacyHookBridgeEntry(pluginName) {
1531
+ const hookId = getHookBridgeId(pluginName)
1532
+ for (const block of readCordisPatch()) {
1533
+ if (!block || !Array.isArray(block.insert)) continue
1534
+ for (const entry of block.insert) {
1535
+ if (entry?.id === hookId && entry?.name === LEGACY_HOOK_BRIDGE_PKG) return true
1536
+ }
1537
+ }
1538
+ return false
1539
+ }
1540
+
1541
+ function removeLegacyHookEntryFromPatch(pluginName) {
1542
+ const id = getHookBridgeId(pluginName)
1543
+ const patch = readCordisPatch()
1544
+ let changed = false
1545
+ for (const item of patch) {
1546
+ if (item && Array.isArray(item.insert)) {
1547
+ const before = item.insert.length
1548
+ item.insert = item.insert.filter((entry) => entry && !(entry.id === id && (!entry.name || entry.name === LEGACY_HOOK_BRIDGE_PKG)))
1549
+ if (item.insert.length !== before) changed = true
1550
+ }
1551
+ }
1552
+ const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
1553
+ if (changed) {
1554
+ writeCordisPatch(cleaned)
1555
+ }
1556
+ }
1557
+
1558
+ /** Host packages referenced by a plugin's active patch entries (LSP only; hooks run natively). */
1559
+ export function requiredHostPackagesForPlugin(pluginName) {
1560
+ const slug = slugify(pluginName)
1561
+ const lspPrefix = `lsp-${slug}-`
1562
+ let needsLsp = false
1563
+ for (const block of readCordisPatch()) {
1564
+ if (!block || !Array.isArray(block.insert)) continue
1565
+ for (const entry of block.insert) {
1566
+ if (!entry || typeof entry.id !== 'string') continue
1567
+ if (entry.id.startsWith(lspPrefix)) needsLsp = true
1568
+ }
1569
+ }
1570
+ return needsLsp ? [...LSP_HOST_PACKAGES] : []
1571
+ }
1572
+
1573
+ /** Synchronously compile a plugin's hooks for the native hook runtime and clean any legacy bridge entry. */
1347
1574
  function registerPluginHooksSync(pluginName) {
1348
1575
  const target = installedDir(pluginName)
1349
1576
  const dataDir = pluginDataDir(pluginName)
1350
1577
  const compiled = compileResolvedHooks(target, readPluginManifest(target), dataDir)
1351
- // A version that dropped its hooks must also lose the previous bridge entry,
1578
+ // A version that dropped its hooks must also lose the previous compiled config,
1352
1579
  // otherwise the old hooks keep firing after reinstall.
1353
1580
  if (!compiled) {
1354
1581
  unregisterPluginHooks(pluginName)
@@ -1360,59 +1587,101 @@ function registerPluginHooksSync(pluginName) {
1360
1587
  mkdirSync(dataDir, { recursive: true })
1361
1588
  writeFileSync(outPath, JSON.stringify(compiled, null, 2), 'utf8')
1362
1589
 
1363
- const patch = readCordisPatch()
1364
- const id = getHookBridgeId(pluginName)
1365
- const block = ensureInsertBlock(patch)
1366
- block.insert = block.insert.filter((item) => item && item.id !== id)
1367
- block.insert.push({
1368
- id,
1369
- name: HOOK_BRIDGE_PKG,
1370
- config: {
1371
- configPath: outPath,
1372
- pluginRoot: target,
1373
- },
1374
- })
1375
- writeCordisPatch(patch)
1590
+ if (hasLegacyHookBridgeEntry(pluginName)) {
1591
+ removeLegacyHookEntryFromPatch(pluginName)
1592
+ }
1593
+ invalidateHooksCache()
1376
1594
  return { ok: true, registered: [outPath] }
1377
1595
  }
1378
1596
 
1379
1597
  /**
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.
1598
+ * Compile an installed plugin's Claude/Codex hooks for the hub's native Cordis hook
1599
+ * runtime (`src/hooks.js`) and remove any legacy external bridge entry.
1389
1600
  */
1390
1601
  export async function registerPluginHooks(pluginName) {
1391
1602
  return registerPluginHooksSync(pluginName)
1392
1603
  }
1393
1604
 
1394
- /** Remove a plugin's hooks bridge entry from cordis.patch.yml. */
1605
+ /** Remove a plugin's compiled hooks config and any legacy bridge entry from cordis.patch.yml. */
1395
1606
  export function unregisterPluginHooks(pluginName) {
1396
- const patch = readCordisPatch()
1397
- const id = getHookBridgeId(pluginName)
1398
- let changed = false
1399
- for (const item of patch) {
1400
- if (item && Array.isArray(item.insert)) {
1401
- const before = item.insert.length
1402
- item.insert = item.insert.filter((entry) => entry && entry.id !== id)
1403
- if (item.insert.length !== before) changed = true
1404
- }
1405
- }
1406
- const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
1407
- if (changed || cleaned.length !== patch.length) {
1408
- writeCordisPatch(cleaned)
1607
+ if (hasLegacyHookBridgeEntry(pluginName)) {
1608
+ removeLegacyHookEntryFromPatch(pluginName)
1409
1609
  }
1410
1610
  try {
1411
1611
  rmSync(compiledHooksPath(pluginName), { force: true })
1412
1612
  } catch {}
1613
+ invalidateHooksCache()
1413
1614
  return { ok: true }
1414
1615
  }
1415
1616
 
1617
+ /**
1618
+ * One-time migration on startup: remove hub-managed `@deepseek-ai/dsh-hooks-claude-code`
1619
+ * entries from `cordis.patch.yml` (preserving user-authored entries) and refresh
1620
+ * compiled hook configs for enabled plugins so native metadata is complete.
1621
+ */
1622
+ export function migrateLegacyHookBridges() {
1623
+ const state = readState()
1624
+ const plugins = Array.isArray(state?.plugins) ? state.plugins : []
1625
+ const installedHookIds = new Set(plugins.filter((p) => p?.name).map((p) => getHookBridgeId(p.name)))
1626
+ const compiledRoot = join(marketRoot(), 'compiled-hooks')
1627
+ const removed = []
1628
+
1629
+ const patchFile = cordisPatchPath()
1630
+ if (existsSync(patchFile)) {
1631
+ try {
1632
+ const patch = loadCordisPatch(patchFile)
1633
+ const pendingRemoved = []
1634
+ for (const block of patch) {
1635
+ if (!block || !Array.isArray(block.insert)) continue
1636
+ block.insert = block.insert.filter((entry) => {
1637
+ if (!entry || typeof entry.id !== 'string') return true
1638
+ const isManagedId = entry.id.startsWith('hooks-')
1639
+ const isLegacyBridgePkg = entry.name === LEGACY_HOOK_BRIDGE_PKG
1640
+ const cfgPath = entry.config?.configPath
1641
+ const pointsToHubCompiled = typeof cfgPath === 'string' && isSameOrInsidePath(cfgPath, compiledRoot)
1642
+ if (isManagedId && isLegacyBridgePkg && (pointsToHubCompiled || (!cfgPath && installedHookIds.has(entry.id)))) {
1643
+ pendingRemoved.push(entry.id)
1644
+ return false
1645
+ }
1646
+ return true
1647
+ })
1648
+ }
1649
+ if (pendingRemoved.length > 0) {
1650
+ const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
1651
+ writeCordisPatch(cleaned)
1652
+ removed.push(...pendingRemoved)
1653
+ }
1654
+ } catch {}
1655
+ }
1656
+
1657
+ const synced = []
1658
+ for (const rec of plugins) {
1659
+ if (!rec?.name || rec.name === 'user-mcp' || rec.enabled === false) continue
1660
+ try {
1661
+ const target = installedDir(rec.name)
1662
+ if (!existsSync(target)) continue
1663
+ const dataDir = pluginDataDir(rec.name)
1664
+ const compiled = compileResolvedHooks(target, readPluginManifest(target), dataDir)
1665
+ if (!compiled) continue
1666
+ const outPath = compiledHooksPath(rec.name)
1667
+ const serialized = JSON.stringify(compiled, null, 2)
1668
+ let prev = null
1669
+ try {
1670
+ if (existsSync(outPath)) prev = readFileSync(outPath, 'utf8')
1671
+ } catch {}
1672
+ if (prev !== serialized) {
1673
+ mkdirSync(dirname(outPath), { recursive: true })
1674
+ mkdirSync(dataDir, { recursive: true })
1675
+ writeFileSync(outPath, serialized, 'utf8')
1676
+ synced.push(rec.name)
1677
+ }
1678
+ } catch {}
1679
+ }
1680
+
1681
+ invalidateHooksCache()
1682
+ return { removed, synced }
1683
+ }
1684
+
1416
1685
  /** Active state for one LSP server of an installed plugin. */
1417
1686
  export function isLspActive(pluginName, serverName) {
1418
1687
  return !!getLspEntry(pluginName, serverName)
@@ -2143,14 +2412,14 @@ async function discoverConnectorTools(pluginName, connectorName, forceFresh, isC
2143
2412
 
2144
2413
  if (!forceFresh && MEMORY_TOOLS_CACHE.has(key)) {
2145
2414
  const mem = MEMORY_TOOLS_CACHE.get(key)
2146
- return { ok: mem.ok !== false, tools: mem.tools || [], disabledTools, ...(mem.message ? { message: mem.message } : {}) }
2415
+ return { ok: mem.ok !== false, cached: true, tools: mem.tools || [], disabledTools, ...(mem.message ? { message: mem.message } : {}) }
2147
2416
  }
2148
2417
 
2149
2418
  const entry = getConnectorEntry(pluginName, connectorName)
2150
2419
  const cached = state[key]?.cachedTools || []
2151
2420
  const hasCachedTools = cached.length > 0 || state[key]?.cachedToolsResolved === true
2152
2421
  const inactiveStandalone = pluginName === 'user-mcp' && !entry
2153
- if (hasCachedTools && (!forceFresh || inactiveStandalone)) return { ok: true, tools: cached, disabledTools }
2422
+ if (hasCachedTools && (!forceFresh || inactiveStandalone)) return { ok: true, cached: true, tools: cached, disabledTools }
2154
2423
  if (inactiveStandalone) return { ok: false, tools: [], disabledTools, message: 'MCP 服务未启用' }
2155
2424
 
2156
2425
  const definition = connectorDefinition(pluginName, connectorName,
@@ -2187,8 +2456,13 @@ function cacheConnectorTools(key, tools) {
2187
2456
  const owner = key.slice(0, key.indexOf('::'))
2188
2457
  if (owner !== 'user-mcp' && !readState().plugins.some((p) => p.name === owner)) return
2189
2458
  const state = readMcpToolsState()
2190
- state[key] = { ...state[key], cachedTools: tools, cachedToolsResolved: true }
2191
- writeMcpToolsState(state)
2459
+ const prev = state[key]
2460
+ const unchanged = prev?.cachedToolsResolved === true
2461
+ && JSON.stringify(prev.cachedTools || []) === JSON.stringify(tools || [])
2462
+ if (!unchanged) {
2463
+ state[key] = { ...prev, cachedTools: tools, cachedToolsResolved: true }
2464
+ writeMcpToolsState(state)
2465
+ }
2192
2466
  MEMORY_TOOLS_CACHE.set(key, { tools })
2193
2467
  }
2194
2468
 
@@ -2277,7 +2551,7 @@ export async function syncPluginSkillsToDsh(pluginName, shouldSync = () => true,
2277
2551
  }
2278
2552
 
2279
2553
  const settled = await Promise.allSettled(candidates.map(async (item) => {
2280
- if (await replaceManagedDir(item.srcSkillDir, item.destSkillDir, keepExisting, false, { allowTrash: true })) {
2554
+ if (await replaceManagedDirAsync(item.srcSkillDir, item.destSkillDir, keepExisting, false, { allowTrash: true, deferCleanup: true })) {
2281
2555
  synced.push(item.name)
2282
2556
  }
2283
2557
  }))
@@ -2311,13 +2585,18 @@ const PLUGIN_LOCKS = new Map()
2311
2585
  const SOURCE_LOCKS = new Map()
2312
2586
  const PLUGIN_EPOCHS = new Map()
2313
2587
 
2588
+ function pluginLockKey(pluginName) {
2589
+ return pluginName == null ? '' : String(pluginName).toLowerCase()
2590
+ }
2591
+
2314
2592
  function currentPluginEpoch(pluginName) {
2315
- return PLUGIN_EPOCHS.get(pluginName) || 0
2593
+ return PLUGIN_EPOCHS.get(pluginLockKey(pluginName)) || 0
2316
2594
  }
2317
2595
 
2318
2596
  function bumpPluginEpoch(pluginName) {
2319
- const next = currentPluginEpoch(pluginName) + 1
2320
- PLUGIN_EPOCHS.set(pluginName, next)
2597
+ const key = pluginLockKey(pluginName)
2598
+ const next = (PLUGIN_EPOCHS.get(key) || 0) + 1
2599
+ PLUGIN_EPOCHS.set(key, next)
2321
2600
  return next
2322
2601
  }
2323
2602
 
@@ -2341,7 +2620,7 @@ async function acquireKeyedLock(locks, key, fn) {
2341
2620
  * when the lock is idle so startup repair reaches its first fs attempt synchronously.
2342
2621
  */
2343
2622
  export function withPluginLock(pluginName, fn) {
2344
- return acquireKeyedLock(PLUGIN_LOCKS, pluginName, fn)
2623
+ return acquireKeyedLock(PLUGIN_LOCKS, pluginLockKey(pluginName), fn)
2345
2624
  }
2346
2625
 
2347
2626
  /**
@@ -2355,7 +2634,7 @@ export function withSourceLock(sourceId, fn) {
2355
2634
  async function retryManagedDirOperation(operation, destination) {
2356
2635
  for (let attempt = 0; ; attempt++) {
2357
2636
  try {
2358
- return operation()
2637
+ return await operation()
2359
2638
  } catch (err) {
2360
2639
  // Windows can keep a deleted directory name reserved until the last
2361
2640
  // handle closes. Keep retries scoped to directory cleanup and creation.
@@ -2382,6 +2661,116 @@ function replaceManagedDir(from, to, keepExisting, repairOnly = false, { allowTr
2382
2661
  }, to)
2383
2662
  }
2384
2663
 
2664
+ async function clearDirContentsBestEffort(dir) {
2665
+ let entries
2666
+ try { entries = await readdir(dir, { withFileTypes: true }) } catch { return }
2667
+ for (const entry of entries) {
2668
+ const child = join(dir, entry.name)
2669
+ try {
2670
+ removeManagedDir(child, { allowTrash: true, deferCleanup: true })
2671
+ } catch (err) {
2672
+ if (entry.isDirectory() && ['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(err?.code)) {
2673
+ await clearDirContentsBestEffort(child)
2674
+ }
2675
+ }
2676
+ }
2677
+ }
2678
+
2679
+ async function copyFileOverwritingLocked(srcPath, dstPath) {
2680
+ try {
2681
+ await copyFile(srcPath, dstPath)
2682
+ } catch (err) {
2683
+ if (process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(err?.code) && quarantineFileToTrash(dstPath)) {
2684
+ await copyFile(srcPath, dstPath)
2685
+ return
2686
+ }
2687
+ throw err
2688
+ }
2689
+ }
2690
+
2691
+ /**
2692
+ * Mirror `from` onto an existing `to` directory without removing `to` itself.
2693
+ * Required on Windows when an active child process (e.g. a stdio MCP server)
2694
+ * holds `to` as its working directory and blocks directory rename/rmdir.
2695
+ */
2696
+ async function syncDirInPlaceAsync(from, to, { excludeNames = null } = {}) {
2697
+ mkdirSync(to, { recursive: true })
2698
+ const srcEntries = await readdir(from, { withFileTypes: true })
2699
+ const copiedNames = new Set()
2700
+
2701
+ for (const entry of srcEntries) {
2702
+ if (excludeNames?.has(entry.name)) continue
2703
+ copiedNames.add(entry.name)
2704
+ const srcPath = join(from, entry.name)
2705
+ const dstPath = join(to, entry.name)
2706
+
2707
+ let existingStat = null
2708
+ try { existingStat = await lstat(dstPath) } catch {}
2709
+
2710
+ if (entry.isDirectory()) {
2711
+ if (existingStat && !existingStat.isDirectory()) {
2712
+ try { await unlink(dstPath) } catch { removeManagedDir(dstPath, { allowTrash: true, deferCleanup: true }) }
2713
+ }
2714
+ await syncDirInPlaceAsync(srcPath, dstPath, { excludeNames })
2715
+ } else if (entry.isSymbolicLink()) {
2716
+ if (existingStat) {
2717
+ try { removeManagedDir(dstPath, { allowTrash: true, deferCleanup: true }) } catch {}
2718
+ }
2719
+ try {
2720
+ await symlink(await readlink(srcPath), dstPath)
2721
+ } catch {
2722
+ let targetStat = null
2723
+ try { targetStat = await stat(srcPath) } catch {}
2724
+ if (targetStat?.isDirectory()) {
2725
+ await syncDirInPlaceAsync(srcPath, dstPath, { excludeNames })
2726
+ } else if (targetStat) {
2727
+ await copyFileOverwritingLocked(srcPath, dstPath)
2728
+ }
2729
+ }
2730
+ } else {
2731
+ if (existingStat?.isDirectory()) {
2732
+ removeManagedDir(dstPath, { allowTrash: true, deferCleanup: true })
2733
+ }
2734
+ await copyFileOverwritingLocked(srcPath, dstPath)
2735
+ }
2736
+ }
2737
+
2738
+ let dstEntries = []
2739
+ try { dstEntries = await readdir(to, { withFileTypes: true }) } catch {}
2740
+ for (const entry of dstEntries) {
2741
+ if (copiedNames.has(entry.name) || excludeNames?.has(entry.name)) continue
2742
+ const dstPath = join(to, entry.name)
2743
+ try {
2744
+ removeManagedDir(dstPath, { allowTrash: true, deferCleanup: true })
2745
+ } catch (err) {
2746
+ if (process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(err?.code)) {
2747
+ if (entry.isDirectory()) await clearDirContentsBestEffort(dstPath)
2748
+ else quarantineFileToTrash(dstPath)
2749
+ } else {
2750
+ throw err
2751
+ }
2752
+ }
2753
+ }
2754
+ }
2755
+
2756
+ export async function replaceManagedDirAsync(from, to, keepExisting, repairOnly = false, { allowTrash = false, deferCleanup = false, excludeNames = null, inPlaceFallback = false } = {}) {
2757
+ return retryManagedDirOperation(async () => {
2758
+ if (keepExisting?.(to)) return false
2759
+ if (repairOnly && hasMatchingSkillCopy(from, to)) return true
2760
+ try {
2761
+ removeManagedDir(to, { allowTrash, deferCleanup })
2762
+ } catch (err) {
2763
+ if (inPlaceFallback && ['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(err?.code) && existsSync(to)) {
2764
+ await syncDirInPlaceAsync(from, to, { excludeNames })
2765
+ return true
2766
+ }
2767
+ throw err
2768
+ }
2769
+ await copyDirAsync(from, to, { excludeNames })
2770
+ return true
2771
+ }, to)
2772
+ }
2773
+
2385
2774
  /**
2386
2775
  * Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
2387
2776
  */
@@ -2405,7 +2794,7 @@ function skillOwnedByOtherEnabledPlugin(pluginName, skillName, plugins = readSta
2405
2794
  return false
2406
2795
  }
2407
2796
 
2408
- export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine = true, preserveOtherEnabled = true } = {}) {
2797
+ export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine = true, preserveOtherEnabled = true, deferCleanup = false } = {}) {
2409
2798
  const target = installedDir(pluginName)
2410
2799
  const pluginSkillsDir = join(target, 'skills')
2411
2800
  const dshSkills = dshSkillsDir()
@@ -2435,7 +2824,7 @@ export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine =
2435
2824
  const settled = await Promise.allSettled(targets.map(async ({ name, dest }) => {
2436
2825
  const didRemove = await retryManagedDirOperation(() => {
2437
2826
  if (isUploadedSkillTarget(dest)) return false
2438
- removeManagedDir(dest, { allowTrash: allowQuarantine })
2827
+ removeManagedDir(dest, { allowTrash: allowQuarantine, deferCleanup })
2439
2828
  return true
2440
2829
  }, dest)
2441
2830
  if (didRemove) removed.push(name)
@@ -2475,17 +2864,24 @@ export async function syncAllInstalledSkillsToDsh() {
2475
2864
  * Returns a result summary for the UI.
2476
2865
  */
2477
2866
  const marketplaceInstalls = new Set()
2867
+ const activePluginUpdates = new Set()
2478
2868
 
2479
2869
  export async function installPlugin(options) {
2480
2870
  const { pluginName } = options
2481
- if (marketplaceInstalls.has(pluginName)) throw new Error(`插件 ${pluginName} 正在安装`)
2482
- marketplaceInstalls.add(pluginName)
2871
+ const lockKey = pluginLockKey(pluginName)
2872
+ if (marketplaceInstalls.has(lockKey)) {
2873
+ throw Object.assign(new Error(`插件 ${pluginName} 正在安装`), { status: 409 })
2874
+ }
2875
+ if (activePluginUpdates.has(lockKey)) {
2876
+ throw Object.assign(new Error(`插件 ${pluginName} 正在更新`), { status: 409 })
2877
+ }
2878
+ marketplaceInstalls.add(lockKey)
2483
2879
  bumpPluginEpoch(pluginName)
2484
2880
  cancelActivePluginProbes(pluginName)
2485
2881
  try {
2486
2882
  return await withPluginLock(pluginName, () => installMarketplacePluginUnlocked(options))
2487
2883
  } finally {
2488
- marketplaceInstalls.delete(pluginName)
2884
+ marketplaceInstalls.delete(lockKey)
2489
2885
  }
2490
2886
  }
2491
2887
 
@@ -2510,15 +2906,15 @@ function installMayWriteCordisPatch(pluginName, dir, row, target, prevConnectors
2510
2906
  const incomingManifest = mergeManifestWithRow(readPluginManifest(dir), row)
2511
2907
  const incomingConnectors = listConnectors(dir, incomingManifest)
2512
2908
  if (prevConnectors.some((name) => !incomingConnectors.some((c) => c.name === name))) return true
2909
+ if (hasLegacyHookBridgeEntry(pluginName)) return true
2513
2910
 
2514
2911
  const dataDir = pluginDataDir(pluginName)
2515
2912
  if (existsSync(target)) {
2516
- if (listLspServers(target).length > 0 || existsSync(compiledHooksPath(pluginName))) return true
2913
+ if (listLspServers(target).length > 0) return true
2517
2914
  if (!initialEnabled && prevConnectors.length > 0) return true
2518
2915
  }
2519
2916
  if (!initialEnabled) return false
2520
2917
 
2521
- if (compileResolvedHooks(dir, incomingManifest, dataDir) !== null) return true
2522
2918
  return canRegisterAnyLsp(dir, dataDir, listLspServers(dir, incomingManifest))
2523
2919
  }
2524
2920
 
@@ -2535,7 +2931,7 @@ async function rollbackFreshInstall(pluginName, target) {
2535
2931
  await removeManagedDirAsync(target, { allowTrash: true }).catch(() => {})
2536
2932
  }
2537
2933
 
2538
- async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName, refresh = false, initialEnabled = true }) {
2934
+ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName, refresh = false, sourcePulled = false, initialEnabled = true }) {
2539
2935
  const state = readState()
2540
2936
  const source = state.sources.find((s) => s.id === sourceId)
2541
2937
  if (!source) throw new Error(`unknown source: ${sourceId}`)
@@ -2548,7 +2944,38 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2548
2944
  const row = await findMarketRow(sourceId, pluginName)
2549
2945
  if (!row) throw new Error(`plugin not found in marketplace: ${pluginName}`)
2550
2946
 
2551
- const { dir } = await materializePlugin(sourceId, pluginName, row.source, { refresh })
2947
+ let effectiveRefresh = refresh
2948
+ let allowStaleFallback = false
2949
+ if (!effectiveRefresh && row.source && typeof row.source === 'object' && row.version) {
2950
+ const normalizedSource = normalizeRemotePluginSource(row.source)
2951
+ if (
2952
+ normalizedSource &&
2953
+ ['url', 'git-subdir', 'github'].includes(normalizedSource.source) &&
2954
+ typeof normalizedSource.url === 'string' &&
2955
+ /^https?:\/\//.test(normalizedSource.url) &&
2956
+ !normalizedSource.sha &&
2957
+ !sourceRepositoryDir(sourceCacheDir(sourceId), normalizedSource)
2958
+ ) {
2959
+ const checkout = remoteCheckoutDir(normalizedSource.url, normalizedSource.ref)
2960
+ if (existsSync(join(checkout, '.git'))) {
2961
+ try {
2962
+ const cachedPluginDir = normalizedSource.path ? pluginPath(checkout, normalizedSource.path) : checkout
2963
+ const cachedVersion = normalizeVersion(readPluginManifest(cachedPluginDir, false)?.version)
2964
+ const rowVersion = normalizeVersion(row.version)
2965
+ if (rowVersion && cachedVersion && semverGt(rowVersion, cachedVersion)) {
2966
+ effectiveRefresh = true
2967
+ allowStaleFallback = true
2968
+ }
2969
+ } catch {}
2970
+ }
2971
+ }
2972
+ }
2973
+
2974
+ const { dir } = await materializePlugin(sourceId, pluginName, row.source, {
2975
+ refresh: effectiveRefresh,
2976
+ sourcePulled,
2977
+ allowStaleFallback,
2978
+ })
2552
2979
  const target = installedDir(pluginName)
2553
2980
 
2554
2981
  // Reinstalling must not inherit the previous copy's registrations: skills it
@@ -2567,11 +2994,53 @@ async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName,
2567
2994
  }
2568
2995
  }
2569
2996
 
2997
+ function isPureSkillPackage(target, manifest) {
2998
+ return (
2999
+ listPrompts(target, manifest).length === 0 &&
3000
+ listConnectors(target, manifest).length === 0 &&
3001
+ listHooks(target, manifest).length === 0 &&
3002
+ listLspServers(target, manifest).length === 0 &&
3003
+ listAgents(target, manifest).length === 0 &&
3004
+ resolvePluginCommandEntries(target, manifest).entries.length === 0
3005
+ )
3006
+ }
3007
+
3008
+ function canMoveTopLevelSkillDir(target, skillDir, manifestOrPure) {
3009
+ const isPure = typeof manifestOrPure === 'boolean'
3010
+ ? manifestOrPure
3011
+ : isPureSkillPackage(target, manifestOrPure)
3012
+ if (!isPure) return false
3013
+ if (resolve(dirname(skillDir)) !== resolve(target)) return false
3014
+ for (const name of ['SKILL.md', 'skill.md']) {
3015
+ const skillMdPath = join(skillDir, name)
3016
+ if (!existsSync(skillMdPath)) continue
3017
+ try {
3018
+ return !/\$\{(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\}|\$(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\b/.test(readFileSync(skillMdPath, 'utf8'))
3019
+ } catch {
3020
+ return false
3021
+ }
3022
+ }
3023
+ return false
3024
+ }
3025
+
3026
+ async function mirrorSkillDir(target, skillDir, dest, pureSkill) {
3027
+ if (resolve(dest) === resolve(skillDir)) return
3028
+ if (!existsSync(dest) && canMoveTopLevelSkillDir(target, skillDir, pureSkill)) {
3029
+ try {
3030
+ renameSync(skillDir, dest)
3031
+ return
3032
+ } catch {}
3033
+ }
3034
+ await copyDirAsync(skillDir, dest)
3035
+ }
3036
+
2570
3037
  async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, target, installed, prevConnectors, initialEnabled }) {
2571
- if (existsSync(target)) await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true })
3038
+ if (existsSync(target)) {
3039
+ await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true, deferCleanup: true })
3040
+ }
2572
3041
 
2573
- // Idempotent reinstall: clear the previous copy first.
2574
- await replaceManagedDir(dir, target)
3042
+ // Idempotent reinstall: clear the previous copy first (with in-place Windows fallback when locked by a live child process cwd).
3043
+ await replaceManagedDirAsync(dir, target, undefined, false, { deferCleanup: true, inPlaceFallback: true, excludeNames: new Set(['.git']) })
2575
3044
 
2576
3045
  // Persist marketplace-declared components into the installed copy's manifest
2577
3046
  // when `strict: false` or when absent on disk, preserving any existing
@@ -2606,7 +3075,10 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2606
3075
  'skills', 'commands', 'agents', '.agents', '.claude-plugin', '.codex-plugin', '.well-known',
2607
3076
  'hooks', 'prompts', 'mcp', 'lsp', 'scripts', 'server', 'node_modules', '.git', 'assets', 'docs',
2608
3077
  ])
2609
- const declaredSkills = readPluginManifest(target)?.skills
3078
+ const installedManifest = readPluginManifest(target)
3079
+ const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(target, f)).find(existsSync)
3080
+ const pureSkill = !rootSkillMd && isPureSkillPackage(target, installedManifest)
3081
+ const declaredSkills = installedManifest?.skills
2610
3082
  const skillPaths = typeof declaredSkills === 'string'
2611
3083
  ? (isDotRelativePath(declaredSkills) ? [declaredSkills] : [])
2612
3084
  : (Array.isArray(declaredSkills) ? declaredSkills.filter((p) => typeof p === 'string' && isDotRelativePath(p)) : [])
@@ -2619,7 +3091,7 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2619
3091
  const parent = dirname(root)
2620
3092
  if (resolve(parent) !== resolve(target)) {
2621
3093
  const dest = join(skillsDir, basename(parent))
2622
- if (resolve(dest) !== resolve(parent)) copyDir(parent, dest)
3094
+ await mirrorSkillDir(target, parent, dest, pureSkill)
2623
3095
  }
2624
3096
  } else if (/\.md$/i.test(base) && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(base)) {
2625
3097
  const skillName = base.replace(/\.md$/i, '')
@@ -2641,19 +3113,19 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2641
3113
  if (resolve(dir) === resolve(target)) continue // handled as a root skill below
2642
3114
  if (!existsSync(join(dir, 'SKILL.md')) && !existsSync(join(dir, 'skill.md'))) continue
2643
3115
  const dest = join(skillsDir, basename(dir))
2644
- if (resolve(dest) !== resolve(dir)) copyDir(dir, dest)
3116
+ await mirrorSkillDir(target, dir, dest, pureSkill)
2645
3117
  }
2646
3118
  }
2647
3119
 
2648
3120
  // 1. Mirror commands/ (nested subdirs, manifest string/array/object paths & inline commands) into skills/
2649
- const { entries: commandEntries } = resolvePluginCommandEntries(target, readPluginManifest(target))
3121
+ const { entries: commandEntries } = resolvePluginCommandEntries(target, installedManifest)
2650
3122
  for (const cmd of commandEntries) {
2651
3123
  const cmdSkillDir = join(skillsDir, cmd.name)
2652
3124
  if (existsSync(cmdSkillDir)) continue
2653
3125
  if (cmd.filePath) {
2654
3126
  if (/^skill\.md$/i.test(basename(cmd.filePath))) {
2655
3127
  mkdirSync(cmdSkillDir, { recursive: true })
2656
- copyDir(dirname(cmd.filePath), cmdSkillDir)
3128
+ await copyDirAsync(dirname(cmd.filePath), cmdSkillDir)
2657
3129
  } else {
2658
3130
  mkdirSync(cmdSkillDir, { recursive: true })
2659
3131
  const rawContent = readFileSync(cmd.filePath, 'utf8')
@@ -2668,14 +3140,13 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2668
3140
  }
2669
3141
 
2670
3142
  // 2. If the plugin has a root SKILL.md, mirror it into skills/<pluginName>/SKILL.md
2671
- const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(target, f)).find(existsSync)
2672
3143
  if (rootSkillMd) {
2673
3144
  const rootSkillDir = join(skillsDir, pluginName)
2674
3145
  if (!existsSync(rootSkillDir)) {
2675
3146
  mkdirSync(rootSkillDir, { recursive: true })
2676
3147
  // Keep relative scripts/references/assets usable when DSH copies the skill.
2677
3148
  for (const entry of readdirSync(target, { withFileTypes: true })) {
2678
- if (entry.isDirectory() && !['skills', '.git', 'node_modules'].includes(entry.name)) copyDir(join(target, entry.name), join(rootSkillDir, entry.name))
3149
+ if (entry.isDirectory() && !['skills', '.git', 'node_modules'].includes(entry.name)) await copyDirAsync(join(target, entry.name), join(rootSkillDir, entry.name))
2679
3150
  else if (entry.isFile()) copyFileSync(join(target, entry.name), join(rootSkillDir, entry.name))
2680
3151
  }
2681
3152
  const rawContent = readFileSync(rootSkillMd, 'utf8')
@@ -2700,8 +3171,7 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2700
3171
  const sMd = join(target, entry.name, 'SKILL.md')
2701
3172
  if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
2702
3173
  const subDir = join(skillsDir, entry.name)
2703
- mkdirSync(subDir, { recursive: true })
2704
- copyDir(join(target, entry.name), subDir)
3174
+ await mirrorSkillDir(target, join(target, entry.name), subDir, pureSkill)
2705
3175
  }
2706
3176
  }
2707
3177
  }
@@ -3117,46 +3587,61 @@ async function togglePluginUnlocked(pluginName, enabled, epoch, options = {}) {
3117
3587
  * reinstall the plugin copy and re-run conversions.
3118
3588
  */
3119
3589
  export async function updatePlugin(pluginName) {
3590
+ const lockKey = pluginLockKey(pluginName)
3591
+ if (activePluginUpdates.has(lockKey)) {
3592
+ throw Object.assign(new Error(`插件 ${pluginName} 正在更新`), { status: 409 })
3593
+ }
3594
+ if (marketplaceInstalls.has(lockKey)) {
3595
+ throw Object.assign(new Error(`插件 ${pluginName} 正在安装`), { status: 409 })
3596
+ }
3597
+ activePluginUpdates.add(lockKey)
3120
3598
  bumpPluginEpoch(pluginName)
3121
3599
  cancelActivePluginProbes(pluginName)
3122
- return withPluginLock(pluginName, async () => {
3123
- const initialRec = readState().plugins.find((p) => p.name === pluginName)
3124
- if (!initialRec) throw new Error(`plugin not installed: ${pluginName}`)
3125
- return withSourceLock(initialRec.sourceId, async () => {
3126
- const state = readState()
3127
- const rec = state.plugins.find((p) => p.name === pluginName)
3128
- if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
3129
- if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
3130
- throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
3131
- }
3132
- const source = state.sources.find((s) => s.id === rec.sourceId)
3133
- if (source && typeof source.url === 'string') {
3134
- const cacheDir = sourceCacheDir(rec.sourceId)
3135
- if (existsSync(join(cacheDir, '.git'))) {
3136
- await pullSource(rec.sourceId)
3600
+ try {
3601
+ return await withPluginLock(pluginName, async () => {
3602
+ const initialRec = readState().plugins.find((p) => p.name === pluginName)
3603
+ if (!initialRec) throw new Error(`plugin not installed: ${pluginName}`)
3604
+ return withSourceLock(initialRec.sourceId, async () => {
3605
+ const state = readState()
3606
+ const rec = state.plugins.find((p) => p.name === pluginName)
3607
+ if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
3608
+ if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
3609
+ throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
3610
+ }
3611
+ const source = state.sources.find((s) => s.id === rec.sourceId)
3612
+ let sourcePulled = false
3613
+ if (source && typeof source.url === 'string') {
3614
+ const cacheDir = sourceCacheDir(rec.sourceId)
3615
+ if (existsSync(join(cacheDir, '.git'))) {
3616
+ await pullSource(rec.sourceId)
3617
+ sourcePulled = true
3618
+ }
3137
3619
  }
3138
- }
3139
3620
 
3140
- // Clear memory cache so fresh MCP tool lists can be queried
3141
- for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
3142
- if (k.startsWith(`${pluginName}::`)) {
3143
- MEMORY_TOOLS_CACHE.delete(k)
3621
+ // Clear memory cache so fresh MCP tool lists can be queried
3622
+ for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
3623
+ if (k.startsWith(`${pluginName}::`)) {
3624
+ MEMORY_TOOLS_CACHE.delete(k)
3625
+ }
3144
3626
  }
3145
- }
3146
3627
 
3147
- // The marketplace rows are cached for 30s; without this the install below
3148
- // re-reads the pre-pull catalog and installs the old revision.
3149
- invalidateMarketplaceCache(rec.sourceId)
3628
+ // The marketplace rows are cached for 30s; without this the install below
3629
+ // re-reads the pre-pull catalog and installs the old revision.
3630
+ invalidateMarketplaceCache(rec.sourceId)
3150
3631
 
3151
- // Freshly materialized install (re-copies, re-registers, re-converts).
3152
- return installMarketplacePluginFromSourceLocked({
3153
- sourceId: rec.sourceId,
3154
- pluginName,
3155
- refresh: true,
3156
- initialEnabled: rec.enabled !== false,
3632
+ // Freshly materialized install (re-copies, re-registers, re-converts).
3633
+ return installMarketplacePluginFromSourceLocked({
3634
+ sourceId: rec.sourceId,
3635
+ pluginName,
3636
+ refresh: true,
3637
+ sourcePulled,
3638
+ initialEnabled: rec.enabled !== false,
3639
+ })
3157
3640
  })
3158
3641
  })
3159
- })
3642
+ } finally {
3643
+ activePluginUpdates.delete(lockKey)
3644
+ }
3160
3645
  }
3161
3646
 
3162
3647
  /**
@@ -3341,7 +3826,7 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3341
3826
 
3342
3827
  const target = installedDir(rec.name)
3343
3828
  const installed = existsSync(target)
3344
- if (installed && !PLUGIN_LOCKS.has(rec.name)) {
3829
+ if (installed && !PLUGIN_LOCKS.has(pluginLockKey(rec.name))) {
3345
3830
  const skillsDir = join(target, 'skills')
3346
3831
  try {
3347
3832
  for (const entry of readdirSync(target, { withFileTypes: true })) {
@@ -3437,7 +3922,7 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3437
3922
  oauthAuthenticated,
3438
3923
  enabled: !!savedEntry,
3439
3924
  connected,
3440
- pending: MCP_ACTIVATIONS.has(toolsKey) || MCP_TOOLS_INFLIGHT.get(toolsKey)?.forceFresh === true,
3925
+ pending: MCP_ACTIVATIONS.has(toolsKey) || (!connected && MCP_TOOLS_INFLIGHT.get(toolsKey)?.forceFresh === true),
3441
3926
  }
3442
3927
  }) : []
3443
3928
  let lspServers = installed ? listLspServers(target, targetManifest) : []
@@ -3490,8 +3975,8 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3490
3975
  connectors,
3491
3976
  hooks: listHooks(target, targetManifest),
3492
3977
  lspServers,
3493
- version: targetManifest?.version ?? null,
3494
- } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
3978
+ version: targetManifest?.version ?? rec.version ?? null,
3979
+ } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: rec.version ?? null }
3495
3980
  const shortDescription = rec.shortDescription || (installed ? readPluginShortDescription(target) : '') || marketRow?.shortDescription || ''
3496
3981
  return {
3497
3982
  ...rec,