universal-plugin-hub 1.5.5 → 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,12 +16,13 @@ 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'
25
+ import { installedDir, pluginDataDir, compiledHooksPath, marketRoot, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, removeManagedDir, quarantineFileToTrash, sourceCacheDir, trashRoot, isSameOrInsidePath } from './store.js'
24
26
  import { materializePlugin, pullSource, sourceRepositoryDir, normalizeRemotePluginSource, remoteCheckoutDir, pluginPath } from './market.js'
25
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'
@@ -29,6 +31,7 @@ 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
 
@@ -2387,11 +2661,111 @@ function replaceManagedDir(from, to, keepExisting, repairOnly = false, { allowTr
2387
2661
  }, to)
2388
2662
  }
2389
2663
 
2390
- function replaceManagedDirAsync(from, to, keepExisting, repairOnly = false, { allowTrash = false, deferCleanup = false, excludeNames = null } = {}) {
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 } = {}) {
2391
2757
  return retryManagedDirOperation(async () => {
2392
2758
  if (keepExisting?.(to)) return false
2393
2759
  if (repairOnly && hasMatchingSkillCopy(from, to)) return true
2394
- removeManagedDir(to, { allowTrash, deferCleanup })
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
+ }
2395
2769
  await copyDirAsync(from, to, { excludeNames })
2396
2770
  return true
2397
2771
  }, to)
@@ -2532,15 +2906,15 @@ function installMayWriteCordisPatch(pluginName, dir, row, target, prevConnectors
2532
2906
  const incomingManifest = mergeManifestWithRow(readPluginManifest(dir), row)
2533
2907
  const incomingConnectors = listConnectors(dir, incomingManifest)
2534
2908
  if (prevConnectors.some((name) => !incomingConnectors.some((c) => c.name === name))) return true
2909
+ if (hasLegacyHookBridgeEntry(pluginName)) return true
2535
2910
 
2536
2911
  const dataDir = pluginDataDir(pluginName)
2537
2912
  if (existsSync(target)) {
2538
- if (listLspServers(target).length > 0 || existsSync(compiledHooksPath(pluginName))) return true
2913
+ if (listLspServers(target).length > 0) return true
2539
2914
  if (!initialEnabled && prevConnectors.length > 0) return true
2540
2915
  }
2541
2916
  if (!initialEnabled) return false
2542
2917
 
2543
- if (compileResolvedHooks(dir, incomingManifest, dataDir) !== null) return true
2544
2918
  return canRegisterAnyLsp(dir, dataDir, listLspServers(dir, incomingManifest))
2545
2919
  }
2546
2920
 
@@ -2665,8 +3039,8 @@ async function materializeAndRegisterPlugin({ sourceId, pluginName, row, dir, ta
2665
3039
  await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true, deferCleanup: true })
2666
3040
  }
2667
3041
 
2668
- // Idempotent reinstall: clear the previous copy first.
2669
- await replaceManagedDirAsync(dir, target, undefined, false, { deferCleanup: true, excludeNames: new Set(['.git']) })
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']) })
2670
3044
 
2671
3045
  // Persist marketplace-declared components into the installed copy's manifest
2672
3046
  // when `strict: false` or when absent on disk, preserving any existing
@@ -3548,7 +3922,7 @@ function buildInstalledPluginDetail(rec, shared = {}) {
3548
3922
  oauthAuthenticated,
3549
3923
  enabled: !!savedEntry,
3550
3924
  connected,
3551
- 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),
3552
3926
  }
3553
3927
  }) : []
3554
3928
  let lspServers = installed ? listLspServers(target, targetManifest) : []