dsh-skill-pool 0.0.0-stage → 0.3.7
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/CONTRACTS-v3.md +288 -0
- package/LICENSE +21 -0
- package/README.md +198 -2
- package/client.js +4434 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +21 -0
- package/index.js +174 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +62 -4
- package/src/activation.js +303 -0
- package/src/inventory.js +447 -0
- package/src/library.js +1168 -0
- package/src/mount.js +73 -0
- package/src/provider.js +309 -0
- package/src/remount.js +78 -0
- package/src/rules.js +243 -0
- package/src/skill-content.js +78 -0
- package/src/store.js +765 -0
- package/src/uploads.js +222 -0
- package/src/web-api.js +1037 -0
package/src/library.js
ADDED
|
@@ -0,0 +1,1168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill library: install skills from uploads, ZIP archives, and Git repositories.
|
|
3
|
+
*
|
|
4
|
+
* Design notes:
|
|
5
|
+
* - No external binaries for ZIP: the parser below reads the End Of Central
|
|
6
|
+
* Directory, walks the central directory, and inflates method-8 entries with
|
|
7
|
+
* `zlib.inflateRawSync`. Method-0 (stored) entries are copied verbatim.
|
|
8
|
+
* - No `git` binary: GitHub/GitLab tarball endpoints are fetched with `fetch`,
|
|
9
|
+
* then unpacked with the system `tar` (present on this platform). Self-hosted
|
|
10
|
+
* GitLab and GitHub Enterprise installs are supported through the same paths,
|
|
11
|
+
* derived from the pasted URL instead of a hard-coded host.
|
|
12
|
+
* - Everything lands in `$DSH_HOME/resource-pool/library/skills/<name>/`, which
|
|
13
|
+
* is deliberately NOT `$DSH_HOME/skills`: the resource pool owns its own store
|
|
14
|
+
* and serves it through its own skill provider (`./provider.js`), so imported
|
|
15
|
+
* resources never mix with hand-written skills.
|
|
16
|
+
* - Sources record provenance so a source can be checked, updated, or removed.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-skill-pool/library
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { execFile } from 'node:child_process'
|
|
22
|
+
import { createHash } from 'node:crypto'
|
|
23
|
+
import { cp, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile, rename } from 'node:fs/promises'
|
|
24
|
+
import { tmpdir } from 'node:os'
|
|
25
|
+
import { join, posix } from 'node:path'
|
|
26
|
+
import { promisify } from 'node:util'
|
|
27
|
+
import { inflateRawSync } from 'node:zlib'
|
|
28
|
+
|
|
29
|
+
import { dshHome, newId } from './store.js'
|
|
30
|
+
|
|
31
|
+
const execFileAsync = promisify(execFile)
|
|
32
|
+
|
|
33
|
+
/** Hard cap for one archive (compressed bytes). */
|
|
34
|
+
const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
|
|
35
|
+
/** Hard cap for one archive's uncompressed payload. */
|
|
36
|
+
const MAX_UNCOMPRESSED_BYTES = 256 * 1024 * 1024
|
|
37
|
+
/** Hard cap for entries in one archive. */
|
|
38
|
+
const MAX_ENTRIES = 20_000
|
|
39
|
+
/** Timeout for one Git fetch. */
|
|
40
|
+
const GIT_TIMEOUT_MS = 45_000
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Directory holding every skill the resource pool owns.
|
|
44
|
+
*
|
|
45
|
+
* It lives beside the state file, never inside `$DSH_HOME/skills`, so the
|
|
46
|
+
* system filesystem provider cannot see (or accidentally gate) these skills.
|
|
47
|
+
*
|
|
48
|
+
* @returns {string} absolute library root.
|
|
49
|
+
*/
|
|
50
|
+
export function librarySkillsRoot() {
|
|
51
|
+
return join(dshHome(), 'resource-pool', 'library', 'skills')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Backwards-compatible alias of {@link librarySkillsRoot}.
|
|
56
|
+
* @returns {string} absolute library root.
|
|
57
|
+
*/
|
|
58
|
+
export function skillsRoot() {
|
|
59
|
+
return librarySkillsRoot()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Normalize a label into a kebab-case name.
|
|
64
|
+
* @param {unknown} value - candidate label.
|
|
65
|
+
* @returns {string} kebab-case name, or ''.
|
|
66
|
+
*/
|
|
67
|
+
export function slugify(value) {
|
|
68
|
+
if (typeof value !== 'string') return ''
|
|
69
|
+
return value
|
|
70
|
+
.trim()
|
|
71
|
+
.toLowerCase()
|
|
72
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
73
|
+
.replace(/^-+|-+$/g, '')
|
|
74
|
+
.slice(0, 64)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Reject a path that could escape the target directory (zip-slip).
|
|
79
|
+
* @param {unknown} value - candidate relative path.
|
|
80
|
+
* @returns {string} normalized posix relative path, or '' when unsafe.
|
|
81
|
+
*/
|
|
82
|
+
export function safeRelativePath(value) {
|
|
83
|
+
if (typeof value !== 'string') return ''
|
|
84
|
+
const trimmed = value.trim().replace(/\\/g, '/')
|
|
85
|
+
if (trimmed.length === 0) return ''
|
|
86
|
+
if (trimmed.startsWith('/') || /^[A-Za-z]:\//.test(trimmed)) return ''
|
|
87
|
+
const normalized = posix.normalize(trimmed)
|
|
88
|
+
if (normalized.length === 0 || normalized === '.' || normalized.startsWith('..')) return ''
|
|
89
|
+
if (normalized.split('/').includes('..')) return ''
|
|
90
|
+
return normalized.replace(/^\/+/, '')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** YAML block-scalar header: `>`, `|`, optionally with chomping (`-`/`+`) and indentation. */
|
|
94
|
+
const BLOCK_SCALAR = /^([>|])([+-]?)(\d*)$/
|
|
95
|
+
|
|
96
|
+
/** Whether one line starts a new top-level frontmatter key. */
|
|
97
|
+
const TOP_LEVEL_KEY = /^[A-Za-z][A-Za-z0-9_-]*\s*:/
|
|
98
|
+
|
|
99
|
+
/** Whether one line is indented (part of a multi-line value). */
|
|
100
|
+
function isIndented(line) {
|
|
101
|
+
return line.length > 0 && (line[0] === ' ' || line[0] === '\t')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Strip one pair of matching YAML quotes. */
|
|
105
|
+
function unquote(value) {
|
|
106
|
+
if (value.length >= 2) {
|
|
107
|
+
const first = value[0]
|
|
108
|
+
const last = value[value.length - 1]
|
|
109
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) return value.slice(1, -1)
|
|
110
|
+
}
|
|
111
|
+
return value
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Parse raw skill Markdown into frontmatter metadata and body.
|
|
116
|
+
*
|
|
117
|
+
* Real-world `SKILL.md` files routinely wrap `description` in a YAML block
|
|
118
|
+
* scalar (`description: >` / `|-`) or continue a plain scalar on the next line.
|
|
119
|
+
* A naive line split would read the indicator itself as the description, so the
|
|
120
|
+
* parser resolves those forms and records each key's line span. The raw block is
|
|
121
|
+
* returned unchanged so an install can keep keys this module does not
|
|
122
|
+
* understand (`metadata`, nested YAML) instead of rewriting them away.
|
|
123
|
+
*
|
|
124
|
+
* @param {string} text - markdown document.
|
|
125
|
+
* @returns {{meta: Record<string, string>, body: string, hadFrontmatter: boolean,
|
|
126
|
+
* frontmatter: string, spans: Record<string, {start: number, end: number}>}} parsed document.
|
|
127
|
+
*/
|
|
128
|
+
export function parseSkillDocument(text) {
|
|
129
|
+
const source = typeof text === 'string' ? text : ''
|
|
130
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(source)
|
|
131
|
+
if (match === null) return { meta: {}, body: source, hadFrontmatter: false, frontmatter: '', spans: {} }
|
|
132
|
+
const lines = match[1].split(/\r?\n/)
|
|
133
|
+
const meta = {}
|
|
134
|
+
const spans = {}
|
|
135
|
+
let index = 0
|
|
136
|
+
while (index < lines.length) {
|
|
137
|
+
const line = lines[index]
|
|
138
|
+
if (isIndented(line) || !TOP_LEVEL_KEY.test(line)) {
|
|
139
|
+
index += 1
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
const field = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line)
|
|
143
|
+
if (field === null) {
|
|
144
|
+
index += 1
|
|
145
|
+
continue
|
|
146
|
+
}
|
|
147
|
+
const key = field[1]
|
|
148
|
+
const raw = field[2].trim()
|
|
149
|
+
const start = index
|
|
150
|
+
index += 1
|
|
151
|
+
|
|
152
|
+
// Gather the value's continuation lines: indented lines, plus blank lines
|
|
153
|
+
// that are followed by more indented content (a blank line inside a block).
|
|
154
|
+
const collected = []
|
|
155
|
+
let lastMeaningful = start
|
|
156
|
+
while (index < lines.length) {
|
|
157
|
+
const next = lines[index]
|
|
158
|
+
if (next.trim().length === 0) {
|
|
159
|
+
collected.push('')
|
|
160
|
+
index += 1
|
|
161
|
+
continue
|
|
162
|
+
}
|
|
163
|
+
if (!isIndented(next)) break
|
|
164
|
+
collected.push(next.trim())
|
|
165
|
+
lastMeaningful = index
|
|
166
|
+
index += 1
|
|
167
|
+
}
|
|
168
|
+
// Trailing blanks belong to chomping, not to the value or the span.
|
|
169
|
+
if (collected.length > 0) {
|
|
170
|
+
let end = collected.length
|
|
171
|
+
while (end > 0 && collected[end - 1].length === 0) end -= 1
|
|
172
|
+
collected.length = end
|
|
173
|
+
}
|
|
174
|
+
spans[key] = { start, end: lastMeaningful + 1 }
|
|
175
|
+
|
|
176
|
+
const block = BLOCK_SCALAR.exec(raw)
|
|
177
|
+
let value
|
|
178
|
+
if (block !== null) {
|
|
179
|
+
// Folded joins with spaces, literal keeps newlines; blank lines survive as
|
|
180
|
+
// paragraph breaks in both styles.
|
|
181
|
+
if (block[1] === '>') {
|
|
182
|
+
const parts = []
|
|
183
|
+
let blanks = 0
|
|
184
|
+
for (const entry of collected) {
|
|
185
|
+
if (entry.length === 0) {
|
|
186
|
+
blanks += 1
|
|
187
|
+
continue
|
|
188
|
+
}
|
|
189
|
+
if (parts.length > 0) parts.push(blanks > 0 ? '\n'.repeat(blanks) : ' ')
|
|
190
|
+
parts.push(entry)
|
|
191
|
+
blanks = 0
|
|
192
|
+
}
|
|
193
|
+
value = parts.join('')
|
|
194
|
+
} else {
|
|
195
|
+
value = collected.join('\n')
|
|
196
|
+
}
|
|
197
|
+
value = value.replace(/\s+$/, '')
|
|
198
|
+
} else if (collected.length > 0) {
|
|
199
|
+
// A plain scalar continued on indented lines folds into one line.
|
|
200
|
+
value = [raw, ...collected.filter((entry) => entry.length > 0)].join(' ')
|
|
201
|
+
} else {
|
|
202
|
+
value = unquote(raw)
|
|
203
|
+
}
|
|
204
|
+
meta[key] = value
|
|
205
|
+
}
|
|
206
|
+
return { meta, body: source.slice(match[0].length), hadFrontmatter: true, frontmatter: match[1], spans }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Write one file atomically. */
|
|
210
|
+
async function writeAtomic(path, content) {
|
|
211
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`
|
|
212
|
+
await writeFile(temporary, content)
|
|
213
|
+
await rename(temporary, path)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Parse one ZIP archive into in-memory entries.
|
|
218
|
+
*
|
|
219
|
+
* Supports stored (0) and deflate (8) entries, which covers every archive
|
|
220
|
+
* produced by `zip`, GitHub's "Download ZIP", and most tooling.
|
|
221
|
+
*
|
|
222
|
+
* @param {Buffer|Uint8Array} buffer - archive bytes.
|
|
223
|
+
* @returns {Array<{path: string, data: Buffer}>} regular-file entries.
|
|
224
|
+
*/
|
|
225
|
+
export function parseZip(buffer) {
|
|
226
|
+
const data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer)
|
|
227
|
+
if (data.length === 0 || data.length > MAX_ARCHIVE_BYTES) throw new Error('ZIP 文件为空或超过 64MB 上限')
|
|
228
|
+
|
|
229
|
+
// Locate the End Of Central Directory record (scan back over the comment).
|
|
230
|
+
let eocd = -1
|
|
231
|
+
const stop = Math.max(0, data.length - 0xffff - 22)
|
|
232
|
+
for (let at = data.length - 22; at >= stop; at -= 1) {
|
|
233
|
+
if (data.readUInt32LE(at) === 0x06054b50) {
|
|
234
|
+
eocd = at
|
|
235
|
+
break
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (eocd < 0) throw new Error('不是有效的 ZIP 文件')
|
|
239
|
+
|
|
240
|
+
const entryCount = data.readUInt16LE(eocd + 10)
|
|
241
|
+
const directoryOffset = data.readUInt32LE(eocd + 16)
|
|
242
|
+
if (entryCount > MAX_ENTRIES) throw new Error('ZIP 条目过多')
|
|
243
|
+
|
|
244
|
+
const entries = []
|
|
245
|
+
let total = 0
|
|
246
|
+
let cursor = directoryOffset
|
|
247
|
+
for (let index = 0; index < entryCount; index += 1) {
|
|
248
|
+
if (cursor + 46 > data.length || data.readUInt32LE(cursor) !== 0x02014b50) throw new Error('ZIP 中央目录损坏')
|
|
249
|
+
const method = data.readUInt16LE(cursor + 10)
|
|
250
|
+
const compressedSize = data.readUInt32LE(cursor + 20)
|
|
251
|
+
const uncompressedSize = data.readUInt32LE(cursor + 24)
|
|
252
|
+
const nameLength = data.readUInt16LE(cursor + 28)
|
|
253
|
+
const extraLength = data.readUInt16LE(cursor + 30)
|
|
254
|
+
const commentLength = data.readUInt16LE(cursor + 32)
|
|
255
|
+
const localOffset = data.readUInt32LE(cursor + 42)
|
|
256
|
+
const name = data.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8')
|
|
257
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
258
|
+
|
|
259
|
+
const safe = safeRelativePath(name)
|
|
260
|
+
if (safe.length === 0) continue // directories, macOS junk, unsafe paths
|
|
261
|
+
if (name.endsWith('/')) continue
|
|
262
|
+
|
|
263
|
+
if (localOffset + 30 > data.length || data.readUInt32LE(localOffset) !== 0x04034b50) throw new Error('ZIP 本地头损坏')
|
|
264
|
+
const localNameLength = data.readUInt16LE(localOffset + 26)
|
|
265
|
+
const localExtraLength = data.readUInt16LE(localOffset + 28)
|
|
266
|
+
const start = localOffset + 30 + localNameLength + localExtraLength
|
|
267
|
+
const raw = data.subarray(start, start + compressedSize)
|
|
268
|
+
let content
|
|
269
|
+
if (method === 0) content = Buffer.from(raw)
|
|
270
|
+
else if (method === 8) content = inflateRawSync(raw, { maxOutputLength: 32 * 1024 * 1024 })
|
|
271
|
+
else throw new Error(`ZIP 使用了不支持的压缩方式 ${method}(仅支持 store/deflate)`)
|
|
272
|
+
if (content.length !== uncompressedSize && uncompressedSize !== 0) {
|
|
273
|
+
throw new Error('ZIP 解压长度不匹配')
|
|
274
|
+
}
|
|
275
|
+
total += content.length
|
|
276
|
+
if (total > MAX_UNCOMPRESSED_BYTES) throw new Error('ZIP 解压后体积过大')
|
|
277
|
+
entries.push({ path: safe, data: content })
|
|
278
|
+
}
|
|
279
|
+
if (entries.length === 0) throw new Error('ZIP 里没有可用文件')
|
|
280
|
+
return entries
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Group a flat file list into skill bundles.
|
|
285
|
+
*
|
|
286
|
+
* A bundle is either `<name>/SKILL.md` (plus siblings) or a top-level `<name>.md`.
|
|
287
|
+
* A leading common root directory (an archive's single top folder) is stripped.
|
|
288
|
+
*
|
|
289
|
+
* @param {Array<{path: string, data: Buffer|string}>} files - files with relative paths.
|
|
290
|
+
* @returns {Array<{name: string, files: Array<{path: string, data: Buffer|string}>}>} bundles.
|
|
291
|
+
*/
|
|
292
|
+
export function groupSkillBundles(files) {
|
|
293
|
+
/** @type {Array<{path: string, data: Buffer|string}>} */
|
|
294
|
+
const list = files
|
|
295
|
+
.filter((file) => typeof file?.path === 'string' && safeRelativePath(file.path).length > 0)
|
|
296
|
+
.map((file) => ({ path: safeRelativePath(file.path), data: file.data }))
|
|
297
|
+
if (list.length === 0) return []
|
|
298
|
+
|
|
299
|
+
// Strip one shared top-level directory when every path sits below it (an
|
|
300
|
+
// archive's single root folder, e.g. "repo-main/...").
|
|
301
|
+
const roots = new Set(list.map((file) => file.path.split('/')[0]))
|
|
302
|
+
const strip = roots.size === 1
|
|
303
|
+
&& list.every((file) => file.path.includes('/'))
|
|
304
|
+
&& !list.some((file) => file.path.split('/').pop() === 'SKILL.md' && file.path.split('/').length === 2)
|
|
305
|
+
? [...roots][0]
|
|
306
|
+
: ''
|
|
307
|
+
const stripped = strip.length > 0
|
|
308
|
+
? list.map((file) => ({ ...file, path: file.path.split('/').slice(1).join('/') }))
|
|
309
|
+
: list
|
|
310
|
+
|
|
311
|
+
// Every directory that directly contains SKILL.md is one bundle root.
|
|
312
|
+
/** @type {string[]} */
|
|
313
|
+
const rootsWithSkill = []
|
|
314
|
+
for (const file of stripped) {
|
|
315
|
+
const parts = file.path.split('/')
|
|
316
|
+
if (parts[parts.length - 1] !== 'SKILL.md') continue
|
|
317
|
+
const dir = parts.slice(0, -1).join('/')
|
|
318
|
+
rootsWithSkill.push(dir)
|
|
319
|
+
}
|
|
320
|
+
// Drop nested roots: a skill inside another skill's directory belongs to the inner one.
|
|
321
|
+
const roots2 = rootsWithSkill.filter((dir) => !rootsWithSkill.some((other) => other !== dir && (other === '' ? true : dir.startsWith(other + '/'))))
|
|
322
|
+
|
|
323
|
+
// Flat "<name>.md" files count as skills only when no SKILL.md bundle exists,
|
|
324
|
+
// so a repository README never becomes a skill next to real bundles.
|
|
325
|
+
const flatMarkdown = roots2.length === 0
|
|
326
|
+
? stripped.filter((file) => file.path.split('/').length === 1 && file.path.toLowerCase().endsWith('.md'))
|
|
327
|
+
: []
|
|
328
|
+
if (roots2.length === 0 && flatMarkdown.length === 0) return []
|
|
329
|
+
const bundles = []
|
|
330
|
+
for (const dir of roots2) {
|
|
331
|
+
if (dir.length > 0) {
|
|
332
|
+
const prefix = dir + '/'
|
|
333
|
+
const members = stripped.filter((file) => file.path.startsWith(prefix))
|
|
334
|
+
if (members.length === 0) continue
|
|
335
|
+
bundles.push({
|
|
336
|
+
name: dir.split('/').pop(),
|
|
337
|
+
files: members.map((file) => ({ path: file.path.slice(prefix.length), data: file.data })),
|
|
338
|
+
})
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
// The upload root itself is the bundle. Its members are every file that does
|
|
342
|
+
// not belong to a nested skill root — subdirectories included. Restricting
|
|
343
|
+
// this to depth 1 silently dropped `scripts/` and `references/` of a
|
|
344
|
+
// root-level skill.
|
|
345
|
+
const nested = rootsWithSkill.filter((other) => other.length > 0)
|
|
346
|
+
const members = stripped.filter((file) => !nested.some((root) => file.path.startsWith(root + '/')))
|
|
347
|
+
if (members.length === 0) continue
|
|
348
|
+
// Never derive the name from the filename `SKILL.md` (that produced "SKILL");
|
|
349
|
+
// prefer the name the document declares.
|
|
350
|
+
const document = members.find((file) => file.path === 'SKILL.md')
|
|
351
|
+
const declared = document === undefined
|
|
352
|
+
? ''
|
|
353
|
+
: slugify(parseSkillDocument(Buffer.isBuffer(document.data) ? document.data.toString('utf8') : String(document.data)).meta.name ?? '')
|
|
354
|
+
bundles.push({ name: declared.length > 0 ? declared : 'skill', files: members })
|
|
355
|
+
}
|
|
356
|
+
for (const file of flatMarkdown) {
|
|
357
|
+
bundles.push({ name: file.path.replace(/\.md$/i, ''), files: [{ path: 'SKILL.md', data: file.data }] })
|
|
358
|
+
}
|
|
359
|
+
return bundles
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Content digest of one skill bundle (order-independent over file paths).
|
|
364
|
+
* @param {Array<{path: string, data: Buffer|string}>} files - bundle files.
|
|
365
|
+
* @returns {string} `sha256:<hex>` digest.
|
|
366
|
+
*/
|
|
367
|
+
export function bundleDigest(files) {
|
|
368
|
+
const list = Array.isArray(files) ? files : []
|
|
369
|
+
const hash = createHash('sha256')
|
|
370
|
+
for (const file of [...list].sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))) {
|
|
371
|
+
hash.update(file.path)
|
|
372
|
+
hash.update('\u0000')
|
|
373
|
+
hash.update(Buffer.isBuffer(file.data) ? file.data : Buffer.from(String(file.data)))
|
|
374
|
+
hash.update('\u0000')
|
|
375
|
+
}
|
|
376
|
+
return `sha256:${hash.digest('hex').slice(0, 32)}`
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Rebuild a skill document, keeping every frontmatter key the author wrote.
|
|
381
|
+
*
|
|
382
|
+
* Only two keys are rewritten: `name` becomes the canonical kebab-case value and
|
|
383
|
+
* `description` becomes the effective single-line description. Each key's whole
|
|
384
|
+
* line span is dropped first, so a block scalar (`description: >` plus its
|
|
385
|
+
* indented lines) is removed as a unit instead of leaving orphaned lines behind.
|
|
386
|
+
* Every other key — including nested YAML such as `metadata:` — survives verbatim.
|
|
387
|
+
*
|
|
388
|
+
* @param {{meta: Record<string, string>, body: string, hadFrontmatter: boolean,
|
|
389
|
+
* frontmatter: string, spans?: Record<string, {start: number, end: number}>}} parsed - parsed document.
|
|
390
|
+
* @param {string} name - canonical skill name.
|
|
391
|
+
* @param {string} description - effective description (collapsed to one line).
|
|
392
|
+
* @returns {string} document to write.
|
|
393
|
+
*/
|
|
394
|
+
function renderSkillDocument(parsed, name, description) {
|
|
395
|
+
// A YAML plain scalar cannot hold a newline; catalogs want one line anyway.
|
|
396
|
+
const line = description.replace(/\s+/g, ' ').trim()
|
|
397
|
+
const lines = parsed.hadFrontmatter ? parsed.frontmatter.split(/\r?\n/) : []
|
|
398
|
+
const dropped = new Set()
|
|
399
|
+
for (const key of ['name', 'description']) {
|
|
400
|
+
const span = parsed.spans?.[key]
|
|
401
|
+
if (span === undefined) continue
|
|
402
|
+
for (let index = span.start; index < span.end; index += 1) dropped.add(index)
|
|
403
|
+
}
|
|
404
|
+
const kept = lines.filter((_line, index) => !dropped.has(index))
|
|
405
|
+
const header = [`name: ${name}`, ...(line.length > 0 ? [`description: ${line}`] : [])]
|
|
406
|
+
const block = [...header, ...kept].join('\n').replace(/^\n+/, '').replace(/\n+$/, '')
|
|
407
|
+
return `---\n${block}\n---\n\n${parsed.body.replace(/^\s+/, '')}`
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Install one skill bundle onto disk.
|
|
412
|
+
* @param {object} options - install options.
|
|
413
|
+
* @param {string} options.name - skill name.
|
|
414
|
+
* @param {Array<{path: string, data: Buffer|string}>} options.files - bundle files (`SKILL.md` required).
|
|
415
|
+
* @param {boolean} [options.overwrite] - replace an existing bundle.
|
|
416
|
+
* @param {string} [options.root] - library root override.
|
|
417
|
+
* @returns {Promise<{name: string, description: string, dir: string, digest: string}>} installed skill.
|
|
418
|
+
*/
|
|
419
|
+
export async function installSkillBundle({ name, files, overwrite = false, root, defaultName = '', defaultDescription = '' } = {}) {
|
|
420
|
+
const skillName = slugify(name) || slugify(defaultName)
|
|
421
|
+
if (skillName.length === 0) throw new Error(`技能名 "${name}" 无法转为 kebab-case`)
|
|
422
|
+
const primary = files.find((file) => file.path === 'SKILL.md')
|
|
423
|
+
if (primary === undefined) throw new Error(`技能 ${skillName} 缺少 SKILL.md`)
|
|
424
|
+
const text = Buffer.isBuffer(primary.data) ? primary.data.toString('utf8') : String(primary.data)
|
|
425
|
+
const parsed = parseSkillDocument(text)
|
|
426
|
+
// The upload dialog may supply the missing fields; frontmatter always wins.
|
|
427
|
+
const description = (parsed.meta.description ?? defaultDescription ?? '').toString().trim()
|
|
428
|
+
if (description.length === 0) throw new Error(`技能 ${skillName} 的 SKILL.md 缺少 description`)
|
|
429
|
+
const frontmatterName = slugify(parsed.meta.name ?? '') || slugify(defaultName) || skillName
|
|
430
|
+
const finalName = frontmatterName.length > 0 ? frontmatterName : skillName
|
|
431
|
+
|
|
432
|
+
const base = typeof root === 'string' && root.length > 0 ? root : librarySkillsRoot()
|
|
433
|
+
const dir = join(base, finalName)
|
|
434
|
+
if (!overwrite) {
|
|
435
|
+
try {
|
|
436
|
+
await stat(join(dir, 'SKILL.md'))
|
|
437
|
+
throw new Error(`技能 ${finalName} 已存在;勾选「覆盖」后再导入`)
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (error instanceof Error && error.message.includes('已存在')) throw error
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
// Replace instead of merging: a re-import must not leave stale bundle files.
|
|
443
|
+
if (overwrite) await rm(dir, { recursive: true, force: true })
|
|
444
|
+
await mkdir(dir, { recursive: true })
|
|
445
|
+
await writeAtomic(join(dir, 'SKILL.md'), renderSkillDocument(parsed, finalName, description))
|
|
446
|
+
for (const file of files) {
|
|
447
|
+
if (file.path === 'SKILL.md') continue
|
|
448
|
+
const relative = safeRelativePath(file.path)
|
|
449
|
+
if (relative.length === 0) continue
|
|
450
|
+
const target = join(dir, relative)
|
|
451
|
+
await mkdir(join(target, '..'), { recursive: true })
|
|
452
|
+
await writeFile(target, file.data)
|
|
453
|
+
}
|
|
454
|
+
const digest = bundleDigest([
|
|
455
|
+
{ path: 'SKILL.md', data: renderSkillDocument(parsed, finalName, description) },
|
|
456
|
+
...files.filter((file) => file.path !== 'SKILL.md'),
|
|
457
|
+
])
|
|
458
|
+
return { name: finalName, description, dir, digest }
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Turn one install error into the API's `{name, error}` shape. */
|
|
462
|
+
function failureOf(bundleName, error) {
|
|
463
|
+
return { name: String(bundleName), error: error instanceof Error ? error.message : String(error) }
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Install every bundle found in a flat file list.
|
|
468
|
+
* @returns {Promise<{installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>}>} result.
|
|
469
|
+
*/
|
|
470
|
+
async function installAllBundles({ files, overwrite = false, root, defaults = {} }) {
|
|
471
|
+
const bundles = groupSkillBundles(files)
|
|
472
|
+
if (bundles.length === 0) throw new Error('没有找到技能:需要一个包含 SKILL.md 的目录,或顶层 *.md 文件')
|
|
473
|
+
const installed = []
|
|
474
|
+
const failures = []
|
|
475
|
+
const digests = {}
|
|
476
|
+
for (const bundle of bundles) {
|
|
477
|
+
try {
|
|
478
|
+
// A name/description typed in the dialog only makes sense for one bundle.
|
|
479
|
+
const single = bundles.length === 1
|
|
480
|
+
const skill = await installSkillBundle({
|
|
481
|
+
name: bundle.name,
|
|
482
|
+
files: bundle.files,
|
|
483
|
+
overwrite,
|
|
484
|
+
root,
|
|
485
|
+
defaultName: single ? defaults.name ?? '' : '',
|
|
486
|
+
defaultDescription: single ? defaults.description ?? '' : '',
|
|
487
|
+
})
|
|
488
|
+
installed.push(skill.name)
|
|
489
|
+
digests[skill.name] = skill.digest
|
|
490
|
+
} catch (error) {
|
|
491
|
+
failures.push(failureOf(bundle.name, error))
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (installed.length === 0) throw new Error(`技能安装失败:${failures.map((failure) => `${failure.name}: ${failure.error}`).join('; ')}`)
|
|
495
|
+
return { installed, failures, digests }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Install skills from a list of uploaded files.
|
|
500
|
+
* @param {{files: Array<{path: string, content: string}>, overwrite?: boolean, root?: string, name?: string, description?: string, scope?: object}} options - install options.
|
|
501
|
+
* @returns {Promise<{installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>}>} installation result.
|
|
502
|
+
*/
|
|
503
|
+
export async function installFromFiles({ files, overwrite = false, root, name = '', description = '' } = {}) {
|
|
504
|
+
const list = (Array.isArray(files) ? files : []).filter((file) => typeof file?.content === 'string')
|
|
505
|
+
if (list.length === 0) throw new Error('没有可上传的文件内容')
|
|
506
|
+
const normalized = list.map((file) => ({ path: safeRelativePath(file.path) || 'SKILL.md', data: file.content }))
|
|
507
|
+
return installAllBundles({ files: normalized, overwrite, root, defaults: { name, description } })
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Install skills from a ZIP archive (base64).
|
|
512
|
+
* @param {{archiveBase64: string, overwrite?: boolean, root?: string, label?: string, scope?: object}} options - install options.
|
|
513
|
+
* @returns {Promise<{installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>}>} installation result.
|
|
514
|
+
*/
|
|
515
|
+
export async function installFromZip({ archiveBase64, overwrite = false, root, label } = {}) {
|
|
516
|
+
if (typeof archiveBase64 !== 'string' || archiveBase64.length === 0) throw new Error('缺少 archiveBase64')
|
|
517
|
+
const buffer = Buffer.from(archiveBase64, 'base64')
|
|
518
|
+
const entries = parseZip(buffer)
|
|
519
|
+
return installAllBundles({ files: entries, overwrite, root })
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Parse a GitHub/GitLab repository URL.
|
|
524
|
+
* @param {unknown} value - repository URL.
|
|
525
|
+
* @returns {{provider: 'github'|'gitlab', project: string, host: string}} parsed repository.
|
|
526
|
+
*/
|
|
527
|
+
/**
|
|
528
|
+
* Parse a repository URL into the endpoints needed to download and check it.
|
|
529
|
+
*
|
|
530
|
+
* Self-hosted installs are first-class: the host comes from the URL, so an
|
|
531
|
+
* internal GitLab (`https://git.example.com/group/repo`) works exactly like
|
|
532
|
+
* gitlab.com. A pasted browser URL is understood too — GitLab's
|
|
533
|
+
* `/-/tree/<branch>/<subdir>` and `/-/blob/...` shapes are stripped back to the
|
|
534
|
+
* project, and the branch/sub-directory they encode are returned as hints.
|
|
535
|
+
*
|
|
536
|
+
* @param {unknown} value - repository URL (https, ssh scp-like, or a web URL).
|
|
537
|
+
* @param {{provider?: 'auto'|'gitlab'|'github'}} [options] - provider override.
|
|
538
|
+
* @returns {{provider: 'github'|'gitlab', project: string, host: string, origin: string,
|
|
539
|
+
* apiBase: string, branchHint: string, subdirHint: string}} parsed repository.
|
|
540
|
+
*/
|
|
541
|
+
export function parseRepoUrl(value, { provider: forced = 'auto' } = {}) {
|
|
542
|
+
if (typeof value !== 'string' || value.trim().length === 0) throw new Error('缺少仓库 URL')
|
|
543
|
+
let url = value.trim()
|
|
544
|
+
// scp-like SSH form: git@host:group/repo.git
|
|
545
|
+
const ssh = /^git@([^:]+):(.+)$/.exec(url)
|
|
546
|
+
if (ssh !== null) url = `https://${ssh[1]}/${ssh[2]}`
|
|
547
|
+
// Bare host/path without a scheme is a common paste; assume https.
|
|
548
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) url = `https://${url}`
|
|
549
|
+
|
|
550
|
+
let parsed
|
|
551
|
+
try {
|
|
552
|
+
parsed = new URL(url)
|
|
553
|
+
} catch {
|
|
554
|
+
throw new Error('仓库 URL 无效,需要 https://<host>/<group>/<repo>')
|
|
555
|
+
}
|
|
556
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
557
|
+
throw new Error('仓库地址只支持 http/https')
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
let segments = parsed.pathname.split('/').filter((part) => part.length > 0)
|
|
561
|
+
|
|
562
|
+
const host = parsed.hostname.toLowerCase()
|
|
563
|
+
const origin = `${parsed.protocol}//${parsed.host}`
|
|
564
|
+
// `hostLabel` keeps an explicit port, which self-hosted instances often use.
|
|
565
|
+
const hostLabel = parsed.host.toLowerCase()
|
|
566
|
+
const looksGithub = host === 'github.com' || host.endsWith('.github.com')
|
|
567
|
+
|
|
568
|
+
// A `/-/tree/...` marker is GitLab's canonical web path, so it decides the
|
|
569
|
+
// provider even on an unknown (self-hosted) host.
|
|
570
|
+
const gitlabMarker = segments.indexOf('-')
|
|
571
|
+
const hasGitlabMarker = gitlabMarker > 0
|
|
572
|
+
&& (segments[gitlabMarker + 1] === 'tree' || segments[gitlabMarker + 1] === 'blob' || segments[gitlabMarker + 1] === 'src')
|
|
573
|
+
// GitHub (and GitHub Enterprise) put the same information directly after the
|
|
574
|
+
// two-segment project: `/<owner>/<repo>/tree/<branch>/<path>`.
|
|
575
|
+
const hasGithubMarker = segments.length > 2 && (segments[2] === 'tree' || segments[2] === 'blob' || segments[2] === 'raw')
|
|
576
|
+
|
|
577
|
+
// Explicit choice wins, then the URL shape, then the host.
|
|
578
|
+
const provider = forced === 'github' || forced === 'gitlab'
|
|
579
|
+
? forced
|
|
580
|
+
: hasGitlabMarker
|
|
581
|
+
? 'gitlab'
|
|
582
|
+
: looksGithub || hasGithubMarker
|
|
583
|
+
? 'github'
|
|
584
|
+
: 'gitlab'
|
|
585
|
+
|
|
586
|
+
// Keep the branch and sub-directory a browser URL already names, so pasting a
|
|
587
|
+
// link to one skill imports exactly that skill.
|
|
588
|
+
let branchHint = ''
|
|
589
|
+
let subdirHint = ''
|
|
590
|
+
if (provider === 'gitlab') {
|
|
591
|
+
if (hasGitlabMarker) {
|
|
592
|
+
const rest = segments.slice(gitlabMarker + 2)
|
|
593
|
+
branchHint = rest[0] ?? ''
|
|
594
|
+
subdirHint = rest.slice(1).join('/')
|
|
595
|
+
segments = segments.slice(0, gitlabMarker)
|
|
596
|
+
}
|
|
597
|
+
} else if (hasGithubMarker) {
|
|
598
|
+
const rest = segments.slice(3)
|
|
599
|
+
branchHint = rest[0] ?? ''
|
|
600
|
+
subdirHint = rest.slice(1).join('/')
|
|
601
|
+
segments = segments.slice(0, 2)
|
|
602
|
+
} else if (looksGithub && segments.length > 2) {
|
|
603
|
+
// A github.com URL with extra path but no recognised marker: treat the
|
|
604
|
+
// trailing segments as junk rather than a longer project name, because a
|
|
605
|
+
// GitHub project is always exactly two segments.
|
|
606
|
+
segments = segments.slice(0, 2)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
if (segments.length > 0 && /\.git$/i.test(segments[segments.length - 1])) {
|
|
610
|
+
segments[segments.length - 1] = segments[segments.length - 1].replace(/\.git$/i, '')
|
|
611
|
+
}
|
|
612
|
+
const project = segments.join('/')
|
|
613
|
+
if (project.split('/').length < 2) throw new Error('仓库 URL 需要包含 owner/repo(GitLab 支持多级 group)')
|
|
614
|
+
// GitHub answers `tree|blob|raw` in the branch position with a Git ref name, so
|
|
615
|
+
// an empty one would build a nonsense archive URL.
|
|
616
|
+
if (branchHint === 'tree' || branchHint === 'blob' || branchHint === 'raw') branchHint = ''
|
|
617
|
+
// A link to a file (`.../blob/main/skills/x/SKILL.md`) points at the file, but
|
|
618
|
+
// the importer needs its directory.
|
|
619
|
+
if (/\.md$/i.test(subdirHint)) subdirHint = subdirHint.split('/').slice(0, -1).join('/')
|
|
620
|
+
|
|
621
|
+
const apiBase =
|
|
622
|
+
provider === 'github'
|
|
623
|
+
? host === 'github.com'
|
|
624
|
+
? 'https://api.github.com'
|
|
625
|
+
: `${origin}/api/v3`
|
|
626
|
+
: `${origin}/api/v4`
|
|
627
|
+
return { provider, project, host, hostLabel, origin, apiBase, branchHint, subdirHint }
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Where to fetch one branch's tarball.
|
|
632
|
+
* @param {object} repo - `parseRepoUrl` result.
|
|
633
|
+
* @param {string} branch - branch name.
|
|
634
|
+
* @returns {string} archive URL.
|
|
635
|
+
*/
|
|
636
|
+
function archiveUrlOf(repo, branch) {
|
|
637
|
+
if (repo.provider === 'github') {
|
|
638
|
+
// codeload is the documented fast path on github.com; GHE serves the same
|
|
639
|
+
// archive from the web origin.
|
|
640
|
+
return repo.host === 'github.com'
|
|
641
|
+
? `https://codeload.github.com/${repo.project}/tar.gz/refs/heads/${encodeURIComponent(branch)}`
|
|
642
|
+
: `${repo.origin}/${repo.project}/archive/refs/heads/${encodeURIComponent(branch)}.tar.gz`
|
|
643
|
+
}
|
|
644
|
+
return `${repo.apiBase}/projects/${encodeURIComponent(repo.project)}/repository/archive.tar.gz?sha=${encodeURIComponent(branch)}`
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Where to ask for one branch's head commit.
|
|
649
|
+
* @param {object} repo - `parseRepoUrl` result.
|
|
650
|
+
* @param {string} branch - branch name.
|
|
651
|
+
* @returns {string} commits API URL.
|
|
652
|
+
*/
|
|
653
|
+
function commitsUrlOf(repo, branch) {
|
|
654
|
+
if (repo.provider === 'github') return `${repo.apiBase}/repos/${repo.project}/commits/${encodeURIComponent(branch)}`
|
|
655
|
+
return `${repo.apiBase}/projects/${encodeURIComponent(repo.project)}/repository/commits/${encodeURIComponent(branch)}`
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** HTTP headers for one provider. */
|
|
659
|
+
function providerHeaders(provider, token) {
|
|
660
|
+
if (typeof token !== 'string' || token.length === 0) return { 'user-agent': 'dsh-skill-pool' }
|
|
661
|
+
if (provider === 'github') return { 'user-agent': 'dsh-skill-pool', authorization: `Bearer ${token}` }
|
|
662
|
+
return { 'user-agent': 'dsh-skill-pool', 'PRIVATE-TOKEN': token }
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Download one archive with a timeout. */
|
|
666
|
+
async function fetchBuffer(url, headers) {
|
|
667
|
+
const response = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(GIT_TIMEOUT_MS) })
|
|
668
|
+
if (!response.ok) {
|
|
669
|
+
const hint = response.status === 404 ? '(仓库或分支不存在,或私有仓库缺少 token)' : ''
|
|
670
|
+
const error = new Error(`下载失败:HTTP ${response.status}${hint}`)
|
|
671
|
+
// Callers need the status to tell "this instance forbids archives" apart from
|
|
672
|
+
// a genuine failure.
|
|
673
|
+
error.status = response.status
|
|
674
|
+
error.url = url
|
|
675
|
+
throw error
|
|
676
|
+
}
|
|
677
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
678
|
+
if (buffer.length > MAX_ARCHIVE_BYTES) throw new Error('仓库归档超过 64MB 上限')
|
|
679
|
+
return buffer
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** Whether an archive download failed because the instance forbids archives. */
|
|
683
|
+
function isArchiveBlocked(error) {
|
|
684
|
+
const status = error?.status
|
|
685
|
+
// GitLab answers 406 when repository archives are disabled or filtered by a
|
|
686
|
+
// proxy; 403/415 show up on hardened instances as well.
|
|
687
|
+
return status === 406 || status === 403 || status === 415
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** Fetch one GitLab API document as JSON. */
|
|
691
|
+
async function gitlabJson(repo, path, token) {
|
|
692
|
+
const response = await fetch(`${repo.apiBase}${path}`, {
|
|
693
|
+
headers: providerHeaders(repo.provider, token),
|
|
694
|
+
signal: AbortSignal.timeout(GIT_TIMEOUT_MS),
|
|
695
|
+
})
|
|
696
|
+
if (!response.ok) {
|
|
697
|
+
const hint = response.status === 404 ? '(仓库或分支不存在,或私有仓库缺少 token)' : ''
|
|
698
|
+
const error = new Error(`读取仓库失败:HTTP ${response.status}${hint}`)
|
|
699
|
+
error.status = response.status
|
|
700
|
+
throw error
|
|
701
|
+
}
|
|
702
|
+
return response.json()
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Read a whole GitLab repository through the API instead of its archive.
|
|
707
|
+
*
|
|
708
|
+
* Some hardened self-hosted instances answer 406 on
|
|
709
|
+
* `/repository/archive.*` while the rest of the API works fine. The recursive
|
|
710
|
+
* tree plus per-file `raw` endpoints reconstruct the same file list, so a repo
|
|
711
|
+
* that cannot be archived can still be imported.
|
|
712
|
+
*
|
|
713
|
+
* @param {object} repo - `parseRepoUrl` result (gitlab only).
|
|
714
|
+
* @param {string} branch - branch or tag name.
|
|
715
|
+
* @param {string} token - access token.
|
|
716
|
+
* @returns {Promise<Array<{path: string, data: Buffer}>>} files, relative to the repository root.
|
|
717
|
+
*/
|
|
718
|
+
async function readTreeViaApi(repo, branch, token) {
|
|
719
|
+
const project = encodeURIComponent(repo.project)
|
|
720
|
+
const entries = []
|
|
721
|
+
for (let page = 1; page <= 100; page += 1) {
|
|
722
|
+
const rows = await gitlabJson(
|
|
723
|
+
repo,
|
|
724
|
+
`/projects/${project}/repository/tree?ref=${encodeURIComponent(branch)}&recursive=true&per_page=100&page=${page}`,
|
|
725
|
+
token,
|
|
726
|
+
)
|
|
727
|
+
if (!Array.isArray(rows) || rows.length === 0) break
|
|
728
|
+
for (const row of rows) {
|
|
729
|
+
if (row === null || typeof row !== 'object') continue
|
|
730
|
+
if (row.type !== 'blob' || typeof row.path !== 'string' || row.path.length === 0) continue
|
|
731
|
+
entries.push(row.path)
|
|
732
|
+
if (entries.length > MAX_ENTRIES) throw new Error('仓库文件过多')
|
|
733
|
+
}
|
|
734
|
+
if (rows.length < 100) break
|
|
735
|
+
}
|
|
736
|
+
if (entries.length === 0) throw new Error('仓库里没有文件')
|
|
737
|
+
|
|
738
|
+
const files = []
|
|
739
|
+
const queue = entries.slice()
|
|
740
|
+
const worker = async () => {
|
|
741
|
+
for (;;) {
|
|
742
|
+
const path = queue.shift()
|
|
743
|
+
if (path === undefined) return
|
|
744
|
+
const response = await fetch(
|
|
745
|
+
`${repo.apiBase}/projects/${project}/repository/files/${encodeURIComponent(path)}/raw?ref=${encodeURIComponent(branch)}`,
|
|
746
|
+
{ headers: providerHeaders(repo.provider, token), signal: AbortSignal.timeout(GIT_TIMEOUT_MS) },
|
|
747
|
+
)
|
|
748
|
+
if (!response.ok) {
|
|
749
|
+
const error = new Error(`读取 ${path} 失败:HTTP ${response.status}`)
|
|
750
|
+
error.status = response.status
|
|
751
|
+
throw error
|
|
752
|
+
}
|
|
753
|
+
files.push({ path, data: Buffer.from(await response.arrayBuffer()) })
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
// A small pool keeps a 40-file repo fast without hammering the instance.
|
|
757
|
+
await Promise.all([worker(), worker(), worker(), worker()])
|
|
758
|
+
return files
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Resolve the remote commit id of one branch without downloading the archive.
|
|
763
|
+
*
|
|
764
|
+
* This is what makes "check for updates" cheap: one API call per source instead
|
|
765
|
+
* of a full tarball download. The endpoint comes from the parsed URL, so this
|
|
766
|
+
* works against gitlab.com, a self-hosted GitLab, or GitHub Enterprise alike.
|
|
767
|
+
*
|
|
768
|
+
* @param {object} options - lookup options.
|
|
769
|
+
* @param {object} options.repo - `parseRepoUrl` result.
|
|
770
|
+
* @param {string} options.branch - branch name.
|
|
771
|
+
* @param {string} [options.token] - access token.
|
|
772
|
+
* @returns {Promise<string>} commit id.
|
|
773
|
+
*/
|
|
774
|
+
async function resolveRemoteSha({ repo, branch, token }) {
|
|
775
|
+
const url = commitsUrlOf(repo, branch)
|
|
776
|
+
const headers = repo.provider === 'github'
|
|
777
|
+
? { ...providerHeaders(repo.provider, token), accept: 'application/vnd.github+json' }
|
|
778
|
+
: providerHeaders(repo.provider, token)
|
|
779
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(GIT_TIMEOUT_MS) })
|
|
780
|
+
if (!response.ok) {
|
|
781
|
+
const hint = response.status === 404 ? '(仓库或分支不存在,或私有仓库缺少 token)' : ''
|
|
782
|
+
throw new Error(`查询提交失败:HTTP ${response.status}${hint}`)
|
|
783
|
+
}
|
|
784
|
+
const payload = await response.json()
|
|
785
|
+
const id = repo.provider === 'github' ? payload?.sha : payload?.id
|
|
786
|
+
if (typeof id === 'string' && id.length > 0) return id
|
|
787
|
+
throw new Error(`查询提交失败:响应缺少 ${repo.provider === 'github' ? 'sha' : 'id'}`)
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Download and unpack one repository into a temporary directory.
|
|
792
|
+
*
|
|
793
|
+
* The archive endpoint is the fast path. When the instance refuses archives
|
|
794
|
+
* (406 on hardened self-hosted GitLab), the same tree is reconstructed through
|
|
795
|
+
* the API and materialised on disk, so the install path downstream does not
|
|
796
|
+
* care which route produced it.
|
|
797
|
+
*/
|
|
798
|
+
async function downloadRepo({ repo, branch, token }) {
|
|
799
|
+
const workDir = await mkdtemp(join(tmpdir(), 'rp-git-'))
|
|
800
|
+
const extractDir = join(workDir, 'tree')
|
|
801
|
+
await mkdir(extractDir, { recursive: true })
|
|
802
|
+
let files = []
|
|
803
|
+
let archiveDigest = ''
|
|
804
|
+
try {
|
|
805
|
+
const archive = await fetchBuffer(archiveUrlOf(repo, branch), providerHeaders(repo.provider, token))
|
|
806
|
+
const archivePath = join(workDir, 'repo.tar.gz')
|
|
807
|
+
await writeFile(archivePath, archive)
|
|
808
|
+
try {
|
|
809
|
+
await execFileAsync('tar', ['-xzf', archivePath, '-C', extractDir], { timeout: GIT_TIMEOUT_MS })
|
|
810
|
+
} catch (error) {
|
|
811
|
+
await rm(workDir, { recursive: true, force: true })
|
|
812
|
+
throw new Error(`解包失败:${error instanceof Error ? error.message : String(error)}`)
|
|
813
|
+
}
|
|
814
|
+
archiveDigest = bundleDigest([{ path: 'archive.tar.gz', data: archive }])
|
|
815
|
+
} catch (error) {
|
|
816
|
+
if (!isArchiveBlocked(error) || repo.provider !== 'gitlab') throw error
|
|
817
|
+
// Archives are disabled on this instance: rebuild the tree file by file.
|
|
818
|
+
files = await readTreeViaApi(repo, branch, token)
|
|
819
|
+
const top = join(extractDir, repo.project.split('/').pop())
|
|
820
|
+
for (const file of files) {
|
|
821
|
+
const relative = safeRelativePath(file.path)
|
|
822
|
+
if (relative.length === 0) continue
|
|
823
|
+
const target = join(top, relative)
|
|
824
|
+
await mkdir(join(target, '..'), { recursive: true })
|
|
825
|
+
await writeFile(target, file.data)
|
|
826
|
+
}
|
|
827
|
+
archiveDigest = bundleDigest(files)
|
|
828
|
+
}
|
|
829
|
+
let sha = ''
|
|
830
|
+
try {
|
|
831
|
+
sha = await resolveRemoteSha({ repo, branch, token })
|
|
832
|
+
} catch {
|
|
833
|
+
// A missing commit API must not block an install; fall back to a content hash.
|
|
834
|
+
sha = `archive:${createHash('sha256').update(archiveDigest).digest('hex').slice(0, 16)}`
|
|
835
|
+
}
|
|
836
|
+
return { workDir, extractDir, sha, digest: archiveDigest, files: files.length }
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** Read every file under one directory into a flat list. */
|
|
840
|
+
async function readTree(dir) {
|
|
841
|
+
const out = []
|
|
842
|
+
const walk = async (current, prefix) => {
|
|
843
|
+
const entries = await readdir(current, { withFileTypes: true })
|
|
844
|
+
for (const entry of entries) {
|
|
845
|
+
if (entry.name === '.git') continue
|
|
846
|
+
const full = join(current, entry.name)
|
|
847
|
+
const relative = prefix.length > 0 ? `${prefix}/${entry.name}` : entry.name
|
|
848
|
+
if (entry.isDirectory()) {
|
|
849
|
+
await walk(full, relative)
|
|
850
|
+
continue
|
|
851
|
+
}
|
|
852
|
+
if (!entry.isFile()) continue
|
|
853
|
+
out.push({ path: relative, data: await readFile(full) })
|
|
854
|
+
if (out.length > MAX_ENTRIES) throw new Error('仓库文件过多')
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
await walk(dir, '')
|
|
858
|
+
return out
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* Group a repository tree into skill bundles.
|
|
863
|
+
*
|
|
864
|
+
* A skill root is any directory that directly holds `SKILL.md`; every file
|
|
865
|
+
* below it (`reference/`, `scripts/`, …) ships with the skill, relative to that
|
|
866
|
+
* root. Nested roots are skipped: the inner skill owns its files.
|
|
867
|
+
*
|
|
868
|
+
* @param {Array<{path: string, data: Buffer|string}>} files - tree files with relative paths.
|
|
869
|
+
* @returns {Array<{name: string, dir: string, files: Array<{path: string, data: Buffer|string}>}>} bundles.
|
|
870
|
+
*/
|
|
871
|
+
export function bundlesFromTree(files) {
|
|
872
|
+
const list = Array.isArray(files) ? files.filter((file) => typeof file?.path === 'string') : []
|
|
873
|
+
const skillRoots = []
|
|
874
|
+
for (const file of list) {
|
|
875
|
+
if (file.path.split('/').pop() !== 'SKILL.md') continue
|
|
876
|
+
skillRoots.push(file.path.split('/').slice(0, -1).join('/'))
|
|
877
|
+
}
|
|
878
|
+
const bundles = []
|
|
879
|
+
for (const dir of skillRoots) {
|
|
880
|
+
const prefix = dir.length > 0 ? dir + '/' : ''
|
|
881
|
+
// A nested skill root owns its own subtree; it never ships inside the parent.
|
|
882
|
+
const nestedRoots = skillRoots.filter((other) => other !== dir && other.startsWith(prefix))
|
|
883
|
+
const members = list
|
|
884
|
+
.filter((file) => file.path.startsWith(prefix))
|
|
885
|
+
.filter((file) => !nestedRoots.some((nested) => file.path.startsWith(nested + '/')))
|
|
886
|
+
.map((file) => ({ path: file.path.slice(prefix.length), data: file.data }))
|
|
887
|
+
if (members.length === 0) continue
|
|
888
|
+
bundles.push({ name: dir.split('/').pop(), dir, files: members })
|
|
889
|
+
}
|
|
890
|
+
return bundles
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Install skills discovered in one extracted repository tree.
|
|
895
|
+
* @returns {Promise<{installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>}>} result.
|
|
896
|
+
*/
|
|
897
|
+
async function installFromTree({ extractDir, subdir, overwrite, root, exclude = [] }) {
|
|
898
|
+
const roots = await readdir(extractDir, { withFileTypes: true })
|
|
899
|
+
const top = roots.find((entry) => entry.isDirectory())
|
|
900
|
+
if (top === undefined) throw new Error('仓库归档为空')
|
|
901
|
+
let base = join(extractDir, top.name)
|
|
902
|
+
if (typeof subdir === 'string' && subdir.length > 0) {
|
|
903
|
+
base = join(base, ...subdir.split('/').filter((part) => part.length > 0 && part !== '.' && part !== '..'))
|
|
904
|
+
}
|
|
905
|
+
const files = await readTree(base)
|
|
906
|
+
const allBundles = bundlesFromTree(files)
|
|
907
|
+
if (allBundles.length === 0) throw new Error('仓库里没有包含 SKILL.md 的技能目录')
|
|
908
|
+
// Names the user deleted are never written back: an update must not resurrect
|
|
909
|
+
// what "删除" removed.
|
|
910
|
+
const blocked = new Set(Array.isArray(exclude) ? exclude : [])
|
|
911
|
+
const bundles = allBundles.filter((bundle) => !blocked.has(bundle.name))
|
|
912
|
+
if (bundles.length === 0) return { installed: [], failures: [], digests: {}, excluded: allBundles.map((bundle) => bundle.name) }
|
|
913
|
+
// When the pasted sub-directory IS the skill bundle, its `SKILL.md` sits at the
|
|
914
|
+
// base and `bundlesFromTree` has no directory segment to name it after.
|
|
915
|
+
const subdirName = base.split(/[\\/]/).filter((part) => part.length > 0).pop() ?? ''
|
|
916
|
+
const installed = []
|
|
917
|
+
const failures = []
|
|
918
|
+
const digests = {}
|
|
919
|
+
for (const bundle of bundles) {
|
|
920
|
+
try {
|
|
921
|
+
const skill = await installSkillBundle({
|
|
922
|
+
name: bundle.name,
|
|
923
|
+
files: bundle.files,
|
|
924
|
+
overwrite,
|
|
925
|
+
root,
|
|
926
|
+
defaultName: bundle.name.length > 0 ? '' : subdirName,
|
|
927
|
+
})
|
|
928
|
+
installed.push(skill.name)
|
|
929
|
+
digests[skill.name] = skill.digest
|
|
930
|
+
} catch (error) {
|
|
931
|
+
// A name clash with an existing skill must never be silent.
|
|
932
|
+
failures.push(failureOf(bundle.name, error))
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (installed.length === 0) throw new Error(`技能安装失败:${failures.map((failure) => `${failure.name}: ${failure.error}`).join('; ')}`)
|
|
936
|
+
return { installed, failures, digests }
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Install skills from a Git repository.
|
|
941
|
+
* @param {object} options - import options.
|
|
942
|
+
* @param {string} options.url - repository URL.
|
|
943
|
+
* @param {string} [options.branch] - branch name.
|
|
944
|
+
* @param {string} [options.subdir] - subdirectory holding the skills.
|
|
945
|
+
* @param {string} [options.token] - access token (stored by the caller, never here).
|
|
946
|
+
* @param {string} [options.label] - display label.
|
|
947
|
+
* @param {boolean} [options.overwrite] - replace existing skills.
|
|
948
|
+
* @param {string} [options.root] - library root override.
|
|
949
|
+
* @returns {Promise<{source: object, installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>}>} installation result.
|
|
950
|
+
*/
|
|
951
|
+
export async function installFromGit({ url, branch, subdir, token = '', label, provider = 'auto', overwrite = false, root } = {}) {
|
|
952
|
+
const repo = parseRepoUrl(url, { provider })
|
|
953
|
+
// A pasted browser URL already names its branch and folder; use those when the
|
|
954
|
+
// caller left the fields alone.
|
|
955
|
+
const wantedBranch = typeof branch === 'string' && branch.trim().length > 0 ? branch.trim() : repo.branchHint || 'main'
|
|
956
|
+
const wantedSubdir = typeof subdir === 'string' && subdir.length > 0 ? subdir : repo.subdirHint
|
|
957
|
+
const { workDir, extractDir, sha, digest } = await downloadRepo({ repo, branch: wantedBranch, token })
|
|
958
|
+
try {
|
|
959
|
+
const { installed, failures, digests } = await installFromTree({ extractDir, subdir: wantedSubdir, overwrite, root })
|
|
960
|
+
const now = new Date().toISOString()
|
|
961
|
+
return {
|
|
962
|
+
installed,
|
|
963
|
+
failures,
|
|
964
|
+
digests,
|
|
965
|
+
source: {
|
|
966
|
+
id: newId('src'),
|
|
967
|
+
kind: 'git',
|
|
968
|
+
label: typeof label === 'string' && label.trim().length > 0 ? label.trim() : `${repo.project}@${wantedBranch}`,
|
|
969
|
+
url: String(url).trim(),
|
|
970
|
+
provider: repo.provider,
|
|
971
|
+
host: repo.hostLabel,
|
|
972
|
+
project: repo.project,
|
|
973
|
+
branch: wantedBranch,
|
|
974
|
+
subdir: typeof wantedSubdir === 'string' ? wantedSubdir : '',
|
|
975
|
+
sha,
|
|
976
|
+
digest,
|
|
977
|
+
skills: installed,
|
|
978
|
+
createdAt: now,
|
|
979
|
+
updatedAt: now,
|
|
980
|
+
},
|
|
981
|
+
}
|
|
982
|
+
} finally {
|
|
983
|
+
await rm(workDir, { recursive: true, force: true })
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Re-fetch one Git source and replace the skills it installed.
|
|
989
|
+
* @param {object} options - update options.
|
|
990
|
+
* @param {object} options.source - stored source record.
|
|
991
|
+
* @param {string} [options.token] - access token.
|
|
992
|
+
* @param {string} [options.root] - library root override.
|
|
993
|
+
* @returns {Promise<{source: object, installed: string[], failures: Array<{name: string, error: string}>, digests: Record<string, string>, changed: boolean}>} update result.
|
|
994
|
+
*/
|
|
995
|
+
export async function updateGitSource({ source, token = '', root, exclude, force = false } = {}) {
|
|
996
|
+
if (source?.kind !== 'git') throw new Error('只有 Git 来源可以更新')
|
|
997
|
+
const repo = parseRepoUrl(source.url)
|
|
998
|
+
const branch = source.branch ?? 'main'
|
|
999
|
+
const blocked = Array.isArray(exclude) ? exclude : Array.isArray(source.excluded) ? source.excluded : []
|
|
1000
|
+
const { workDir, extractDir, sha, digest } = await downloadRepo({ repo, branch, token })
|
|
1001
|
+
try {
|
|
1002
|
+
// `force` reinstalls even when the commit is unchanged: that is what
|
|
1003
|
+
// "恢复已排除" needs, since nothing upstream moved.
|
|
1004
|
+
if (!force && typeof source.sha === 'string' && source.sha.length > 0 && source.sha === sha) {
|
|
1005
|
+
return { changed: false, source: { ...source, sha, digest }, installed: [], failures: [], digests: {} }
|
|
1006
|
+
}
|
|
1007
|
+
const { installed, failures, digests } = await installFromTree({
|
|
1008
|
+
extractDir,
|
|
1009
|
+
subdir: source.subdir ?? '',
|
|
1010
|
+
overwrite: true,
|
|
1011
|
+
root,
|
|
1012
|
+
exclude: blocked,
|
|
1013
|
+
})
|
|
1014
|
+
const now = new Date().toISOString()
|
|
1015
|
+
// Skills that disappeared upstream must not linger in the pool.
|
|
1016
|
+
const previous = Array.isArray(source.skills) ? source.skills : []
|
|
1017
|
+
const gone = previous.filter((name) => !installed.includes(name))
|
|
1018
|
+
for (const name of gone) {
|
|
1019
|
+
const safe = slugify(name)
|
|
1020
|
+
if (safe.length > 0) await rm(join(typeof root === 'string' && root.length > 0 ? root : librarySkillsRoot(), safe), { recursive: true, force: true })
|
|
1021
|
+
}
|
|
1022
|
+
return {
|
|
1023
|
+
changed: true,
|
|
1024
|
+
installed,
|
|
1025
|
+
failures,
|
|
1026
|
+
digests,
|
|
1027
|
+
removed: gone,
|
|
1028
|
+
source: { ...source, sha, digest, skills: installed, updatedAt: now },
|
|
1029
|
+
}
|
|
1030
|
+
} finally {
|
|
1031
|
+
await rm(workDir, { recursive: true, force: true })
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* Check one Git source for an upstream change without downloading it.
|
|
1037
|
+
* @param {{source: object, token?: string}} options - check options.
|
|
1038
|
+
* @returns {Promise<{id: string, label: string, status: 'up-to-date'|'update-available', current: string, remote: string}>} check result.
|
|
1039
|
+
*/
|
|
1040
|
+
export async function checkGitSource({ source, token = '' } = {}) {
|
|
1041
|
+
if (source?.kind !== 'git') throw new Error('只有 Git 来源可以检查更新')
|
|
1042
|
+
const repo = parseRepoUrl(source.url)
|
|
1043
|
+
const current = typeof source.sha === 'string' ? source.sha : ''
|
|
1044
|
+
const branch = source.branch ?? 'main'
|
|
1045
|
+
let remote
|
|
1046
|
+
try {
|
|
1047
|
+
remote = await resolveRemoteSha({ repo, branch, token })
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
// The install recorded an archive-based identity when the commits API was
|
|
1050
|
+
// unavailable (no token, rate limit, GitLab without a readable commit).
|
|
1051
|
+
// Compare like with like rather than reporting a permanent error.
|
|
1052
|
+
if (!current.startsWith('archive:')) throw error
|
|
1053
|
+
const archive = await fetchBuffer(archiveUrlOf(repo, branch), providerHeaders(repo.provider, token))
|
|
1054
|
+
remote = `archive:${createHash('sha256').update(archive).digest('hex').slice(0, 16)}`
|
|
1055
|
+
}
|
|
1056
|
+
const changed = current.length === 0 || current !== remote
|
|
1057
|
+
return {
|
|
1058
|
+
id: source.id,
|
|
1059
|
+
label: typeof source.label === 'string' ? source.label : source.url,
|
|
1060
|
+
status: changed ? 'update-available' : 'up-to-date',
|
|
1061
|
+
current,
|
|
1062
|
+
remote,
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* Delete the skill directories one source installed, skipping shared names.
|
|
1068
|
+
* @param {{source: object, root?: string, skipSkills?: string[]}} options - removal options.
|
|
1069
|
+
* @returns {Promise<{removed: string[], skipped: string[]}>} removal outcome.
|
|
1070
|
+
*/
|
|
1071
|
+
export async function removeSourceSkills({ source, root, skipSkills = [] } = {}) {
|
|
1072
|
+
const base = typeof root === 'string' && root.length > 0 ? root : librarySkillsRoot()
|
|
1073
|
+
const skip = new Set((Array.isArray(skipSkills) ? skipSkills : []).map((name) => slugify(name)).filter((name) => name.length > 0))
|
|
1074
|
+
const removed = []
|
|
1075
|
+
const skipped = []
|
|
1076
|
+
for (const name of Array.isArray(source?.skills) ? source.skills : []) {
|
|
1077
|
+
const safe = slugify(name)
|
|
1078
|
+
if (safe.length === 0) continue
|
|
1079
|
+
if (skip.has(safe)) {
|
|
1080
|
+
skipped.push(safe)
|
|
1081
|
+
continue
|
|
1082
|
+
}
|
|
1083
|
+
const dir = join(base, safe)
|
|
1084
|
+
try {
|
|
1085
|
+
await stat(dir)
|
|
1086
|
+
} catch {
|
|
1087
|
+
continue
|
|
1088
|
+
}
|
|
1089
|
+
await rm(dir, { recursive: true, force: true })
|
|
1090
|
+
removed.push(safe)
|
|
1091
|
+
}
|
|
1092
|
+
return { removed, skipped }
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/**
|
|
1096
|
+
* Read every skill currently on disk in the library.
|
|
1097
|
+
*
|
|
1098
|
+
* The registry cannot answer this: the library provider is registered per
|
|
1099
|
+
* Agent, so a global catalog read legitimately returns nothing. The panel needs
|
|
1100
|
+
* the on-disk truth instead, which is what this returns.
|
|
1101
|
+
*
|
|
1102
|
+
* @param {{root?: string}} [options] - listing options.
|
|
1103
|
+
* @returns {Promise<Array<{name: string, description: string, path: string, dir: string, modelInvocable: boolean, userInvocable: boolean, digest: string, whenToUse?: string}>>} skills sorted by name.
|
|
1104
|
+
*/
|
|
1105
|
+
export async function listLibrarySkills({ root } = {}) {
|
|
1106
|
+
const base = typeof root === 'string' && root.length > 0 ? root : librarySkillsRoot()
|
|
1107
|
+
let entries
|
|
1108
|
+
try {
|
|
1109
|
+
entries = await readdir(base, { withFileTypes: true })
|
|
1110
|
+
} catch {
|
|
1111
|
+
return []
|
|
1112
|
+
}
|
|
1113
|
+
const out = []
|
|
1114
|
+
for (const entry of entries) {
|
|
1115
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
|
|
1116
|
+
const dir = join(base, entry.name)
|
|
1117
|
+
const file = join(dir, 'SKILL.md')
|
|
1118
|
+
let text
|
|
1119
|
+
try {
|
|
1120
|
+
text = await readFile(file, 'utf8')
|
|
1121
|
+
} catch {
|
|
1122
|
+
continue
|
|
1123
|
+
}
|
|
1124
|
+
const parsed = parseSkillDocument(text)
|
|
1125
|
+
const declared = typeof parsed.meta.name === 'string' ? parsed.meta.name.trim() : ''
|
|
1126
|
+
const name = /^[a-z0-9]+(-[a-z0-9]+)*$/.test(declared) ? declared : /^[a-z0-9]+(-[a-z0-9]+)*$/.test(entry.name) ? entry.name : ''
|
|
1127
|
+
if (name.length === 0) continue
|
|
1128
|
+
const description = typeof parsed.meta.description === 'string' ? parsed.meta.description.trim() : ''
|
|
1129
|
+
const whenToUse = typeof parsed.meta.whenToUse === 'string' ? parsed.meta.whenToUse.trim() : ''
|
|
1130
|
+
out.push({
|
|
1131
|
+
name,
|
|
1132
|
+
description,
|
|
1133
|
+
...(whenToUse.length > 0 ? { whenToUse } : {}),
|
|
1134
|
+
path: file,
|
|
1135
|
+
dir,
|
|
1136
|
+
modelInvocable: parsed.meta['disable-model-invocation'] !== 'true',
|
|
1137
|
+
userInvocable: parsed.meta['user-invocable'] !== 'false',
|
|
1138
|
+
digest: bundleDigest([{ path: 'SKILL.md', data: text }]),
|
|
1139
|
+
})
|
|
1140
|
+
}
|
|
1141
|
+
out.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
|
|
1142
|
+
return out
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* Delete one skill directory from the library.
|
|
1147
|
+
* @param {{root?: string, name: string}} options - removal options.
|
|
1148
|
+
* @returns {Promise<boolean>} whether a directory was removed.
|
|
1149
|
+
*/
|
|
1150
|
+
export async function removeSkillDir({ root, name } = {}) {
|
|
1151
|
+
const base = typeof root === 'string' && root.length > 0 ? root : librarySkillsRoot()
|
|
1152
|
+
const safe = slugify(name)
|
|
1153
|
+
if (safe.length === 0) return false
|
|
1154
|
+
const dir = join(base, safe)
|
|
1155
|
+
try {
|
|
1156
|
+
await stat(dir)
|
|
1157
|
+
} catch {
|
|
1158
|
+
return false
|
|
1159
|
+
}
|
|
1160
|
+
await rm(dir, { recursive: true, force: true })
|
|
1161
|
+
return true
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/** Copy one directory tree (used by tests and future local-source support). */
|
|
1165
|
+
export async function copyTree(from, to) {
|
|
1166
|
+
await mkdir(to, { recursive: true })
|
|
1167
|
+
await cp(from, to, { recursive: true })
|
|
1168
|
+
}
|