@xi4z/dsh-utils-utils-agents 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/lib/git.d.ts +87 -0
  3. package/lib/git.js +403 -0
  4. package/lib/git.js.map +1 -0
  5. package/lib/global-repo.d.ts +57 -0
  6. package/lib/global-repo.js +301 -0
  7. package/lib/global-repo.js.map +1 -0
  8. package/lib/index.d.ts +111 -0
  9. package/lib/index.js +470 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/legacy.d.ts +30 -0
  12. package/lib/legacy.js +141 -0
  13. package/lib/legacy.js.map +1 -0
  14. package/lib/native.d.ts +74 -0
  15. package/lib/native.js +232 -0
  16. package/lib/native.js.map +1 -0
  17. package/lib/presets.d.ts +34 -0
  18. package/lib/presets.js +312 -0
  19. package/lib/presets.js.map +1 -0
  20. package/lib/shared.d.ts +105 -0
  21. package/lib/shared.js +507 -0
  22. package/lib/shared.js.map +1 -0
  23. package/lib/skill-discovery.d.ts +52 -0
  24. package/lib/skill-discovery.js +850 -0
  25. package/lib/skill-discovery.js.map +1 -0
  26. package/lib/skill-panel.d.ts +36 -0
  27. package/lib/skill-panel.js +409 -0
  28. package/lib/skill-panel.js.map +1 -0
  29. package/lib/update.d.ts +129 -0
  30. package/lib/update.js +507 -0
  31. package/lib/update.js.map +1 -0
  32. package/lib/util.d.ts +215 -0
  33. package/lib/util.js +475 -0
  34. package/lib/util.js.map +1 -0
  35. package/locale/en.json +6 -0
  36. package/locale/zh.json +6 -0
  37. package/package.json +52 -3
  38. package/src/git.ts +444 -0
  39. package/src/global-repo.ts +343 -0
  40. package/src/index.ts +522 -0
  41. package/src/legacy.ts +170 -0
  42. package/src/native.ts +291 -0
  43. package/src/presets.ts +329 -0
  44. package/src/shared.ts +589 -0
  45. package/src/skill-discovery.ts +917 -0
  46. package/src/skill-panel.ts +488 -0
  47. package/src/update.ts +574 -0
  48. package/src/util.ts +570 -0
  49. package/README.md +0 -3
package/src/shared.ts ADDED
@@ -0,0 +1,589 @@
1
+ /**
2
+ * Shared preset sources for the utils-agents panel.
3
+ *
4
+ * A skill repository may carry a ".dsh" directory that mirrors part of the DSH
5
+ * home, so presets can travel with the skills instead of being copied by hand.
6
+ * This module discovers those presets and copies them into
7
+ * "$DSH_HOME/.agent-presets"; the existing legacy bridge then registers the
8
+ * result as real Agent presets.
9
+ *
10
+ * Accepted layouts inside one repository root:
11
+ *
12
+ * - ".dsh/preset/<id>/" (canonical)
13
+ * - ".dsh/preset/" itself when it holds "preset.yml" or "agent.cordis.yml"
14
+ * - ".dsh/presets/<id>/" and ".dsh/.agent-presets/<id>/" (tolerated aliases)
15
+ * - ".dsh/<id>/" when the directory holds "preset.yml" or "agent.cordis.yml"
16
+ *
17
+ * Sources are read-only: the repository checkout is never modified. Writes are
18
+ * limited to the local preset home, and a removed source file is only deleted
19
+ * when the caller asks for a pruning sync.
20
+ *
21
+ * @module dsh-utils/utils-agents/shared
22
+ */
23
+
24
+ import { createHash } from 'node:crypto'
25
+ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises'
26
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
27
+ import type { Context } from '@deepseek-ai/cordis'
28
+ import { scanSkills } from './presets.js'
29
+ import { readRepoState, targetPath } from './git.js'
30
+ import {
31
+ BODY_LIMIT_BYTES,
32
+ IGNORED_DIRS,
33
+ AgentsError,
34
+ directoryOf,
35
+ dshHome,
36
+ errorMessage,
37
+ exists,
38
+ expandAbsolute,
39
+ insideJoin,
40
+ stringList,
41
+ agentsStorageDir,
42
+ type Options,
43
+ type PresetInfo,
44
+ } from './util.js'
45
+
46
+ /** Per-file copy ceiling; larger files are skipped, not truncated. */
47
+ const SHARED_MAX_BYTES = BODY_LIMIT_BYTES
48
+
49
+ /** Directories never copied out of a source repository. */
50
+ const IGNORED_SHARED_DIRS = new Set([...IGNORED_DIRS, '.dsh-utils'])
51
+
52
+ /** Local-only trees that a pruning sync never deletes. */
53
+ const LOCAL_ONLY_DIRS = new Set(['.dsh-utils', '.git'])
54
+
55
+ /** Ids the panel reserves for its own pseudo target. */
56
+ const RESERVED_IDS = new Set(['__global__'])
57
+
58
+ /** Status of one source preset against the local preset home. */
59
+ export type SharedStatus = 'new' | 'update' | 'same' | 'invalid'
60
+
61
+ /** Where a source repository came from. */
62
+ export type SharedSourceKind = 'preset-repo' | 'global-repo' | 'skills-home' | 'extra'
63
+
64
+ /** One preset found in a shared repository. */
65
+ export interface SharedPresetView {
66
+ readonly id: string
67
+ readonly name: string
68
+ readonly description: string
69
+ readonly status: SharedStatus
70
+ readonly sourceKind: SharedSourceKind
71
+ readonly sourceRoot: string
72
+ readonly sourcePath: string
73
+ readonly targetPath: string
74
+ readonly skills: number
75
+ readonly files: number
76
+ readonly managed: boolean
77
+ readonly lastSyncAt: string | null
78
+ readonly reason?: string
79
+ }
80
+
81
+ /** One repository root that was scanned. */
82
+ export interface SharedSourceView {
83
+ readonly path: string
84
+ readonly kind: SharedSourceKind
85
+ readonly exists: boolean
86
+ readonly presets: SharedPresetView[]
87
+ }
88
+
89
+ /** The complete shared-preset view returned to the browser. */
90
+ export interface SharedListView {
91
+ readonly localRoot: string
92
+ readonly sources: SharedSourceView[]
93
+ }
94
+
95
+ /** One record remembered from a previous sync. */
96
+ interface ManagedPreset {
97
+ readonly source: string
98
+ readonly syncedAt: string
99
+ readonly files: string[]
100
+ }
101
+
102
+ /** The on-disk sync manifest. */
103
+ interface SharedManifest {
104
+ readonly version: 1
105
+ readonly presets: Record<string, ManagedPreset>
106
+ }
107
+
108
+ /** Outcome for one preset sync. */
109
+ export interface SharedSyncResult {
110
+ readonly id: string
111
+ readonly status: SharedStatus
112
+ readonly written: number
113
+ readonly removed: number
114
+ readonly skipped: string[]
115
+ readonly error?: string
116
+ }
117
+
118
+ /** The response of one sync request. */
119
+ export interface SharedSyncPayload {
120
+ readonly results: SharedSyncResult[]
121
+ readonly view: SharedListView
122
+ }
123
+
124
+ /** One source file to copy. */
125
+ interface SourceFile {
126
+ readonly rel: string
127
+ readonly path: string
128
+ readonly mode: number
129
+ readonly size: number
130
+ }
131
+
132
+ /**
133
+ * Scan every known repository for ".dsh" presets.
134
+ * @param ctx - host context.
135
+ * @param options - normalized settings.
136
+ * @param preset - the selected preset, whose synced checkout is also a source.
137
+ * @returns the source roots with their preset rows.
138
+ */
139
+ export async function sharedPresetView(ctx: Context, options: Options, preset: PresetInfo | null): Promise<SharedListView> {
140
+ const localRoot = join(dshHome(), '.agent-presets')
141
+ const manifest = await readManifest()
142
+ const sources: SharedSourceView[] = []
143
+ const seen = new Set<string>()
144
+ for (const source of await presetSources(options, preset)) {
145
+ const key = await canonicalPath(source.path)
146
+ if (seen.has(key)) continue
147
+ seen.add(key)
148
+ if (!(await directoryOf(source.path))) {
149
+ sources.push({ path: source.path, kind: source.kind, exists: false, presets: [] })
150
+ continue
151
+ }
152
+ sources.push({
153
+ path: source.path,
154
+ kind: source.kind,
155
+ exists: true,
156
+ presets: await discoverSourcePresets(ctx, source.path, source.kind, manifest),
157
+ })
158
+ }
159
+ return { localRoot, sources }
160
+ }
161
+
162
+ /**
163
+ * Copy the requested source presets into the DSH preset home.
164
+ * @param ctx - host context.
165
+ * @param options - normalized settings.
166
+ * @param preset - the selected preset, used to locate its repository checkout.
167
+ * @param body - request body with optional "ids" and "prune".
168
+ * @returns per-preset results plus the refreshed view.
169
+ */
170
+ export async function syncSharedPresets(
171
+ ctx: Context,
172
+ options: Options,
173
+ preset: PresetInfo | null,
174
+ body: Record<string, unknown>,
175
+ ): Promise<SharedSyncPayload> {
176
+ const requested = stringList(body.ids)
177
+ const prune = body.prune === true
178
+ const manifest = await readManifest()
179
+ const view = await sharedPresetView(ctx, options, preset)
180
+ const all = view.sources.flatMap((source) => source.presets)
181
+ const targets = requested.length === 0 ? all : all.filter((row) => requested.includes(row.id))
182
+ if (requested.length > 0 && targets.length === 0) throw new AgentsError('没有找到要同步的预设:' + requested.join(', '), 404)
183
+
184
+ const results: SharedSyncResult[] = []
185
+ for (const row of targets) {
186
+ if (row.status === 'invalid') {
187
+ results.push({ id: row.id, status: row.status, written: 0, removed: 0, skipped: [], error: row.reason ?? '预设 id 不合法' })
188
+ continue
189
+ }
190
+ try {
191
+ const previous = manifest.presets[row.id]?.files ?? []
192
+ const outcome = await copyPreset(ctx, row, prune, previous)
193
+ manifest.presets[row.id] = { source: row.sourceRoot, syncedAt: new Date().toISOString(), files: outcome.files }
194
+ results.push({ id: row.id, status: row.status, written: outcome.written, removed: outcome.removed, skipped: outcome.skipped })
195
+ } catch (error) {
196
+ const message = errorMessage(error)
197
+ ctx.logger.warn('utils-agents: cannot sync shared preset ' + row.id + ': ' + message)
198
+ results.push({ id: row.id, status: row.status, written: 0, removed: 0, skipped: [], error: message })
199
+ }
200
+ }
201
+ if (results.some((result) => result.error === undefined)) await writeManifest(manifest)
202
+ return { results, view: await sharedPresetView(ctx, options, preset) }
203
+ }
204
+
205
+ /** The storage path of the shared-preset manifest. */
206
+ export function sharedManifestPath(): string {
207
+ return join(agentsStorageDir(), 'shared-presets.json')
208
+ }
209
+
210
+ /** Normalize one preset directory name into a safe id, or null. */
211
+ export function sharedPresetId(name: string): string | null {
212
+ if (name === '' || name === '.' || name === '..') return null
213
+ if (name.startsWith('.') || RESERVED_IDS.has(name)) return null
214
+ if (name.includes('/') || name.includes('\\') || name.includes(String.fromCharCode(0))) return null
215
+ return name
216
+ }
217
+
218
+ /** Candidate directories inside one scanned repository. */
219
+ async function sharedLayouts(root: string): Promise<string[]> {
220
+ const candidates = [
221
+ join(root, '.dsh', 'preset'),
222
+ join(root, '.dsh', 'presets'),
223
+ join(root, '.dsh', '.agent-presets'),
224
+ join(root, '.dsh'),
225
+ ]
226
+ const out: string[] = []
227
+ for (const candidate of candidates) {
228
+ if (await directoryOf(candidate)) out.push(candidate)
229
+ }
230
+ return out
231
+ }
232
+
233
+ /** Discover the presets inside one repository root. */
234
+ async function discoverSourcePresets(
235
+ ctx: Context,
236
+ root: string,
237
+ kind: SharedSourceKind,
238
+ manifest: SharedManifest,
239
+ ): Promise<SharedPresetView[]> {
240
+ const rows: SharedPresetView[] = []
241
+ const seen = new Set<string>()
242
+ const seenPaths = new Set<string>()
243
+ for (const layout of await sharedLayouts(root)) {
244
+ let entries
245
+ try {
246
+ entries = await readdir(layout, { withFileTypes: true })
247
+ } catch (error) {
248
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.debug('utils-agents: cannot read shared layout ' + layout + ': ' + errorMessage(error))
249
+ continue
250
+ }
251
+ entries.sort((left, right) => left.name.localeCompare(right.name))
252
+ for (const entry of entries) {
253
+ if (!entry.isDirectory()) continue
254
+ if (entry.name.startsWith('.')) continue
255
+ const sourcePath = join(layout, entry.name)
256
+ // Every candidate must carry the markers of a preset, so a skills/ tree
257
+ // inside the layout is not mistaken for a preset.
258
+ if (!(await looksLikePreset(sourcePath))) continue
259
+ const id = sharedPresetId(entry.name)
260
+ const pathKey = await canonicalPath(sourcePath)
261
+ if (id === null || seen.has(id) || seenPaths.has(pathKey)) continue
262
+ seen.add(id)
263
+ seenPaths.add(pathKey)
264
+ rows.push(await describeSourcePreset(ctx, id, sourcePath, root, kind, manifest))
265
+ }
266
+ // ".dsh/preset/" may also be a single preset directory instead of a parent
267
+ // of preset directories; take its display id from preset.yml when present.
268
+ if (await looksLikePreset(layout)) {
269
+ const meta = await readSourceMeta(layout)
270
+ const id = sharedPresetId(meta.id === '' ? basename(layout) : meta.id)
271
+ const pathKey = await canonicalPath(layout)
272
+ if (id !== null && !seen.has(id) && !seenPaths.has(pathKey)) {
273
+ seen.add(id)
274
+ seenPaths.add(pathKey)
275
+ rows.push(await describeSourcePreset(ctx, id, layout, root, kind, manifest))
276
+ }
277
+ }
278
+ }
279
+ return rows
280
+ }
281
+
282
+ /** Whether a directory holds the markers of a preset. */
283
+ async function looksLikePreset(path: string): Promise<boolean> {
284
+ return (await exists(join(path, 'preset.yml'))) || (await exists(join(path, 'agent.cordis.yml')))
285
+ }
286
+
287
+ /** Build one browser row for a source preset. */
288
+ async function describeSourcePreset(
289
+ ctx: Context,
290
+ id: string,
291
+ sourcePath: string,
292
+ sourceRoot: string,
293
+ kind: SharedSourceKind,
294
+ manifest: SharedManifest,
295
+ ): Promise<SharedPresetView> {
296
+ const meta = await readSourceMeta(sourcePath)
297
+ const skills = await scanSkills(ctx, sourcePath)
298
+ const files = await collectFiles(ctx, sourcePath)
299
+ const targetPath = join(dshHome(), '.agent-presets', id)
300
+ const managed = manifest.presets[id] !== undefined
301
+ const status = await comparePreset(files, targetPath)
302
+ return {
303
+ id,
304
+ name: meta.name === '' ? id : meta.name,
305
+ description: meta.description,
306
+ status,
307
+ sourceKind: kind,
308
+ sourceRoot,
309
+ sourcePath,
310
+ targetPath,
311
+ skills: skills.filter((skill) => skill.enabled).length,
312
+ files: files.length,
313
+ managed,
314
+ lastSyncAt: managed ? manifest.presets[id].syncedAt : null,
315
+ }
316
+ }
317
+
318
+ /** Read the preset display metadata without a YAML dependency. */
319
+ async function readSourceMeta(presetPath: string): Promise<{ id: string; name: string; description: string }> {
320
+ let text
321
+ try {
322
+ text = await readFile(join(presetPath, 'preset.yml'), 'utf8')
323
+ } catch {
324
+ return { id: '', name: '', description: '' }
325
+ }
326
+ const values: Record<string, string> = {}
327
+ for (const line of text.split(/\r?\n/)) {
328
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/.exec(line)
329
+ if (match === null) continue
330
+ const value = match[2].trim()
331
+ values[match[1]] = value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])
332
+ ? value.slice(1, -1)
333
+ : value
334
+ }
335
+ return { id: values.id ?? '', name: values.name ?? '', description: values.description ?? '' }
336
+ }
337
+
338
+ /** Compare every source file with its local copy. */
339
+ async function comparePreset(files: SourceFile[], targetPath: string): Promise<SharedStatus> {
340
+ if (!(await directoryOf(targetPath))) return 'new'
341
+ for (const file of files) {
342
+ const target = join(targetPath, file.rel)
343
+ let info
344
+ try {
345
+ info = await lstat(target)
346
+ } catch {
347
+ return 'update'
348
+ }
349
+ if (!info.isFile() || info.isSymbolicLink() || info.size !== file.size) return 'update'
350
+ if (await hashFile(target) !== await hashFile(file.path)) return 'update'
351
+ }
352
+ return 'same'
353
+ }
354
+
355
+ /** Every regular file under one source preset, relative to its root. */
356
+ async function collectFiles(ctx: Context, root: string): Promise<SourceFile[]> {
357
+ const out: SourceFile[] = []
358
+ await walkSource(root, root, ctx, out)
359
+ return out.sort((left, right) => left.rel.localeCompare(right.rel))
360
+ }
361
+
362
+ /** Recursively collect regular files, skipping symlinks and ignored trees. */
363
+ async function walkSource(root: string, dir: string, ctx: Context, out: SourceFile[]): Promise<void> {
364
+ let entries
365
+ try {
366
+ entries = await readdir(dir, { withFileTypes: true })
367
+ } catch (error) {
368
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.debug('utils-agents: cannot scan shared preset ' + dir + ': ' + errorMessage(error))
369
+ return
370
+ }
371
+ entries.sort((left, right) => left.name.localeCompare(right.name))
372
+ for (const entry of entries) {
373
+ if (IGNORED_SHARED_DIRS.has(entry.name)) continue
374
+ const path = join(dir, entry.name)
375
+ if (entry.isDirectory()) {
376
+ await walkSource(root, path, ctx, out)
377
+ continue
378
+ }
379
+ if (!entry.isFile()) continue
380
+ let info
381
+ try {
382
+ info = await lstat(path)
383
+ } catch {
384
+ continue
385
+ }
386
+ if (!info.isFile() || info.isSymbolicLink()) continue
387
+ if (info.size > SHARED_MAX_BYTES) {
388
+ ctx.logger.warn('utils-agents: skipping oversized shared preset file ' + path)
389
+ continue
390
+ }
391
+ out.push({ rel: relative(root, path).split(sep).join('/'), path, mode: info.mode & 0o777, size: info.size })
392
+ }
393
+ }
394
+
395
+ /** Copy one preset into $DSH_HOME/.agent-presets/<id>. */
396
+ async function copyPreset(
397
+ ctx: Context,
398
+ row: SharedPresetView,
399
+ prune: boolean,
400
+ previous: string[],
401
+ ): Promise<{ written: number; removed: number; skipped: string[]; files: string[] }> {
402
+ if (sharedPresetId(row.id) === null) throw new AgentsError('预设 id 不合法:' + row.id, 400)
403
+ const targetRoot = join(dshHome(), '.agent-presets', row.id)
404
+ await mkdir(targetRoot, { recursive: true, mode: 0o755 })
405
+ const files = await collectFiles(ctx, row.sourcePath)
406
+ const skipped: string[] = []
407
+ let written = 0
408
+ for (const file of files) {
409
+ const target = insideJoin(targetRoot, file.rel)
410
+ await mkdir(dirname(target), { recursive: true, mode: 0o755 })
411
+ if (await sameContent(file.path, target)) continue
412
+ const content = await readFile(file.path)
413
+ await writeAtomic(target, content, file.mode)
414
+ written += 1
415
+ }
416
+ const removed = prune ? await prunePreset(ctx, targetRoot, files, previous) : 0
417
+ return { written, removed, skipped, files: files.map((file) => file.rel) }
418
+ }
419
+
420
+ /** Whether two files already carry identical bytes. */
421
+ async function sameContent(source: string, target: string): Promise<boolean> {
422
+ try {
423
+ const info = await lstat(target)
424
+ if (!info.isFile() || info.isSymbolicLink()) return false
425
+ if (info.size !== (await lstat(source)).size) return false
426
+ return await hashFile(source) === await hashFile(target)
427
+ } catch {
428
+ return false
429
+ }
430
+ }
431
+
432
+ /** Remove files this source owned before but no longer publishes. */
433
+ async function prunePreset(ctx: Context, targetRoot: string, files: SourceFile[], previous: string[]): Promise<number> {
434
+ const keep = new Set(files.map((file) => file.rel))
435
+ const removed: string[] = []
436
+ for (const rel of previous) {
437
+ if (keep.has(rel)) continue
438
+ if (LOCAL_ONLY_DIRS.has(rel.split('/')[0])) continue
439
+ try {
440
+ const info = await lstat(insideJoin(targetRoot, rel))
441
+ if (!info.isFile() || info.isSymbolicLink()) continue
442
+ } catch {
443
+ continue
444
+ }
445
+ removed.push(rel)
446
+ }
447
+ for (const rel of removed) await rm(insideJoin(targetRoot, rel), { force: true })
448
+ await removeEmptyDirs(ctx, targetRoot, targetRoot)
449
+ return removed.length
450
+ }
451
+
452
+ /** Remove directories left empty by a pruning sync. */
453
+ async function removeEmptyDirs(ctx: Context, root: string, dir: string): Promise<void> {
454
+ let entries
455
+ try {
456
+ entries = await readdir(dir, { withFileTypes: true })
457
+ } catch {
458
+ return
459
+ }
460
+ for (const entry of entries) {
461
+ if (!entry.isDirectory() || entry.name === '.git') continue
462
+ const path = join(dir, entry.name)
463
+ if (LOCAL_ONLY_DIRS.has(relative(root, path).split(sep)[0])) continue
464
+ await removeEmptyDirs(ctx, root, path)
465
+ }
466
+ if (dir === root) return
467
+ try {
468
+ const remaining = await readdir(dir)
469
+ if (remaining.length === 0) await rm(dir, { recursive: true, force: true })
470
+ } catch (error) {
471
+ ctx.logger.debug('utils-agents: cannot remove empty shared preset directory ' + dir + ': ' + errorMessage(error))
472
+ }
473
+ }
474
+
475
+ /** Write one file through a temporary sibling, then rename. */
476
+ async function writeAtomic(target: string, content: Buffer, mode: number): Promise<void> {
477
+ const temp = join(dirname(target), '.' + basename(target) + '.' + process.pid.toString(36) + Math.random().toString(36).slice(2, 8) + '.tmp')
478
+ try {
479
+ await writeFile(temp, content, { mode: mode === 0 ? 0o644 : mode, flag: 'wx' })
480
+ await rename(temp, target)
481
+ } catch (error) {
482
+ await rm(temp, { force: true })
483
+ throw error
484
+ }
485
+ }
486
+
487
+ /** sha256 of one file. */
488
+ async function hashFile(path: string): Promise<string> {
489
+ const content = await readFile(path)
490
+ return createHash('sha256').update(content).digest('hex')
491
+ }
492
+
493
+ /** The checkout the legacy global skill-repository route syncs into. */
494
+ async function legacySkillRepoRoot(): Promise<string> {
495
+ try {
496
+ const raw = JSON.parse(await readFile(join(dshHome(), 'storages', 'dsh-utils-ui.json'), 'utf8')) as unknown
497
+ const record = raw !== null && typeof raw === 'object' ? raw as Record<string, unknown> : {}
498
+ if (typeof record.targetDir === 'string' && record.targetDir.trim() !== '') return expandAbsolute(record.targetDir)
499
+ } catch {
500
+ // Missing or malformed legacy state falls back to the shipped default.
501
+ }
502
+ return join(dshHome(), 'skills', 'herskill')
503
+ }
504
+
505
+ /** The repository roots to scan, in display order. */
506
+ async function presetSources(options: Options, preset: PresetInfo | null): Promise<Array<{ path: string; kind: SharedSourceKind }>> {
507
+ const out: Array<{ path: string; kind: SharedSourceKind }> = []
508
+ if (preset !== null) {
509
+ try {
510
+ const state = await readRepoState(preset, options)
511
+ const target = targetPath(preset, state)
512
+ if (await directoryOf(target)) out.push({ path: target, kind: 'preset-repo' })
513
+ } catch {
514
+ // A malformed repository configuration only hides that source.
515
+ }
516
+ }
517
+ const legacy = await legacySkillRepoRoot()
518
+ if (legacy !== null && await directoryOf(legacy)) out.push({ path: legacy, kind: 'global-repo' })
519
+ const skills = join(dshHome(), 'skills')
520
+ out.push({ path: skills, kind: 'skills-home' })
521
+ // The legacy global repository may live one level below (for example
522
+ // $DSH_HOME/skills/herskill); treat any child that carries .dsh as a source.
523
+ try {
524
+ const entries = await readdir(skills, { withFileTypes: true })
525
+ entries.sort((left, right) => left.name.localeCompare(right.name))
526
+ for (const entry of entries) {
527
+ if (entry.name.startsWith('.')) continue
528
+ const child = join(skills, entry.name)
529
+ if (!entry.isDirectory() && !(entry.isSymbolicLink() && await directoryOf(child))) continue
530
+ if (await directoryOf(join(child, '.dsh'))) out.push({ path: child, kind: 'skills-home' })
531
+ }
532
+ } catch {
533
+ // A missing skills home simply contributes no per-repository sources.
534
+ }
535
+ for (const raw of options.presetSourceDirs) {
536
+ try {
537
+ out.push({ path: expandAbsolute(raw), kind: 'extra' })
538
+ } catch {
539
+ // Invalid extras are ignored, matching the other path settings.
540
+ }
541
+ }
542
+ return out
543
+ }
544
+
545
+ /** Real path when it exists, resolved path otherwise. */
546
+ async function canonicalPath(path: string): Promise<string> {
547
+ try {
548
+ return await realpath(path)
549
+ } catch {
550
+ return resolve(path)
551
+ }
552
+ }
553
+
554
+ /** Read the sync manifest, tolerating a missing or broken file. */
555
+ export async function readManifest(): Promise<SharedManifest> {
556
+ let raw: unknown = null
557
+ try {
558
+ raw = JSON.parse(await readFile(sharedManifestPath(), 'utf8')) as unknown
559
+ } catch {
560
+ return { version: 1, presets: {} }
561
+ }
562
+ const record = raw !== null && typeof raw === 'object' ? raw as Record<string, unknown> : {}
563
+ const presets: Record<string, ManagedPreset> = {}
564
+ const source = record.presets !== null && typeof record.presets === 'object' ? record.presets as Record<string, unknown> : {}
565
+ for (const [id, value] of Object.entries(source)) {
566
+ if (value === null || typeof value !== 'object') continue
567
+ const entry = value as Record<string, unknown>
568
+ presets[id] = {
569
+ source: typeof entry.source === 'string' ? entry.source : '',
570
+ syncedAt: typeof entry.syncedAt === 'string' ? entry.syncedAt : '',
571
+ files: Array.isArray(entry.files) ? entry.files.filter((file): file is string => typeof file === 'string') : [],
572
+ }
573
+ }
574
+ return { version: 1, presets }
575
+ }
576
+
577
+ /** Persist the sync manifest. */
578
+ async function writeManifest(manifest: SharedManifest): Promise<void> {
579
+ await mkdir(agentsStorageDir(), { recursive: true, mode: 0o700 })
580
+ const file = sharedManifestPath()
581
+ const temp = file + '.' + process.pid.toString(36) + Math.random().toString(36).slice(2, 8) + '.tmp'
582
+ try {
583
+ await writeFile(temp, JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
584
+ await rename(temp, file)
585
+ } catch (error) {
586
+ await rm(temp, { force: true })
587
+ throw error
588
+ }
589
+ }