@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,343 @@
1
+ /**
2
+ * Shared skill repository support for the utils-agents panel.
3
+ *
4
+ * The repository configured here is the tracked skills checkout: the panel
5
+ * clones or fast-forwards it with an optional Deploy Key, and the shared
6
+ * preset scanner reads ".dsh/preset" from that checkout. When the shared
7
+ * repository has no key path and no key of its own, the panel-wide Deploy Key
8
+ * from git.js is used, so a private skills checkout pulls without extra setup.
9
+ * Settings and the pasted key intentionally keep the storage the former global
10
+ * repository route used ($DSH_HOME/storages/dsh-utils-ui.json and
11
+ * dsh-utils-ui.deploy-key), so an upgraded profile keeps its repository and key.
12
+ *
13
+ * @module dsh-utils/utils-agents/global-repo
14
+ */
15
+
16
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
17
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import {
20
+ canonicalRepoUrl,
21
+ cloneUrlFor,
22
+ globalKeyPath,
23
+ runGit,
24
+ validateBranch,
25
+ validateRepoUrl,
26
+ type GitOutcome,
27
+ type KeyStatus,
28
+ } from './git.js'
29
+ import {
30
+ IGNORED_DIRS,
31
+ AgentsError,
32
+ directoryOf,
33
+ dshHome,
34
+ errorMessage,
35
+ exists,
36
+ expandAbsolute,
37
+ walkFiles,
38
+ type Options,
39
+ type SyncRecord,
40
+ } from './util.js'
41
+
42
+ /** Legacy state file name; the old global route reads the same document. */
43
+ const STATE_FILE_NAME = 'dsh-utils-ui.json'
44
+
45
+ /** Legacy deploy-key file name; never returned to the browser. */
46
+ const KEY_FILE_NAME = 'dsh-utils-ui.deploy-key'
47
+
48
+ /** Depth used when counting skills in the shared checkout. */
49
+ const SKILL_SCAN_DEPTH = 8
50
+
51
+ /** Durable settings for the shared skill repository. */
52
+ export interface SharedRepoState {
53
+ repoUrl: string
54
+ branch: string
55
+ targetDir: string
56
+ keyPath: string
57
+ recurseSubmodules: boolean
58
+ lastSync: SyncRecord | null
59
+ }
60
+
61
+ /** Checkout status for the shared skill repository. */
62
+ export interface SharedRepoTarget {
63
+ exists: boolean
64
+ isRepo: boolean
65
+ branch: string | null
66
+ commit: string | null
67
+ dirty: boolean
68
+ skills: number
69
+ }
70
+
71
+ /** The full repository view returned to the browser. */
72
+ export interface SharedRepoView {
73
+ state: SharedRepoState
74
+ target: SharedRepoTarget
75
+ key: KeyStatus
76
+ }
77
+
78
+ /** Read the shared repository settings, filling defaults. */
79
+ export async function readSharedRepoState(options: Options): Promise<SharedRepoState> {
80
+ const fallback: SharedRepoState = {
81
+ repoUrl: options.defaultRepoUrl,
82
+ branch: options.defaultBranch,
83
+ targetDir: join(dshHome(), 'skills', 'herskill'),
84
+ keyPath: '',
85
+ recurseSubmodules: true,
86
+ lastSync: null,
87
+ }
88
+ let raw: unknown = null
89
+ try {
90
+ raw = JSON.parse(await readFile(sharedRepoStatePath(), 'utf8')) as unknown
91
+ } catch {
92
+ return fallback
93
+ }
94
+ const record = raw !== null && typeof raw === 'object' ? raw as Record<string, unknown> : {}
95
+ return {
96
+ repoUrl: textValue(record.repoUrl, fallback.repoUrl),
97
+ branch: textValue(record.branch, fallback.branch),
98
+ targetDir: absoluteValue(record.targetDir, fallback.targetDir),
99
+ keyPath: typeof record.keyPath === 'string' ? record.keyPath : '',
100
+ recurseSubmodules: record.recurseSubmodules !== false,
101
+ lastSync: normalizeSync(record.lastSync),
102
+ }
103
+ }
104
+
105
+ /** Read the shared repository settings plus checkout and key status. */
106
+ export async function sharedRepoView(ctx: Context, options: Options): Promise<SharedRepoView> {
107
+ const state = await readSharedRepoState(options)
108
+ return { state, target: await targetStatus(ctx, state), key: await sharedKeyStatus(state) }
109
+ }
110
+
111
+ /** Save new shared repository settings after validation. */
112
+ export async function saveSharedRepoConfig(ctx: Context, options: Options, body: Record<string, unknown>): Promise<SharedRepoView> {
113
+ const current = await readSharedRepoState(options)
114
+ const repoUrl = textValue(body.repoUrl, current.repoUrl)
115
+ const branch = textValue(body.branch, current.branch)
116
+ const targetDir = textValue(body.targetDir, current.targetDir)
117
+ const keyPath = typeof body.keyPath === 'string' ? body.keyPath.trim() : current.keyPath
118
+ const recurseSubmodules = typeof body.recurseSubmodules === 'boolean' ? body.recurseSubmodules : current.recurseSubmodules
119
+ validateRepoUrl(repoUrl)
120
+ validateBranch(branch)
121
+ let resolvedTarget: string
122
+ try {
123
+ resolvedTarget = expandAbsolute(targetDir)
124
+ } catch (error) {
125
+ throw new AgentsError('检出目录必须是绝对路径:' + errorMessage(error), 400)
126
+ }
127
+ if (keyPath !== '') {
128
+ try {
129
+ if (!(await exists(expandAbsolute(keyPath)))) throw new AgentsError('密钥路径不存在:' + keyPath, 400)
130
+ } catch (error) {
131
+ if (error instanceof AgentsError) throw error
132
+ throw new AgentsError('密钥路径不合法:' + keyPath, 400)
133
+ }
134
+ }
135
+ await writeSharedRepoState({
136
+ repoUrl,
137
+ branch,
138
+ targetDir: resolvedTarget,
139
+ keyPath,
140
+ recurseSubmodules,
141
+ lastSync: current.lastSync,
142
+ })
143
+ return sharedRepoView(ctx, options)
144
+ }
145
+
146
+ /** Store a pasted Deploy Key; an empty string clears it. */
147
+ export async function saveSharedRepoKey(ctx: Context, options: Options, key: string): Promise<SharedRepoView> {
148
+ const file = sharedStoredKeyPath()
149
+ if (key.trim() === '') {
150
+ await rm(file, { force: true })
151
+ return sharedRepoView(ctx, options)
152
+ }
153
+ if (key.includes(String.fromCharCode(0))) throw new AgentsError('Deploy Key 不能包含 NUL 字符', 400)
154
+ await mkdir(join(dshHome(), 'storages'), { recursive: true, mode: 0o700 })
155
+ const temp = file + '.' + randomSuffix() + '.tmp'
156
+ try {
157
+ await writeFile(temp, key.trimEnd() + '\n', { mode: 0o600, flag: 'wx' })
158
+ await rename(temp, file)
159
+ } catch (error) {
160
+ await rm(temp, { force: true })
161
+ throw error
162
+ }
163
+ await chmod(file, 0o600)
164
+ return sharedRepoView(ctx, options)
165
+ }
166
+
167
+ /** Clone or fast-forward the shared repository with the configured key. */
168
+ export async function pullSharedRepo(ctx: Context, options: Options): Promise<SharedRepoView> {
169
+ const state = await readSharedRepoState(options)
170
+ const key = await sharedKeyStatus(state)
171
+ if (state.keyPath !== '' && key.file === undefined) throw new AgentsError('配置的密钥路径不存在', 409)
172
+ const parsed = validateRepoUrl(state.repoUrl)
173
+ validateBranch(state.branch)
174
+ if (!isAbsolute(state.targetDir)) throw new AgentsError('检出目录必须是绝对路径', 400)
175
+ const target = state.targetDir
176
+ const cloneUrl = cloneUrlFor(parsed, key.file)
177
+ let message = ''
178
+
179
+ if (!(await exists(target))) {
180
+ await mkdir(dirname(target), { recursive: true })
181
+ const cloned = await runGit(['clone', '--depth', '1', '--branch', state.branch, '--single-branch', cloneUrl, target], undefined, key.file)
182
+ if (cloned.code !== 0) throw pullError('克隆仓库失败', cloned)
183
+ message = '已 clone 分支 ' + state.branch
184
+ } else {
185
+ if (!(await directoryOf(target))) throw new AgentsError('检出目录已存在但不是目录:' + target, 409)
186
+ const root = await runGit(['-C', target, 'rev-parse', '--show-toplevel'], undefined, key.file)
187
+ if (root.code !== 0 || resolve(root.stdout.trim()) !== resolve(target)) {
188
+ throw new AgentsError('检出目录不是该仓库的 Git checkout', 409)
189
+ }
190
+ const origin = await runGit(['-C', target, 'remote', 'get-url', 'origin'], undefined, key.file)
191
+ if (origin.code !== 0) throw pullError('读取 origin 失败', origin)
192
+ if (canonicalRepoUrl(origin.stdout.trim()) !== parsed.canonical) {
193
+ throw new AgentsError('检出目录的 origin 与配置的仓库不一致', 409)
194
+ }
195
+ const current = await runGit(['-C', target, 'rev-parse', '--abbrev-ref', 'HEAD'], undefined, key.file)
196
+ if (current.code !== 0) throw pullError('读取当前分支失败', current)
197
+ if (current.stdout.trim() !== state.branch) {
198
+ throw new AgentsError('检出目录当前分支是 ' + current.stdout.trim() + ',配置分支是 ' + state.branch, 409)
199
+ }
200
+ const shallow = await runGit(['-C', target, 'rev-parse', '--is-shallow-repository'], undefined, key.file)
201
+ const fetchArgs = shallow.code === 0 && shallow.stdout.trim() === 'true'
202
+ ? ['-C', target, 'fetch', '--unshallow', 'origin', state.branch]
203
+ : ['-C', target, 'fetch', 'origin', state.branch]
204
+ const fetched = await runGit(fetchArgs, undefined, key.file)
205
+ if (fetched.code !== 0) throw pullError('fetch 失败', fetched)
206
+ const merged = await runGit(['-C', target, 'merge', '--ff-only', 'FETCH_HEAD'], undefined, key.file)
207
+ if (merged.code !== 0) throw pullError('快进合并失败', merged)
208
+ message = '已快进到最新提交'
209
+ }
210
+
211
+ if (state.recurseSubmodules) {
212
+ const sync = await runGit(['-C', target, 'submodule', 'sync', '--recursive'], undefined, key.file)
213
+ if (sync.code !== 0) ctx.logger.warn('utils-agents: shared submodule sync failed: ' + sync.stderr.trim())
214
+ const update = await runGit(['-C', target, 'submodule', 'update', '--init', '--recursive'], undefined, key.file)
215
+ if (update.code !== 0) ctx.logger.warn('utils-agents: shared submodule update failed: ' + update.stderr.trim())
216
+ }
217
+
218
+ const status = await targetStatus(ctx, { ...state })
219
+ await writeSharedRepoState({
220
+ ...state,
221
+ lastSync: {
222
+ at: new Date().toISOString(),
223
+ ok: true,
224
+ commit: status.commit ?? '',
225
+ skills: status.skills,
226
+ message,
227
+ },
228
+ })
229
+ return sharedRepoView(ctx, options)
230
+ }
231
+
232
+ /** The legacy state path shared with the old global route. */
233
+ export function sharedRepoStatePath(): string {
234
+ return join(dshHome(), 'storages', STATE_FILE_NAME)
235
+ }
236
+
237
+ /** The legacy deploy-key path shared with the old global route. */
238
+ export function sharedStoredKeyPath(): string {
239
+ return join(dshHome(), 'storages', KEY_FILE_NAME)
240
+ }
241
+
242
+ /** The SSH identity for the shared repository. */
243
+ export async function sharedKeyStatus(state: SharedRepoState): Promise<KeyStatus> {
244
+ if (state.keyPath !== '') {
245
+ let file: string
246
+ try {
247
+ file = expandAbsolute(state.keyPath)
248
+ } catch {
249
+ return { source: 'none', file: undefined, hasStoredKey: await exists(sharedStoredKeyPath()) }
250
+ }
251
+ if (await exists(file)) return { source: 'path', file, hasStoredKey: await exists(sharedStoredKeyPath()) }
252
+ }
253
+ const stored = sharedStoredKeyPath()
254
+ if (await exists(stored)) return { source: 'stored', file: stored, hasStoredKey: true }
255
+ const fallback = globalKeyPath()
256
+ if (await exists(fallback)) return { source: 'global', file: fallback, hasStoredKey: false }
257
+ return { source: 'none', file: undefined, hasStoredKey: false }
258
+ }
259
+
260
+ /** Inspect the shared checkout. */
261
+ async function targetStatus(ctx: Context, state: SharedRepoState): Promise<SharedRepoTarget> {
262
+ const target = state.targetDir
263
+ if (!(await exists(target))) return { exists: false, isRepo: false, branch: null, commit: null, dirty: false, skills: 0 }
264
+ const root = await runGit(['-C', target, 'rev-parse', '--show-toplevel'], undefined, undefined)
265
+ if (root.code !== 0 || resolve(root.stdout.trim()) !== resolve(target)) {
266
+ return { exists: true, isRepo: false, branch: null, commit: null, dirty: false, skills: 0 }
267
+ }
268
+ const branch = await runGit(['-C', target, 'rev-parse', '--abbrev-ref', 'HEAD'], undefined, undefined)
269
+ const commit = await runGit(['-C', target, 'rev-parse', 'HEAD'], undefined, undefined)
270
+ const dirty = await runGit(['-C', target, 'status', '--porcelain'], undefined, undefined)
271
+ const skills = await countSkills(ctx, target)
272
+ return {
273
+ exists: true,
274
+ isRepo: true,
275
+ branch: branch.code === 0 ? branch.stdout.trim() : null,
276
+ commit: commit.code === 0 ? commit.stdout.trim() : null,
277
+ dirty: dirty.code === 0 && dirty.stdout.trim() !== '',
278
+ skills,
279
+ }
280
+ }
281
+
282
+ /** Count enabled SKILL.md files inside the shared checkout. */
283
+ async function countSkills(ctx: Context, root: string): Promise<number> {
284
+ let count = 0
285
+ await walkFiles(root, SKILL_SCAN_DEPTH, new Set(IGNORED_DIRS), (path) => {
286
+ if (path.endsWith('/SKILL.md') || path.endsWith('\\SKILL.md')) count += 1
287
+ }, ctx)
288
+ return count
289
+ }
290
+
291
+ /** Persist the shared repository settings. */
292
+ async function writeSharedRepoState(state: SharedRepoState): Promise<void> {
293
+ const file = sharedRepoStatePath()
294
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 })
295
+ const temp = file + '.' + randomSuffix() + '.tmp'
296
+ try {
297
+ await writeFile(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
298
+ await rename(temp, file)
299
+ } catch (error) {
300
+ await rm(temp, { force: true })
301
+ throw error
302
+ }
303
+ await chmod(file, 0o600)
304
+ }
305
+
306
+ /** Build a sanitized git failure. */
307
+ function pullError(prefix: string, outcome: GitOutcome): AgentsError {
308
+ const detail = outcome.stderr.trim() || outcome.spawnError || (outcome.timedOut ? 'timeout' : 'exit ' + String(outcome.code))
309
+ return new AgentsError(prefix + ':' + detail.split(/\r?\n/).slice(0, 3).join(' / '), 500)
310
+ }
311
+
312
+ /** Read one string field or its fallback. */
313
+ function textValue(value: unknown, fallback: string): string {
314
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
315
+ }
316
+
317
+ /** Read one absolute path field or its fallback. */
318
+ function absoluteValue(value: unknown, fallback: string): string {
319
+ if (typeof value !== 'string' || value.trim() === '') return fallback
320
+ try {
321
+ return expandAbsolute(value)
322
+ } catch {
323
+ return fallback
324
+ }
325
+ }
326
+
327
+ /** Normalize a persisted sync record. */
328
+ function normalizeSync(raw: unknown): SyncRecord | null {
329
+ if (raw === null || typeof raw !== 'object') return null
330
+ const record = raw as Record<string, unknown>
331
+ return {
332
+ at: typeof record.at === 'string' ? record.at : '',
333
+ ok: record.ok === true,
334
+ commit: typeof record.commit === 'string' ? record.commit : '',
335
+ skills: typeof record.skills === 'number' ? record.skills : 0,
336
+ message: typeof record.message === 'string' ? record.message : '',
337
+ }
338
+ }
339
+
340
+ /** Short random suffix for one temporary file. */
341
+ function randomSuffix(): string {
342
+ return process.pid.toString(36) + Math.random().toString(36).slice(2, 8)
343
+ }