dsh-skill-pool 0.3.7 → 0.4.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.
package/src/web-api.js CHANGED
@@ -22,14 +22,16 @@ import {
22
22
  excludeSourceSkill,
23
23
  newId,
24
24
  normalizeItemName,
25
+ normalizePath,
25
26
  removeItem,
26
27
  removeSource,
28
+ StateReadError,
27
29
  upsertGroup,
28
30
  upsertItem,
29
31
  upsertSource,
30
32
  } from './store.js'
31
33
  import { buildInventory } from './inventory.js'
32
- import { resolvePool } from './rules.js'
34
+ import { effectiveEnabled, effectiveScope, groupKeyOfSource, groupOfMember, resolvePool } from './rules.js'
33
35
  import { DEFAULT_PROBE_INTERVAL_MS, DEFAULT_PROBE_TIMEOUT_MS, mountServer } from './mount.js'
34
36
  import {
35
37
  buildMcpConfig,
@@ -68,6 +70,17 @@ function failure(code, message, status = 400) {
68
70
  return json({ ok: false, error: { code, message } }, status)
69
71
  }
70
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
+
71
84
  /** Whether a value is a plain object (not an array, not null). */
72
85
  function isObject(value) {
73
86
  return value !== null && typeof value === 'object' && !Array.isArray(value)
@@ -88,6 +101,47 @@ async function readBody(request) {
88
101
  }
89
102
  }
90
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
+
91
145
  /**
92
146
  * Register the panel's HTTP routes.
93
147
  *
@@ -107,17 +161,58 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
107
161
  const probeTimeoutMs = Number.isFinite(mountProbe?.timeoutMs) ? mountProbe.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS
108
162
  const probeIntervalMs = Number.isFinite(mountProbe?.intervalMs) ? mountProbe.intervalMs : DEFAULT_PROBE_INTERVAL_MS
109
163
 
110
- const readState = () => store.read()
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 })
111
167
  const skillsRoot = () => librarySkillsRoot()
112
168
 
113
169
  /** Committed mutation response: file is already on disk, re-apply, then answer. */
114
170
  const committed = async (state, extra = {}) => {
171
+ let warning
115
172
  try {
116
- await onChanged?.()
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
+ }
117
208
  } catch (error) {
118
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
+ }
119
214
  }
120
- return json({ ok: true, state, ...extra })
215
+ return json({ ok: true, state: publicState(state), ...extra, ...(warning === undefined ? {} : { warning }) })
121
216
  }
122
217
 
123
218
  /** Resolve one stored Git token from the credential store. */
@@ -150,37 +245,115 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
150
245
 
151
246
  // ------------------------------------------------------------- validation
152
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
+
153
338
  /** Read one `scope` object (`{modes, workspaces}`); undefined when absent. */
154
339
  const readScope = (value) => {
155
340
  if (value === undefined || value === null) return undefined
156
341
  if (!isObject(value)) throw new Error('scope 必须是 {modes, workspaces} 对象')
157
342
  const scope = {}
158
- if (value.modes !== undefined) {
159
- if (!Array.isArray(value.modes)) throw new Error('scope.modes 必须是数组')
160
- scope.modes = value.modes
161
- }
162
- if (value.workspaces !== undefined) {
163
- if (!Array.isArray(value.workspaces)) throw new Error('scope.workspaces 必须是字符串数组')
164
- scope.workspaces = value.workspaces
165
- }
343
+ if (value.modes !== undefined) scope.modes = strictModes(value.modes, 'scope.modes')
344
+ if (value.workspaces !== undefined) scope.workspaces = strictWorkspaces(value.workspaces, 'scope.workspaces')
166
345
  return scope
167
346
  }
168
347
 
169
- /** Read the `/item` condition patch (`{enabled?, modes?, workspaces?}`). */
348
+ /** Read the `/item` patch: activation conditions only. */
170
349
  const readItemPatch = (body) => {
171
350
  const patch = {}
172
351
  if (body.enabled !== undefined) {
173
352
  if (typeof body.enabled !== 'boolean') throw new Error('enabled 必须是布尔值')
174
353
  patch.enabled = body.enabled
175
354
  }
176
- if (body.modes !== undefined) {
177
- if (!Array.isArray(body.modes)) throw new Error('modes 必须是数组')
178
- patch.modes = body.modes
179
- }
180
- if (body.workspaces !== undefined) {
181
- if (!Array.isArray(body.workspaces)) throw new Error('workspaces 必须是字符串数组')
182
- patch.workspaces = body.workspaces
183
- }
355
+ if (body.modes !== undefined) patch.modes = strictModes(body.modes, 'modes')
356
+ if (body.workspaces !== undefined) patch.workspaces = strictWorkspaces(body.workspaces, 'workspaces')
184
357
  for (const key of ['modesFrom', 'workspacesFrom']) {
185
358
  if (body[key] === undefined) continue
186
359
  if (body[key] !== 'group' && body[key] !== 'self') throw new Error(`${key} 必须是 'group' 或 'self'`)
@@ -200,18 +373,89 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
200
373
  }
201
374
  }
202
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
+
203
393
  /**
204
- * Add freshly installed skills to the pool, keeping a member's previous
205
- * conditions when the import did not specify new ones.
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.
206
407
  */
207
- const installItems = (state, names, { scope, sourceId, digests, installedAt }) => {
408
+ const installItems = (state, names, { scope, sourceId, digests, installedAt, previous }) => {
208
409
  let next = state
410
+ const provided = isObject(scope) ? scope : {}
209
411
  for (const name of names) {
210
412
  const extra = { installedAt }
211
413
  if (typeof sourceId === 'string' && sourceId.length > 0) extra.sourceId = sourceId
212
414
  const digest = isObject(digests) ? digests[name] : undefined
213
415
  if (typeof digest === 'string' && digest.length > 0) extra.digest = digest
214
- next = upsertItem(next, 'skill', name, itemScope(next, 'skill', name, scope ?? {}), extra)
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)
215
459
  }
216
460
  return next
217
461
  }
@@ -283,8 +527,12 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
283
527
  try {
284
528
  const state = await readState()
285
529
  const inventory = await buildInventory(ctx, { state, libraryRoot: skillsRoot() })
286
- return json({ ok: true, meta, state, inventory, mounts: mounts.status() })
530
+ return json({ ok: true, meta, state: publicState(state), inventory, mounts: mounts.status() })
287
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
+ }
288
536
  logger?.warn?.(`[resource-pool] overview failed: ${error instanceof Error ? error.message : String(error)}`)
289
537
  return failure('resource-pool/read-failed', '无法读取技能池状态', 500)
290
538
  }
@@ -309,6 +557,38 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
309
557
  try {
310
558
  const state = await store.update((current) => {
311
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
+ }
312
592
  const extra = {
313
593
  sourceId: existing?.sourceId,
314
594
  digest: existing?.digest,
@@ -320,7 +600,8 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
320
600
  })
321
601
  return committed(state)
322
602
  } catch (error) {
323
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
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)
324
605
  }
325
606
  }
326
607
 
@@ -334,6 +615,9 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
334
615
  if (kind === '') return failure('resource-pool/bad-kind', "kind 必须是 'skill' 或 'mcp'")
335
616
  const name = normalizeItemName(body.name)
336
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()
337
621
 
338
622
  const removed = { kind, name }
339
623
  if (kind === 'skill') {
@@ -359,7 +643,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
359
643
  })
360
644
  return committed(state, { removed })
361
645
  } catch (error) {
362
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
646
+ return stateFailure(error, 'resource-pool/save-failed', 500)
363
647
  }
364
648
  }
365
649
 
@@ -377,7 +661,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
377
661
  const state = await store.update((current) => removeItem(current, 'mcp', name))
378
662
  return committed(state, { removed })
379
663
  } catch (error) {
380
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
664
+ return stateFailure(error, 'resource-pool/save-failed', 500)
381
665
  }
382
666
  }
383
667
 
@@ -386,11 +670,16 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
386
670
  const body = await readBody(request)
387
671
  const patch = isObject(body.patch) ? body.patch : isObject(body.settings) ? body.settings : null
388
672
  if (patch === null) return failure('resource-pool/bad-settings', '缺少 patch 对象')
673
+ for (const key of ['enabled', 'mcpGate', 'gateDefaultSkills']) {
674
+ if (patch[key] !== undefined && typeof patch[key] !== 'boolean') {
675
+ return failure('resource-pool/bad-settings', `${key} 必须是布尔值`)
676
+ }
677
+ }
389
678
  try {
390
679
  const state = await store.update((current) => applySettingsPatch(current, patch))
391
680
  return committed(state)
392
681
  } catch (error) {
393
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
682
+ return stateFailure(error, 'resource-pool/save-failed', 500)
394
683
  }
395
684
  }
396
685
 
@@ -399,24 +688,34 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
399
688
  const body = await readBody(request)
400
689
  const key = typeof body.key === 'string' ? body.key.trim() : ''
401
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
+ }
402
703
  const patch = { key }
403
704
  if (body.enabled !== undefined) {
404
705
  if (typeof body.enabled !== 'boolean') return failure('resource-pool/bad-group', 'enabled 必须是布尔值')
405
706
  patch.enabled = body.enabled
406
707
  }
407
- if (body.modes !== undefined) {
408
- if (!Array.isArray(body.modes)) return failure('resource-pool/bad-group', 'modes 必须是数组')
409
- patch.modes = body.modes
410
- }
411
- if (body.workspaces !== undefined) {
412
- if (!Array.isArray(body.workspaces)) return failure('resource-pool/bad-group', 'workspaces 必须是字符串数组')
413
- patch.workspaces = body.workspaces
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))
414
713
  }
415
714
  try {
416
715
  const state = await store.update((current) => upsertGroup(current, patch))
417
716
  return committed(state)
418
717
  } catch (error) {
419
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
718
+ return stateFailure(error, 'resource-pool/save-failed', 500)
420
719
  }
421
720
  }
422
721
 
@@ -478,7 +777,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
478
777
  return next
479
778
  })
480
779
  } catch (error) {
481
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
780
+ return stateFailure(error, 'resource-pool/save-failed', 500)
482
781
  }
483
782
 
484
783
  const servers = []
@@ -503,6 +802,8 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
503
802
  const body = await readBody(request)
504
803
  const serverName = textOf(body.server)
505
804
  if (serverName.length === 0) return failure('resource-pool/bad-server', '缺少 server')
805
+ // Validate state before removing the Loader row.
806
+ await readState()
506
807
  let result
507
808
  try {
508
809
  result = await removeMcpServer(ctx, serverName)
@@ -514,7 +815,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
514
815
  const state = await store.update((current) => removeItem(current, 'mcp', result.serverName))
515
816
  return committed(state)
516
817
  } catch (error) {
517
- return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
818
+ return stateFailure(error, 'resource-pool/save-failed', 500)
518
819
  }
519
820
  }
520
821
 
@@ -523,6 +824,8 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
523
824
  const body = await readBody(request)
524
825
  const files = uploadFiles(body.files)
525
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()
526
829
  let scope
527
830
  try {
528
831
  scope = readScope(body.scope)
@@ -545,12 +848,14 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
545
848
  createdAt: new Date().toISOString(),
546
849
  }
547
850
  const state = await store.update((current) => {
851
+ const previous = captureEffectiveScopes(current, result.installed)
548
852
  let next = upsertSource(current, source)
549
853
  next = installItems(next, result.installed, {
550
854
  scope,
551
855
  sourceId: source.id,
552
856
  digests: result.digests,
553
857
  installedAt: new Date().toISOString(),
858
+ previous,
554
859
  })
555
860
  return next
556
861
  })
@@ -560,7 +865,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
560
865
  failures: result.failures,
561
866
  })
562
867
  } catch (error) {
563
- return failure('resource-pool/upload-failed', error instanceof Error ? error.message : String(error), 400)
868
+ return stateFailure(error, 'resource-pool/upload-failed', 400)
564
869
  }
565
870
  }
566
871
 
@@ -570,6 +875,8 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
570
875
  if (typeof body.archiveBase64 !== 'string' || body.archiveBase64.length === 0) {
571
876
  return failure('resource-pool/bad-archive', '缺少 archiveBase64')
572
877
  }
878
+ // Validate before unpacking anything to disk.
879
+ await readState()
573
880
  let scope
574
881
  try {
575
882
  scope = readScope(body.scope)
@@ -591,12 +898,14 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
591
898
  createdAt: new Date().toISOString(),
592
899
  }
593
900
  const state = await store.update((current) => {
901
+ const previous = captureEffectiveScopes(current, result.installed)
594
902
  let next = upsertSource(current, source)
595
903
  next = installItems(next, result.installed, {
596
904
  scope,
597
905
  sourceId: source.id,
598
906
  digests: result.digests,
599
907
  installedAt: new Date().toISOString(),
908
+ previous,
600
909
  })
601
910
  return next
602
911
  })
@@ -606,7 +915,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
606
915
  failures: result.failures,
607
916
  })
608
917
  } catch (error) {
609
- return failure('resource-pool/zip-failed', error instanceof Error ? error.message : String(error), 400)
918
+ return stateFailure(error, 'resource-pool/zip-failed', 400)
610
919
  }
611
920
  }
612
921
 
@@ -615,6 +924,8 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
615
924
  const body = await readBody(request)
616
925
  const url = textOf(body.url)
617
926
  if (url.length === 0) return failure('resource-pool/bad-url', '缺少仓库 URL')
927
+ // Validate before downloading/installing anything to disk.
928
+ await readState()
618
929
  // Empty branch/subdir lets the library fall back to what the pasted URL encodes
619
930
  // (GitLab's '/-/tree/<branch>/<subdir>'), then to 'main'.
620
931
  const branch = textOf(body.branch)
@@ -653,12 +964,14 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
653
964
  const tokenCredential = await storeGitToken(source.id, token)
654
965
  if (tokenCredential !== undefined) source.tokenCredential = tokenCredential
655
966
  const state = await store.update((current) => {
967
+ const previous = captureEffectiveScopes(current, result.installed)
656
968
  let next = upsertSource(current, source)
657
969
  next = installItems(next, result.installed, {
658
970
  scope,
659
971
  sourceId: source.id,
660
972
  digests: result.digests,
661
973
  installedAt: new Date().toISOString(),
974
+ previous,
662
975
  })
663
976
  return next
664
977
  })
@@ -668,7 +981,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
668
981
  failures: result.failures,
669
982
  })
670
983
  } catch (error) {
671
- return failure('resource-pool/git-failed', error instanceof Error ? error.message : String(error), 400)
984
+ return stateFailure(error, 'resource-pool/git-failed', 400)
672
985
  }
673
986
  }
674
987
 
@@ -746,7 +1059,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
746
1059
  if (Object.keys(checks).length === 0) {
747
1060
  // Nothing to record (no Git sources): the document is unchanged, so the
748
1061
  // pool does not need re-applying.
749
- return json({ ok: true, state: current, results })
1062
+ return json({ ok: true, state: publicState(current), results })
750
1063
  }
751
1064
  try {
752
1065
  const state = await store.update((doc) => {
@@ -762,7 +1075,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
762
1075
  })
763
1076
  return committed(state, { results })
764
1077
  } catch (error) {
765
- return failure('resource-pool/check-failed', error instanceof Error ? error.message : String(error), 500)
1078
+ return stateFailure(error, 'resource-pool/check-failed', 500)
766
1079
  }
767
1080
  }
768
1081
 
@@ -815,12 +1128,14 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
815
1128
  },
816
1129
  }
817
1130
  const state = await store.update((doc) => {
1131
+ const previous = captureEffectiveScopes(doc, result.installed)
818
1132
  let next = upsertSource(doc, nextSource)
819
1133
  next = installItems(next, result.installed, {
820
1134
  scope: undefined,
821
1135
  sourceId: id,
822
1136
  digests: result.digests,
823
1137
  installedAt: new Date().toISOString(),
1138
+ previous,
824
1139
  })
825
1140
  // Skills that disappeared upstream are gone from disk already.
826
1141
  const shared = sharedNames(next, id)
@@ -844,7 +1159,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
844
1159
  changed,
845
1160
  })
846
1161
  } catch (error) {
847
- return failure('resource-pool/update-failed', error instanceof Error ? error.message : String(error), 400)
1162
+ return stateFailure(error, 'resource-pool/update-failed', 400)
848
1163
  }
849
1164
  }
850
1165
 
@@ -865,38 +1180,64 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
865
1180
  const removed = Array.isArray(result?.removed) ? result.removed : []
866
1181
  const skipped = Array.isArray(result?.skipped) ? result.skipped : skipSkills
867
1182
  const state = await store.update((doc) => {
868
- let next = removeSource(doc, id)
869
- for (const name of removed) next = removeItem(next, 'skill', name)
870
- // Shared skills stay installed; their dangling sourceId is cleared.
871
- for (const name of skipped) {
872
- const member = next.skills[name]
873
- if (member === undefined || member.sourceId !== id) continue
874
- next = upsertItem(next, 'skill', name, member, { sourceId: '' })
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' })
875
1198
  }
1199
+ next = removeSource(next, id)
1200
+ for (const name of removed) next = removeItem(next, 'skill', name)
876
1201
  return next
877
1202
  })
878
1203
  return committed(state, { removed, skipped })
879
1204
  } catch (error) {
880
- return failure('resource-pool/delete-failed', error instanceof Error ? error.message : String(error), 400)
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
881
1222
  }
882
1223
  }
883
1224
 
884
1225
  const routes = [
885
- ['', ['GET'], overview],
886
- ['/item', ['POST'], itemRoute],
887
- ['/item/remove', ['POST'], itemRemoveRoute],
888
- ['/settings', ['POST'], settingsRoute],
889
- ['/group', ['POST'], groupRoute],
890
- ['/resolve', ['GET'], resolveRoute],
891
- ['/skill/upload', ['POST'], skillUploadRoute],
892
- ['/skill/zip', ['POST'], skillZipRoute],
893
- ['/source/git', ['POST'], sourceGitRoute],
894
- ['/source/check', ['POST'], sourceCheckRoute],
895
- ['/source/update', ['POST'], sourceUpdateRoute],
896
- ['/source/delete', ['POST'], sourceDeleteRoute],
897
- ['/mcp/import', ['POST'], mcpImportRoute],
898
- ['/mcp/remove', ['POST'], mcpRemoveRoute],
899
- ['/mounts', ['GET'], mountsRoute],
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)],
900
1241
  ]
901
1242
 
902
1243
  // ------------------------------------------------------------- transport
@@ -1034,4 +1375,7 @@ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe
1034
1375
  }
1035
1376
  debug(`registered ${routes.length} resource pool routes under ${ROUTE_PREFIX} (exact fetch)`)
1036
1377
  }
1378
+
1379
+ // Host-independent seam for scope-preservation tests; production ignores it.
1380
+ return { testHooks: { captureEffectiveScopes, installItems } }
1037
1381
  }