universal-plugin-hub 1.0.50 → 1.1.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
@@ -7,21 +7,22 @@
7
7
  * next DSH restart (or registry re-scan) exposes the plugin's skills to
8
8
  * agents.
9
9
  */
10
- import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync, renameSync, readdirSync, copyFileSync, statSync, accessSync, constants as fsConstants } from 'node:fs'
10
+ import { existsSync, lstatSync, mkdirSync, rmSync, readFileSync, writeFileSync, renameSync, readdirSync, copyFileSync, statSync, accessSync, constants as fsConstants } from 'node:fs'
11
11
  import { fileURLToPath } from 'node:url'
12
12
  import { dirname, join, basename, isAbsolute, resolve, extname, delimiter } from 'node:path'
13
13
  import { spawn, execFile, execFileSync } from 'node:child_process'
14
14
  import { gunzipSync } from 'node:zlib'
15
15
  import { createHash } from 'node:crypto'
16
16
  import { homedir } from 'node:os'
17
+ import { setImmediate as yieldToHost, setTimeout as delay } from 'node:timers/promises'
17
18
  import * as yaml from 'js-yaml'
18
- import { installedDir, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, sourceCacheDir } from './store.js'
19
+ import { installedDir, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, removeManagedDir, sourceCacheDir } from './store.js'
19
20
  import { materializePlugin, pullSource, pluginPath } from './market.js'
20
21
  import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, resolveHookConfigPath, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName } from './parser.js'
21
22
  import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
22
23
  import { isUploadedSkillTarget } from './skill-uploads.js'
23
24
  import { buildPluginIcons } from './icons.js'
24
- import { beginOAuthVerification, completeOAuthVerification, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
25
+ import { beginOAuthVerification, completeOAuthVerification, cancelPluginOAuthVerifications, standaloneOAuthConnectorNames, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
25
26
  import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
26
27
  import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord } from './oauth-store.js'
27
28
 
@@ -139,7 +140,10 @@ export function isConnectorAuthenticated(pluginName, connectorName) {
139
140
  const target = installedDir(pluginName)
140
141
  const connectors = existsSync(target) ? getPluginConnectors(target) : []
141
142
  const found = connectors.find((c) => c.name === connectorName)
142
- const entry = getConnectorEntry(pluginName, connectorName)
143
+ return connectorAuthenticated(found, getConnectorEntry(pluginName, connectorName))
144
+ }
145
+
146
+ function connectorAuthenticated(found, entry) {
143
147
  const cfg = entry?.config || found || {}
144
148
 
145
149
  const isHttp = (isRemoteTransportName(entry?.config?.transport) || isRemoteTransportName(found?.type) || (!found?.command && (found?.url || cfg.url)) || (!found?.command && !found?.args?.length))
@@ -213,15 +217,15 @@ function setRemoteVerification(pluginName, connectorName, payload, verified) {
213
217
 
214
218
  export function isConnectorActive(pluginName, connectorName) {
215
219
  const entry = getConnectorEntry(pluginName, connectorName)
220
+ return connectorActive(entry, () => isConnectorAuthenticated(pluginName, connectorName),
221
+ () => readMcpToolsState()[`${pluginName}::${connectorName}`])
222
+ }
223
+
224
+ function connectorActive(entry, authenticated, toolState) {
216
225
  if (!entry) return false
217
226
  const remote = remoteConfigFromEntry(entry.config)
218
- if (remote) {
219
- const key = `${pluginName}::${connectorName}`
220
- return readMcpToolsState()[key]?.verifiedRemoteConfig === remoteConfigFingerprint(remote)
221
- }
222
- if (!isRemoteConnector(entry.config)) return isConnectorAuthenticated(pluginName, connectorName)
223
- const key = `${pluginName}::${connectorName}`
224
- return readMcpToolsState()[key]?.verifiedRemoteConfig === remoteConfigFingerprint(entry.config)
227
+ if (!remote && !isRemoteConnector(entry.config)) return authenticated()
228
+ return toolState()?.verifiedRemoteConfig === remoteConfigFingerprint(remote || entry.config)
225
229
  }
226
230
 
227
231
  export const getPluginConnectors = listConnectors
@@ -714,8 +718,7 @@ function versionLine(v) {
714
718
  }
715
719
 
716
720
  /** Read the running DSH release version from its installation, or '' when unknown. */
717
- export function findDshVersion() {
718
- const main = findDshMainNodeModules()
721
+ export function findDshVersion(main = findDshMainNodeModules()) {
719
722
  if (main) {
720
723
  for (const anchor of ['dsh-app-boot', 'dsh-session', 'dsh']) {
721
724
  try {
@@ -747,7 +750,7 @@ export function findDshVersion() {
747
750
  * hooks bridge latest=0.0.1-rc.5 while 0.1.1-rc.2 exists) nor a hard pin (which
748
751
  * would break once the user's DSH moves to a new line).
749
752
  */
750
- export async function matchingPublishedVersion(packageName) {
753
+ export async function matchingPublishedVersion(packageName, dshVersion) {
751
754
  try {
752
755
  const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageName)}`, { headers: { accept: 'application/json' } })
753
756
  let versions = []
@@ -760,7 +763,7 @@ export async function matchingPublishedVersion(packageName) {
760
763
  if (Array.isArray(parsed)) versions = parsed.filter((v) => typeof v === 'string')
761
764
  }
762
765
  if (versions.length === 0) return ''
763
- const line = versionLine(findDshVersion())
766
+ const line = versionLine(dshVersion ?? findDshVersion())
764
767
  const pool = line ? versions.filter((v) => versionLine(v) === line) : []
765
768
  const candidates = pool.length > 0 ? pool : versions
766
769
  let best = ''
@@ -802,7 +805,8 @@ export async function installProfilePackages(packageNames) {
802
805
  const names = Array.from(new Set((packageNames || []).filter((n) => typeof n === 'string' && n.trim())))
803
806
  if (names.length === 0) return { ok: true, installed: [] }
804
807
 
805
- let main = findDshMainNodeModules()
808
+ const runtimeModules = findDshMainNodeModules()
809
+ let main = runtimeModules
806
810
  if (!main) {
807
811
  const sharedNm = join(dshHome(), 'profiles', 'node_modules')
808
812
  const activeNm = join(dshHome(), 'profiles', resolveActiveProfileName(), 'node_modules')
@@ -816,12 +820,13 @@ export async function installProfilePackages(packageNames) {
816
820
  // A host package from a different major.minor line than the running DSH
817
821
  // release is stale: skipping it because the directory exists left the hooks
818
822
  // and LSP bridges pinned to whatever line was current at first provision.
819
- const dshLine = versionLine(findDshVersion())
820
- const need = []
823
+ const dshVersion = findDshVersion(runtimeModules)
824
+ const dshLine = versionLine(dshVersion)
825
+ const need = new Map()
821
826
  for (const name of names) {
822
827
  const installedManifest = join(main, name, 'package.json')
823
828
  if (!existsSync(installedManifest)) {
824
- need.push(name)
829
+ need.set(name, '')
825
830
  continue
826
831
  }
827
832
  if (!dshLine) continue
@@ -830,10 +835,11 @@ export async function installProfilePackages(packageNames) {
830
835
  if (typeof present !== 'string' || versionLine(present) === dshLine) continue
831
836
  // Re-provision only when a build for the running line actually exists;
832
837
  // otherwise the same mismatched version would be reinstalled every start.
833
- if (versionLine(await matchingPublishedVersion(name)) === dshLine) need.push(name)
838
+ const version = await matchingPublishedVersion(name, dshVersion)
839
+ if (versionLine(version) === dshLine) need.set(name, version)
834
840
  } catch {}
835
841
  }
836
- if (need.length === 0) return { ok: true, installed: [] }
842
+ if (need.size === 0) return { ok: true, installed: [] }
837
843
 
838
844
  // Install each package by downloading its tarball and extracting it into the
839
845
  // installation's node_modules. Do NOT run `npm install` against the DSH
@@ -841,11 +847,11 @@ export async function installProfilePackages(packageNames) {
841
847
  // packages that are not in the manifest, which has deleted DSH runtime
842
848
  // packages in the wild. A raw tarball extract has zero side effects.
843
849
  const installed = []
844
- for (const name of need) {
850
+ for (const [name, version] of need) {
845
851
  try {
846
852
  // Resolve a version compatible with the running DSH release (same major.minor
847
853
  // line as the installed DSH), not the `latest` dist-tag which can lag behind.
848
- const ver = await matchingPublishedVersion(name)
854
+ const ver = version || await matchingPublishedVersion(name, dshVersion)
849
855
  if (!ver) return { ok: false, error: `无法确定 ${name} 的匹配版本`, installed }
850
856
  let url = null
851
857
  try {
@@ -1158,7 +1164,7 @@ export function toggleConnector(pluginName, connectorName, enabled) {
1158
1164
  }
1159
1165
  }
1160
1166
 
1161
- export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1167
+ export async function verifyConnectorAuth(pluginName, connectorName, payload, { pluginOwned = pluginName !== 'user-mcp' } = {}) {
1162
1168
  const target = installedDir(pluginName)
1163
1169
  const connectors = getPluginConnectors(target)
1164
1170
  const found = connectors.find((c) => c.name === connectorName)
@@ -1170,17 +1176,19 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1170
1176
  const command = (typeof payload === 'object' && payload?.command) || found?.command || null
1171
1177
 
1172
1178
  if (transport !== 'stdio' && url && isOAuthMode(payload?.oauth)) {
1173
- setRemoteVerification(pluginName, connectorName, payload, false)
1174
1179
  try {
1180
+ if (pluginOwned) rememberPluginOAuthUrls(pluginName, connectorName, url)
1181
+ setRemoteVerification(pluginName, connectorName, payload, false)
1175
1182
  saveCustomOAuthClient(pluginName, connectorName, payload)
1176
1183
  const session = beginOAuthVerification(pluginName, connectorName, { ...payload, url }, {
1184
+ pluginOwned,
1177
1185
  onFinished: (result) => setRemoteVerification(pluginName, connectorName, payload, result.ok === true),
1178
1186
  })
1179
1187
  const result = await Promise.race([
1180
1188
  completeOAuthVerification(session),
1181
1189
  new Promise((resolve) => setTimeout(() => resolve({ pending: true, sessionId: session.id, status: session.status, message: session.message || '正在准备 OAuth 授权…' }), 250)),
1182
1190
  ])
1183
- setRemoteVerification(pluginName, connectorName, payload, result.ok === true)
1191
+ if (!session.cancelled) setRemoteVerification(pluginName, connectorName, payload, result.ok === true)
1184
1192
  return { ...result, server: connectorName, transport: 'http', endpoint: url, statusCode: result.statusCode ?? result.status }
1185
1193
  } catch (error) {
1186
1194
  return { ok: false, message: error.message, server: connectorName, transport: 'http', endpoint: url }
@@ -1316,7 +1324,7 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1316
1324
  return result
1317
1325
  }
1318
1326
 
1319
- export function saveConnectorAuth(pluginName, connectorName, payload) {
1327
+ export function saveConnectorAuth(pluginName, connectorName, payload, { pluginOwned = pluginName !== 'user-mcp' } = {}) {
1320
1328
  const target = installedDir(pluginName)
1321
1329
  const connectors = getPluginConnectors(target)
1322
1330
  const found = connectors.find((c) => c.name === connectorName) || { name: connectorName }
@@ -1356,6 +1364,10 @@ export function saveConnectorAuth(pluginName, connectorName, payload) {
1356
1364
  headers: { ...baseHeaders, ...customHeaders },
1357
1365
  oauth: isStdio ? 'none' : oauth,
1358
1366
  }
1367
+ if (pluginOwned) {
1368
+ const previousRemote = remoteConfigFromEntry(getConnectorEntry(pluginName, connectorName)?.config)
1369
+ rememberPluginOAuthUrls(pluginName, connectorName, !isStdio && isOAuthMode(oauth) ? url : null, previousRemote?.url)
1370
+ }
1359
1371
  if (!isStdio && isOAuthMode(oauth)) {
1360
1372
  saveCustomOAuthClient(pluginName, connectorName, payload)
1361
1373
  const credentialKey = oauthCredentialKey(pluginName, connectorName, url, oauth)
@@ -1411,12 +1423,30 @@ export function readMcpToolsState() {
1411
1423
  }
1412
1424
  }
1413
1425
 
1414
- export function writeMcpToolsState(state) {
1426
+ export function writeMcpToolsState(state, { required = false } = {}) {
1415
1427
  try {
1416
1428
  const file = MCP_TOOLS_STATE_PATH()
1417
1429
  mkdirSync(dirname(file), { recursive: true })
1418
1430
  writeFileSync(file, JSON.stringify(state, null, 2), 'utf8')
1419
- } catch {}
1431
+ } catch (error) {
1432
+ if (required) throw error
1433
+ }
1434
+ }
1435
+
1436
+ function rememberPluginOAuthUrls(pluginName, connectorName, ...urls) {
1437
+ const key = `${pluginName}::${connectorName}`
1438
+ const state = readMcpToolsState()
1439
+ const entry = state[key] || {}
1440
+ const history = new Set(Array.isArray(entry.oauthUrls) ? entry.oauthUrls : [])
1441
+ const size = history.size
1442
+ for (const url of [...urls, entry.savedOAuthRemoteConfig?.url]) {
1443
+ if (typeof url === 'string' && url.trim()) history.add(url)
1444
+ }
1445
+ if (history.size !== size) {
1446
+ state[key] = { ...entry, oauthUrls: [...history], ...(pluginName === 'user-mcp' ? { pluginOAuthOwned: true } : {}) }
1447
+ // Record ownership before a verification child can write the credential.
1448
+ writeMcpToolsState(state, { required: true })
1449
+ }
1420
1450
  }
1421
1451
 
1422
1452
  export function getDisabledTools(pluginName, connectorName) {
@@ -1785,7 +1815,7 @@ function ensureSkillFrontmatter(content, skillName, description) {
1785
1815
  * This ensures DSH Desktop's @deepseek-ai/dsh-skill-filesystem discovers them
1786
1816
  * natively and hot-reloads them into the composer's "/" slash command menu.
1787
1817
  */
1788
- export function syncPluginSkillsToDsh(pluginName) {
1818
+ export async function syncPluginSkillsToDsh(pluginName, shouldSync = () => true, { repairOnly = false } = {}) {
1789
1819
  const target = installedDir(pluginName)
1790
1820
  const pluginSkillsDir = join(target, 'skills')
1791
1821
  if (!existsSync(pluginSkillsDir)) return []
@@ -1795,23 +1825,66 @@ export function syncPluginSkillsToDsh(pluginName) {
1795
1825
 
1796
1826
  const synced = []
1797
1827
  for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
1798
- if (entry.isDirectory()) {
1799
- const srcSkillDir = join(pluginSkillsDir, entry.name)
1800
- const srcSkillFile = join(srcSkillDir, 'SKILL.md')
1801
- if (existsSync(srcSkillFile)) {
1802
- const destSkillDir = join(dshSkills, entry.name)
1803
- // A direct upload owns its junction/copy. A later plugin installation
1804
- // must not replace it or delete the user's original through the link.
1805
- if (isUploadedSkillTarget(destSkillDir)) continue
1806
- safeRmDir(destSkillDir)
1807
- copyDir(srcSkillDir, destSkillDir)
1808
- synced.push(entry.name)
1809
- }
1828
+ if (!entry.isDirectory()) continue
1829
+ const srcSkillDir = join(pluginSkillsDir, entry.name)
1830
+ if (!existsSync(join(srcSkillDir, 'SKILL.md'))) continue
1831
+ const destSkillDir = join(dshSkills, entry.name)
1832
+ // Direct uploads own their native paths, including during a retry.
1833
+ const keepExisting = path => !shouldSync() || isUploadedSkillTarget(path)
1834
+ if (await replaceManagedDir(srcSkillDir, destSkillDir, keepExisting, repairOnly)) {
1835
+ synced.push(entry.name)
1810
1836
  }
1837
+ if (repairOnly) await yieldToHost()
1811
1838
  }
1812
1839
  return synced
1813
1840
  }
1814
1841
 
1842
+ function hasMatchingSkillCopy(source, destination) {
1843
+ try {
1844
+ // A link must still be repaired, even if its target currently matches.
1845
+ if (!lstatSync(destination, { throwIfNoEntry: false })?.isDirectory()) return false
1846
+ const entries = readdirSync(source, { withFileTypes: true })
1847
+ const existing = new Map(readdirSync(destination, { withFileTypes: true }).map(entry => [entry.name, entry]))
1848
+ if (entries.length !== existing.size) return false
1849
+ return entries.every(entry => {
1850
+ const other = existing.get(entry.name)
1851
+ const from = join(source, entry.name)
1852
+ const to = join(destination, entry.name)
1853
+ if (entry.isDirectory()) return other?.isDirectory() && hasMatchingSkillCopy(from, to)
1854
+ if (!entry.isFile() || !other?.isFile()) return false
1855
+ if (process.platform !== 'win32' && (statSync(from).mode & 0o777) !== (statSync(to).mode & 0o777)) return false
1856
+ return readFileSync(from).equals(readFileSync(to))
1857
+ })
1858
+ } catch {
1859
+ return false
1860
+ }
1861
+ }
1862
+
1863
+ async function retryManagedDirOperation(operation, destination) {
1864
+ for (let attempt = 0; ; attempt++) {
1865
+ try {
1866
+ return operation()
1867
+ } catch (err) {
1868
+ // Windows can keep a deleted directory name reserved until the last
1869
+ // handle closes. Keep retries scoped to directory cleanup and creation.
1870
+ if (process.platform !== 'win32' || attempt >= 5 || (destination && err.path !== destination) ||
1871
+ ![undefined, 'lstat', 'unlink', 'mkdir'].includes(err.syscall) ||
1872
+ !['EPERM', 'EACCES', 'EBUSY'].includes(err.code)) throw err
1873
+ await delay(50 * 2 ** attempt)
1874
+ }
1875
+ }
1876
+ }
1877
+
1878
+ function replaceManagedDir(from, to, keepExisting, repairOnly = false) {
1879
+ return retryManagedDirOperation(() => {
1880
+ if (keepExisting?.(to)) return false
1881
+ if (repairOnly && hasMatchingSkillCopy(from, to)) return true
1882
+ removeManagedDir(to)
1883
+ copyDir(from, to)
1884
+ return true
1885
+ }, to)
1886
+ }
1887
+
1815
1888
  /**
1816
1889
  * Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
1817
1890
  */
@@ -1827,29 +1900,31 @@ export function removePluginSkillsFromDsh(pluginName) {
1827
1900
  if (entry.isDirectory()) {
1828
1901
  const destSkillDir = join(dshSkills, entry.name)
1829
1902
  if (isUploadedSkillTarget(destSkillDir)) continue
1830
- safeRmDir(destSkillDir)
1903
+ removeManagedDir(destSkillDir)
1831
1904
  }
1832
1905
  }
1833
1906
  }
1834
1907
 
1835
- // 2. Also remove any skills prefixed with plugin name or compiled subagent hub
1836
- const subagentHubName = `${pluginName}-agents`
1837
- if (!isUploadedSkillTarget(join(dshSkills, subagentHubName))) safeRmDir(join(dshSkills, subagentHubName))
1908
+ // Older installs may have exposed the compiled subagent hub separately.
1909
+ const subagentHubDir = join(dshSkills, `${pluginName}-agents`)
1910
+ if (!isUploadedSkillTarget(subagentHubDir)) removeManagedDir(subagentHubDir)
1838
1911
  }
1839
1912
 
1840
1913
  /**
1841
1914
  * Sync all installed and enabled plugins into $DSH_HOME/skills.
1842
1915
  * Called at boot or after configuration change.
1843
1916
  */
1844
- export function syncAllInstalledSkillsToDsh() {
1917
+ export async function syncAllInstalledSkillsToDsh() {
1845
1918
  const state = readState()
1846
1919
  const dshSkills = dshSkillsDir()
1847
1920
  mkdirSync(dshSkills, { recursive: true })
1848
1921
 
1849
1922
  const results = {}
1850
1923
  for (const plugin of state.plugins || []) {
1924
+ const stillEnabled = () => readState().plugins.some(current =>
1925
+ current.name === plugin.name && current.installedAt === plugin.installedAt && current.enabled !== false)
1851
1926
  if (plugin.enabled !== false) {
1852
- results[plugin.name] = syncPluginSkillsToDsh(plugin.name)
1927
+ results[plugin.name] = await syncPluginSkillsToDsh(plugin.name, stillEnabled, { repairOnly: true })
1853
1928
  }
1854
1929
  }
1855
1930
  return results
@@ -1873,12 +1948,10 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
1873
1948
  // Reinstalling must not inherit the previous copy's registrations: skills it
1874
1949
  // no longer ships and MCP servers it dropped would otherwise stay visible.
1875
1950
  const prevConnectors = existsSync(target) ? getPluginConnectors(target).map((c) => c.name) : []
1876
- if (existsSync(target)) removePluginSkillsFromDsh(pluginName)
1951
+ if (existsSync(target)) await retryManagedDirOperation(() => removePluginSkillsFromDsh(pluginName))
1877
1952
 
1878
1953
  // Idempotent reinstall: clear the previous copy first.
1879
- safeRmDir(target)
1880
- mkdirSync(dirname(target), { recursive: true })
1881
- copyDir(dir, target)
1954
+ await replaceManagedDir(dir, target)
1882
1955
 
1883
1956
  // Persist marketplace-declared LSP servers into the installed copy's
1884
1957
  // manifest, so installedDetails / detail views can read them back even when
@@ -2039,7 +2112,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
2039
2112
 
2040
2113
  // Sync skills and subagent delegates to DSH native skills directory.
2041
2114
  if (existsSync(skillsDir)) {
2042
- syncPluginSkillsToDsh(pluginName)
2115
+ await syncPluginSkillsToDsh(pluginName)
2043
2116
  }
2044
2117
 
2045
2118
  // Auto-register and connect any MCP connectors defined in the plugin that do NOT require auth and have valid URLs/commands.
@@ -2140,20 +2213,66 @@ function readInstalledVersion(target) {
2140
2213
  }
2141
2214
 
2142
2215
  /** Uninstall: remove copy, unregister scan dir, clean legacy presets and connectors. */
2143
- export function uninstallPlugin(pluginName) {
2216
+ export async function uninstallPlugin(pluginName) {
2217
+ const sharedNamespace = pluginName === 'user-mcp'
2218
+ const standaloneIds = () => new Set([
2219
+ ...(readState().userMcps || []).map(mcp => mcp.name),
2220
+ ...standaloneOAuthConnectorNames(),
2221
+ ].map(name => getConnectorId(pluginName, name)))
2222
+ const stopVerifications = () => {
2223
+ const claimed = sharedNamespace ? standaloneIds() : new Set()
2224
+ return cancelPluginOAuthVerifications(pluginName, name => !claimed.has(getConnectorId(pluginName, name)))
2225
+ }
2226
+ let stopping = stopVerifications()
2227
+ while (stopping) {
2228
+ await stopping
2229
+ stopping = stopVerifications()
2230
+ }
2144
2231
  const state = readState()
2145
2232
  const target = installedDir(pluginName)
2146
- if (existsSync(target)) {
2147
- const pluginConnectors = getPluginConnectors(target)
2148
- for (const c of pluginConnectors) {
2149
- unregisterConnector(pluginName, c.name)
2233
+ removePluginSkillsFromDsh(pluginName)
2234
+ const prefix = `${pluginName}::`
2235
+ const priorToolsState = readMcpToolsState()
2236
+ const declared = new Map((existsSync(target) ? getPluginConnectors(target) : []).map(c => [c.name, c.url]))
2237
+ // Standalone definitions and in-flight sign-ins take precedence in the
2238
+ // shared namespace. Other cached entries are eligible only with provenance.
2239
+ const claimed = sharedNamespace ? standaloneIds() : new Set()
2240
+ const cachedNames = Object.entries(priorToolsState)
2241
+ .filter(([key, saved]) => key.startsWith(prefix) && (!sharedNamespace || saved?.pluginOAuthOwned))
2242
+ .map(([key]) => key.slice(prefix.length))
2243
+ const ownedNames = new Set()
2244
+ for (const name of new Set([...declared.keys(), ...cachedNames])) {
2245
+ if (claimed.has(getConnectorId(pluginName, name))) continue
2246
+ const saved = priorToolsState[prefix + name]
2247
+ const entry = getConnectorEntry(pluginName, name)
2248
+ if (sharedNamespace && entry && entry.config?.serverName !== name) continue
2249
+ const remote = remoteConfigFromEntry(entry?.config)
2250
+ const ownsRegistration = remote && remote.credentialKey === oauthCredentialKey(pluginName, name, remote.url, remote.oauth)
2251
+ if (sharedNamespace && remote && !ownsRegistration) continue
2252
+ if (sharedNamespace && !entry && !saved?.pluginOAuthOwned) continue
2253
+ ownedNames.add(name)
2254
+ if (remote ? ownsRegistration : declared.has(name)) unregisterConnector(pluginName, name)
2255
+ const oauthUrls = new Set([
2256
+ ...(Array.isArray(saved?.oauthUrls) ? saved.oauthUrls : []),
2257
+ saved?.savedOAuthRemoteConfig?.url,
2258
+ ownsRegistration ? remote.url : null,
2259
+ ])
2260
+ for (const url of new Set([declared.get(name), ...oauthUrls])) {
2261
+ if (typeof url !== 'string' || !url.trim()) continue
2262
+ for (const mode of ['auto_register', 'custom']) {
2263
+ deleteOAuthRecord(oauthCredentialKey(pluginName, name, url, mode), {
2264
+ required: true,
2265
+ ifPresent: !oauthUrls.has(url),
2266
+ })
2267
+ }
2150
2268
  }
2269
+ }
2270
+ if (existsSync(target)) {
2151
2271
  unregisterPluginLsp(pluginName)
2152
2272
  unregisterPluginHooks(pluginName)
2153
2273
  }
2154
- removePluginSkillsFromDsh(pluginName)
2155
- try { safeRmDir(target) } catch {}
2156
-
2274
+ removeManagedDir(target)
2275
+
2157
2276
  // Clean any legacy preset directories left by prior versions
2158
2277
  cleanupLegacyPresets(pluginName)
2159
2278
 
@@ -2161,7 +2280,7 @@ export function uninstallPlugin(pluginName) {
2161
2280
  const mcpToolsState = readMcpToolsState()
2162
2281
  let mcpToolsStateChanged = false
2163
2282
  for (const k of Object.keys(mcpToolsState)) {
2164
- if (k.startsWith(`${pluginName}::`)) {
2283
+ if (k.startsWith(prefix) && ownedNames.has(k.slice(prefix.length))) {
2165
2284
  delete mcpToolsState[k]
2166
2285
  mcpToolsStateChanged = true
2167
2286
  MEMORY_TOOLS_CACHE.delete(k)
@@ -2169,7 +2288,7 @@ export function uninstallPlugin(pluginName) {
2169
2288
  }
2170
2289
  }
2171
2290
  if (mcpToolsStateChanged) {
2172
- writeMcpToolsState(mcpToolsState)
2291
+ writeMcpToolsState(mcpToolsState, { required: true })
2173
2292
  }
2174
2293
 
2175
2294
  state.plugins = state.plugins.filter((p) => p.name !== pluginName)
@@ -2192,7 +2311,7 @@ export async function togglePlugin(pluginName, enabled) {
2192
2311
 
2193
2312
  if (enabled) {
2194
2313
  if (existsSync(skillsDir)) {
2195
- syncPluginSkillsToDsh(pluginName)
2314
+ await syncPluginSkillsToDsh(pluginName)
2196
2315
  }
2197
2316
  for (const c of pluginConnectors) {
2198
2317
  registerConnector(pluginName, c.name, c)
@@ -2269,12 +2388,114 @@ function findMarketRowSync(sourceId, pluginName) {
2269
2388
  }
2270
2389
  }
2271
2390
 
2391
+ function installedPluginIconIdentity(rec, target, manifest, marketRow) {
2392
+ const author = typeof manifest?.author === 'string' ? manifest.author : manifest?.author?.name
2393
+ const declared = buildPluginIcons(manifest, { sourceId: rec.sourceId, name: rec.name, dir: target, source: marketRow?.source })
2394
+ return {
2395
+ name: rec.name,
2396
+ sourceId: rec.sourceId,
2397
+ author: rec.author || author || marketRow?.author || rec.author,
2398
+ homepage: rec.homepage || marketRow?.homepage,
2399
+ source: rec.source || marketRow?.source,
2400
+ icons: declared.light.length || declared.dark.length ? declared : (marketRow?.icons || declared),
2401
+ }
2402
+ }
2403
+
2404
+ /** Match the DSH MCP client's public name, including lossy or long raw names. */
2405
+ function mcpPublicToolName(server, rawName) {
2406
+ const name = `mcp__${server}__${rawName}`
2407
+ const normalized = name.replace(/[^A-Za-z0-9_-]/g, '_')
2408
+ if (name === normalized && name.length <= 64) return name
2409
+ const hash = createHash('sha256').update(`${server}\0${rawName}`).digest('hex').slice(0, 12)
2410
+ return `${normalized.slice(0, 51)}_${hash}`
2411
+ }
2412
+
2413
+ /** Public branding only. Connector configuration and tool arguments stay out of this response. */
2414
+ export function toolCallIconGroups() {
2415
+ const registrations = readCordisPatch().flatMap(block => block?.insert || [])
2416
+ .filter(entry => entry?.name === '@deepseek-ai/dsh-mcp-client' && /^[A-Za-z0-9_-]{1,32}$/.test(entry.config?.serverName || ''))
2417
+ const byServer = new Map()
2418
+ for (const entry of registrations) {
2419
+ const server = entry.config.serverName
2420
+ byServer.set(server, byServer.has(server) ? null : entry.id)
2421
+ }
2422
+ if (!byServer.size) return []
2423
+ const toolsState = readMcpToolsState()
2424
+ const owners = new Set()
2425
+ for (const [key, state] of Object.entries(toolsState)) {
2426
+ if (!state?.cachedTools?.length) continue
2427
+ const separator = key.lastIndexOf('::')
2428
+ if (separator < 0) continue
2429
+ const owner = key.slice(0, separator)
2430
+ const server = key.slice(separator + 2)
2431
+ if (byServer.get(server) === getConnectorId(owner, server)) owners.add(owner)
2432
+ }
2433
+ const installed = readState().plugins.filter(rec =>
2434
+ rec.enabled !== false && rec.name !== 'user-mcp' && owners.has(rec.name))
2435
+ const namesBySource = new Map()
2436
+ for (const rec of installed) {
2437
+ if (!namesBySource.has(rec.sourceId)) namesBySource.set(rec.sourceId, new Set())
2438
+ namesBySource.get(rec.sourceId).add(rec.name)
2439
+ }
2440
+ const rowsBySource = new Map()
2441
+ const claimedTools = new Map()
2442
+ const groups = []
2443
+ for (const rec of installed) {
2444
+ const target = installedDir(rec.name)
2445
+ if (!existsSync(target)) continue
2446
+ const manifest = readPluginManifest(target)
2447
+ const tools = new Map()
2448
+ for (const { name } of getPluginConnectors(target, manifest)) {
2449
+ if (byServer.get(name) !== getConnectorId(rec.name, name)) continue
2450
+ for (const tool of toolsState[`${rec.name}::${name}`]?.cachedTools || []) {
2451
+ if (typeof tool?.name !== 'string' || !tool.name) continue
2452
+ const publicName = mcpPublicToolName(name, tool.name)
2453
+ // Double underscores can also occur inside a DSH server name.
2454
+ if (hasOverlappingToolPrefix(publicName, name, byServer)) continue
2455
+ tools.set(publicName, tool.name)
2456
+ }
2457
+ }
2458
+ if (!tools.size) continue
2459
+ if (!rowsBySource.has(rec.sourceId)) {
2460
+ const rows = new Map()
2461
+ // Keep the first matching descriptor, as the full lookup does.
2462
+ try {
2463
+ for (const row of readMarketplace(rec.sourceId, namesBySource.get(rec.sourceId))) {
2464
+ if (!rows.has(row.name)) rows.set(row.name, row)
2465
+ }
2466
+ } catch {}
2467
+ rowsBySource.set(rec.sourceId, rows)
2468
+ }
2469
+ for (const name of tools.keys()) claimedTools.set(name, (claimedTools.get(name) || 0) + 1)
2470
+ groups.push({
2471
+ plugin: {
2472
+ ...installedPluginIconIdentity(rec, target, manifest, rowsBySource.get(rec.sourceId).get(rec.name)),
2473
+ displayName: rec.displayName || rec.name,
2474
+ },
2475
+ tools: Array.from(tools, ([name, rawName]) => ({ name, rawName })),
2476
+ })
2477
+ }
2478
+ return groups.map(group => ({ ...group, tools: group.tools.filter(tool => claimedTools.get(tool.name) === 1) }))
2479
+ .filter(group => group.tools.length)
2480
+ }
2481
+
2482
+ function hasOverlappingToolPrefix(publicName, name, servers) {
2483
+ for (let end = publicName.indexOf('__', 5); end !== -1; end = publicName.indexOf('__', end + 1)) {
2484
+ const server = publicName.slice(5, end)
2485
+ if (server !== name && servers.has(server)) return true
2486
+ }
2487
+ return false
2488
+ }
2489
+
2272
2490
  /** Re-exported for routes: list installed plugins with details. */
2273
2491
  export function installedDetails() {
2274
2492
  const state = readState()
2493
+ let connectorEntries
2494
+ let toolsState
2275
2495
  return state.plugins.map((rec) => {
2276
2496
  const target = installedDir(rec.name)
2277
- if (existsSync(target)) {
2497
+ const installed = existsSync(target)
2498
+ if (installed) {
2278
2499
  const skillsDir = join(target, 'skills')
2279
2500
  if (!existsSync(skillsDir)) {
2280
2501
  try { mkdirSync(skillsDir, { recursive: true }) } catch {}
@@ -2300,13 +2521,24 @@ export function installedDetails() {
2300
2521
  }
2301
2522
  } catch {}
2302
2523
  }
2303
- const connectors = existsSync(target) ? getPluginConnectors(target).map((c) => {
2524
+ const targetManifest = installed ? readPluginManifest(target) : null
2525
+ const connectors = installed ? getPluginConnectors(target, targetManifest).map((c) => {
2526
+ if (!connectorEntries) {
2527
+ connectorEntries = new Map()
2528
+ for (const block of readCordisPatch()) {
2529
+ if (!Array.isArray(block?.insert)) continue
2530
+ for (const entry of block.insert) {
2531
+ if (entry && !connectorEntries.has(entry.id)) connectorEntries.set(entry.id, entry)
2532
+ }
2533
+ }
2534
+ }
2304
2535
  const needsAuth = connectorRequiresAuth(c)
2305
- const authenticated = isConnectorAuthenticated(rec.name, c.name)
2306
- const connected = isConnectorActive(rec.name, c.name)
2307
- const savedEntry = getConnectorEntry(rec.name, c.name)
2536
+ const savedEntry = connectorEntries.get(getConnectorId(rec.name, c.name))
2537
+ const toolState = () => (toolsState ??= readMcpToolsState())[`${rec.name}::${c.name}`]
2538
+ const authenticated = connectorAuthenticated(c, savedEntry)
2539
+ const connected = connectorActive(savedEntry, () => authenticated, toolState)
2308
2540
  const savedConfig = savedEntry?.config || {}
2309
- const remote = remoteConfigFromEntry(savedConfig) || (!savedEntry ? readMcpToolsState()[`${rec.name}::${c.name}`]?.savedOAuthRemoteConfig : null)
2541
+ const remote = remoteConfigFromEntry(savedConfig) || (!savedEntry ? toolState()?.savedOAuthRemoteConfig : null)
2310
2542
  const savedHeaders = remote ? remote.headers : ((savedConfig.headers && Object.keys(savedConfig.headers).length > 0) ? savedConfig.headers : c.headers)
2311
2543
  const savedEnv = remote ? {} : ((savedConfig.env && Object.keys(savedConfig.env).length > 0) ? savedConfig.env : c.env)
2312
2544
  const savedUrl = remote ? remote.url : (savedConfig.url || c.url)
@@ -2332,7 +2564,7 @@ export function installedDetails() {
2332
2564
  connected,
2333
2565
  }
2334
2566
  }) : []
2335
- let lspServers = existsSync(target) ? listLspServers(target) : []
2567
+ let lspServers = listLspServers(targetManifest)
2336
2568
  // Auto-activate: if an LSP server's binary is now on PATH but the entry
2337
2569
  // hasn't been written to cordis.patch.yml yet (e.g. the user installed the
2338
2570
  // binary after the plugin — registration was previously skipped because the
@@ -2342,7 +2574,7 @@ export function installedDetails() {
2342
2574
  // ~1s, so the newly registered server becomes truly active immediately —
2343
2575
  // no DSH restart needed (verified against @deepseek-ai/dsh-app-boot's
2344
2576
  // `watchUserPatches`, which registers cordis.patch.yml with Cordis HMR).
2345
- if (existsSync(target) && lspServers.length > 0) {
2577
+ if (lspServers.length > 0) {
2346
2578
  const autoRegistered = lspServers.filter((s) => {
2347
2579
  if (isLspActive(rec.name, s.name)) return false
2348
2580
  // Honor an explicit removal: if we already auto-activated this server
@@ -2374,43 +2606,37 @@ export function installedDetails() {
2374
2606
  const missingCommand = !active && !!s.command && !resolveCommandPath(s.command)
2375
2607
  return { ...s, active, missingCommand }
2376
2608
  })
2377
- const targetManifest = existsSync(target) ? readPluginManifest(target) : null
2378
2609
  // Author: the state record is written at install time, so installs made
2379
2610
  // before the marketplace reader learned to merge a plugin's own manifest
2380
2611
  // carry `author: null` forever. Fall back to the installed copy's manifest,
2381
2612
  // then to the live marketplace row, so those records self-heal on read.
2382
- const manifestAuthor = targetManifest?.author
2383
- ? (typeof targetManifest.author === 'string' ? targetManifest.author : targetManifest.author.name)
2384
- : null
2385
2613
  const marketRow = findMarketRowSync(rec.sourceId, rec.name)
2386
- const author = rec.author || manifestAuthor || marketRow?.author
2387
2614
  // The browse list and the connector rows render the same plugin through the
2388
2615
  // same icon component, so they must be handed the same identity fields the
2389
2616
  // detail page merges in. Without these a plugin whose manifest declares no
2390
2617
  // icon falls back to "author name as a GitHub handle" and shows a stranger's
2391
2618
  // avatar while its own page shows the real logo.
2392
- const declaredIcons = buildPluginIcons(targetManifest, { sourceId: rec.sourceId, name: rec.name, dir: existsSync(target) ? target : undefined, source: marketRow?.source })
2393
- const hasDeclaredIcon = !!((declaredIcons.light.length) || (declaredIcons.dark.length))
2394
- const detail = existsSync(target) ? {
2395
- icons: hasDeclaredIcon ? declaredIcons : (marketRow?.icons || declaredIcons),
2396
- skills: listSkills(target),
2397
- agents: listAgents(target),
2398
- prompts: listPrompts(target),
2619
+ const identity = installedPluginIconIdentity(rec, installed ? target : undefined, targetManifest, marketRow)
2620
+ const detail = installed ? {
2621
+ icons: identity.icons,
2622
+ skills: listSkills(target, targetManifest),
2623
+ agents: listAgents(target, targetManifest),
2624
+ prompts: listPrompts(target, targetManifest),
2399
2625
  connectors,
2400
- hooks: listHooks(target),
2626
+ hooks: listHooks(target, targetManifest),
2401
2627
  lspServers,
2402
- version: readInstalledVersion(target) ?? null,
2628
+ version: targetManifest?.version ?? null,
2403
2629
  } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
2404
2630
  return {
2405
2631
  ...rec,
2406
2632
  ...detail,
2407
2633
  description: rec.description || targetManifest?.description || marketRow?.description || '',
2408
- author: author || rec.author,
2634
+ author: identity.author,
2409
2635
  // Identity fields the icon chain reads. The detail page already merges
2410
2636
  // these from the marketplace row before rendering, which is why the same
2411
2637
  // plugin showed one icon inline and another on its own page.
2412
- homepage: rec.homepage || marketRow?.homepage,
2413
- source: rec.source || marketRow?.source,
2638
+ homepage: identity.homepage,
2639
+ source: identity.source,
2414
2640
  skillCount: detail.skills.length,
2415
2641
  agentCount: detail.agents.length,
2416
2642
  promptCount: detail.prompts.length,