universal-plugin-hub 1.0.35 → 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/local.js CHANGED
@@ -1,16 +1,34 @@
1
- import { existsSync, readdirSync, statSync, cpSync, mkdirSync, writeFileSync, mkdtempSync } from 'node:fs'
1
+ import { existsSync, readdirSync, statSync, cpSync, copyFileSync, mkdirSync, writeFileSync, mkdtempSync, readFileSync } from 'node:fs'
2
2
  import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { execFile } from 'node:child_process'
5
5
  import { promisify } from 'node:util'
6
- import { sourceCacheDir, readState, writeState, safeRmDir } from './store.js'
7
- import { safeSegment } from './market.js'
8
- import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache } from './parser.js'
6
+ import { load as parseYaml } from 'js-yaml'
7
+ import { sourceCacheDir, readState, writeState, safeRmDir, slugify } from './store.js'
8
+ import { safeSegment, pluginPath } from './market.js'
9
+ import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache, formatDisplayName } from './parser.js'
10
+ import { installUploadedSkills } from './skill-uploads.js'
9
11
 
10
12
  const execFileAsync = promisify(execFile)
11
13
 
12
14
  const TEMP_ROOT = () => join(sourceCacheDir('local'), '.temp')
13
15
 
16
+ /** True when `child` is `root` itself or sits inside it. */
17
+ function containsPath(root, child) {
18
+ const rel = relative(resolve(root), resolve(child))
19
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..\\') && !rel.startsWith('../'))
20
+ }
21
+
22
+ /** Copy a directory's entries into an existing directory, not into a subdir of it. */
23
+ function copyTreeContents(from, to) {
24
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
25
+ const source = join(from, entry.name)
26
+ const target = join(to, entry.name)
27
+ if (entry.isDirectory()) cpSync(source, target, { recursive: true, force: true })
28
+ else if (entry.isFile()) copyFileSync(source, target)
29
+ }
30
+ }
31
+
14
32
  /** Delete stale .temp artifacts (uploaded zips, inspect extraction dirs) older than 1h. */
15
33
  function sweepTemp() {
16
34
  const root = TEMP_ROOT()
@@ -73,6 +91,79 @@ export function resolvePluginDir(rootDir) {
73
91
  return null
74
92
  }
75
93
 
94
+ function skillFileMetadata(file) {
95
+ try {
96
+ const raw = readFileSync(file, 'utf8').replace(/^/, '')
97
+ const match = raw.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/)
98
+ const meta = match ? parseYaml(match[1]) : null
99
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return null
100
+ if (typeof meta.name !== 'string' || typeof meta.description !== 'string' || !meta.description.trim()) return null
101
+ return meta
102
+ } catch { return null }
103
+ }
104
+
105
+ function directSkillEntry(dir, fallbackName, file = null) {
106
+ const manifest = file ? skillFileMetadata(file) : skillFileMetadata(['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync))
107
+ if (!manifest) return null
108
+ const name = manifest.name.trim()
109
+ if (!name) return null
110
+ return {
111
+ dir,
112
+ file: file || undefined,
113
+ singleFile: !!file,
114
+ row: {
115
+ id: `skills/${name}`, sourceId: 'skills-local', name,
116
+ displayName: typeof manifest.displayName === 'string' ? manifest.displayName : formatDisplayName(name),
117
+ description: manifest.description.trim(), version: '1.0.0', source: './',
118
+ },
119
+ }
120
+ }
121
+
122
+ /** A pure skill package is a root skill or one level of direct skill entries. */
123
+ function collectDirectSkills(dir, fallbackName) {
124
+ const rootFile = ['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync)
125
+ if (rootFile) {
126
+ const entry = directSkillEntry(dir, fallbackName)
127
+ return entry ? [entry] : []
128
+ }
129
+ const root = existsSync(join(dir, 'skills')) ? join(dir, 'skills') : dir
130
+ const entries = []
131
+ try {
132
+ for (const child of readdirSync(root, { withFileTypes: true })) {
133
+ if (EXCLUDED_UPLOAD_DIRS.has(child.name) || child.name.startsWith('.')) continue
134
+ const path = join(root, child.name)
135
+ if (child.isDirectory()) {
136
+ const entry = directSkillEntry(path, child.name)
137
+ if (entry) entries.push(entry)
138
+ } else if (child.isFile() && /\.md$/i.test(child.name)) {
139
+ const entry = directSkillEntry(root, child.name.replace(/\.md$/i, ''), path)
140
+ if (entry) entries.push(entry)
141
+ }
142
+ }
143
+ } catch {}
144
+ return entries
145
+ }
146
+
147
+ const EXCLUDED_UPLOAD_DIRS = new Set(['node_modules', '__pycache__', 'agents', 'commands', 'hooks', 'docs', 'assets'])
148
+
149
+ function isPureSkillPackage(dir) {
150
+ return ![
151
+ '.claude-plugin/plugin.json', '.codex-plugin/plugin.json', 'plugin.json', 'package.json',
152
+ 'mcp.json', '.mcp.json', 'server.json', 'agents', 'commands',
153
+ ].some(path => existsSync(join(dir, path)))
154
+ }
155
+
156
+ function marketSourceName(dir, fallbackName) {
157
+ for (const path of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
158
+ try {
159
+ const raw = JSON.parse(readFileSync(join(dir, path), 'utf8'))
160
+ if (typeof raw.name === 'string' && raw.name.trim()) return raw.name.trim()
161
+ if (typeof raw.title === 'string' && raw.title.trim()) return raw.title.trim()
162
+ } catch {}
163
+ }
164
+ return formatDisplayName(fallbackName) || '本地市场'
165
+ }
166
+
76
167
  export async function inspectLocalPlugin(rawPath) {
77
168
  let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
78
169
  if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
@@ -109,9 +200,16 @@ export async function inspectLocalPlugin(rawPath) {
109
200
 
110
201
  const rawFallbackName = (isZip && effectiveDir === tempExtractDir ? basename(targetPath).replace(/\.(zip|tgz|tar\.gz)$/i, '') : basename(effectiveDir)).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'local-plugin'
111
202
  const fallbackName = safeSegment(rawFallbackName, 'plugin name')
112
- const isMarket = ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
113
- && !existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) && !existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json'))
203
+ // Recognition follows the package formats, not the upload transport:
204
+ // marketplace -> Claude -> Codex -> pure skills. Claude/Codex precedence in
205
+ // readPluginManifest is shared with the existing source installation path.
206
+ const isMarket = ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
207
+ const pureSkills = !isMarket && isPureSkillPackage(effectiveDir)
208
+ const directSkills = pureSkills ? collectDirectSkills(effectiveDir, fallbackName) : []
209
+ const singleFile = !isZip && statSync(targetPath).isFile()
210
+ const kind = isMarket ? 'marketplace' : pureSkills ? 'skills' : existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json')) ? 'claude' : existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) ? 'codex' : 'plugin'
114
211
  let entries
212
+ if (kind === 'skills') entries = directSkills
115
213
  try {
116
214
  if (isMarket) {
117
215
  entries = parseMarketplaceFromDisk('local-upload', effectiveDir).map((row) => {
@@ -121,7 +219,7 @@ export async function inspectLocalPlugin(rawPath) {
121
219
  if (rel.startsWith('..') || isAbsolute(rel) || !isPluginDir(dir)) throw new Error(`市场条目「${row.name}」缺少有效的本地插件目录`)
122
220
  return { row, dir }
123
221
  })
124
- } else {
222
+ } else if (kind !== 'skills') {
125
223
  const row = parsePluginRowFromDir(effectiveDir, fallbackName, 'local')
126
224
  entries = row ? [{ row, dir: effectiveDir }] : []
127
225
  if (!row) {
@@ -149,6 +247,7 @@ export async function inspectLocalPlugin(rawPath) {
149
247
  const agents = entries.flatMap((e) => listAgents(e.dir))
150
248
 
151
249
  const duplicate = entries.find((e) => existsSync(join(sourceCacheDir('local'), safeSegment(e.row.name, 'plugin name'))))
250
+ || (kind === 'skills' ? entries.find((e) => (readState().uploadedSkills || []).some(record => record.name === e.row.name)) : undefined)
152
251
  const localDest = duplicate ? join(sourceCacheDir('local'), duplicate.row.name) : join(sourceCacheDir('local'), cleanPluginName)
153
252
  let exists = false
154
253
  let existingVersion = undefined
@@ -165,6 +264,7 @@ export async function inspectLocalPlugin(rawPath) {
165
264
 
166
265
  return {
167
266
  ok: true,
267
+ kind,
168
268
  effectiveDir,
169
269
  tempExtractDir,
170
270
  entries,
@@ -180,6 +280,84 @@ export async function inspectLocalPlugin(rawPath) {
180
280
  }
181
281
  }
182
282
 
283
+ /**
284
+ * Pure skill packages go straight into the Skills tab instead of the plugin
285
+ * install pipeline: no mirrored copy, no agents/commands conversion.
286
+ */
287
+ export async function importLocalSkills(rawPath, { overwrite = false } = {}) {
288
+ const inspectRes = await inspectLocalPlugin(rawPath)
289
+ if (!inspectRes.ok) throw new Error(inspectRes.error)
290
+ if (inspectRes.kind !== 'skills') throw new Error('该内容不是纯 Skills 包')
291
+ const { tempExtractDir, entries, singleFile } = inspectRes
292
+ try {
293
+ // A bare SKILL.md upload is one flat skill. When the folder it came from is
294
+ // a collection, the walk up yields several entries, and flattening those
295
+ // would drop each skill's assets along with its directory.
296
+ const installed = installUploadedSkills(entries, { overwrite, singleFile: singleFile && entries.length === 1 })
297
+ return { ok: true, sourceId: 'skills-local', skills: installed, kind: 'skills' }
298
+ } finally {
299
+ if (tempExtractDir) safeRmDir(tempExtractDir)
300
+ }
301
+ }
302
+
303
+ /**
304
+ * An uploaded marketplace becomes its own plugin source tab: its declared
305
+ * plugins are copied under the source cache and listed by the normal market
306
+ * reader, so install/update/uninstall behave exactly like a Git source.
307
+ */
308
+ export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false } = {}) {
309
+ const inspectRes = await inspectLocalPlugin(rawPath)
310
+ if (!inspectRes.ok) throw new Error(inspectRes.error)
311
+ if (inspectRes.kind !== 'marketplace') throw new Error('该内容不是插件市场')
312
+ const { effectiveDir, tempExtractDir, entries } = inspectRes
313
+ const label = marketSourceName(effectiveDir, basename(effectiveDir))
314
+ const name = String(sourceName || '').trim().slice(0, 30) || label
315
+ const sourceId = `local-${slugify(label) || 'market'}`
316
+ const dest = sourceCacheDir(sourceId)
317
+ const state = readState()
318
+ if (existsSync(dest) && !overwrite && state.sources.some(source => source.id === sourceId)) {
319
+ if (tempExtractDir) safeRmDir(tempExtractDir)
320
+ throw new Error(`已存在同名插件市场「${label}」`)
321
+ }
322
+ // The destination is wiped below, so a source that is or contains it would be
323
+ // destroyed along with the copy that is still being read from.
324
+ if (containsPath(dest, effectiveDir) || containsPath(effectiveDir, dest)) {
325
+ if (tempExtractDir) safeRmDir(tempExtractDir)
326
+ throw new Error('导入源与插件市场存储目录重叠,请从独立文件夹导入')
327
+ }
328
+ try {
329
+ safeRmDir(dest)
330
+ mkdirSync(dest, { recursive: true })
331
+ for (const { row, dir } of entries) {
332
+ // Keep each plugin on the path its manifest declares: a rewritten layout
333
+ // (`plugins/<name>`) would break `./external_plugins/x` and `./`, and the
334
+ // reader resolves sources against the copied manifest after a restart.
335
+ const target = pluginPath(dest, `./${row.source.replace(/^\.\//, '')}`)
336
+ mkdirSync(dirname(target), { recursive: true })
337
+ if (resolve(target) !== resolve(dest)) cpSync(dir, target, { recursive: true, force: true })
338
+ else copyTreeContents(dir, target)
339
+ }
340
+ // Carry the marketplace manifest itself so the standard reader finds the
341
+ // same rows on the next start, not only during this upload.
342
+ for (const relativePath of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
343
+ const file = join(effectiveDir, relativePath)
344
+ if (!existsSync(file)) continue
345
+ const out = join(dest, relativePath)
346
+ mkdirSync(dirname(out), { recursive: true })
347
+ copyFileSync(file, out)
348
+ }
349
+ } finally {
350
+ if (tempExtractDir) safeRmDir(tempExtractDir)
351
+ }
352
+ if (!state.sources.some(source => source.id === sourceId)) {
353
+ state.sources.push({ id: sourceId, name, url: `local-market://${sourceId}`, addedAt: Date.now() })
354
+ writeState(state)
355
+ }
356
+ invalidateMarketplaceCache(sourceId)
357
+ return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row) }
358
+ }
359
+
360
+ /** Legacy plugin-pipeline import; the UI routes pure skill packages elsewhere. */
183
361
  export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
184
362
  const inspectRes = await inspectLocalPlugin(rawPath)
185
363
  if (!inspectRes.ok) {
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/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)
@@ -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
+ }