universal-plugin-hub 1.0.35 → 1.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/market.js CHANGED
@@ -8,7 +8,7 @@
8
8
  import { execFile } from 'node:child_process'
9
9
  import { existsSync, mkdirSync, readFileSync } from 'node:fs'
10
10
  import { join, resolve, relative, isAbsolute } from 'node:path'
11
- import { sourceCacheDir, safeRmDir } from './store.js'
11
+ import { sourceCacheDir, safeRmDir, readState } from './store.js'
12
12
 
13
13
  const SEGMENT_RE = /^[a-z0-9][a-z0-9._-]*$/i
14
14
 
@@ -100,7 +100,7 @@ function runGit(args, cwd) {
100
100
  export async function ensureSourceCloned(sourceId, url) {
101
101
  safeSegment(sourceId, 'source id')
102
102
  const dir = sourceCacheDir(sourceId)
103
- if (sourceId === 'local') {
103
+ if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(url || ''))) {
104
104
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
105
105
  return dir
106
106
  }
@@ -138,7 +138,7 @@ export async function ensureSourceCloned(sourceId, url) {
138
138
  /** git pull in a source cache dir (waits for any in-flight clone of the same source). */
139
139
  export async function pullSource(sourceId) {
140
140
  safeSegment(sourceId, 'source id')
141
- if (sourceId === 'local') return
141
+ if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(readState().sources.find(source => source.id === sourceId)?.url || ''))) return
142
142
  const dir = sourceCacheDir(sourceId)
143
143
  const inFlight = GIT_LOCKS.get(`src:${sourceId}`)
144
144
  if (inFlight) {
package/src/parser.js CHANGED
@@ -66,6 +66,23 @@ function extractMdDescription(text) {
66
66
  return ''
67
67
  }
68
68
 
69
+ // Presentation only: read Codex's card copy without changing which manifest
70
+ // owns the plugin's description, components, or installation behavior.
71
+ function readPluginShortDescription(dir) {
72
+ if (!dir) return ''
73
+ const text = value => typeof value === 'string' ? value.trim() : ''
74
+ try {
75
+ const root = JSON.parse(readFileSync(join(dir, 'plugin.json'), 'utf8'))
76
+ const openai = root?.extensions?.['com.openai']
77
+ // An inline OpenAI extension replaces the compatibility overlay entirely.
78
+ if (openai && typeof openai === 'object' && !Array.isArray(openai)) return text(openai.interface?.shortDescription)
79
+ } catch {}
80
+ try {
81
+ const codex = JSON.parse(readFileSync(join(dir, '.codex-plugin', 'plugin.json'), 'utf8'))
82
+ return text(codex?.interface?.shortDescription)
83
+ } catch { return '' }
84
+ }
85
+
69
86
  function normalizeRow(row, sourceId, dir) {
70
87
  if (!row) return null
71
88
  const name = typeof row.name === 'string' ? row.name : (typeof row.identifier === 'string' ? row.identifier : '')
@@ -81,6 +98,8 @@ function normalizeRow(row, sourceId, dir) {
81
98
  const description = typeof row.description === 'string'
82
99
  ? row.description
83
100
  : (row.interface?.shortDescription || meta.description || '')
101
+ const shortDescription = readPluginShortDescription(dir)
102
+ || (typeof row.interface?.shortDescription === 'string' ? row.interface.shortDescription.trim() : '')
84
103
 
85
104
  const source = row.source?.source === 'local' ? row.source.path : (row.source || './')
86
105
  if (row.source?.source === 'local' && (typeof source !== 'string' || !source.startsWith('./'))) return null
@@ -91,6 +110,7 @@ function normalizeRow(row, sourceId, dir) {
91
110
  name: cleanName,
92
111
  displayName,
93
112
  description,
113
+ ...(shortDescription ? { shortDescription } : {}),
94
114
  author: typeof author === 'string' ? author : (meta.author || undefined),
95
115
  version: typeof row.version === 'string' ? row.version : (meta.version || undefined),
96
116
  category: typeof row.category === 'string' ? row.category : (meta.category || undefined),
package/src/routes.js CHANGED
@@ -17,7 +17,8 @@ import {
17
17
  toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
18
18
  fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
19
19
  } from './install.js'
20
- import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
20
+ import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, saveUploadedZip } from './local.js'
21
+ import { uninstallUploadedSkill, uploadedSkillRecord } from './skill-uploads.js'
21
22
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
22
23
  import { remoteConfigFromEntry } from './oauth-config.js'
23
24
  import { scheduledResult } from './runtime.js'
@@ -129,7 +130,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
129
130
  if (typeof body.enabled !== 'boolean') throw new Error('无效的开关状态')
130
131
  return sendJson(res, 200, await skills.toggle(body.id, body.enabled))
131
132
  }
132
- if (path === '/skills/detail' && method === 'GET' && skills) return sendJson(res, 200, { skill: skills.detail(url.searchParams.get('id'), false) })
133
+ if (path === '/skills/detail' && method === 'GET' && skills) {
134
+ const skill = skills.detail(url.searchParams.get('id'), false)
135
+ return sendJson(res, 200, { skill: { ...skill, uploaded: !!uploadedSkillRecord(skill.name) } })
136
+ }
137
+ if (path === '/skills/uninstall' && method === 'POST' && skills) {
138
+ requireSameOrigin(req)
139
+ const body = await readJsonBody(req)
140
+ const name = String(body.name || '')
141
+ if (!uploadedSkillRecord(name)) throw new Error('只能卸载通过本插件上传的 Skill')
142
+ uninstallUploadedSkill(name)
143
+ skills.refresh()
144
+ return sendJson(res, 200, { ok: true, skills: await skills.list() })
145
+ }
133
146
  if (path === '/skills/resource' && method === 'GET' && skills) return sendJson(res, 200, { content: skills.resource(url.searchParams.get('id'), url.searchParams.get('path')) })
134
147
  if (path === '/skills/icon' && method === 'GET' && skills) {
135
148
  try {
@@ -224,6 +237,26 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
224
237
  return sendJson(res, 200, result)
225
238
  }
226
239
 
240
+ // Pure skill packages bypass the plugin pipeline: upload, private copy,
241
+ // junction into $DSH_HOME/skills, then a hot refresh of the Skills tab.
242
+ if (method === 'POST' && path === '/skills/import') {
243
+ requireSameOrigin(req)
244
+ const body = await readJsonBody(req, 30_000_000)
245
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
246
+ const result = await importLocalSkills(target, { overwrite: body.overwrite === true })
247
+ skills?.refresh()
248
+ return sendJson(res, 200, result)
249
+ }
250
+
251
+ // An uploaded marketplace becomes its own plugin source tab.
252
+ if (method === 'POST' && path === '/marketplaces/import') {
253
+ requireSameOrigin(req)
254
+ const body = await readJsonBody(req, 30_000_000)
255
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
256
+ const result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true })
257
+ return sendJson(res, 200, result)
258
+ }
259
+
227
260
  if (method === 'POST' && path === '/sources') {
228
261
  requireSameOrigin(req)
229
262
  const body = await readJsonBody(req)
@@ -468,7 +501,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
468
501
  // ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
469
502
  if (method === 'GET' && path.startsWith('/mcps/') && path.endsWith('/tools')) {
470
503
  const name = safeSegment(normalizeMcpName(path.slice('/mcps/'.length, -'/tools'.length)), 'MCP 名称')
471
- const result = await fetchConnectorTools('user-mcp', name)
504
+ const result = await fetchConnectorTools('user-mcp', name, url.searchParams.get('fresh') === '1')
472
505
  return sendJson(res, 200, result)
473
506
  }
474
507
 
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Direct skill imports live in the hub's private tree and are exposed through
3
+ * DSH's native user-dsh root. Directory bundles use junctions on Windows (and
4
+ * directory symlinks elsewhere); a bare SKILL.md is copied as <name>.md.
5
+ */
6
+ import { cpSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync } from 'node:fs'
7
+ import { createHash } from 'node:crypto'
8
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
9
+ import { dshSkillsDir, readState, safeRmDir, uploadedSkillsDir, writeState } from './store.js'
10
+
11
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
12
+
13
+ function samePath(a, b) {
14
+ if (!a || !b) return false
15
+ const left = resolve(a), right = resolve(b)
16
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
17
+ }
18
+
19
+ /**
20
+ * The switch state is keyed by this hash (see skillId in skills.js), and the
21
+ * junction means the discovered path resolves to the private original, so both
22
+ * ends of the link have to be cleared.
23
+ */
24
+ function skillLocationId(path) {
25
+ let value
26
+ try { value = realpathSync.native(path) } catch { value = resolve(path) }
27
+ if (process.platform === 'win32') value = value.toLowerCase()
28
+ return createHash('sha256').update(value).digest('hex')
29
+ }
30
+
31
+ function contains(root, child) {
32
+ const rel = relative(resolve(root), resolve(child))
33
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`))
34
+ }
35
+
36
+ function recordPaths(name, kind) {
37
+ if (!SKILL_NAME.test(name)) throw new Error('Skill 名称必须符合小写连字符格式')
38
+ return {
39
+ sourceDir: join(uploadedSkillsDir(), name),
40
+ target: join(dshSkillsDir(), kind === 'file' ? `${name}.md` : name),
41
+ }
42
+ }
43
+
44
+ export function isUploadedSkillTarget(path) {
45
+ return (readState().uploadedSkills || []).some(record => samePath(record?.target, path))
46
+ }
47
+
48
+ export function uploadedSkillRecord(name) {
49
+ return (readState().uploadedSkills || []).find(record => record?.name === name) || null
50
+ }
51
+
52
+ function pathExists(path) {
53
+ try { lstatSync(path); return true } catch { return false }
54
+ }
55
+
56
+ function removeTarget(record) {
57
+ const { target } = recordPaths(record.name, record.kind)
58
+ if (!pathExists(target)) return
59
+ const stat = lstatSync(target)
60
+ if (stat.isSymbolicLink()) {
61
+ // Remove the link itself. Never use safeRmDir's attrib fallback here:
62
+ // its recursive wildcard could modify the private original's files.
63
+ rmSync(target, { recursive: true, force: true })
64
+ } else if (stat.isDirectory()) safeRmDir(target)
65
+ else rmSync(target, { force: true })
66
+ }
67
+
68
+ function expose(record) {
69
+ const { sourceDir, target } = recordPaths(record.name, record.kind)
70
+ mkdirSync(dirname(target), { recursive: true })
71
+ if (record.kind === 'file') copyFileSync(join(sourceDir, 'SKILL.md'), target)
72
+ else symlinkSync(sourceDir, target, process.platform === 'win32' ? 'junction' : 'dir')
73
+ }
74
+
75
+ function rootSkillFile(dir) {
76
+ return ['SKILL.md', 'skill.md'].map(file => join(dir, file)).find(existsSync)
77
+ }
78
+
79
+ function validateEntry(entry) {
80
+ const name = String(entry?.row?.name || '')
81
+ if (!SKILL_NAME.test(name)) throw new Error(`Skill「${name || basename(entry?.dir || '')}」的 name 必须是小写连字符格式`)
82
+ // A flat `<name>.md` skill keeps its manifest in entry.file beside the other
83
+ // skills of the same folder, so the shared folder has no SKILL.md of its own.
84
+ const file = entry.file || rootSkillFile(entry.dir)
85
+ if (!file) throw new Error(`Skill「${name}」缺少 SKILL.md`)
86
+ const raw = readFileSyncSafe(file)
87
+ if (!/^description\s*:/m.test(raw)) throw new Error(`Skill「${name}」缺少 description`)
88
+ return { name, file }
89
+ }
90
+
91
+ function readFileSyncSafe(file) {
92
+ try { return readFileSync(file, 'utf8') } catch { return '' }
93
+ }
94
+
95
+ /** Every rejection this import can raise, so a batch can be checked up front. */
96
+ function preflight(entry, { overwrite, singleFile, fileDir = null }) {
97
+ const { name, file } = validateEntry(entry)
98
+ const kind = singleFile ? 'file' : 'directory'
99
+ const paths = recordPaths(name, kind)
100
+ const previous = uploadedSkillRecord(name)
101
+ if (previous && !overwrite) throw new Error(`已存在同名 Skill「${name}」`)
102
+ if (!previous && pathExists(paths.target)) {
103
+ throw new Error(`DSH Skills 目录已存在「${name}」,为避免覆盖你的文件,本次未导入`)
104
+ }
105
+ const source = resolve(entry.dir)
106
+ if (contains(uploadedSkillsDir(), source) || contains(source, uploadedSkillsDir())) {
107
+ throw new Error('导入源与技能存储目录重叠,请从独立文件夹导入')
108
+ }
109
+ return { name, file, kind, paths, previous, source }
110
+ }
111
+
112
+ function installOne(entry, options) {
113
+ const { name, file, kind, paths, previous, source } = preflight(entry, options)
114
+ // A bare SKILL.md file, or a flat `<name>.md` sitting beside other skills in
115
+ // one folder, has no assets to carry: only the manifest is copied.
116
+ const manifestOnly = options.singleFile || options.fileDir
117
+ mkdirSync(uploadedSkillsDir(), { recursive: true })
118
+ const staging = join(uploadedSkillsDir(), `.${name}-${process.pid}-${Date.now()}.tmp`)
119
+ let staged = false, installed = false, exposed = false
120
+ try {
121
+ if (manifestOnly) {
122
+ mkdirSync(staging, { recursive: true })
123
+ copyFileSync(file, join(staging, 'SKILL.md'))
124
+ } else {
125
+ cpSync(source, staging, { recursive: true, force: true })
126
+ const stagedRoot = join(staging, 'SKILL.md')
127
+ if (!existsSync(stagedRoot)) copyFileSync(join(staging, basename(file)), stagedRoot)
128
+ }
129
+ staged = true
130
+
131
+ if (previous) {
132
+ removeTarget(previous)
133
+ safeRmDir(recordPaths(previous.name, previous.kind).sourceDir)
134
+ }
135
+ renameSync(staging, paths.sourceDir)
136
+ staged = false
137
+ installed = true
138
+ expose({ name, kind })
139
+ exposed = true
140
+
141
+ const state = readState()
142
+ state.uploadedSkills = [...(state.uploadedSkills || []).filter(item => item.name !== name),
143
+ { name, kind, ...paths, uploadedAt: previous?.uploadedAt || Date.now(), updatedAt: Date.now() }]
144
+ writeState(state)
145
+ return { name, kind }
146
+ } catch (error) {
147
+ // Roll back only what this attempt created; never delete an old original
148
+ // that was already removed before the failure (its target is gone too, so
149
+ // the previous entry stays recorded and can be restored from the source).
150
+ if (exposed) { try { removeTarget({ name, kind }) } catch {} }
151
+ if (installed) { try { safeRmDir(paths.sourceDir) } catch {} }
152
+ throw error
153
+ } finally {
154
+ if (staged) { try { safeRmDir(staging) } catch {} }
155
+ }
156
+ }
157
+
158
+ export function installUploadedSkills(entries, { overwrite = false, singleFile = false } = {}) {
159
+ if (!Array.isArray(entries) || entries.length === 0) throw new Error('未检测到可上传的 Skill')
160
+ // A batch must not half-install: every rejection this import can predict is
161
+ // raised before the first file moves, so a duplicate name in the middle of
162
+ // the package cannot leave the earlier skills live while the UI reports a
163
+ // failure.
164
+ for (const entry of entries) preflight(entry, { overwrite, singleFile, fileDir: entry.singleFile })
165
+ const installed = []
166
+ try {
167
+ for (const entry of entries) {
168
+ const replaced = !!uploadedSkillRecord(String(entry?.row?.name || ''))
169
+ installed.push({ ...installOne(entry, { overwrite, singleFile, fileDir: entry.singleFile }), replaced })
170
+ }
171
+ return installed.map(({ replaced, ...skill }) => skill)
172
+ } catch (error) {
173
+ // Only a failure preflight cannot see (disk, permissions) gets here. Undo
174
+ // the entries this batch created; an overwrite has already replaced its
175
+ // original, so deleting it would be worse than leaving the new copy.
176
+ for (const skill of installed) {
177
+ if (skill.replaced) continue
178
+ try { uninstallUploadedSkill(skill.name) } catch {}
179
+ }
180
+ throw error
181
+ }
182
+ }
183
+
184
+ export function uninstallUploadedSkill(name) {
185
+ const record = uploadedSkillRecord(name)
186
+ if (!record) throw new Error('只能卸载通过本插件上传的 Skill')
187
+ const { sourceDir, target } = recordPaths(record.name, record.kind)
188
+ // The switch key hashes the manifest file, not the folder.
189
+ const removal = (record.kind === 'file' ? [target, join(sourceDir, 'SKILL.md')] : [join(target, 'SKILL.md'), join(sourceDir, 'SKILL.md')])
190
+ .map(file => skillLocationId(file))
191
+ removeTarget(record)
192
+ safeRmDir(recordPaths(record.name, record.kind).sourceDir)
193
+ const state = readState()
194
+ state.uploadedSkills = (state.uploadedSkills || []).filter(item => item.name !== name)
195
+ // The id hashes the canonical path, and a re-upload recreates that same path,
196
+ // so a stale "off" left here would switch the fresh copy off on arrival.
197
+ if (state.disabledLocalSkills) {
198
+ for (const id of removal) delete state.disabledLocalSkills[id]
199
+ }
200
+ writeState(state)
201
+ return { ok: true, name }
202
+ }
203
+
204
+ /** Repair links/copies after a restart without rewriting the originals. */
205
+ export function restoreUploadedSkills() {
206
+ const restored = []
207
+ for (const record of readState().uploadedSkills || []) {
208
+ try {
209
+ const paths = recordPaths(record.name, record.kind)
210
+ if (!existsSync(join(paths.sourceDir, 'SKILL.md'))) continue
211
+ if (!pathExists(paths.target)) {
212
+ expose(record)
213
+ restored.push(record.name)
214
+ }
215
+ } catch {}
216
+ }
217
+ return restored
218
+ }
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 {