dsh-skill-harbor 0.2.0 → 0.3.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.
@@ -1,255 +1,317 @@
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 { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
14
- import { FILE_STATE, isWritable } from '../collect/observe.js'
15
- import { extractSkillMeta } from '../collect/frontmatter.js'
16
-
17
- /** 关闭/开启模型的 frontmatter 键。 */
18
- const DISABLE_KEY = 'disable-model-invocation'
19
-
20
- /** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
21
- export function setModelInvocation(text, enabled) {
22
- const line = enabled ? 'false' : 'true'
23
- const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
24
-
25
- if (prefixed === null) {
26
- // 没有 frontmatter:新建一个
27
- return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
28
- }
29
-
30
- const head = prefixed[2]
31
- const entry = `${DISABLE_KEY}: ${line}`
32
- const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
33
-
34
- const nextHead = existing.test(head)
35
- ? head.replace(existing, entry)
36
- : `${head}${head.trim() === '' ? '' : '\n'}${entry}`
37
-
38
- return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
39
- }
40
-
41
- /** 原子写:先写临时文件再 rename,避免半截文件。 */
42
- function atomicWrite(path, content) {
43
- const temp = `${path}.harbor-tmp-${process.pid}`
44
- writeFileSync(temp, content, 'utf8')
45
- try {
46
- renameSync(temp, path)
47
- } catch (error) {
48
- try {
49
- if (existsSync(temp)) unlinkSync(temp)
50
- } catch {
51
- /* ignore */
52
- }
53
- throw error
54
- }
55
- }
56
-
57
- /**
58
- * 注册全部路由。
59
- * @param {object} ctx
60
- * @param {object} config
61
- * @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
62
- */
63
- export function registerRoutes(ctx, config = {}, deps = {}) {
64
- const webServer = deps.webServer ?? ctx.webServer
65
- if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
66
- // 没有 webserver(如纯 CLI 场景):不注册,但 provider 仍然工作
67
- return () => {}
68
- }
69
-
70
- const logger = ctx?.logger ?? console
71
- const disposers = []
72
-
73
- /** 每次请求都重新扫描?否 —— 用短 TTL 缓存,写后立即失效。 */
74
- let cached = null
75
- let cacheAt = 0
76
- const CACHE_MS = 1500
77
-
78
- const snapshot = async () => {
79
- const now = Date.now()
80
- if (cached !== null && now - cacheAt < CACHE_MS) return cached
81
- const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
82
- cached = buildSnapshot(config, registrySummaries)
83
- cacheAt = now
84
- return cached
85
- }
86
- const invalidate = () => {
87
- cached = null
88
- cacheAt = 0
89
- }
90
-
91
- const register = (path, methods, handler) => {
92
- const dispose = webServer.register({
93
- kind: 'handler',
94
- path: `${ROUTE_PREFIX}${path}`,
95
- auth: 'required',
96
- handler: guarded(ctx, { methods }, handler),
97
- })
98
- disposers.push(dispose)
99
- }
100
-
101
- // ---- 读:列表 ----
102
- register('/list', ['GET'], async (req, res) => {
103
- const snap = await snapshot()
104
- sendJson(res, 200, {
105
- takenAt: snap.takenAt,
106
- skills: snap.observations.map(observation => ({
107
- name: observation.name,
108
- description: observation.description,
109
- source: observation.source,
110
- rank: observation.rank,
111
- fileState: observation.fileState,
112
- modelInvocable: observation.modelInvocable,
113
- announcementChars: observation.announcementChars,
114
- shadowedBy: observation.shadowedBy ?? null,
115
- // 只有 editable 才暴露 path,且可写
116
- path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
117
- writable: isWritable(observation),
118
- })),
119
- duplicates: snap.duplicates.map(group => ({
120
- name: group.name,
121
- count: group.count,
122
- winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
123
- })),
124
- totals: {
125
- all: snap.observations.length,
126
- editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
127
- providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
128
- virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
129
- shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
130
- },
131
- })
132
- })
133
-
134
- // ---- 读:单技能正文 ----
135
- register('/read', ['GET'], async (req, res) => {
136
- const snap = await snapshot()
137
- const url = new URL(req.url ?? '/', 'http://localhost')
138
- const target = url.searchParams.get('path')
139
-
140
- const allowed = isAllowedPath(target, snap.allowlist)
141
- if (!allowed.ok) {
142
- sendJson(res, 403, { error: allowed.reason })
143
- return
144
- }
145
- const body = readSkillBody(target, snap.allowlist)
146
- if (!body.ok) {
147
- sendJson(res, 404, { error: body.reason })
148
- return
149
- }
150
- sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
151
- })
152
-
153
- // ---- 写:启停模型调用 ----
154
- register('/set-enabled', ['POST'], async (req, res, body) => {
155
- const snap = await snapshot()
156
- const target = body?.path
157
- const enabled = body?.enabled
158
-
159
- if (typeof enabled !== 'boolean') {
160
- sendJson(res, 400, { error: 'enabled-must-be-boolean' })
161
- return
162
- }
163
- const allowed = isAllowedPath(target, snap.allowlist)
164
- if (!allowed.ok) {
165
- sendJson(res, 403, { error: allowed.reason })
166
- return
167
- }
168
- if (!isSkillMarkdown(target)) {
169
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
170
- return
171
- }
172
-
173
- try {
174
- const current = readSkillBody(target, snap.allowlist)
175
- if (!current.ok) {
176
- sendJson(res, 404, { error: current.reason })
177
- return
178
- }
179
- atomicWrite(target, setModelInvocation(current.content, enabled))
180
- invalidate()
181
- sendJson(res, 200, { ok: true, path: target, enabled })
182
- } catch (error) {
183
- logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
184
- sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
185
- }
186
- })
187
-
188
- // ---- 写:整体更新正文 ----
189
- register('/update', ['POST'], async (req, res, body) => {
190
- const snap = await snapshot()
191
- const target = body?.path
192
- const content = body?.content
193
-
194
- if (typeof content !== 'string') {
195
- sendJson(res, 400, { error: 'content-must-be-string' })
196
- return
197
- }
198
- const allowed = isAllowedPath(target, snap.allowlist)
199
- if (!allowed.ok) {
200
- sendJson(res, 403, { error: allowed.reason })
201
- return
202
- }
203
- if (!isSkillMarkdown(target)) {
204
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
205
- return
206
- }
207
-
208
- try {
209
- atomicWrite(target, content)
210
- invalidate()
211
- sendJson(res, 200, { ok: true, path: target })
212
- } catch (error) {
213
- logger.warn?.('[dsh-skill-harbor] update failed', error)
214
- sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
215
- }
216
- })
217
-
218
- // ---- 写:删除 ----
219
- register('/delete', ['POST'], async (req, res, body) => {
220
- const snap = await snapshot()
221
- const target = body?.path
222
-
223
- const allowed = isAllowedPath(target, snap.allowlist)
224
- if (!allowed.ok) {
225
- sendJson(res, 403, { error: allowed.reason })
226
- return
227
- }
228
- if (!isSkillMarkdown(target)) {
229
- sendJson(res, 400, { error: 'not-a-skill-markdown' })
230
- return
231
- }
232
-
233
- try {
234
- unlinkSync(target)
235
- invalidate()
236
- sendJson(res, 200, { ok: true, path: target })
237
- } catch (error) {
238
- logger.warn?.('[dsh-skill-harbor] delete failed', error)
239
- sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
240
- }
241
- })
242
-
243
- return () => {
244
- for (const dispose of disposers) {
245
- try {
246
- dispose()
247
- } catch {
248
- /* ignore */
249
- }
250
- }
251
- disposers.length = 0
252
- }
253
- }
254
-
255
- 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 { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
14
+ import { FILE_STATE, isWritable } from '../collect/observe.js'
15
+ import { extractSkillMeta } from '../collect/frontmatter.js'
16
+ import { auditSkillText } from '../audit/rules.js'
17
+ import { budgetReport } from '../budget/announcement.js'
18
+
19
+ /** 关闭/开启模型的 frontmatter 键。 */
20
+ const DISABLE_KEY = 'disable-model-invocation'
21
+
22
+ /** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
23
+ export function setModelInvocation(text, enabled) {
24
+ const line = enabled ? 'false' : 'true'
25
+ const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
26
+
27
+ if (prefixed === null) {
28
+ // 没有 frontmatter:新建一个
29
+ return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
30
+ }
31
+
32
+ const head = prefixed[2]
33
+ const entry = `${DISABLE_KEY}: ${line}`
34
+ const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
35
+
36
+ const nextHead = existing.test(head)
37
+ ? head.replace(existing, entry)
38
+ : `${head}${head.trim() === '' ? '' : '\n'}${entry}`
39
+
40
+ return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
41
+ }
42
+
43
+ /** 原子写:先写临时文件再 rename,避免半截文件。 */
44
+ function atomicWrite(path, content) {
45
+ const temp = `${path}.harbor-tmp-${process.pid}`
46
+ writeFileSync(temp, content, 'utf8')
47
+ try {
48
+ renameSync(temp, path)
49
+ } catch (error) {
50
+ try {
51
+ if (existsSync(temp)) unlinkSync(temp)
52
+ } catch {
53
+ /* ignore */
54
+ }
55
+ throw error
56
+ }
57
+ }
58
+
59
+ /**
60
+ * 注册全部路由。
61
+ * @param {object} ctx
62
+ * @param {object} config
63
+ * @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
64
+ */
65
+ export function registerRoutes(ctx, config = {}, deps = {}) {
66
+ const webServer = deps.webServer ?? ctx.webServer
67
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
68
+ // 没有 webserver(如纯 CLI 场景):不注册,但 provider 仍然工作
69
+ return () => {}
70
+ }
71
+
72
+ const logger = ctx?.logger ?? console
73
+ const disposers = []
74
+
75
+ /** 每次请求都重新扫描?否 —— 用短 TTL 缓存,写后立即失效。 */
76
+ let cached = null
77
+ let cacheAt = 0
78
+ const CACHE_MS = 1500
79
+
80
+ const snapshot = async () => {
81
+ const now = Date.now()
82
+ if (cached !== null && now - cacheAt < CACHE_MS) return cached
83
+ const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
84
+ cached = buildSnapshot(config, registrySummaries)
85
+ cacheAt = now
86
+ return cached
87
+ }
88
+ const invalidate = () => {
89
+ cached = null
90
+ cacheAt = 0
91
+ }
92
+
93
+ const register = (path, methods, handler) => {
94
+ const dispose = webServer.register({
95
+ kind: 'handler',
96
+ path: `${ROUTE_PREFIX}${path}`,
97
+ auth: 'required',
98
+ handler: guarded(ctx, { methods }, handler),
99
+ })
100
+ disposers.push(dispose)
101
+ }
102
+
103
+ // ---- 读:列表 ----
104
+ register('/list', ['GET'], async (req, res) => {
105
+ const snap = await snapshot()
106
+ sendJson(res, 200, {
107
+ takenAt: snap.takenAt,
108
+ skills: snap.observations.map(observation => ({
109
+ name: observation.name,
110
+ description: observation.description,
111
+ source: observation.source,
112
+ rank: observation.rank,
113
+ fileState: observation.fileState,
114
+ modelInvocable: observation.modelInvocable,
115
+ announcementChars: observation.announcementChars,
116
+ shadowedBy: observation.shadowedBy ?? null,
117
+ // 只有 editable 才暴露 path,且可写
118
+ path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
119
+ writable: isWritable(observation),
120
+ })),
121
+ duplicates: snap.duplicates.map(group => ({
122
+ name: group.name,
123
+ count: group.count,
124
+ winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
125
+ })),
126
+ totals: {
127
+ all: snap.observations.length,
128
+ editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
129
+ providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
130
+ virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
131
+ shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
132
+ },
133
+ })
134
+ })
135
+
136
+ // ---- 读:单技能正文 ----
137
+ register('/read', ['GET'], async (req, res) => {
138
+ const snap = await snapshot()
139
+ const url = new URL(req.url ?? '/', 'http://localhost')
140
+ const target = url.searchParams.get('path')
141
+
142
+ const allowed = isAllowedPath(target, snap.allowlist)
143
+ if (!allowed.ok) {
144
+ sendJson(res, 403, { error: allowed.reason })
145
+ return
146
+ }
147
+ const body = readSkillBody(target, snap.allowlist)
148
+ if (!body.ok) {
149
+ sendJson(res, 404, { error: body.reason })
150
+ return
151
+ }
152
+ sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
153
+ })
154
+
155
+ // ---- 写:启停模型调用 ----
156
+ register('/set-enabled', ['POST'], async (req, res, body) => {
157
+ const snap = await snapshot()
158
+ const target = body?.path
159
+ const enabled = body?.enabled
160
+
161
+ if (typeof enabled !== 'boolean') {
162
+ sendJson(res, 400, { error: 'enabled-must-be-boolean' })
163
+ return
164
+ }
165
+ const allowed = isAllowedPath(target, snap.allowlist)
166
+ if (!allowed.ok) {
167
+ sendJson(res, 403, { error: allowed.reason })
168
+ return
169
+ }
170
+ if (!isSkillMarkdown(target)) {
171
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
172
+ return
173
+ }
174
+
175
+ try {
176
+ const current = readSkillBody(target, snap.allowlist)
177
+ if (!current.ok) {
178
+ sendJson(res, 404, { error: current.reason })
179
+ return
180
+ }
181
+ atomicWrite(target, setModelInvocation(current.content, enabled))
182
+ invalidate()
183
+ sendJson(res, 200, { ok: true, path: target, enabled })
184
+ } catch (error) {
185
+ logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
186
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
187
+ }
188
+ })
189
+
190
+ // ---- 写:整体更新正文 ----
191
+ register('/update', ['POST'], async (req, res, body) => {
192
+ const snap = await snapshot()
193
+ const target = body?.path
194
+ const content = body?.content
195
+
196
+ if (typeof content !== 'string') {
197
+ sendJson(res, 400, { error: 'content-must-be-string' })
198
+ return
199
+ }
200
+ const allowed = isAllowedPath(target, snap.allowlist)
201
+ if (!allowed.ok) {
202
+ sendJson(res, 403, { error: allowed.reason })
203
+ return
204
+ }
205
+ if (!isSkillMarkdown(target)) {
206
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
207
+ return
208
+ }
209
+
210
+ try {
211
+ atomicWrite(target, content)
212
+ invalidate()
213
+ sendJson(res, 200, { ok: true, path: target })
214
+ } catch (error) {
215
+ logger.warn?.('[dsh-skill-harbor] update failed', error)
216
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
217
+ }
218
+ })
219
+
220
+ // ---- 写:删除 ----
221
+ register('/delete', ['POST'], async (req, res, body) => {
222
+ const snap = await snapshot()
223
+ const target = body?.path
224
+
225
+ const allowed = isAllowedPath(target, snap.allowlist)
226
+ if (!allowed.ok) {
227
+ sendJson(res, 403, { error: allowed.reason })
228
+ return
229
+ }
230
+ if (!isSkillMarkdown(target)) {
231
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
232
+ return
233
+ }
234
+
235
+ try {
236
+ unlinkSync(target)
237
+ invalidate()
238
+ sendJson(res, 200, { ok: true, path: target })
239
+ } catch (error) {
240
+ logger.warn?.('[dsh-skill-harbor] delete failed', error)
241
+ sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
242
+ }
243
+ })
244
+
245
+ // ---- 读:审计全量 ----
246
+ register('/audit', ['GET'], async (req, res) => {
247
+ const snap = await snapshot()
248
+ const results = []
249
+ for (const observation of snap.observations) {
250
+ if (observation.fileState !== FILE_STATE.EDITABLE) {
251
+ // provider-file / virtual 没有可信路径 → 明确是 skipped,不是 ok
252
+ results.push({
253
+ name: observation.name,
254
+ source: observation.source,
255
+ fileState: observation.fileState,
256
+ verdict: 'skipped',
257
+ reason: observation.fileState === FILE_STATE.PROVIDER_FILE
258
+ ? 'file-exists-but-not-scanned'
259
+ : 'no-instruction-file',
260
+ findings: [],
261
+ })
262
+ continue
263
+ }
264
+ const body = readSkillBody(observation.path, snap.allowlist)
265
+ if (!body.ok) {
266
+ results.push({
267
+ name: observation.name,
268
+ source: observation.source,
269
+ fileState: observation.fileState,
270
+ verdict: 'skipped',
271
+ reason: body.reason,
272
+ findings: [],
273
+ })
274
+ continue
275
+ }
276
+ const audit = auditSkillText(body.content, { name: observation.name })
277
+ results.push({
278
+ name: observation.name,
279
+ source: observation.source,
280
+ fileState: observation.fileState,
281
+ verdict: audit.verdict,
282
+ findings: audit.findings,
283
+ stats: audit.stats,
284
+ })
285
+ }
286
+
287
+ sendJson(res, 200, {
288
+ takenAt: snap.takenAt,
289
+ totals: {
290
+ ok: results.filter(r => r.verdict === 'ok').length,
291
+ warn: results.filter(r => r.verdict === 'warn').length,
292
+ fail: results.filter(r => r.verdict === 'fail').length,
293
+ skipped: results.filter(r => r.verdict === 'skipped').length,
294
+ },
295
+ results,
296
+ })
297
+ })
298
+
299
+ // ---- 读:字符预算 ----
300
+ register('/budget', ['GET'], async (req, res) => {
301
+ const snap = await snapshot()
302
+ sendJson(res, 200, { takenAt: snap.takenAt, ...budgetReport(snap.observations) })
303
+ })
304
+
305
+ return () => {
306
+ for (const dispose of disposers) {
307
+ try {
308
+ dispose()
309
+ } catch {
310
+ /* ignore */
311
+ }
312
+ }
313
+ disposers.length = 0
314
+ }
315
+ }
316
+
317
+ export { ROUTE_PREFIX, safePath }