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

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
@@ -0,0 +1,917 @@
1
+ /**
2
+ * `utils-agents` skill-discovery half: recursive `SKILL.md` discovery in nested
3
+ * skill folders.
4
+ *
5
+ * The provider adds nested skill bundles (depth >= `minDepth`) to the skill
6
+ * catalog, leaving depth-1 discovery to the built-in filesystem provider. It
7
+ * used to be the separate `@xi4z/dsh-utils-main` component; the bundle now
8
+ * mounts it as part of `@xi4z/dsh-utils-utils-agents`.
9
+ *
10
+ * @module @xi4z/dsh-utils-utils-agents/skill-discovery
11
+ */
12
+
13
+ import { watch, type FSWatcher } from 'node:fs'
14
+ import { readdir, readFile, realpath, stat } from 'node:fs/promises'
15
+ import { homedir } from 'node:os'
16
+ import { dirname, join, resolve } from 'node:path'
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import type {
19
+ SkillCandidate,
20
+ SkillDefinition,
21
+ SkillLookupOptions,
22
+ SkillProvider,
23
+ SkillProviderControl,
24
+ SkillProviderObservation,
25
+ SkillSource,
26
+ } from '@deepseek-ai/dsh-skill'
27
+ import type {} from '@deepseek-ai/dsh-settings'
28
+
29
+ /** Provider name reported in the skill catalog. */
30
+ export const PROVIDER_NAME = 'utils-agents'
31
+
32
+ /** Ranks sit one step below the shipped filesystem provider, so flat skills win collisions. */
33
+ const RANKS = {
34
+ 'project-dsh': 110,
35
+ 'project-agents': 210,
36
+ custom: 310,
37
+ 'user-dsh': 410,
38
+ 'user-agents': 510,
39
+ } as const
40
+
41
+ const SKILL_FILE = 'SKILL.md'
42
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
43
+
44
+ export const SKILL_DISCOVERY_DEFAULTS = {
45
+ minDepth: 2,
46
+ maxDepth: 8,
47
+ watch: true,
48
+ debounceMs: 200,
49
+ pollIntervalMs: 2000,
50
+ includeProjectRoots: true,
51
+ includeUserRoots: true,
52
+ followSymlinks: false,
53
+ extraRoots: [] as string[],
54
+ ignoreDirs: ['.system', 'node_modules', '.git'],
55
+ }
56
+
57
+ /** Volatile Config fields arrive as live references; `.get()` snapshots. */
58
+ interface VolatileRef<T> {
59
+ get(): T
60
+ }
61
+
62
+ /** One setting as the Loader supplies it: a live reference, or a plain value in tests. */
63
+ type MaybeRef<T> = T | VolatileRef<T>
64
+
65
+ /** The runtime shape `apply` receives (every field volatile, every field optional). */
66
+ export interface SkillDiscoveryConfig {
67
+ readonly minDepth?: MaybeRef<number>
68
+ readonly maxDepth?: MaybeRef<number>
69
+ readonly watch?: MaybeRef<boolean>
70
+ readonly debounceMs?: MaybeRef<number>
71
+ readonly pollIntervalMs?: MaybeRef<number>
72
+ readonly includeProjectRoots?: MaybeRef<boolean>
73
+ readonly includeUserRoots?: MaybeRef<boolean>
74
+ readonly followSymlinks?: MaybeRef<boolean>
75
+ readonly extraRoots?: MaybeRef<readonly string[]>
76
+ readonly ignoreDirs?: MaybeRef<readonly string[]>
77
+ }
78
+
79
+ /** One resolved skill root in precedence order. */
80
+ interface Root {
81
+ readonly path: string
82
+ readonly source: SkillSource
83
+ readonly rank: number
84
+ }
85
+
86
+ /** Normalized options with every default applied. */
87
+ interface Options {
88
+ minDepth: number
89
+ maxDepth: number
90
+ watch: boolean
91
+ debounceMs: number
92
+ pollIntervalMs: number
93
+ includeProjectRoots: boolean
94
+ includeUserRoots: boolean
95
+ followSymlinks: boolean
96
+ extraRoots: string[]
97
+ ignoreDirs: string[]
98
+ }
99
+
100
+ /** Per-root change observation state. */
101
+ interface WatcherState {
102
+ readonly root: Root
103
+ handle: FSWatcher | undefined
104
+ polling: NodeJS.Timeout | undefined
105
+ lastSignature: string | undefined
106
+ closed: boolean
107
+ }
108
+
109
+ /** One parsed skill file: summary fields plus the Markdown body. */
110
+ interface ParsedSkill {
111
+ readonly name: string
112
+ readonly description: string
113
+ readonly whenToUse?: string
114
+ readonly invocation: { modelInvocable: boolean; userInvocable: boolean }
115
+ readonly metadata?: Readonly<Record<string, unknown>>
116
+ readonly path: string
117
+ readonly content: string
118
+ }
119
+
120
+ /**
121
+ * Register the recursive skill provider on the host `skills` registry.
122
+ * @param ctx - plugin context carrying the `skills` service.
123
+ * @param config - optional row config; see {@link normalizeConfig}.
124
+ */
125
+ export function applySkillDiscovery(ctx: Context, config?: SkillDiscoveryConfig): void {
126
+ const registry = (ctx as { skills?: Context['skills'] }).skills
127
+ if (registry === undefined || typeof registry.registerProvider !== 'function') {
128
+ ctx.logger.warn('utils-agents skills: the host provides no skill registry; nested discovery is off')
129
+ return
130
+ }
131
+ let provider: RecursiveSkillProvider | undefined
132
+ registry.registerProvider((control) => {
133
+ provider = new RecursiveSkillProvider(ctx, control, config)
134
+ return provider
135
+ })
136
+ ctx.on('settings/document-updated', () => provider?.syncOptions())
137
+ ctx.effect(function* () {
138
+ yield async () => {
139
+ await provider?.dispose()
140
+ }
141
+ }, 'utils-agents skills: watcher')
142
+ }
143
+
144
+ /** Provider that adds nested `SKILL.md` bundles to the skill catalog. */
145
+ class RecursiveSkillProvider implements SkillProvider {
146
+ readonly name = PROVIDER_NAME
147
+ private readonly ctx: Context
148
+ private readonly control: SkillProviderControl
149
+ private readonly config: SkillDiscoveryConfig | undefined
150
+ private options: Options
151
+ private readonly watchers = new Map<string, WatcherState>()
152
+ private pendingInvalidation: NodeJS.Timeout | undefined
153
+ private disposed = false
154
+
155
+ /**
156
+ * @param ctx - plugin context.
157
+ * @param control - registry registration control.
158
+ * @param config - raw row config, including Loader volatile references.
159
+ */
160
+ constructor(ctx: Context, control: SkillProviderControl, config: SkillDiscoveryConfig | undefined) {
161
+ this.ctx = ctx
162
+ this.control = control
163
+ this.config = config
164
+ this.options = normalizeConfig(ctx, config)
165
+ control.signal.addEventListener('abort', () => {
166
+ void this.dispose()
167
+ }, { once: true })
168
+ }
169
+
170
+ /**
171
+ * Discover nested skill candidates for one workspace.
172
+ * @param options - lookup options; `cwd` selects the project roots.
173
+ * @returns candidates, or an incomplete observation when a scan failed.
174
+ */
175
+ async list(options: SkillLookupOptions = {}): Promise<readonly SkillCandidate[] | SkillProviderObservation> {
176
+ this.syncOptions()
177
+ const roots = await this.roots(options.cwd)
178
+ this.observeRoots(roots)
179
+ const candidates: SkillCandidate[] = []
180
+ let complete = true
181
+ for (const root of roots) {
182
+ const scan = await scanRoot(root, this.options, this.ctx, this.name)
183
+ if (!scan.complete) complete = false
184
+ for (const candidate of scan.candidates) candidates.push(candidate)
185
+ }
186
+ return complete ? candidates : { candidates, complete }
187
+ }
188
+
189
+ /** Pick up Settings changes; the Loader updates volatile refs in place. */
190
+ syncOptions(): void {
191
+ if (this.disposed) return
192
+ let next: Options
193
+ try {
194
+ next = normalizeConfig(this.ctx, this.config)
195
+ } catch (error) {
196
+ this.ctx.logger.warn(`utils-agents skills: ignoring invalid settings: ${errorMessage(error)}`)
197
+ return
198
+ }
199
+ if (sameOptions(next, this.options)) return
200
+ this.options = next
201
+ if (this.pendingInvalidation !== undefined) {
202
+ clearTimeout(this.pendingInvalidation)
203
+ this.pendingInvalidation = undefined
204
+ }
205
+ this.closeWatchers()
206
+ this.control.invalidate()
207
+ }
208
+
209
+ /**
210
+ * Load one nested skill body from its candidate.
211
+ * @param candidate - winning candidate returned by {@link list}.
212
+ * @param options - lookup options whose signal cancels reads.
213
+ * @returns the full definition, or undefined when the file vanished.
214
+ */
215
+ async get(candidate: SkillCandidate, options: SkillLookupOptions = {}): Promise<SkillDefinition | undefined> {
216
+ const path = candidate.path
217
+ if (path === undefined) throw new TypeError(`utils-agents skills: candidate "${candidate.name}" carries no path`)
218
+ const parsed = await readSkill(path, options.signal)
219
+ if (parsed === undefined) return undefined
220
+ if (parsed.name !== candidate.name) {
221
+ throw new Error(`skill file ${candidate.path} now declares "${parsed.name}" but was discovered as "${candidate.name}"`)
222
+ }
223
+ return {
224
+ name: parsed.name,
225
+ description: parsed.description,
226
+ ...(parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {}),
227
+ invocation: parsed.invocation,
228
+ source: candidate.source,
229
+ provider: this.name,
230
+ resourceBase: { kind: 'directory', path: dirname(path) },
231
+ path: parsed.path,
232
+ content: parsed.content,
233
+ ...(parsed.metadata !== undefined ? { metadata: parsed.metadata } : {}),
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Resolve the standard skill roots for a workspace.
239
+ * @param cwd - session working directory.
240
+ * @returns de-duplicated roots in precedence order.
241
+ */
242
+ async roots(cwd: string | undefined): Promise<Root[]> {
243
+ const roots: Root[] = []
244
+ if (this.options.includeProjectRoots && typeof cwd === 'string' && cwd.length > 0) {
245
+ const projectRoot = await findProjectRoot(resolve(cwd), this.ctx)
246
+ roots.push({ path: join(projectRoot, '.dsh', 'skills'), source: 'project-dsh', rank: RANKS['project-dsh'] })
247
+ roots.push({ path: join(projectRoot, '.agents', 'skills'), source: 'project-agents', rank: RANKS['project-agents'] })
248
+ }
249
+ for (const path of this.options.extraRoots) {
250
+ roots.push({ path, source: 'custom', rank: RANKS.custom })
251
+ }
252
+ if (this.options.includeUserRoots) {
253
+ roots.push({ path: join(agentHome('DSH_HOME', '.dsh'), 'skills'), source: 'user-dsh', rank: RANKS['user-dsh'] })
254
+ roots.push({ path: join(agentHome('DSH_AGENTS_HOME', '.agents'), 'skills'), source: 'user-agents', rank: RANKS['user-agents'] })
255
+ }
256
+ const seen = new Set<string>()
257
+ const unique: Root[] = []
258
+ for (const root of roots) {
259
+ if (seen.has(root.path)) continue
260
+ seen.add(root.path)
261
+ unique.push(root)
262
+ }
263
+ return unique
264
+ }
265
+
266
+ /**
267
+ * Start a watcher per known root so a new nested skill invalidates the cache.
268
+ * @param roots - resolved roots from {@link roots}.
269
+ */
270
+ observeRoots(roots: readonly Root[]): void {
271
+ if (!this.options.watch || this.disposed) return
272
+ for (const root of roots) {
273
+ if (this.watchers.has(root.path)) continue
274
+ const watcher: WatcherState = { root, handle: undefined, polling: undefined, lastSignature: undefined, closed: false }
275
+ this.watchers.set(root.path, watcher)
276
+ void this.openWatcher(watcher)
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Open a recursive filesystem watcher, falling back to polling where the
282
+ * platform does not support recursive watches.
283
+ * @param watcher - per-root watcher state.
284
+ */
285
+ async openWatcher(watcher: WatcherState): Promise<void> {
286
+ try {
287
+ const info = await stat(watcher.root.path)
288
+ if (!info.isDirectory()) {
289
+ this.watchers.delete(watcher.root.path)
290
+ return
291
+ }
292
+ } catch {
293
+ // Retry on a later listing; the root may be created after first discovery.
294
+ this.watchers.delete(watcher.root.path)
295
+ return
296
+ }
297
+ if (this.disposed || watcher.closed) return
298
+ try {
299
+ const handle = watch(watcher.root.path, { recursive: true, persistent: false }, () => this.scheduleInvalidation())
300
+ handle.on('error', () => {
301
+ handle.close()
302
+ watcher.handle = undefined
303
+ this.startPolling(watcher)
304
+ })
305
+ watcher.handle = handle
306
+ } catch {
307
+ this.startPolling(watcher)
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Poll a root's nested skill signature when recursive watching is unavailable.
313
+ * @param watcher - per-root watcher state.
314
+ */
315
+ startPolling(watcher: WatcherState): void {
316
+ if (this.disposed || watcher.closed || watcher.polling !== undefined) return
317
+ const tick = async (): Promise<void> => {
318
+ const signature = await scanRootSignature(watcher.root, this.options, this.ctx)
319
+ if (watcher.lastSignature === undefined) {
320
+ watcher.lastSignature = signature
321
+ return
322
+ }
323
+ if (signature !== watcher.lastSignature) {
324
+ watcher.lastSignature = signature
325
+ this.scheduleInvalidation()
326
+ }
327
+ }
328
+ void tick()
329
+ watcher.polling = setInterval(() => void tick(), this.options.pollIntervalMs)
330
+ watcher.polling.unref()
331
+ }
332
+
333
+ /** Debounce a catalog invalidation burst into one refresh. */
334
+ scheduleInvalidation(): void {
335
+ if (this.disposed || this.pendingInvalidation !== undefined) return
336
+ this.pendingInvalidation = setTimeout(() => {
337
+ this.pendingInvalidation = undefined
338
+ this.control.invalidate()
339
+ }, this.options.debounceMs)
340
+ this.pendingInvalidation.unref()
341
+ }
342
+
343
+ /** Stop every watcher and timer owned by this registration. */
344
+ async dispose(): Promise<void> {
345
+ if (this.disposed) return
346
+ this.disposed = true
347
+ if (this.pendingInvalidation !== undefined) {
348
+ clearTimeout(this.pendingInvalidation)
349
+ this.pendingInvalidation = undefined
350
+ }
351
+ this.closeWatchers()
352
+ }
353
+
354
+ /** Close watcher handles and polling timers; the next listing opens fresh ones. */
355
+ closeWatchers(): void {
356
+ for (const watcher of this.watchers.values()) {
357
+ watcher.closed = true
358
+ watcher.handle?.close()
359
+ watcher.handle = undefined
360
+ if (watcher.polling !== undefined) {
361
+ clearInterval(watcher.polling)
362
+ watcher.polling = undefined
363
+ }
364
+ }
365
+ this.watchers.clear()
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Depth-limited recursive scan of one skill root for nested `SKILL.md` files.
371
+ * @param root - resolved root descriptor.
372
+ * @param options - normalized plugin options.
373
+ * @param ctx - plugin context for warnings.
374
+ * @returns candidates plus whether the scan was complete.
375
+ */
376
+ async function scanRoot(
377
+ root: Root,
378
+ options: Options,
379
+ ctx: Context,
380
+ providerName: string,
381
+ ): Promise<{ candidates: SkillCandidate[]; complete: boolean }> {
382
+ const candidates: SkillCandidate[] = []
383
+ let complete = true
384
+ const stack: { dir: string; depth: number }[] = [{ dir: root.path, depth: 0 }]
385
+ const visited = new Set<string>()
386
+ while (stack.length > 0) {
387
+ const current = stack.pop() as { dir: string; depth: number }
388
+ let entries
389
+ try {
390
+ entries = await readdir(current.dir, { withFileTypes: true })
391
+ } catch (error) {
392
+ if (!isAbsent(error)) {
393
+ complete = false
394
+ ctx.logger.warn(`utils-agents skills: cannot read ${current.dir}: ${errorMessage(error)}`)
395
+ }
396
+ continue
397
+ }
398
+ if (current.depth >= options.minDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
399
+ const file = join(current.dir, SKILL_FILE)
400
+ const parsed = await readSkillCandidate(file, root, ctx, providerName)
401
+ if (parsed !== undefined) candidates.push(parsed)
402
+ }
403
+ if (current.depth >= options.maxDepth) continue
404
+ for (const entry of entries) {
405
+ const child = join(current.dir, entry.name)
406
+ if (entry.isDirectory()) {
407
+ if (isIgnored(entry.name, options)) continue
408
+ stack.push({ dir: child, depth: current.depth + 1 })
409
+ continue
410
+ }
411
+ if (!entry.isSymbolicLink() || !options.followSymlinks) continue
412
+ try {
413
+ const info = await stat(child)
414
+ if (!info.isDirectory()) continue
415
+ const real = await realpath(child)
416
+ if (visited.has(real)) continue
417
+ visited.add(real)
418
+ stack.push({ dir: child, depth: current.depth + 1 })
419
+ } catch (error) {
420
+ ctx.logger.warn(`utils-agents skills: cannot follow ${child}: ${errorMessage(error)}`)
421
+ }
422
+ }
423
+ }
424
+ return { candidates, complete }
425
+ }
426
+
427
+ /**
428
+ * Read and validate one nested skill file into a provider candidate.
429
+ * @param path - absolute `SKILL.md` path.
430
+ * @param root - root descriptor supplying source and rank.
431
+ * @param ctx - plugin context for warnings.
432
+ * @returns candidate, or undefined when the file is not a valid skill.
433
+ */
434
+ async function readSkillCandidate(
435
+ path: string,
436
+ root: Root,
437
+ ctx: Context,
438
+ providerName: string,
439
+ ): Promise<SkillCandidate | undefined> {
440
+ let info
441
+ try {
442
+ info = await stat(path)
443
+ } catch (error) {
444
+ if (isAbsent(error)) return undefined
445
+ ctx.logger.warn(`utils-agents skills: cannot stat ${path}: ${errorMessage(error)}`)
446
+ return undefined
447
+ }
448
+ if (!info.isFile()) return undefined
449
+ let parsed: ParsedSkill | undefined
450
+ try {
451
+ parsed = await readSkill(path)
452
+ } catch (error) {
453
+ ctx.logger.warn(`skill file ${path} ignored: ${errorMessage(error)}`)
454
+ return undefined
455
+ }
456
+ if (parsed === undefined) return undefined
457
+ return {
458
+ name: parsed.name,
459
+ description: parsed.description,
460
+ ...(parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {}),
461
+ invocation: parsed.invocation,
462
+ provider: providerName,
463
+ source: root.source,
464
+ rank: root.rank,
465
+ locator: { path, directory: dirname(path) },
466
+ resourceBase: { kind: 'directory', path: dirname(path) },
467
+ path,
468
+ ...(parsed.metadata !== undefined ? { metadata: parsed.metadata } : {}),
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Read and parse one skill file.
474
+ * @param path - absolute `SKILL.md` path.
475
+ * @param signal - optional abort signal.
476
+ * @returns parsed summary, or undefined when the file is missing or invalid.
477
+ */
478
+ async function readSkill(path: string, signal?: AbortSignal): Promise<ParsedSkill | undefined> {
479
+ signal?.throwIfAborted()
480
+ let resolvedPath: string
481
+ let raw: string
482
+ try {
483
+ resolvedPath = await realpath(path)
484
+ raw = await readFile(resolvedPath, { encoding: 'utf8', signal })
485
+ } catch (error) {
486
+ signal?.throwIfAborted()
487
+ if (isAbsent(error)) return undefined
488
+ throw error
489
+ }
490
+ signal?.throwIfAborted()
491
+ const frontmatter = parseFrontmatter(raw)
492
+ if (frontmatter === undefined) return undefined
493
+ const data = frontmatter.data
494
+ const skillName = stringField(data, 'name')
495
+ const description = stringField(data, 'description')
496
+ if (skillName === undefined || description === undefined) return undefined
497
+ if (!SKILL_NAME.test(skillName)) {
498
+ throw new Error(`invalid skill name "${skillName}"`)
499
+ }
500
+ const whenToUse = stringField(data, 'whenToUse')
501
+ const metadata = data.metadata
502
+ return {
503
+ name: skillName,
504
+ description,
505
+ ...(whenToUse !== undefined ? { whenToUse } : {}),
506
+ invocation: parseInvocationPolicy(data),
507
+ ...(typeof metadata === 'object' && metadata !== null && !Array.isArray(metadata) ? { metadata: metadata as Record<string, unknown> } : {}),
508
+ path: resolvedPath,
509
+ content: frontmatter.body.trim(),
510
+ }
511
+ }
512
+
513
+ /** One frontmatter parse result: the parsed field map and the Markdown body. */
514
+ interface Frontmatter {
515
+ readonly data: Record<string, unknown>
516
+ readonly body: string
517
+ }
518
+
519
+ /**
520
+ * Extract the YAML frontmatter block and Markdown body.
521
+ * @param raw - whole file text.
522
+ * @returns parsed data and body, or undefined when no frontmatter exists.
523
+ */
524
+ function parseFrontmatter(raw: string): Frontmatter | undefined {
525
+ const firstLineEnd = raw.indexOf('\n')
526
+ if (firstLineEnd < 0) return undefined
527
+ if (raw.slice(0, firstLineEnd).replace(/\r$/, '') !== '---') return undefined
528
+ const start = firstLineEnd + 1
529
+ const closing = findClosingFrontmatter(raw, start)
530
+ if (closing === undefined) return undefined
531
+ const data = parseFrontmatterData(raw.slice(start, closing.start))
532
+ return { data, body: raw.slice(closing.bodyStart) }
533
+ }
534
+
535
+ /**
536
+ * Locate the closing `---` line.
537
+ * @param raw - whole file text.
538
+ * @param start - offset just after the opening delimiter.
539
+ * @returns closing offsets, or undefined when unterminated.
540
+ */
541
+ function findClosingFrontmatter(raw: string, start: number): { start: number; bodyStart: number } | undefined {
542
+ let lineStart = start
543
+ while (lineStart <= raw.length) {
544
+ const nextNewline = raw.indexOf('\n', lineStart)
545
+ const lineEnd = nextNewline < 0 ? raw.length : nextNewline
546
+ if (raw.slice(lineStart, lineEnd).replace(/\r$/, '') === '---') {
547
+ return { start: lineStart, bodyStart: nextNewline < 0 ? raw.length : nextNewline + 1 }
548
+ }
549
+ if (nextNewline < 0) return undefined
550
+ lineStart = nextNewline + 1
551
+ }
552
+ return undefined
553
+ }
554
+
555
+ /**
556
+ * Parse the small YAML subset skill frontmatter uses: plain and quoted scalars,
557
+ * block scalars, and booleans. Nested mappings and sequences are ignored.
558
+ * @param block - frontmatter text without delimiters.
559
+ * @returns parsed top-level fields.
560
+ */
561
+ function parseFrontmatterData(block: string): Record<string, unknown> {
562
+ const data: Record<string, unknown> = Object.create(null)
563
+ const lines = block.split(/\r?\n/)
564
+ for (let index = 0; index < lines.length; index += 1) {
565
+ const line = lines[index]
566
+ if (line.trim() === '' || line.trimStart().startsWith('#')) continue
567
+ if (/^\s/.test(line)) continue
568
+ const colon = line.indexOf(':')
569
+ if (colon <= 0) continue
570
+ const key = line.slice(0, colon).trim()
571
+ if (!/^[A-Za-z0-9_.-]+$/.test(key)) continue
572
+ const rest = line.slice(colon + 1).trim()
573
+ if (/^[|>][+-]?$/.test(rest)) {
574
+ const style = rest[0]
575
+ const collected: string[] = []
576
+ let cursor = index + 1
577
+ for (; cursor < lines.length; cursor += 1) {
578
+ const next = lines[cursor]
579
+ if (next.trim() === '') {
580
+ collected.push('')
581
+ continue
582
+ }
583
+ if (!/^\s/.test(next)) break
584
+ collected.push(next)
585
+ }
586
+ index = cursor - 1
587
+ const dedented = dedent(collected)
588
+ data[key] = style === '|' ? dedented.trim() : fold(dedented).trim()
589
+ continue
590
+ }
591
+ if (rest === '') continue
592
+ data[key] = parseScalar(rest)
593
+ }
594
+ return data
595
+ }
596
+
597
+ /**
598
+ * Remove the common indentation from block-scalar lines.
599
+ * @param lines - raw block lines.
600
+ * @returns de-indented text lines joined with newlines.
601
+ */
602
+ function dedent(lines: readonly string[]): string {
603
+ const indents = lines.filter((line) => line.length > 0).map((line) => (line.match(/^\s*/) as RegExpMatchArray)[0].length)
604
+ const minimum = indents.length > 0 ? Math.min(...indents) : 0
605
+ return lines.map((line) => line.slice(Math.min(minimum, line.length))).join('\n')
606
+ }
607
+
608
+ /**
609
+ * Fold block-scalar lines into prose.
610
+ * @param text - de-indented block text.
611
+ * @returns folded text.
612
+ */
613
+ function fold(text: string): string {
614
+ return text
615
+ .split('\n')
616
+ .map((line) => line.trim())
617
+ .filter((line) => line.length > 0)
618
+ .join(' ')
619
+ }
620
+
621
+ /**
622
+ * Parse one inline scalar value.
623
+ * @param raw - raw scalar text.
624
+ * @returns string, boolean, or null.
625
+ */
626
+ function parseScalar(raw: string): string | boolean | null {
627
+ const value = raw.trim()
628
+ if (value === '' || value === '~' || value === 'null') return null
629
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
630
+ return value.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\')
631
+ }
632
+ if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
633
+ return value.slice(1, -1).replace(/''/g, "'")
634
+ }
635
+ const lower = value.toLowerCase()
636
+ if (lower === 'true' || lower === 'yes' || lower === 'on') return true
637
+ if (lower === 'false' || lower === 'no' || lower === 'off') return false
638
+ return value
639
+ }
640
+
641
+ /**
642
+ * Resolve model/user invocation controls from frontmatter.
643
+ * @param data - parsed frontmatter fields.
644
+ * @returns invocation policy.
645
+ */
646
+ function parseInvocationPolicy(data: Record<string, unknown>): { modelInvocable: boolean; userInvocable: boolean } {
647
+ for (const [legacy, canonical] of [
648
+ ['disableModelInvocation', 'disable-model-invocation'],
649
+ ['modelInvocable', 'disable-model-invocation'],
650
+ ['userInvocable', 'user-invocable'],
651
+ ] as const) {
652
+ if (Object.hasOwn(data, legacy)) throw new Error(`frontmatter field "${legacy}" is unsupported; use "${canonical}"`)
653
+ }
654
+ const disableModelInvocation = booleanField(data, 'disable-model-invocation')
655
+ const userInvocable = booleanField(data, 'user-invocable')
656
+ return {
657
+ modelInvocable: disableModelInvocation !== true,
658
+ userInvocable: userInvocable !== false,
659
+ }
660
+ }
661
+
662
+ /**
663
+ * Read an optional boolean field with YAML-compatible coercions.
664
+ * @param data - parsed frontmatter fields.
665
+ * @param key - field name.
666
+ * @returns boolean when present and understood.
667
+ */
668
+ function booleanField(data: Record<string, unknown>, key: string): boolean | undefined {
669
+ if (!Object.hasOwn(data, key)) return undefined
670
+ const value = data[key]
671
+ if (typeof value === 'boolean') return value
672
+ if (value === 1 || value === '1') return true
673
+ if (value === 0 || value === '0') return false
674
+ if (typeof value === 'string') {
675
+ switch (value.toLowerCase()) {
676
+ case 'true':
677
+ case 'yes':
678
+ case 'on':
679
+ return true
680
+ case 'false':
681
+ case 'no':
682
+ case 'off':
683
+ return false
684
+ }
685
+ }
686
+ throw new TypeError(`frontmatter field "${key}" must be a boolean`)
687
+ }
688
+
689
+ /**
690
+ * Read a non-empty string field.
691
+ * @param data - parsed frontmatter fields.
692
+ * @param key - field name.
693
+ * @returns the string, or undefined when absent or empty.
694
+ */
695
+ function stringField(data: Record<string, unknown>, key: string): string | undefined {
696
+ const value = data[key]
697
+ return typeof value === 'string' && value.length > 0 ? value : undefined
698
+ }
699
+
700
+ /**
701
+ * Walk up from `cwd` to the nearest directory containing `.git`.
702
+ * @param cwd - absolute session directory.
703
+ * @param ctx - plugin context for warnings.
704
+ * @returns project root, or `cwd` when no repository marker exists.
705
+ */
706
+ async function findProjectRoot(cwd: string, ctx: Context): Promise<string> {
707
+ let current = cwd
708
+ while (true) {
709
+ try {
710
+ await stat(join(current, '.git'))
711
+ return current
712
+ } catch (error) {
713
+ if (!isAbsent(error)) ctx.logger.warn(`utils-agents skills: cannot inspect ${join(current, '.git')}: ${errorMessage(error)}`)
714
+ }
715
+ const parent = dirname(current)
716
+ if (parent === current) return cwd
717
+ current = parent
718
+ }
719
+ }
720
+
721
+ /**
722
+ * Resolve a home-based directory from an environment override.
723
+ * @param variable - environment variable name.
724
+ * @param fallback - directory name under the home directory.
725
+ * @returns absolute directory path.
726
+ */
727
+ function agentHome(variable: string, fallback: string): string {
728
+ const override = process.env[variable]
729
+ if (typeof override === 'string' && override.length > 0) return resolve(override)
730
+ return join(homedir(), fallback)
731
+ }
732
+
733
+ /**
734
+ * Build a change signature for polling fallback.
735
+ * @param root - root descriptor.
736
+ * @param options - normalized plugin options.
737
+ * @param ctx - plugin context for warnings.
738
+ * @returns stable signature string.
739
+ */
740
+ async function scanRootSignature(root: Root, options: Options, ctx: Context): Promise<string> {
741
+ const parts: string[] = []
742
+ const stack: { dir: string; depth: number }[] = [{ dir: root.path, depth: 0 }]
743
+ const visited = new Set<string>()
744
+ while (stack.length > 0) {
745
+ const current = stack.pop() as { dir: string; depth: number }
746
+ let entries
747
+ try {
748
+ entries = await readdir(current.dir, { withFileTypes: true })
749
+ } catch {
750
+ continue
751
+ }
752
+ if (current.depth >= options.minDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
753
+ const file = join(current.dir, SKILL_FILE)
754
+ try {
755
+ const info = await stat(file)
756
+ parts.push(`${file}:${info.size}:${info.mtimeMs}`)
757
+ } catch {
758
+ // The file vanished between listing and stat; the next scan settles it.
759
+ }
760
+ }
761
+ if (current.depth >= options.maxDepth) continue
762
+ for (const entry of entries) {
763
+ if (entry.isDirectory()) {
764
+ if (isIgnored(entry.name, options)) continue
765
+ stack.push({ dir: join(current.dir, entry.name), depth: current.depth + 1 })
766
+ continue
767
+ }
768
+ if (!entry.isSymbolicLink() || !options.followSymlinks) continue
769
+ try {
770
+ const info = await stat(join(current.dir, entry.name))
771
+ if (!info.isDirectory()) continue
772
+ const real = await realpath(join(current.dir, entry.name))
773
+ if (visited.has(real)) continue
774
+ visited.add(real)
775
+ stack.push({ dir: join(current.dir, entry.name), depth: current.depth + 1 })
776
+ } catch (error) {
777
+ ctx.logger.warn(`utils-agents skills: cannot follow ${join(current.dir, entry.name)}: ${errorMessage(error)}`)
778
+ }
779
+ }
780
+ }
781
+ return parts.sort().join('\n')
782
+ }
783
+
784
+ /**
785
+ * Whether a directory name is excluded from recursion.
786
+ * @param dirName - directory base name.
787
+ * @param options - normalized plugin options.
788
+ * @returns whether to skip it.
789
+ */
790
+ function isIgnored(dirName: string, options: Options): boolean {
791
+ return options.ignoreDirs.includes(dirName)
792
+ }
793
+
794
+ /**
795
+ * Validate and normalize row config.
796
+ * @param ctx - plugin context for warnings about unknown keys.
797
+ * @param raw - raw row config.
798
+ * @returns normalized options.
799
+ */
800
+ function normalizeConfig(ctx: Context, raw: SkillDiscoveryConfig | undefined): Options {
801
+ const root = (unwrap(raw) ?? {}) as Record<string, unknown>
802
+ if (typeof root !== 'object' || Array.isArray(root)) throw new TypeError('utils-agents skills: config must be an object')
803
+ const known = new Set(Object.keys(SKILL_DISCOVERY_DEFAULTS))
804
+ for (const key of Object.keys(root)) {
805
+ if (!known.has(key)) ctx.logger.warn(`utils-agents skills: unknown config key "${key}" ignored`)
806
+ }
807
+ const value = <T>(key: keyof SkillDiscoveryConfig): T | undefined => unwrap<T>(root[key] as MaybeRef<T> | undefined)
808
+ const options: Options = { ...SKILL_DISCOVERY_DEFAULTS }
809
+ options.minDepth = positiveInteger('minDepth', value<number>('minDepth') ?? SKILL_DISCOVERY_DEFAULTS.minDepth, 1)
810
+ options.maxDepth = positiveInteger('maxDepth', value<number>('maxDepth') ?? SKILL_DISCOVERY_DEFAULTS.maxDepth, options.minDepth)
811
+ options.debounceMs = nonNegativeInteger('debounceMs', value<number>('debounceMs') ?? SKILL_DISCOVERY_DEFAULTS.debounceMs)
812
+ options.pollIntervalMs = positiveInteger('pollIntervalMs', value<number>('pollIntervalMs') ?? SKILL_DISCOVERY_DEFAULTS.pollIntervalMs, 250)
813
+ options.watch = booleanOption('watch', value<boolean>('watch') ?? SKILL_DISCOVERY_DEFAULTS.watch)
814
+ options.includeProjectRoots = booleanOption('includeProjectRoots', value<boolean>('includeProjectRoots') ?? SKILL_DISCOVERY_DEFAULTS.includeProjectRoots)
815
+ options.includeUserRoots = booleanOption('includeUserRoots', value<boolean>('includeUserRoots') ?? SKILL_DISCOVERY_DEFAULTS.includeUserRoots)
816
+ options.followSymlinks = booleanOption('followSymlinks', value<boolean>('followSymlinks') ?? SKILL_DISCOVERY_DEFAULTS.followSymlinks)
817
+ options.extraRoots = stringArray('extraRoots', value<readonly string[]>('extraRoots') ?? SKILL_DISCOVERY_DEFAULTS.extraRoots).map((path) => resolve(path))
818
+ options.ignoreDirs = stringArray('ignoreDirs', value<readonly string[]>('ignoreDirs') ?? SKILL_DISCOVERY_DEFAULTS.ignoreDirs)
819
+ return options
820
+ }
821
+
822
+ /** Read a Loader volatile reference, or return a plain value. */
823
+ function unwrap<T>(value: MaybeRef<T> | undefined): T | undefined {
824
+ if (value !== null && typeof value === 'object' && typeof (value as VolatileRef<T>).get === 'function') {
825
+ return (value as VolatileRef<T>).get()
826
+ }
827
+ return value as T | undefined
828
+ }
829
+
830
+ /** Whether two normalized option sets describe the same behavior. */
831
+ function sameOptions(a: Options, b: Options): boolean {
832
+ return a.minDepth === b.minDepth
833
+ && a.maxDepth === b.maxDepth
834
+ && a.watch === b.watch
835
+ && a.debounceMs === b.debounceMs
836
+ && a.pollIntervalMs === b.pollIntervalMs
837
+ && a.includeProjectRoots === b.includeProjectRoots
838
+ && a.includeUserRoots === b.includeUserRoots
839
+ && a.followSymlinks === b.followSymlinks
840
+ && sameList(a.extraRoots, b.extraRoots)
841
+ && sameList(a.ignoreDirs, b.ignoreDirs)
842
+ }
843
+
844
+ /** Whether two string arrays are equal. */
845
+ function sameList(a: readonly string[], b: readonly string[]): boolean {
846
+ return a.length === b.length && a.every((value, index) => value === b[index])
847
+ }
848
+
849
+ /**
850
+ * Validate a positive integer option.
851
+ * @param field - option name.
852
+ * @param value - raw value.
853
+ * @param minimum - inclusive minimum.
854
+ * @returns validated value.
855
+ */
856
+ function positiveInteger(field: string, value: number, minimum: number): number {
857
+ if (!Number.isInteger(value) || value < minimum) {
858
+ throw new TypeError(`utils-agents skills: ${field} must be an integer >= ${minimum}`)
859
+ }
860
+ return value
861
+ }
862
+
863
+ /**
864
+ * Validate a non-negative integer option.
865
+ * @param field - option name.
866
+ * @param value - raw value.
867
+ * @returns validated value.
868
+ */
869
+ function nonNegativeInteger(field: string, value: number): number {
870
+ if (!Number.isInteger(value) || value < 0) {
871
+ throw new TypeError(`utils-agents skills: ${field} must be a non-negative integer`)
872
+ }
873
+ return value
874
+ }
875
+
876
+ /**
877
+ * Validate a boolean option.
878
+ * @param field - option name.
879
+ * @param value - raw value.
880
+ * @returns validated value.
881
+ */
882
+ function booleanOption(field: string, value: boolean): boolean {
883
+ if (typeof value !== 'boolean') throw new TypeError(`utils-agents skills: ${field} must be a boolean`)
884
+ return value
885
+ }
886
+
887
+ /**
888
+ * Validate a string-array option.
889
+ * @param field - option name.
890
+ * @param value - raw value.
891
+ * @returns validated array.
892
+ */
893
+ function stringArray(field: string, value: readonly string[]): string[] {
894
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry.length === 0)) {
895
+ throw new TypeError(`utils-agents skills: ${field} must be an array of non-empty strings`)
896
+ }
897
+ return [...value]
898
+ }
899
+
900
+ /**
901
+ * Whether an fs error means the path is simply absent.
902
+ * @param error - thrown value.
903
+ * @returns whether it is ENOENT or ENOTDIR.
904
+ */
905
+ function isAbsent(error: unknown): boolean {
906
+ return typeof error === 'object' && error !== null && 'code' in error
907
+ && ((error as { code?: unknown }).code === 'ENOENT' || (error as { code?: unknown }).code === 'ENOTDIR')
908
+ }
909
+
910
+ /**
911
+ * Render an error for logs.
912
+ * @param error - thrown value.
913
+ * @returns message text.
914
+ */
915
+ function errorMessage(error: unknown): string {
916
+ return error instanceof Error ? error.message : String(error)
917
+ }