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.
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Live inventory for the settings page (§6.1).
3
+ *
4
+ * v3 supplies library skills through a provider registered on *each Agent's own
5
+ * context*, so the global registry view deliberately cannot see them: the pool
6
+ * document is the source of truth for pool members and the on-disk library is
7
+ * the source of truth for their descriptions/paths/digests. The registry is
8
+ * only used for the read-only "system skills" section.
9
+ *
10
+ * Everything here is defensive: a missing service, a provider failure or an
11
+ * unreadable directory degrades that one field instead of failing the whole
12
+ * read.
13
+ *
14
+ * @module dsh-skill-pool/inventory
15
+ */
16
+
17
+ import { join } from 'node:path'
18
+
19
+ import { listLibrarySkills } from './library.js'
20
+ import { MCP_TOOL_PREFIX, effectiveEnabled, effectiveScope, groupKeyOfSource, mcpServerOf } from './rules.js'
21
+ import { mcpEntryId } from './uploads.js'
22
+
23
+ /** Provider name the library provider registers under (must match §3). */
24
+ const LIBRARY_PROVIDER = 'resource-pool'
25
+
26
+ /** Maximum rows kept in one inventory section. */
27
+ const MAX_ROWS = 500
28
+ /** Maximum description length returned per skill. */
29
+ const DESCRIPTION_LIMIT = 300
30
+
31
+ /** Read one optional service without throwing. */
32
+ function optional(ctx, name) {
33
+ try {
34
+ return ctx.get(name)
35
+ } catch {
36
+ return undefined
37
+ }
38
+ }
39
+
40
+ /** Clamp one description for the picker. */
41
+ function clipDescription(value) {
42
+ if (typeof value !== 'string') return ''
43
+ const text = value.replace(/\s+/g, ' ').trim()
44
+ return text.length > DESCRIPTION_LIMIT ? `${text.slice(0, DESCRIPTION_LIMIT - 1)}…` : text
45
+ }
46
+
47
+ /** Whether a skill name looks like a usable catalog entry. */
48
+ function isPlainString(value) {
49
+ return typeof value === 'string' && value.trim().length > 0
50
+ }
51
+
52
+ /**
53
+ * Collect the skill catalog for one scope.
54
+ *
55
+ * @param {object} ctx - plugin context.
56
+ * @param {{ cwd?: string, agent?: object }} [options] - lookup identity.
57
+ * @returns {Promise<Array<object>>} skill summaries.
58
+ */
59
+ async function skillsFor(ctx, { cwd, agent } = {}) {
60
+ const skills = optional(ctx, 'skills')
61
+ if (skills === undefined || typeof skills.snapshot !== 'function') return []
62
+ const options = {}
63
+ if (typeof cwd === 'string' && cwd.length > 0) options.cwd = cwd
64
+ if (agent !== undefined) options.scope = agent
65
+ let snapshot
66
+ try {
67
+ snapshot = await skills.snapshot(options)
68
+ } catch {
69
+ return []
70
+ }
71
+ const list = Array.isArray(snapshot?.skills) ? snapshot.skills : []
72
+ const out = []
73
+ for (const skill of list) {
74
+ if (skill === null || typeof skill !== 'object') continue
75
+ if (!isPlainString(skill.name)) continue
76
+ out.push({
77
+ name: skill.name.trim(),
78
+ description: clipDescription(skill.description),
79
+ path: typeof skill.path === 'string' ? skill.path : '',
80
+ source: typeof skill.source === 'string' ? skill.source : '',
81
+ provider: typeof skill.provider === 'string' ? skill.provider : '',
82
+ modelInvocable: skill.invocation?.modelInvocable !== false,
83
+ userInvocable: skill.invocation?.userInvocable !== false,
84
+ })
85
+ }
86
+ return out
87
+ }
88
+
89
+ /**
90
+ * Union every live Agent's skill catalog with the global one.
91
+ *
92
+ * @param {object} ctx - plugin context.
93
+ * @param {{ cwd?: string, agent?: object }} [options] - preferred identity.
94
+ * @returns {Promise<Array<object>>} de-duplicated skill summaries.
95
+ */
96
+ export async function collectSkills(ctx, { cwd, agent } = {}) {
97
+ const byName = new Map()
98
+ const add = (entries) => {
99
+ for (const entry of entries) if (!byName.has(entry.name)) byName.set(entry.name, entry)
100
+ }
101
+ add(await skillsFor(ctx, { cwd }))
102
+ if (agent !== undefined) add(await skillsFor(ctx, { cwd, agent }))
103
+ const agents = optional(ctx, 'agents')
104
+ const live = typeof agents?.list === 'function' ? agents.list() : []
105
+ for (const each of live.slice(0, 8)) {
106
+ try {
107
+ add(await skillsFor(ctx, { cwd: each?.session?.header?.cwd ?? cwd, agent: each }))
108
+ } catch {
109
+ /* one broken agent must not hide the rest */
110
+ }
111
+ }
112
+ return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name)).slice(0, MAX_ROWS)
113
+ }
114
+
115
+ /**
116
+ * Build the `skills` section: one row per pool member (§6.1), enriched from the
117
+ * on-disk library. A member whose directory disappeared is returned with
118
+ * `missing: true` instead of being dropped, so the panel can explain and clean
119
+ * up a broken entry.
120
+ *
121
+ * @param {object} state - normalized document.
122
+ * @param {Array<object>} librarySkills - `listLibrarySkills()` output.
123
+ * @param {string} libraryRoot - library skills root.
124
+ * @returns {Array<object>} skill rows.
125
+ */
126
+ function skillRows(state, librarySkills, libraryRoot) {
127
+ const byName = new Map(librarySkills.map((entry) => [entry.name, entry]))
128
+ const sources = state.sources !== null && typeof state.sources === 'object' ? state.sources : {}
129
+ const members = state.skills !== null && typeof state.skills === 'object' ? state.skills : {}
130
+ const rows = []
131
+ for (const [name, member] of Object.entries(members)) {
132
+ const installed = byName.get(name)
133
+ const fallbackPath = typeof libraryRoot === 'string' && libraryRoot.length > 0
134
+ ? join(libraryRoot, name, 'SKILL.md')
135
+ : ''
136
+ const source = member.sourceId === undefined ? undefined : sources[member.sourceId]
137
+ const groupKey = groupKeyOfSource(source)
138
+ const effective = effectiveScope(state, member)
139
+ rows.push({
140
+ name,
141
+ description: typeof installed?.description === 'string' ? installed.description : '',
142
+ path: typeof installed?.path === 'string' ? installed.path : fallbackPath,
143
+ sourceId: typeof member.sourceId === 'string' ? member.sourceId : '',
144
+ sourceLabel: typeof source?.label === 'string' ? source.label : '',
145
+ // The panel groups rows by this key and edits the scope once per group.
146
+ groupKey,
147
+ groupName: groupKey.startsWith('repo:') ? groupKey.slice(5) : typeof source?.label === 'string' ? source.label : '',
148
+ enabled: member.enabled !== false,
149
+ effectiveEnabled: effectiveEnabled(state, member),
150
+ modes: Array.isArray(member.modes) ? [...member.modes] : [],
151
+ workspaces: Array.isArray(member.workspaces) ? [...member.workspaces] : [],
152
+ modesFrom: member.modesFrom === 'self' ? 'self' : 'group',
153
+ workspacesFrom: member.workspacesFrom === 'self' ? 'self' : 'group',
154
+ effectiveModes: Array.isArray(effective.modes) ? [...effective.modes] : [],
155
+ effectiveWorkspaces: Array.isArray(effective.workspaces) ? [...effective.workspaces] : [],
156
+ digest: typeof installed?.digest === 'string'
157
+ ? installed.digest
158
+ : typeof member.digest === 'string' ? member.digest : '',
159
+ installedAt: typeof member.installedAt === 'string' ? member.installedAt : '',
160
+ modelInvocable: installed === undefined ? true : installed.modelInvocable !== false,
161
+ missing: installed === undefined,
162
+ })
163
+ if (rows.length >= MAX_ROWS) break
164
+ }
165
+ return rows.sort((left, right) => left.name.localeCompare(right.name))
166
+ }
167
+
168
+ /**
169
+ * Build the read-only `nativeSkills` section: skills the global registry knows
170
+ * that this plugin does not supply (§6.1).
171
+ *
172
+ * @param {Array<object>} catalog - live skill summaries.
173
+ * @param {object} state - normalized document.
174
+ * @returns {Array<object>} native skill rows.
175
+ */
176
+ function nativeSkillRows(catalog, state) {
177
+ const members = state.skills !== null && typeof state.skills === 'object' ? state.skills : {}
178
+ const rows = []
179
+ for (const skill of catalog) {
180
+ if (skill.provider === LIBRARY_PROVIDER) continue
181
+ if (Object.hasOwn(members, skill.name)) continue
182
+ rows.push({
183
+ name: skill.name,
184
+ description: skill.description,
185
+ source: skill.source,
186
+ provider: skill.provider,
187
+ })
188
+ if (rows.length >= MAX_ROWS) break
189
+ }
190
+ return rows.sort((left, right) => left.name.localeCompare(right.name))
191
+ }
192
+
193
+ /**
194
+ * Collect mounted MCP servers and the public tool names they registered.
195
+ *
196
+ * A server is discovered from two independent observations so a server keeps
197
+ * its entry even when one side is temporarily unavailable:
198
+ * - its managed `@deepseek-ai/dsh-mcp-client` Loader row (`rp-<serverName>`),
199
+ * which carries `config.serverName` and the transport;
200
+ * - the live global tool names under `mcp__<serverName>__`.
201
+ *
202
+ * @param {object} ctx - plugin context.
203
+ * @returns {Array<object>} servers with their tools.
204
+ */
205
+ export function collectMcpServers(ctx) {
206
+ /** @type {Map<string, {serverName: string, transport: string, tools: string[], source: string}>} */
207
+ const byServer = new Map()
208
+ const ensure = (serverName) => {
209
+ let entry = byServer.get(serverName)
210
+ if (entry === undefined) {
211
+ entry = { serverName, transport: '', tools: [], source: 'tool', entryId: '', managed: false }
212
+ byServer.set(serverName, entry)
213
+ }
214
+ return entry
215
+ }
216
+
217
+ const tools = optional(ctx, 'tools')
218
+ if (tools !== undefined && typeof tools.schemas === 'function') {
219
+ try {
220
+ for (const schema of tools.schemas()) {
221
+ const name = schema?.name
222
+ if (typeof name !== 'string' || !name.startsWith(MCP_TOOL_PREFIX)) continue
223
+ const server = mcpServerOf(name)
224
+ if (server.length === 0) continue
225
+ ensure(server).tools.push(name)
226
+ }
227
+ } catch {
228
+ /* tool runtime unavailable; loader rows may still describe servers */
229
+ }
230
+ }
231
+
232
+ const loader = optional(ctx, 'loader')
233
+ if (loader !== undefined && typeof loader.entries === 'function') {
234
+ try {
235
+ for (const entry of loader.entries()) {
236
+ const name = entry?.options?.name
237
+ if (name !== '@deepseek-ai/dsh-mcp-client') continue
238
+ if (entry.disabled === true) continue
239
+ const config = entry.options?.config ?? {}
240
+ const serverName = typeof config.serverName === 'string' && config.serverName.length > 0
241
+ ? config.serverName
242
+ : String(entry.options?.id ?? '').replace(/^[^-]+-/, '')
243
+ if (serverName.length === 0) continue
244
+ const record = ensure(serverName)
245
+ const id = String(entry.options?.id ?? '')
246
+ if (id.length > 0) record.entryId = id
247
+ // Rows created by this plugin use the "rp-" prefix; the connector uses "mcp-".
248
+ if (id.startsWith('rp-')) record.managed = true
249
+ if (record.transport.length === 0) record.transport = typeof config.transport === 'string' ? config.transport : ''
250
+ record.source = record.source === 'tool' ? 'tool+loader' : 'loader'
251
+ }
252
+ } catch {
253
+ /* loader unavailable; keep tool-derived servers */
254
+ }
255
+ }
256
+
257
+ return [...byServer.values()]
258
+ .map((entry) => ({
259
+ serverName: entry.serverName,
260
+ transport: entry.transport,
261
+ tools: [...new Set(entry.tools)].sort(),
262
+ toolCount: new Set(entry.tools).size,
263
+ entryId: entry.entryId,
264
+ managed: entry.managed,
265
+ source: entry.source,
266
+ }))
267
+ .sort((left, right) => left.serverName.localeCompare(right.serverName))
268
+ }
269
+
270
+ /**
271
+ * Build the `mcp` section: one row per pool member (§6.1), enriched with the
272
+ * tools and loader row currently observed.
273
+ *
274
+ * @param {object} ctx - plugin context.
275
+ * @param {object} state - normalized document.
276
+ * @returns {Array<object>} MCP rows.
277
+ */
278
+ function mcpRows(ctx, state) {
279
+ let observed = []
280
+ try {
281
+ observed = collectMcpServers(ctx)
282
+ } catch {
283
+ observed = []
284
+ }
285
+ const byName = new Map(observed.map((entry) => [entry.serverName, entry]))
286
+ const members = state.mcp !== null && typeof state.mcp === 'object' ? state.mcp : {}
287
+ const rows = []
288
+ for (const [server, member] of Object.entries(members)) {
289
+ const live = byName.get(server)
290
+ rows.push({
291
+ server,
292
+ tools: Array.isArray(live?.tools) ? [...live.tools] : [],
293
+ managed: live?.managed === true,
294
+ entryId: live?.entryId !== undefined && live.entryId.length > 0 ? live.entryId : mcpEntryId(server),
295
+ enabled: member.enabled !== false,
296
+ modes: Array.isArray(member.modes) ? [...member.modes] : [],
297
+ workspaces: Array.isArray(member.workspaces) ? [...member.workspaces] : [],
298
+ installedAt: typeof member.installedAt === 'string' ? member.installedAt : '',
299
+ })
300
+ if (rows.length >= MAX_ROWS) break
301
+ }
302
+ return rows.sort((left, right) => left.server.localeCompare(right.server))
303
+ }
304
+
305
+ /**
306
+ * Collect Agent modes known without awaiting the preset registry: the modes live
307
+ * sessions already use and an explicitly requested mode. The synthetic id the
308
+ * host falls back to when a session carries no preset is *not* offered here: it
309
+ * names no real preset, so a member scoped to it could never be hit.
310
+ * @param {object} ctx - plugin context.
311
+ * @param {{ currentMode?: string }} [options] - mode to include even when unlisted.
312
+ * @returns {Array<{id: string, name: string, order?: number}>} modes.
313
+ */
314
+ export function collectModes(ctx, { currentMode } = {}) {
315
+ /** @type {Map<string, {id: string, name: string, order?: number}>} */
316
+ const byId = new Map()
317
+ const add = (id) => {
318
+ if (typeof id !== 'string' || id.trim().length === 0) return
319
+ const key = id.trim()
320
+ if (!byId.has(key)) byId.set(key, { id: key, name: key })
321
+ }
322
+ const agents = optional(ctx, 'agents')
323
+ const live = typeof agents?.list === 'function' ? agents.list() : []
324
+ for (const agent of live) add(agent?.session?.header?.agentPreset)
325
+ if (typeof currentMode === 'string') add(currentMode)
326
+ return [...byId.values()]
327
+ }
328
+
329
+ /**
330
+ * Collect Agent modes, awaiting the preset registry for display names and order.
331
+ * @param {object} ctx - plugin context.
332
+ * @param {{ currentMode?: string }} [options] - mode to include even when unlisted.
333
+ * @returns {Promise<Array<{id: string, name: string, order?: number}>>} modes.
334
+ */
335
+ export async function collectModesAsync(ctx, options = {}) {
336
+ const byId = new Map(collectModes(ctx, options).map((mode) => [mode.id, mode]))
337
+ const registry = optional(ctx, 'agentPresets')
338
+ if (registry !== undefined && typeof registry.list === 'function') {
339
+ try {
340
+ const presets = await registry.list()
341
+ if (Array.isArray(presets)) {
342
+ for (const preset of presets) {
343
+ const id = typeof preset?.id === 'string' ? preset.id.trim() : ''
344
+ if (id.length === 0) continue
345
+ byId.set(id, {
346
+ id,
347
+ name: typeof preset.name === 'string' && preset.name.length > 0 ? preset.name : id,
348
+ ...(typeof preset.order === 'number' ? { order: preset.order } : {}),
349
+ })
350
+ }
351
+ }
352
+ } catch {
353
+ /* registry failure leaves the live/default modes */
354
+ }
355
+ }
356
+ return [...byId.values()].sort((left, right) => (left.order ?? 999) - (right.order ?? 999) || left.name.localeCompare(right.name))
357
+ }
358
+
359
+ /**
360
+ * Collect workspaces plus any working directory a live session uses.
361
+ * @param {object} ctx - plugin context.
362
+ * @returns {Array<{id: string, name: string, path: string}>} workspaces.
363
+ */
364
+ export function collectWorkspaces(ctx) {
365
+ const registry = optional(ctx, 'workspaceRegistry')
366
+ /** @type {Map<string, {id: string, name: string, path: string}>} */
367
+ const byPath = new Map()
368
+ let list = []
369
+ try {
370
+ list = typeof registry?.list === 'function' ? registry.list() : []
371
+ } catch {
372
+ list = []
373
+ }
374
+ for (const workspace of list) {
375
+ const path = typeof workspace?.path === 'string' ? workspace.path : ''
376
+ if (path.length === 0) continue
377
+ const name = typeof workspace.title === 'string' && workspace.title.length > 0 ? workspace.title : path
378
+ byPath.set(path, { id: typeof workspace.id === 'string' ? workspace.id : path, name, path })
379
+ }
380
+ const agents = optional(ctx, 'agents')
381
+ const live = typeof agents?.list === 'function' ? agents.list() : []
382
+ for (const agent of live) {
383
+ const path = agent?.session?.header?.cwd
384
+ if (typeof path !== 'string' || path.length === 0) continue
385
+ if (byPath.has(path)) continue
386
+ byPath.set(path, { id: path, name: path.split('/').filter(Boolean).pop() ?? path, path })
387
+ }
388
+ return [...byPath.values()].sort((left, right) => left.name.localeCompare(right.name))
389
+ }
390
+
391
+ /**
392
+ * Build the complete inventory payload for the panel (§6.1).
393
+ *
394
+ * @param {object} ctx - plugin context.
395
+ * @param {{
396
+ * state?: object,
397
+ * libraryRoot?: string,
398
+ * cwd?: string,
399
+ * agent?: object,
400
+ * currentMode?: string,
401
+ * }} [options] - document, library root, and preferred identity.
402
+ * @returns {Promise<{skills: object[], nativeSkills: object[], mcp: object[],
403
+ * modes: string[], workspaces: string[]}>} inventory.
404
+ */
405
+ export async function buildInventory(ctx, options = {}) {
406
+ const state = options.state !== null && typeof options.state === 'object' ? options.state : defaultInventoryState()
407
+ const libraryRoot = typeof options.libraryRoot === 'string' ? options.libraryRoot : ''
408
+ const [librarySkills, catalog, collectedModes] = await Promise.all([
409
+ listLibrarySkills(libraryRoot.length > 0 ? { root: libraryRoot } : {}).catch(() => []),
410
+ collectSkills(ctx, options).catch(() => []),
411
+ collectModesAsync(ctx, { currentMode: options.currentMode }).catch(() => []),
412
+ ])
413
+ const skills = skillRows(state, librarySkills, libraryRoot)
414
+ const nativeSkills = nativeSkillRows(catalog, state)
415
+ const mcp = mcpRows(ctx, state)
416
+
417
+ // §6.1 returns plain ids/paths: the panel renders them in multi-selects and
418
+ // sends the chosen values straight back to `/item`.
419
+ const modeIds = []
420
+ for (const mode of collectedModes) {
421
+ if (typeof mode?.id !== 'string' || mode.id.length === 0) continue
422
+ if (!modeIds.includes(mode.id)) modeIds.push(mode.id)
423
+ }
424
+ const modes = modeIds
425
+ const registry = optional(ctx, 'agentPresets')
426
+ let defaultMode = ''
427
+ try {
428
+ const id = registry?.defaultId
429
+ if (typeof id === 'string') defaultMode = id.trim()
430
+ } catch {
431
+ /* a broken registry leaves the caller to pick the first mode */
432
+ }
433
+ let workspaces = []
434
+ try {
435
+ workspaces = collectWorkspaces(ctx)
436
+ .map((workspace) => workspace.path)
437
+ .filter((path) => typeof path === 'string' && path.length > 0)
438
+ } catch {
439
+ workspaces = []
440
+ }
441
+ return { skills, nativeSkills, mcp, modes, workspaces, defaultMode: defaultMode.length > 0 ? defaultMode : (modes[0] ?? '') }
442
+ }
443
+
444
+ /** Minimal document used when the caller has no state yet. */
445
+ function defaultInventoryState() {
446
+ return { skills: {}, mcp: {}, sources: {} }
447
+ }