@xi4z/dsh-utils-utils-agents 0.7.1 → 0.9.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.
- package/lib/global-repo.d.ts +37 -19
- package/lib/global-repo.js +149 -96
- package/lib/global-repo.js.map +1 -1
- package/lib/index.d.ts +2 -0
- package/lib/index.js +20 -2
- package/lib/index.js.map +1 -1
- package/lib/shared.d.ts +19 -0
- package/lib/shared.js +97 -17
- package/lib/shared.js.map +1 -1
- package/lib/skill-discovery.d.ts +9 -1
- package/lib/skill-discovery.js +93 -18
- package/lib/skill-discovery.js.map +1 -1
- package/lib/skill-repo-updater.d.ts +36 -0
- package/lib/skill-repo-updater.js +90 -0
- package/lib/skill-repo-updater.js.map +1 -0
- package/lib/utils-config.d.ts +75 -0
- package/lib/utils-config.js +217 -0
- package/lib/utils-config.js.map +1 -0
- package/package.json +1 -1
- package/src/global-repo.ts +179 -106
- package/src/index.ts +19 -2
- package/src/shared.ts +100 -13
- package/src/skill-discovery.ts +106 -18
- package/src/skill-repo-updater.ts +96 -0
- package/src/utils-config.ts +259 -0
package/src/skill-discovery.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { watch, type FSWatcher } from 'node:fs'
|
|
14
14
|
import { readdir, readFile, realpath, stat } from 'node:fs/promises'
|
|
15
15
|
import { homedir } from 'node:os'
|
|
16
|
-
import { dirname, join, resolve } from 'node:path'
|
|
16
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
17
17
|
import type { Context } from '@deepseek-ai/cordis'
|
|
18
18
|
import type {
|
|
19
19
|
SkillCandidate,
|
|
@@ -25,12 +25,16 @@ import type {
|
|
|
25
25
|
SkillSource,
|
|
26
26
|
} from '@deepseek-ai/dsh-skill'
|
|
27
27
|
import type {} from '@deepseek-ai/dsh-settings'
|
|
28
|
+
import { readUtilsConfig } from './utils-config.js'
|
|
28
29
|
|
|
29
30
|
/** Provider name reported in the skill catalog. */
|
|
30
31
|
export const PROVIDER_NAME = 'utils-agents'
|
|
31
32
|
|
|
32
33
|
/** Ranks sit one step below the shipped filesystem provider, so flat skills win collisions. */
|
|
33
34
|
const RANKS = {
|
|
35
|
+
// An explicitly configured Skill repository outranks every inferred root, so
|
|
36
|
+
// the checkout the operator named wins a name collision.
|
|
37
|
+
'skill-repo': 90,
|
|
34
38
|
'project-dsh': 110,
|
|
35
39
|
'project-agents': 210,
|
|
36
40
|
custom: 310,
|
|
@@ -49,6 +53,7 @@ export const SKILL_DISCOVERY_DEFAULTS = {
|
|
|
49
53
|
pollIntervalMs: 2000,
|
|
50
54
|
includeProjectRoots: true,
|
|
51
55
|
includeUserRoots: true,
|
|
56
|
+
includeSkillRepositories: true,
|
|
52
57
|
followSymlinks: false,
|
|
53
58
|
extraRoots: [] as string[],
|
|
54
59
|
ignoreDirs: ['.system', 'node_modules', '.git'],
|
|
@@ -71,6 +76,7 @@ export interface SkillDiscoveryConfig {
|
|
|
71
76
|
readonly pollIntervalMs?: MaybeRef<number>
|
|
72
77
|
readonly includeProjectRoots?: MaybeRef<boolean>
|
|
73
78
|
readonly includeUserRoots?: MaybeRef<boolean>
|
|
79
|
+
readonly includeSkillRepositories?: MaybeRef<boolean>
|
|
74
80
|
readonly followSymlinks?: MaybeRef<boolean>
|
|
75
81
|
readonly extraRoots?: MaybeRef<readonly string[]>
|
|
76
82
|
readonly ignoreDirs?: MaybeRef<readonly string[]>
|
|
@@ -81,6 +87,8 @@ interface Root {
|
|
|
81
87
|
readonly path: string
|
|
82
88
|
readonly source: SkillSource
|
|
83
89
|
readonly rank: number
|
|
90
|
+
/** Depth at which the walk may first contribute a SKILL.md (0 = the root itself). */
|
|
91
|
+
readonly startDepth: number
|
|
84
92
|
}
|
|
85
93
|
|
|
86
94
|
/** Normalized options with every default applied. */
|
|
@@ -92,6 +100,7 @@ interface Options {
|
|
|
92
100
|
pollIntervalMs: number
|
|
93
101
|
includeProjectRoots: boolean
|
|
94
102
|
includeUserRoots: boolean
|
|
103
|
+
includeSkillRepositories: boolean
|
|
95
104
|
followSymlinks: boolean
|
|
96
105
|
extraRoots: string[]
|
|
97
106
|
ignoreDirs: string[]
|
|
@@ -117,16 +126,23 @@ interface ParsedSkill {
|
|
|
117
126
|
readonly content: string
|
|
118
127
|
}
|
|
119
128
|
|
|
129
|
+
/** Handle returned by {@link applySkillDiscovery} for out-of-band refreshes. */
|
|
130
|
+
export interface SkillDiscoveryHandle {
|
|
131
|
+
/** Invalidate the catalog, for example after a Skill repository was pulled. */
|
|
132
|
+
refresh(): void
|
|
133
|
+
}
|
|
134
|
+
|
|
120
135
|
/**
|
|
121
136
|
* Register the recursive skill provider on the host `skills` registry.
|
|
122
137
|
* @param ctx - plugin context carrying the `skills` service.
|
|
123
138
|
* @param config - optional row config; see {@link normalizeConfig}.
|
|
139
|
+
* @returns a handle that refreshes the catalog from outside the provider.
|
|
124
140
|
*/
|
|
125
|
-
export function applySkillDiscovery(ctx: Context, config?: SkillDiscoveryConfig):
|
|
141
|
+
export function applySkillDiscovery(ctx: Context, config?: SkillDiscoveryConfig): SkillDiscoveryHandle {
|
|
126
142
|
const registry = (ctx as { skills?: Context['skills'] }).skills
|
|
127
143
|
if (registry === undefined || typeof registry.registerProvider !== 'function') {
|
|
128
144
|
ctx.logger.warn('utils-agents skills: the host provides no skill registry; nested discovery is off')
|
|
129
|
-
return
|
|
145
|
+
return { refresh() {} }
|
|
130
146
|
}
|
|
131
147
|
let provider: RecursiveSkillProvider | undefined
|
|
132
148
|
registry.registerProvider((control) => {
|
|
@@ -139,6 +155,7 @@ export function applySkillDiscovery(ctx: Context, config?: SkillDiscoveryConfig)
|
|
|
139
155
|
await provider?.dispose()
|
|
140
156
|
}
|
|
141
157
|
}, 'utils-agents skills: watcher')
|
|
158
|
+
return { refresh: () => provider?.refresh() }
|
|
142
159
|
}
|
|
143
160
|
|
|
144
161
|
/** Provider that adds nested `SKILL.md` bundles to the skill catalog. */
|
|
@@ -183,7 +200,14 @@ class RecursiveSkillProvider implements SkillProvider {
|
|
|
183
200
|
if (!scan.complete) complete = false
|
|
184
201
|
for (const candidate of scan.candidates) candidates.push(candidate)
|
|
185
202
|
}
|
|
186
|
-
|
|
203
|
+
const unique = await dedupeCandidates(candidates)
|
|
204
|
+
return complete ? unique : { candidates: unique, complete }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Invalidate the visible catalog immediately (used after a repository pull). */
|
|
208
|
+
refresh(): void {
|
|
209
|
+
if (this.disposed) return
|
|
210
|
+
this.control.invalidate()
|
|
187
211
|
}
|
|
188
212
|
|
|
189
213
|
/** Pick up Settings changes; the Loader updates volatile refs in place. */
|
|
@@ -241,26 +265,28 @@ class RecursiveSkillProvider implements SkillProvider {
|
|
|
241
265
|
*/
|
|
242
266
|
async roots(cwd: string | undefined): Promise<Root[]> {
|
|
243
267
|
const roots: Root[] = []
|
|
268
|
+
const startDepth = this.options.minDepth
|
|
244
269
|
if (this.options.includeProjectRoots && typeof cwd === 'string' && cwd.length > 0) {
|
|
245
270
|
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'] })
|
|
271
|
+
roots.push({ path: join(projectRoot, '.dsh', 'skills'), source: 'project-dsh', rank: RANKS['project-dsh'], startDepth })
|
|
272
|
+
roots.push({ path: join(projectRoot, '.agents', 'skills'), source: 'project-agents', rank: RANKS['project-agents'], startDepth })
|
|
248
273
|
}
|
|
249
274
|
for (const path of this.options.extraRoots) {
|
|
250
|
-
roots.push({ path, source: 'custom', rank: RANKS.custom })
|
|
275
|
+
roots.push({ path, source: 'custom', rank: RANKS.custom, startDepth })
|
|
251
276
|
}
|
|
252
277
|
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'] })
|
|
278
|
+
roots.push({ path: join(agentHome('DSH_HOME', '.dsh'), 'skills'), source: 'user-dsh', rank: RANKS['user-dsh'], startDepth })
|
|
279
|
+
roots.push({ path: join(agentHome('DSH_AGENTS_HOME', '.agents'), 'skills'), source: 'user-agents', rank: RANKS['user-agents'], startDepth })
|
|
255
280
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
281
|
+
if (this.options.includeSkillRepositories) {
|
|
282
|
+
// A configured Skill repository owns its whole tree: the walk starts at the
|
|
283
|
+
// checkout root (depth 0) instead of the usual minDepth, so a SKILL.md at
|
|
284
|
+
// the repository root and every nested bundle are discovered.
|
|
285
|
+
for (const repository of await configuredSkillRepositories()) {
|
|
286
|
+
roots.push({ path: repository.targetDir, source: 'custom', rank: RANKS['skill-repo'], startDepth: 0 })
|
|
287
|
+
}
|
|
262
288
|
}
|
|
263
|
-
return
|
|
289
|
+
return dedupeRoots(roots)
|
|
264
290
|
}
|
|
265
291
|
|
|
266
292
|
/**
|
|
@@ -366,6 +392,66 @@ class RecursiveSkillProvider implements SkillProvider {
|
|
|
366
392
|
}
|
|
367
393
|
}
|
|
368
394
|
|
|
395
|
+
/**
|
|
396
|
+
* The configured Skill repository checkouts, read from
|
|
397
|
+
* `$DSH_HOME/utils/utils.json`. A repository without a URL or an absolute
|
|
398
|
+
* checkout is ignored instead of failing discovery.
|
|
399
|
+
* @returns absolute checkout paths in configuration order.
|
|
400
|
+
*/
|
|
401
|
+
async function configuredSkillRepositories(): Promise<{ targetDir: string }[]> {
|
|
402
|
+
const { config } = await readUtilsConfig()
|
|
403
|
+
return config.skillRepositories.filter(
|
|
404
|
+
(repository) => repository.repoUrl !== '' && isAbsolute(repository.targetDir),
|
|
405
|
+
)
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* De-duplicate roots by path, keeping the highest-precedence descriptor.
|
|
410
|
+
* @param roots - roots in construction order.
|
|
411
|
+
* @returns unique roots in first-seen order.
|
|
412
|
+
*/
|
|
413
|
+
function dedupeRoots(roots: readonly Root[]): Root[] {
|
|
414
|
+
const byPath = new Map<string, Root>()
|
|
415
|
+
for (const root of roots) {
|
|
416
|
+
const existing = byPath.get(root.path)
|
|
417
|
+
if (existing === undefined || root.rank < existing.rank) byPath.set(root.path, root)
|
|
418
|
+
}
|
|
419
|
+
return [...byPath.values()]
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Collapse candidates that resolve to the same file. A configured repository is
|
|
424
|
+
* often also reachable through a symlinked standard root (for example
|
|
425
|
+
* `$DSH_HOME/skills -> <checkout>`), and scanning both must not duplicate skills.
|
|
426
|
+
* @param candidates - candidates from every root, in precedence order.
|
|
427
|
+
* @returns one candidate per real file, keeping the lowest rank.
|
|
428
|
+
*/
|
|
429
|
+
async function dedupeCandidates(candidates: readonly SkillCandidate[]): Promise<SkillCandidate[]> {
|
|
430
|
+
const byPath = new Map<string, number>()
|
|
431
|
+
const unique: SkillCandidate[] = []
|
|
432
|
+
for (const candidate of candidates) {
|
|
433
|
+
const path = candidate.path
|
|
434
|
+
if (path === undefined) {
|
|
435
|
+
unique.push(candidate)
|
|
436
|
+
continue
|
|
437
|
+
}
|
|
438
|
+
let key: string
|
|
439
|
+
try {
|
|
440
|
+
key = await realpath(path)
|
|
441
|
+
} catch {
|
|
442
|
+
key = resolve(path)
|
|
443
|
+
}
|
|
444
|
+
const at = byPath.get(key)
|
|
445
|
+
if (at === undefined) {
|
|
446
|
+
byPath.set(key, unique.length)
|
|
447
|
+
unique.push(candidate)
|
|
448
|
+
continue
|
|
449
|
+
}
|
|
450
|
+
if (candidate.rank < unique[at].rank) unique[at] = candidate
|
|
451
|
+
}
|
|
452
|
+
return unique
|
|
453
|
+
}
|
|
454
|
+
|
|
369
455
|
/**
|
|
370
456
|
* Depth-limited recursive scan of one skill root for nested `SKILL.md` files.
|
|
371
457
|
* @param root - resolved root descriptor.
|
|
@@ -395,7 +481,7 @@ async function scanRoot(
|
|
|
395
481
|
}
|
|
396
482
|
continue
|
|
397
483
|
}
|
|
398
|
-
if (current.depth >=
|
|
484
|
+
if (current.depth >= root.startDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
|
|
399
485
|
const file = join(current.dir, SKILL_FILE)
|
|
400
486
|
const parsed = await readSkillCandidate(file, root, ctx, providerName)
|
|
401
487
|
if (parsed !== undefined) candidates.push(parsed)
|
|
@@ -749,7 +835,7 @@ async function scanRootSignature(root: Root, options: Options, ctx: Context): Pr
|
|
|
749
835
|
} catch {
|
|
750
836
|
continue
|
|
751
837
|
}
|
|
752
|
-
if (current.depth >=
|
|
838
|
+
if (current.depth >= root.startDepth && entries.some((entry) => entry.name === SKILL_FILE)) {
|
|
753
839
|
const file = join(current.dir, SKILL_FILE)
|
|
754
840
|
try {
|
|
755
841
|
const info = await stat(file)
|
|
@@ -813,6 +899,7 @@ function normalizeConfig(ctx: Context, raw: SkillDiscoveryConfig | undefined): O
|
|
|
813
899
|
options.watch = booleanOption('watch', value<boolean>('watch') ?? SKILL_DISCOVERY_DEFAULTS.watch)
|
|
814
900
|
options.includeProjectRoots = booleanOption('includeProjectRoots', value<boolean>('includeProjectRoots') ?? SKILL_DISCOVERY_DEFAULTS.includeProjectRoots)
|
|
815
901
|
options.includeUserRoots = booleanOption('includeUserRoots', value<boolean>('includeUserRoots') ?? SKILL_DISCOVERY_DEFAULTS.includeUserRoots)
|
|
902
|
+
options.includeSkillRepositories = booleanOption('includeSkillRepositories', value<boolean>('includeSkillRepositories') ?? SKILL_DISCOVERY_DEFAULTS.includeSkillRepositories)
|
|
816
903
|
options.followSymlinks = booleanOption('followSymlinks', value<boolean>('followSymlinks') ?? SKILL_DISCOVERY_DEFAULTS.followSymlinks)
|
|
817
904
|
options.extraRoots = stringArray('extraRoots', value<readonly string[]>('extraRoots') ?? SKILL_DISCOVERY_DEFAULTS.extraRoots).map((path) => resolve(path))
|
|
818
905
|
options.ignoreDirs = stringArray('ignoreDirs', value<readonly string[]>('ignoreDirs') ?? SKILL_DISCOVERY_DEFAULTS.ignoreDirs)
|
|
@@ -836,6 +923,7 @@ function sameOptions(a: Options, b: Options): boolean {
|
|
|
836
923
|
&& a.pollIntervalMs === b.pollIntervalMs
|
|
837
924
|
&& a.includeProjectRoots === b.includeProjectRoots
|
|
838
925
|
&& a.includeUserRoots === b.includeUserRoots
|
|
926
|
+
&& a.includeSkillRepositories === b.includeSkillRepositories
|
|
839
927
|
&& a.followSymlinks === b.followSymlinks
|
|
840
928
|
&& sameList(a.extraRoots, b.extraRoots)
|
|
841
929
|
&& sameList(a.ignoreDirs, b.ignoreDirs)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Periodic refresh of the configured Skill repositories.
|
|
3
|
+
*
|
|
4
|
+
* A configured checkout is only useful while it keeps moving, and a skill
|
|
5
|
+
* repository usually carries its skills in submodules. This watcher fast-forwards
|
|
6
|
+
* every repository from `$DSH_HOME/utils/utils.json` and refreshes its
|
|
7
|
+
* submodules, then invalidates the skill catalog when something actually
|
|
8
|
+
* changed. It never merges over a dirty working tree, never resets, and never
|
|
9
|
+
* pushes; failures stay warnings.
|
|
10
|
+
*
|
|
11
|
+
* After the pull it can also mirror the presets a checkout carries under
|
|
12
|
+
* `.dsh/preset` into `$DSH_HOME/.agent-presets` (`autoSyncPresets`). The
|
|
13
|
+
* repository is the only source of truth: the pass adds new presets, updates
|
|
14
|
+
* changed ones, and removes local copies whose preset disappeared upstream.
|
|
15
|
+
* Nothing is ever published or deleted in the repository from here.
|
|
16
|
+
*
|
|
17
|
+
* The cadence is read from the same document on every tick, so editing
|
|
18
|
+
* `autoUpdate`, `autoSyncPresets` or `updateIntervalMinutes` takes effect
|
|
19
|
+
* without a restart.
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-utils/utils-agents/skill-repo-updater
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
25
|
+
import { updateSkillRepositories } from './global-repo.js'
|
|
26
|
+
import { errorMessage } from './util.js'
|
|
27
|
+
import { readUtilsConfig } from './utils-config.js'
|
|
28
|
+
|
|
29
|
+
/** First refresh runs well after startup, so activation stays cheap. */
|
|
30
|
+
const FIRST_UPDATE_DELAY_MS = 5 * 60_000
|
|
31
|
+
|
|
32
|
+
/** Fallback cadence when the document cannot be read. */
|
|
33
|
+
const FALLBACK_INTERVAL_MINUTES = 60
|
|
34
|
+
|
|
35
|
+
/** Callbacks the periodic refresh needs from the owning component. */
|
|
36
|
+
export interface SkillRepositoryUpdaterHooks {
|
|
37
|
+
/** Refresh the skill catalog after a changed checkout. */
|
|
38
|
+
readonly invalidateSkills: () => void
|
|
39
|
+
/** Copy presets carried by the configured repositories into the preset home. */
|
|
40
|
+
readonly syncPresets: () => Promise<void>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Start the periodic Skill repository refresh.
|
|
45
|
+
* @param ctx - plugin context for warnings and lifecycle.
|
|
46
|
+
* @param hooks - catalog refresh and preset sync callbacks.
|
|
47
|
+
*/
|
|
48
|
+
export function startSkillRepositoryUpdater(ctx: Context, hooks: SkillRepositoryUpdaterHooks): void {
|
|
49
|
+
let disposed = false
|
|
50
|
+
let timer: NodeJS.Timeout | undefined
|
|
51
|
+
|
|
52
|
+
const schedule = (delayMs: number): void => {
|
|
53
|
+
if (disposed) return
|
|
54
|
+
timer = setTimeout(() => { void tick() }, delayMs)
|
|
55
|
+
// A pending refresh must not keep a headless process alive.
|
|
56
|
+
timer.unref?.()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const tick = async (): Promise<void> => {
|
|
60
|
+
if (disposed) return
|
|
61
|
+
let intervalMinutes = FALLBACK_INTERVAL_MINUTES
|
|
62
|
+
try {
|
|
63
|
+
const snapshot = await readUtilsConfig()
|
|
64
|
+
intervalMinutes = snapshot.config.updateIntervalMinutes
|
|
65
|
+
if (snapshot.config.autoUpdate) {
|
|
66
|
+
const results = await updateSkillRepositories(ctx)
|
|
67
|
+
if (results.some((result) => result.changed)) hooks.invalidateSkills()
|
|
68
|
+
for (const result of results) {
|
|
69
|
+
if (result.skipped) ctx.logger.debug('utils-agents: ' + result.targetDir + ': ' + result.message)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (snapshot.config.autoSyncPresets && snapshot.config.skillRepositories.length > 0) {
|
|
73
|
+
try {
|
|
74
|
+
await hooks.syncPresets()
|
|
75
|
+
} catch (error) {
|
|
76
|
+
ctx.logger.warn('utils-agents: scheduled preset sync failed: ' + errorMessage(error))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} catch (error) {
|
|
80
|
+
ctx.logger.warn('utils-agents: scheduled skill repository update failed: ' + errorMessage(error))
|
|
81
|
+
}
|
|
82
|
+
if (disposed) return
|
|
83
|
+
try {
|
|
84
|
+
intervalMinutes = (await readUtilsConfig()).config.updateIntervalMinutes
|
|
85
|
+
} catch {
|
|
86
|
+
// Keep the last known cadence when the document is unreadable.
|
|
87
|
+
}
|
|
88
|
+
schedule(Math.max(1, intervalMinutes) * 60_000)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
schedule(FIRST_UPDATE_DELAY_MS)
|
|
92
|
+
ctx.effect(() => () => {
|
|
93
|
+
disposed = true
|
|
94
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
95
|
+
}, 'utils-agents: skill repository updater')
|
|
96
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consolidated `dsh-utils` configuration at `$DSH_HOME/utils/utils.json`.
|
|
3
|
+
*
|
|
4
|
+
* The document is the one place the bundle keeps operator-editable settings:
|
|
5
|
+
*
|
|
6
|
+
* - `skillRepositories`: the Skill checkouts that are scanned from their own
|
|
7
|
+
* repository root and refreshed on a timer;
|
|
8
|
+
* - `autoUpdate` / `updateIntervalMinutes`: whether (and how often) the timer
|
|
9
|
+
* pulls those checkouts together with their submodules;
|
|
10
|
+
* - `autoSyncPresets`: whether each refresh mirrors the presets a checkout
|
|
11
|
+
* carries under `.dsh/preset` into the local preset home. The repository is
|
|
12
|
+
* the only source of truth: a preset it no longer carries is removed locally
|
|
13
|
+
* as well, and `builtinPresets` are always exempt.
|
|
14
|
+
*
|
|
15
|
+
* The former single-repository state file
|
|
16
|
+
* (`$DSH_HOME/storages/dsh-utils-ui.json`) is migrated on first read and left
|
|
17
|
+
* untouched afterwards, so downgrading still works. Deploy Keys stay under
|
|
18
|
+
* `$DSH_HOME/storages`: they are secrets, not configuration.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-utils/utils-agents/utils-config
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { randomBytes } from 'node:crypto'
|
|
24
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
25
|
+
import { join } from 'node:path'
|
|
26
|
+
import {
|
|
27
|
+
dshHome,
|
|
28
|
+
expandAbsolute,
|
|
29
|
+
type Options,
|
|
30
|
+
type SyncRecord,
|
|
31
|
+
} from './util.js'
|
|
32
|
+
|
|
33
|
+
/** Version of the on-disk document. */
|
|
34
|
+
export const UTILS_CONFIG_VERSION = 1
|
|
35
|
+
|
|
36
|
+
/** Minutes between two automatic Skill repository refreshes. */
|
|
37
|
+
export const DEFAULT_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES = 60
|
|
38
|
+
|
|
39
|
+
/** Smallest accepted automatic refresh interval. */
|
|
40
|
+
export const MIN_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES = 5
|
|
41
|
+
|
|
42
|
+
/** Largest accepted automatic refresh interval. */
|
|
43
|
+
export const MAX_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES = 1440
|
|
44
|
+
|
|
45
|
+
/** Branch used for a migrated repository that never recorded one. */
|
|
46
|
+
const FALLBACK_BRANCH = 'Agent'
|
|
47
|
+
|
|
48
|
+
/** One configured Skill repository checkout. */
|
|
49
|
+
export interface SkillRepositoryConfig {
|
|
50
|
+
repoUrl: string
|
|
51
|
+
branch: string
|
|
52
|
+
targetDir: string
|
|
53
|
+
keyPath: string
|
|
54
|
+
recurseSubmodules: boolean
|
|
55
|
+
lastSync: SyncRecord | null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The whole `utils.json` document. */
|
|
59
|
+
export interface UtilsConfig {
|
|
60
|
+
version: number
|
|
61
|
+
skillRepositories: SkillRepositoryConfig[]
|
|
62
|
+
autoUpdate: boolean
|
|
63
|
+
/** Also copy presets carried by `.dsh/preset` into the local preset home. */
|
|
64
|
+
autoSyncPresets: boolean
|
|
65
|
+
updateIntervalMinutes: number
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One read result: the normalized document plus whether the file existed. */
|
|
69
|
+
export interface UtilsConfigSnapshot {
|
|
70
|
+
readonly config: UtilsConfig
|
|
71
|
+
readonly existed: boolean
|
|
72
|
+
readonly path: string
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `$DSH_HOME/utils`. */
|
|
76
|
+
export function utilsConfigDir(): string {
|
|
77
|
+
return join(dshHome(), 'utils')
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `$DSH_HOME/utils/utils.json`. */
|
|
81
|
+
export function utilsConfigPath(): string {
|
|
82
|
+
return join(utilsConfigDir(), 'utils.json')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The legacy single-repository document `global-repo` used to write. */
|
|
86
|
+
export function legacyUtilsStatePath(): string {
|
|
87
|
+
return join(dshHome(), 'storages', 'dsh-utils-ui.json')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A fresh document with the shipped defaults. */
|
|
91
|
+
export function emptyUtilsConfig(): UtilsConfig {
|
|
92
|
+
return {
|
|
93
|
+
version: UTILS_CONFIG_VERSION,
|
|
94
|
+
skillRepositories: [],
|
|
95
|
+
autoUpdate: true,
|
|
96
|
+
autoSyncPresets: true,
|
|
97
|
+
updateIntervalMinutes: DEFAULT_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The fallback repository the panel shows before anything is saved. */
|
|
102
|
+
export function defaultSkillRepository(options: Pick<Options, 'defaultRepoUrl' | 'defaultBranch'>): SkillRepositoryConfig {
|
|
103
|
+
return {
|
|
104
|
+
repoUrl: options.defaultRepoUrl,
|
|
105
|
+
branch: options.defaultBranch,
|
|
106
|
+
targetDir: join(dshHome(), 'skills', 'utils-skill'),
|
|
107
|
+
keyPath: '',
|
|
108
|
+
recurseSubmodules: true,
|
|
109
|
+
lastSync: null,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Read the consolidated configuration.
|
|
115
|
+
*
|
|
116
|
+
* A missing file is migrated from the legacy state document (and written back
|
|
117
|
+
* when that document exists); a malformed document yields the defaults without
|
|
118
|
+
* destroying the file, so a hand-edit can be repaired.
|
|
119
|
+
* @returns the normalized document, whether it existed, and its path.
|
|
120
|
+
*/
|
|
121
|
+
export async function readUtilsConfig(): Promise<UtilsConfigSnapshot> {
|
|
122
|
+
const path = utilsConfigPath()
|
|
123
|
+
let raw: unknown
|
|
124
|
+
try {
|
|
125
|
+
raw = JSON.parse(await readFile(path, 'utf8')) as unknown
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (isAbsent(error)) return migrateLegacyConfig(path)
|
|
128
|
+
return { config: emptyUtilsConfig(), existed: true, path }
|
|
129
|
+
}
|
|
130
|
+
return { config: normalizeUtilsConfig(raw), existed: true, path }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Replace the document atomically with mode 0600. */
|
|
134
|
+
export async function writeUtilsConfig(config: UtilsConfig): Promise<void> {
|
|
135
|
+
const file = utilsConfigPath()
|
|
136
|
+
await mkdir(utilsConfigDir(), { recursive: true, mode: 0o700 })
|
|
137
|
+
const document: UtilsConfig = {
|
|
138
|
+
version: UTILS_CONFIG_VERSION,
|
|
139
|
+
skillRepositories: config.skillRepositories,
|
|
140
|
+
autoUpdate: config.autoUpdate,
|
|
141
|
+
autoSyncPresets: config.autoSyncPresets,
|
|
142
|
+
updateIntervalMinutes: normalizeInterval(config.updateIntervalMinutes),
|
|
143
|
+
}
|
|
144
|
+
const temp = file + '.' + randomBytes(6).toString('hex') + '.tmp'
|
|
145
|
+
try {
|
|
146
|
+
await writeFile(temp, JSON.stringify(document, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
|
|
147
|
+
await rename(temp, file)
|
|
148
|
+
} catch (error) {
|
|
149
|
+
await rm(temp, { force: true })
|
|
150
|
+
throw error
|
|
151
|
+
}
|
|
152
|
+
await chmod(file, 0o600)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Normalize a parsed document. A legacy single-repository object (fields at the
|
|
157
|
+
* top level) is accepted so an already-written utils.json keeps working.
|
|
158
|
+
* @param raw - parsed JSON value.
|
|
159
|
+
* @returns a document with every field defaulted.
|
|
160
|
+
*/
|
|
161
|
+
function normalizeUtilsConfig(raw: unknown): UtilsConfig {
|
|
162
|
+
const config = emptyUtilsConfig()
|
|
163
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return config
|
|
164
|
+
const record = raw as Record<string, unknown>
|
|
165
|
+
const list = Array.isArray(record.skillRepositories)
|
|
166
|
+
? record.skillRepositories
|
|
167
|
+
: record.repoUrl !== undefined || record.targetDir !== undefined
|
|
168
|
+
? [record]
|
|
169
|
+
: []
|
|
170
|
+
config.skillRepositories = list
|
|
171
|
+
.map((entry) => normalizeSkillRepository(entry))
|
|
172
|
+
.filter((entry): entry is SkillRepositoryConfig => entry !== undefined)
|
|
173
|
+
config.autoUpdate = record.autoUpdate !== false
|
|
174
|
+
config.autoSyncPresets = record.autoSyncPresets !== false
|
|
175
|
+
config.updateIntervalMinutes = normalizeInterval(record.updateIntervalMinutes)
|
|
176
|
+
return config
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Normalize one persisted repository.
|
|
181
|
+
* @param raw - one array entry.
|
|
182
|
+
* @returns the entry, or undefined when it names no repository or checkout.
|
|
183
|
+
*/
|
|
184
|
+
function normalizeSkillRepository(raw: unknown): SkillRepositoryConfig | undefined {
|
|
185
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
|
|
186
|
+
const record = raw as Record<string, unknown>
|
|
187
|
+
const repoUrl = typeof record.repoUrl === 'string' ? record.repoUrl.trim() : ''
|
|
188
|
+
const targetRaw = typeof record.targetDir === 'string' ? record.targetDir.trim() : ''
|
|
189
|
+
if (repoUrl === '' || targetRaw === '') return undefined
|
|
190
|
+
let targetDir: string
|
|
191
|
+
try {
|
|
192
|
+
targetDir = expandAbsolute(targetRaw)
|
|
193
|
+
} catch {
|
|
194
|
+
return undefined
|
|
195
|
+
}
|
|
196
|
+
const branch = typeof record.branch === 'string' && record.branch.trim() !== '' ? record.branch.trim() : FALLBACK_BRANCH
|
|
197
|
+
return {
|
|
198
|
+
repoUrl,
|
|
199
|
+
branch,
|
|
200
|
+
targetDir,
|
|
201
|
+
keyPath: typeof record.keyPath === 'string' ? record.keyPath.trim() : '',
|
|
202
|
+
recurseSubmodules: record.recurseSubmodules !== false,
|
|
203
|
+
lastSync: normalizeSync(record.lastSync),
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Migrate the legacy single-repository document exactly once.
|
|
209
|
+
* @param path - the consolidated config path.
|
|
210
|
+
* @returns the migrated snapshot; the legacy file is never modified.
|
|
211
|
+
*/
|
|
212
|
+
async function migrateLegacyConfig(path: string): Promise<UtilsConfigSnapshot> {
|
|
213
|
+
const config = emptyUtilsConfig()
|
|
214
|
+
try {
|
|
215
|
+
const raw = JSON.parse(await readFile(legacyUtilsStatePath(), 'utf8')) as unknown
|
|
216
|
+
const repository = normalizeSkillRepository(raw)
|
|
217
|
+
if (repository !== undefined) config.skillRepositories.push(repository)
|
|
218
|
+
} catch {
|
|
219
|
+
// No legacy document, or it is unreadable: start empty.
|
|
220
|
+
}
|
|
221
|
+
if (config.skillRepositories.length > 0) {
|
|
222
|
+
try {
|
|
223
|
+
await writeUtilsConfig(config)
|
|
224
|
+
} catch {
|
|
225
|
+
// A read-only home must not turn discovery into a failure.
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return { config, existed: false, path }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Clamp one refresh interval to the accepted range. */
|
|
232
|
+
function normalizeInterval(raw: unknown): number {
|
|
233
|
+
if (typeof raw !== 'number' || !Number.isFinite(raw)) {
|
|
234
|
+
return DEFAULT_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES
|
|
235
|
+
}
|
|
236
|
+
return Math.min(
|
|
237
|
+
MAX_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES,
|
|
238
|
+
Math.max(MIN_SKILL_REPOSITORY_UPDATE_INTERVAL_MINUTES, Math.trunc(raw)),
|
|
239
|
+
)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Normalize a persisted sync record. */
|
|
243
|
+
function normalizeSync(raw: unknown): SyncRecord | null {
|
|
244
|
+
if (raw === null || typeof raw !== 'object') return null
|
|
245
|
+
const record = raw as Record<string, unknown>
|
|
246
|
+
return {
|
|
247
|
+
at: typeof record.at === 'string' ? record.at : '',
|
|
248
|
+
ok: record.ok === true,
|
|
249
|
+
commit: typeof record.commit === 'string' ? record.commit : '',
|
|
250
|
+
skills: typeof record.skills === 'number' ? record.skills : 0,
|
|
251
|
+
message: typeof record.message === 'string' ? record.message : '',
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Whether an fs error means the path is simply absent. */
|
|
256
|
+
function isAbsent(error: unknown): boolean {
|
|
257
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
258
|
+
&& ((error as { code?: unknown }).code === 'ENOENT' || (error as { code?: unknown }).code === 'ENOTDIR')
|
|
259
|
+
}
|