@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.
@@ -2,18 +2,26 @@
2
2
  * Shared skill repository support for the utils-agents panel.
3
3
  *
4
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.
5
+ * clones or fast-forwards it with an optional Deploy Key, the shared preset
6
+ * scanner reads ".dsh/preset" from that checkout, and Skill discovery scans it
7
+ * recursively from its own root. When the shared repository has no key path
8
+ * and no key of its own, the panel-wide Deploy Key from git.js is used, so a
9
+ * private skills checkout pulls without extra setup.
10
+ *
11
+ * Settings live in the consolidated document
12
+ * `$DSH_HOME/utils/utils.json` (see utils-config.ts); the old
13
+ * `storages/dsh-utils-ui.json` document is migrated on first read. The pasted
14
+ * key intentionally keeps its former path (`dsh-utils-ui.deploy-key`), so an
15
+ * upgraded profile keeps its repository and key.
16
+ *
17
+ * A timer (skill-repo-updater.ts) calls {@link updateSkillRepositories}: it
18
+ * fast-forwards every configured checkout and refreshes its submodules, but
19
+ * never merges over a dirty working tree and never resets or pushes.
12
20
  *
13
21
  * @module dsh-utils/utils-agents/global-repo
14
22
  */
15
23
 
16
- import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
24
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises'
17
25
  import { dirname, isAbsolute, join, resolve } from 'node:path'
18
26
  import type { Context } from '@deepseek-ai/cordis'
19
27
  import {
@@ -36,27 +44,22 @@ import {
36
44
  expandAbsolute,
37
45
  walkFiles,
38
46
  type Options,
39
- type SyncRecord,
40
47
  } 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'
48
+ import {
49
+ defaultSkillRepository,
50
+ readUtilsConfig,
51
+ writeUtilsConfig,
52
+ type SkillRepositoryConfig,
53
+ } from './utils-config.js'
44
54
 
45
55
  /** Legacy deploy-key file name; never returned to the browser. */
46
56
  const KEY_FILE_NAME = 'dsh-utils-ui.deploy-key'
47
57
 
48
- /** Depth used when counting skills in the shared checkout. */
58
+ /** Depth used when counting skills in a shared checkout. */
49
59
  const SKILL_SCAN_DEPTH = 8
50
60
 
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
- }
61
+ /** Durable settings for one shared skill repository. */
62
+ export type SharedRepoState = SkillRepositoryConfig
60
63
 
61
64
  /** Checkout status for the shared skill repository. */
62
65
  export interface SharedRepoTarget {
@@ -75,31 +78,34 @@ export interface SharedRepoView {
75
78
  key: KeyStatus
76
79
  }
77
80
 
81
+ /** How one automatic refresh ended. */
82
+ export interface SkillRepositoryUpdate {
83
+ readonly targetDir: string
84
+ readonly repoUrl: string
85
+ readonly ok: boolean
86
+ readonly changed: boolean
87
+ readonly skipped: boolean
88
+ readonly message: string
89
+ }
90
+
91
+ /** Per-call switch for one repository sync. */
92
+ interface SyncOptions {
93
+ /** Refuse to fetch/merge over uncommitted changes (the timer's choice). */
94
+ readonly skipDirty: boolean
95
+ }
96
+
97
+ /** One completed repository sync. */
98
+ interface SyncResult {
99
+ readonly target: SharedRepoTarget
100
+ readonly message: string
101
+ readonly changed: boolean
102
+ readonly skipped: boolean
103
+ }
104
+
78
105
  /** Read the shared repository settings, filling defaults. */
79
106
  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
- }
107
+ const { config } = await readUtilsConfig()
108
+ return config.skillRepositories[0] ?? defaultSkillRepository(options)
103
109
  }
104
110
 
105
111
  /** Read the shared repository settings plus checkout and key status. */
@@ -132,14 +138,17 @@ export async function saveSharedRepoConfig(ctx: Context, options: Options, body:
132
138
  throw new AgentsError('密钥路径不合法:' + keyPath, 400)
133
139
  }
134
140
  }
135
- await writeSharedRepoState({
141
+ const saved: SharedRepoState = {
136
142
  repoUrl,
137
143
  branch,
138
144
  targetDir: resolvedTarget,
139
145
  keyPath,
140
146
  recurseSubmodules,
141
147
  lastSync: current.lastSync,
142
- })
148
+ }
149
+ const { config } = await readUtilsConfig()
150
+ config.skillRepositories = [saved, ...config.skillRepositories.slice(1)]
151
+ await writeUtilsConfig(config)
143
152
  return sharedRepoView(ctx, options)
144
153
  }
145
154
 
@@ -151,7 +160,7 @@ export async function saveSharedRepoKey(ctx: Context, options: Options, key: str
151
160
  return sharedRepoView(ctx, options)
152
161
  }
153
162
  if (key.includes(String.fromCharCode(0))) throw new AgentsError('Deploy Key 不能包含 NUL 字符', 400)
154
- await mkdir(join(dshHome(), 'storages'), { recursive: true, mode: 0o700 })
163
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 })
155
164
  const temp = file + '.' + randomSuffix() + '.tmp'
156
165
  try {
157
166
  await writeFile(temp, key.trimEnd() + '\n', { mode: 0o600, flag: 'wx' })
@@ -166,7 +175,105 @@ export async function saveSharedRepoKey(ctx: Context, options: Options, key: str
166
175
 
167
176
  /** Clone or fast-forward the shared repository with the configured key. */
168
177
  export async function pullSharedRepo(ctx: Context, options: Options): Promise<SharedRepoView> {
169
- const state = await readSharedRepoState(options)
178
+ const snapshot = await readUtilsConfig()
179
+ const current = snapshot.config.skillRepositories[0] ?? defaultSkillRepository(options)
180
+ const synced = await syncRepository(ctx, current, { skipDirty: false })
181
+ const next: SharedRepoState = {
182
+ ...current,
183
+ lastSync: {
184
+ at: new Date().toISOString(),
185
+ ok: true,
186
+ commit: synced.target.commit ?? '',
187
+ skills: synced.target.skills,
188
+ message: synced.message,
189
+ },
190
+ }
191
+ const repositories = snapshot.config.skillRepositories.length > 0
192
+ ? [next, ...snapshot.config.skillRepositories.slice(1)]
193
+ : [next]
194
+ await writeUtilsConfig({ ...snapshot.config, skillRepositories: repositories })
195
+ return { state: next, target: synced.target, key: await sharedKeyStatus(next) }
196
+ }
197
+
198
+ /**
199
+ * Refresh every configured Skill repository and its submodules.
200
+ *
201
+ * This is the timer's entry point: best-effort per repository, never over a
202
+ * dirty working tree, and failures are reported instead of thrown.
203
+ * @param ctx - plugin context for warnings.
204
+ * @returns one result per configured repository.
205
+ */
206
+ export async function updateSkillRepositories(ctx: Context): Promise<SkillRepositoryUpdate[]> {
207
+ const snapshot = await readUtilsConfig()
208
+ const { skillRepositories } = snapshot.config
209
+ if (skillRepositories.length === 0) return []
210
+ const results: SkillRepositoryUpdate[] = []
211
+ let dirty = false
212
+ for (let index = 0; index < skillRepositories.length; index += 1) {
213
+ const repository = skillRepositories[index]
214
+ try {
215
+ const synced = await syncRepository(ctx, repository, { skipDirty: true })
216
+ if (synced.skipped) {
217
+ results.push({
218
+ targetDir: repository.targetDir,
219
+ repoUrl: repository.repoUrl,
220
+ ok: true,
221
+ changed: false,
222
+ skipped: true,
223
+ message: synced.message,
224
+ })
225
+ continue
226
+ }
227
+ skillRepositories[index] = {
228
+ ...repository,
229
+ lastSync: {
230
+ at: new Date().toISOString(),
231
+ ok: true,
232
+ commit: synced.target.commit ?? '',
233
+ skills: synced.target.skills,
234
+ message: synced.message,
235
+ },
236
+ }
237
+ dirty = true
238
+ results.push({
239
+ targetDir: repository.targetDir,
240
+ repoUrl: repository.repoUrl,
241
+ ok: true,
242
+ changed: synced.changed,
243
+ skipped: false,
244
+ message: synced.message,
245
+ })
246
+ } catch (error) {
247
+ const message = errorMessage(error)
248
+ ctx.logger.warn('utils-agents: skill repository update failed for ' + repository.targetDir + ': ' + message)
249
+ results.push({
250
+ targetDir: repository.targetDir,
251
+ repoUrl: repository.repoUrl,
252
+ ok: false,
253
+ changed: false,
254
+ skipped: false,
255
+ message,
256
+ })
257
+ }
258
+ }
259
+ if (dirty) {
260
+ try {
261
+ await writeUtilsConfig(snapshot.config)
262
+ } catch (error) {
263
+ ctx.logger.debug('utils-agents: cannot persist skill repository state: ' + errorMessage(error))
264
+ }
265
+ }
266
+ return results
267
+ }
268
+
269
+ /**
270
+ * Clone or fast-forward one configured checkout, then refresh its submodules.
271
+ * @param ctx - plugin context for warnings.
272
+ * @param state - one repository configuration.
273
+ * @param options - per-call behavior.
274
+ * @returns the new status plus whether the checkout changed.
275
+ */
276
+ async function syncRepository(ctx: Context, state: SharedRepoState, options: SyncOptions): Promise<SyncResult> {
170
277
  const key = await sharedKeyStatus(state)
171
278
  if (state.keyPath !== '' && key.file === undefined) throw new AgentsError('配置的密钥路径不存在', 409)
172
279
  const parsed = validateRepoUrl(state.repoUrl)
@@ -175,12 +282,14 @@ export async function pullSharedRepo(ctx: Context, options: Options): Promise<Sh
175
282
  const target = state.targetDir
176
283
  const cloneUrl = cloneUrlFor(parsed, key.file)
177
284
  let message = ''
285
+ let changed = false
178
286
 
179
287
  if (!(await exists(target))) {
180
288
  await mkdir(dirname(target), { recursive: true })
181
289
  const cloned = await runGit(['clone', '--depth', '1', '--branch', state.branch, '--single-branch', cloneUrl, target], undefined, key.file)
182
290
  if (cloned.code !== 0) throw pullError('克隆仓库失败', cloned)
183
291
  message = '已 clone 分支 ' + state.branch
292
+ changed = true
184
293
  } else {
185
294
  if (!(await directoryOf(target))) throw new AgentsError('检出目录已存在但不是目录:' + target, 409)
186
295
  const root = await runGit(['-C', target, 'rev-parse', '--show-toplevel'], undefined, key.file)
@@ -197,6 +306,18 @@ export async function pullSharedRepo(ctx: Context, options: Options): Promise<Sh
197
306
  if (current.stdout.trim() !== state.branch) {
198
307
  throw new AgentsError('检出目录当前分支是 ' + current.stdout.trim() + ',配置分支是 ' + state.branch, 409)
199
308
  }
309
+ if (options.skipDirty) {
310
+ const dirty = await runGit(['-C', target, 'status', '--porcelain'], undefined, key.file)
311
+ if (dirty.code === 0 && dirty.stdout.trim() !== '') {
312
+ return {
313
+ target: await targetStatus(ctx, state),
314
+ message: '工作区有本地改动,跳过自动更新',
315
+ changed: false,
316
+ skipped: true,
317
+ }
318
+ }
319
+ }
320
+ const before = await runGit(['-C', target, 'rev-parse', 'HEAD'], undefined, key.file)
200
321
  const shallow = await runGit(['-C', target, 'rev-parse', '--is-shallow-repository'], undefined, key.file)
201
322
  const fetchArgs = shallow.code === 0 && shallow.stdout.trim() === 'true'
202
323
  ? ['-C', target, 'fetch', '--unshallow', 'origin', state.branch]
@@ -205,33 +326,23 @@ export async function pullSharedRepo(ctx: Context, options: Options): Promise<Sh
205
326
  if (fetched.code !== 0) throw pullError('fetch 失败', fetched)
206
327
  const merged = await runGit(['-C', target, 'merge', '--ff-only', 'FETCH_HEAD'], undefined, key.file)
207
328
  if (merged.code !== 0) throw pullError('快进合并失败', merged)
208
- message = '已快进到最新提交'
329
+ const after = await runGit(['-C', target, 'rev-parse', 'HEAD'], undefined, key.file)
330
+ changed = before.code !== 0 || after.code !== 0 || before.stdout.trim() !== after.stdout.trim()
331
+ message = changed ? '已快进到最新提交' : '已是最新提交'
209
332
  }
210
333
 
211
334
  if (state.recurseSubmodules) {
212
335
  const sync = await runGit(['-C', target, 'submodule', 'sync', '--recursive'], undefined, key.file)
213
336
  if (sync.code !== 0) ctx.logger.warn('utils-agents: shared submodule sync failed: ' + sync.stderr.trim())
214
337
  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())
338
+ if (update.code !== 0) {
339
+ ctx.logger.warn('utils-agents: shared submodule update failed: ' + update.stderr.trim())
340
+ } else if (update.stdout.trim() !== '') {
341
+ changed = true
342
+ }
216
343
  }
217
344
 
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)
345
+ return { target: await targetStatus(ctx, state), message, changed, skipped: false }
235
346
  }
236
347
 
237
348
  /** The legacy deploy-key path shared with the old global route. */
@@ -288,21 +399,6 @@ async function countSkills(ctx: Context, root: string): Promise<number> {
288
399
  return count
289
400
  }
290
401
 
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
402
  /** Build a sanitized git failure. */
307
403
  function pullError(prefix: string, outcome: GitOutcome): AgentsError {
308
404
  const detail = outcome.stderr.trim() || outcome.spawnError || (outcome.timedOut ? 'timeout' : 'exit ' + String(outcome.code))
@@ -314,29 +410,6 @@ function textValue(value: unknown, fallback: string): string {
314
410
  return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
315
411
  }
316
412
 
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
413
  /** Short random suffix for one temporary file. */
341
414
  function randomSuffix(): string {
342
415
  return process.pid.toString(36) + Math.random().toString(36).slice(2, 8)
package/src/index.ts CHANGED
@@ -56,7 +56,7 @@ import {
56
56
  type KeyStatus,
57
57
  } from './git.js'
58
58
  import { createLegacyBridge, type LegacyBridge } from './legacy.js'
59
- import { sharedPresetView, syncSharedPresets } from './shared.js'
59
+ import { autoSyncSharedPresets, sharedPresetView, syncSharedPresets } from './shared.js'
60
60
  import { pullSharedRepo, saveSharedRepoConfig, saveSharedRepoKey, sharedRepoView } from './global-repo.js'
61
61
  import { importNativePresets, nativePresetView, publishPresets } from './native.js'
62
62
  import { createUpdateChecker, startUpdateWatcher, type UpdateChecker } from './update.js'
@@ -65,6 +65,7 @@ import {
65
65
  applySkillDiscovery,
66
66
  type SkillDiscoveryConfig,
67
67
  } from './skill-discovery.js'
68
+ import { startSkillRepositoryUpdater } from './skill-repo-updater.js'
68
69
  import {
69
70
  ROUTE_PATH as SKILL_PANEL_ROUTE,
70
71
  applySkillPanel,
@@ -121,6 +122,8 @@ export const Config = z.object({
121
122
  .description('扫描项目级 .dsh/skills 与 .agents/skills。').volatile(),
122
123
  includeUserRoots: z.boolean().default(SKILL_DISCOVERY_DEFAULTS.includeUserRoots)
123
124
  .description('扫描用户级技能根。').volatile(),
125
+ includeSkillRepositories: z.boolean().default(SKILL_DISCOVERY_DEFAULTS.includeSkillRepositories)
126
+ .description('把 $DSH_HOME/utils/utils.json 里配置的 Skill 仓库作为根,从仓库根递归扫描。').volatile(),
124
127
  followSymlinks: z.boolean().default(SKILL_DISCOVERY_DEFAULTS.followSymlinks)
125
128
  .description('跟随符号链接目录(带环路保护)。').volatile(),
126
129
  extraRoots: z.array(z.string().min(1)).default([...SKILL_DISCOVERY_DEFAULTS.extraRoots])
@@ -179,10 +182,24 @@ interface ConnectionLike {
179
182
  export function apply(ctx: Context, config: UtilsAgentsConfig = {}): void {
180
183
  // The two former components are host-only halves of this one now; the browser
181
184
  // half in @xi4z/dsh-utils-ui still renders their pages on this row.
182
- applySkillDiscovery(ctx, config)
185
+ const discovery = applySkillDiscovery(ctx, config)
183
186
  applySkillPanel(ctx, config)
184
187
 
185
188
  const legacy = createLegacyBridge(ctx, config)
189
+ // Keep the configured Skill checkouts (and their submodules) fresh; a pull
190
+ // that moved a checkout refreshes the catalog immediately. The repository is
191
+ // the only source of truth for presets: the same schedule copies new/updated
192
+ // ones into the preset home and removes the ones it no longer carries.
193
+ startSkillRepositoryUpdater(ctx, {
194
+ invalidateSkills: () => discovery.refresh(),
195
+ syncPresets: async () => {
196
+ const payload = await autoSyncSharedPresets(ctx, normalizeOptions(config))
197
+ const synced = payload.results.filter((result) => result.error === undefined)
198
+ if (synced.length === 0 && payload.removed.length === 0) return
199
+ await legacy.ensure()
200
+ ctx.logger.info('utils-agents: auto-synced ' + synced.length + ' shared preset(s), removed ' + payload.removed.length + ' from configured repositories')
201
+ },
202
+ })
186
203
  const updates = createUpdateChecker(ctx, () => normalizeOptions(config))
187
204
  startUpdateWatcher(ctx, updates, () => normalizeOptions(config))
188
205
  ctx.effect(() => () => { void legacy.dispose() }, 'utils-agents: legacy preset bridge')
package/src/shared.ts CHANGED
@@ -27,6 +27,7 @@ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
27
27
  import type { Context } from '@deepseek-ai/cordis'
28
28
  import { scanSkills } from './presets.js'
29
29
  import { readRepoState, targetPath } from './git.js'
30
+ import { readUtilsConfig } from './utils-config.js'
30
31
  import {
31
32
  BODY_LIMIT_BYTES,
32
33
  IGNORED_DIRS,
@@ -37,6 +38,7 @@ import {
37
38
  exists,
38
39
  expandAbsolute,
39
40
  insideJoin,
41
+ isInside,
40
42
  stringList,
41
43
  agentsStorageDir,
42
44
  type Options,
@@ -181,8 +183,92 @@ export async function syncSharedPresets(
181
183
  const targets = requested.length === 0 ? all : all.filter((row) => requested.includes(row.id))
182
184
  if (requested.length > 0 && targets.length === 0) throw new AgentsError('没有找到要同步的预设:' + requested.join(', '), 404)
183
185
 
186
+ const results = await copyPresetRows(ctx, targets, prune, manifest)
187
+ if (results.some((result) => result.error === undefined)) await writeManifest(manifest)
188
+ return { results, view: await sharedPresetView(ctx, options, preset) }
189
+ }
190
+
191
+ /** Payload of one automatic preset pass. */
192
+ export interface AutoPresetSyncPayload extends SharedSyncPayload {
193
+ /** Preset ids whose local copy was removed because the repository dropped them. */
194
+ readonly removed: string[]
195
+ }
196
+
197
+ /**
198
+ * Mirror the presets carried by the configured Skill repositories into the
199
+ * preset home.
200
+ *
201
+ * The repository is the only source of truth: new and outdated presets are
202
+ * copied, and a preset the repository no longer carries is removed locally when
203
+ * an earlier pass synced it (the manifest records that ownership). Built-in
204
+ * presets and presets that only ever existed locally are never touched, and a
205
+ * checkout that is missing or unreadable never triggers a removal.
206
+ * @param ctx - host context.
207
+ * @param options - normalized settings.
208
+ * @returns per-preset results, removed ids, and the refreshed view.
209
+ */
210
+ export async function autoSyncSharedPresets(ctx: Context, options: Options): Promise<AutoPresetSyncPayload> {
211
+ const manifest = await readManifest()
212
+ const view = await sharedPresetView(ctx, options, null)
213
+ const repoRoots = view.sources
214
+ .filter((source) => source.kind === 'global-repo' && source.exists)
215
+ .map((source) => source.path)
216
+ const carried = new Set<string>()
217
+ for (const source of view.sources) {
218
+ if (source.kind !== 'global-repo' || !source.exists) continue
219
+ for (const preset of source.presets) carried.add(preset.id)
220
+ }
221
+
222
+ const removed: string[] = []
223
+ const localRoot = join(dshHome(), '.agent-presets')
224
+ for (const [id, entry] of Object.entries(manifest.presets)) {
225
+ if (carried.has(id) || options.builtinPresets.includes(id) || RESERVED_IDS.has(id)) continue
226
+ if (entry.source === '' || !repoRoots.some((root) => entry.source === root || isInside(root, entry.source))) continue
227
+ delete manifest.presets[id]
228
+ const target = join(localRoot, id)
229
+ if (!(await directoryOf(target))) continue
230
+ try {
231
+ await rm(target, { recursive: true, force: true })
232
+ removed.push(id)
233
+ } catch (error) {
234
+ ctx.logger.warn('utils-agents: cannot remove preset ' + id + ' dropped by the repository: ' + errorMessage(error))
235
+ }
236
+ }
237
+
238
+ const targets = view.sources
239
+ .filter((source) => source.kind === 'global-repo' && source.exists)
240
+ .flatMap((source) => source.presets)
241
+ .filter((row) => !options.builtinPresets.includes(row.id))
242
+ .filter((row) => row.status === 'new' || row.status === 'update')
243
+ // A preset that is already identical must still be recorded as managed, or a
244
+ // later repository deletion could not be told apart from a local-only preset.
245
+ let ownershipChanged = false
246
+ for (const source of view.sources) {
247
+ if (source.kind !== 'global-repo' || !source.exists) continue
248
+ for (const row of source.presets) {
249
+ if (row.status !== 'same' || options.builtinPresets.includes(row.id)) continue
250
+ if (manifest.presets[row.id] !== undefined) continue
251
+ const files = (await collectFiles(ctx, row.sourcePath)).map((file) => file.rel)
252
+ manifest.presets[row.id] = { source: row.sourceRoot, syncedAt: new Date().toISOString(), files }
253
+ ownershipChanged = true
254
+ }
255
+ }
256
+ const results = targets.length === 0 ? [] : await copyPresetRows(ctx, targets, false, manifest)
257
+ if (ownershipChanged || removed.length > 0 || results.some((result) => result.error === undefined)) {
258
+ await writeManifest(manifest)
259
+ }
260
+ return { results, removed, view: await sharedPresetView(ctx, options, null) }
261
+ }
262
+
263
+ /** Copy one scanned batch, recording each outcome in the manifest. */
264
+ async function copyPresetRows(
265
+ ctx: Context,
266
+ rows: readonly SharedPresetView[],
267
+ prune: boolean,
268
+ manifest: SharedManifest,
269
+ ): Promise<SharedSyncResult[]> {
184
270
  const results: SharedSyncResult[] = []
185
- for (const row of targets) {
271
+ for (const row of rows) {
186
272
  if (row.status === 'invalid') {
187
273
  results.push({ id: row.id, status: row.status, written: 0, removed: 0, skipped: [], error: row.reason ?? '预设 id 不合法' })
188
274
  continue
@@ -198,8 +284,7 @@ export async function syncSharedPresets(
198
284
  results.push({ id: row.id, status: row.status, written: 0, removed: 0, skipped: [], error: message })
199
285
  }
200
286
  }
201
- if (results.some((result) => result.error === undefined)) await writeManifest(manifest)
202
- return { results, view: await sharedPresetView(ctx, options, preset) }
287
+ return results
203
288
  }
204
289
 
205
290
  /** The storage path of the shared-preset manifest. */
@@ -490,16 +575,17 @@ async function hashFile(path: string): Promise<string> {
490
575
  return createHash('sha256').update(content).digest('hex')
491
576
  }
492
577
 
493
- /** The checkout the legacy global skill-repository route syncs into. */
494
- async function legacySkillRepoRoot(): Promise<string> {
578
+ /** The checkouts of the configured Skill repositories, from `utils.json`. */
579
+ async function configuredSkillRepoRoots(): Promise<string[]> {
495
580
  try {
496
- const raw = JSON.parse(await readFile(join(dshHome(), 'storages', 'dsh-utils-ui.json'), 'utf8')) as unknown
497
- const record = raw !== null && typeof raw === 'object' ? raw as Record<string, unknown> : {}
498
- if (typeof record.targetDir === 'string' && record.targetDir.trim() !== '') return expandAbsolute(record.targetDir)
581
+ const roots = (await readUtilsConfig()).config.skillRepositories
582
+ .map((repository) => repository.targetDir)
583
+ .filter((path) => path !== '')
584
+ if (roots.length > 0) return roots
499
585
  } catch {
500
- // Missing or malformed legacy state falls back to the shipped default.
586
+ // A missing or malformed document falls back to the shipped default.
501
587
  }
502
- return join(dshHome(), 'skills', 'herskill')
588
+ return [join(dshHome(), 'skills', 'utils-skill')]
503
589
  }
504
590
 
505
591
  /** The repository roots to scan, in display order. */
@@ -514,12 +600,13 @@ async function presetSources(options: Options, preset: PresetInfo | null): Promi
514
600
  // A malformed repository configuration only hides that source.
515
601
  }
516
602
  }
517
- const legacy = await legacySkillRepoRoot()
518
- if (legacy !== null && await directoryOf(legacy)) out.push({ path: legacy, kind: 'global-repo' })
603
+ for (const shared of await configuredSkillRepoRoots()) {
604
+ if (await directoryOf(shared)) out.push({ path: shared, kind: 'global-repo' })
605
+ }
519
606
  const skills = join(dshHome(), 'skills')
520
607
  out.push({ path: skills, kind: 'skills-home' })
521
608
  // The legacy global repository may live one level below (for example
522
- // $DSH_HOME/skills/herskill); treat any child that carries .dsh as a source.
609
+ // $DSH_HOME/skills/utils-skill); treat any child that carries .dsh as a source.
523
610
  try {
524
611
  const entries = await readdir(skills, { withFileTypes: true })
525
612
  entries.sort((left, right) => left.name.localeCompare(right.name))