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