dsh-skill-pool 0.0.0-stage → 0.3.7

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,1037 @@
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
+ removeItem,
26
+ removeSource,
27
+ upsertGroup,
28
+ upsertItem,
29
+ upsertSource,
30
+ } from './store.js'
31
+ import { buildInventory } from './inventory.js'
32
+ import { resolvePool } from './rules.js'
33
+ import { DEFAULT_PROBE_INTERVAL_MS, DEFAULT_PROBE_TIMEOUT_MS, mountServer } from './mount.js'
34
+ import {
35
+ buildMcpConfig,
36
+ createMountTracker,
37
+ normalizeMcpImport,
38
+ removeMcpServer,
39
+ } from './uploads.js'
40
+ import {
41
+ checkGitSource,
42
+ installFromFiles,
43
+ installFromGit,
44
+ installFromZip,
45
+ librarySkillsRoot,
46
+ removeSkillDir,
47
+ removeSourceSkills,
48
+ updateGitSource,
49
+ } from './library.js'
50
+
51
+ /** Route prefix below the origin root. */
52
+ export const ROUTE_PREFIX = '/dsh-skill-pool'
53
+
54
+ /** Credential-name prefix for Git tokens (only the name is stored in `state`). */
55
+ const GIT_TOKEN_PREFIX = 'RESOURCE_POOL_GIT_'
56
+
57
+ /** Body cap for panel writes. */
58
+ // 64MB archive cap in base64 plus JSON overhead; see library.MAX_ARCHIVE_BYTES.
59
+ const MAX_BODY_BYTES = 96 * 1024 * 1024
60
+
61
+ /** JSON response helper. */
62
+ function json(value, status = 200) {
63
+ return Response.json(value, { status, headers: { 'cache-control': 'no-store' } })
64
+ }
65
+
66
+ /** Failure response helper. */
67
+ function failure(code, message, status = 400) {
68
+ return json({ ok: false, error: { code, message } }, status)
69
+ }
70
+
71
+ /** Whether a value is a plain object (not an array, not null). */
72
+ function isObject(value) {
73
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
74
+ }
75
+
76
+ /** Trim one optional string, returning '' when absent. */
77
+ function textOf(value) {
78
+ return typeof value === 'string' ? value.trim() : ''
79
+ }
80
+
81
+ /** Parse a JSON body without throwing on empty or malformed input. */
82
+ async function readBody(request) {
83
+ try {
84
+ const value = await request.json()
85
+ return isObject(value) ? value : {}
86
+ } catch {
87
+ return {}
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Register the panel's HTTP routes.
93
+ *
94
+ * @param {object} options - registration options.
95
+ * @param {object} options.ctx - plugin context.
96
+ * @param {object} options.store - state store.
97
+ * @param {object} options.meta - static metadata returned to the panel.
98
+ * @param {() => Promise<void>} [options.onChanged] - called after a committed mutation.
99
+ * @param {{ debug?: Function, warn?: Function, info?: Function }} [options.logger] - logger.
100
+ * @param {{ timeoutMs?: number, intervalMs?: number }} [options.mountProbe] - MCP readiness window.
101
+ * @param {object} [options.mounts] - shared mount tracker (boot re-mounts land here too).
102
+ */
103
+ export function registerWebApi({ ctx, store, meta, onChanged, logger, mountProbe, mounts = createMountTracker() } = {}) {
104
+ const debug = logger?.debug ?? (() => {})
105
+ // "ready" means the server's tools are actually registered, not merely that a
106
+ // Loader row exists: an unreachable server creates the row and never connects.
107
+ const probeTimeoutMs = Number.isFinite(mountProbe?.timeoutMs) ? mountProbe.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS
108
+ const probeIntervalMs = Number.isFinite(mountProbe?.intervalMs) ? mountProbe.intervalMs : DEFAULT_PROBE_INTERVAL_MS
109
+
110
+ const readState = () => store.read()
111
+ const skillsRoot = () => librarySkillsRoot()
112
+
113
+ /** Committed mutation response: file is already on disk, re-apply, then answer. */
114
+ const committed = async (state, extra = {}) => {
115
+ try {
116
+ await onChanged?.()
117
+ } catch (error) {
118
+ logger?.warn?.(`[resource-pool] re-application failed: ${error instanceof Error ? error.message : String(error)}`)
119
+ }
120
+ return json({ ok: true, state, ...extra })
121
+ }
122
+
123
+ /** Resolve one stored Git token from the credential store. */
124
+ const gitToken = async (credentialName) => {
125
+ if (typeof credentialName !== 'string' || credentialName.length === 0) return ''
126
+ const credentials = ctx.get('credentials')
127
+ if (credentials === undefined || typeof credentials.resolve !== 'function') return ''
128
+ try {
129
+ const resolved = await credentials.resolve(credentialName)
130
+ return typeof resolved?.value === 'string' ? resolved.value : ''
131
+ } catch {
132
+ return ''
133
+ }
134
+ }
135
+
136
+ /** Store one provided token under a source-scoped credential name. */
137
+ const storeGitToken = async (sourceId, token) => {
138
+ if (typeof token !== 'string' || token.trim().length === 0) return undefined
139
+ const credentials = ctx.get('credentials')
140
+ if (credentials === undefined || typeof credentials.set !== 'function') return undefined
141
+ const name = `${GIT_TOKEN_PREFIX}${sourceId.toUpperCase().replace(/[^A-Z0-9_]/g, '_')}`
142
+ try {
143
+ await credentials.set(name, token.trim())
144
+ return name
145
+ } catch (error) {
146
+ logger?.warn?.(`[resource-pool] token not stored: ${error instanceof Error ? error.message : String(error)}`)
147
+ return undefined
148
+ }
149
+ }
150
+
151
+ // ------------------------------------------------------------- validation
152
+
153
+ /** Read one `scope` object (`{modes, workspaces}`); undefined when absent. */
154
+ const readScope = (value) => {
155
+ if (value === undefined || value === null) return undefined
156
+ if (!isObject(value)) throw new Error('scope 必须是 {modes, workspaces} 对象')
157
+ 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
+ }
166
+ return scope
167
+ }
168
+
169
+ /** Read the `/item` condition patch (`{enabled?, modes?, workspaces?}`). */
170
+ const readItemPatch = (body) => {
171
+ const patch = {}
172
+ if (body.enabled !== undefined) {
173
+ if (typeof body.enabled !== 'boolean') throw new Error('enabled 必须是布尔值')
174
+ patch.enabled = body.enabled
175
+ }
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
+ }
184
+ for (const key of ['modesFrom', 'workspacesFrom']) {
185
+ if (body[key] === undefined) continue
186
+ if (body[key] !== 'group' && body[key] !== 'self') throw new Error(`${key} 必须是 'group' 或 'self'`)
187
+ patch[key] = body[key]
188
+ }
189
+ return patch
190
+ }
191
+
192
+ /** Merge a condition patch over the stored member (or defaults for a new one). */
193
+ const itemScope = (state, kind, name, patch = {}) => {
194
+ const bucket = kind === 'skill' ? state.skills : state.mcp
195
+ const existing = isObject(bucket) ? bucket[name] : undefined
196
+ return {
197
+ enabled: patch.enabled !== undefined ? patch.enabled : (existing?.enabled ?? true),
198
+ modes: patch.modes !== undefined ? patch.modes : (existing?.modes ?? []),
199
+ workspaces: patch.workspaces !== undefined ? patch.workspaces : (existing?.workspaces ?? []),
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Add freshly installed skills to the pool, keeping a member's previous
205
+ * conditions when the import did not specify new ones.
206
+ */
207
+ const installItems = (state, names, { scope, sourceId, digests, installedAt }) => {
208
+ let next = state
209
+ for (const name of names) {
210
+ const extra = { installedAt }
211
+ if (typeof sourceId === 'string' && sourceId.length > 0) extra.sourceId = sourceId
212
+ const digest = isObject(digests) ? digests[name] : undefined
213
+ if (typeof digest === 'string' && digest.length > 0) extra.digest = digest
214
+ next = upsertItem(next, 'skill', name, itemScope(next, 'skill', name, scope ?? {}), extra)
215
+ }
216
+ return next
217
+ }
218
+
219
+ /** Assert an install result has the §7 shape; a mismatch is an integration bug. */
220
+ const installResult = (result) => {
221
+ if (!isObject(result) || !Array.isArray(result.installed)) {
222
+ throw new Error('library.js 返回值缺少 installed[](请确认其实现符合契约 §7)')
223
+ }
224
+ return {
225
+ installed: result.installed.filter((name) => typeof name === 'string' && name.length > 0),
226
+ failures: Array.isArray(result.failures) ? result.failures : [],
227
+ digests: isObject(result.digests) ? result.digests : {},
228
+ source: isObject(result.source) ? result.source : undefined,
229
+ }
230
+ }
231
+
232
+ /** Label for one import-created source record. */
233
+ const importLabel = (kind, names, providedLabel) => {
234
+ const label = textOf(providedLabel)
235
+ if (label.length > 0) return label
236
+ if (names.length === 1) return names[0]
237
+ if (kind === 'zip') return `ZIP(${names.length} 个技能)`
238
+ return `上传的 ${names.length} 个技能`
239
+ }
240
+
241
+ /** Decode panel upload files to the library's `{path, content}` shape. */
242
+ const uploadFiles = (raw) => {
243
+ const list = Array.isArray(raw) ? raw : []
244
+ const out = []
245
+ for (const file of list) {
246
+ if (!isObject(file)) continue
247
+ const path = typeof file.path === 'string' ? file.path : ''
248
+ if (typeof file.contentBase64 === 'string' && file.contentBase64.length > 0) {
249
+ const data = Buffer.from(file.contentBase64, 'base64')
250
+ // `installFromFiles` currently filters on `content`; carry both so the
251
+ // decoded bytes are also available to the library.
252
+ out.push({ path, content: data.toString('utf8'), data })
253
+ continue
254
+ }
255
+ if (typeof file.content === 'string') {
256
+ out.push({ path, content: file.content, data: Buffer.from(file.content, 'utf8') })
257
+ }
258
+ }
259
+ return out
260
+ }
261
+
262
+ /** Normalize one check outcome status (§2.1). */
263
+ const checkStatus = (status, current, remote) => {
264
+ if (status === 'up-to-date' || status === 'update-available' || status === 'error') return status
265
+ if (current.length > 0 && remote.length > 0) return current === remote ? 'up-to-date' : 'update-available'
266
+ return 'error'
267
+ }
268
+
269
+ /** Names other sources still list (used to avoid deleting a shared skill). */
270
+ const sharedNames = (state, exceptId) => {
271
+ const shared = new Set()
272
+ for (const [id, source] of Object.entries(state.sources)) {
273
+ if (id === exceptId) continue
274
+ for (const name of Array.isArray(source.skills) ? source.skills : []) shared.add(name)
275
+ }
276
+ return shared
277
+ }
278
+
279
+ // ---------------------------------------------------------------- handlers
280
+
281
+ /** GET /dsh-skill-pool */
282
+ const overview = async () => {
283
+ try {
284
+ const state = await readState()
285
+ const inventory = await buildInventory(ctx, { state, libraryRoot: skillsRoot() })
286
+ return json({ ok: true, meta, state, inventory, mounts: mounts.status() })
287
+ } catch (error) {
288
+ logger?.warn?.(`[resource-pool] overview failed: ${error instanceof Error ? error.message : String(error)}`)
289
+ return failure('resource-pool/read-failed', '无法读取技能池状态', 500)
290
+ }
291
+ }
292
+
293
+ /** GET /dsh-skill-pool/mounts */
294
+ const mountsRoute = async () => json({ ok: true, mounts: mounts.status() })
295
+
296
+ /** POST /dsh-skill-pool/item — edit one member's conditions / enabled flag. */
297
+ const itemRoute = async (request) => {
298
+ const body = await readBody(request)
299
+ const kind = body.kind === 'skill' ? 'skill' : body.kind === 'mcp' ? 'mcp' : ''
300
+ if (kind === '') return failure('resource-pool/bad-kind', "kind 必须是 'skill' 或 'mcp'")
301
+ const name = normalizeItemName(body.name)
302
+ if (name.length === 0) return failure('resource-pool/bad-name', '缺少合法的 name')
303
+ let patch
304
+ try {
305
+ patch = readItemPatch(body)
306
+ } catch (error) {
307
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
308
+ }
309
+ try {
310
+ const state = await store.update((current) => {
311
+ const existing = kind === 'skill' ? current.skills[name] : current.mcp[name]
312
+ const extra = {
313
+ sourceId: existing?.sourceId,
314
+ digest: existing?.digest,
315
+ installedAt: existing?.installedAt,
316
+ modesFrom: patch.modesFrom !== undefined ? patch.modesFrom : existing?.modesFrom,
317
+ workspacesFrom: patch.workspacesFrom !== undefined ? patch.workspacesFrom : existing?.workspacesFrom,
318
+ }
319
+ return upsertItem(current, kind, name, itemScope(current, kind, name, patch), extra)
320
+ })
321
+ return committed(state)
322
+ } catch (error) {
323
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
324
+ }
325
+ }
326
+
327
+ /**
328
+ * POST /dsh-skill-pool/item/remove — remove one pool member.
329
+ * Skills lose their library directory; MCP servers lose their Loader row.
330
+ */
331
+ const itemRemoveRoute = async (request) => {
332
+ const body = await readBody(request)
333
+ const kind = body.kind === 'skill' ? 'skill' : body.kind === 'mcp' ? 'mcp' : ''
334
+ if (kind === '') return failure('resource-pool/bad-kind', "kind 必须是 'skill' 或 'mcp'")
335
+ const name = normalizeItemName(body.name)
336
+ if (name.length === 0) return failure('resource-pool/bad-name', '缺少合法的 name')
337
+
338
+ const removed = { kind, name }
339
+ if (kind === 'skill') {
340
+ try {
341
+ removed.dir = (await removeSkillDir({ root: skillsRoot(), name })) === true
342
+ } catch (error) {
343
+ removed.dir = false
344
+ removed.warning = error instanceof Error ? error.message : String(error)
345
+ }
346
+ try {
347
+ const state = await store.update((current) => {
348
+ // Deleting is also an exclusion: the source remembers the name so an
349
+ // update never installs it again.
350
+ let next = excludeSourceSkill(removeItem(current, 'skill', name), name)
351
+ // A source with nothing left to install has nothing to update: drop it,
352
+ // and its group when it was the repository's last source.
353
+ for (const source of Object.values(next.sources)) {
354
+ if (Array.isArray(source.skills) && source.skills.length > 0) continue
355
+ const referenced = Object.values(next.skills).some((item) => item.sourceId === source.id)
356
+ if (!referenced) next = removeSource(next, source.id)
357
+ }
358
+ return next
359
+ })
360
+ return committed(state, { removed })
361
+ } catch (error) {
362
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
363
+ }
364
+ }
365
+
366
+ // MCP: drop the Loader row; a member whose row is already gone can still be
367
+ // removed from the pool (the panel shows the warning).
368
+ try {
369
+ const result = await removeMcpServer(ctx, name)
370
+ mounts.forget(result.serverName)
371
+ removed.mount = true
372
+ } catch (error) {
373
+ removed.mount = false
374
+ removed.warning = error instanceof Error ? error.message : String(error)
375
+ }
376
+ try {
377
+ const state = await store.update((current) => removeItem(current, 'mcp', name))
378
+ return committed(state, { removed })
379
+ } catch (error) {
380
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
381
+ }
382
+ }
383
+
384
+ /** POST /dsh-skill-pool/settings */
385
+ const settingsRoute = async (request) => {
386
+ const body = await readBody(request)
387
+ const patch = isObject(body.patch) ? body.patch : isObject(body.settings) ? body.settings : null
388
+ if (patch === null) return failure('resource-pool/bad-settings', '缺少 patch 对象')
389
+ try {
390
+ const state = await store.update((current) => applySettingsPatch(current, patch))
391
+ return committed(state)
392
+ } catch (error) {
393
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
394
+ }
395
+ }
396
+
397
+ /** POST /dsh-skill-pool/group — set the scope of one repository/import group. */
398
+ const groupRoute = async (request) => {
399
+ const body = await readBody(request)
400
+ const key = typeof body.key === 'string' ? body.key.trim() : ''
401
+ if (key.length === 0) return failure('resource-pool/bad-group', '缺少 group.key')
402
+ const patch = { key }
403
+ if (body.enabled !== undefined) {
404
+ if (typeof body.enabled !== 'boolean') return failure('resource-pool/bad-group', 'enabled 必须是布尔值')
405
+ patch.enabled = body.enabled
406
+ }
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
414
+ }
415
+ try {
416
+ const state = await store.update((current) => upsertGroup(current, patch))
417
+ return committed(state)
418
+ } catch (error) {
419
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
420
+ }
421
+ }
422
+
423
+ /** GET /dsh-skill-pool/resolve?mode=&cwd=&allModes=&allWorkspaces= */
424
+ const resolveRoute = async (request) => {
425
+ const state = await readState()
426
+ const url = new URL(request.url)
427
+ const cwd = url.searchParams.get('cwd') ?? ''
428
+ const mode = url.searchParams.get('mode') ?? ''
429
+ const allModes = url.searchParams.get('allModes') === '1'
430
+ const allWorkspaces = url.searchParams.get('allWorkspaces') === '1'
431
+ return json({ ok: true, pool: resolvePool(state, { mode, cwd, allModes, allWorkspaces }) })
432
+ }
433
+
434
+ /**
435
+ * POST /dsh-skill-pool/mcp/import — returns immediately, mounts in background.
436
+ * Body: `{payload, scope?}` where `payload` is the parsed `mcpServers` object
437
+ * (a JSON string is tolerated).
438
+ */
439
+ const mcpImportRoute = async (request) => {
440
+ const body = await readBody(request)
441
+ let entries
442
+ try {
443
+ entries = normalizeMcpImport(body.payload !== undefined ? body.payload : body)
444
+ } catch (error) {
445
+ return failure('resource-pool/mcp-import-failed', error instanceof Error ? error.message : String(error), 400)
446
+ }
447
+ // Validate the shape up front so an unusable definition fails as a 400
448
+ // instead of mounting and then reporting "failed".
449
+ const configs = new Map()
450
+ try {
451
+ for (const [serverName, definition] of entries) configs.set(serverName, buildMcpConfig(serverName, definition))
452
+ } catch (error) {
453
+ return failure('resource-pool/mcp-import-failed', error instanceof Error ? error.message : String(error), 400)
454
+ }
455
+ let scope
456
+ try {
457
+ scope = readScope(body.scope)
458
+ } catch (error) {
459
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
460
+ }
461
+
462
+ // Membership plus its connection definition land first: the definition is
463
+ // what a later Host start re-mounts from, so persisting it before the row
464
+ // exists means a crash mid-mount still leaves a recoverable member.
465
+ let state
466
+ try {
467
+ state = await store.update((current) => {
468
+ let next = current
469
+ for (const [serverName, definition] of entries) {
470
+ next = upsertItem(
471
+ next,
472
+ 'mcp',
473
+ serverName,
474
+ itemScope(next, 'mcp', serverName, scope ?? {}),
475
+ { definition: configs.get(serverName) ?? definition },
476
+ )
477
+ }
478
+ return next
479
+ })
480
+ } catch (error) {
481
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
482
+ }
483
+
484
+ const servers = []
485
+ for (const [serverName, definition] of entries) {
486
+ servers.push({ server: serverName, state: 'mounting' })
487
+ mountServer({
488
+ ctx,
489
+ serverName,
490
+ definition: configs.get(serverName) ?? definition,
491
+ mounts,
492
+ timeoutMs: probeTimeoutMs,
493
+ intervalMs: probeIntervalMs,
494
+ logger,
495
+ origin: 'import',
496
+ })
497
+ }
498
+ return committed(state, { servers, mounts: mounts.status() })
499
+ }
500
+
501
+ /** POST /dsh-skill-pool/mcp/remove — `{server}`. */
502
+ const mcpRemoveRoute = async (request) => {
503
+ const body = await readBody(request)
504
+ const serverName = textOf(body.server)
505
+ if (serverName.length === 0) return failure('resource-pool/bad-server', '缺少 server')
506
+ let result
507
+ try {
508
+ result = await removeMcpServer(ctx, serverName)
509
+ } catch (error) {
510
+ return failure('resource-pool/mcp-remove-failed', error instanceof Error ? error.message : String(error), 400)
511
+ }
512
+ mounts.forget(result.serverName)
513
+ try {
514
+ const state = await store.update((current) => removeItem(current, 'mcp', result.serverName))
515
+ return committed(state)
516
+ } catch (error) {
517
+ return failure('resource-pool/save-failed', error instanceof Error ? error.message : String(error), 500)
518
+ }
519
+ }
520
+
521
+ /** POST /dsh-skill-pool/skill/upload — install skill bundles from plain files. */
522
+ const skillUploadRoute = async (request) => {
523
+ const body = await readBody(request)
524
+ const files = uploadFiles(body.files)
525
+ if (files.length === 0) return failure('resource-pool/bad-files', '缺少 files([{path, contentBase64}])')
526
+ let scope
527
+ try {
528
+ scope = readScope(body.scope)
529
+ } catch (error) {
530
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
531
+ }
532
+ try {
533
+ const result = installResult(await installFromFiles({
534
+ files,
535
+ root: skillsRoot(),
536
+ overwrite: body.overwrite === true,
537
+ name: textOf(body.name),
538
+ description: textOf(body.description),
539
+ }))
540
+ const source = {
541
+ id: newId('src'),
542
+ kind: 'files',
543
+ label: importLabel('files', result.installed, ''),
544
+ skills: result.installed,
545
+ createdAt: new Date().toISOString(),
546
+ }
547
+ const state = await store.update((current) => {
548
+ let next = upsertSource(current, source)
549
+ next = installItems(next, result.installed, {
550
+ scope,
551
+ sourceId: source.id,
552
+ digests: result.digests,
553
+ installedAt: new Date().toISOString(),
554
+ })
555
+ return next
556
+ })
557
+ return committed(state, {
558
+ source: state.sources[source.id],
559
+ installed: result.installed,
560
+ failures: result.failures,
561
+ })
562
+ } catch (error) {
563
+ return failure('resource-pool/upload-failed', error instanceof Error ? error.message : String(error), 400)
564
+ }
565
+ }
566
+
567
+ /** POST /dsh-skill-pool/skill/zip — install skill bundles from a ZIP archive. */
568
+ const skillZipRoute = async (request) => {
569
+ const body = await readBody(request)
570
+ if (typeof body.archiveBase64 !== 'string' || body.archiveBase64.length === 0) {
571
+ return failure('resource-pool/bad-archive', '缺少 archiveBase64')
572
+ }
573
+ let scope
574
+ try {
575
+ scope = readScope(body.scope)
576
+ } catch (error) {
577
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
578
+ }
579
+ try {
580
+ const result = installResult(await installFromZip({
581
+ archiveBase64: body.archiveBase64,
582
+ root: skillsRoot(),
583
+ overwrite: body.overwrite === true,
584
+ label: textOf(body.label),
585
+ }))
586
+ const source = {
587
+ id: newId('src'),
588
+ kind: 'zip',
589
+ label: importLabel('zip', result.installed, body.label),
590
+ skills: result.installed,
591
+ createdAt: new Date().toISOString(),
592
+ }
593
+ const state = await store.update((current) => {
594
+ let next = upsertSource(current, source)
595
+ next = installItems(next, result.installed, {
596
+ scope,
597
+ sourceId: source.id,
598
+ digests: result.digests,
599
+ installedAt: new Date().toISOString(),
600
+ })
601
+ return next
602
+ })
603
+ return committed(state, {
604
+ source: state.sources[source.id],
605
+ installed: result.installed,
606
+ failures: result.failures,
607
+ })
608
+ } catch (error) {
609
+ return failure('resource-pool/zip-failed', error instanceof Error ? error.message : String(error), 400)
610
+ }
611
+ }
612
+
613
+ /** POST /dsh-skill-pool/source/git — install skills from GitHub/GitLab. */
614
+ const sourceGitRoute = async (request) => {
615
+ const body = await readBody(request)
616
+ const url = textOf(body.url)
617
+ if (url.length === 0) return failure('resource-pool/bad-url', '缺少仓库 URL')
618
+ // Empty branch/subdir lets the library fall back to what the pasted URL encodes
619
+ // (GitLab's '/-/tree/<branch>/<subdir>'), then to 'main'.
620
+ const branch = textOf(body.branch)
621
+ const subdir = textOf(body.subdir)
622
+ const token = typeof body.token === 'string' ? body.token : ''
623
+ const provider = body.provider === 'github' || body.provider === 'gitlab' ? body.provider : 'auto'
624
+ let scope
625
+ try {
626
+ scope = readScope(body.scope)
627
+ } catch (error) {
628
+ return failure('resource-pool/bad-scope', error instanceof Error ? error.message : String(error))
629
+ }
630
+ try {
631
+ const result = installResult(await installFromGit({
632
+ url,
633
+ branch,
634
+ subdir,
635
+ token,
636
+ provider,
637
+ label: textOf(body.label),
638
+ root: skillsRoot(),
639
+ overwrite: body.overwrite === true,
640
+ }))
641
+ const returned = isObject(result.source) ? result.source : {}
642
+ const source = {
643
+ ...returned,
644
+ id: typeof returned.id === 'string' && returned.id.length > 0 ? returned.id : newId('src'),
645
+ kind: 'git',
646
+ url,
647
+ host: typeof returned.host === 'string' ? returned.host : '',
648
+ branch: typeof returned.branch === 'string' && returned.branch.length > 0 ? returned.branch : branch || 'main',
649
+ subdir: typeof returned.subdir === 'string' ? returned.subdir : subdir,
650
+ skills: result.installed,
651
+ createdAt: typeof returned.createdAt === 'string' ? returned.createdAt : new Date().toISOString(),
652
+ }
653
+ const tokenCredential = await storeGitToken(source.id, token)
654
+ if (tokenCredential !== undefined) source.tokenCredential = tokenCredential
655
+ const state = await store.update((current) => {
656
+ let next = upsertSource(current, source)
657
+ next = installItems(next, result.installed, {
658
+ scope,
659
+ sourceId: source.id,
660
+ digests: result.digests,
661
+ installedAt: new Date().toISOString(),
662
+ })
663
+ return next
664
+ })
665
+ return committed(state, {
666
+ source: state.sources[source.id],
667
+ installed: result.installed,
668
+ failures: result.failures,
669
+ })
670
+ } catch (error) {
671
+ return failure('resource-pool/git-failed', error instanceof Error ? error.message : String(error), 400)
672
+ }
673
+ }
674
+
675
+ /**
676
+ * POST /dsh-skill-pool/source/check — compare each Git source's stored
677
+ * commit with the remote one *without downloading the archive*. One failing
678
+ * source is reported as `status: 'error'` in `results`; the route never 500s.
679
+ */
680
+ const sourceCheckRoute = async (request) => {
681
+ const body = await readBody(request)
682
+ let ids
683
+ if (body.ids !== undefined) {
684
+ if (!Array.isArray(body.ids)) return failure('resource-pool/bad-ids', 'ids 必须是字符串数组')
685
+ ids = body.ids.map((id) => textOf(id)).filter((id) => id.length > 0)
686
+ }
687
+ const current = await readState()
688
+ const targets = []
689
+ if (ids !== undefined) {
690
+ for (const id of ids) targets.push({ id, source: current.sources[id] })
691
+ } else {
692
+ for (const source of Object.values(current.sources)) {
693
+ if (source.kind === 'git') targets.push({ id: source.id, source })
694
+ }
695
+ }
696
+
697
+ const results = []
698
+ const checks = {}
699
+ const checkedAt = new Date().toISOString()
700
+ for (const { id, source } of targets) {
701
+ if (source === undefined) {
702
+ results.push({ id, label: '', status: 'error', current: '', remote: '', error: `来源 ${id} 不存在` })
703
+ continue
704
+ }
705
+ if (source.kind !== 'git') {
706
+ results.push({
707
+ id,
708
+ label: source.label,
709
+ status: 'error',
710
+ current: '',
711
+ remote: '',
712
+ error: '只有 Git 来源可以检查更新',
713
+ })
714
+ continue
715
+ }
716
+ try {
717
+ const token = await gitToken(source.tokenCredential)
718
+ const raw = await checkGitSource({ source, token })
719
+ const check = isObject(raw) ? raw : {}
720
+ const remote = textOf(check.remote)
721
+ const status = checkStatus(check.status, textOf(check.current), remote)
722
+ const result = {
723
+ id,
724
+ label: textOf(check.label) || source.label,
725
+ status,
726
+ current: textOf(check.current),
727
+ remote,
728
+ }
729
+ if (status === 'error') result.error = '无法确认远端提交'
730
+ results.push(result)
731
+ checks[id] = { at: checkedAt, status, remote, error: status === 'error' ? '无法确认远端提交' : '' }
732
+ } catch (error) {
733
+ const message = error instanceof Error ? error.message : String(error)
734
+ results.push({
735
+ id,
736
+ label: source.label,
737
+ status: 'error',
738
+ current: typeof source.sha === 'string' ? source.sha : '',
739
+ remote: '',
740
+ error: message,
741
+ })
742
+ checks[id] = { at: checkedAt, status: 'error', remote: '', error: message }
743
+ }
744
+ }
745
+
746
+ if (Object.keys(checks).length === 0) {
747
+ // Nothing to record (no Git sources): the document is unchanged, so the
748
+ // pool does not need re-applying.
749
+ return json({ ok: true, state: current, results })
750
+ }
751
+ try {
752
+ const state = await store.update((doc) => {
753
+ let next = doc
754
+ for (const [id, lastCheck] of Object.entries(checks)) {
755
+ const source = next.sources[id]
756
+ if (source === undefined) continue
757
+ // Only the check outcome is stored: `sha` keeps naming the commit that
758
+ // is actually installed, so update detection stays correct.
759
+ next = upsertSource(next, { ...source, lastCheck })
760
+ }
761
+ return next
762
+ })
763
+ return committed(state, { results })
764
+ } catch (error) {
765
+ return failure('resource-pool/check-failed', error instanceof Error ? error.message : String(error), 500)
766
+ }
767
+ }
768
+
769
+ /** POST /dsh-skill-pool/source/update — re-fetch one Git source. */
770
+ const sourceUpdateRoute = async (request) => {
771
+ const body = await readBody(request)
772
+ const id = textOf(body.id)
773
+ if (id.length === 0) return failure('resource-pool/bad-id', '缺少 id')
774
+ const current = await readState()
775
+ const source = current.sources[id]
776
+ if (source === undefined) return failure('resource-pool/unknown-source', `来源 ${id} 不存在`, 404)
777
+ if (source.kind !== 'git') return failure('resource-pool/bad-kind', '只有 Git 来源可以更新', 400)
778
+ try {
779
+ const token = await gitToken(source.tokenCredential)
780
+ // `restore` clears the exclusion list and forces a reinstall; `force` alone
781
+ // reinstall the current commit without clearing anything.
782
+ const restore = body.restore === true
783
+ const force = body.force === true || restore
784
+ const updated = await updateGitSource({
785
+ source: restore ? { ...source, excluded: [] } : source,
786
+ token,
787
+ root: skillsRoot(),
788
+ exclude: restore ? [] : source.excluded,
789
+ force,
790
+ })
791
+ const result = installResult(updated)
792
+ const changed = updated?.changed === true
793
+ const removed = Array.isArray(updated?.removed)
794
+ ? updated.removed.filter((name) => typeof name === 'string' && name.length > 0)
795
+ : []
796
+ const returned = isObject(updated?.source) ? updated.source : {}
797
+ const nextSource = {
798
+ ...source,
799
+ ...returned,
800
+ id,
801
+ kind: 'git',
802
+ skills: Array.isArray(returned.skills) ? returned.skills : source.skills,
803
+ excluded: restore
804
+ ? []
805
+ : Array.isArray(returned.excluded)
806
+ ? returned.excluded
807
+ : Array.isArray(source.excluded)
808
+ ? source.excluded
809
+ : [],
810
+ lastCheck: {
811
+ at: new Date().toISOString(),
812
+ status: 'up-to-date',
813
+ remote: typeof returned.sha === 'string' ? returned.sha : '',
814
+ error: '',
815
+ },
816
+ }
817
+ const state = await store.update((doc) => {
818
+ let next = upsertSource(doc, nextSource)
819
+ next = installItems(next, result.installed, {
820
+ scope: undefined,
821
+ sourceId: id,
822
+ digests: result.digests,
823
+ installedAt: new Date().toISOString(),
824
+ })
825
+ // Skills that disappeared upstream are gone from disk already.
826
+ const shared = sharedNames(next, id)
827
+ for (const name of removed) {
828
+ if (shared.has(name)) continue
829
+ next = removeItem(next, 'skill', name)
830
+ }
831
+ // An update that leaves the source with nothing installed turns it into
832
+ // a dead tree row: drop it (and its group) like a delete would.
833
+ const after = next.sources[id]
834
+ if (after !== undefined && (!Array.isArray(after.skills) || after.skills.length === 0)) {
835
+ const referenced = Object.values(next.skills).some((item) => item.sourceId === id)
836
+ if (!referenced) next = removeSource(next, id)
837
+ }
838
+ return next
839
+ })
840
+ return committed(state, {
841
+ source: state.sources[id],
842
+ installed: result.installed,
843
+ failures: result.failures,
844
+ changed,
845
+ })
846
+ } catch (error) {
847
+ return failure('resource-pool/update-failed', error instanceof Error ? error.message : String(error), 400)
848
+ }
849
+ }
850
+
851
+ /** POST /dsh-skill-pool/source/delete — remove a source and its skills. */
852
+ const sourceDeleteRoute = async (request) => {
853
+ const body = await readBody(request)
854
+ const id = textOf(body.id)
855
+ if (id.length === 0) return failure('resource-pool/bad-id', '缺少 id')
856
+ const current = await readState()
857
+ const source = current.sources[id]
858
+ if (source === undefined) return failure('resource-pool/unknown-source', `来源 ${id} 不存在`, 404)
859
+ try {
860
+ // A skill may be claimed by more than one source (same name from a ZIP and
861
+ // a repo); only delete the ones no other source still lists.
862
+ const shared = sharedNames(current, id)
863
+ const skipSkills = (Array.isArray(source.skills) ? source.skills : []).filter((name) => shared.has(name))
864
+ const result = await removeSourceSkills({ source, root: skillsRoot(), skipSkills })
865
+ const removed = Array.isArray(result?.removed) ? result.removed : []
866
+ const skipped = Array.isArray(result?.skipped) ? result.skipped : skipSkills
867
+ 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: '' })
875
+ }
876
+ return next
877
+ })
878
+ return committed(state, { removed, skipped })
879
+ } catch (error) {
880
+ return failure('resource-pool/delete-failed', error instanceof Error ? error.message : String(error), 400)
881
+ }
882
+ }
883
+
884
+ 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],
900
+ ]
901
+
902
+ // ------------------------------------------------------------- transport
903
+
904
+ const readNodeBody = (request) => new Promise((resolve, reject) => {
905
+ const chunks = []
906
+ let size = 0
907
+ request.on('data', (chunk) => {
908
+ size += chunk.length
909
+ if (size > MAX_BODY_BYTES) {
910
+ reject(new Error('request body too large'))
911
+ request.destroy()
912
+ return
913
+ }
914
+ chunks.push(chunk)
915
+ })
916
+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
917
+ request.on('error', reject)
918
+ })
919
+
920
+ const writeNodeResponse = async (response, res) => {
921
+ const headers = {}
922
+ response.headers.forEach((value, key) => {
923
+ headers[key] = value
924
+ })
925
+ res.writeHead(response.status, headers)
926
+ res.end(Buffer.from(await response.arrayBuffer()))
927
+ }
928
+
929
+ const refuse = (res, status) => {
930
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
931
+ res.end(status === 401 ? 'unauthorized' : 'forbidden')
932
+ }
933
+
934
+ const handleNodeRequest = async (connection, req, res) => {
935
+ const admission = typeof connection?.admit === 'function' ? connection.admit(req) : undefined
936
+ if (admission === undefined || admission === null) {
937
+ refuse(res, 401)
938
+ return
939
+ }
940
+ if ('rejection' in admission) {
941
+ refuse(res, admission.rejection === 403 ? 403 : 401)
942
+ return
943
+ }
944
+ const url = new URL(req.url ?? '/', 'http://dsh.invalid')
945
+ const method = req.method ?? 'GET'
946
+ const route = routes.find(([suffix, methods]) => `${ROUTE_PREFIX}${suffix}` === url.pathname && methods.includes(method))
947
+ if (route === undefined) {
948
+ await writeNodeResponse(json({ ok: false, error: { code: 'resource-pool/not-found', message: 'unknown resource-pool route' } }, 404), res)
949
+ return
950
+ }
951
+ const headers = {}
952
+ for (const [key, value] of Object.entries(req.headers)) {
953
+ if (value === undefined) continue
954
+ headers[key] = Array.isArray(value) ? value.join(', ') : value
955
+ }
956
+ let body
957
+ try {
958
+ body = method === 'GET' || method === 'HEAD' ? undefined : await readNodeBody(req)
959
+ } catch (error) {
960
+ await writeNodeResponse(failure('resource-pool/too-large', error instanceof Error ? error.message : String(error), 413), res)
961
+ return
962
+ }
963
+ let request
964
+ try {
965
+ request = new Request(url.toString(), {
966
+ method,
967
+ headers,
968
+ ...(body === undefined || body.length === 0 ? {} : { body }),
969
+ })
970
+ } catch (error) {
971
+ await writeNodeResponse(failure('resource-pool/bad-request', error instanceof Error ? error.message : String(error), 400), res)
972
+ return
973
+ }
974
+ await writeNodeResponse(await route[2](request), res)
975
+ }
976
+
977
+ ctx.inject(['webServer', 'connection'], (webCtx) => {
978
+ const webServer = webCtx.get('webServer')
979
+ const connection = webCtx.get('connection')
980
+ if (webServer === undefined || typeof webServer.register !== 'function' || typeof connection?.admit !== 'function') {
981
+ registerFetchRoutes(webCtx, connection)
982
+ return
983
+ }
984
+ // Owned by the plugin context: a webServer/connection restart re-runs this
985
+ // inject callback and would dispose a scope-owned route.
986
+ ctx.effect(
987
+ () =>
988
+ webServer.register({
989
+ kind: 'prefix',
990
+ path: ROUTE_PREFIX,
991
+ handler: (req, res) => {
992
+ handleNodeRequest(connection, req, res).catch((error) => {
993
+ logger?.warn?.(`[resource-pool] request failed: ${error instanceof Error ? error.message : String(error)}`)
994
+ if (res.headersSent) {
995
+ try {
996
+ res.destroy()
997
+ } catch {
998
+ /* already gone */
999
+ }
1000
+ return
1001
+ }
1002
+ try {
1003
+ res.writeHead(500, { 'content-type': 'application/json' })
1004
+ res.end(JSON.stringify({ ok: false, error: { code: 'resource-pool/internal', message: 'request failed' } }))
1005
+ } catch {
1006
+ /* response already closed */
1007
+ }
1008
+ })
1009
+ },
1010
+ }),
1011
+ 'resource-pool.http',
1012
+ )
1013
+ debug(`registered ${routes.length} resource pool routes under ${ROUTE_PREFIX} (webServer prefix)`)
1014
+ })
1015
+
1016
+ /** Fallback for compositions without a webServer: exact-Fetch routes. */
1017
+ function registerFetchRoutes(targetCtx, connection) {
1018
+ const register = connection?.fetch?.register
1019
+ if (typeof register !== 'function') {
1020
+ debug('neither webServer nor connection.fetch is available; resource pool API disabled')
1021
+ return
1022
+ }
1023
+ for (const [suffix, methods, handler] of routes) {
1024
+ targetCtx.effect(
1025
+ () =>
1026
+ register({
1027
+ path: `${ROUTE_PREFIX}${suffix}`,
1028
+ methods,
1029
+ requestBody: 'buffered',
1030
+ fetch: handler,
1031
+ }),
1032
+ `resource-pool.route.${suffix.length > 0 ? suffix.slice(1).replaceAll('/', '.') : 'overview'}`,
1033
+ )
1034
+ }
1035
+ debug(`registered ${routes.length} resource pool routes under ${ROUTE_PREFIX} (exact fetch)`)
1036
+ }
1037
+ }