universal-plugin-hub 1.0.12 → 1.0.30

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.
Files changed (60) hide show
  1. package/README.md +34 -8
  2. package/README.zh.md +35 -9
  3. package/assets/Add-plugin-source.png +0 -0
  4. package/assets/MCP.png +0 -0
  5. package/assets/Plugin-management.png +0 -0
  6. package/assets/Plugins-official.png +0 -0
  7. package/assets/Skills.png +0 -0
  8. package/assets/fluent-3d/balance_scale_3d.png +0 -0
  9. package/assets/fluent-3d/bar_chart_3d.png +0 -0
  10. package/assets/fluent-3d/books_3d.png +0 -0
  11. package/assets/fluent-3d/brain_3d.png +0 -0
  12. package/assets/fluent-3d/briefcase_3d.png +0 -0
  13. package/assets/fluent-3d/card_file_box_3d.png +0 -0
  14. package/assets/fluent-3d/chart_increasing_3d.png +0 -0
  15. package/assets/fluent-3d/clapper_board_3d.png +0 -0
  16. package/assets/fluent-3d/clipboard_3d.png +0 -0
  17. package/assets/fluent-3d/cloud_3d.png +0 -0
  18. package/assets/fluent-3d/compass_3d.png +0 -0
  19. package/assets/fluent-3d/control_knobs_3d.png +0 -0
  20. package/assets/fluent-3d/desktop_computer_3d.png +0 -0
  21. package/assets/fluent-3d/framed_picture_3d.png +0 -0
  22. package/assets/fluent-3d/gear_3d.png +0 -0
  23. package/assets/fluent-3d/globe_with_meridians_3d.png +0 -0
  24. package/assets/fluent-3d/graduation_cap_3d.png +0 -0
  25. package/assets/fluent-3d/handshake_3d.png +0 -0
  26. package/assets/fluent-3d/identification_card_3d.png +0 -0
  27. package/assets/fluent-3d/input_latin_letters_3d.png +0 -0
  28. package/assets/fluent-3d/lady_beetle_3d.png +0 -0
  29. package/assets/fluent-3d/laptop_3d.png +0 -0
  30. package/assets/fluent-3d/link_3d.png +0 -0
  31. package/assets/fluent-3d/locked_3d.png +0 -0
  32. package/assets/fluent-3d/magnifying_glass_tilted_left_3d.png +0 -0
  33. package/assets/fluent-3d/manifest.json +221 -0
  34. package/assets/fluent-3d/memo_3d.png +0 -0
  35. package/assets/fluent-3d/microscope_3d.png +0 -0
  36. package/assets/fluent-3d/money_bag_3d.png +0 -0
  37. package/assets/fluent-3d/musical_notes_3d.png +0 -0
  38. package/assets/fluent-3d/notebook_3d.png +0 -0
  39. package/assets/fluent-3d/open_book_3d.png +0 -0
  40. package/assets/fluent-3d/puzzle_piece_3d.png +0 -0
  41. package/assets/fluent-3d/red_question_mark_3d.png +0 -0
  42. package/assets/fluent-3d/robot_3d.png +0 -0
  43. package/assets/fluent-3d/shield_3d.png +0 -0
  44. package/assets/fluent-3d/shopping_bags_3d.png +0 -0
  45. package/assets/fluent-3d/sparkles_3d.png +0 -0
  46. package/assets/fluent-3d/speech_balloon_3d.png +0 -0
  47. package/assets/fluent-3d/spiral_calendar_3d.png +0 -0
  48. package/assets/fluent-3d/ticket_3d.png +0 -0
  49. package/assets/fluent-3d/triangular_ruler_3d.png +0 -0
  50. package/assets/fluent-3d/world_map_3d.png +0 -0
  51. package/assets/licenses/fluent-emoji.txt +21 -0
  52. package/client/client.js +10335 -10800
  53. package/package.json +13 -3
  54. package/screenshots.json +7 -0
  55. package/src/icons.js +5 -1
  56. package/src/index.js +26 -2
  57. package/src/install.js +3 -0
  58. package/src/routes.js +54 -6
  59. package/src/skills.js +397 -0
  60. package/assets/hero.png +0 -0
package/package.json CHANGED
@@ -2,8 +2,11 @@
2
2
  "name": "universal-plugin-hub",
3
3
  "title": "Universal Plugin Hub",
4
4
  "displayName": "Universal Plugin Hub",
5
- "description": "DSH 插件市场:安装 Claude Code 与 Codex 插件、Skills 和命令,接入子代理、MCP、Hooks 与 LSP。",
6
- "version": "1.0.12",
5
+ "description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加 Git 插件源和 marketplace、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
+ "version": "1.0.30",
7
+ "engines": {
8
+ "dsh": ">=0.1.5-rc.1"
9
+ },
7
10
  "type": "module",
8
11
  "main": "src/index.js",
9
12
  "license": "MIT",
@@ -67,7 +70,14 @@
67
70
  "client",
68
71
  "scripts/postinstall.js",
69
72
  "cordis.patch.yml",
70
- "assets/hero.png"
73
+ "screenshots.json",
74
+ "assets/Plugins-official.png",
75
+ "assets/Skills.png",
76
+ "assets/MCP.png",
77
+ "assets/Plugin-management.png",
78
+ "assets/Add-plugin-source.png",
79
+ "assets/licenses/fluent-emoji.txt",
80
+ "assets/fluent-3d"
71
81
  ],
72
82
  "devDependencies": {
73
83
  "react": "^19.2.0",
@@ -0,0 +1,7 @@
1
+ [
2
+ "assets/Plugins-official.png",
3
+ "assets/Plugin-management.png",
4
+ "assets/Skills.png",
5
+ "assets/MCP.png",
6
+ "assets/Add-plugin-source.png"
7
+ ]
package/src/icons.js CHANGED
@@ -10,6 +10,8 @@ const CACHE_TTL = 7 * 24 * 60 * 60 * 1000
10
10
  const memory = new Map()
11
11
  const pending = new Map()
12
12
  const failures = new Map()
13
+ const bundledIconRoot = new URL('../assets/fluent-3d/', import.meta.url)
14
+ const bundledIconFiles = new Map(Object.values(JSON.parse(readFileSync(new URL('manifest.json', bundledIconRoot), 'utf8')).icons).map(icon => [icon.url, icon.file]))
13
15
 
14
16
  export function imageContentType(buffer) {
15
17
  if (!buffer?.length) return null
@@ -63,7 +65,7 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
63
65
  }
64
66
  const common = [ui.composerIcon, ui.icon, ui.iconSmall, ui.iconLarge, ui.logo, meta?.icon, meta?.iconUrl, meta?.logo]
65
67
  const values = (theme) => common.flatMap((v) => typeof v === 'object' && v ? [v[theme], v.default, v.url, v.src, v[theme === 'dark' ? 'light' : 'dark']] : [v])
66
- const defaults = dir ? ['assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/logo.png', 'icon.svg', 'logo.svg', 'icon.png', 'logo.png'] : []
68
+ const defaults = dir ? ['assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/codex-icon.png', 'assets/logo.png', 'icon.svg', 'logo.svg', 'icon.png', 'logo.png'] : []
67
69
  const light = [...new Set([ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...defaults].map(toUrl).filter(Boolean))]
68
70
  const dark = [...new Set([ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...defaults].map(toUrl).filter(Boolean))]
69
71
  return { light, dark }
@@ -86,6 +88,8 @@ export async function getOrFetchIcon(url) {
86
88
  }
87
89
  const cached = memory.get(url)
88
90
  if (cached && Date.now() - cached.time < CACHE_TTL) return cached
91
+ const bundledFile = bundledIconFiles.get(url)
92
+ if (bundledFile) return remember(url, { buffer: readFileSync(new URL(bundledFile, bundledIconRoot)), contentType: 'image/png' })
89
93
  if (failures.get(url) > Date.now()) throw new Error('Icon temporarily unavailable')
90
94
  if (pending.has(url)) return pending.get(url)
91
95
  const task = (async () => {
package/src/index.js CHANGED
@@ -8,11 +8,35 @@
8
8
  */
9
9
  import { mountRoutes } from './routes.js'
10
10
  import { cancelAllOAuthVerifications } from './oauth.js'
11
- import { syncAllInstalledSkillsToDsh, installProfilePackages, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
11
+ import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
12
+ import { createSkillsManager } from './skills.js'
13
+ import { createRequire } from 'node:module'
14
+ import { join } from 'node:path'
12
15
 
13
16
  export const name = 'universal-plugin-hub'
14
17
 
15
18
  export function apply(ctx) {
19
+ const skills = createSkillsManager()
20
+ ctx.inject(['skills'], (hostCtx) => {
21
+ hostCtx.effect(() => skills.attach(hostCtx.skills, () => {
22
+ hostCtx.emit('plugin-manager/changed')
23
+ }), 'universal-plugin-hub: skills provider')
24
+ })
25
+ ctx.inject(['skills', 'agents'], (hostCtx) => {
26
+ // Borrow DSH's own scope module so its opaque scope identity is shared.
27
+ // A profile that cannot resolve it only loses the *scoped* half of the
28
+ // skill switches; throwing here would take the whole plugin down with it,
29
+ // so degrade to the global provider and say so once.
30
+ let createScope = null
31
+ try {
32
+ const main = findDshMainNodeModules()
33
+ if (!main) throw new Error('无法定位 DSH 原生 node_modules')
34
+ createScope = createRequire(join(main, '.universal-plugin-hub-resolve.cjs'))('@deepseek-ai/dsh-scope').createScope
35
+ } catch (err) {
36
+ ctx.logger?.warn?.(`[universal-plugin-hub] scoped skill switches unavailable: ${err.message}`)
37
+ }
38
+ hostCtx.effect(() => skills.attachAgents(hostCtx, createScope), 'universal-plugin-hub: scoped skill switches')
39
+ })
16
40
  // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
17
41
  try {
18
42
  syncAllInstalledSkillsToDsh()
@@ -29,7 +53,7 @@ export function apply(ctx) {
29
53
 
30
54
  ctx.inject(['webServer'], (hostCtx) => {
31
55
  hostCtx.effect(() => {
32
- const unmount = mountRoutes(hostCtx.webServer)
56
+ const unmount = mountRoutes(hostCtx.webServer, skills)
33
57
  return () => { unmount(); cancelAllOAuthVerifications() }
34
58
  }, 'universal-plugin-hub: http routes')
35
59
  })
package/src/install.js CHANGED
@@ -1985,6 +1985,9 @@ export async function updatePlugin(pluginName) {
1985
1985
  const state = readState()
1986
1986
  const rec = state.plugins.find((p) => p.name === pluginName)
1987
1987
  if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
1988
+ if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
1989
+ throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
1990
+ }
1988
1991
  const source = state.sources.find((s) => s.id === rec.sourceId)
1989
1992
  if (source && typeof source.url === 'string') {
1990
1993
  const cacheDir = sourceCacheDir(rec.sourceId)
package/src/routes.js CHANGED
@@ -23,11 +23,11 @@ import { remoteConfigFromEntry } from './oauth-config.js'
23
23
 
24
24
  const API_PREFIX = '/universal-plugin-hub/api'
25
25
 
26
- export function mountRoutes(webServer) {
26
+ export function mountRoutes(webServer, skills = null) {
27
27
  const r = webServer.register({
28
28
  kind: 'prefix',
29
29
  path: API_PREFIX,
30
- handler: (req, res) => handle(req, res, API_PREFIX),
30
+ handler: (req, res) => handle(req, res, API_PREFIX, skills),
31
31
  })
32
32
  return () => {
33
33
  try { if (typeof r === 'function') r() } catch {}
@@ -54,7 +54,7 @@ function userMcpConfig(name, body) {
54
54
  }
55
55
  }
56
56
 
57
- async function handle(req, res, prefix = API_PREFIX) {
57
+ async function handle(req, res, prefix = API_PREFIX, skills = null) {
58
58
  const url = new URL(req.url, 'http://localhost')
59
59
  const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
60
60
  const method = req.method ?? 'GET'
@@ -98,8 +98,20 @@ async function handle(req, res, prefix = API_PREFIX) {
98
98
  if (method === 'GET' && path === '/state') {
99
99
  const state = readState()
100
100
  const details = installedDetails()
101
+ let sources = state.sources.map((source) => source.id === 'local' ? { ...source, pluginCount: new Set([...readMarketplace('local').map(p => p.name), ...details.filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name))).map(p => p.name)]).size } : source)
102
+ if (skills && skills.entries().length) {
103
+ const skillSource = { id: 'skills-local', name: 'Skills', virtual: true }
104
+ const ordered = Array.isArray(state.tabOrder) ? state.tabOrder : []
105
+ if (ordered.includes(skillSource.id)) {
106
+ const order = new Map(ordered.map((id, index) => [id, index]))
107
+ sources = [...sources, skillSource].sort((a, b) => (order.get(a.id) ?? 1e9) - (order.get(b.id) ?? 1e9))
108
+ } else {
109
+ const anthropic = sources.findIndex(s => s.id === 'anthropic')
110
+ sources.splice(anthropic < 0 ? 0 : anthropic + 1, 0, skillSource)
111
+ }
112
+ }
101
113
  return sendJson(res, 200, {
102
- sources: state.sources.map((source) => source.id === 'local' ? { ...source, pluginCount: readMarketplace('local').length } : source),
114
+ sources,
103
115
  plugins: details.map((p) => ({
104
116
  ...p,
105
117
  skillsEnabled: isScanDirRegistered(join(installedDir(p.name), 'skills')),
@@ -107,12 +119,38 @@ async function handle(req, res, prefix = API_PREFIX) {
107
119
  })
108
120
  }
109
121
 
122
+ if (path === '/skills' && method === 'GET' && skills) return sendJson(res, 200, { skills: await skills.list() })
123
+ if (path === '/skills/refresh' && method === 'POST' && skills) {
124
+ requireSameOrigin(req); skills.refresh()
125
+ return sendJson(res, 200, { skills: await skills.list() })
126
+ }
127
+ if (path === '/skills/toggle' && method === 'POST' && skills) {
128
+ requireSameOrigin(req)
129
+ const body = await readJsonBody(req)
130
+ if (typeof body.enabled !== 'boolean') throw new Error('无效的开关状态')
131
+ return sendJson(res, 200, await skills.toggle(body.id, body.enabled))
132
+ }
133
+ if (path === '/skills/detail' && method === 'GET' && skills) return sendJson(res, 200, { skill: skills.detail(url.searchParams.get('id'), false) })
134
+ if (path === '/skills/resource' && method === 'GET' && skills) return sendJson(res, 200, { content: skills.resource(url.searchParams.get('id'), url.searchParams.get('path')) })
135
+ if (path === '/skills/icon' && method === 'GET' && skills) {
136
+ try {
137
+ const item = skills.detail(url.searchParams.get('id'), false)
138
+ const { buffer, contentType } = readLocalIcon(item.directory, item.iconPath)
139
+ res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=3600', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" })
140
+ return res.end(buffer)
141
+ } catch { return sendJson(res, 404, { error: 'Icon not found' }) }
142
+ }
143
+
110
144
  // ── market listing / refresh ─────────────────────────────────────────
111
145
  if (method === 'GET' && path === '/market') {
112
146
  const rawSource = url.searchParams.get('sourceId') || url.searchParams.get('source') || 'anthropic'
113
147
  const sourceId = safeSegment(rawSource, 'source id')
114
148
  await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
115
- const rows = readMarketplace(sourceId)
149
+ let rows = readMarketplace(sourceId)
150
+ if (sourceId === 'local') {
151
+ const names = new Set(rows.map(r => r.name))
152
+ rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
153
+ }
116
154
  return sendJson(res, 200, { plugins: rows })
117
155
  }
118
156
 
@@ -125,7 +163,12 @@ async function handle(req, res, prefix = API_PREFIX) {
125
163
  await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
126
164
  await pullSource(sourceId)
127
165
  invalidateMarketplaceCache(sourceId)
128
- return sendJson(res, 200, { ok: true, plugins: readMarketplace(sourceId) })
166
+ let plugins = readMarketplace(sourceId)
167
+ if (sourceId === 'local') {
168
+ const names = new Set(plugins.map(p => p.name))
169
+ plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
170
+ }
171
+ return sendJson(res, 200, { ok: true, plugins })
129
172
  }
130
173
 
131
174
  // ── sources ──────────────────────────────────────────────────────────
@@ -226,6 +269,11 @@ async function handle(req, res, prefix = API_PREFIX) {
226
269
  const sourceIds = Array.isArray(body.sourceIds) ? body.sourceIds : []
227
270
  if (sourceIds.length === 0) throw new Error('无效的插件源列表')
228
271
  const state = readState()
272
+ const order = sourceIds.filter((id, index) => typeof id === 'string' && sourceIds.indexOf(id) === index)
273
+ if (!order.includes('skills-local') && state.tabOrder?.includes('skills-local')) {
274
+ order.splice(Math.min(state.tabOrder.indexOf('skills-local'), order.length), 0, 'skills-local')
275
+ }
276
+ state.tabOrder = order
229
277
  const sourceMap = new Map(state.sources.map((s) => [s.id, s]))
230
278
  const reordered = []
231
279
  for (const id of sourceIds) {
package/src/skills.js ADDED
@@ -0,0 +1,397 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
5
+ import { load as parseYaml } from 'js-yaml'
6
+ import { readState, writeState } from './store.js'
7
+ import { formatDisplayName } from './parser.js'
8
+
9
+ const PROVIDER = 'universal-plugin-hub-skills'
10
+ const EXCLUDED = new Set(['.git', 'node_modules', '__pycache__'])
11
+ const MAX_FILE = 2 * 1024 * 1024
12
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
13
+
14
+ function canonical(path) {
15
+ try { return realpathSync.native(path) } catch { return resolve(path) }
16
+ }
17
+ function samePath(a, b) {
18
+ if (!a || !b) return false
19
+ const left = canonical(a), right = canonical(b)
20
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
21
+ }
22
+ function skillId(file) {
23
+ const path = canonical(file)
24
+ return createHash('sha256').update(process.platform === 'win32' ? path.toLowerCase() : path).digest('hex')
25
+ }
26
+ function policyValue(value, fallback) {
27
+ if (value === undefined) return fallback
28
+ if (typeof value === 'boolean') return value
29
+ const normalized = String(value).toLowerCase()
30
+ if (['true', 'yes', 'on', '1'].includes(normalized)) return true
31
+ if (['false', 'no', 'off', '0'].includes(normalized)) return false
32
+ throw new Error('调用策略必须是布尔值')
33
+ }
34
+ function parseYamlObject(source) {
35
+ try {
36
+ const value = parseYaml(source)
37
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined
38
+ } catch { return undefined }
39
+ }
40
+ // Some SKILL.md files carry the metadata block twice: a template header that
41
+ // was never removed sits above the real one. Only the first block was read and
42
+ // cut, so the copy rendered as a `--- name: … ---` table at the top of the
43
+ // detail page — and the card took the template's name. The body starts after
44
+ // the last leading block instead; a `---` rule further down is page content.
45
+ function splitFrontmatter(raw) {
46
+ // Both ends of a block pin the same line terminator: with `\r?` on only one
47
+ // side, an LF file matches a range running from line 1's `---` to line 2's
48
+ // closing one plus its leading `\r`, and the leftover `\n` throws the next
49
+ // round off by a line — the second copy then never matched.
50
+ const block = /^---[ \t]*(\r?\n)([\s\S]*?)\1---[ \t]*\1/
51
+ // The blank line a copy sits under is skipped with it, so the check below
52
+ // lands on the next block instead of stopping at the gap.
53
+ const gap = /^(?:[ \t]*\r?\n)*/
54
+ let yaml = '', end = 0
55
+ while (end < raw.length) {
56
+ const skip = raw.slice(end).match(gap)[0].length
57
+ const next = raw.slice(end + skip).match(block)
58
+ // Only consecutive metadata counts. A block further down sits under page
59
+ // content, where it is a horizontal rule and a table, not a header.
60
+ if (!next || parseYamlObject(next[2]) === undefined) break
61
+ yaml = next[2]
62
+ end += skip + next[0].length
63
+ }
64
+ return yaml ? { yaml, body: raw.slice(end) } : null
65
+ }
66
+ function readSkill(file, root, isNested) {
67
+ let raw = '', meta = {}, content = '', error = ''
68
+ let invocation = { modelInvocable: true, userInvocable: true }
69
+ try {
70
+ if (statSync(file).size > MAX_FILE) throw new Error('SKILL.md 文件过大')
71
+ raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
72
+ const parsed = splitFrontmatter(raw)
73
+ if (!parsed) throw new Error('缺少完整的 YAML 元数据')
74
+ meta = parseYaml(parsed.yaml) || {}
75
+ if (typeof meta !== 'object' || Array.isArray(meta)) throw new Error('YAML 元数据必须是对象')
76
+ content = parsed.body
77
+ if (typeof meta.name !== 'string' || !NAME.test(meta.name)) throw new Error('名称不符合 DSH 的小写连字符格式')
78
+ if (typeof meta.description !== 'string' || !meta.description.trim()) throw new Error('缺少 description')
79
+ invocation = { modelInvocable: !policyValue(meta['disable-model-invocation'], false), userInvocable: policyValue(meta['user-invocable'], true) }
80
+ } catch (e) {
81
+ error = String(e.message).split('\n')[0]
82
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) meta = {}
83
+ if (!meta.name) meta.name = raw.match(/^name:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '')
84
+ if (!meta.description) meta.description = raw.match(/^description:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '') || raw.match(/^#\s+(.+)/m)?.[1] || ''
85
+ }
86
+ const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name : /^skill\.md$/i.test(basename(file)) ? basename(dirname(file)) : basename(file).replace(/\.md$/i, '')
87
+ const icons = [meta.icon, meta.logo, 'assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/logo.png', 'icon.svg', 'icon.png', 'logo.png']
88
+ const iconPath = icons.find(path => typeof path === 'string' && !path.includes('..') && existsSync(join(dirname(file), path)))
89
+ return {
90
+ id: skillId(file), name, displayName: typeof meta.displayName === 'string' ? meta.displayName : formatDisplayName(name), description: typeof meta.description === 'string' ? meta.description : '',
91
+ path: file, directory: dirname(file), relativePath: relative(root, file), nested: isNested,
92
+ error, content: content || raw, metadata: meta, iconPath,
93
+ invocation,
94
+ }
95
+ }
96
+
97
+ export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')) {
98
+ const entries = [], seen = new Set()
99
+ let children
100
+ try { children = readdirSync(root, { withFileTypes: true }) } catch { return entries }
101
+ // Match DSH's native boundary: <root>/<name>/SKILL.md or <root>/<name>.md.
102
+ for (const entry of children) {
103
+ if (EXCLUDED.has(entry.name)) continue
104
+ const path = join(root, entry.name)
105
+ try {
106
+ const stat = entry.isSymbolicLink() ? statSync(path) : entry
107
+ let file
108
+ if (stat.isDirectory()) {
109
+ const manifest = readdirSync(path).find(name => /^skill\.md$/i.test(name) && statSync(join(path, name)).isFile())
110
+ if (manifest) file = join(path, manifest)
111
+ } else if (stat.isFile() && /\.md$/i.test(entry.name)) file = path
112
+ if (!file) continue
113
+ const id = skillId(file)
114
+ if (!seen.has(id)) { seen.add(id); entries.push(readSkill(file, root, false)) }
115
+ } catch {}
116
+ }
117
+ // Identical direct entries share one card and one provider candidate.
118
+ entries.sort((a, b) => a.path.localeCompare(b.path))
119
+ const identical = new Map(), merged = []
120
+ for (const item of entries) {
121
+ const key = JSON.stringify([item.name, item.metadata, item.content.replace(/\r\n/g, '\n')])
122
+ const existing = !item.error && identical.get(key)
123
+ const location = { id: item.id, path: item.path, relativePath: item.relativePath }
124
+ if (existing) existing.locations.push(location)
125
+ else { item.locations = [location]; merged.push(item); if (!item.error) identical.set(key, item) }
126
+ }
127
+ const counts = new Map()
128
+ for (const item of merged) counts.set(item.name, (counts.get(item.name) || 0) + 1)
129
+ for (const item of merged) item.duplicate = counts.get(item.name) > 1
130
+ return merged.sort((a, b) => a.name.localeCompare(b.name))
131
+ }
132
+
133
+ export function createSkillsManager(root) {
134
+ root ||= join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')
135
+ let cache = null, registry = null, invalidate = null, catalogChanged = null, watcher = null, watchTimer = null, toggling = false
136
+ const agentViews = new Map()
137
+ const scopePolicies = new Map(), presetProviders = new Map()
138
+ let createPolicyScope = null
139
+ function invalidateAll() {
140
+ invalidate?.()
141
+ for (const preset of presetProviders.values()) preset.invalidate?.()
142
+ }
143
+ function ensureScope(scope, service = registry) {
144
+ if (!scope || !createPolicyScope) return
145
+ const existing = scopePolicies.get(scope)
146
+ if (existing?.service === service) return existing.ready
147
+ if (!existing) {
148
+ const off = disabled()
149
+ if (!scan().some(item => !item.error && isDisabled(item, off))) return
150
+ }
151
+ existing?.dispose()
152
+ scopePolicies.delete(scope)
153
+ let owner
154
+ try { owner = createPolicyScope(service.ctx, scope) }
155
+ catch { return }
156
+ let settle
157
+ const pending = new Promise(resolve => { settle = resolve })
158
+ scopePolicies.set(scope, { service, ready: pending, dispose: () => { settle(); return owner.dispose() } })
159
+ // Never reject: failing to register only means this one scope gets no
160
+ // disabled-skill overlay. A rejected promise would be cached here and
161
+ // re-thrown on every later read of this scope, and because catalogs()
162
+ // reads through Promise.all it would blank the entire skills list rather
163
+ // than just this scope.
164
+ owner.ctx.inject(['skills'], target => {
165
+ try { target.skills.registerProvider(() => disabledProvider()) }
166
+ catch { scopePolicies.delete(scope); try { owner.dispose() } catch {} }
167
+ finally { settle() }
168
+ })
169
+ // Cold catalog leases can mint scopes without live agents. Bound their
170
+ // policy lifetimes — but only those: evicting a live agent's policy would
171
+ // quietly report its switched-off skills as enabled again.
172
+ if (scopePolicies.size > 128) {
173
+ for (const key of scopePolicies.keys()) {
174
+ if (agentViews.has(key)) continue
175
+ scopePolicies.get(key).dispose(); scopePolicies.delete(key); break
176
+ }
177
+ }
178
+ return pending
179
+ }
180
+ const scan = (force = false) => {
181
+ if (force || !cache) cache = discoverSkills(root)
182
+ return cache
183
+ }
184
+ const disabled = () => readState().disabledLocalSkills || {}
185
+ const isDisabled = (item, off = disabled()) => item.locations.some(location => off[location.id])
186
+ const matches = (item, current) => current && item.locations.some(location => samePath(current.path, location.path))
187
+ const entries = () => {
188
+ const off = disabled()
189
+ return scan().map(item => {
190
+ const { content, metadata, ...summary } = item
191
+ const icon = item.iconPath ? `/universal-plugin-hub/api/skills/icon?id=${encodeURIComponent(item.id)}` : null
192
+ return { ...summary, sourceId: 'skills-local', enabled: !isDisabled(item, off), available: !!registry, icons: { light: icon ? [icon] : [], dark: icon ? [icon] : [] } }
193
+ })
194
+ }
195
+ function candidate(item, isDisabled) {
196
+ return {
197
+ name: item.name, description: item.description, invocation: isDisabled ? { modelInvocable: false, userInvocable: false } : item.invocation,
198
+ // The same ~/.agents file can be discovered as a project root (rank 200).
199
+ // An explicit off choice must precede every native filesystem rank.
200
+ provider: PROVIDER, source: 'user-agents', rank: isDisabled ? 99 : 501,
201
+ path: item.path, resourceBase: { kind: 'directory', path: item.directory }, locator: item.id,
202
+ }
203
+ }
204
+ const provider = {
205
+ name: PROVIDER,
206
+ async list(options = {}) {
207
+ await ensureScope(options.scope)
208
+ const off = disabled()
209
+ // The native filesystem provider (rank 500) wins whenever it discovers
210
+ // the skill. Profiles that omit that user root still get a fallback.
211
+ return scan().filter(item => !item.error).map(item => candidate(item, isDisabled(item, off)))
212
+ },
213
+ async get(entry) {
214
+ const item = scan().find(s => s.id === entry.locator)
215
+ if (!item || item.error) return undefined
216
+ const fresh = readSkill(item.path, root, item.nested)
217
+ if (fresh.error || fresh.name !== item.name) return undefined
218
+ const { rank, locator, ...summary } = candidate(fresh, isDisabled(item))
219
+ return { ...summary, content: fresh.content, metadata: fresh.metadata.metadata }
220
+ },
221
+ }
222
+ function disabledProvider() {
223
+ return { ...provider, async list() {
224
+ const off = disabled()
225
+ return scan().filter(item => !item.error && isDisabled(item, off)).map(item => candidate(item, true))
226
+ } }
227
+ }
228
+ function refresh() { cache = null; invalidateAll(); catalogChanged?.(); return entries() }
229
+ async function catalogs() {
230
+ return Promise.all([registry.list(), ...[...agentViews.values()].map(view => view.registry().list(view.lookup()))])
231
+ }
232
+ async function status(item) {
233
+ if (!registry) return { available: false, message: 'DSH Skills 服务不可用' }
234
+ try {
235
+ // A session that never surfaced this skill has nothing to enforce, and
236
+ // must not veto the switch: requiring every agent catalogue to list it
237
+ // would revert every toggle as soon as one preset scopes it away.
238
+ const present = (await catalogs()).map(list => list.find(s => s.name === item.name)).filter(Boolean)
239
+ if (!present.length) return { available: false, message: '当前管理视图未查到此 Skill,无法确认调用状态' }
240
+ const foreign = present.find(s => !matches(item, s))
241
+ if (foreign) return { available: false, message: `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` }
242
+ return { available: true, invocations: present.map(s => s.invocation) }
243
+ } catch (e) { return { available: false, message: e.message } }
244
+ }
245
+ async function list() {
246
+ const list = entries()
247
+ if (!registry) return list.map(x => ({ ...x, enabled: null, statusMessage: x.error || 'DSH Skills 服务不可用' }))
248
+ let current
249
+ try { current = await catalogs() } catch { return list.map(x => ({ ...x, enabled: null, available: false, statusMessage: x.error || '无法读取 DSH Skills 状态' })) }
250
+ const catalogsByName = current.map(rows => new Map(rows.map(s => [s.name, s])))
251
+ return list.map(item => {
252
+ // Only the catalogues that actually surface this skill have a say, the
253
+ // same rule status() uses, so a preset that scopes a skill away does not
254
+ // show it as unavailable or reverted.
255
+ const found = catalogsByName.map(rows => rows.get(item.name)).filter(Boolean)
256
+ const foreign = found.find(s => !matches(item, s))
257
+ const matching = found.length > 0 && !foreign
258
+ const desired = item.enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
259
+ const applied = matching && found.every(s => s.invocation.modelInvocable === desired.modelInvocable && s.invocation.userInvocable === desired.userInvocable)
260
+ const actualInvocation = matching ? { modelInvocable: found.some(s => s.invocation.modelInvocable), userInvocable: found.some(s => s.invocation.userInvocable) } : null
261
+ return { ...item, enabled: matching ? applied ? item.enabled : actualInvocation.modelInvocable || actualInvocation.userInvocable : null,
262
+ available: matching && !item.error, actualInvocation, verifiedViews: matching ? found.length : 0, activePath: matching ? found[0].path : null,
263
+ statusMessage: item.error || (!matching && !foreign ? '当前管理视图未查到此 Skill,无法确认调用状态' : foreign ? `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` : !applied ? '开关状态尚未在所有会话中生效,请重新切换' : '') }
264
+ })
265
+ }
266
+ async function toggle(id, enabled) {
267
+ if (toggling) throw new Error('正在更新另一个 Skill,请稍后重试')
268
+ toggling = true
269
+ try {
270
+ const item = scan().find(s => s.id === id)
271
+ if (!item) throw new Error('Skill 不存在,请刷新列表')
272
+ if (item.error) throw new Error(item.error)
273
+ const before = await status(item)
274
+ if (!before.available) throw new Error(before.message)
275
+ const state = readState(), previous = { ...(state.disabledLocalSkills || {}) }
276
+ state.disabledLocalSkills = { ...previous }
277
+ for (const location of item.locations) {
278
+ if (enabled) delete state.disabledLocalSkills[location.id]
279
+ else state.disabledLocalSkills[location.id] = true
280
+ }
281
+ writeState(state); invalidateAll()
282
+ const after = await status(item)
283
+ const desired = enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
284
+ if (!after.available || !after.invocations.every(policy => policy.modelInvocable === desired.modelInvocable && policy.userInvocable === desired.userInvocable)) {
285
+ state.disabledLocalSkills = previous; writeState(state); invalidateAll()
286
+ catalogChanged?.()
287
+ throw new Error(after.message || 'DSH 未确认开关状态,已恢复原状态')
288
+ }
289
+ catalogChanged?.()
290
+ return { ok: true, skills: await list() }
291
+ } finally { toggling = false }
292
+ }
293
+ function detail(id, includeFiles = true) {
294
+ const item = scan().find(s => s.id === id)
295
+ if (!item) throw new Error('Skill 不存在,请刷新列表')
296
+ const files = []
297
+ function walk(dir, depth) {
298
+ if (depth > 8 || files.length >= 500) return
299
+ let children; try { children = readdirSync(dir, { withFileTypes: true }) } catch { return }
300
+ for (const entry of children) {
301
+ if (entry.name === '.git' || entry.name === 'node_modules' || entry.isSymbolicLink()) continue
302
+ const path = join(dir, entry.name)
303
+ if (entry.isDirectory()) walk(path, depth + 1)
304
+ else if (entry.isFile() && path !== item.path) files.push({ path: relative(item.directory, path).split(sep).join('/'), category: relative(item.directory, path).split(sep)[0] })
305
+ }
306
+ }
307
+ if (includeFiles) walk(item.directory, 0)
308
+ return { ...item, enabled: !isDisabled(item), files }
309
+ }
310
+ function resource(id, name) {
311
+ const item = scan().find(s => s.id === id)
312
+ if (!item) throw new Error('Skill 不存在')
313
+ const file = resolve(item.directory, String(name || ''))
314
+ const base = canonical(item.directory), real = canonical(file), rel = relative(base, real)
315
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`) || resolve(base, rel) !== real) throw new Error('无效的资源路径')
316
+ if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size > MAX_FILE) throw new Error('资源不存在或文件过大')
317
+ const data = readFileSync(file)
318
+ if (data.includes(0)) throw new Error('该资源不是文本文件')
319
+ return data.toString('utf8')
320
+ }
321
+ function attach(service, onCatalogChanged = null) {
322
+ registry = service
323
+ catalogChanged = onCatalogChanged
324
+ const dispose = service.registerProvider(control => { invalidate = control.invalidate; return provider })
325
+ try {
326
+ watcher = watch(root, { recursive: true }, (event, filename) => {
327
+ if (filename) {
328
+ const parts = String(filename).split(/[\\/]/)
329
+ if (parts.length > 2 || (parts.length === 2 && !/^skill\.md$/i.test(parts[1]))) return
330
+ if (event === 'change' && parts.length === 1 && !/\.md$/i.test(parts[0])) return
331
+ }
332
+ clearTimeout(watchTimer)
333
+ watchTimer = setTimeout(() => { cache = null; invalidateAll(); catalogChanged?.() }, 150)
334
+ watchTimer.unref?.()
335
+ })
336
+ watcher.on('error', () => {})
337
+ } catch {}
338
+ return () => { clearTimeout(watchTimer); watcher?.close(); watcher = null; registry = null; invalidate = null; catalogChanged = null; dispose() }
339
+ }
340
+ function attachAgents(ctx, createScope = null) {
341
+ createPolicyScope = createScope
342
+ // Every per-agent registration is best effort: one agent whose context
343
+ // lacks a skills service (or already holds this provider name) must not
344
+ // abort the loop and leave the remaining agents unbound.
345
+ function guard(what, run) {
346
+ try { return run() } catch (error) { ctx.logger?.warn?.(`[universal-plugin-hub] ${what} skipped: ${error.message}`); return null }
347
+ }
348
+ const bind = (agent) => {
349
+ if (agentViews.has(agent)) return
350
+ // A preset's filesystem provider shadows the global layer regardless of
351
+ // rank. Explicit off choices must also live in the exact agent scope.
352
+ // Enabled skills continue to resolve through their native providers.
353
+ const serviceFor = () => ctx.get?.('agentPresets')?.serviceFor(agent, 'skills') ?? registry
354
+ const service = serviceFor()
355
+ if (service !== registry && !presetProviders.has(service)) {
356
+ let invalidatePreset
357
+ const dispose = guard('preset provider', () => service.registerProvider(control => { invalidatePreset = control.invalidate; return { ...disabledProvider(), async list(options = {}) {
358
+ await ensureScope(options.scope, service)
359
+ return disabledProvider().list(options)
360
+ } } }))
361
+ // A provider that failed to register has no invalidation hook, so it
362
+ // must not be tracked: doing so would hand out a users count for a
363
+ // registration that does not exist.
364
+ if (dispose) presetProviders.set(service, { dispose, invalidate: invalidatePreset, users: 0 })
365
+ }
366
+ if (service !== registry && presetProviders.has(service)) presetProviders.get(service).users++
367
+ const dispose = (createScope ? (() => { const policy = scopePolicies.get(agent); scopePolicies.delete(agent); return policy?.dispose() })
368
+ : guard('agent provider', () => agent.ctx.skills.registerProvider(() => disabledProvider()))) || (() => {})
369
+ agentViews.set(agent, { dispose: () => {
370
+ const pending = dispose()
371
+ const preset = presetProviders.get(service)
372
+ if (preset && --preset.users === 0) { preset.dispose(); presetProviders.delete(service) }
373
+ return pending
374
+ }, registry: serviceFor, lookup: () => ({ scope: agent, cwd: ctx.get?.('workingDirectory')?.get(agent.session) ?? agent.session?.header?.cwd }) })
375
+ }
376
+ const unbind = (agent) => { const view = agentViews.get(agent); agentViews.delete(agent); return view?.dispose() }
377
+ const offCreated = ctx.on('agent/created', ({ agent }) => bind(agent))
378
+ const offDisposed = ctx.on('agent/disposed', ({ agent }) => unbind(agent))
379
+ const offPreset = ctx.on('agent-preset/selected', async id => {
380
+ const agent = ctx.agents.get(id)
381
+ if (agent) { await unbind(agent); bind(agent) }
382
+ })
383
+ for (const agent of ctx.agents.list()) bind(agent)
384
+ invalidateAll()
385
+ catalogChanged?.()
386
+ return () => {
387
+ offCreated(); offDisposed(); offPreset()
388
+ const pending = [...agentViews.keys()].map(unbind)
389
+ for (const policy of scopePolicies.values()) pending.push(policy.dispose())
390
+ scopePolicies.clear(); createPolicyScope = null
391
+ for (const { dispose } of presetProviders.values()) dispose()
392
+ presetProviders.clear()
393
+ return Promise.all(pending)
394
+ }
395
+ }
396
+ return { attach, attachAgents, entries, list, toggle, detail, resource, refresh }
397
+ }
package/assets/hero.png DELETED
Binary file