@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
package/src/legacy.ts ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Bridge legacy directory presets into the live DSH preset registry.
3
+ *
4
+ * DSH 0.2.x no longer scans $DSH_HOME/.agent-presets by itself. This panel
5
+ * still treats those directories as editable sources, so this module registers
6
+ * each one as a real Agent preset: the declaration contains one cordis:include
7
+ * row pointing at the directory's agent.cordis.yml. The Loader's include plugin
8
+ * parses the same !!js entry list the legacy directory always used, and keeps
9
+ * watching it for edits.
10
+ *
11
+ * @module dsh-utils/utils-agents/legacy
12
+ */
13
+
14
+ import { access } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+ import { pathToFileURL } from 'node:url'
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import { discoverPresets } from './presets.js'
19
+ import {
20
+ errorMessage,
21
+ normalizeOptions,
22
+ serviceOf,
23
+ type PresetInfo,
24
+ type AgentsConfig,
25
+ } from './util.js'
26
+
27
+ /** Registry methods this bridge uses. */
28
+ interface PresetRegistry {
29
+ list(): Promise<Array<{ id: string; broken?: string }>>
30
+ register(definition: Record<string, unknown>): Promise<() => Promise<void>>
31
+ }
32
+
33
+ /** One registered directory preset. */
34
+ interface Registered {
35
+ readonly id: string
36
+ readonly path: string
37
+ unregister: (() => Promise<void>) | undefined
38
+ error: string | undefined
39
+ }
40
+
41
+ /** Live status for one directory preset. */
42
+ export interface LegacyStatus {
43
+ readonly registered: boolean
44
+ readonly broken: string | undefined
45
+ }
46
+
47
+ /** The bridge owned by one plugin instance. */
48
+ export interface LegacyBridge {
49
+ ensure(): Promise<void>
50
+ status(): Map<string, LegacyStatus>
51
+ dispose(): Promise<void>
52
+ }
53
+
54
+ /**
55
+ * Create the bridge. Registration is lazy: the first list request performs it,
56
+ * so the route can report a useful status even when agentPresets is absent.
57
+ */
58
+ export function createLegacyBridge(ctx: Context, config: AgentsConfig): LegacyBridge {
59
+ const records = new Map<string, Registered>()
60
+ const statuses = new Map<string, LegacyStatus>()
61
+ let inflight: Promise<void> | null = null
62
+ let disposed = false
63
+
64
+ const ensure = async function (): Promise<void> {
65
+ if (disposed) return
66
+ if (inflight !== null) return await inflight
67
+ inflight = run().finally(function () { inflight = null })
68
+ return await inflight
69
+ }
70
+
71
+ const run = async function (): Promise<void> {
72
+ const options = normalizeOptions(config)
73
+ const presets = await discoverPresets(ctx, options)
74
+ const byId = new Map<string, PresetInfo>()
75
+ for (const preset of presets) if (!byId.has(preset.id)) byId.set(preset.id, preset)
76
+
77
+ for (const [id, record] of [...records]) {
78
+ if (byId.has(id)) continue
79
+ records.delete(id)
80
+ if (record.unregister !== undefined) {
81
+ try {
82
+ await record.unregister()
83
+ } catch (error) {
84
+ ctx.logger.warn('utils-agents: cannot unregister legacy preset ' + id + ': ' + errorMessage(error))
85
+ }
86
+ }
87
+ }
88
+
89
+ const registry = serviceOf(ctx, 'agentPresets') as PresetRegistry | undefined
90
+ if (registry === undefined || typeof registry.register !== 'function') {
91
+ statuses.clear()
92
+ for (const id of byId.keys()) statuses.set(id, { registered: false, broken: '宿主没有提供 agentPresets 服务' })
93
+ return
94
+ }
95
+
96
+ let listed: Array<{ id: string; broken?: string }> = []
97
+ try {
98
+ listed = await registry.list()
99
+ } catch (error) {
100
+ ctx.logger.warn('utils-agents: cannot list agent presets: ' + errorMessage(error))
101
+ }
102
+ const known = new Set(listed.map((row) => row.id))
103
+
104
+ let order = 1000
105
+ for (const preset of byId.values()) {
106
+ order += 1
107
+ if (known.has(preset.id) || records.has(preset.id)) continue
108
+ const composition = join(preset.path, 'agent.cordis.yml')
109
+ try {
110
+ await access(composition)
111
+ } catch {
112
+ records.set(preset.id, { id: preset.id, path: preset.path, unregister: undefined, error: '缺少 agent.cordis.yml' })
113
+ continue
114
+ }
115
+ try {
116
+ const unregister = await registry.register({
117
+ id: preset.id,
118
+ name: preset.name,
119
+ description: preset.description,
120
+ order,
121
+ plugins: [{
122
+ id: 'legacy-agent-composition',
123
+ name: 'cordis:include',
124
+ config: { path: pathToFileURL(composition).href },
125
+ }],
126
+ })
127
+ records.set(preset.id, { id: preset.id, path: preset.path, unregister, error: undefined })
128
+ ctx.logger.info('utils-agents: registered legacy agent preset ' + preset.id)
129
+ } catch (error) {
130
+ const message = errorMessage(error)
131
+ records.set(preset.id, { id: preset.id, path: preset.path, unregister: undefined, error: message })
132
+ ctx.logger.warn('utils-agents: cannot register legacy preset ' + preset.id + ': ' + message)
133
+ }
134
+ }
135
+
136
+ try {
137
+ listed = await registry.list()
138
+ } catch {
139
+ // Keep the previous listing when the registry is temporarily unavailable.
140
+ }
141
+ const broken = new Map(listed.map((row) => [row.id, row.broken]))
142
+ statuses.clear()
143
+ for (const preset of byId.values()) {
144
+ const record = records.get(preset.id)
145
+ const inRegistry = broken.has(preset.id)
146
+ statuses.set(preset.id, {
147
+ registered: inRegistry,
148
+ broken: inRegistry ? broken.get(preset.id) : record?.error,
149
+ })
150
+ }
151
+ }
152
+
153
+ return {
154
+ ensure,
155
+ status: function (): Map<string, LegacyStatus> { return new Map(statuses) },
156
+ dispose: async function (): Promise<void> {
157
+ disposed = true
158
+ for (const record of records.values()) {
159
+ if (record.unregister === undefined) continue
160
+ try {
161
+ await record.unregister()
162
+ } catch (error) {
163
+ ctx.logger.warn('utils-agents: cannot dispose legacy preset ' + record.id + ': ' + errorMessage(error))
164
+ }
165
+ }
166
+ records.clear()
167
+ statuses.clear()
168
+ },
169
+ }
170
+ }
package/src/native.ts ADDED
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Takeover support for presets declared outside the panel.
3
+ *
4
+ * DSH presets normally come from Cordis rows (the shipped standard/ptc presets
5
+ * or a bundle such as dsh-butler-preset). The panel can import every
6
+ * non-built-in declaration as a directory preset under
7
+ * "$DSH_HOME/.agent-presets/<id>", and publish the resulting directories into
8
+ * the shared skill repository under ".dsh/preset" before committing/pushing.
9
+ *
10
+ * The built-in allowlist is configuration, so a deployment can keep additional
11
+ * shipped ids native without changing code.
12
+ *
13
+ * @module dsh-utils/utils-agents/native
14
+ */
15
+
16
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
17
+ import { basename, dirname, join, relative, resolve } from 'node:path'
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import { discoverPresets } from './presets.js'
20
+ import { readSharedRepoState, sharedKeyStatus } from './global-repo.js'
21
+ import { runGit, type GitOutcome } from './git.js'
22
+ import {
23
+ AgentsError,
24
+ dshHome,
25
+ errorMessage,
26
+ exists,
27
+ serviceOf,
28
+ stringList,
29
+ type Options,
30
+ } from './util.js'
31
+ import { sharedPresetId } from './shared.js'
32
+
33
+ /** Directory trees never copied into the shared repository. */
34
+ const IGNORED_PUBLISH_DIRS = new Set(['.git', 'node_modules', '.dsh-utils', '.temp', '.tmp'])
35
+
36
+ /** The registry surface this module needs. */
37
+ interface NativeRegistry {
38
+ list(): Promise<Array<{ id: string; name?: string; description?: string }>>
39
+ readDocument?(id: string): Promise<{ content: string; name?: string; description?: string }>
40
+ }
41
+
42
+ /** One declared preset as the panel lists it. */
43
+ export interface NativePresetRow {
44
+ readonly id: string
45
+ readonly name: string
46
+ readonly description: string
47
+ readonly builtin: boolean
48
+ readonly directory: boolean
49
+ readonly importable: boolean
50
+ }
51
+
52
+ /** The takeover view returned to the browser. */
53
+ export interface NativePresetView {
54
+ readonly builtin: string[]
55
+ readonly localRoot: string
56
+ readonly presets: NativePresetRow[]
57
+ }
58
+
59
+ /** Outcome for one import attempt. */
60
+ export interface NativeImportResult {
61
+ readonly id: string
62
+ readonly status: 'imported' | 'exists' | 'skipped' | 'error'
63
+ readonly path?: string
64
+ readonly error?: string
65
+ }
66
+
67
+ /** Outcome for one publish attempt. */
68
+ export interface PublishResult {
69
+ readonly id: string
70
+ readonly files: number
71
+ }
72
+
73
+ /** The response of one publish request. */
74
+ export interface PublishPayload {
75
+ readonly target: string
76
+ readonly branch: string
77
+ readonly commit: string
78
+ readonly pushed: boolean
79
+ readonly results: PublishResult[]
80
+ }
81
+
82
+ /**
83
+ * List every declared preset and whether the panel can take it over.
84
+ * @param ctx - host context.
85
+ * @param options - normalized settings.
86
+ */
87
+ export async function nativePresetView(ctx: Context, options: Options): Promise<NativePresetView> {
88
+ const registry = nativeRegistry(ctx)
89
+ const rows = registry === undefined ? [] : await registry.list()
90
+ const directories = new Map<string, string>()
91
+ for (const preset of await discoverPresets(ctx, options)) directories.set(preset.id, preset.path)
92
+ return {
93
+ builtin: options.builtinPresets,
94
+ localRoot: join(dshHome(), '.agent-presets'),
95
+ presets: rows.map((row) => {
96
+ const builtin = options.builtinPresets.includes(row.id)
97
+ const directory = directories.has(row.id)
98
+ return {
99
+ id: row.id,
100
+ name: row.name === undefined || row.name === '' ? row.id : row.name,
101
+ description: row.description ?? '',
102
+ builtin,
103
+ directory,
104
+ importable: !builtin && !directory,
105
+ }
106
+ }),
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Import non-built-in declarations as directory presets.
112
+ * @param ctx - host context.
113
+ * @param options - normalized settings.
114
+ * @param body - request body with optional "ids" and "force".
115
+ */
116
+ export async function importNativePresets(
117
+ ctx: Context,
118
+ options: Options,
119
+ body: Record<string, unknown>,
120
+ ): Promise<{ results: NativeImportResult[]; view: NativePresetView }> {
121
+ const registry = nativeRegistry(ctx)
122
+ if (registry === undefined || typeof registry.readDocument !== 'function') {
123
+ throw new AgentsError('宿主没有提供 agentPresets.readDocument,无法导出原生预设', 409)
124
+ }
125
+ const requested = stringList(body.ids)
126
+ const force = body.force === true
127
+ const listed = await nativePresetView(ctx, options)
128
+ const targets = requested.length === 0
129
+ ? listed.presets.filter((row) => row.importable)
130
+ : listed.presets.filter((row) => requested.includes(row.id))
131
+ if (requested.length > 0 && targets.length === 0) throw new AgentsError('没有找到要导入的预设:' + requested.join(', '), 404)
132
+
133
+ const results: NativeImportResult[] = []
134
+ for (const row of targets) {
135
+ if (row.builtin) {
136
+ results.push({ id: row.id, status: 'skipped', error: '内置预设不导入' })
137
+ continue
138
+ }
139
+ const id = sharedPresetId(row.id)
140
+ if (id === null) {
141
+ results.push({ id: row.id, status: 'error', error: '预设 id 不能作为目录名' })
142
+ continue
143
+ }
144
+ const target = join(dshHome(), '.agent-presets', id)
145
+ if (await exists(target) && !force) {
146
+ results.push({ id, status: 'exists', path: target })
147
+ continue
148
+ }
149
+ try {
150
+ const document = await registry.readDocument(row.id)
151
+ if (typeof document.content !== 'string' || document.content.trim() === '') {
152
+ throw new AgentsError('预设组合为空,拒绝导入', 409)
153
+ }
154
+ await mkdir(join(target, 'skills'), { recursive: true, mode: 0o755 })
155
+ await writeAtomic(join(target, 'preset.yml'), presetYaml(document.name ?? row.name, document.description ?? row.description))
156
+ await writeAtomic(join(target, 'agent.cordis.yml'), document.content)
157
+ results.push({ id, status: 'imported', path: target })
158
+ ctx.logger.info('utils-agents: imported native preset ' + id)
159
+ } catch (error) {
160
+ const message = errorMessage(error)
161
+ ctx.logger.warn('utils-agents: cannot import native preset ' + row.id + ': ' + message)
162
+ results.push({ id: row.id, status: 'error', error: message })
163
+ }
164
+ }
165
+ return { results, view: await nativePresetView(ctx, options) }
166
+ }
167
+
168
+ /**
169
+ * Copy local non-built-in presets into the shared repository and commit/push.
170
+ * @param ctx - host context.
171
+ * @param options - normalized settings.
172
+ * @param body - request body with optional "ids", "message" and "push".
173
+ */
174
+ export async function publishPresets(
175
+ ctx: Context,
176
+ options: Options,
177
+ body: Record<string, unknown>,
178
+ ): Promise<PublishPayload> {
179
+ const requested = stringList(body.ids)
180
+ const push = body.push !== false
181
+ const message = typeof body.message === 'string' && body.message.trim() !== '' ? body.message.trim() : 'presets: sync from dsh-utils'
182
+ const state = await readSharedRepoState(options)
183
+ const key = await sharedKeyStatus(state)
184
+ if (state.keyPath !== '' && key.file === undefined) throw new AgentsError('配置的密钥路径不存在', 409)
185
+ const target = state.targetDir
186
+ if (!(await exists(target))) throw new AgentsError('共享仓库尚未检出,请先在“共享技能仓库”里拉取:' + target, 409)
187
+ const keyArg = key.file
188
+ const root = await runGit(['-C', target, 'rev-parse', '--show-toplevel'], undefined, keyArg)
189
+ if (root.code !== 0 || resolve(root.stdout.trim()) !== resolve(target)) {
190
+ throw new AgentsError('共享仓库不是该仓库的 Git checkout:' + target, 409)
191
+ }
192
+ const branch = await runGit(['-C', target, 'rev-parse', '--abbrev-ref', 'HEAD'], undefined, key.file)
193
+ if (branch.code !== 0) throw pullError('读取当前分支失败', branch)
194
+ if (branch.stdout.trim() !== state.branch) {
195
+ throw new AgentsError('共享仓库当前分支是 ' + branch.stdout.trim() + ',配置分支是 ' + state.branch, 409)
196
+ }
197
+
198
+ const presets = (await discoverPresets(ctx, options))
199
+ .filter((preset) => !options.builtinPresets.includes(preset.id))
200
+ .filter((preset) => requested.length === 0 || requested.includes(preset.id))
201
+ if (requested.length > 0 && presets.length === 0) throw new AgentsError('没有找到要发布的预设:' + requested.join(', '), 404)
202
+
203
+ const results: PublishResult[] = []
204
+ for (const preset of presets) {
205
+ const destination = join(target, '.dsh', 'preset', preset.id)
206
+ const files = await copyPresetTree(ctx, preset.path, destination)
207
+ results.push({ id: preset.id, files })
208
+ }
209
+
210
+ const added = await runGit(['-C', target, 'add', '--', '.dsh/preset'], undefined, key.file)
211
+ if (added.code !== 0) throw pullError('暂存共享预设失败', added)
212
+ let commit = ''
213
+ const staged = await runGit(['-C', target, 'diff', '--cached', '--quiet', '--', '.dsh/preset'], undefined, key.file)
214
+ if (staged.code !== 0) {
215
+ const committed = await runGit(['-C', target, 'commit', '-m', message, '--', '.dsh/preset'], undefined, key.file)
216
+ if (committed.code !== 0) throw pullError('提交共享预设失败', committed)
217
+ const head = await runGit(['-C', target, 'rev-parse', 'HEAD'], undefined, key.file)
218
+ commit = head.code === 0 ? head.stdout.trim() : ''
219
+ }
220
+ let pushed = false
221
+ if (push && commit !== '') {
222
+ const pushedResult = await runGit(['-C', target, 'push', 'origin', 'HEAD:' + state.branch], undefined, key.file)
223
+ if (pushedResult.code !== 0) throw pullError('推送共享预设失败', pushedResult)
224
+ pushed = true
225
+ }
226
+ return { target, branch: state.branch, commit, pushed, results }
227
+ }
228
+
229
+ /** Locate the live preset registry. */
230
+ function nativeRegistry(ctx: Context): NativeRegistry | undefined {
231
+ const service = serviceOf(ctx, 'agentPresets')
232
+ if (service === undefined || typeof service.list !== 'function') return undefined
233
+ return service as unknown as NativeRegistry
234
+ }
235
+
236
+ /** Copy one preset directory, skipping local-only trees and symlinks. */
237
+ async function copyPresetTree(ctx: Context, source: string, destination: string): Promise<number> {
238
+ let count = 0
239
+ const walk = async (dir: string): Promise<void> => {
240
+ let entries
241
+ try {
242
+ entries = await readdir(dir, { withFileTypes: true })
243
+ } catch (error) {
244
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.debug('utils-agents: cannot scan ' + dir + ': ' + errorMessage(error))
245
+ return
246
+ }
247
+ for (const entry of entries) {
248
+ if (IGNORED_PUBLISH_DIRS.has(entry.name)) continue
249
+ const path = join(dir, entry.name)
250
+ if (entry.isDirectory()) {
251
+ await walk(path)
252
+ continue
253
+ }
254
+ if (!entry.isFile()) continue
255
+ const rel = relative(source, path)
256
+ const target = join(destination, rel)
257
+ await mkdir(dirname(target), { recursive: true, mode: 0o755 })
258
+ const content = await readFile(path)
259
+ await writeAtomic(target, content)
260
+ count += 1
261
+ }
262
+ }
263
+ await mkdir(destination, { recursive: true, mode: 0o755 })
264
+ await walk(source)
265
+ return count
266
+ }
267
+
268
+ /** Render one preset.yml document. */
269
+ function presetYaml(name: string, description: string): string {
270
+ const lines = ['name: ' + JSON.stringify(name)]
271
+ if (description !== '') lines.push('description: ' + JSON.stringify(description))
272
+ return lines.join('\n') + '\n'
273
+ }
274
+
275
+ /** Write one file through a temporary sibling. */
276
+ async function writeAtomic(target: string, content: string | Buffer): Promise<void> {
277
+ const temp = join(dirname(target), '.' + basename(target) + '.' + process.pid.toString(36) + Math.random().toString(36).slice(2, 8) + '.tmp')
278
+ try {
279
+ await writeFile(temp, content, { mode: 0o644, flag: 'wx' })
280
+ await rename(temp, target)
281
+ } catch (error) {
282
+ await rm(temp, { force: true })
283
+ throw error
284
+ }
285
+ }
286
+
287
+ /** Build a sanitized git failure. */
288
+ function pullError(prefix: string, outcome: GitOutcome): AgentsError {
289
+ const detail = outcome.stderr.trim() || outcome.spawnError || (outcome.timedOut ? 'timeout' : 'exit ' + String(outcome.code))
290
+ return new AgentsError(prefix + ':' + detail.split(/\r?\n/).slice(0, 3).join(' / '), 500)
291
+ }