universal-plugin-hub 1.0.45 → 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 }
@@ -1248,7 +1256,7 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1248
1256
  let result
1249
1257
  try {
1250
1258
  const controller = new AbortController()
1251
- const timer = setTimeout(() => controller.abort(), 8000)
1259
+ const timer = setTimeout(() => controller.abort(), MCP_AUTH_TIMEOUT_MS)
1252
1260
  const res = await fetch(url, {
1253
1261
  method: 'POST',
1254
1262
  headers: reqHeaders,
@@ -1293,29 +1301,30 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1293
1301
  if (e.name === 'AbortError') {
1294
1302
  result = {
1295
1303
  ok: false,
1296
- message: '连接超时(8 秒未响应),请检查服务 URL 与网络',
1304
+ message: `连接超时(${MCP_AUTH_TIMEOUT_MS / 1000} 秒未响应),请检查服务 URL 与网络`,
1297
1305
  server: connectorName,
1298
1306
  transport,
1299
1307
  endpoint: url,
1300
- errorDetails: 'Connection timed out (8s limit)',
1308
+ errorDetails: `Connection timed out (${MCP_AUTH_TIMEOUT_MS / 1000}s limit)`,
1309
+ duration,
1310
+ }
1311
+ } else {
1312
+ result = {
1313
+ ok: false,
1314
+ message: `连接异常:${e.message}`,
1315
+ server: connectorName,
1316
+ transport,
1317
+ endpoint: url,
1318
+ errorDetails: e.message,
1301
1319
  duration,
1302
1320
  }
1303
- }
1304
- result = {
1305
- ok: false,
1306
- message: `连接异常:${e.message}`,
1307
- server: connectorName,
1308
- transport,
1309
- endpoint: url,
1310
- errorDetails: e.message,
1311
- duration,
1312
1321
  }
1313
1322
  }
1314
1323
  setRemoteVerification(pluginName, connectorName, { transport, url, headers: reqHeaders, oauth: payload?.oauth }, result.ok === true)
1315
1324
  return result
1316
1325
  }
1317
1326
 
1318
- export function saveConnectorAuth(pluginName, connectorName, payload) {
1327
+ export function saveConnectorAuth(pluginName, connectorName, payload, { pluginOwned = pluginName !== 'user-mcp' } = {}) {
1319
1328
  const target = installedDir(pluginName)
1320
1329
  const connectors = getPluginConnectors(target)
1321
1330
  const found = connectors.find((c) => c.name === connectorName) || { name: connectorName }
@@ -1355,6 +1364,10 @@ export function saveConnectorAuth(pluginName, connectorName, payload) {
1355
1364
  headers: { ...baseHeaders, ...customHeaders },
1356
1365
  oauth: isStdio ? 'none' : oauth,
1357
1366
  }
1367
+ if (pluginOwned) {
1368
+ const previousRemote = remoteConfigFromEntry(getConnectorEntry(pluginName, connectorName)?.config)
1369
+ rememberPluginOAuthUrls(pluginName, connectorName, !isStdio && isOAuthMode(oauth) ? url : null, previousRemote?.url)
1370
+ }
1358
1371
  if (!isStdio && isOAuthMode(oauth)) {
1359
1372
  saveCustomOAuthClient(pluginName, connectorName, payload)
1360
1373
  const credentialKey = oauthCredentialKey(pluginName, connectorName, url, oauth)
@@ -1389,9 +1402,10 @@ export function saveConnectorAuth(pluginName, connectorName, payload) {
1389
1402
  writeMcpToolsState(savedState)
1390
1403
  }
1391
1404
  }
1392
- if (MEMORY_TOOLS_CACHE.has(toolsKey)) {
1393
- const mem = MEMORY_TOOLS_CACHE.get(toolsKey)
1394
- MEMORY_TOOLS_CACHE.set(toolsKey, { ...mem, tools: [], disabledTools: mem.disabledTools || [] })
1405
+ if (result.ok) {
1406
+ MEMORY_TOOLS_CACHE.delete(toolsKey)
1407
+ // A probe still running against the old configuration must not be reused.
1408
+ MCP_TOOLS_INFLIGHT.delete(toolsKey)
1395
1409
  }
1396
1410
  return result
1397
1411
  }
@@ -1409,12 +1423,30 @@ export function readMcpToolsState() {
1409
1423
  }
1410
1424
  }
1411
1425
 
1412
- export function writeMcpToolsState(state) {
1426
+ export function writeMcpToolsState(state, { required = false } = {}) {
1413
1427
  try {
1414
1428
  const file = MCP_TOOLS_STATE_PATH()
1415
1429
  mkdirSync(dirname(file), { recursive: true })
1416
1430
  writeFileSync(file, JSON.stringify(state, null, 2), 'utf8')
1417
- } 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
+ }
1418
1450
  }
1419
1451
 
1420
1452
  export function getDisabledTools(pluginName, connectorName) {
@@ -1466,6 +1498,14 @@ function quoteArgForShell(value) {
1466
1498
  * an (possibly empty) tool list, so callers can tell "no tools" from "the
1467
1499
  * probe never reached the server".
1468
1500
  */
1501
+ const MCP_STARTUP_TIMEOUT_MS = 180000
1502
+ const MCP_TOOLS_TIMEOUT_MS = 60000
1503
+ // A user-initiated connection test is not the same wait as a background probe.
1504
+ const MCP_AUTH_TIMEOUT_MS = 8000
1505
+ // Keep only the tail: a chatty server during a 180s startup window would
1506
+ // otherwise grow this string without bound (and `+=` copies it each time).
1507
+ const STDERR_TAIL_BYTES = 8192
1508
+
1469
1509
  export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1470
1510
  return new Promise((resolve) => {
1471
1511
  const argv = Array.isArray(args) ? args : []
@@ -1498,10 +1538,22 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1498
1538
  settled = true
1499
1539
  clearTimeout(timer)
1500
1540
  try { cp.kill() } catch {}
1501
- resolve({ tools: tools || [], error: tools ? null : error })
1541
+ resolve({ tools: tools || [], error: error || null })
1542
+ }
1543
+
1544
+ const armTimeout = (ms, phase) => {
1545
+ if (settled) return
1546
+ clearTimeout(timer)
1547
+ timer = setTimeout(() => {
1548
+ const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1549
+ finish([], `MCP ${phase}超时(${ms / 1000} 秒)${detail ? `:${detail}` : ''}`)
1550
+ }, ms)
1502
1551
  }
1503
1552
 
1504
- cp.stderr.on('data', (d) => { stderr += d.toString() })
1553
+ cp.stderr.on('data', (d) => {
1554
+ stderr += d.toString()
1555
+ if (stderr.length > STDERR_TAIL_BYTES) stderr = stderr.slice(-STDERR_TAIL_BYTES)
1556
+ })
1505
1557
 
1506
1558
  cp.stdout.on('data', (d) => {
1507
1559
  output += d.toString()
@@ -1516,19 +1568,25 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1516
1568
  finish(json.result.tools, null)
1517
1569
  return
1518
1570
  }
1519
- if (json.id === 0 && json.result) {
1571
+ if (json.id === 0 && json.result && !answered) {
1572
+ answered = true
1573
+ armTimeout(MCP_TOOLS_TIMEOUT_MS, '工具解析')
1520
1574
  cp.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
1521
1575
  cp.stdin.write(toolsReq)
1522
1576
  }
1523
- if (json.id === 0 && json.error) finish([], json.error.message || 'MCP initialize failed')
1577
+ if ((json.id === 0 || json.id === 1) && json.error) {
1578
+ finish([], json.error.message || 'MCP 工具解析失败')
1579
+ return
1580
+ }
1524
1581
  } catch {}
1525
1582
  }
1526
1583
  })
1527
1584
 
1528
1585
  cp.on('error', (err) => finish([], `无法启动 ${cmd}: ${err.message}`))
1586
+ cp.stdin.on?.('error', (err) => finish([], `MCP 输入连接失败: ${err.message}`))
1529
1587
 
1530
1588
  cp.on('close', (code) => {
1531
- if (!answered) {
1589
+ if (!settled) {
1532
1590
  const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1533
1591
  finish([], detail || `MCP 服务提前退出(exit ${code})`)
1534
1592
  }
@@ -1548,29 +1606,45 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1548
1606
  params: {}
1549
1607
  }) + '\n'
1550
1608
 
1609
+ armTimeout(MCP_STARTUP_TIMEOUT_MS, '启动')
1551
1610
  try {
1552
1611
  cp.stdin.write(initReq)
1553
- } catch {}
1554
-
1555
- timer = setTimeout(() => {
1556
- if (!settled) {
1557
- const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1558
- finish([], detail || 'MCP 服务在 25 秒内没有返回工具列表')
1559
- }
1560
- }, 25000)
1612
+ } catch (err) { finish([], err.message) }
1561
1613
  })
1562
1614
  }
1563
1615
 
1564
1616
  const MEMORY_TOOLS_CACHE = new Map()
1617
+ const MCP_TOOLS_INFLIGHT = new Map()
1565
1618
 
1566
1619
  export async function fetchConnectorTools(pluginName, connectorName, forceFresh = false) {
1620
+ const key = `${pluginName}::${connectorName}`
1621
+ const inflight = MCP_TOOLS_INFLIGHT.get(key)
1622
+ // A caller asking for a fresh probe must never be served a background
1623
+ // probe's stale answer (e.g. right after the user fixed a bad URL).
1624
+ if (inflight && !(forceFresh && !inflight.forceFresh)) return inflight.promise
1625
+ const entry = { forceFresh, promise: null }
1626
+ entry.promise = discoverConnectorTools(pluginName, connectorName, forceFresh)
1627
+ MCP_TOOLS_INFLIGHT.set(key, entry)
1628
+ try {
1629
+ const result = await entry.promise
1630
+ // A failure is transient; remembering it with no expiry pinned the UI to
1631
+ // "解析失败" until the process restarted.
1632
+ if (result.ok === false) MEMORY_TOOLS_CACHE.delete(key)
1633
+ else MEMORY_TOOLS_CACHE.set(key, { tools: result.tools || [], ok: result.ok, message: result.message })
1634
+ return result
1635
+ } finally {
1636
+ if (MCP_TOOLS_INFLIGHT.get(key) === entry) MCP_TOOLS_INFLIGHT.delete(key)
1637
+ }
1638
+ }
1639
+
1640
+ async function discoverConnectorTools(pluginName, connectorName, forceFresh = false) {
1567
1641
  const key = `${pluginName}::${connectorName}`
1568
1642
  const state = readMcpToolsState()
1569
1643
  const disabledTools = Array.isArray(state[key]?.disabledTools) ? state[key].disabledTools : []
1570
1644
 
1571
1645
  if (!forceFresh && MEMORY_TOOLS_CACHE.has(key)) {
1572
1646
  const mem = MEMORY_TOOLS_CACHE.get(key)
1573
- return { ok: true, tools: mem.tools || [], disabledTools }
1647
+ return { ok: mem.ok !== false, tools: mem.tools || [], disabledTools, ...(mem.message ? { message: mem.message } : {}) }
1574
1648
  }
1575
1649
 
1576
1650
  const target = installedDir(pluginName)
@@ -1601,9 +1675,9 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1601
1675
 
1602
1676
  // 1. HTTP / SSE fetch
1603
1677
  if (transport !== 'stdio' && url) {
1678
+ const controller = new AbortController()
1679
+ const timer = setTimeout(() => controller.abort(), MCP_TOOLS_TIMEOUT_MS)
1604
1680
  try {
1605
- const controller = new AbortController()
1606
- const timer = setTimeout(() => controller.abort(), 6000)
1607
1681
  const res = await fetch(url, {
1608
1682
  method: 'POST',
1609
1683
  headers: {
@@ -1612,14 +1686,15 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1612
1686
  },
1613
1687
  signal: controller.signal,
1614
1688
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
1615
- }).finally(() => clearTimeout(timer))
1689
+ })
1616
1690
 
1617
1691
  if (res.status === 200) {
1618
1692
  const text = await res.text()
1619
- let tools = []
1693
+ let tools = null
1620
1694
  try {
1621
1695
  const data = JSON.parse(text)
1622
1696
  if (Array.isArray(data.result?.tools)) tools = data.result.tools
1697
+ else if (data.error) probeError = data.error.message || 'MCP 工具解析失败'
1623
1698
  } catch {
1624
1699
  const lines = text.split('\n')
1625
1700
  for (const line of lines) {
@@ -1635,18 +1710,17 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1635
1710
  }
1636
1711
  }
1637
1712
 
1638
- if (tools.length > 0) {
1639
- if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
1640
- state[key].cachedTools = tools
1641
- writeMcpToolsState(state)
1713
+ if (tools) {
1714
+ cacheConnectorTools(key, tools)
1642
1715
  return { ok: true, tools, disabledTools }
1643
1716
  }
1717
+ probeError ||= 'MCP 响应中未包含有效的工具列表'
1644
1718
  } else {
1645
1719
  probeError = `MCP 服务返回 HTTP ${res.status}`
1646
1720
  }
1647
1721
  } catch (err) {
1648
- probeError = `连接 MCP 服务失败: ${err.message}`
1649
- }
1722
+ probeError = controller.signal.aborted ? `MCP 工具解析超时(${MCP_TOOLS_TIMEOUT_MS / 1000} 秒)` : `连接 MCP 服务失败: ${err.message}`
1723
+ } finally { clearTimeout(timer) }
1650
1724
  }
1651
1725
 
1652
1726
  // 2. Stdio fetch
@@ -1657,9 +1731,7 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1657
1731
  try {
1658
1732
  const probe = await queryStdioToolsList(cmd, args, entryCfg.env || found?.env || {})
1659
1733
  if (probe.tools.length > 0 || !probe.error) {
1660
- if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
1661
- state[key].cachedTools = probe.tools
1662
- writeMcpToolsState(state)
1734
+ cacheConnectorTools(key, probe.tools)
1663
1735
  return { ok: true, tools: probe.tools, disabledTools }
1664
1736
  }
1665
1737
  probeError = probe.error
@@ -1671,20 +1743,38 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1671
1743
  }
1672
1744
  }
1673
1745
 
1674
- // 3. Return cached fallback
1675
- if (cached.length > 0) {
1676
- return { ok: true, tools: cached, disabledTools }
1677
- }
1678
-
1679
1746
  // A probe that never reached the server is an error, not an empty tool list;
1680
- // reporting ok:true here made the UI claim the server exposes no tools.
1747
+ // reporting ok:true with an empty list made the UI claim the server exposes
1748
+ // no tools. A cached list is different: it is still usable, and surfacing it
1749
+ // as an error replaced the whole row (and its toggles) with a failure notice.
1681
1750
  if (probeError) {
1751
+ if (cached.length > 0) return { ok: true, tools: cached, disabledTools, message: probeError }
1682
1752
  return { ok: false, tools: [], disabledTools, message: probeError }
1683
1753
  }
1684
1754
 
1685
1755
  return { ok: true, tools: [], disabledTools }
1686
1756
  }
1687
1757
 
1758
+ function cacheConnectorTools(key, tools) {
1759
+ // A probe started before an uninstall can finish afterwards; writing then
1760
+ // resurrects the removed plugin's tool table for the next install of the
1761
+ // same name.
1762
+ const owner = key.slice(0, key.indexOf('::'))
1763
+ if (owner !== 'user-mcp' && !readState().plugins.some((p) => p.name === owner)) return
1764
+ const state = readMcpToolsState()
1765
+ state[key] = { ...state[key], cachedTools: tools }
1766
+ writeMcpToolsState(state)
1767
+ MEMORY_TOOLS_CACHE.set(key, { tools })
1768
+ }
1769
+
1770
+ function warmInstalledConnectorTools(pluginName, connectors) {
1771
+ for (const connector of connectors) {
1772
+ if (getConnectorEntry(pluginName, connector.name)) {
1773
+ void fetchConnectorTools(pluginName, connector.name, true).catch(() => {})
1774
+ }
1775
+ }
1776
+ }
1777
+
1688
1778
  export function isScanDirRegistered(path) {
1689
1779
  const state = readState()
1690
1780
  const target = (path || '').replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '')
@@ -1725,7 +1815,7 @@ function ensureSkillFrontmatter(content, skillName, description) {
1725
1815
  * This ensures DSH Desktop's @deepseek-ai/dsh-skill-filesystem discovers them
1726
1816
  * natively and hot-reloads them into the composer's "/" slash command menu.
1727
1817
  */
1728
- export function syncPluginSkillsToDsh(pluginName) {
1818
+ export async function syncPluginSkillsToDsh(pluginName, shouldSync = () => true, { repairOnly = false } = {}) {
1729
1819
  const target = installedDir(pluginName)
1730
1820
  const pluginSkillsDir = join(target, 'skills')
1731
1821
  if (!existsSync(pluginSkillsDir)) return []
@@ -1735,23 +1825,66 @@ export function syncPluginSkillsToDsh(pluginName) {
1735
1825
 
1736
1826
  const synced = []
1737
1827
  for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
1738
- if (entry.isDirectory()) {
1739
- const srcSkillDir = join(pluginSkillsDir, entry.name)
1740
- const srcSkillFile = join(srcSkillDir, 'SKILL.md')
1741
- if (existsSync(srcSkillFile)) {
1742
- const destSkillDir = join(dshSkills, entry.name)
1743
- // A direct upload owns its junction/copy. A later plugin installation
1744
- // must not replace it or delete the user's original through the link.
1745
- if (isUploadedSkillTarget(destSkillDir)) continue
1746
- safeRmDir(destSkillDir)
1747
- copyDir(srcSkillDir, destSkillDir)
1748
- synced.push(entry.name)
1749
- }
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)
1750
1836
  }
1837
+ if (repairOnly) await yieldToHost()
1751
1838
  }
1752
1839
  return synced
1753
1840
  }
1754
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
+
1755
1888
  /**
1756
1889
  * Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
1757
1890
  */
@@ -1767,29 +1900,31 @@ export function removePluginSkillsFromDsh(pluginName) {
1767
1900
  if (entry.isDirectory()) {
1768
1901
  const destSkillDir = join(dshSkills, entry.name)
1769
1902
  if (isUploadedSkillTarget(destSkillDir)) continue
1770
- safeRmDir(destSkillDir)
1903
+ removeManagedDir(destSkillDir)
1771
1904
  }
1772
1905
  }
1773
1906
  }
1774
1907
 
1775
- // 2. Also remove any skills prefixed with plugin name or compiled subagent hub
1776
- const subagentHubName = `${pluginName}-agents`
1777
- 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)
1778
1911
  }
1779
1912
 
1780
1913
  /**
1781
1914
  * Sync all installed and enabled plugins into $DSH_HOME/skills.
1782
1915
  * Called at boot or after configuration change.
1783
1916
  */
1784
- export function syncAllInstalledSkillsToDsh() {
1917
+ export async function syncAllInstalledSkillsToDsh() {
1785
1918
  const state = readState()
1786
1919
  const dshSkills = dshSkillsDir()
1787
1920
  mkdirSync(dshSkills, { recursive: true })
1788
1921
 
1789
1922
  const results = {}
1790
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)
1791
1926
  if (plugin.enabled !== false) {
1792
- results[plugin.name] = syncPluginSkillsToDsh(plugin.name)
1927
+ results[plugin.name] = await syncPluginSkillsToDsh(plugin.name, stillEnabled, { repairOnly: true })
1793
1928
  }
1794
1929
  }
1795
1930
  return results
@@ -1813,12 +1948,10 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
1813
1948
  // Reinstalling must not inherit the previous copy's registrations: skills it
1814
1949
  // no longer ships and MCP servers it dropped would otherwise stay visible.
1815
1950
  const prevConnectors = existsSync(target) ? getPluginConnectors(target).map((c) => c.name) : []
1816
- if (existsSync(target)) removePluginSkillsFromDsh(pluginName)
1951
+ if (existsSync(target)) await retryManagedDirOperation(() => removePluginSkillsFromDsh(pluginName))
1817
1952
 
1818
1953
  // Idempotent reinstall: clear the previous copy first.
1819
- safeRmDir(target)
1820
- mkdirSync(dirname(target), { recursive: true })
1821
- copyDir(dir, target)
1954
+ await replaceManagedDir(dir, target)
1822
1955
 
1823
1956
  // Persist marketplace-declared LSP servers into the installed copy's
1824
1957
  // manifest, so installedDetails / detail views can read them back even when
@@ -1979,7 +2112,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
1979
2112
 
1980
2113
  // Sync skills and subagent delegates to DSH native skills directory.
1981
2114
  if (existsSync(skillsDir)) {
1982
- syncPluginSkillsToDsh(pluginName)
2115
+ await syncPluginSkillsToDsh(pluginName)
1983
2116
  }
1984
2117
 
1985
2118
  // Auto-register and connect any MCP connectors defined in the plugin that do NOT require auth and have valid URLs/commands.
@@ -2040,14 +2173,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
2040
2173
  writeState(state)
2041
2174
  invalidateParserCaches()
2042
2175
 
2043
- // Proactively warm up and cache tools for local stdio/npx MCP servers in the background
2044
- for (const c of pluginConnectors) {
2045
- if (c.command === 'npx' || (c.args && c.args.some((a) => typeof a === 'string' && a.includes('@')))) {
2046
- setTimeout(() => {
2047
- fetchConnectorTools(pluginName, c.name, true).catch(() => {});
2048
- }, 500);
2049
- }
2050
- }
2176
+ warmInstalledConnectorTools(pluginName, pluginConnectors)
2051
2177
 
2052
2178
  return {
2053
2179
  ok: true,
@@ -2087,20 +2213,66 @@ function readInstalledVersion(target) {
2087
2213
  }
2088
2214
 
2089
2215
  /** Uninstall: remove copy, unregister scan dir, clean legacy presets and connectors. */
2090
- 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
+ }
2091
2231
  const state = readState()
2092
2232
  const target = installedDir(pluginName)
2093
- if (existsSync(target)) {
2094
- const pluginConnectors = getPluginConnectors(target)
2095
- for (const c of pluginConnectors) {
2096
- 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
+ }
2097
2268
  }
2269
+ }
2270
+ if (existsSync(target)) {
2098
2271
  unregisterPluginLsp(pluginName)
2099
2272
  unregisterPluginHooks(pluginName)
2100
2273
  }
2101
- removePluginSkillsFromDsh(pluginName)
2102
- try { safeRmDir(target) } catch {}
2103
-
2274
+ removeManagedDir(target)
2275
+
2104
2276
  // Clean any legacy preset directories left by prior versions
2105
2277
  cleanupLegacyPresets(pluginName)
2106
2278
 
@@ -2108,14 +2280,15 @@ export function uninstallPlugin(pluginName) {
2108
2280
  const mcpToolsState = readMcpToolsState()
2109
2281
  let mcpToolsStateChanged = false
2110
2282
  for (const k of Object.keys(mcpToolsState)) {
2111
- if (k.startsWith(`${pluginName}::`)) {
2283
+ if (k.startsWith(prefix) && ownedNames.has(k.slice(prefix.length))) {
2112
2284
  delete mcpToolsState[k]
2113
2285
  mcpToolsStateChanged = true
2114
2286
  MEMORY_TOOLS_CACHE.delete(k)
2287
+ MCP_TOOLS_INFLIGHT.delete(k)
2115
2288
  }
2116
2289
  }
2117
2290
  if (mcpToolsStateChanged) {
2118
- writeMcpToolsState(mcpToolsState)
2291
+ writeMcpToolsState(mcpToolsState, { required: true })
2119
2292
  }
2120
2293
 
2121
2294
  state.plugins = state.plugins.filter((p) => p.name !== pluginName)
@@ -2138,7 +2311,7 @@ export async function togglePlugin(pluginName, enabled) {
2138
2311
 
2139
2312
  if (enabled) {
2140
2313
  if (existsSync(skillsDir)) {
2141
- syncPluginSkillsToDsh(pluginName)
2314
+ await syncPluginSkillsToDsh(pluginName)
2142
2315
  }
2143
2316
  for (const c of pluginConnectors) {
2144
2317
  registerConnector(pluginName, c.name, c)
@@ -2215,12 +2388,114 @@ function findMarketRowSync(sourceId, pluginName) {
2215
2388
  }
2216
2389
  }
2217
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
+
2218
2490
  /** Re-exported for routes: list installed plugins with details. */
2219
2491
  export function installedDetails() {
2220
2492
  const state = readState()
2493
+ let connectorEntries
2494
+ let toolsState
2221
2495
  return state.plugins.map((rec) => {
2222
2496
  const target = installedDir(rec.name)
2223
- if (existsSync(target)) {
2497
+ const installed = existsSync(target)
2498
+ if (installed) {
2224
2499
  const skillsDir = join(target, 'skills')
2225
2500
  if (!existsSync(skillsDir)) {
2226
2501
  try { mkdirSync(skillsDir, { recursive: true }) } catch {}
@@ -2246,13 +2521,24 @@ export function installedDetails() {
2246
2521
  }
2247
2522
  } catch {}
2248
2523
  }
2249
- 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
+ }
2250
2535
  const needsAuth = connectorRequiresAuth(c)
2251
- const authenticated = isConnectorAuthenticated(rec.name, c.name)
2252
- const connected = isConnectorActive(rec.name, c.name)
2253
- 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)
2254
2540
  const savedConfig = savedEntry?.config || {}
2255
- const remote = remoteConfigFromEntry(savedConfig) || (!savedEntry ? readMcpToolsState()[`${rec.name}::${c.name}`]?.savedOAuthRemoteConfig : null)
2541
+ const remote = remoteConfigFromEntry(savedConfig) || (!savedEntry ? toolState()?.savedOAuthRemoteConfig : null)
2256
2542
  const savedHeaders = remote ? remote.headers : ((savedConfig.headers && Object.keys(savedConfig.headers).length > 0) ? savedConfig.headers : c.headers)
2257
2543
  const savedEnv = remote ? {} : ((savedConfig.env && Object.keys(savedConfig.env).length > 0) ? savedConfig.env : c.env)
2258
2544
  const savedUrl = remote ? remote.url : (savedConfig.url || c.url)
@@ -2278,7 +2564,7 @@ export function installedDetails() {
2278
2564
  connected,
2279
2565
  }
2280
2566
  }) : []
2281
- let lspServers = existsSync(target) ? listLspServers(target) : []
2567
+ let lspServers = listLspServers(targetManifest)
2282
2568
  // Auto-activate: if an LSP server's binary is now on PATH but the entry
2283
2569
  // hasn't been written to cordis.patch.yml yet (e.g. the user installed the
2284
2570
  // binary after the plugin — registration was previously skipped because the
@@ -2288,7 +2574,7 @@ export function installedDetails() {
2288
2574
  // ~1s, so the newly registered server becomes truly active immediately —
2289
2575
  // no DSH restart needed (verified against @deepseek-ai/dsh-app-boot's
2290
2576
  // `watchUserPatches`, which registers cordis.patch.yml with Cordis HMR).
2291
- if (existsSync(target) && lspServers.length > 0) {
2577
+ if (lspServers.length > 0) {
2292
2578
  const autoRegistered = lspServers.filter((s) => {
2293
2579
  if (isLspActive(rec.name, s.name)) return false
2294
2580
  // Honor an explicit removal: if we already auto-activated this server
@@ -2320,42 +2606,37 @@ export function installedDetails() {
2320
2606
  const missingCommand = !active && !!s.command && !resolveCommandPath(s.command)
2321
2607
  return { ...s, active, missingCommand }
2322
2608
  })
2323
- const targetManifest = existsSync(target) ? readPluginManifest(target) : null
2324
2609
  // Author: the state record is written at install time, so installs made
2325
2610
  // before the marketplace reader learned to merge a plugin's own manifest
2326
2611
  // carry `author: null` forever. Fall back to the installed copy's manifest,
2327
2612
  // then to the live marketplace row, so those records self-heal on read.
2328
- const manifestAuthor = targetManifest?.author
2329
- ? (typeof targetManifest.author === 'string' ? targetManifest.author : targetManifest.author.name)
2330
- : null
2331
2613
  const marketRow = findMarketRowSync(rec.sourceId, rec.name)
2332
- const author = rec.author || manifestAuthor || marketRow?.author
2333
2614
  // The browse list and the connector rows render the same plugin through the
2334
2615
  // same icon component, so they must be handed the same identity fields the
2335
2616
  // detail page merges in. Without these a plugin whose manifest declares no
2336
2617
  // icon falls back to "author name as a GitHub handle" and shows a stranger's
2337
2618
  // avatar while its own page shows the real logo.
2338
- const declaredIcons = buildPluginIcons(targetManifest, { sourceId: rec.sourceId, name: rec.name, dir: existsSync(target) ? target : undefined, source: marketRow?.source })
2339
- const hasDeclaredIcon = !!((declaredIcons.light.length) || (declaredIcons.dark.length))
2340
- const detail = existsSync(target) ? {
2341
- icons: hasDeclaredIcon ? declaredIcons : (marketRow?.icons || declaredIcons),
2342
- skills: listSkills(target),
2343
- agents: listAgents(target),
2344
- 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),
2345
2625
  connectors,
2346
- hooks: listHooks(target),
2626
+ hooks: listHooks(target, targetManifest),
2347
2627
  lspServers,
2348
- version: readInstalledVersion(target) ?? null,
2628
+ version: targetManifest?.version ?? null,
2349
2629
  } : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
2350
2630
  return {
2351
2631
  ...rec,
2352
2632
  ...detail,
2353
- author: author || rec.author,
2633
+ description: rec.description || targetManifest?.description || marketRow?.description || '',
2634
+ author: identity.author,
2354
2635
  // Identity fields the icon chain reads. The detail page already merges
2355
2636
  // these from the marketplace row before rendering, which is why the same
2356
2637
  // plugin showed one icon inline and another on its own page.
2357
- homepage: rec.homepage || marketRow?.homepage,
2358
- source: rec.source || marketRow?.source,
2638
+ homepage: identity.homepage,
2639
+ source: identity.source,
2359
2640
  skillCount: detail.skills.length,
2360
2641
  agentCount: detail.agents.length,
2361
2642
  promptCount: detail.prompts.length,