dsh-skill-pool 0.0.0-stage → 0.3.8

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.
package/src/web-api.js ADDED
@@ -0,0 +1,1381 @@
1
+ /**
2
+ * Browser-facing API for the resource-pool settings page (§6).
3
+ *
4
+ * The routes live on their own `webServer` prefix (`/dsh-skill-pool`) and
5
+ * admit every request through `connection.admit`, which inherits the
6
+ * deployment's trusted-origin checks and browser credential. The prefix effect
7
+ * is owned by the plugin context (not the inject-derived scope): a service
8
+ * restart re-runs an inject callback and would otherwise dispose the route.
9
+ *
10
+ * v3 has no "resource library -> pool" step: importing a skill or an MCP server
11
+ * writes its pool membership in the same request. Every write is atomic
12
+ * (state file first), then re-applies the document to live Agents, then returns
13
+ * the new document. MCP imports return before the mount because an unreachable
14
+ * server can block for a long time; readiness is observed as `mcp__<server>__*`
15
+ * tools appearing within the probe window.
16
+ *
17
+ * @module dsh-skill-pool/web-api
18
+ */
19
+
20
+ import {
21
+ applySettingsPatch,
22
+ excludeSourceSkill,
23
+ newId,
24
+ normalizeItemName,
25
+ normalizePath,
26
+ removeItem,
27
+ removeSource,
28
+ StateReadError,
29
+ upsertGroup,
30
+ upsertItem,
31
+ upsertSource,
32
+ } from './store.js'
33
+ import { buildInventory } from './inventory.js'
34
+ import { effectiveEnabled, effectiveScope, groupKeyOfSource, groupOfMember, resolvePool } from './rules.js'
35
+ import { DEFAULT_PROBE_INTERVAL_MS, DEFAULT_PROBE_TIMEOUT_MS, mountServer } from './mount.js'
36
+ import {
37
+ buildMcpConfig,
38
+ createMountTracker,
39
+ normalizeMcpImport,
40
+ removeMcpServer,
41
+ } from './uploads.js'
42
+ import {
43
+ checkGitSource,
44
+ installFromFiles,
45
+ installFromGit,
46
+ installFromZip,
47
+ librarySkillsRoot,
48
+ removeSkillDir,
49
+ removeSourceSkills,
50
+ updateGitSource,
51
+ } from './library.js'
52
+
53
+ /** Route prefix below the origin root. */
54
+ export const ROUTE_PREFIX = '/dsh-skill-pool'
55
+
56
+ /** Credential-name prefix for Git tokens (only the name is stored in `state`). */
57
+ const GIT_TOKEN_PREFIX = 'RESOURCE_POOL_GIT_'
58
+
59
+ /** Body cap for panel writes. */
60
+ // 64MB archive cap in base64 plus JSON overhead; see library.MAX_ARCHIVE_BYTES.
61
+ const MAX_BODY_BYTES = 96 * 1024 * 1024
62
+
63
+ /** JSON response helper. */
64
+ function json(value, status = 200) {
65
+ return Response.json(value, { status, headers: { 'cache-control': 'no-store' } })
66
+ }
67
+
68
+ /** Failure response helper. */
69
+ function failure(code, message, status = 400) {
70
+ return json({ ok: false, error: { code, message } }, status)
71
+ }
72
+
73
+ /**
74
+ * Map one route failure, preserving the explicit state-read code when the
75
+ * document could not be trusted. A corrupt file must not be reported as a
76
+ * generic import/update failure: the panel's error should tell the user to
77
+ * repair the state file.
78
+ */
79
+ function stateFailure(error, fallbackCode, fallbackStatus = 500) {
80
+ if (error instanceof StateReadError) return failure(error.code, error.message, 500)
81
+ return failure(fallbackCode, error instanceof Error ? error.message : String(error), fallbackStatus)
82
+ }
83
+
84
+ /** Whether a value is a plain object (not an array, not null). */
85
+ function isObject(value) {
86
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
87
+ }
88
+
89
+ /** Trim one optional string, returning '' when absent. */
90
+ function textOf(value) {
91
+ return typeof value === 'string' ? value.trim() : ''
92
+ }
93
+
94
+ /** Parse a JSON body without throwing on empty or malformed input. */
95
+ async function readBody(request) {
96
+ try {
97
+ const value = await request.json()
98
+ return isObject(value) ? value : {}
99
+ } catch {
100
+ return {}
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Project one MCP member onto the fields the Settings page may see.
106
+ *
107
+ * `definition` carries URLs, commands, headers and environment variables —
108
+ * including `Authorization` tokens — and never belongs in a browser response.
109
+ * An explicit allow-list (activation scope only) also keeps any future
110
+ * connection field from leaking by accident.
111
+ *
112
+ * @param {unknown} member - stored MCP member.
113
+ * @returns {object} browser-safe member.
114
+ */
115
+ function publicMcpMember(member) {
116
+ const source = isObject(member) ? member : {}
117
+ const out = {
118
+ enabled: source.enabled !== false,
119
+ modes: Array.isArray(source.modes) ? [...source.modes] : [],
120
+ workspaces: Array.isArray(source.workspaces) ? [...source.workspaces] : [],
121
+ }
122
+ if (typeof source.installedAt === 'string' && source.installedAt.length > 0) out.installedAt = source.installedAt
123
+ return out
124
+ }
125
+
126
+ /**
127
+ * Project a state document for the browser, dropping every MCP connection
128
+ * definition while keeping scopes and the other sections intact.
129
+ *
130
+ * Every response that carries `state` — the overview and every mutation — goes
131
+ * through this one function, so a new route cannot accidentally expose
132
+ * credentials just by returning the document it just persisted.
133
+ *
134
+ * @param {unknown} state - normalized document.
135
+ * @returns {object} browser-safe document.
136
+ */
137
+ export function publicState(state) {
138
+ const source = isObject(state) ? state : {}
139
+ const mcp = {}
140
+ const members = isObject(source.mcp) ? source.mcp : {}
141
+ for (const [name, member] of Object.entries(members)) mcp[name] = publicMcpMember(member)
142
+ return { ...source, mcp }
143
+ }
144
+
145
+ /**
146
+ * Register the panel's HTTP routes.
147
+ *
148
+ * @param {object} options - registration options.
149
+ * @param {object} options.ctx - plugin context.
150
+ * @param {object} options.store - state store.
151
+ * @param {object} options.meta - static metadata returned to the panel.
152
+ * @param {() => Promise<void>} [options.onChanged] - called after a committed mutation.
153
+ * @param {{ debug?: Function, warn?: Function, info?: Function }} [options.logger] - logger.
154
+ * @param {{ timeoutMs?: number, intervalMs?: number }} [options.mountProbe] - MCP readiness window.
155
+ * @param {object} [options.mounts] - shared mount tracker (boot re-mounts land here too).
156
+ */
157
+ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe, mounts = createMountTracker() } = {}) {
158
+ const debug = logger?.debug ?? (() => {})
159
+ // "ready" means the server's tools are actually registered, not merely that a
160
+ // Loader row exists: an unreachable server creates the row and never connects.
161
+ const probeTimeoutMs = Number.isFinite(mountProbe?.timeoutMs) ? mountProbe.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS
162
+ const probeIntervalMs = Number.isFinite(mountProbe?.intervalMs) ? mountProbe.intervalMs : DEFAULT_PROBE_INTERVAL_MS
163
+
164
+ // Always read the file for the panel: a cached document would hide an
165
+ // external edit (including corruption) until the process restarted.
166
+ const readState = () => store.read({ fresh: true })
167
+ const skillsRoot = () => librarySkillsRoot()
168
+
169
+ /** Committed mutation response: file is already on disk, re-apply, then answer. */
170
+ const committed = async (state, extra = {}) => {
171
+ let warning
172
+ try {
173
+ const result = await onChanged?.()
174
+ const count = (key) => (Number.isFinite(result?.[key]) ? result[key] : 0)
175
+ const failed = count('failed')
176
+ const under = count('under')
177
+ const over = count('over')
178
+ const conservative = count('conservative')
179
+ const noVisible = count('noVisible')
180
+ const retainedOldGate = count('retainedOldGate')
181
+ const fallbackFailed = count('fallbackFailed')
182
+ if (failed > 0 || under + over + conservative + noVisible + retainedOldGate + fallbackFailed > 0) {
183
+ // Classify from structured counts; never parse untrusted warning text.
184
+ const parts = []
185
+ if (under > 0) parts.push(`${under} 个会话未完整应用 MCP 限制,部分工具可能仍可调用,直到下一次重放`)
186
+ if (conservative > 0) parts.push(`${conservative} 个会话使用保守 MCP deny(已对可见工具生效)`)
187
+ if (over > 0) parts.push(`${over} 个会话保留了暂不可见工具的旧限制,可能暂时过度限制`)
188
+ if (noVisible > 0) parts.push(`${noVisible} 个会话当前无可见 MCP 工具,未安装新的拒绝层`)
189
+ if (retainedOldGate > 0) parts.push(`${retainedOldGate} 个会话激活失败,保留旧限制`)
190
+ if (fallbackFailed > 0) parts.push(`${fallbackFailed} 个会话的保守拒绝层安装失败`)
191
+ if (parts.length === 0) parts.push('部分活动会话未能重新应用')
192
+ warning = {
193
+ code: under > 0
194
+ ? 'resource-pool/activation-incomplete'
195
+ : conservative > 0
196
+ ? 'resource-pool/activation-conservative'
197
+ : 'resource-pool/activation-degraded',
198
+ message: `状态已保存;${parts.join(';')}。`,
199
+ ...(failed > 0 ? { failed } : {}),
200
+ ...(under > 0 ? { under } : {}),
201
+ ...(over > 0 ? { over, degraded: over } : {}),
202
+ ...(conservative > 0 ? { conservative } : {}),
203
+ ...(noVisible > 0 ? { noVisible } : {}),
204
+ ...(retainedOldGate > 0 ? { retainedOldGate } : {}),
205
+ ...(fallbackFailed > 0 ? { fallbackFailed } : {}),
206
+ }
207
+ }
208
+ } catch (error) {
209
+ logger?.warn?.(`[resource-pool] re-application failed: ${error instanceof Error ? error.message : String(error)}`)
210
+ warning = {
211
+ code: 'resource-pool/activation-failed',
212
+ message: '状态已保存,但重新应用结果未知;活动会话可能保留旧限制。',
213
+ }
214
+ }
215
+ return json({ ok: true, state: publicState(state), ...extra, ...(warning === undefined ? {} : { warning }) })
216
+ }
217
+
218
+ /** Resolve one stored Git token from the credential store. */
219
+ const gitToken = async (credentialName) => {
220
+ if (typeof credentialName !== 'string' || credentialName.length === 0) return ''
221
+ const credentials = ctx.get('credentials')
222
+ if (credentials === undefined || typeof credentials.resolve !== 'function') return ''
223
+ try {
224
+ const resolved = await credentials.resolve(credentialName)
225
+ return typeof resolved?.value === 'string' ? resolved.value : ''
226
+ } catch {
227
+ return ''
228
+ }
229
+ }
230
+
231
+ /** Store one provided token under a source-scoped credential name. */
232
+ const storeGitToken = async (sourceId, token) => {
233
+ if (typeof token !== 'string' || token.trim().length === 0) return undefined
234
+ const credentials = ctx.get('credentials')
235
+ if (credentials === undefined || typeof credentials.set !== 'function') return undefined
236
+ const name = `${GIT_TOKEN_PREFIX}${sourceId.toUpperCase().replace(/[^A-Z0-9_]/g, '_')}`
237
+ try {
238
+ await credentials.set(name, token.trim())
239
+ return name
240
+ } catch (error) {
241
+ logger?.warn?.(`[resource-pool] token not stored: ${error instanceof Error ? error.message : String(error)}`)
242
+ return undefined
243
+ }
244
+ }
245
+
246
+ // ------------------------------------------------------------- validation
247
+
248
+ /**
249
+ * Validate a mode list at the API boundary.
250
+ *
251
+ * The store's lenient normalizer drops unusable entries, which would turn
252
+ * `[123]` into `[]` ("all modes") and silently widen access. Reject instead;
253
+ * an absent field still means "leave unchanged", and `[]` is a real "all".
254
+ */
255
+ const strictModes = (value, field) => {
256
+ if (!Array.isArray(value)) throw new Error(`${field} 必须是数组`)
257
+ const modes = []
258
+ for (const item of value) {
259
+ if (typeof item !== 'string' || item.length === 0 || normalizeItemName(item) !== item) {
260
+ throw new Error(`${field} 包含非法的模式名`)
261
+ }
262
+ modes.push(item)
263
+ }
264
+ return modes
265
+ }
266
+
267
+ /** Validate absolute workspace paths at the API boundary. */
268
+ const strictWorkspaces = (value, field) => {
269
+ if (!Array.isArray(value)) throw new Error(`${field} 必须是字符串数组`)
270
+ const workspaces = []
271
+ for (const item of value) {
272
+ const path = typeof item === 'string' ? normalizePath(item) : ''
273
+ if (path.length === 0) throw new Error(`${field} 包含非法的工作区路径`)
274
+ workspaces.push(path)
275
+ }
276
+ return workspaces
277
+ }
278
+
279
+ /** Whether two string lists contain the same values (order/duplicates ignored). */
280
+ const sameStringList = (left, right) => {
281
+ if (!Array.isArray(left) || !Array.isArray(right)) return false
282
+ const a = [...new Set(left)].sort()
283
+ const b = [...new Set(right)].sort()
284
+ return a.length === b.length && a.every((value, index) => value === b[index])
285
+ }
286
+
287
+ /**
288
+ * Refuse scope edits whose inheritance marker would silently discard them.
289
+ *
290
+ * The panel always switches the edited dimension to `self`, but API callers
291
+ * may send only `modes`/`workspaces`. When the member inherits a resolvable
292
+ * group, that edit would be ignored; when there is no resolvable group, the
293
+ * marker is ambiguous and can become wider if a group appears later. Existing
294
+ * unchanged legacy markers (enabled-only panel saves) still pass.
295
+ */
296
+ const assertScopePatch = (state, existing, patch) => {
297
+ const group = groupOfMember(state, existing)
298
+ const hasGroup = group !== undefined
299
+ const modesChanged = patch.modes !== undefined && !sameStringList(patch.modes, existing.modes)
300
+ const workspacesChanged =
301
+ patch.workspaces !== undefined && !sameStringList(patch.workspaces, existing.workspaces)
302
+ const desiredModesFrom = patch.modesFrom !== undefined
303
+ ? patch.modesFrom
304
+ : existing.modesFrom === 'self' ? 'self' : 'group'
305
+ const desiredWorkspacesFrom = patch.workspacesFrom !== undefined
306
+ ? patch.workspacesFrom
307
+ : existing.workspacesFrom === 'self' ? 'self' : 'group'
308
+
309
+ if (
310
+ desiredModesFrom === 'group' &&
311
+ ((hasGroup && modesChanged) || (!hasGroup && (modesChanged || (patch.modesFrom === 'group' && existing.modesFrom !== 'group'))))
312
+ ) {
313
+ throw Object.assign(
314
+ new Error(
315
+ hasGroup
316
+ ? "该成员的模式条件由组继承;修改 modes 时请同时提交 modesFrom: 'self',否则修改不会生效。"
317
+ : "该成员没有可解析的组,不能保存 modesFrom: 'group' 与修改后的 modes;请提交 modesFrom: 'self'。",
318
+ ),
319
+ { code: 'resource-pool/bad-scope', status: 400 },
320
+ )
321
+ }
322
+ if (
323
+ desiredWorkspacesFrom === 'group' &&
324
+ ((hasGroup && workspacesChanged) ||
325
+ (!hasGroup && (workspacesChanged || (patch.workspacesFrom === 'group' && existing.workspacesFrom !== 'group'))))
326
+ ) {
327
+ throw Object.assign(
328
+ new Error(
329
+ hasGroup
330
+ ? "该成员的工作区条件由组继承;修改 workspaces 时请同时提交 workspacesFrom: 'self',否则修改不会生效。"
331
+ : "该成员没有可解析的组,不能保存 workspacesFrom: 'group' 与修改后的 workspaces;请提交 workspacesFrom: 'self'。",
332
+ ),
333
+ { code: 'resource-pool/bad-scope', status: 400 },
334
+ )
335
+ }
336
+ }
337
+
338
+ /** Read one `scope` object (`{modes, workspaces}`); undefined when absent. */
339
+ const readScope = (value) => {
340
+ if (value === undefined || value === null) return undefined
341
+ if (!isObject(value)) throw new Error('scope 必须是 {modes, workspaces} 对象')
342
+ const scope = {}
343
+ if (value.modes !== undefined) scope.modes = strictModes(value.modes, 'scope.modes')
344
+ if (value.workspaces !== undefined) scope.workspaces = strictWorkspaces(value.workspaces, 'scope.workspaces')
345
+ return scope
346
+ }
347
+
348
+ /** Read the `/item` patch: activation conditions only. */
349
+ const readItemPatch = (body) => {
350
+ const patch = {}
351
+ if (body.enabled !== undefined) {
352
+ if (typeof body.enabled !== 'boolean') throw new Error('enabled 必须是布尔值')
353
+ patch.enabled = body.enabled
354
+ }
355
+ if (body.modes !== undefined) patch.modes = strictModes(body.modes, 'modes')
356
+ if (body.workspaces !== undefined) patch.workspaces = strictWorkspaces(body.workspaces, 'workspaces')
357
+ for (const key of ['modesFrom', 'workspacesFrom']) {
358
+ if (body[key] === undefined) continue
359
+ if (body[key] !== 'group' && body[key] !== 'self') throw new Error(`${key} 必须是 'group' 或 'self'`)
360
+ patch[key] = body[key]
361
+ }
362
+ return patch
363
+ }
364
+
365
+ /** Merge a condition patch over the stored member (or defaults for a new one). */
366
+ const itemScope = (state, kind, name, patch = {}) => {
367
+ const bucket = kind === 'skill' ? state.skills : state.mcp
368
+ const existing = isObject(bucket) ? bucket[name] : undefined
369
+ return {
370
+ enabled: patch.enabled !== undefined ? patch.enabled : (existing?.enabled ?? true),
371
+ modes: patch.modes !== undefined ? patch.modes : (existing?.modes ?? []),
372
+ workspaces: patch.workspaces !== undefined ? patch.workspaces : (existing?.workspaces ?? []),
373
+ }
374
+ }
375
+
376
+ /** Capture effective scopes before a source change (see `installItems`). */
377
+ const captureEffectiveScopes = (state, names) => {
378
+ const out = {}
379
+ for (const name of names) {
380
+ const member = isObject(state.skills) ? state.skills[name] : undefined
381
+ if (!isObject(member)) continue
382
+ const effective = effectiveScope(state, member)
383
+ out[name] = {
384
+ enabled: effectiveEnabled(state, member),
385
+ modes: [...effective.modes],
386
+ workspaces: [...effective.workspaces],
387
+ groupKey: groupKeyOfSource(isObject(state.sources) ? state.sources[member.sourceId] : undefined),
388
+ }
389
+ }
390
+ return out
391
+ }
392
+
393
+ /**
394
+ * Add freshly installed skills to the pool.
395
+ *
396
+ * A re-import can move a member to a different source. Its group may not
397
+ * exist in the new source's repository, so blindly keeping `modesFrom:
398
+ * 'group'` would turn an inherited scope into the member's empty own list
399
+ * ("all modes/workspaces"). Any dimension that would change effective scope
400
+ * is materialized into `self` from the pre-import effective scope; `enabled`
401
+ * is always preserved as the effective value (a disabled group stays
402
+ * disabled). An explicit import `scope` wins for that dimension and is
403
+ * stored as `self`, so a group can never silently override it.
404
+ *
405
+ * `previous` must be captured before the new source is written; it is
406
+ * supplied by every import/update route.
407
+ */
408
+ const installItems = (state, names, { scope, sourceId, digests, installedAt, previous }) => {
409
+ let next = state
410
+ const provided = isObject(scope) ? scope : {}
411
+ for (const name of names) {
412
+ const extra = { installedAt }
413
+ if (typeof sourceId === 'string' && sourceId.length > 0) extra.sourceId = sourceId
414
+ const digest = isObject(digests) ? digests[name] : undefined
415
+ if (typeof digest === 'string' && digest.length > 0) extra.digest = digest
416
+ const existing = isObject(next.skills) ? next.skills[name] : undefined
417
+ const own = itemScope(next, 'skill', name, provided)
418
+
419
+ if (isObject(existing)) {
420
+ const prior = isObject(previous) && isObject(previous[name])
421
+ ? previous[name]
422
+ : {
423
+ enabled: effectiveEnabled(next, existing),
424
+ modes: [...effectiveScope(next, existing).modes],
425
+ workspaces: [...effectiveScope(next, existing).workspaces],
426
+ groupKey: groupKeyOfSource(isObject(next.sources) ? next.sources[existing.sourceId] : undefined),
427
+ }
428
+ let modesFrom = existing.modesFrom === 'self' ? 'self' : 'group'
429
+ let workspacesFrom = existing.workspacesFrom === 'self' ? 'self' : 'group'
430
+ if (provided.modes !== undefined) modesFrom = 'self'
431
+ if (provided.workspaces !== undefined) workspacesFrom = 'self'
432
+
433
+ const newGroup = groupOfMember(next, { sourceId })
434
+ if (modesFrom === 'group' && (newGroup === undefined || !sameStringList(newGroup.modes, prior.modes))) {
435
+ modesFrom = 'self'
436
+ own.modes = [...prior.modes]
437
+ }
438
+ if (
439
+ workspacesFrom === 'group' &&
440
+ (newGroup === undefined || !sameStringList(newGroup.workspaces, prior.workspaces))
441
+ ) {
442
+ workspacesFrom = 'self'
443
+ own.workspaces = [...prior.workspaces]
444
+ }
445
+ // A still-identical group keeps the member's own enabled flag, so
446
+ // disabling and re-enabling that group restores the member. Only a
447
+ // changed/lost group materializes the old effective enabled state.
448
+ const newGroupKey = groupKeyOfSource(isObject(next.sources) ? next.sources[sourceId] : undefined)
449
+ const sameGroup = prior.groupKey === newGroupKey && (newGroup !== undefined || newGroupKey.length === 0)
450
+ own.enabled = sameGroup ? existing.enabled : prior.enabled
451
+ extra.modesFrom = modesFrom
452
+ extra.workspacesFrom = workspacesFrom
453
+ } else if (provided.modes !== undefined || provided.workspaces !== undefined) {
454
+ if (provided.modes !== undefined) extra.modesFrom = 'self'
455
+ if (provided.workspaces !== undefined) extra.workspacesFrom = 'self'
456
+ }
457
+
458
+ next = upsertItem(next, 'skill', name, own, extra)
459
+ }
460
+ return next
461
+ }
462
+
463
+ /** Assert an install result has the §7 shape; a mismatch is an integration bug. */
464
+ const installResult = (result) => {
465
+ if (!isObject(result) || !Array.isArray(result.installed)) {
466
+ throw new Error('library.js 返回值缺少 installed[](请确认其实现符合契约 §7)')
467
+ }
468
+ return {
469
+ installed: result.installed.filter((name) => typeof name === 'string' && name.length > 0),
470
+ failures: Array.isArray(result.failures) ? result.failures : [],
471
+ digests: isObject(result.digests) ? result.digests : {},
472
+ source: isObject(result.source) ? result.source : undefined,
473
+ }
474
+ }
475
+
476
+ /** Label for one import-created source record. */
477
+ const importLabel = (kind, names, providedLabel) => {
478
+ const label = textOf(providedLabel)
479
+ if (label.length > 0) return label
480
+ if (names.length === 1) return names[0]
481
+ if (kind === 'zip') return `ZIP(${names.length} 个技能)`
482
+ return `上传的 ${names.length} 个技能`
483
+ }
484
+
485
+ /** Decode panel upload files to the library's `{path, content}` shape. */
486
+ const uploadFiles = (raw) => {
487
+ const list = Array.isArray(raw) ? raw : []
488
+ const out = []
489
+ for (const file of list) {
490
+ if (!isObject(file)) continue
491
+ const path = typeof file.path === 'string' ? file.path : ''
492
+ if (typeof file.contentBase64 === 'string' && file.contentBase64.length > 0) {
493
+ const data = Buffer.from(file.contentBase64, 'base64')
494
+ // `installFromFiles` currently filters on `content`; carry both so the
495
+ // decoded bytes are also available to the library.
496
+ out.push({ path, content: data.toString('utf8'), data })
497
+ continue
498
+ }
499
+ if (typeof file.content === 'string') {
500
+ out.push({ path, content: file.content, data: Buffer.from(file.content, 'utf8') })
501
+ }
502
+ }
503
+ return out
504
+ }
505
+
506
+ /** Normalize one check outcome status (§2.1). */
507
+ const checkStatus = (status, current, remote) => {
508
+ if (status === 'up-to-date' || status === 'update-available' || status === 'error') return status
509
+ if (current.length > 0 && remote.length > 0) return current === remote ? 'up-to-date' : 'update-available'
510
+ return 'error'
511
+ }
512
+
513
+ /** Names other sources still list (used to avoid deleting a shared skill). */
514
+ const sharedNames = (state, exceptId) => {
515
+ const shared = new Set()
516
+ for (const [id, source] of Object.entries(state.sources)) {
517
+ if (id === exceptId) continue
518
+ for (const name of Array.isArray(source.skills) ? source.skills : []) shared.add(name)
519
+ }
520
+ return shared
521
+ }
522
+
523
+ // ---------------------------------------------------------------- handlers
524
+
525
+ /** GET /dsh-skill-pool */
526
+ const overview = async () => {
527
+ try {
528
+ const state = await readState()
529
+ const inventory = await buildInventory(ctx, { state, libraryRoot: skillsRoot() })
530
+ return json({ ok: true, meta, state: publicState(state), inventory, mounts: mounts.status() })
531
+ } catch (error) {
532
+ if (error instanceof StateReadError) {
533
+ logger?.warn?.(`[resource-pool] overview refused: ${error.message}`)
534
+ return failure(error.code, error.message, 500)
535
+ }
536
+ logger?.warn?.(`[resource-pool] overview failed: ${error instanceof Error ? error.message : String(error)}`)
537
+ return failure('resource-pool/read-failed', '无法读取技能池状态', 500)
538
+ }
539
+ }
540
+
541
+ /** GET /dsh-skill-pool/mounts */
542
+ const mountsRoute = async () => json({ ok: true, mounts: mounts.status() })
543
+
544
+ /** POST /dsh-skill-pool/item — edit one member's conditions / enabled flag. */
545
+ const itemRoute = async (request) => {
546
+ const body = await readBody(request)
547
+ const kind = body.kind === 'skill' ? 'skill' : body.kind === 'mcp' ? 'mcp' : ''
548
+ if (kind === '') return failure('resource-pool/bad-kind', "kind 必须是 'skill' 或 'mcp'")
549
+ const name = normalizeItemName(body.name)
550
+ if (name.length === 0) return failure('resource-pool/bad-name', '缺少合法的 name')
551
+ let patch
552
+ try {
553
+ patch = readItemPatch(body)
554
+ } catch (error) {
555
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
556
+ }
557
+ try {
558
+ const state = await store.update((current) => {
559
+ const existing = kind === 'skill' ? current.skills[name] : current.mcp[name]
560
+ // `/item` only edits an existing member: a save that was queued before a
561
+ // delete (or a focused row for a member that is already gone) must fail
562
+ // instead of recreating the member after the removal.
563
+ if (!isObject(existing)) {
564
+ throw Object.assign(
565
+ new Error(`成员 ${name} 不存在;/item 只能编辑已有成员`),
566
+ { code: 'resource-pool/unknown-item', status: 400 },
567
+ )
568
+ }
569
+ if (kind === 'skill') {
570
+ assertScopePatch(current, existing, patch)
571
+ // Marker-only group -> self must retain the inherited values. The
572
+ // panel normally sends them, but an API caller may switch only the marker.
573
+ const group = groupOfMember(current, existing)
574
+ if (group !== undefined) {
575
+ const effective = effectiveScope(current, existing)
576
+ // The panel's inherit-off action sends the member's existing own
577
+ // values with `self`. If those values did not actually change, the
578
+ // action is marker-only: materialize the inherited scope rather
579
+ // than turning the empty own list into "all".
580
+ const modesUnchanged =
581
+ patch.modes === undefined || sameStringList(patch.modes, existing.modes)
582
+ const workspacesUnchanged =
583
+ patch.workspaces === undefined || sameStringList(patch.workspaces, existing.workspaces)
584
+ if (patch.modesFrom === 'self' && existing.modesFrom !== 'self' && modesUnchanged) {
585
+ patch.modes = [...effective.modes]
586
+ }
587
+ if (patch.workspacesFrom === 'self' && existing.workspacesFrom !== 'self' && workspacesUnchanged) {
588
+ patch.workspaces = [...effective.workspaces]
589
+ }
590
+ }
591
+ }
592
+ const extra = {
593
+ sourceId: existing?.sourceId,
594
+ digest: existing?.digest,
595
+ installedAt: existing?.installedAt,
596
+ modesFrom: patch.modesFrom !== undefined ? patch.modesFrom : existing?.modesFrom,
597
+ workspacesFrom: patch.workspacesFrom !== undefined ? patch.workspacesFrom : existing?.workspacesFrom,
598
+ }
599
+ return upsertItem(current, kind, name, itemScope(current, kind, name, patch), extra)
600
+ })
601
+ return committed(state)
602
+ } catch (error) {
603
+ const code = typeof error?.code === 'string' ? error.code : 'resource-pool/save-failed'
604
+ return failure(code, error instanceof Error ? error.message : String(error), error?.status === 400 ? 400 : 500)
605
+ }
606
+ }
607
+
608
+ /**
609
+ * POST /dsh-skill-pool/item/remove — remove one pool member.
610
+ * Skills lose their library directory; MCP servers lose their Loader row.
611
+ */
612
+ const itemRemoveRoute = async (request) => {
613
+ const body = await readBody(request)
614
+ const kind = body.kind === 'skill' ? 'skill' : body.kind === 'mcp' ? 'mcp' : ''
615
+ if (kind === '') return failure('resource-pool/bad-kind', "kind 必须是 'skill' 或 'mcp'")
616
+ const name = normalizeItemName(body.name)
617
+ if (name.length === 0) return failure('resource-pool/bad-name', '缺少合法的 name')
618
+ // Refuse before deleting skill files or a Loader row: a corrupt state file
619
+ // must not turn a failed remove into partial data loss.
620
+ await readState()
621
+
622
+ const removed = { kind, name }
623
+ if (kind === 'skill') {
624
+ try {
625
+ removed.dir = (await removeSkillDir({ root: skillsRoot(), name })) === true
626
+ } catch (error) {
627
+ removed.dir = false
628
+ removed.warning = error instanceof Error ? error.message : String(error)
629
+ }
630
+ try {
631
+ const state = await store.update((current) => {
632
+ // Deleting is also an exclusion: the source remembers the name so an
633
+ // update never installs it again.
634
+ let next = excludeSourceSkill(removeItem(current, 'skill', name), name)
635
+ // A source with nothing left to install has nothing to update: drop it,
636
+ // and its group when it was the repository's last source.
637
+ for (const source of Object.values(next.sources)) {
638
+ if (Array.isArray(source.skills) && source.skills.length > 0) continue
639
+ const referenced = Object.values(next.skills).some((item) => item.sourceId === source.id)
640
+ if (!referenced) next = removeSource(next, source.id)
641
+ }
642
+ return next
643
+ })
644
+ return committed(state, { removed })
645
+ } catch (error) {
646
+ return stateFailure(error, 'resource-pool/save-failed', 500)
647
+ }
648
+ }
649
+
650
+ // MCP: drop the Loader row; a member whose row is already gone can still be
651
+ // removed from the pool (the panel shows the warning).
652
+ try {
653
+ const result = await removeMcpServer(ctx, name)
654
+ mounts.forget(result.serverName)
655
+ removed.mount = true
656
+ } catch (error) {
657
+ removed.mount = false
658
+ removed.warning = error instanceof Error ? error.message : String(error)
659
+ }
660
+ try {
661
+ const state = await store.update((current) => removeItem(current, 'mcp', name))
662
+ return committed(state, { removed })
663
+ } catch (error) {
664
+ return stateFailure(error, 'resource-pool/save-failed', 500)
665
+ }
666
+ }
667
+
668
+ /** POST /dsh-skill-pool/settings */
669
+ const settingsRoute = async (request) => {
670
+ const body = await readBody(request)
671
+ const patch = isObject(body.patch) ? body.patch : isObject(body.settings) ? body.settings : null
672
+ if (patch === null) return failure('resource-pool/bad-settings', '缺少 patch 对象')
673
+ for (const key of ['enabled', 'mcpGate', 'injectSummary', 'gateDefaultSkills']) {
674
+ if (patch[key] !== undefined && typeof patch[key] !== 'boolean') {
675
+ return failure('resource-pool/bad-settings', `${key} 必须是布尔值`)
676
+ }
677
+ }
678
+ try {
679
+ const state = await store.update((current) => applySettingsPatch(current, patch))
680
+ return committed(state)
681
+ } catch (error) {
682
+ return stateFailure(error, 'resource-pool/save-failed', 500)
683
+ }
684
+ }
685
+
686
+ /** POST /dsh-skill-pool/group — set the scope of one repository/import group. */
687
+ const groupRoute = async (request) => {
688
+ const body = await readBody(request)
689
+ const key = typeof body.key === 'string' ? body.key.trim() : ''
690
+ if (key.length === 0) return failure('resource-pool/bad-group', '缺少 group.key')
691
+ // Only repo:/import: groups can ever be referenced by a source. Older API
692
+ // versions could write other keys; they remain readable as inert legacy
693
+ // entries, but new writes must not create more of them.
694
+ const groupPrefix = key.startsWith('repo:') ? 'repo:' : key.startsWith('import:') ? 'import:' : ''
695
+ if (
696
+ groupPrefix.length === 0 ||
697
+ key.length <= groupPrefix.length ||
698
+ key.length > 512 ||
699
+ /[\u0000-\u001f\u007f]/.test(key)
700
+ ) {
701
+ return failure('resource-pool/bad-group', 'group.key 必须是 repo:<project> 或 import:<sourceId>')
702
+ }
703
+ const patch = { key }
704
+ if (body.enabled !== undefined) {
705
+ if (typeof body.enabled !== 'boolean') return failure('resource-pool/bad-group', 'enabled 必须是布尔值')
706
+ patch.enabled = body.enabled
707
+ }
708
+ try {
709
+ if (body.modes !== undefined) patch.modes = strictModes(body.modes, 'modes')
710
+ if (body.workspaces !== undefined) patch.workspaces = strictWorkspaces(body.workspaces, 'workspaces')
711
+ } catch (error) {
712
+ return failure('resource-pool/bad-group', error instanceof Error ? error.message : String(error))
713
+ }
714
+ try {
715
+ const state = await store.update((current) => upsertGroup(current, patch))
716
+ return committed(state)
717
+ } catch (error) {
718
+ return stateFailure(error, 'resource-pool/save-failed', 500)
719
+ }
720
+ }
721
+
722
+ /** GET /dsh-skill-pool/resolve?mode=&cwd=&allModes=&allWorkspaces= */
723
+ const resolveRoute = async (request) => {
724
+ const state = await readState()
725
+ const url = new URL(request.url)
726
+ const cwd = url.searchParams.get('cwd') ?? ''
727
+ const mode = url.searchParams.get('mode') ?? ''
728
+ const allModes = url.searchParams.get('allModes') === '1'
729
+ const allWorkspaces = url.searchParams.get('allWorkspaces') === '1'
730
+ return json({ ok: true, pool: resolvePool(state, { mode, cwd, allModes, allWorkspaces }) })
731
+ }
732
+
733
+ /**
734
+ * POST /dsh-skill-pool/mcp/import — returns immediately, mounts in background.
735
+ * Body: `{payload, scope?}` where `payload` is the parsed `mcpServers` object
736
+ * (a JSON string is tolerated).
737
+ */
738
+ const mcpImportRoute = async (request) => {
739
+ const body = await readBody(request)
740
+ let entries
741
+ try {
742
+ entries = normalizeMcpImport(body.payload !== undefined ? body.payload : body)
743
+ } catch (error) {
744
+ return failure('resource-pool/mcp-import-failed', error instanceof Error ? error.message : String(error), 400)
745
+ }
746
+ // Validate the shape up front so an unusable definition fails as a 400
747
+ // instead of mounting and then reporting "failed".
748
+ const configs = new Map()
749
+ try {
750
+ for (const [serverName, definition] of entries) configs.set(serverName, buildMcpConfig(serverName, definition))
751
+ } catch (error) {
752
+ return failure('resource-pool/mcp-import-failed', error instanceof Error ? error.message : String(error), 400)
753
+ }
754
+ let scope
755
+ try {
756
+ scope = readScope(body.scope)
757
+ } catch (error) {
758
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
759
+ }
760
+
761
+ // Membership plus its connection definition land first: the definition is
762
+ // what a later Host start re-mounts from, so persisting it before the row
763
+ // exists means a crash mid-mount still leaves a recoverable member.
764
+ let state
765
+ try {
766
+ state = await store.update((current) => {
767
+ let next = current
768
+ for (const [serverName, definition] of entries) {
769
+ next = upsertItem(
770
+ next,
771
+ 'mcp',
772
+ serverName,
773
+ itemScope(next, 'mcp', serverName, scope ?? {}),
774
+ { definition: configs.get(serverName) ?? definition },
775
+ )
776
+ }
777
+ return next
778
+ })
779
+ } catch (error) {
780
+ return stateFailure(error, 'resource-pool/save-failed', 500)
781
+ }
782
+
783
+ const servers = []
784
+ for (const [serverName, definition] of entries) {
785
+ servers.push({ server: serverName, state: 'mounting' })
786
+ mountServer({
787
+ ctx,
788
+ serverName,
789
+ definition: configs.get(serverName) ?? definition,
790
+ mounts,
791
+ timeoutMs: probeTimeoutMs,
792
+ intervalMs: probeIntervalMs,
793
+ logger,
794
+ origin: 'import',
795
+ })
796
+ }
797
+ return committed(state, { servers, mounts: mounts.status() })
798
+ }
799
+
800
+ /** POST /dsh-skill-pool/mcp/remove — `{server}`. */
801
+ const mcpRemoveRoute = async (request) => {
802
+ const body = await readBody(request)
803
+ const serverName = textOf(body.server)
804
+ if (serverName.length === 0) return failure('resource-pool/bad-server', '缺少 server')
805
+ // Validate state before removing the Loader row.
806
+ await readState()
807
+ let result
808
+ try {
809
+ result = await removeMcpServer(ctx, serverName)
810
+ } catch (error) {
811
+ return failure('resource-pool/mcp-remove-failed', error instanceof Error ? error.message : String(error), 400)
812
+ }
813
+ mounts.forget(result.serverName)
814
+ try {
815
+ const state = await store.update((current) => removeItem(current, 'mcp', result.serverName))
816
+ return committed(state)
817
+ } catch (error) {
818
+ return stateFailure(error, 'resource-pool/save-failed', 500)
819
+ }
820
+ }
821
+
822
+ /** POST /dsh-skill-pool/skill/upload — install skill bundles from plain files. */
823
+ const skillUploadRoute = async (request) => {
824
+ const body = await readBody(request)
825
+ const files = uploadFiles(body.files)
826
+ if (files.length === 0) return failure('resource-pool/bad-files', '缺少 files([{path, contentBase64}])')
827
+ // Do not install files if the membership update cannot be read back later.
828
+ await readState()
829
+ let scope
830
+ try {
831
+ scope = readScope(body.scope)
832
+ } catch (error) {
833
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
834
+ }
835
+ try {
836
+ const result = installResult(await installFromFiles({
837
+ files,
838
+ root: skillsRoot(),
839
+ overwrite: body.overwrite === true,
840
+ name: textOf(body.name),
841
+ description: textOf(body.description),
842
+ }))
843
+ const source = {
844
+ id: newId('src'),
845
+ kind: 'files',
846
+ label: importLabel('files', result.installed, ''),
847
+ skills: result.installed,
848
+ createdAt: new Date().toISOString(),
849
+ }
850
+ const state = await store.update((current) => {
851
+ const previous = captureEffectiveScopes(current, result.installed)
852
+ let next = upsertSource(current, source)
853
+ next = installItems(next, result.installed, {
854
+ scope,
855
+ sourceId: source.id,
856
+ digests: result.digests,
857
+ installedAt: new Date().toISOString(),
858
+ previous,
859
+ })
860
+ return next
861
+ })
862
+ return committed(state, {
863
+ source: state.sources[source.id],
864
+ installed: result.installed,
865
+ failures: result.failures,
866
+ })
867
+ } catch (error) {
868
+ return stateFailure(error, 'resource-pool/upload-failed', 400)
869
+ }
870
+ }
871
+
872
+ /** POST /dsh-skill-pool/skill/zip — install skill bundles from a ZIP archive. */
873
+ const skillZipRoute = async (request) => {
874
+ const body = await readBody(request)
875
+ if (typeof body.archiveBase64 !== 'string' || body.archiveBase64.length === 0) {
876
+ return failure('resource-pool/bad-archive', '缺少 archiveBase64')
877
+ }
878
+ // Validate before unpacking anything to disk.
879
+ await readState()
880
+ let scope
881
+ try {
882
+ scope = readScope(body.scope)
883
+ } catch (error) {
884
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
885
+ }
886
+ try {
887
+ const result = installResult(await installFromZip({
888
+ archiveBase64: body.archiveBase64,
889
+ root: skillsRoot(),
890
+ overwrite: body.overwrite === true,
891
+ label: textOf(body.label),
892
+ }))
893
+ const source = {
894
+ id: newId('src'),
895
+ kind: 'zip',
896
+ label: importLabel('zip', result.installed, body.label),
897
+ skills: result.installed,
898
+ createdAt: new Date().toISOString(),
899
+ }
900
+ const state = await store.update((current) => {
901
+ const previous = captureEffectiveScopes(current, result.installed)
902
+ let next = upsertSource(current, source)
903
+ next = installItems(next, result.installed, {
904
+ scope,
905
+ sourceId: source.id,
906
+ digests: result.digests,
907
+ installedAt: new Date().toISOString(),
908
+ previous,
909
+ })
910
+ return next
911
+ })
912
+ return committed(state, {
913
+ source: state.sources[source.id],
914
+ installed: result.installed,
915
+ failures: result.failures,
916
+ })
917
+ } catch (error) {
918
+ return stateFailure(error, 'resource-pool/zip-failed', 400)
919
+ }
920
+ }
921
+
922
+ /** POST /dsh-skill-pool/source/git — install skills from GitHub/GitLab. */
923
+ const sourceGitRoute = async (request) => {
924
+ const body = await readBody(request)
925
+ const url = textOf(body.url)
926
+ if (url.length === 0) return failure('resource-pool/bad-url', '缺少仓库 URL')
927
+ // Validate before downloading/installing anything to disk.
928
+ await readState()
929
+ // Empty branch/subdir lets the library fall back to what the pasted URL encodes
930
+ // (GitLab's '/-/tree/<branch>/<subdir>'), then to 'main'.
931
+ const branch = textOf(body.branch)
932
+ const subdir = textOf(body.subdir)
933
+ const token = typeof body.token === 'string' ? body.token : ''
934
+ const provider = body.provider === 'github' || body.provider === 'gitlab' ? body.provider : 'auto'
935
+ let scope
936
+ try {
937
+ scope = readScope(body.scope)
938
+ } catch (error) {
939
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
940
+ }
941
+ try {
942
+ const result = installResult(await installFromGit({
943
+ url,
944
+ branch,
945
+ subdir,
946
+ token,
947
+ provider,
948
+ label: textOf(body.label),
949
+ root: skillsRoot(),
950
+ overwrite: body.overwrite === true,
951
+ }))
952
+ const returned = isObject(result.source) ? result.source : {}
953
+ const source = {
954
+ ...returned,
955
+ id: typeof returned.id === 'string' && returned.id.length > 0 ? returned.id : newId('src'),
956
+ kind: 'git',
957
+ url,
958
+ host: typeof returned.host === 'string' ? returned.host : '',
959
+ branch: typeof returned.branch === 'string' && returned.branch.length > 0 ? returned.branch : branch || 'main',
960
+ subdir: typeof returned.subdir === 'string' ? returned.subdir : subdir,
961
+ skills: result.installed,
962
+ createdAt: typeof returned.createdAt === 'string' ? returned.createdAt : new Date().toISOString(),
963
+ }
964
+ const tokenCredential = await storeGitToken(source.id, token)
965
+ if (tokenCredential !== undefined) source.tokenCredential = tokenCredential
966
+ const state = await store.update((current) => {
967
+ const previous = captureEffectiveScopes(current, result.installed)
968
+ let next = upsertSource(current, source)
969
+ next = installItems(next, result.installed, {
970
+ scope,
971
+ sourceId: source.id,
972
+ digests: result.digests,
973
+ installedAt: new Date().toISOString(),
974
+ previous,
975
+ })
976
+ return next
977
+ })
978
+ return committed(state, {
979
+ source: state.sources[source.id],
980
+ installed: result.installed,
981
+ failures: result.failures,
982
+ })
983
+ } catch (error) {
984
+ return stateFailure(error, 'resource-pool/git-failed', 400)
985
+ }
986
+ }
987
+
988
+ /**
989
+ * POST /dsh-skill-pool/source/check — compare each Git source's stored
990
+ * commit with the remote one *without downloading the archive*. One failing
991
+ * source is reported as `status: 'error'` in `results`; the route never 500s.
992
+ */
993
+ const sourceCheckRoute = async (request) => {
994
+ const body = await readBody(request)
995
+ let ids
996
+ if (body.ids !== undefined) {
997
+ if (!Array.isArray(body.ids)) return failure('resource-pool/bad-ids', 'ids 必须是字符串数组')
998
+ ids = body.ids.map((id) => textOf(id)).filter((id) => id.length > 0)
999
+ }
1000
+ const current = await readState()
1001
+ const targets = []
1002
+ if (ids !== undefined) {
1003
+ for (const id of ids) targets.push({ id, source: current.sources[id] })
1004
+ } else {
1005
+ for (const source of Object.values(current.sources)) {
1006
+ if (source.kind === 'git') targets.push({ id: source.id, source })
1007
+ }
1008
+ }
1009
+
1010
+ const results = []
1011
+ const checks = {}
1012
+ const checkedAt = new Date().toISOString()
1013
+ for (const { id, source } of targets) {
1014
+ if (source === undefined) {
1015
+ results.push({ id, label: '', status: 'error', current: '', remote: '', error: `来源 ${id} 不存在` })
1016
+ continue
1017
+ }
1018
+ if (source.kind !== 'git') {
1019
+ results.push({
1020
+ id,
1021
+ label: source.label,
1022
+ status: 'error',
1023
+ current: '',
1024
+ remote: '',
1025
+ error: '只有 Git 来源可以检查更新',
1026
+ })
1027
+ continue
1028
+ }
1029
+ try {
1030
+ const token = await gitToken(source.tokenCredential)
1031
+ const raw = await checkGitSource({ source, token })
1032
+ const check = isObject(raw) ? raw : {}
1033
+ const remote = textOf(check.remote)
1034
+ const status = checkStatus(check.status, textOf(check.current), remote)
1035
+ const result = {
1036
+ id,
1037
+ label: textOf(check.label) || source.label,
1038
+ status,
1039
+ current: textOf(check.current),
1040
+ remote,
1041
+ }
1042
+ if (status === 'error') result.error = '无法确认远端提交'
1043
+ results.push(result)
1044
+ checks[id] = { at: checkedAt, status, remote, error: status === 'error' ? '无法确认远端提交' : '' }
1045
+ } catch (error) {
1046
+ const message = error instanceof Error ? error.message : String(error)
1047
+ results.push({
1048
+ id,
1049
+ label: source.label,
1050
+ status: 'error',
1051
+ current: typeof source.sha === 'string' ? source.sha : '',
1052
+ remote: '',
1053
+ error: message,
1054
+ })
1055
+ checks[id] = { at: checkedAt, status: 'error', remote: '', error: message }
1056
+ }
1057
+ }
1058
+
1059
+ if (Object.keys(checks).length === 0) {
1060
+ // Nothing to record (no Git sources): the document is unchanged, so the
1061
+ // pool does not need re-applying.
1062
+ return json({ ok: true, state: publicState(current), results })
1063
+ }
1064
+ try {
1065
+ const state = await store.update((doc) => {
1066
+ let next = doc
1067
+ for (const [id, lastCheck] of Object.entries(checks)) {
1068
+ const source = next.sources[id]
1069
+ if (source === undefined) continue
1070
+ // Only the check outcome is stored: `sha` keeps naming the commit that
1071
+ // is actually installed, so update detection stays correct.
1072
+ next = upsertSource(next, { ...source, lastCheck })
1073
+ }
1074
+ return next
1075
+ })
1076
+ return committed(state, { results })
1077
+ } catch (error) {
1078
+ return stateFailure(error, 'resource-pool/check-failed', 500)
1079
+ }
1080
+ }
1081
+
1082
+ /** POST /dsh-skill-pool/source/update — re-fetch one Git source. */
1083
+ const sourceUpdateRoute = async (request) => {
1084
+ const body = await readBody(request)
1085
+ const id = textOf(body.id)
1086
+ if (id.length === 0) return failure('resource-pool/bad-id', '缺少 id')
1087
+ const current = await readState()
1088
+ const source = current.sources[id]
1089
+ if (source === undefined) return failure('resource-pool/unknown-source', `来源 ${id} 不存在`, 404)
1090
+ if (source.kind !== 'git') return failure('resource-pool/bad-kind', '只有 Git 来源可以更新', 400)
1091
+ try {
1092
+ const token = await gitToken(source.tokenCredential)
1093
+ // `restore` clears the exclusion list and forces a reinstall; `force` alone
1094
+ // reinstall the current commit without clearing anything.
1095
+ const restore = body.restore === true
1096
+ const force = body.force === true || restore
1097
+ const updated = await updateGitSource({
1098
+ source: restore ? { ...source, excluded: [] } : source,
1099
+ token,
1100
+ root: skillsRoot(),
1101
+ exclude: restore ? [] : source.excluded,
1102
+ force,
1103
+ })
1104
+ const result = installResult(updated)
1105
+ const changed = updated?.changed === true
1106
+ const removed = Array.isArray(updated?.removed)
1107
+ ? updated.removed.filter((name) => typeof name === 'string' && name.length > 0)
1108
+ : []
1109
+ const returned = isObject(updated?.source) ? updated.source : {}
1110
+ const nextSource = {
1111
+ ...source,
1112
+ ...returned,
1113
+ id,
1114
+ kind: 'git',
1115
+ skills: Array.isArray(returned.skills) ? returned.skills : source.skills,
1116
+ excluded: restore
1117
+ ? []
1118
+ : Array.isArray(returned.excluded)
1119
+ ? returned.excluded
1120
+ : Array.isArray(source.excluded)
1121
+ ? source.excluded
1122
+ : [],
1123
+ lastCheck: {
1124
+ at: new Date().toISOString(),
1125
+ status: 'up-to-date',
1126
+ remote: typeof returned.sha === 'string' ? returned.sha : '',
1127
+ error: '',
1128
+ },
1129
+ }
1130
+ const state = await store.update((doc) => {
1131
+ const previous = captureEffectiveScopes(doc, result.installed)
1132
+ let next = upsertSource(doc, nextSource)
1133
+ next = installItems(next, result.installed, {
1134
+ scope: undefined,
1135
+ sourceId: id,
1136
+ digests: result.digests,
1137
+ installedAt: new Date().toISOString(),
1138
+ previous,
1139
+ })
1140
+ // Skills that disappeared upstream are gone from disk already.
1141
+ const shared = sharedNames(next, id)
1142
+ for (const name of removed) {
1143
+ if (shared.has(name)) continue
1144
+ next = removeItem(next, 'skill', name)
1145
+ }
1146
+ // An update that leaves the source with nothing installed turns it into
1147
+ // a dead tree row: drop it (and its group) like a delete would.
1148
+ const after = next.sources[id]
1149
+ if (after !== undefined && (!Array.isArray(after.skills) || after.skills.length === 0)) {
1150
+ const referenced = Object.values(next.skills).some((item) => item.sourceId === id)
1151
+ if (!referenced) next = removeSource(next, id)
1152
+ }
1153
+ return next
1154
+ })
1155
+ return committed(state, {
1156
+ source: state.sources[id],
1157
+ installed: result.installed,
1158
+ failures: result.failures,
1159
+ changed,
1160
+ })
1161
+ } catch (error) {
1162
+ return stateFailure(error, 'resource-pool/update-failed', 400)
1163
+ }
1164
+ }
1165
+
1166
+ /** POST /dsh-skill-pool/source/delete — remove a source and its skills. */
1167
+ const sourceDeleteRoute = async (request) => {
1168
+ const body = await readBody(request)
1169
+ const id = textOf(body.id)
1170
+ if (id.length === 0) return failure('resource-pool/bad-id', '缺少 id')
1171
+ const current = await readState()
1172
+ const source = current.sources[id]
1173
+ if (source === undefined) return failure('resource-pool/unknown-source', `来源 ${id} 不存在`, 404)
1174
+ try {
1175
+ // A skill may be claimed by more than one source (same name from a ZIP and
1176
+ // a repo); only delete the ones no other source still lists.
1177
+ const shared = sharedNames(current, id)
1178
+ const skipSkills = (Array.isArray(source.skills) ? source.skills : []).filter((name) => shared.has(name))
1179
+ const result = await removeSourceSkills({ source, root: skillsRoot(), skipSkills })
1180
+ const removed = Array.isArray(result?.removed) ? result.removed : []
1181
+ const skipped = Array.isArray(result?.skipped) ? result.skipped : skipSkills
1182
+ const state = await store.update((doc) => {
1183
+ // Shared skills stay installed, but they may currently inherit their
1184
+ // group scope. Materialize the *effective* scope/enabled before the
1185
+ // source (and possibly its group) disappears, otherwise a group-owned
1186
+ // empty scope would become an unrestricted self scope.
1187
+ let next = doc
1188
+ const removedSet = new Set(removed)
1189
+ for (const [name, member] of Object.entries(next.skills)) {
1190
+ if (member.sourceId !== id) continue
1191
+ if (removedSet.has(name)) continue
1192
+ const scope = effectiveScope(next, member)
1193
+ next = upsertItem(next, 'skill', name, {
1194
+ enabled: effectiveEnabled(next, member),
1195
+ modes: [...scope.modes],
1196
+ workspaces: [...scope.workspaces],
1197
+ }, { sourceId: '', modesFrom: 'self', workspacesFrom: 'self' })
1198
+ }
1199
+ next = removeSource(next, id)
1200
+ for (const name of removed) next = removeItem(next, 'skill', name)
1201
+ return next
1202
+ })
1203
+ return committed(state, { removed, skipped })
1204
+ } catch (error) {
1205
+ return stateFailure(error, 'resource-pool/delete-failed', 400)
1206
+ }
1207
+ }
1208
+
1209
+ /**
1210
+ * Turn a fail-closed state read into an explicit 500 for the panel instead of
1211
+ * letting it fall through as a generic internal error. Reads never write.
1212
+ */
1213
+ const guarded = (handler) => async (request) => {
1214
+ try {
1215
+ return await handler(request)
1216
+ } catch (error) {
1217
+ if (error instanceof StateReadError) {
1218
+ logger?.warn?.(`[resource-pool] request refused: ${error.message}`)
1219
+ return failure(error.code, error.message, 500)
1220
+ }
1221
+ throw error
1222
+ }
1223
+ }
1224
+
1225
+ const routes = [
1226
+ ['', ['GET'], guarded(overview)],
1227
+ ['/item', ['POST'], guarded(itemRoute)],
1228
+ ['/item/remove', ['POST'], guarded(itemRemoveRoute)],
1229
+ ['/settings', ['POST'], guarded(settingsRoute)],
1230
+ ['/group', ['POST'], guarded(groupRoute)],
1231
+ ['/resolve', ['GET'], guarded(resolveRoute)],
1232
+ ['/skill/upload', ['POST'], guarded(skillUploadRoute)],
1233
+ ['/skill/zip', ['POST'], guarded(skillZipRoute)],
1234
+ ['/source/git', ['POST'], guarded(sourceGitRoute)],
1235
+ ['/source/check', ['POST'], guarded(sourceCheckRoute)],
1236
+ ['/source/update', ['POST'], guarded(sourceUpdateRoute)],
1237
+ ['/source/delete', ['POST'], guarded(sourceDeleteRoute)],
1238
+ ['/mcp/import', ['POST'], guarded(mcpImportRoute)],
1239
+ ['/mcp/remove', ['POST'], guarded(mcpRemoveRoute)],
1240
+ ['/mounts', ['GET'], guarded(mountsRoute)],
1241
+ ]
1242
+
1243
+ // ------------------------------------------------------------- transport
1244
+
1245
+ const readNodeBody = (request) => new Promise((resolve, reject) => {
1246
+ const chunks = []
1247
+ let size = 0
1248
+ request.on('data', (chunk) => {
1249
+ size += chunk.length
1250
+ if (size > MAX_BODY_BYTES) {
1251
+ reject(new Error('request body too large'))
1252
+ request.destroy()
1253
+ return
1254
+ }
1255
+ chunks.push(chunk)
1256
+ })
1257
+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1258
+ request.on('error', reject)
1259
+ })
1260
+
1261
+ const writeNodeResponse = async (response, res) => {
1262
+ const headers = {}
1263
+ response.headers.forEach((value, key) => {
1264
+ headers[key] = value
1265
+ })
1266
+ res.writeHead(response.status, headers)
1267
+ res.end(Buffer.from(await response.arrayBuffer()))
1268
+ }
1269
+
1270
+ const refuse = (res, status) => {
1271
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
1272
+ res.end(status === 401 ? 'unauthorized' : 'forbidden')
1273
+ }
1274
+
1275
+ const handleNodeRequest = async (connection, req, res) => {
1276
+ const admission = typeof connection?.admit === 'function' ? connection.admit(req) : undefined
1277
+ if (admission === undefined || admission === null) {
1278
+ refuse(res, 401)
1279
+ return
1280
+ }
1281
+ if ('rejection' in admission) {
1282
+ refuse(res, admission.rejection === 403 ? 403 : 401)
1283
+ return
1284
+ }
1285
+ const url = new URL(req.url ?? '/', 'http://dsh.invalid')
1286
+ const method = req.method ?? 'GET'
1287
+ const route = routes.find(([suffix, methods]) => `${ROUTE_PREFIX}${suffix}` === url.pathname && methods.includes(method))
1288
+ if (route === undefined) {
1289
+ await writeNodeResponse(json({ ok: false, error: { code: 'resource-pool/not-found', message: 'unknown resource-pool route' } }, 404), res)
1290
+ return
1291
+ }
1292
+ const headers = {}
1293
+ for (const [key, value] of Object.entries(req.headers)) {
1294
+ if (value === undefined) continue
1295
+ headers[key] = Array.isArray(value) ? value.join(', ') : value
1296
+ }
1297
+ let body
1298
+ try {
1299
+ body = method === 'GET' || method === 'HEAD' ? undefined : await readNodeBody(req)
1300
+ } catch (error) {
1301
+ await writeNodeResponse(failure('resource-pool/too-large', error instanceof Error ? error.message : String(error), 413), res)
1302
+ return
1303
+ }
1304
+ let request
1305
+ try {
1306
+ request = new Request(url.toString(), {
1307
+ method,
1308
+ headers,
1309
+ ...(body === undefined || body.length === 0 ? {} : { body }),
1310
+ })
1311
+ } catch (error) {
1312
+ await writeNodeResponse(failure('resource-pool/bad-request', error instanceof Error ? error.message : String(error), 400), res)
1313
+ return
1314
+ }
1315
+ await writeNodeResponse(await route[2](request), res)
1316
+ }
1317
+
1318
+ ctx.inject(['webServer', 'connection'], (webCtx) => {
1319
+ const webServer = webCtx.get('webServer')
1320
+ const connection = webCtx.get('connection')
1321
+ if (webServer === undefined || typeof webServer.register !== 'function' || typeof connection?.admit !== 'function') {
1322
+ registerFetchRoutes(webCtx, connection)
1323
+ return
1324
+ }
1325
+ // Owned by the plugin context: a webServer/connection restart re-runs this
1326
+ // inject callback and would dispose a scope-owned route.
1327
+ ctx.effect(
1328
+ () =>
1329
+ webServer.register({
1330
+ kind: 'prefix',
1331
+ path: ROUTE_PREFIX,
1332
+ handler: (req, res) => {
1333
+ handleNodeRequest(connection, req, res).catch((error) => {
1334
+ logger?.warn?.(`[resource-pool] request failed: ${error instanceof Error ? error.message : String(error)}`)
1335
+ if (res.headersSent) {
1336
+ try {
1337
+ res.destroy()
1338
+ } catch {
1339
+ /* already gone */
1340
+ }
1341
+ return
1342
+ }
1343
+ try {
1344
+ res.writeHead(500, { 'content-type': 'application/json' })
1345
+ res.end(JSON.stringify({ ok: false, error: { code: 'resource-pool/internal', message: 'request failed' } }))
1346
+ } catch {
1347
+ /* response already closed */
1348
+ }
1349
+ })
1350
+ },
1351
+ }),
1352
+ 'resource-pool.http',
1353
+ )
1354
+ debug(`registered ${routes.length} resource pool routes under ${ROUTE_PREFIX} (webServer prefix)`)
1355
+ })
1356
+
1357
+ /** Fallback for compositions without a webServer: exact-Fetch routes. */
1358
+ function registerFetchRoutes(targetCtx, connection) {
1359
+ const register = connection?.fetch?.register
1360
+ if (typeof register !== 'function') {
1361
+ debug('neither webServer nor connection.fetch is available; resource pool API disabled')
1362
+ return
1363
+ }
1364
+ for (const [suffix, methods, handler] of routes) {
1365
+ targetCtx.effect(
1366
+ () =>
1367
+ register({
1368
+ path: `${ROUTE_PREFIX}${suffix}`,
1369
+ methods,
1370
+ requestBody: 'buffered',
1371
+ fetch: handler,
1372
+ }),
1373
+ `resource-pool.route.${suffix.length > 0 ? suffix.slice(1).replaceAll('/', '.') : 'overview'}`,
1374
+ )
1375
+ }
1376
+ debug(`registered ${routes.length} resource pool routes under ${ROUTE_PREFIX} (exact fetch)`)
1377
+ }
1378
+
1379
+ // Host-independent seam for scope-preservation tests; production ignores it.
1380
+ return { testHooks: { captureEffectiveScopes, installItems } }
1381
+ }