universal-plugin-hub 1.0.12 → 1.0.25

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 +33 -5
  2. package/README.zh.md +33 -5
  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 +496 -1122
  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 +365 -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 插件源、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
+ "version": "1.0.25",
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,365 @@
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 readSkill(file, root, isNested) {
35
+ let raw = '', meta = {}, content = '', error = ''
36
+ let invocation = { modelInvocable: true, userInvocable: true }
37
+ try {
38
+ if (statSync(file).size > MAX_FILE) throw new Error('SKILL.md 文件过大')
39
+ raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
40
+ const match = raw.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/)
41
+ if (!match) throw new Error('缺少完整的 YAML 元数据')
42
+ meta = parseYaml(match[1]) || {}
43
+ if (typeof meta !== 'object' || Array.isArray(meta)) throw new Error('YAML 元数据必须是对象')
44
+ content = raw.slice(match[0].length)
45
+ if (typeof meta.name !== 'string' || !NAME.test(meta.name)) throw new Error('名称不符合 DSH 的小写连字符格式')
46
+ if (typeof meta.description !== 'string' || !meta.description.trim()) throw new Error('缺少 description')
47
+ invocation = { modelInvocable: !policyValue(meta['disable-model-invocation'], false), userInvocable: policyValue(meta['user-invocable'], true) }
48
+ } catch (e) {
49
+ error = String(e.message).split('\n')[0]
50
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) meta = {}
51
+ if (!meta.name) meta.name = raw.match(/^name:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '')
52
+ if (!meta.description) meta.description = raw.match(/^description:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '') || raw.match(/^#\s+(.+)/m)?.[1] || ''
53
+ }
54
+ 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, '')
55
+ const icons = [meta.icon, meta.logo, 'assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/logo.png', 'icon.svg', 'icon.png', 'logo.png']
56
+ const iconPath = icons.find(path => typeof path === 'string' && !path.includes('..') && existsSync(join(dirname(file), path)))
57
+ return {
58
+ id: skillId(file), name, displayName: typeof meta.displayName === 'string' ? meta.displayName : formatDisplayName(name), description: typeof meta.description === 'string' ? meta.description : '',
59
+ path: file, directory: dirname(file), relativePath: relative(root, file), nested: isNested,
60
+ error, content: content || raw, metadata: meta, iconPath,
61
+ invocation,
62
+ }
63
+ }
64
+
65
+ export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')) {
66
+ const entries = [], seen = new Set()
67
+ let children
68
+ try { children = readdirSync(root, { withFileTypes: true }) } catch { return entries }
69
+ // Match DSH's native boundary: <root>/<name>/SKILL.md or <root>/<name>.md.
70
+ for (const entry of children) {
71
+ if (EXCLUDED.has(entry.name)) continue
72
+ const path = join(root, entry.name)
73
+ try {
74
+ const stat = entry.isSymbolicLink() ? statSync(path) : entry
75
+ let file
76
+ if (stat.isDirectory()) {
77
+ const manifest = readdirSync(path).find(name => /^skill\.md$/i.test(name) && statSync(join(path, name)).isFile())
78
+ if (manifest) file = join(path, manifest)
79
+ } else if (stat.isFile() && /\.md$/i.test(entry.name)) file = path
80
+ if (!file) continue
81
+ const id = skillId(file)
82
+ if (!seen.has(id)) { seen.add(id); entries.push(readSkill(file, root, false)) }
83
+ } catch {}
84
+ }
85
+ // Identical direct entries share one card and one provider candidate.
86
+ entries.sort((a, b) => a.path.localeCompare(b.path))
87
+ const identical = new Map(), merged = []
88
+ for (const item of entries) {
89
+ const key = JSON.stringify([item.name, item.metadata, item.content.replace(/\r\n/g, '\n')])
90
+ const existing = !item.error && identical.get(key)
91
+ const location = { id: item.id, path: item.path, relativePath: item.relativePath }
92
+ if (existing) existing.locations.push(location)
93
+ else { item.locations = [location]; merged.push(item); if (!item.error) identical.set(key, item) }
94
+ }
95
+ const counts = new Map()
96
+ for (const item of merged) counts.set(item.name, (counts.get(item.name) || 0) + 1)
97
+ for (const item of merged) item.duplicate = counts.get(item.name) > 1
98
+ return merged.sort((a, b) => a.name.localeCompare(b.name))
99
+ }
100
+
101
+ export function createSkillsManager(root) {
102
+ root ||= join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')
103
+ let cache = null, registry = null, invalidate = null, catalogChanged = null, watcher = null, watchTimer = null, toggling = false
104
+ const agentViews = new Map()
105
+ const scopePolicies = new Map(), presetProviders = new Map()
106
+ let createPolicyScope = null
107
+ function invalidateAll() {
108
+ invalidate?.()
109
+ for (const preset of presetProviders.values()) preset.invalidate?.()
110
+ }
111
+ function ensureScope(scope, service = registry) {
112
+ if (!scope || !createPolicyScope) return
113
+ const existing = scopePolicies.get(scope)
114
+ if (existing?.service === service) return existing.ready
115
+ if (!existing) {
116
+ const off = disabled()
117
+ if (!scan().some(item => !item.error && isDisabled(item, off))) return
118
+ }
119
+ existing?.dispose()
120
+ scopePolicies.delete(scope)
121
+ let owner
122
+ try { owner = createPolicyScope(service.ctx, scope) }
123
+ catch { return }
124
+ let settle
125
+ const pending = new Promise(resolve => { settle = resolve })
126
+ scopePolicies.set(scope, { service, ready: pending, dispose: () => { settle(); return owner.dispose() } })
127
+ // Never reject: failing to register only means this one scope gets no
128
+ // disabled-skill overlay. A rejected promise would be cached here and
129
+ // re-thrown on every later read of this scope, and because catalogs()
130
+ // reads through Promise.all it would blank the entire skills list rather
131
+ // than just this scope.
132
+ owner.ctx.inject(['skills'], target => {
133
+ try { target.skills.registerProvider(() => disabledProvider()) }
134
+ catch { scopePolicies.delete(scope); try { owner.dispose() } catch {} }
135
+ finally { settle() }
136
+ })
137
+ // Cold catalog leases can mint scopes without live agents. Bound their
138
+ // policy lifetimes — but only those: evicting a live agent's policy would
139
+ // quietly report its switched-off skills as enabled again.
140
+ if (scopePolicies.size > 128) {
141
+ for (const key of scopePolicies.keys()) {
142
+ if (agentViews.has(key)) continue
143
+ scopePolicies.get(key).dispose(); scopePolicies.delete(key); break
144
+ }
145
+ }
146
+ return pending
147
+ }
148
+ const scan = (force = false) => {
149
+ if (force || !cache) cache = discoverSkills(root)
150
+ return cache
151
+ }
152
+ const disabled = () => readState().disabledLocalSkills || {}
153
+ const isDisabled = (item, off = disabled()) => item.locations.some(location => off[location.id])
154
+ const matches = (item, current) => current && item.locations.some(location => samePath(current.path, location.path))
155
+ const entries = () => {
156
+ const off = disabled()
157
+ return scan().map(item => {
158
+ const { content, metadata, ...summary } = item
159
+ const icon = item.iconPath ? `/universal-plugin-hub/api/skills/icon?id=${encodeURIComponent(item.id)}` : null
160
+ return { ...summary, sourceId: 'skills-local', enabled: !isDisabled(item, off), available: !!registry, icons: { light: icon ? [icon] : [], dark: icon ? [icon] : [] } }
161
+ })
162
+ }
163
+ function candidate(item, isDisabled) {
164
+ return {
165
+ name: item.name, description: item.description, invocation: isDisabled ? { modelInvocable: false, userInvocable: false } : item.invocation,
166
+ // The same ~/.agents file can be discovered as a project root (rank 200).
167
+ // An explicit off choice must precede every native filesystem rank.
168
+ provider: PROVIDER, source: 'user-agents', rank: isDisabled ? 99 : 501,
169
+ path: item.path, resourceBase: { kind: 'directory', path: item.directory }, locator: item.id,
170
+ }
171
+ }
172
+ const provider = {
173
+ name: PROVIDER,
174
+ async list(options = {}) {
175
+ await ensureScope(options.scope)
176
+ const off = disabled()
177
+ // The native filesystem provider (rank 500) wins whenever it discovers
178
+ // the skill. Profiles that omit that user root still get a fallback.
179
+ return scan().filter(item => !item.error).map(item => candidate(item, isDisabled(item, off)))
180
+ },
181
+ async get(entry) {
182
+ const item = scan().find(s => s.id === entry.locator)
183
+ if (!item || item.error) return undefined
184
+ const fresh = readSkill(item.path, root, item.nested)
185
+ if (fresh.error || fresh.name !== item.name) return undefined
186
+ const { rank, locator, ...summary } = candidate(fresh, isDisabled(item))
187
+ return { ...summary, content: fresh.content, metadata: fresh.metadata.metadata }
188
+ },
189
+ }
190
+ function disabledProvider() {
191
+ return { ...provider, async list() {
192
+ const off = disabled()
193
+ return scan().filter(item => !item.error && isDisabled(item, off)).map(item => candidate(item, true))
194
+ } }
195
+ }
196
+ function refresh() { cache = null; invalidateAll(); catalogChanged?.(); return entries() }
197
+ async function catalogs() {
198
+ return Promise.all([registry.list(), ...[...agentViews.values()].map(view => view.registry().list(view.lookup()))])
199
+ }
200
+ async function status(item) {
201
+ if (!registry) return { available: false, message: 'DSH Skills 服务不可用' }
202
+ try {
203
+ // A session that never surfaced this skill has nothing to enforce, and
204
+ // must not veto the switch: requiring every agent catalogue to list it
205
+ // would revert every toggle as soon as one preset scopes it away.
206
+ const present = (await catalogs()).map(list => list.find(s => s.name === item.name)).filter(Boolean)
207
+ if (!present.length) return { available: false, message: '当前管理视图未查到此 Skill,无法确认调用状态' }
208
+ const foreign = present.find(s => !matches(item, s))
209
+ if (foreign) return { available: false, message: `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` }
210
+ return { available: true, invocations: present.map(s => s.invocation) }
211
+ } catch (e) { return { available: false, message: e.message } }
212
+ }
213
+ async function list() {
214
+ const list = entries()
215
+ if (!registry) return list.map(x => ({ ...x, enabled: null, statusMessage: x.error || 'DSH Skills 服务不可用' }))
216
+ let current
217
+ try { current = await catalogs() } catch { return list.map(x => ({ ...x, enabled: null, available: false, statusMessage: x.error || '无法读取 DSH Skills 状态' })) }
218
+ const catalogsByName = current.map(rows => new Map(rows.map(s => [s.name, s])))
219
+ return list.map(item => {
220
+ // Only the catalogues that actually surface this skill have a say, the
221
+ // same rule status() uses, so a preset that scopes a skill away does not
222
+ // show it as unavailable or reverted.
223
+ const found = catalogsByName.map(rows => rows.get(item.name)).filter(Boolean)
224
+ const foreign = found.find(s => !matches(item, s))
225
+ const matching = found.length > 0 && !foreign
226
+ const desired = item.enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
227
+ const applied = matching && found.every(s => s.invocation.modelInvocable === desired.modelInvocable && s.invocation.userInvocable === desired.userInvocable)
228
+ const actualInvocation = matching ? { modelInvocable: found.some(s => s.invocation.modelInvocable), userInvocable: found.some(s => s.invocation.userInvocable) } : null
229
+ return { ...item, enabled: matching ? applied ? item.enabled : actualInvocation.modelInvocable || actualInvocation.userInvocable : null,
230
+ available: matching && !item.error, actualInvocation, verifiedViews: matching ? found.length : 0, activePath: matching ? found[0].path : null,
231
+ statusMessage: item.error || (!matching && !foreign ? '当前管理视图未查到此 Skill,无法确认调用状态' : foreign ? `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` : !applied ? '开关状态尚未在所有会话中生效,请重新切换' : '') }
232
+ })
233
+ }
234
+ async function toggle(id, enabled) {
235
+ if (toggling) throw new Error('正在更新另一个 Skill,请稍后重试')
236
+ toggling = true
237
+ try {
238
+ const item = scan().find(s => s.id === id)
239
+ if (!item) throw new Error('Skill 不存在,请刷新列表')
240
+ if (item.error) throw new Error(item.error)
241
+ const before = await status(item)
242
+ if (!before.available) throw new Error(before.message)
243
+ const state = readState(), previous = { ...(state.disabledLocalSkills || {}) }
244
+ state.disabledLocalSkills = { ...previous }
245
+ for (const location of item.locations) {
246
+ if (enabled) delete state.disabledLocalSkills[location.id]
247
+ else state.disabledLocalSkills[location.id] = true
248
+ }
249
+ writeState(state); invalidateAll()
250
+ const after = await status(item)
251
+ const desired = enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
252
+ if (!after.available || !after.invocations.every(policy => policy.modelInvocable === desired.modelInvocable && policy.userInvocable === desired.userInvocable)) {
253
+ state.disabledLocalSkills = previous; writeState(state); invalidateAll()
254
+ catalogChanged?.()
255
+ throw new Error(after.message || 'DSH 未确认开关状态,已恢复原状态')
256
+ }
257
+ catalogChanged?.()
258
+ return { ok: true, skills: await list() }
259
+ } finally { toggling = false }
260
+ }
261
+ function detail(id, includeFiles = true) {
262
+ const item = scan().find(s => s.id === id)
263
+ if (!item) throw new Error('Skill 不存在,请刷新列表')
264
+ const files = []
265
+ function walk(dir, depth) {
266
+ if (depth > 8 || files.length >= 500) return
267
+ let children; try { children = readdirSync(dir, { withFileTypes: true }) } catch { return }
268
+ for (const entry of children) {
269
+ if (entry.name === '.git' || entry.name === 'node_modules' || entry.isSymbolicLink()) continue
270
+ const path = join(dir, entry.name)
271
+ if (entry.isDirectory()) walk(path, depth + 1)
272
+ 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] })
273
+ }
274
+ }
275
+ if (includeFiles) walk(item.directory, 0)
276
+ return { ...item, enabled: !isDisabled(item), files }
277
+ }
278
+ function resource(id, name) {
279
+ const item = scan().find(s => s.id === id)
280
+ if (!item) throw new Error('Skill 不存在')
281
+ const file = resolve(item.directory, String(name || ''))
282
+ const base = canonical(item.directory), real = canonical(file), rel = relative(base, real)
283
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`) || resolve(base, rel) !== real) throw new Error('无效的资源路径')
284
+ if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size > MAX_FILE) throw new Error('资源不存在或文件过大')
285
+ const data = readFileSync(file)
286
+ if (data.includes(0)) throw new Error('该资源不是文本文件')
287
+ return data.toString('utf8')
288
+ }
289
+ function attach(service, onCatalogChanged = null) {
290
+ registry = service
291
+ catalogChanged = onCatalogChanged
292
+ const dispose = service.registerProvider(control => { invalidate = control.invalidate; return provider })
293
+ try {
294
+ watcher = watch(root, { recursive: true }, (event, filename) => {
295
+ if (filename) {
296
+ const parts = String(filename).split(/[\\/]/)
297
+ if (parts.length > 2 || (parts.length === 2 && !/^skill\.md$/i.test(parts[1]))) return
298
+ if (event === 'change' && parts.length === 1 && !/\.md$/i.test(parts[0])) return
299
+ }
300
+ clearTimeout(watchTimer)
301
+ watchTimer = setTimeout(() => { cache = null; invalidateAll(); catalogChanged?.() }, 150)
302
+ watchTimer.unref?.()
303
+ })
304
+ watcher.on('error', () => {})
305
+ } catch {}
306
+ return () => { clearTimeout(watchTimer); watcher?.close(); watcher = null; registry = null; invalidate = null; catalogChanged = null; dispose() }
307
+ }
308
+ function attachAgents(ctx, createScope = null) {
309
+ createPolicyScope = createScope
310
+ // Every per-agent registration is best effort: one agent whose context
311
+ // lacks a skills service (or already holds this provider name) must not
312
+ // abort the loop and leave the remaining agents unbound.
313
+ function guard(what, run) {
314
+ try { return run() } catch (error) { ctx.logger?.warn?.(`[universal-plugin-hub] ${what} skipped: ${error.message}`); return null }
315
+ }
316
+ const bind = (agent) => {
317
+ if (agentViews.has(agent)) return
318
+ // A preset's filesystem provider shadows the global layer regardless of
319
+ // rank. Explicit off choices must also live in the exact agent scope.
320
+ // Enabled skills continue to resolve through their native providers.
321
+ const serviceFor = () => ctx.get?.('agentPresets')?.serviceFor(agent, 'skills') ?? registry
322
+ const service = serviceFor()
323
+ if (service !== registry && !presetProviders.has(service)) {
324
+ let invalidatePreset
325
+ const dispose = guard('preset provider', () => service.registerProvider(control => { invalidatePreset = control.invalidate; return { ...disabledProvider(), async list(options = {}) {
326
+ await ensureScope(options.scope, service)
327
+ return disabledProvider().list(options)
328
+ } } }))
329
+ // A provider that failed to register has no invalidation hook, so it
330
+ // must not be tracked: doing so would hand out a users count for a
331
+ // registration that does not exist.
332
+ if (dispose) presetProviders.set(service, { dispose, invalidate: invalidatePreset, users: 0 })
333
+ }
334
+ if (service !== registry && presetProviders.has(service)) presetProviders.get(service).users++
335
+ const dispose = (createScope ? (() => { const policy = scopePolicies.get(agent); scopePolicies.delete(agent); return policy?.dispose() })
336
+ : guard('agent provider', () => agent.ctx.skills.registerProvider(() => disabledProvider()))) || (() => {})
337
+ agentViews.set(agent, { dispose: () => {
338
+ const pending = dispose()
339
+ const preset = presetProviders.get(service)
340
+ if (preset && --preset.users === 0) { preset.dispose(); presetProviders.delete(service) }
341
+ return pending
342
+ }, registry: serviceFor, lookup: () => ({ scope: agent, cwd: ctx.get?.('workingDirectory')?.get(agent.session) ?? agent.session?.header?.cwd }) })
343
+ }
344
+ const unbind = (agent) => { const view = agentViews.get(agent); agentViews.delete(agent); return view?.dispose() }
345
+ const offCreated = ctx.on('agent/created', ({ agent }) => bind(agent))
346
+ const offDisposed = ctx.on('agent/disposed', ({ agent }) => unbind(agent))
347
+ const offPreset = ctx.on('agent-preset/selected', async id => {
348
+ const agent = ctx.agents.get(id)
349
+ if (agent) { await unbind(agent); bind(agent) }
350
+ })
351
+ for (const agent of ctx.agents.list()) bind(agent)
352
+ invalidateAll()
353
+ catalogChanged?.()
354
+ return () => {
355
+ offCreated(); offDisposed(); offPreset()
356
+ const pending = [...agentViews.keys()].map(unbind)
357
+ for (const policy of scopePolicies.values()) pending.push(policy.dispose())
358
+ scopePolicies.clear(); createPolicyScope = null
359
+ for (const { dispose } of presetProviders.values()) dispose()
360
+ presetProviders.clear()
361
+ return Promise.all(pending)
362
+ }
363
+ }
364
+ return { attach, attachAgents, entries, list, toggle, detail, resource, refresh }
365
+ }
package/assets/hero.png DELETED
Binary file