universal-plugin-hub 1.0.30 → 1.0.45

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/skills.js CHANGED
@@ -3,7 +3,8 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, watch }
3
3
  import { homedir } from 'node:os'
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
5
5
  import { load as parseYaml } from 'js-yaml'
6
- import { readState, writeState } from './store.js'
6
+ import { readState, writeState, dshSkillsDir, installedDir } from './store.js'
7
+ import { isUploadedSkillTarget, uploadedSkillRecord } from './skill-uploads.js'
7
8
  import { formatDisplayName } from './parser.js'
8
9
 
9
10
  const PROVIDER = 'universal-plugin-hub-skills'
@@ -94,7 +95,19 @@ function readSkill(file, root, isNested) {
94
95
  }
95
96
  }
96
97
 
97
- export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')) {
98
+ function mergeSkillLocations(entries) {
99
+ const identical = new Map(), merged = []
100
+ for (const item of entries) {
101
+ const key = JSON.stringify([item.name, item.metadata, item.content.replace(/\r\n/g, '\n')])
102
+ const existing = !item.error && identical.get(key)
103
+ const location = { id: item.id, path: item.path, relativePath: item.relativePath }
104
+ if (existing) existing.locations.push(location)
105
+ else { item.locations = [location]; merged.push(item); if (!item.error) identical.set(key, item) }
106
+ }
107
+ return merged
108
+ }
109
+
110
+ function discoverRootSkills(root) {
98
111
  const entries = [], seen = new Set()
99
112
  let children
100
113
  try { children = readdirSync(root, { withFileTypes: true }) } catch { return entries }
@@ -114,25 +127,158 @@ export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(h
114
127
  if (!seen.has(id)) { seen.add(id); entries.push(readSkill(file, root, false)) }
115
128
  } catch {}
116
129
  }
117
- // Identical direct entries share one card and one provider candidate.
130
+ return entries
131
+ }
132
+
133
+ export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')) {
134
+ const entries = discoverRootSkills(root)
118
135
  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
- }
136
+ const merged = mergeSkillLocations(entries)
127
137
  const counts = new Map()
128
138
  for (const item of merged) counts.set(item.name, (counts.get(item.name) || 0) + 1)
129
139
  for (const item of merged) item.duplicate = counts.get(item.name) > 1
130
140
  return merged.sort((a, b) => a.name.localeCompare(b.name))
131
141
  }
132
142
 
143
+ function defaultSkillRoots() {
144
+ return [
145
+ { path: dshSkillsDir(), source: 'user-dsh', rank: 400 },
146
+ { path: join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills'), source: 'user-agents', rank: 500 },
147
+ ]
148
+ }
149
+
150
+ /**
151
+ * Keys must be produced and consumed by this one function: realpathSync returns
152
+ * the mixed-case display path on Windows, so a raw canonical lookups never
153
+ * matches a lowercased key.
154
+ */
155
+ function pathKey(path) {
156
+ const value = canonical(path)
157
+ return process.platform === 'win32' ? value.toLowerCase() : value
158
+ }
159
+
160
+ function readText(path) {
161
+ try { return readFileSync(path, 'utf8') } catch { return null }
162
+ }
163
+
164
+ /**
165
+ * Skills the hub mirrored into $DSH_HOME/skills on behalf of an installed
166
+ * plugin. They belong to the plugin's own row and stay out of the Skills tab.
167
+ *
168
+ * Ownership is decided by content, not by name: the mirror is a byte copy of
169
+ * the plugin's SKILL.md, so a same-named directory holding anything else is the
170
+ * user's own skill (or a direct upload) and must stay visible. A disabled
171
+ * plugin leaves no mirror behind, and a leftover one still matches its source,
172
+ * so the check covers both states without reading `enabled`.
173
+ */
174
+ function pluginOwnedSkillPaths() {
175
+ const paths = new Set()
176
+ for (const plugin of readState().plugins || []) {
177
+ const root = join(installedDir(plugin.name), 'skills')
178
+ let children
179
+ try { children = readdirSync(root, { withFileTypes: true }) } catch { continue }
180
+ for (const child of children) {
181
+ if (!child.isDirectory() && !child.isSymbolicLink()) continue
182
+ const source = readText(join(root, child.name, 'SKILL.md'))
183
+ if (source === null) continue
184
+ const target = join(dshSkillsDir(), child.name)
185
+ if (isUploadedSkillTarget(target)) continue
186
+ if (readText(join(target, 'SKILL.md')) !== source) continue
187
+ paths.add(pathKey(target))
188
+ }
189
+ }
190
+ return paths
191
+ }
192
+
193
+ /**
194
+ * Merge the native user roots.
195
+ *
196
+ * Within one root the long-standing rule stands: identical copies share a card
197
+ * and same-name/different-content skills stay visible as separate cards (the
198
+ * detail view then reports which one DSH actually resolved). Across roots a
199
+ * lower-ranked root never adds a second card for a name the higher root already
200
+ * provides — its file locations are folded into the surviving cards instead, so
201
+ * one switch writes every copy and a hidden copy cannot come back later with a
202
+ * stale state.
203
+ */
204
+ export function discoverSkillsFromRoots(roots = defaultSkillRoots()) {
205
+ const sorted = [...roots].filter(root => root?.path).sort((a, b) => (a.rank || 300) - (b.rank || 300))
206
+ const pluginPaths = pluginOwnedSkillPaths()
207
+ const claimed = new Map()
208
+ for (const root of sorted) {
209
+ const items = discoverRootSkills(root.path)
210
+ // A plugin mirror is dropped before merging, not after: it must not claim
211
+ // its name at the higher user-dsh rank and take the user's own copy in
212
+ // another root down with it.
213
+ .filter(item => !pluginPaths.has(pathKey(item.directory)))
214
+ .map(item => {
215
+ item.skillSource = root.source
216
+ item.rank = root.rank
217
+ return item
218
+ })
219
+ for (const item of mergeSkillLocations(items)) {
220
+ const current = claimed.get(item.name)
221
+ if (!current) {
222
+ claimed.set(item.name, { rank: root.rank, cards: [item], shadowed: [] })
223
+ } else if (root.rank === current.rank) {
224
+ current.cards.push(item)
225
+ } else if (root.rank < current.rank) {
226
+ for (const card of current.cards) current.shadowed.push(...card.locations)
227
+ current.rank = root.rank
228
+ current.cards = [item]
229
+ } else {
230
+ current.shadowed.push(...item.locations)
231
+ }
232
+ }
233
+ }
234
+ const result = []
235
+ for (const { cards, shadowed } of claimed.values()) {
236
+ for (const card of cards) {
237
+ const ids = new Set(card.locations.map(location => location.id))
238
+ for (const location of shadowed) {
239
+ if (!ids.has(location.id)) { ids.add(location.id); card.locations.push(location) }
240
+ }
241
+ card.duplicate = cards.length > 1
242
+ card.uploaded = card.skillSource === 'user-dsh' && !!uploadedSkillRecord(card.name)
243
+ result.push(card)
244
+ }
245
+ }
246
+ return result.sort((a, b) => a.name.localeCompare(b.name))
247
+ }
248
+
133
249
  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
250
+ const customRoot = typeof root === 'string' ? root : null
251
+ const explicitRoots = Array.isArray(root) ? root : null
252
+ // `customSkillDirs` / `bundledSkillDir` are evaluated JS expressions in the
253
+ // profile patch, so the paths are not readable as text. DSH has already
254
+ // resolved them into its catalog by the time we attach; collect those
255
+ // directories here instead of parsing configuration ourselves.
256
+ let registryRoots = null
257
+ const baseRoots = () => explicitRoots
258
+ || (customRoot
259
+ // An explicit test root replaces the defaults (legacy single-root tests).
260
+ // It stands in for the native user-agents root, so it keeps that rank and
261
+ // the fallback candidate lands one step below it, as it always has.
262
+ // In production this string is the native user-agents root, and the
263
+ // user-dsh root must still be scanned alongside it.
264
+ ? (customRoot === join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')
265
+ ? defaultSkillRoots()
266
+ : [{ path: customRoot, source: 'user-agents', rank: 500 }])
267
+ : defaultSkillRoots())
268
+ const roots = () => {
269
+ if (explicitRoots) return explicitRoots
270
+ const known = baseRoots()
271
+ const seen = new Set(known.map(root => canonical(root.path).toLowerCase()))
272
+ const extra = []
273
+ for (const root of registryRoots || []) {
274
+ const key = canonical(root.path).toLowerCase()
275
+ if (seen.has(key)) continue
276
+ seen.add(key)
277
+ extra.push(root)
278
+ }
279
+ return [...known, ...extra]
280
+ }
281
+ let cache = null, registry = null, invalidate = null, catalogChanged = null, watchers = [], watchedRoots = new Set(), watchTimer = null, toggling = false
136
282
  const agentViews = new Map()
137
283
  const scopePolicies = new Map(), presetProviders = new Map()
138
284
  let createPolicyScope = null
@@ -178,7 +324,7 @@ export function createSkillsManager(root) {
178
324
  return pending
179
325
  }
180
326
  const scan = (force = false) => {
181
- if (force || !cache) cache = discoverSkills(root)
327
+ if (force || !cache) cache = discoverSkillsFromRoots(roots())
182
328
  return cache
183
329
  }
184
330
  const disabled = () => readState().disabledLocalSkills || {}
@@ -195,9 +341,12 @@ export function createSkillsManager(root) {
195
341
  function candidate(item, isDisabled) {
196
342
  return {
197
343
  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).
344
+ // One step below the native provider of the same root, so the native
345
+ // filesystem provider still wins whenever it discovers the skill and this
346
+ // stays a fallback. Ordering between roots is preserved: a user-dsh copy
347
+ // (401) beats the user-agents fallback (501), matching the .dsh priority.
199
348
  // An explicit off choice must precede every native filesystem rank.
200
- provider: PROVIDER, source: 'user-agents', rank: isDisabled ? 99 : 501,
349
+ provider: PROVIDER, source: item.skillSource || 'user-agents', rank: isDisabled ? 99 : (item.rank || 500) + 1,
201
350
  path: item.path, resourceBase: { kind: 'directory', path: item.directory }, locator: item.id,
202
351
  }
203
352
  }
@@ -213,7 +362,7 @@ export function createSkillsManager(root) {
213
362
  async get(entry) {
214
363
  const item = scan().find(s => s.id === entry.locator)
215
364
  if (!item || item.error) return undefined
216
- const fresh = readSkill(item.path, root, item.nested)
365
+ const fresh = readSkill(item.path, dirname(item.path), item.nested)
217
366
  if (fresh.error || fresh.name !== item.name) return undefined
218
367
  const { rank, locator, ...summary } = candidate(fresh, isDisabled(item))
219
368
  return { ...summary, content: fresh.content, metadata: fresh.metadata.metadata }
@@ -318,24 +467,58 @@ export function createSkillsManager(root) {
318
467
  if (data.includes(0)) throw new Error('该资源不是文本文件')
319
468
  return data.toString('utf8')
320
469
  }
470
+ // Only the configured custom roots (rank 300) are scanned on top of the two
471
+ // native user roots. Bundled skills (rank 600) belong to DSH itself and stay
472
+ // out of the Skills tab.
473
+ const CUSTOM_SOURCES = new Set(['custom'])
474
+ const CUSTOM_RANKS = { custom: 300 }
475
+ async function observeRegistryRoots() {
476
+ if (!registry || explicitRoots || customRoot) return
477
+ let catalog
478
+ try { catalog = await registry.list() } catch { return }
479
+ const roots = new Map()
480
+ for (const entry of catalog) {
481
+ if (!CUSTOM_SOURCES.has(entry.source) || typeof entry.path !== 'string') continue
482
+ // A directory bundle is <root>/<name>/SKILL.md, a flat skill <root>/<name>.md.
483
+ // Walk back to the scanned root, never to the skill directory itself.
484
+ const directory = /^skill\.md$/i.test(basename(entry.path)) ? dirname(dirname(entry.path)) : dirname(entry.path)
485
+ if (roots.has(directory)) continue
486
+ roots.set(directory, { path: directory, source: entry.source, rank: CUSTOM_RANKS[entry.source] || 300 })
487
+ }
488
+ registryRoots = [...roots.values()]
489
+ // The custom directories only become known here, after the catalog is read,
490
+ // so their watchers have to be installed now rather than in attach().
491
+ watchRoots()
492
+ }
493
+ /** Watch every scanned root that does not have a watcher yet, once each. */
494
+ function watchRoots() {
495
+ for (const root of roots()) {
496
+ const key = canonical(root.path).toLowerCase()
497
+ if (watchedRoots.has(key)) continue
498
+ watchedRoots.add(key)
499
+ try {
500
+ const watcher = watch(root.path, { recursive: true }, (event, filename) => {
501
+ if (filename) {
502
+ const parts = String(filename).split(/[\\/]/)
503
+ if (parts.length > 2 || (parts.length === 2 && !/^skill\.md$/i.test(parts[1]))) return
504
+ if (event === 'change' && parts.length === 1 && !/\.md$/i.test(parts[0])) return
505
+ }
506
+ clearTimeout(watchTimer)
507
+ watchTimer = setTimeout(() => { cache = null; invalidateAll(); catalogChanged?.() }, 150)
508
+ watchTimer.unref?.()
509
+ })
510
+ watcher.on('error', () => {})
511
+ watchers.push(watcher)
512
+ } catch {}
513
+ }
514
+ }
321
515
  function attach(service, onCatalogChanged = null) {
322
516
  registry = service
323
517
  catalogChanged = onCatalogChanged
324
518
  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() }
519
+ watchRoots()
520
+ void observeRegistryRoots()
521
+ return () => { clearTimeout(watchTimer); for (const watcher of watchers) watcher.close(); watchers = []; watchedRoots.clear(); registry = null; invalidate = null; catalogChanged = null; dispose() }
339
522
  }
340
523
  function attachAgents(ctx, createScope = null) {
341
524
  createPolicyScope = createScope
package/src/store.js CHANGED
@@ -69,6 +69,11 @@ export function installedDir(name) {
69
69
  return join(marketRoot(), 'installed', name)
70
70
  }
71
71
 
72
+ /** Original copies of skills imported directly into the Skills tab. */
73
+ export function uploadedSkillsDir() {
74
+ return join(marketRoot(), 'uploaded')
75
+ }
76
+
72
77
  /** Default state: the built-in Anthropic source. */
73
78
  export function defaultState() {
74
79
  return {