dsh-skill-harbor 0.5.2 → 0.5.3

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.
@@ -1,516 +1,516 @@
1
- /**
2
- * 路由注册总装 —— 所有 HTTP 入口在这里一次性挂上。
3
- *
4
- * 设计要点:
5
- * - 前缀统一 `/dsh-skill-harbor/api`,写操作全部要求 CSRF 头
6
- * - 写路由只接受 `snapshot.allowlist` 里的路径(不是请求里带来的任意路径)
7
- * - 面板席位在 Phase 2 是独立 api + 客户端渲染,不注册 settings tab
8
- */
9
- import { writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs'
10
-
11
- import { ROUTE_PREFIX, guarded, sendJson } from './guard.js'
12
- import { buildSnapshot, readSkillBody } from './store.js'
13
- import { watchRoots } from '../collect/watcher.js'
14
- import { collectRoots } from '../collect/roots.js'
15
- import { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
16
- import { FILE_STATE, isWritable } from '../collect/observe.js'
17
- import { extractSkillMeta } from '../collect/frontmatter.js'
18
- import { auditSkillText } from '../audit/rules.js'
19
- import { budgetReport } from '../budget/announcement.js'
20
- import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
21
- import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
22
- import { readSources, saveSource } from '../market/store.js'
23
- import { readSettings, writeSettings } from '../settings.js'
24
- import { exportRulePack, importRulePack } from '../audit/ruleset.js'
25
-
26
- function listSources(config) {
27
- return readSources(config).sources
28
- }
29
-
30
- /** 关闭/开启模型的 frontmatter 键。 */
31
- const DISABLE_KEY = 'disable-model-invocation'
32
-
33
- /** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
34
- export function setModelInvocation(text, enabled) {
35
- const line = enabled ? 'false' : 'true'
36
- const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
37
-
38
- if (prefixed === null) {
39
- // 没有 frontmatter:新建一个
40
- return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
41
- }
42
-
43
- const head = prefixed[2]
44
- const entry = `${DISABLE_KEY}: ${line}`
45
- const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
46
-
47
- const nextHead = existing.test(head)
48
- ? head.replace(existing, entry)
49
- : `${head}${head.trim() === '' ? '' : '\n'}${entry}`
50
-
51
- return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
52
- }
53
-
54
- /** 原子写:先写临时文件再 rename,避免半截文件。 */
55
- function atomicWrite(path, content) {
56
- const temp = `${path}.harbor-tmp-${process.pid}`
57
- writeFileSync(temp, content, 'utf8')
58
- try {
59
- renameSync(temp, path)
60
- } catch (error) {
61
- try {
62
- if (existsSync(temp)) unlinkSync(temp)
63
- } catch {
64
- /* ignore */
65
- }
66
- throw error
67
- }
68
- }
69
-
70
- /**
71
- * 注册全部路由。
72
- * @param {object} ctx
73
- * @param {object} config
74
- * @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
75
- */
76
- export function registerRoutes(ctx, config = {}, deps = {}) {
77
- const webServer = deps.webServer ?? ctx.webServer
78
- if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
79
- // 兜底:正常路径由 apply() 的动态注入保证 webServer 就绪(纯 CLI 根本不会进来)。
80
- // 单测可传 deps.webServer 绕过;形状不符时安静跳过,provider 仍然工作。
81
- return () => {}
82
- }
83
-
84
- const logger = ctx?.logger ?? console
85
- const disposers = []
86
-
87
- /**
88
- * 快照缓存:watcher 代数 + TTL 双判据。
89
- *
90
- * - 有 watcher 时:代数变了立刻失效(增量感知),代数不变则可长期复用。
91
- * - watcher 降级(目录不存在 / 平台不支持 recursive)时:回落到 TTL。
92
- * - 写操作后显式 invalidate(本地写不经过文件事件,等不到 watcher)。
93
- */
94
- let cached = null
95
- let cacheAt = 0
96
- let cachedGeneration = -1
97
- const CACHE_MS = 1500
98
-
99
- const snapshot = async () => {
100
- const now = Date.now()
101
- const generation = watcherState === null ? -1 : watcherState.generation()
102
-
103
- if (cached !== null) {
104
- if (watcherState === null) {
105
- if (now - cacheAt < CACHE_MS) return cached
106
- } else if (generation === cachedGeneration) {
107
- return cached
108
- }
109
- }
110
-
111
- const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
112
- cached = buildSnapshot(config, registrySummaries)
113
- cacheAt = now
114
- cachedGeneration = generation
115
- return cached
116
- }
117
- const invalidate = () => {
118
- cached = null
119
- cacheAt = 0
120
- cachedGeneration = -1
121
- }
122
-
123
- // watcher:任何目录变动 → 代数 +1 → 下次请求重扫
124
- let watcherState = null
125
- try {
126
- const initialRoots = collectRoots({
127
- cwd: config.cwd ?? process.cwd(),
128
- dshHome: config.dshHome,
129
- agentsHome: config.agentsHome,
130
- customSkillDirs: config.customSkillDirs ?? [],
131
- bundledSkillDir: config.bundledSkillDir,
132
- })
133
- watcherState = watchRoots(initialRoots, invalidate)
134
- } catch (error) {
135
- logger.warn?.('[dsh-skill-harbor] watcher unavailable, falling back to TTL', error)
136
- }
137
-
138
- const register = (path, methods, handler) => {
139
- const dispose = webServer.register({
140
- kind: 'handler',
141
- path: `${ROUTE_PREFIX}${path}`,
142
- auth: 'required',
143
- handler: guarded(ctx, { methods }, handler),
144
- })
145
- disposers.push(dispose)
146
- }
147
-
148
- // ---- 读:列表 ----
149
- register('/list', ['GET'], async (req, res) => {
150
- const snap = await snapshot()
151
- sendJson(res, 200, {
152
- takenAt: snap.takenAt,
153
- skills: snap.observations.map(observation => ({
154
- name: observation.name,
155
- description: observation.description,
156
- source: observation.source,
157
- rank: observation.rank,
158
- fileState: observation.fileState,
159
- modelInvocable: observation.modelInvocable,
160
- announcementChars: observation.announcementChars,
161
- shadowedBy: observation.shadowedBy ?? null,
162
- // 只有 editable 才暴露 path,且可写
163
- path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
164
- writable: isWritable(observation),
165
- })),
166
- duplicates: snap.duplicates.map(group => ({
167
- name: group.name,
168
- count: group.count,
169
- winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
170
- })),
171
- totals: {
172
- all: snap.observations.length,
173
- editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
174
- providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
175
- virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
176
- shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
177
- },
178
- })
179
- })
180
-
181
- // ---- 读:单技能正文 ----
182
- register('/read', ['GET'], async (req, res) => {
183
- const snap = await snapshot()
184
- const url = new URL(req.url ?? '/', 'http://localhost')
185
- const target = url.searchParams.get('path')
186
-
187
- const allowed = isAllowedPath(target, snap.allowlist)
188
- if (!allowed.ok) {
189
- sendJson(res, 403, { error: allowed.reason })
190
- return
191
- }
192
- const body = readSkillBody(target, snap.allowlist)
193
- if (!body.ok) {
194
- sendJson(res, 404, { error: body.reason })
195
- return
196
- }
197
- sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
198
- })
199
-
200
- // ---- 写:启停模型调用 ----
201
- register('/set-enabled', ['POST'], async (req, res, body) => {
202
- const snap = await snapshot()
203
- const target = body?.path
204
- const enabled = body?.enabled
205
-
206
- if (typeof enabled !== 'boolean') {
207
- sendJson(res, 400, { error: 'enabled-must-be-boolean' })
208
- return
209
- }
210
- const allowed = isAllowedPath(target, snap.allowlist)
211
- if (!allowed.ok) {
212
- sendJson(res, 403, { error: allowed.reason })
213
- return
214
- }
215
- if (!isSkillMarkdown(target)) {
216
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
217
- return
218
- }
219
-
220
- try {
221
- const current = readSkillBody(target, snap.allowlist)
222
- if (!current.ok) {
223
- sendJson(res, 404, { error: current.reason })
224
- return
225
- }
226
- atomicWrite(target, setModelInvocation(current.content, enabled))
227
- invalidate()
228
- sendJson(res, 200, { ok: true, path: target, enabled })
229
- } catch (error) {
230
- logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
231
- sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
232
- }
233
- })
234
-
235
- // ---- 写:整体更新正文 ----
236
- register('/update', ['POST'], async (req, res, body) => {
237
- const snap = await snapshot()
238
- const target = body?.path
239
- const content = body?.content
240
-
241
- if (typeof content !== 'string') {
242
- sendJson(res, 400, { error: 'content-must-be-string' })
243
- return
244
- }
245
- const allowed = isAllowedPath(target, snap.allowlist)
246
- if (!allowed.ok) {
247
- sendJson(res, 403, { error: allowed.reason })
248
- return
249
- }
250
- if (!isSkillMarkdown(target)) {
251
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
252
- return
253
- }
254
-
255
- try {
256
- atomicWrite(target, content)
257
- invalidate()
258
- sendJson(res, 200, { ok: true, path: target })
259
- } catch (error) {
260
- logger.warn?.('[dsh-skill-harbor] update failed', error)
261
- sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
262
- }
263
- })
264
-
265
- // ---- 写:删除 ----
266
- register('/delete', ['POST'], async (req, res, body) => {
267
- const snap = await snapshot()
268
- const target = body?.path
269
-
270
- const allowed = isAllowedPath(target, snap.allowlist)
271
- if (!allowed.ok) {
272
- sendJson(res, 403, { error: allowed.reason })
273
- return
274
- }
275
- if (!isSkillMarkdown(target)) {
276
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
277
- return
278
- }
279
-
280
- try {
281
- unlinkSync(target)
282
- invalidate()
283
- sendJson(res, 200, { ok: true, path: target })
284
- } catch (error) {
285
- logger.warn?.('[dsh-skill-harbor] delete failed', error)
286
- sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
287
- }
288
- })
289
-
290
- // ---- 读:审计全量 ----
291
- register('/audit', ['GET'], async (req, res) => {
292
- const snap = await snapshot()
293
- const results = []
294
- for (const observation of snap.observations) {
295
- if (observation.fileState !== FILE_STATE.EDITABLE) {
296
- // provider-file / virtual 没有可信路径 → 明确是 skipped,不是 ok
297
- results.push({
298
- name: observation.name,
299
- source: observation.source,
300
- fileState: observation.fileState,
301
- verdict: 'skipped',
302
- reason: observation.fileState === FILE_STATE.PROVIDER_FILE
303
- ? 'file-exists-but-not-scanned'
304
- : 'no-instruction-file',
305
- findings: [],
306
- })
307
- continue
308
- }
309
- const body = readSkillBody(observation.path, snap.allowlist)
310
- if (!body.ok) {
311
- results.push({
312
- name: observation.name,
313
- source: observation.source,
314
- fileState: observation.fileState,
315
- verdict: 'skipped',
316
- reason: body.reason,
317
- findings: [],
318
- })
319
- continue
320
- }
321
- const audit = auditSkillText(body.content, { name: observation.name })
322
- results.push({
323
- name: observation.name,
324
- source: observation.source,
325
- fileState: observation.fileState,
326
- verdict: audit.verdict,
327
- findings: audit.findings,
328
- stats: audit.stats,
329
- })
330
- }
331
-
332
- sendJson(res, 200, {
333
- takenAt: snap.takenAt,
334
- totals: {
335
- ok: results.filter(r => r.verdict === 'ok').length,
336
- warn: results.filter(r => r.verdict === 'warn').length,
337
- fail: results.filter(r => r.verdict === 'fail').length,
338
- skipped: results.filter(r => r.verdict === 'skipped').length,
339
- },
340
- results,
341
- })
342
- })
343
-
344
- // ---- 读:字符预算 ----
345
- register('/budget', ['GET'], async (req, res) => {
346
- const snap = await snapshot()
347
- sendJson(res, 200, { takenAt: snap.takenAt, ...budgetReport(snap.observations) })
348
- })
349
-
350
- // ---- 写:导入归档 ----
351
- register('/import', ['POST'], async (req, res, body) => {
352
- const snap = await snapshot()
353
- const archiveBase64 = body?.archive
354
- const targetSource = body?.targetSource ?? 'user-dsh'
355
-
356
- if (typeof archiveBase64 !== 'string' || archiveBase64 === '') {
357
- sendJson(res, 400, { error: 'archive-required' })
358
- return
359
- }
360
-
361
- let buffer
362
- try {
363
- buffer = Buffer.from(archiveBase64, 'base64')
364
- } catch {
365
- sendJson(res, 400, { error: 'invalid-base64' })
366
- return
367
- }
368
-
369
- const targetRoot = snap.roots.find(root => root.source === targetSource)
370
- if (targetRoot === undefined) {
371
- sendJson(res, 400, {
372
- error: 'unknown-target-source',
373
- available: snap.roots.map(root => root.source),
374
- })
375
- return
376
- }
377
-
378
- let parsed
379
- try {
380
- parsed = parseSkillsFromArchive(buffer)
381
- } catch (error) {
382
- const code = error?.code ?? 'archive-invalid'
383
- const status = code === 'archive-too-large' || code === 'too-many-entries' || code === 'total-too-large' ? 413
384
- : code === 'encrypted-entry' ? 422
385
- : 400
386
- sendJson(res, status, { error: code, message: String(error?.message ?? error) })
387
- return
388
- }
389
-
390
- const results = []
391
- for (const skill of parsed.skills) {
392
- const placement = decidePlacement({
393
- skillName: skill.name,
394
- targetRoot,
395
- allRoots: snap.roots,
396
- observations: snap.observations,
397
- })
398
- if (!placement.ok) {
399
- results.push({ name: skill.name, installed: false, reason: placement.reason, message: placement.message })
400
- continue
401
- }
402
- const outcome = installSkill({ skill, targetDir: placement.targetDir })
403
- results.push({ name: skill.name, ...outcome })
404
- }
405
-
406
- const installedCount = results.filter(r => r.installed).length
407
- if (installedCount > 0) invalidate()
408
-
409
- sendJson(res, installedCount > 0 ? 200 : 422, {
410
- ok: installedCount > 0,
411
- skippedSymlinks: parsed.skippedSymlinks,
412
- totalBytes: parsed.totalBytes,
413
- results,
414
- })
415
- })
416
-
417
- // ---- 市场:列出已登记仓库源 ----
418
- register('/market/sources', ['GET'], async (req, res) => {
419
- sendJson(res, 200, { sources: listSources(config) })
420
- })
421
-
422
- // ---- 市场:登记一个仓库源(钉 commit) ----
423
- register('/market/add-source', ['POST'], async (req, res, body) => {
424
- const { owner, repo, ref, commitSha } = body ?? {}
425
- if (typeof owner !== 'string' || typeof repo !== 'string') {
426
- sendJson(res, 400, { error: 'owner-and-repo-required' })
427
- return
428
- }
429
- if (!isCommitSha(commitSha)) {
430
- // 浮动 ref 拒绝入库:必须先解析成 sha
431
- sendJson(res, 400, { error: 'commit-sha-required', message: '仓库源必须钉死 commitSha,不接受浮动 ref' })
432
- return
433
- }
434
- const source = makeSource({ owner, repo, ref: ref ?? 'HEAD', commitSha })
435
- const saved = saveSource(config, source)
436
- sendJson(res, 200, { ok: true, source: saved })
437
- })
438
-
439
- // ---- 市场:检查更新(只读,不落盘) ----
440
- register('/market/check', ['POST'], async (req, res, body) => {
441
- const { id, remoteSha } = body ?? {}
442
- const source = listSources(config).find(item => item.id === id)
443
- if (source === undefined) {
444
- sendJson(res, 404, { error: 'source-not-found' })
445
- return
446
- }
447
- const result = checkUpdate(source.commitSha, remoteSha)
448
- if (!result.ok) {
449
- sendJson(res, 400, { error: result.reason })
450
- return
451
- }
452
- sendJson(res, 200, { ok: true, source: source.id, ...result })
453
- })
454
-
455
- // ---- 市场:同步到钉住的远端 sha ----
456
- register('/market/sync', ['POST'], async (req, res, body) => {
457
- const { id, remoteSha } = body ?? {}
458
- const source = listSources(config).find(item => item.id === id)
459
- if (source === undefined) {
460
- sendJson(res, 404, { error: 'source-not-found' })
461
- return
462
- }
463
- const result = applySync(source, remoteSha)
464
- if (!result.ok) {
465
- sendJson(res, 400, { error: result.reason })
466
- return
467
- }
468
- saveSource(config, result.source)
469
- sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
470
- })
471
-
472
- // ---- 偏好:GET 读 / POST 部分更新 ----
473
- // 同一路径只能注册一次(宿主按绝对路径去重),方法在这里分派。
474
- register('/settings', ['GET', 'POST'], async (req, res, body, method) => {
475
- if (method === 'GET') {
476
- const { settings, degraded, reason } = readSettings(config)
477
- sendJson(res, 200, { settings, degraded, ...(reason === undefined ? {} : { reason }) })
478
- return
479
- }
480
- try {
481
- const next = writeSettings(config, body ?? {})
482
- sendJson(res, 200, { ok: true, settings: next })
483
- } catch (error) {
484
- logger.warn?.('[dsh-skill-harbor] settings write failed', error)
485
- sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
486
- }
487
- })
488
-
489
- // ---- 规则包:导出 ----
490
- register('/rules/export', ['GET'], async (req, res) => {
491
- sendJson(res, 200, exportRulePack({ plugin: 'dsh-skill-harbor' }))
492
- })
493
-
494
- // ---- 规则包:回灌 ----
495
- register('/rules/import', ['POST'], async (req, res, body) => {
496
- const result = importRulePack(body)
497
- sendJson(res, result.ok ? 200 : 422, result)
498
- })
499
-
500
- return () => {
501
- if (watcherState !== null) {
502
- watcherState.close()
503
- watcherState = null
504
- }
505
- for (const dispose of disposers) {
506
- try {
507
- dispose()
508
- } catch {
509
- /* ignore */
510
- }
511
- }
512
- disposers.length = 0
513
- }
514
- }
515
-
516
- export { ROUTE_PREFIX, safePath }
1
+ /**
2
+ * 路由注册总装 —— 所有 HTTP 入口在这里一次性挂上。
3
+ *
4
+ * 设计要点:
5
+ * - 前缀统一 `/dsh-skill-harbor/api`,写操作全部要求 CSRF 头
6
+ * - 写路由只接受 `snapshot.allowlist` 里的路径(不是请求里带来的任意路径)
7
+ * - 面板席位在 Phase 2 是独立 api + 客户端渲染,不注册 settings tab
8
+ */
9
+ import { writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs'
10
+
11
+ import { ROUTE_PREFIX, guarded, sendJson } from './guard.js'
12
+ import { buildSnapshot, readSkillBody } from './store.js'
13
+ import { watchRoots } from '../collect/watcher.js'
14
+ import { collectRoots } from '../collect/roots.js'
15
+ import { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
16
+ import { FILE_STATE, isWritable } from '../collect/observe.js'
17
+ import { extractSkillMeta } from '../collect/frontmatter.js'
18
+ import { auditSkillText } from '../audit/rules.js'
19
+ import { budgetReport } from '../budget/announcement.js'
20
+ import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
21
+ import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
22
+ import { readSources, saveSource } from '../market/store.js'
23
+ import { readSettings, writeSettings } from '../settings.js'
24
+ import { exportRulePack, importRulePack } from '../audit/ruleset.js'
25
+
26
+ function listSources(config) {
27
+ return readSources(config).sources
28
+ }
29
+
30
+ /** 关闭/开启模型的 frontmatter 键。 */
31
+ const DISABLE_KEY = 'disable-model-invocation'
32
+
33
+ /** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
34
+ export function setModelInvocation(text, enabled) {
35
+ const line = enabled ? 'false' : 'true'
36
+ const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
37
+
38
+ if (prefixed === null) {
39
+ // 没有 frontmatter:新建一个
40
+ return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
41
+ }
42
+
43
+ const head = prefixed[2]
44
+ const entry = `${DISABLE_KEY}: ${line}`
45
+ const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
46
+
47
+ const nextHead = existing.test(head)
48
+ ? head.replace(existing, entry)
49
+ : `${head}${head.trim() === '' ? '' : '\n'}${entry}`
50
+
51
+ return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
52
+ }
53
+
54
+ /** 原子写:先写临时文件再 rename,避免半截文件。 */
55
+ function atomicWrite(path, content) {
56
+ const temp = `${path}.harbor-tmp-${process.pid}`
57
+ writeFileSync(temp, content, 'utf8')
58
+ try {
59
+ renameSync(temp, path)
60
+ } catch (error) {
61
+ try {
62
+ if (existsSync(temp)) unlinkSync(temp)
63
+ } catch {
64
+ /* ignore */
65
+ }
66
+ throw error
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 注册全部路由。
72
+ * @param {object} ctx
73
+ * @param {object} config
74
+ * @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
75
+ */
76
+ export function registerRoutes(ctx, config = {}, deps = {}) {
77
+ const webServer = deps.webServer ?? ctx.webServer
78
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
79
+ // 兜底:正常路径由 apply() 的动态注入保证 webServer 就绪(纯 CLI 根本不会进来)。
80
+ // 单测可传 deps.webServer 绕过;形状不符时安静跳过,provider 仍然工作。
81
+ return () => {}
82
+ }
83
+
84
+ const logger = ctx?.logger ?? console
85
+ const disposers = []
86
+
87
+ /**
88
+ * 快照缓存:watcher 代数 + TTL 双判据。
89
+ *
90
+ * - 有 watcher 时:代数变了立刻失效(增量感知),代数不变则可长期复用。
91
+ * - watcher 降级(目录不存在 / 平台不支持 recursive)时:回落到 TTL。
92
+ * - 写操作后显式 invalidate(本地写不经过文件事件,等不到 watcher)。
93
+ */
94
+ let cached = null
95
+ let cacheAt = 0
96
+ let cachedGeneration = -1
97
+ const CACHE_MS = 1500
98
+
99
+ const snapshot = async () => {
100
+ const now = Date.now()
101
+ const generation = watcherState === null ? -1 : watcherState.generation()
102
+
103
+ if (cached !== null) {
104
+ if (watcherState === null) {
105
+ if (now - cacheAt < CACHE_MS) return cached
106
+ } else if (generation === cachedGeneration) {
107
+ return cached
108
+ }
109
+ }
110
+
111
+ const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
112
+ cached = buildSnapshot(config, registrySummaries)
113
+ cacheAt = now
114
+ cachedGeneration = generation
115
+ return cached
116
+ }
117
+ const invalidate = () => {
118
+ cached = null
119
+ cacheAt = 0
120
+ cachedGeneration = -1
121
+ }
122
+
123
+ // watcher:任何目录变动 → 代数 +1 → 下次请求重扫
124
+ let watcherState = null
125
+ try {
126
+ const initialRoots = collectRoots({
127
+ cwd: config.cwd ?? process.cwd(),
128
+ dshHome: config.dshHome,
129
+ agentsHome: config.agentsHome,
130
+ customSkillDirs: config.customSkillDirs ?? [],
131
+ bundledSkillDir: config.bundledSkillDir,
132
+ })
133
+ watcherState = watchRoots(initialRoots, invalidate)
134
+ } catch (error) {
135
+ logger.warn?.('[dsh-skill-harbor] watcher unavailable, falling back to TTL', error)
136
+ }
137
+
138
+ const register = (path, methods, handler) => {
139
+ const dispose = webServer.register({
140
+ kind: 'handler',
141
+ path: `${ROUTE_PREFIX}${path}`,
142
+ auth: 'required',
143
+ handler: guarded(ctx, { methods }, handler),
144
+ })
145
+ disposers.push(dispose)
146
+ }
147
+
148
+ // ---- 读:列表 ----
149
+ register('/list', ['GET'], async (req, res) => {
150
+ const snap = await snapshot()
151
+ sendJson(res, 200, {
152
+ takenAt: snap.takenAt,
153
+ skills: snap.observations.map(observation => ({
154
+ name: observation.name,
155
+ description: observation.description,
156
+ source: observation.source,
157
+ rank: observation.rank,
158
+ fileState: observation.fileState,
159
+ modelInvocable: observation.modelInvocable,
160
+ announcementChars: observation.announcementChars,
161
+ shadowedBy: observation.shadowedBy ?? null,
162
+ // 只有 editable 才暴露 path,且可写
163
+ path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
164
+ writable: isWritable(observation),
165
+ })),
166
+ duplicates: snap.duplicates.map(group => ({
167
+ name: group.name,
168
+ count: group.count,
169
+ winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
170
+ })),
171
+ totals: {
172
+ all: snap.observations.length,
173
+ editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
174
+ providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
175
+ virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
176
+ shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
177
+ },
178
+ })
179
+ })
180
+
181
+ // ---- 读:单技能正文 ----
182
+ register('/read', ['GET'], async (req, res) => {
183
+ const snap = await snapshot()
184
+ const url = new URL(req.url ?? '/', 'http://localhost')
185
+ const target = url.searchParams.get('path')
186
+
187
+ const allowed = isAllowedPath(target, snap.allowlist)
188
+ if (!allowed.ok) {
189
+ sendJson(res, 403, { error: allowed.reason })
190
+ return
191
+ }
192
+ const body = readSkillBody(target, snap.allowlist)
193
+ if (!body.ok) {
194
+ sendJson(res, 404, { error: body.reason })
195
+ return
196
+ }
197
+ sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
198
+ })
199
+
200
+ // ---- 写:启停模型调用 ----
201
+ register('/set-enabled', ['POST'], async (req, res, body) => {
202
+ const snap = await snapshot()
203
+ const target = body?.path
204
+ const enabled = body?.enabled
205
+
206
+ if (typeof enabled !== 'boolean') {
207
+ sendJson(res, 400, { error: 'enabled-must-be-boolean' })
208
+ return
209
+ }
210
+ const allowed = isAllowedPath(target, snap.allowlist)
211
+ if (!allowed.ok) {
212
+ sendJson(res, 403, { error: allowed.reason })
213
+ return
214
+ }
215
+ if (!isSkillMarkdown(target)) {
216
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
217
+ return
218
+ }
219
+
220
+ try {
221
+ const current = readSkillBody(target, snap.allowlist)
222
+ if (!current.ok) {
223
+ sendJson(res, 404, { error: current.reason })
224
+ return
225
+ }
226
+ atomicWrite(target, setModelInvocation(current.content, enabled))
227
+ invalidate()
228
+ sendJson(res, 200, { ok: true, path: target, enabled })
229
+ } catch (error) {
230
+ logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
231
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
232
+ }
233
+ })
234
+
235
+ // ---- 写:整体更新正文 ----
236
+ register('/update', ['POST'], async (req, res, body) => {
237
+ const snap = await snapshot()
238
+ const target = body?.path
239
+ const content = body?.content
240
+
241
+ if (typeof content !== 'string') {
242
+ sendJson(res, 400, { error: 'content-must-be-string' })
243
+ return
244
+ }
245
+ const allowed = isAllowedPath(target, snap.allowlist)
246
+ if (!allowed.ok) {
247
+ sendJson(res, 403, { error: allowed.reason })
248
+ return
249
+ }
250
+ if (!isSkillMarkdown(target)) {
251
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
252
+ return
253
+ }
254
+
255
+ try {
256
+ atomicWrite(target, content)
257
+ invalidate()
258
+ sendJson(res, 200, { ok: true, path: target })
259
+ } catch (error) {
260
+ logger.warn?.('[dsh-skill-harbor] update failed', error)
261
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
262
+ }
263
+ })
264
+
265
+ // ---- 写:删除 ----
266
+ register('/delete', ['POST'], async (req, res, body) => {
267
+ const snap = await snapshot()
268
+ const target = body?.path
269
+
270
+ const allowed = isAllowedPath(target, snap.allowlist)
271
+ if (!allowed.ok) {
272
+ sendJson(res, 403, { error: allowed.reason })
273
+ return
274
+ }
275
+ if (!isSkillMarkdown(target)) {
276
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
277
+ return
278
+ }
279
+
280
+ try {
281
+ unlinkSync(target)
282
+ invalidate()
283
+ sendJson(res, 200, { ok: true, path: target })
284
+ } catch (error) {
285
+ logger.warn?.('[dsh-skill-harbor] delete failed', error)
286
+ sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
287
+ }
288
+ })
289
+
290
+ // ---- 读:审计全量 ----
291
+ register('/audit', ['GET'], async (req, res) => {
292
+ const snap = await snapshot()
293
+ const results = []
294
+ for (const observation of snap.observations) {
295
+ if (observation.fileState !== FILE_STATE.EDITABLE) {
296
+ // provider-file / virtual 没有可信路径 → 明确是 skipped,不是 ok
297
+ results.push({
298
+ name: observation.name,
299
+ source: observation.source,
300
+ fileState: observation.fileState,
301
+ verdict: 'skipped',
302
+ reason: observation.fileState === FILE_STATE.PROVIDER_FILE
303
+ ? 'file-exists-but-not-scanned'
304
+ : 'no-instruction-file',
305
+ findings: [],
306
+ })
307
+ continue
308
+ }
309
+ const body = readSkillBody(observation.path, snap.allowlist)
310
+ if (!body.ok) {
311
+ results.push({
312
+ name: observation.name,
313
+ source: observation.source,
314
+ fileState: observation.fileState,
315
+ verdict: 'skipped',
316
+ reason: body.reason,
317
+ findings: [],
318
+ })
319
+ continue
320
+ }
321
+ const audit = auditSkillText(body.content, { name: observation.name })
322
+ results.push({
323
+ name: observation.name,
324
+ source: observation.source,
325
+ fileState: observation.fileState,
326
+ verdict: audit.verdict,
327
+ findings: audit.findings,
328
+ stats: audit.stats,
329
+ })
330
+ }
331
+
332
+ sendJson(res, 200, {
333
+ takenAt: snap.takenAt,
334
+ totals: {
335
+ ok: results.filter(r => r.verdict === 'ok').length,
336
+ warn: results.filter(r => r.verdict === 'warn').length,
337
+ fail: results.filter(r => r.verdict === 'fail').length,
338
+ skipped: results.filter(r => r.verdict === 'skipped').length,
339
+ },
340
+ results,
341
+ })
342
+ })
343
+
344
+ // ---- 读:字符预算 ----
345
+ register('/budget', ['GET'], async (req, res) => {
346
+ const snap = await snapshot()
347
+ sendJson(res, 200, { takenAt: snap.takenAt, ...budgetReport(snap.observations) })
348
+ })
349
+
350
+ // ---- 写:导入归档 ----
351
+ register('/import', ['POST'], async (req, res, body) => {
352
+ const snap = await snapshot()
353
+ const archiveBase64 = body?.archive
354
+ const targetSource = body?.targetSource ?? 'user-dsh'
355
+
356
+ if (typeof archiveBase64 !== 'string' || archiveBase64 === '') {
357
+ sendJson(res, 400, { error: 'archive-required' })
358
+ return
359
+ }
360
+
361
+ let buffer
362
+ try {
363
+ buffer = Buffer.from(archiveBase64, 'base64')
364
+ } catch {
365
+ sendJson(res, 400, { error: 'invalid-base64' })
366
+ return
367
+ }
368
+
369
+ const targetRoot = snap.roots.find(root => root.source === targetSource)
370
+ if (targetRoot === undefined) {
371
+ sendJson(res, 400, {
372
+ error: 'unknown-target-source',
373
+ available: snap.roots.map(root => root.source),
374
+ })
375
+ return
376
+ }
377
+
378
+ let parsed
379
+ try {
380
+ parsed = parseSkillsFromArchive(buffer)
381
+ } catch (error) {
382
+ const code = error?.code ?? 'archive-invalid'
383
+ const status = code === 'archive-too-large' || code === 'too-many-entries' || code === 'total-too-large' ? 413
384
+ : code === 'encrypted-entry' ? 422
385
+ : 400
386
+ sendJson(res, status, { error: code, message: String(error?.message ?? error) })
387
+ return
388
+ }
389
+
390
+ const results = []
391
+ for (const skill of parsed.skills) {
392
+ const placement = decidePlacement({
393
+ skillName: skill.name,
394
+ targetRoot,
395
+ allRoots: snap.roots,
396
+ observations: snap.observations,
397
+ })
398
+ if (!placement.ok) {
399
+ results.push({ name: skill.name, installed: false, reason: placement.reason, message: placement.message })
400
+ continue
401
+ }
402
+ const outcome = installSkill({ skill, targetDir: placement.targetDir })
403
+ results.push({ name: skill.name, ...outcome })
404
+ }
405
+
406
+ const installedCount = results.filter(r => r.installed).length
407
+ if (installedCount > 0) invalidate()
408
+
409
+ sendJson(res, installedCount > 0 ? 200 : 422, {
410
+ ok: installedCount > 0,
411
+ skippedSymlinks: parsed.skippedSymlinks,
412
+ totalBytes: parsed.totalBytes,
413
+ results,
414
+ })
415
+ })
416
+
417
+ // ---- 市场:列出已登记仓库源 ----
418
+ register('/market/sources', ['GET'], async (req, res) => {
419
+ sendJson(res, 200, { sources: listSources(config) })
420
+ })
421
+
422
+ // ---- 市场:登记一个仓库源(钉 commit) ----
423
+ register('/market/add-source', ['POST'], async (req, res, body) => {
424
+ const { owner, repo, ref, commitSha } = body ?? {}
425
+ if (typeof owner !== 'string' || typeof repo !== 'string') {
426
+ sendJson(res, 400, { error: 'owner-and-repo-required' })
427
+ return
428
+ }
429
+ if (!isCommitSha(commitSha)) {
430
+ // 浮动 ref 拒绝入库:必须先解析成 sha
431
+ sendJson(res, 400, { error: 'commit-sha-required', message: '仓库源必须钉死 commitSha,不接受浮动 ref' })
432
+ return
433
+ }
434
+ const source = makeSource({ owner, repo, ref: ref ?? 'HEAD', commitSha })
435
+ const saved = saveSource(config, source)
436
+ sendJson(res, 200, { ok: true, source: saved })
437
+ })
438
+
439
+ // ---- 市场:检查更新(只读,不落盘) ----
440
+ register('/market/check', ['POST'], async (req, res, body) => {
441
+ const { id, remoteSha } = body ?? {}
442
+ const source = listSources(config).find(item => item.id === id)
443
+ if (source === undefined) {
444
+ sendJson(res, 404, { error: 'source-not-found' })
445
+ return
446
+ }
447
+ const result = checkUpdate(source.commitSha, remoteSha)
448
+ if (!result.ok) {
449
+ sendJson(res, 400, { error: result.reason })
450
+ return
451
+ }
452
+ sendJson(res, 200, { ok: true, source: source.id, ...result })
453
+ })
454
+
455
+ // ---- 市场:同步到钉住的远端 sha ----
456
+ register('/market/sync', ['POST'], async (req, res, body) => {
457
+ const { id, remoteSha } = body ?? {}
458
+ const source = listSources(config).find(item => item.id === id)
459
+ if (source === undefined) {
460
+ sendJson(res, 404, { error: 'source-not-found' })
461
+ return
462
+ }
463
+ const result = applySync(source, remoteSha)
464
+ if (!result.ok) {
465
+ sendJson(res, 400, { error: result.reason })
466
+ return
467
+ }
468
+ saveSource(config, result.source)
469
+ sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
470
+ })
471
+
472
+ // ---- 偏好:GET 读 / POST 部分更新 ----
473
+ // 同一路径只能注册一次(宿主按绝对路径去重),方法在这里分派。
474
+ register('/settings', ['GET', 'POST'], async (req, res, body, method) => {
475
+ if (method === 'GET') {
476
+ const { settings, degraded, reason } = readSettings(config)
477
+ sendJson(res, 200, { settings, degraded, ...(reason === undefined ? {} : { reason }) })
478
+ return
479
+ }
480
+ try {
481
+ const next = writeSettings(config, body ?? {})
482
+ sendJson(res, 200, { ok: true, settings: next })
483
+ } catch (error) {
484
+ logger.warn?.('[dsh-skill-harbor] settings write failed', error)
485
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
486
+ }
487
+ })
488
+
489
+ // ---- 规则包:导出 ----
490
+ register('/rules/export', ['GET'], async (req, res) => {
491
+ sendJson(res, 200, exportRulePack({ plugin: 'dsh-skill-harbor' }))
492
+ })
493
+
494
+ // ---- 规则包:回灌 ----
495
+ register('/rules/import', ['POST'], async (req, res, body) => {
496
+ const result = importRulePack(body)
497
+ sendJson(res, result.ok ? 200 : 422, result)
498
+ })
499
+
500
+ return () => {
501
+ if (watcherState !== null) {
502
+ watcherState.close()
503
+ watcherState = null
504
+ }
505
+ for (const dispose of disposers) {
506
+ try {
507
+ dispose()
508
+ } catch {
509
+ /* ignore */
510
+ }
511
+ }
512
+ disposers.length = 0
513
+ }
514
+ }
515
+
516
+ export { ROUTE_PREFIX, safePath }