universal-plugin-hub 1.0.35 → 1.0.50

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
@@ -19,6 +19,7 @@ import { installedDir, readState, writeState, slugify, dshHome, dshSkillsDir, sa
19
19
  import { materializePlugin, pullSource, pluginPath } from './market.js'
20
20
  import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, resolveHookConfigPath, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName } from './parser.js'
21
21
  import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
22
+ import { isUploadedSkillTarget } from './skill-uploads.js'
22
23
  import { buildPluginIcons } from './icons.js'
23
24
  import { beginOAuthVerification, completeOAuthVerification, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
24
25
  import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
@@ -1247,7 +1248,7 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1247
1248
  let result
1248
1249
  try {
1249
1250
  const controller = new AbortController()
1250
- const timer = setTimeout(() => controller.abort(), 8000)
1251
+ const timer = setTimeout(() => controller.abort(), MCP_AUTH_TIMEOUT_MS)
1251
1252
  const res = await fetch(url, {
1252
1253
  method: 'POST',
1253
1254
  headers: reqHeaders,
@@ -1292,22 +1293,23 @@ export async function verifyConnectorAuth(pluginName, connectorName, payload) {
1292
1293
  if (e.name === 'AbortError') {
1293
1294
  result = {
1294
1295
  ok: false,
1295
- message: '连接超时(8 秒未响应),请检查服务 URL 与网络',
1296
+ message: `连接超时(${MCP_AUTH_TIMEOUT_MS / 1000} 秒未响应),请检查服务 URL 与网络`,
1296
1297
  server: connectorName,
1297
1298
  transport,
1298
1299
  endpoint: url,
1299
- errorDetails: 'Connection timed out (8s limit)',
1300
+ errorDetails: `Connection timed out (${MCP_AUTH_TIMEOUT_MS / 1000}s limit)`,
1301
+ duration,
1302
+ }
1303
+ } else {
1304
+ result = {
1305
+ ok: false,
1306
+ message: `连接异常:${e.message}`,
1307
+ server: connectorName,
1308
+ transport,
1309
+ endpoint: url,
1310
+ errorDetails: e.message,
1300
1311
  duration,
1301
1312
  }
1302
- }
1303
- result = {
1304
- ok: false,
1305
- message: `连接异常:${e.message}`,
1306
- server: connectorName,
1307
- transport,
1308
- endpoint: url,
1309
- errorDetails: e.message,
1310
- duration,
1311
1313
  }
1312
1314
  }
1313
1315
  setRemoteVerification(pluginName, connectorName, { transport, url, headers: reqHeaders, oauth: payload?.oauth }, result.ok === true)
@@ -1388,9 +1390,10 @@ export function saveConnectorAuth(pluginName, connectorName, payload) {
1388
1390
  writeMcpToolsState(savedState)
1389
1391
  }
1390
1392
  }
1391
- if (MEMORY_TOOLS_CACHE.has(toolsKey)) {
1392
- const mem = MEMORY_TOOLS_CACHE.get(toolsKey)
1393
- MEMORY_TOOLS_CACHE.set(toolsKey, { ...mem, tools: [], disabledTools: mem.disabledTools || [] })
1393
+ if (result.ok) {
1394
+ MEMORY_TOOLS_CACHE.delete(toolsKey)
1395
+ // A probe still running against the old configuration must not be reused.
1396
+ MCP_TOOLS_INFLIGHT.delete(toolsKey)
1394
1397
  }
1395
1398
  return result
1396
1399
  }
@@ -1465,6 +1468,14 @@ function quoteArgForShell(value) {
1465
1468
  * an (possibly empty) tool list, so callers can tell "no tools" from "the
1466
1469
  * probe never reached the server".
1467
1470
  */
1471
+ const MCP_STARTUP_TIMEOUT_MS = 180000
1472
+ const MCP_TOOLS_TIMEOUT_MS = 60000
1473
+ // A user-initiated connection test is not the same wait as a background probe.
1474
+ const MCP_AUTH_TIMEOUT_MS = 8000
1475
+ // Keep only the tail: a chatty server during a 180s startup window would
1476
+ // otherwise grow this string without bound (and `+=` copies it each time).
1477
+ const STDERR_TAIL_BYTES = 8192
1478
+
1468
1479
  export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1469
1480
  return new Promise((resolve) => {
1470
1481
  const argv = Array.isArray(args) ? args : []
@@ -1497,10 +1508,22 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1497
1508
  settled = true
1498
1509
  clearTimeout(timer)
1499
1510
  try { cp.kill() } catch {}
1500
- resolve({ tools: tools || [], error: tools ? null : error })
1511
+ resolve({ tools: tools || [], error: error || null })
1501
1512
  }
1502
1513
 
1503
- cp.stderr.on('data', (d) => { stderr += d.toString() })
1514
+ const armTimeout = (ms, phase) => {
1515
+ if (settled) return
1516
+ clearTimeout(timer)
1517
+ timer = setTimeout(() => {
1518
+ const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1519
+ finish([], `MCP ${phase}超时(${ms / 1000} 秒)${detail ? `:${detail}` : ''}`)
1520
+ }, ms)
1521
+ }
1522
+
1523
+ cp.stderr.on('data', (d) => {
1524
+ stderr += d.toString()
1525
+ if (stderr.length > STDERR_TAIL_BYTES) stderr = stderr.slice(-STDERR_TAIL_BYTES)
1526
+ })
1504
1527
 
1505
1528
  cp.stdout.on('data', (d) => {
1506
1529
  output += d.toString()
@@ -1515,19 +1538,25 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1515
1538
  finish(json.result.tools, null)
1516
1539
  return
1517
1540
  }
1518
- if (json.id === 0 && json.result) {
1541
+ if (json.id === 0 && json.result && !answered) {
1542
+ answered = true
1543
+ armTimeout(MCP_TOOLS_TIMEOUT_MS, '工具解析')
1519
1544
  cp.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
1520
1545
  cp.stdin.write(toolsReq)
1521
1546
  }
1522
- if (json.id === 0 && json.error) finish([], json.error.message || 'MCP initialize failed')
1547
+ if ((json.id === 0 || json.id === 1) && json.error) {
1548
+ finish([], json.error.message || 'MCP 工具解析失败')
1549
+ return
1550
+ }
1523
1551
  } catch {}
1524
1552
  }
1525
1553
  })
1526
1554
 
1527
1555
  cp.on('error', (err) => finish([], `无法启动 ${cmd}: ${err.message}`))
1556
+ cp.stdin.on?.('error', (err) => finish([], `MCP 输入连接失败: ${err.message}`))
1528
1557
 
1529
1558
  cp.on('close', (code) => {
1530
- if (!answered) {
1559
+ if (!settled) {
1531
1560
  const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1532
1561
  finish([], detail || `MCP 服务提前退出(exit ${code})`)
1533
1562
  }
@@ -1547,29 +1576,45 @@ export function queryStdioToolsList(cmd, args, extraEnv = {}) {
1547
1576
  params: {}
1548
1577
  }) + '\n'
1549
1578
 
1579
+ armTimeout(MCP_STARTUP_TIMEOUT_MS, '启动')
1550
1580
  try {
1551
1581
  cp.stdin.write(initReq)
1552
- } catch {}
1553
-
1554
- timer = setTimeout(() => {
1555
- if (!settled) {
1556
- const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
1557
- finish([], detail || 'MCP 服务在 25 秒内没有返回工具列表')
1558
- }
1559
- }, 25000)
1582
+ } catch (err) { finish([], err.message) }
1560
1583
  })
1561
1584
  }
1562
1585
 
1563
1586
  const MEMORY_TOOLS_CACHE = new Map()
1587
+ const MCP_TOOLS_INFLIGHT = new Map()
1564
1588
 
1565
1589
  export async function fetchConnectorTools(pluginName, connectorName, forceFresh = false) {
1590
+ const key = `${pluginName}::${connectorName}`
1591
+ const inflight = MCP_TOOLS_INFLIGHT.get(key)
1592
+ // A caller asking for a fresh probe must never be served a background
1593
+ // probe's stale answer (e.g. right after the user fixed a bad URL).
1594
+ if (inflight && !(forceFresh && !inflight.forceFresh)) return inflight.promise
1595
+ const entry = { forceFresh, promise: null }
1596
+ entry.promise = discoverConnectorTools(pluginName, connectorName, forceFresh)
1597
+ MCP_TOOLS_INFLIGHT.set(key, entry)
1598
+ try {
1599
+ const result = await entry.promise
1600
+ // A failure is transient; remembering it with no expiry pinned the UI to
1601
+ // "解析失败" until the process restarted.
1602
+ if (result.ok === false) MEMORY_TOOLS_CACHE.delete(key)
1603
+ else MEMORY_TOOLS_CACHE.set(key, { tools: result.tools || [], ok: result.ok, message: result.message })
1604
+ return result
1605
+ } finally {
1606
+ if (MCP_TOOLS_INFLIGHT.get(key) === entry) MCP_TOOLS_INFLIGHT.delete(key)
1607
+ }
1608
+ }
1609
+
1610
+ async function discoverConnectorTools(pluginName, connectorName, forceFresh = false) {
1566
1611
  const key = `${pluginName}::${connectorName}`
1567
1612
  const state = readMcpToolsState()
1568
1613
  const disabledTools = Array.isArray(state[key]?.disabledTools) ? state[key].disabledTools : []
1569
1614
 
1570
1615
  if (!forceFresh && MEMORY_TOOLS_CACHE.has(key)) {
1571
1616
  const mem = MEMORY_TOOLS_CACHE.get(key)
1572
- return { ok: true, tools: mem.tools || [], disabledTools }
1617
+ return { ok: mem.ok !== false, tools: mem.tools || [], disabledTools, ...(mem.message ? { message: mem.message } : {}) }
1573
1618
  }
1574
1619
 
1575
1620
  const target = installedDir(pluginName)
@@ -1600,9 +1645,9 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1600
1645
 
1601
1646
  // 1. HTTP / SSE fetch
1602
1647
  if (transport !== 'stdio' && url) {
1648
+ const controller = new AbortController()
1649
+ const timer = setTimeout(() => controller.abort(), MCP_TOOLS_TIMEOUT_MS)
1603
1650
  try {
1604
- const controller = new AbortController()
1605
- const timer = setTimeout(() => controller.abort(), 6000)
1606
1651
  const res = await fetch(url, {
1607
1652
  method: 'POST',
1608
1653
  headers: {
@@ -1611,14 +1656,15 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1611
1656
  },
1612
1657
  signal: controller.signal,
1613
1658
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
1614
- }).finally(() => clearTimeout(timer))
1659
+ })
1615
1660
 
1616
1661
  if (res.status === 200) {
1617
1662
  const text = await res.text()
1618
- let tools = []
1663
+ let tools = null
1619
1664
  try {
1620
1665
  const data = JSON.parse(text)
1621
1666
  if (Array.isArray(data.result?.tools)) tools = data.result.tools
1667
+ else if (data.error) probeError = data.error.message || 'MCP 工具解析失败'
1622
1668
  } catch {
1623
1669
  const lines = text.split('\n')
1624
1670
  for (const line of lines) {
@@ -1634,18 +1680,17 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1634
1680
  }
1635
1681
  }
1636
1682
 
1637
- if (tools.length > 0) {
1638
- if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
1639
- state[key].cachedTools = tools
1640
- writeMcpToolsState(state)
1683
+ if (tools) {
1684
+ cacheConnectorTools(key, tools)
1641
1685
  return { ok: true, tools, disabledTools }
1642
1686
  }
1687
+ probeError ||= 'MCP 响应中未包含有效的工具列表'
1643
1688
  } else {
1644
1689
  probeError = `MCP 服务返回 HTTP ${res.status}`
1645
1690
  }
1646
1691
  } catch (err) {
1647
- probeError = `连接 MCP 服务失败: ${err.message}`
1648
- }
1692
+ probeError = controller.signal.aborted ? `MCP 工具解析超时(${MCP_TOOLS_TIMEOUT_MS / 1000} 秒)` : `连接 MCP 服务失败: ${err.message}`
1693
+ } finally { clearTimeout(timer) }
1649
1694
  }
1650
1695
 
1651
1696
  // 2. Stdio fetch
@@ -1656,9 +1701,7 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1656
1701
  try {
1657
1702
  const probe = await queryStdioToolsList(cmd, args, entryCfg.env || found?.env || {})
1658
1703
  if (probe.tools.length > 0 || !probe.error) {
1659
- if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
1660
- state[key].cachedTools = probe.tools
1661
- writeMcpToolsState(state)
1704
+ cacheConnectorTools(key, probe.tools)
1662
1705
  return { ok: true, tools: probe.tools, disabledTools }
1663
1706
  }
1664
1707
  probeError = probe.error
@@ -1670,20 +1713,38 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
1670
1713
  }
1671
1714
  }
1672
1715
 
1673
- // 3. Return cached fallback
1674
- if (cached.length > 0) {
1675
- return { ok: true, tools: cached, disabledTools }
1676
- }
1677
-
1678
1716
  // A probe that never reached the server is an error, not an empty tool list;
1679
- // reporting ok:true here made the UI claim the server exposes no tools.
1717
+ // reporting ok:true with an empty list made the UI claim the server exposes
1718
+ // no tools. A cached list is different: it is still usable, and surfacing it
1719
+ // as an error replaced the whole row (and its toggles) with a failure notice.
1680
1720
  if (probeError) {
1721
+ if (cached.length > 0) return { ok: true, tools: cached, disabledTools, message: probeError }
1681
1722
  return { ok: false, tools: [], disabledTools, message: probeError }
1682
1723
  }
1683
1724
 
1684
1725
  return { ok: true, tools: [], disabledTools }
1685
1726
  }
1686
1727
 
1728
+ function cacheConnectorTools(key, tools) {
1729
+ // A probe started before an uninstall can finish afterwards; writing then
1730
+ // resurrects the removed plugin's tool table for the next install of the
1731
+ // same name.
1732
+ const owner = key.slice(0, key.indexOf('::'))
1733
+ if (owner !== 'user-mcp' && !readState().plugins.some((p) => p.name === owner)) return
1734
+ const state = readMcpToolsState()
1735
+ state[key] = { ...state[key], cachedTools: tools }
1736
+ writeMcpToolsState(state)
1737
+ MEMORY_TOOLS_CACHE.set(key, { tools })
1738
+ }
1739
+
1740
+ function warmInstalledConnectorTools(pluginName, connectors) {
1741
+ for (const connector of connectors) {
1742
+ if (getConnectorEntry(pluginName, connector.name)) {
1743
+ void fetchConnectorTools(pluginName, connector.name, true).catch(() => {})
1744
+ }
1745
+ }
1746
+ }
1747
+
1687
1748
  export function isScanDirRegistered(path) {
1688
1749
  const state = readState()
1689
1750
  const target = (path || '').replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '')
@@ -1739,6 +1800,9 @@ export function syncPluginSkillsToDsh(pluginName) {
1739
1800
  const srcSkillFile = join(srcSkillDir, 'SKILL.md')
1740
1801
  if (existsSync(srcSkillFile)) {
1741
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
1742
1806
  safeRmDir(destSkillDir)
1743
1807
  copyDir(srcSkillDir, destSkillDir)
1744
1808
  synced.push(entry.name)
@@ -1762,6 +1826,7 @@ export function removePluginSkillsFromDsh(pluginName) {
1762
1826
  for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
1763
1827
  if (entry.isDirectory()) {
1764
1828
  const destSkillDir = join(dshSkills, entry.name)
1829
+ if (isUploadedSkillTarget(destSkillDir)) continue
1765
1830
  safeRmDir(destSkillDir)
1766
1831
  }
1767
1832
  }
@@ -1769,7 +1834,7 @@ export function removePluginSkillsFromDsh(pluginName) {
1769
1834
 
1770
1835
  // 2. Also remove any skills prefixed with plugin name or compiled subagent hub
1771
1836
  const subagentHubName = `${pluginName}-agents`
1772
- safeRmDir(join(dshSkills, subagentHubName))
1837
+ if (!isUploadedSkillTarget(join(dshSkills, subagentHubName))) safeRmDir(join(dshSkills, subagentHubName))
1773
1838
  }
1774
1839
 
1775
1840
  /**
@@ -1889,9 +1954,10 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
1889
1954
  }
1890
1955
  }
1891
1956
 
1892
- // 2.5. If the plugin repository has skill directories directly under root, mirror into skills/
1957
+ // 2.5. Skill directories beside a root SKILL.md belong to that one skill.
1958
+ // Only expand them when the package has no root skill of its own.
1893
1959
  try {
1894
- for (const entry of readdirSync(target, { withFileTypes: true })) {
1960
+ if (!rootSkillMd) for (const entry of readdirSync(target, { withFileTypes: true })) {
1895
1961
  if (
1896
1962
  entry.isDirectory() &&
1897
1963
  entry.name !== 'skills' &&
@@ -2034,14 +2100,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
2034
2100
  writeState(state)
2035
2101
  invalidateParserCaches()
2036
2102
 
2037
- // Proactively warm up and cache tools for local stdio/npx MCP servers in the background
2038
- for (const c of pluginConnectors) {
2039
- if (c.command === 'npx' || (c.args && c.args.some((a) => typeof a === 'string' && a.includes('@')))) {
2040
- setTimeout(() => {
2041
- fetchConnectorTools(pluginName, c.name, true).catch(() => {});
2042
- }, 500);
2043
- }
2044
- }
2103
+ warmInstalledConnectorTools(pluginName, pluginConnectors)
2045
2104
 
2046
2105
  return {
2047
2106
  ok: true,
@@ -2106,6 +2165,7 @@ export function uninstallPlugin(pluginName) {
2106
2165
  delete mcpToolsState[k]
2107
2166
  mcpToolsStateChanged = true
2108
2167
  MEMORY_TOOLS_CACHE.delete(k)
2168
+ MCP_TOOLS_INFLIGHT.delete(k)
2109
2169
  }
2110
2170
  }
2111
2171
  if (mcpToolsStateChanged) {
@@ -2196,13 +2256,14 @@ export async function findMarketRow(sourceId, pluginName) {
2196
2256
  }
2197
2257
 
2198
2258
  /**
2199
- * Author from the source's live marketplace row. Used as the last fallback for
2200
- * installed records written before the reader merged each plugin's own
2201
- * manifest (`author: null`). Returns null when the row or its author is absent.
2259
+ * The source's live marketplace row, read synchronously. Used as the last
2260
+ * fallback for installed records written before the reader merged each
2261
+ * plugin's own manifest, and as the identity source (`homepage`, `source`,
2262
+ * `icons`) the browse grid and connector rows render from. Null when absent.
2202
2263
  */
2203
- function findMarketRowAuthor(sourceId, pluginName) {
2264
+ function findMarketRowSync(sourceId, pluginName) {
2204
2265
  try {
2205
- return readMarketplace(sourceId).find((r) => r.name === pluginName)?.author ?? null
2266
+ return readMarketplace(sourceId).find((r) => r.name === pluginName) ?? null
2206
2267
  } catch {
2207
2268
  return null
2208
2269
  }
@@ -2321,9 +2382,17 @@ export function installedDetails() {
2321
2382
  const manifestAuthor = targetManifest?.author
2322
2383
  ? (typeof targetManifest.author === 'string' ? targetManifest.author : targetManifest.author.name)
2323
2384
  : null
2324
- const author = rec.author || manifestAuthor || findMarketRowAuthor(rec.sourceId, rec.name)
2385
+ const marketRow = findMarketRowSync(rec.sourceId, rec.name)
2386
+ const author = rec.author || manifestAuthor || marketRow?.author
2387
+ // The browse list and the connector rows render the same plugin through the
2388
+ // same icon component, so they must be handed the same identity fields the
2389
+ // detail page merges in. Without these a plugin whose manifest declares no
2390
+ // icon falls back to "author name as a GitHub handle" and shows a stranger's
2391
+ // 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))
2325
2394
  const detail = existsSync(target) ? {
2326
- icons: buildPluginIcons(targetManifest, { sourceId: rec.sourceId, name: rec.name, dir: target }),
2395
+ icons: hasDeclaredIcon ? declaredIcons : (marketRow?.icons || declaredIcons),
2327
2396
  skills: listSkills(target),
2328
2397
  agents: listAgents(target),
2329
2398
  prompts: listPrompts(target),
@@ -2335,7 +2404,13 @@ export function installedDetails() {
2335
2404
  return {
2336
2405
  ...rec,
2337
2406
  ...detail,
2407
+ description: rec.description || targetManifest?.description || marketRow?.description || '',
2338
2408
  author: author || rec.author,
2409
+ // Identity fields the icon chain reads. The detail page already merges
2410
+ // these from the marketplace row before rendering, which is why the same
2411
+ // plugin showed one icon inline and another on its own page.
2412
+ homepage: rec.homepage || marketRow?.homepage,
2413
+ source: rec.source || marketRow?.source,
2339
2414
  skillCount: detail.skills.length,
2340
2415
  agentCount: detail.agents.length,
2341
2416
  promptCount: detail.prompts.length,
package/src/local.js CHANGED
@@ -1,16 +1,34 @@
1
- import { existsSync, readdirSync, statSync, cpSync, mkdirSync, writeFileSync, mkdtempSync } from 'node:fs'
1
+ import { existsSync, readdirSync, statSync, cpSync, copyFileSync, mkdirSync, writeFileSync, mkdtempSync, readFileSync } from 'node:fs'
2
2
  import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { execFile } from 'node:child_process'
5
5
  import { promisify } from 'node:util'
6
- import { sourceCacheDir, readState, writeState, safeRmDir } from './store.js'
7
- import { safeSegment } from './market.js'
8
- import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache } from './parser.js'
6
+ import { load as parseYaml } from 'js-yaml'
7
+ import { sourceCacheDir, readState, writeState, safeRmDir, slugify } from './store.js'
8
+ import { safeSegment, pluginPath } from './market.js'
9
+ import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache, formatDisplayName } from './parser.js'
10
+ import { installUploadedSkills } from './skill-uploads.js'
9
11
 
10
12
  const execFileAsync = promisify(execFile)
11
13
 
12
14
  const TEMP_ROOT = () => join(sourceCacheDir('local'), '.temp')
13
15
 
16
+ /** True when `child` is `root` itself or sits inside it. */
17
+ function containsPath(root, child) {
18
+ const rel = relative(resolve(root), resolve(child))
19
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..\\') && !rel.startsWith('../'))
20
+ }
21
+
22
+ /** Copy a directory's entries into an existing directory, not into a subdir of it. */
23
+ function copyTreeContents(from, to) {
24
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
25
+ const source = join(from, entry.name)
26
+ const target = join(to, entry.name)
27
+ if (entry.isDirectory()) cpSync(source, target, { recursive: true, force: true })
28
+ else if (entry.isFile()) copyFileSync(source, target)
29
+ }
30
+ }
31
+
14
32
  /** Delete stale .temp artifacts (uploaded zips, inspect extraction dirs) older than 1h. */
15
33
  function sweepTemp() {
16
34
  const root = TEMP_ROOT()
@@ -73,6 +91,79 @@ export function resolvePluginDir(rootDir) {
73
91
  return null
74
92
  }
75
93
 
94
+ function skillFileMetadata(file) {
95
+ try {
96
+ const raw = readFileSync(file, 'utf8').replace(/^/, '')
97
+ const match = raw.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/)
98
+ const meta = match ? parseYaml(match[1]) : null
99
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return null
100
+ if (typeof meta.name !== 'string' || typeof meta.description !== 'string' || !meta.description.trim()) return null
101
+ return meta
102
+ } catch { return null }
103
+ }
104
+
105
+ function directSkillEntry(dir, fallbackName, file = null) {
106
+ const manifest = file ? skillFileMetadata(file) : skillFileMetadata(['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync))
107
+ if (!manifest) return null
108
+ const name = manifest.name.trim()
109
+ if (!name) return null
110
+ return {
111
+ dir,
112
+ file: file || undefined,
113
+ singleFile: !!file,
114
+ row: {
115
+ id: `skills/${name}`, sourceId: 'skills-local', name,
116
+ displayName: typeof manifest.displayName === 'string' ? manifest.displayName : formatDisplayName(name),
117
+ description: manifest.description.trim(), version: '1.0.0', source: './',
118
+ },
119
+ }
120
+ }
121
+
122
+ /** A pure skill package is a root skill or one level of direct skill entries. */
123
+ function collectDirectSkills(dir, fallbackName) {
124
+ const rootFile = ['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync)
125
+ if (rootFile) {
126
+ const entry = directSkillEntry(dir, fallbackName)
127
+ return entry ? [entry] : []
128
+ }
129
+ const root = existsSync(join(dir, 'skills')) ? join(dir, 'skills') : dir
130
+ const entries = []
131
+ try {
132
+ for (const child of readdirSync(root, { withFileTypes: true })) {
133
+ if (EXCLUDED_UPLOAD_DIRS.has(child.name) || child.name.startsWith('.')) continue
134
+ const path = join(root, child.name)
135
+ if (child.isDirectory()) {
136
+ const entry = directSkillEntry(path, child.name)
137
+ if (entry) entries.push(entry)
138
+ } else if (child.isFile() && /\.md$/i.test(child.name)) {
139
+ const entry = directSkillEntry(root, child.name.replace(/\.md$/i, ''), path)
140
+ if (entry) entries.push(entry)
141
+ }
142
+ }
143
+ } catch {}
144
+ return entries
145
+ }
146
+
147
+ const EXCLUDED_UPLOAD_DIRS = new Set(['node_modules', '__pycache__', 'agents', 'commands', 'hooks', 'docs', 'assets'])
148
+
149
+ function isPureSkillPackage(dir) {
150
+ return ![
151
+ '.claude-plugin/plugin.json', '.codex-plugin/plugin.json', 'plugin.json', 'package.json',
152
+ 'mcp.json', '.mcp.json', 'server.json', 'agents', 'commands',
153
+ ].some(path => existsSync(join(dir, path)))
154
+ }
155
+
156
+ function marketSourceName(dir, fallbackName) {
157
+ for (const path of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
158
+ try {
159
+ const raw = JSON.parse(readFileSync(join(dir, path), 'utf8'))
160
+ if (typeof raw.name === 'string' && raw.name.trim()) return raw.name.trim()
161
+ if (typeof raw.title === 'string' && raw.title.trim()) return raw.title.trim()
162
+ } catch {}
163
+ }
164
+ return formatDisplayName(fallbackName) || '本地市场'
165
+ }
166
+
76
167
  export async function inspectLocalPlugin(rawPath) {
77
168
  let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
78
169
  if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
@@ -109,9 +200,16 @@ export async function inspectLocalPlugin(rawPath) {
109
200
 
110
201
  const rawFallbackName = (isZip && effectiveDir === tempExtractDir ? basename(targetPath).replace(/\.(zip|tgz|tar\.gz)$/i, '') : basename(effectiveDir)).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'local-plugin'
111
202
  const fallbackName = safeSegment(rawFallbackName, 'plugin name')
112
- const isMarket = ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
113
- && !existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) && !existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json'))
203
+ // Recognition follows the package formats, not the upload transport:
204
+ // marketplace -> Claude -> Codex -> pure skills. Claude/Codex precedence in
205
+ // readPluginManifest is shared with the existing source installation path.
206
+ const isMarket = ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
207
+ const pureSkills = !isMarket && isPureSkillPackage(effectiveDir)
208
+ const directSkills = pureSkills ? collectDirectSkills(effectiveDir, fallbackName) : []
209
+ const singleFile = !isZip && statSync(targetPath).isFile()
210
+ const kind = isMarket ? 'marketplace' : pureSkills ? 'skills' : existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json')) ? 'claude' : existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) ? 'codex' : 'plugin'
114
211
  let entries
212
+ if (kind === 'skills') entries = directSkills
115
213
  try {
116
214
  if (isMarket) {
117
215
  entries = parseMarketplaceFromDisk('local-upload', effectiveDir).map((row) => {
@@ -121,7 +219,7 @@ export async function inspectLocalPlugin(rawPath) {
121
219
  if (rel.startsWith('..') || isAbsolute(rel) || !isPluginDir(dir)) throw new Error(`市场条目「${row.name}」缺少有效的本地插件目录`)
122
220
  return { row, dir }
123
221
  })
124
- } else {
222
+ } else if (kind !== 'skills') {
125
223
  const row = parsePluginRowFromDir(effectiveDir, fallbackName, 'local')
126
224
  entries = row ? [{ row, dir: effectiveDir }] : []
127
225
  if (!row) {
@@ -149,6 +247,7 @@ export async function inspectLocalPlugin(rawPath) {
149
247
  const agents = entries.flatMap((e) => listAgents(e.dir))
150
248
 
151
249
  const duplicate = entries.find((e) => existsSync(join(sourceCacheDir('local'), safeSegment(e.row.name, 'plugin name'))))
250
+ || (kind === 'skills' ? entries.find((e) => (readState().uploadedSkills || []).some(record => record.name === e.row.name)) : undefined)
152
251
  const localDest = duplicate ? join(sourceCacheDir('local'), duplicate.row.name) : join(sourceCacheDir('local'), cleanPluginName)
153
252
  let exists = false
154
253
  let existingVersion = undefined
@@ -165,6 +264,7 @@ export async function inspectLocalPlugin(rawPath) {
165
264
 
166
265
  return {
167
266
  ok: true,
267
+ kind,
168
268
  effectiveDir,
169
269
  tempExtractDir,
170
270
  entries,
@@ -180,6 +280,84 @@ export async function inspectLocalPlugin(rawPath) {
180
280
  }
181
281
  }
182
282
 
283
+ /**
284
+ * Pure skill packages go straight into the Skills tab instead of the plugin
285
+ * install pipeline: no mirrored copy, no agents/commands conversion.
286
+ */
287
+ export async function importLocalSkills(rawPath, { overwrite = false } = {}) {
288
+ const inspectRes = await inspectLocalPlugin(rawPath)
289
+ if (!inspectRes.ok) throw new Error(inspectRes.error)
290
+ if (inspectRes.kind !== 'skills') throw new Error('该内容不是纯 Skills 包')
291
+ const { tempExtractDir, entries, singleFile } = inspectRes
292
+ try {
293
+ // A bare SKILL.md upload is one flat skill. When the folder it came from is
294
+ // a collection, the walk up yields several entries, and flattening those
295
+ // would drop each skill's assets along with its directory.
296
+ const installed = installUploadedSkills(entries, { overwrite, singleFile: singleFile && entries.length === 1 })
297
+ return { ok: true, sourceId: 'skills-local', skills: installed, kind: 'skills' }
298
+ } finally {
299
+ if (tempExtractDir) safeRmDir(tempExtractDir)
300
+ }
301
+ }
302
+
303
+ /**
304
+ * An uploaded marketplace becomes its own plugin source tab: its declared
305
+ * plugins are copied under the source cache and listed by the normal market
306
+ * reader, so install/update/uninstall behave exactly like a Git source.
307
+ */
308
+ export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false } = {}) {
309
+ const inspectRes = await inspectLocalPlugin(rawPath)
310
+ if (!inspectRes.ok) throw new Error(inspectRes.error)
311
+ if (inspectRes.kind !== 'marketplace') throw new Error('该内容不是插件市场')
312
+ const { effectiveDir, tempExtractDir, entries } = inspectRes
313
+ const label = marketSourceName(effectiveDir, basename(effectiveDir))
314
+ const name = String(sourceName || '').trim().slice(0, 30) || label
315
+ const sourceId = `local-${slugify(label) || 'market'}`
316
+ const dest = sourceCacheDir(sourceId)
317
+ const state = readState()
318
+ if (existsSync(dest) && !overwrite && state.sources.some(source => source.id === sourceId)) {
319
+ if (tempExtractDir) safeRmDir(tempExtractDir)
320
+ throw new Error(`已存在同名插件市场「${label}」`)
321
+ }
322
+ // The destination is wiped below, so a source that is or contains it would be
323
+ // destroyed along with the copy that is still being read from.
324
+ if (containsPath(dest, effectiveDir) || containsPath(effectiveDir, dest)) {
325
+ if (tempExtractDir) safeRmDir(tempExtractDir)
326
+ throw new Error('导入源与插件市场存储目录重叠,请从独立文件夹导入')
327
+ }
328
+ try {
329
+ safeRmDir(dest)
330
+ mkdirSync(dest, { recursive: true })
331
+ for (const { row, dir } of entries) {
332
+ // Keep each plugin on the path its manifest declares: a rewritten layout
333
+ // (`plugins/<name>`) would break `./external_plugins/x` and `./`, and the
334
+ // reader resolves sources against the copied manifest after a restart.
335
+ const target = pluginPath(dest, `./${row.source.replace(/^\.\//, '')}`)
336
+ mkdirSync(dirname(target), { recursive: true })
337
+ if (resolve(target) !== resolve(dest)) cpSync(dir, target, { recursive: true, force: true })
338
+ else copyTreeContents(dir, target)
339
+ }
340
+ // Carry the marketplace manifest itself so the standard reader finds the
341
+ // same rows on the next start, not only during this upload.
342
+ for (const relativePath of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
343
+ const file = join(effectiveDir, relativePath)
344
+ if (!existsSync(file)) continue
345
+ const out = join(dest, relativePath)
346
+ mkdirSync(dirname(out), { recursive: true })
347
+ copyFileSync(file, out)
348
+ }
349
+ } finally {
350
+ if (tempExtractDir) safeRmDir(tempExtractDir)
351
+ }
352
+ if (!state.sources.some(source => source.id === sourceId)) {
353
+ state.sources.push({ id: sourceId, name, url: `local-market://${sourceId}`, addedAt: Date.now() })
354
+ writeState(state)
355
+ }
356
+ invalidateMarketplaceCache(sourceId)
357
+ return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row) }
358
+ }
359
+
360
+ /** Legacy plugin-pipeline import; the UI routes pure skill packages elsewhere. */
183
361
  export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
184
362
  const inspectRes = await inspectLocalPlugin(rawPath)
185
363
  if (!inspectRes.ok) {