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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/lib/git.d.ts +87 -0
  3. package/lib/git.js +403 -0
  4. package/lib/git.js.map +1 -0
  5. package/lib/global-repo.d.ts +57 -0
  6. package/lib/global-repo.js +301 -0
  7. package/lib/global-repo.js.map +1 -0
  8. package/lib/index.d.ts +111 -0
  9. package/lib/index.js +470 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/legacy.d.ts +30 -0
  12. package/lib/legacy.js +141 -0
  13. package/lib/legacy.js.map +1 -0
  14. package/lib/native.d.ts +74 -0
  15. package/lib/native.js +232 -0
  16. package/lib/native.js.map +1 -0
  17. package/lib/presets.d.ts +34 -0
  18. package/lib/presets.js +312 -0
  19. package/lib/presets.js.map +1 -0
  20. package/lib/shared.d.ts +105 -0
  21. package/lib/shared.js +507 -0
  22. package/lib/shared.js.map +1 -0
  23. package/lib/skill-discovery.d.ts +52 -0
  24. package/lib/skill-discovery.js +850 -0
  25. package/lib/skill-discovery.js.map +1 -0
  26. package/lib/skill-panel.d.ts +36 -0
  27. package/lib/skill-panel.js +409 -0
  28. package/lib/skill-panel.js.map +1 -0
  29. package/lib/update.d.ts +129 -0
  30. package/lib/update.js +507 -0
  31. package/lib/update.js.map +1 -0
  32. package/lib/util.d.ts +215 -0
  33. package/lib/util.js +475 -0
  34. package/lib/util.js.map +1 -0
  35. package/locale/en.json +6 -0
  36. package/locale/zh.json +6 -0
  37. package/package.json +52 -3
  38. package/src/git.ts +444 -0
  39. package/src/global-repo.ts +343 -0
  40. package/src/index.ts +522 -0
  41. package/src/legacy.ts +170 -0
  42. package/src/native.ts +291 -0
  43. package/src/presets.ts +329 -0
  44. package/src/shared.ts +589 -0
  45. package/src/skill-discovery.ts +917 -0
  46. package/src/skill-panel.ts +488 -0
  47. package/src/update.ts +574 -0
  48. package/src/util.ts +570 -0
  49. package/README.md +0 -3
package/src/presets.ts ADDED
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Preset discovery and preset-scoped file operations for the utils-agents panel.
3
+ *
4
+ * A preset is one directory under a configured preset root (default
5
+ * $DSH_HOME/.agent-presets). The panel reads its preset.yml display name,
6
+ * scans its skills/ tree for SKILL.md / SKILL.md.disabled, and treats the
7
+ * preset root as the editable Markdown scope (AGENTS.md first).
8
+ *
9
+ * @module dsh-utils/utils-agents/presets
10
+ */
11
+
12
+ import { lstat, readdir, readFile, rename, rm } from 'node:fs/promises'
13
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import {
16
+ AGENTS_CANDIDATES,
17
+ GLOBAL_PRESET,
18
+ IGNORED_DIRS,
19
+ AgentsError,
20
+ agentsHome,
21
+ decodeIdPart,
22
+ dshHome,
23
+ encodeIdPart,
24
+ errorMessage,
25
+ exists,
26
+ expandAbsolute,
27
+ fileRow,
28
+ findProjectRoot,
29
+ insideJoin,
30
+ presetRoots,
31
+ projectChain,
32
+ scopeOf,
33
+ walkFiles,
34
+ type FileRow,
35
+ type Options,
36
+ type PresetInfo,
37
+ type SkillRow,
38
+ } from './util.js'
39
+
40
+ /** Deepest walk inside one preset. */
41
+ const PRESET_MAX_DEPTH = 8
42
+
43
+ /** Discover every preset directory in the configured roots. */
44
+ export async function discoverPresets(ctx: Context, options: Options): Promise<PresetInfo[]> {
45
+ const presets: PresetInfo[] = []
46
+ for (const root of presetRoots(options)) {
47
+ let entries
48
+ try {
49
+ entries = await readdir(root, { withFileTypes: true })
50
+ } catch (error) {
51
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.debug('utils-agents: cannot read preset root ' + root + ': ' + errorMessage(error))
52
+ continue
53
+ }
54
+ entries.sort((left, right) => left.name.localeCompare(right.name))
55
+ for (const entry of entries) {
56
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
57
+ const path = join(root, entry.name)
58
+ presets.push(await describePreset(ctx, entry.name, path, options))
59
+ }
60
+ }
61
+ return presets
62
+ }
63
+
64
+ /** Find one preset by id; throws 404 when it is not in a configured root. */
65
+ export async function presetById(ctx: Context, options: Options, id: string): Promise<PresetInfo> {
66
+ const presets = await discoverPresets(ctx, options)
67
+ const found = presets.find((preset) => preset.id === id)
68
+ if (found === undefined) throw new AgentsError('未知的预设:' + id, 404)
69
+ return found
70
+ }
71
+
72
+ /** Build the browser row for one discovered preset. */
73
+ async function describePreset(ctx: Context, id: string, path: string, options: Options): Promise<PresetInfo> {
74
+ const meta = await readPresetMeta(path)
75
+ const skills = await scanSkills(ctx, path)
76
+
77
+ return {
78
+ id,
79
+ name: meta.name === '' ? id : meta.name,
80
+ description: meta.description,
81
+ path,
82
+ skills,
83
+ agents: await fileRow(agentsId(path), 'AGENTS.md', join(path, 'AGENTS.md'), id, 'agents'),
84
+ }
85
+ }
86
+
87
+ /** Read name/description from preset.yml with a deliberately small parser. */
88
+ async function readPresetMeta(presetPath: string): Promise<{ name: string; description: string }> {
89
+ let text
90
+ try {
91
+ text = await readFile(join(presetPath, 'preset.yml'), 'utf8')
92
+ } catch {
93
+ return { name: '', description: '' }
94
+ }
95
+ const values = parseSimpleYaml(text)
96
+ return { name: values.name ?? '', description: values.description ?? '' }
97
+ }
98
+
99
+ /** Parse top-level scalar keys, including simple folded/literal blocks. */
100
+ function parseSimpleYaml(text: string): Record<string, string> {
101
+ const values: Record<string, string> = {}
102
+ const lines = text.split(/\r?\n/)
103
+ for (let index = 0; index < lines.length; index += 1) {
104
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/.exec(lines[index])
105
+ if (match === null) continue
106
+ const key = match[1]
107
+ let value = match[2].trim()
108
+ if (value === '>-' || value === '>' || value === '|' || value === '|-') {
109
+ const parts: string[] = []
110
+ while (index + 1 < lines.length && /^\s+/.test(lines[index + 1])) {
111
+ index += 1
112
+ parts.push(lines[index].trim())
113
+ }
114
+ value = parts.join(' ').trim()
115
+ }
116
+ values[key] = unquote(value)
117
+ }
118
+ return values
119
+ }
120
+
121
+ /** Strip YAML quotes from one scalar. */
122
+ function unquote(value: string): string {
123
+ if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/g, "'")
124
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
125
+ return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\')
126
+ }
127
+ return value
128
+ }
129
+
130
+ /** Scan skills/ for SKILL.md and SKILL.md.disabled, one row per skill directory. */
131
+ export async function scanSkills(ctx: Context, presetPath: string): Promise<SkillRow[]> {
132
+ const root = join(presetPath, 'skills')
133
+ if (!(await exists(root))) return []
134
+ const files: string[] = []
135
+ await walkFiles(root, PRESET_MAX_DEPTH, new Set(IGNORED_DIRS), (path) => {
136
+ const name = basename(path)
137
+ if (name === 'SKILL.md' || name === 'SKILL.md.disabled') files.push(path)
138
+ }, ctx)
139
+
140
+ const byDirectory = new Map<string, SkillRow>()
141
+ for (const path of files) {
142
+ const rel = relative(presetPath, path).split(sep).join('/')
143
+ const directory = dirname(rel)
144
+ const enabled = basename(path) === 'SKILL.md'
145
+ const existing = byDirectory.get(directory)
146
+ if (existing !== undefined && existing.enabled) continue
147
+ const meta = await readSkillMeta(path)
148
+ const row: SkillRow = {
149
+ name: meta.name === '' ? basename(directory) : meta.name,
150
+ description: meta.description,
151
+ path: rel,
152
+ enabled,
153
+ size: await fileSize(path),
154
+ mtimeMs: await fileMtime(path),
155
+ }
156
+ byDirectory.set(directory, row)
157
+ }
158
+ return [...byDirectory.values()].sort((left, right) => left.name.localeCompare(right.name))
159
+ }
160
+
161
+ /** Read name/description from one SKILL.md frontmatter. */
162
+ async function readSkillMeta(path: string): Promise<{ name: string; description: string }> {
163
+ let text
164
+ try {
165
+ text = await readFile(path, 'utf8')
166
+ } catch {
167
+ return { name: '', description: '' }
168
+ }
169
+ if (!text.startsWith('---')) return { name: '', description: '' }
170
+ const end = text.indexOf('\n---', 3)
171
+ if (end < 0) return { name: '', description: '' }
172
+ const values = parseSimpleYaml(text.slice(3, end))
173
+ return { name: values.name ?? '', description: values.description ?? '' }
174
+ }
175
+
176
+ /** File size, or 0 when it disappears. */
177
+ async function fileSize(path: string): Promise<number> {
178
+ try {
179
+ const info = await lstat(path)
180
+ return info.isFile() ? info.size : 0
181
+ } catch {
182
+ return 0
183
+ }
184
+ }
185
+
186
+ /** File mtime, or null when it disappears. */
187
+ async function fileMtime(path: string): Promise<number | null> {
188
+ try {
189
+ const info = await lstat(path)
190
+ return Number.isFinite(info.mtimeMs) ? info.mtimeMs : null
191
+ } catch {
192
+ return null
193
+ }
194
+ }
195
+
196
+ /** Toggle one preset skill by renaming SKILL.md and SKILL.md.disabled. */
197
+ export async function toggleSkill(preset: PresetInfo, relPath: string, enabled: boolean): Promise<SkillRow> {
198
+ const normalized = relPath.split(sep).join('/')
199
+ if (!normalized.startsWith('skills/') || normalized.includes('..')) throw new AgentsError('技能路径不合法', 400)
200
+ const name = basename(normalized)
201
+ if (name !== 'SKILL.md' && name !== 'SKILL.md.disabled') throw new AgentsError('只允许切换 SKILL.md', 400)
202
+ const sourceName = enabled ? 'SKILL.md.disabled' : 'SKILL.md'
203
+ if (name !== sourceName) throw new AgentsError('开关状态与文件名不一致', 400)
204
+ const source = insideJoin(preset.path, normalized)
205
+ const targetRel = enabled ? normalized.slice(0, -'.disabled'.length) : normalized + '.disabled'
206
+ const target = insideJoin(preset.path, targetRel)
207
+ const info = await lstat(source)
208
+ if (info.isSymbolicLink() || !info.isFile()) throw new AgentsError('技能文件不是普通文件', 409)
209
+ if (await exists(target)) throw new AgentsError('目标文件已存在:' + relative(preset.path, target), 409)
210
+ await rename(source, target)
211
+ const meta = await readSkillMeta(target)
212
+ return {
213
+ name: meta.name === '' ? basename(dirname(targetRel)) : meta.name,
214
+ description: meta.description,
215
+ path: targetRel,
216
+ enabled,
217
+ size: await fileSize(target),
218
+ mtimeMs: await fileMtime(target),
219
+ }
220
+ }
221
+
222
+ /** All Markdown files for one preset, AGENTS.md first. */
223
+ export async function presetFiles(ctx: Context, preset: PresetInfo): Promise<FileRow[]> {
224
+ const paths: string[] = []
225
+ await walkFiles(preset.path, PRESET_MAX_DEPTH, new Set(IGNORED_DIRS), (path) => {
226
+ if (path === preset.agents.path) return
227
+ const lower = path.toLowerCase()
228
+ if (!lower.endsWith('.md') && !lower.endsWith('.md.disabled')) return
229
+ paths.push(path)
230
+ }, ctx)
231
+ const rows = [preset.agents]
232
+ for (const path of paths) {
233
+ const rel = relative(preset.path, path).split(sep).join('/')
234
+ rows.push(await fileRow(presetFileId(preset.path, rel), rel, path, preset.id, kindOf(path)))
235
+ }
236
+ return rows.sort((left, right) => {
237
+ if (left.kind === 'agents' && right.kind !== 'agents') return -1
238
+ if (right.kind === 'agents' && left.kind !== 'agents') return 1
239
+ return left.label.localeCompare(right.label)
240
+ })
241
+ }
242
+
243
+ /** Classify one Markdown file inside a preset. */
244
+ function kindOf(path: string): FileRow['kind'] {
245
+ const name = basename(path)
246
+ return name === 'SKILL.md' || name === 'SKILL.md.disabled' ? 'skill' : 'reference'
247
+ }
248
+
249
+ /** Build the opaque id for one preset file. */
250
+ export function presetFileId(presetPath: string, rel: string): string {
251
+ return 'preset:' + encodeIdPart(presetPath) + ':' + encodeIdPart(rel)
252
+ }
253
+
254
+ /** Build the opaque id for one global AGENTS-family file. */
255
+ export function globalFileId(path: string): string {
256
+ return 'global:' + encodeIdPart(path)
257
+ }
258
+
259
+ /** The preset AGENTS.md id. */
260
+ function agentsId(presetPath: string): string {
261
+ return presetFileId(presetPath, 'AGENTS.md')
262
+ }
263
+
264
+ /** Resolve one opaque file id to a path and browser row. */
265
+ export async function resolveFileId(
266
+ ctx: Context,
267
+ options: Options,
268
+ id: string,
269
+ cwd: string,
270
+ ): Promise<{ row: FileRow; path: string; preset: PresetInfo | null }> {
271
+ if (id.startsWith('global:')) {
272
+ const path = decodeIdPart(id.slice('global:'.length))
273
+ const row = (await globalFiles(ctx, options, cwd)).find((candidate) => candidate.path === path)
274
+ if (row === undefined) throw new AgentsError('未知的全局文件 id', 404)
275
+ return { row, path, preset: null }
276
+ }
277
+ if (!id.startsWith('preset:')) throw new AgentsError('未知的文件 id', 404)
278
+ const rest = id.slice('preset:'.length)
279
+ const at = rest.indexOf(':')
280
+ if (at <= 0) throw new AgentsError('预设文件 id 不合法', 400)
281
+ const presetPath = decodeIdPart(rest.slice(0, at))
282
+ const rel = decodeIdPart(rest.slice(at + 1))
283
+ const presets = await discoverPresets(ctx, options)
284
+ const preset = presets.find((candidate) => resolve(candidate.path) === resolve(presetPath))
285
+ if (preset === undefined) throw new AgentsError('未知的预设路径', 404)
286
+ const lower = rel.toLowerCase()
287
+ if ((!lower.endsWith('.md') && !lower.endsWith('.md.disabled')) || rel.includes('..')) throw new AgentsError('只允许编辑 .md / .md.disabled 文件', 400)
288
+ const path = insideJoin(preset.path, rel)
289
+ const row = await fileRow(id, rel.split(sep).join('/'), path, preset.id, rel === 'AGENTS.md' ? 'agents' : kindOf(path))
290
+ return { row, path, preset }
291
+ }
292
+
293
+ /** Global AGENTS.md family for the global pseudo preset. */
294
+ export async function globalFiles(ctx: Context, options: Options, cwd: string): Promise<FileRow[]> {
295
+ const rows: FileRow[] = []
296
+ const add = async (path: string, label: string, scope: string) => {
297
+ const row = await fileRow(globalFileId(path), label, path, GLOBAL_PRESET, 'global')
298
+ rows.push({ ...row, scope })
299
+ }
300
+ await add(join(dshHome(), 'AGENTS.md'), 'AGENTS.md', '用户全局 · $DSH_HOME')
301
+ await add(join(agentsHome(), 'AGENTS.md'), 'AGENTS.md', '共享全局 · $DSH_AGENTS_HOME')
302
+ const projectRoot = await findProjectRoot(cwd)
303
+ for (const dir of projectChain(projectRoot, cwd)) {
304
+ for (const candidate of AGENTS_CANDIDATES) {
305
+ const path = join(dir, candidate)
306
+ const present = await exists(path)
307
+ const primary = candidate === 'AGENTS.md' && (dir === cwd || dir === projectRoot)
308
+ if (!present && !primary) continue
309
+ await add(path, candidate, scopeOf(dir, cwd, projectRoot))
310
+ }
311
+ }
312
+ if (options.scanNestedAgents) {
313
+ const known = new Set(rows.map((row) => row.path))
314
+ const nested: string[] = []
315
+ await walkFiles(cwd, options.nestedDepth, new Set(IGNORED_DIRS), (path) => {
316
+ const name = basename(path)
317
+ if ((name === 'AGENTS.md' || name === 'CLAUDE.md') && !known.has(path)) nested.push(path)
318
+ }, ctx)
319
+ for (const path of nested) await add(path, basename(path), relative(projectRoot, dirname(path)) || '.')
320
+ }
321
+ for (const raw of options.extraAgentsFiles) {
322
+ try {
323
+ await add(expandAbsolute(raw), basename(expandAbsolute(raw)), '额外文件')
324
+ } catch {
325
+ // Invalid extras are ignored.
326
+ }
327
+ }
328
+ return rows
329
+ }