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/CONTRACTS-v3.md +288 -0
- package/LICENSE +21 -0
- package/README.md +198 -2
- package/client.js +4434 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +21 -0
- package/index.js +174 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +62 -4
- package/src/activation.js +303 -0
- package/src/inventory.js +447 -0
- package/src/library.js +1168 -0
- package/src/mount.js +73 -0
- package/src/provider.js +309 -0
- package/src/remount.js +78 -0
- package/src/rules.js +243 -0
- package/src/skill-content.js +78 -0
- package/src/store.js +765 -0
- package/src/uploads.js +222 -0
- package/src/web-api.js +1037 -0
package/src/store.js
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable resource-pool state (v4): one global pool, which *is* the user's
|
|
3
|
+
* resource library.
|
|
4
|
+
*
|
|
5
|
+
* The document keeps five maps:
|
|
6
|
+
* - `skills` / `mcp`: resource name -> membership (`enabled`, `modes`,
|
|
7
|
+
* `workspaces`) plus provenance (`sourceId`, `digest`, `installedAt`). A
|
|
8
|
+
* resource is in the pool exactly when it has an entry: an import writes the
|
|
9
|
+
* entry in the same transaction, there is no separate "add to pool" step.
|
|
10
|
+
* An `mcp` member also keeps its `definition` (URL/command/headers), which is
|
|
11
|
+
* what a Host restart re-mounts the `mcp-client` row from — see remount.js.
|
|
12
|
+
* A skill additionally carries `modesFrom` / `workspacesFrom`: `group` means
|
|
13
|
+
* "use the group of its source", `self` means "use my own list".
|
|
14
|
+
* - `groups`: one scope per *repository* (`repo:<project>`) or, for imports
|
|
15
|
+
* without a repository, per import (`import:<sourceId>`). Members inherit it
|
|
16
|
+
* unless they opt out, so one edit scopes a whole repository.
|
|
17
|
+
* - `sources`: where installed skills came from (git repository, ZIP archive or
|
|
18
|
+
* an uploaded file set), used to check for updates, update, or remove what a
|
|
19
|
+
* source installed.
|
|
20
|
+
* - `settings`: the switches the panel exposes (§2.1).
|
|
21
|
+
*
|
|
22
|
+
* A v3 document is migrated (see `migrateV3`), not dropped: groups are derived
|
|
23
|
+
* from what the members already do, so gating is identical before and after.
|
|
24
|
+
* Any other version is reset to an empty document: v1/v2 used a different
|
|
25
|
+
* membership model (a separate library and pool), and guessing a mapping would
|
|
26
|
+
* silently change what is gated.
|
|
27
|
+
*
|
|
28
|
+
* Writes are atomic and serialized; the module has no Cordis imports so
|
|
29
|
+
* `node --test` can load it directly.
|
|
30
|
+
*
|
|
31
|
+
* @module dsh-skill-pool/store
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
35
|
+
import { dirname, join } from 'node:path'
|
|
36
|
+
import { homedir } from 'node:os'
|
|
37
|
+
import { groupKeyOfSource } from './rules.js'
|
|
38
|
+
|
|
39
|
+
/** Current document version. */
|
|
40
|
+
export const STATE_VERSION = 4
|
|
41
|
+
|
|
42
|
+
/** The one older version this module upgrades instead of discarding. */
|
|
43
|
+
export const LEGACY_VERSION = 3
|
|
44
|
+
|
|
45
|
+
/** Group records keyed by `repo:<project>` or `import:<sourceId>`. */
|
|
46
|
+
export const GROUP_KINDS = ['repo', 'import']
|
|
47
|
+
|
|
48
|
+
/** Default file name under the DSH home. */
|
|
49
|
+
export const STATE_FILE_NAME = 'resource-pool/state.json'
|
|
50
|
+
|
|
51
|
+
/** Namespaces that hold pool members. */
|
|
52
|
+
export const KINDS = ['skill', 'mcp']
|
|
53
|
+
|
|
54
|
+
/** Provenance kinds a source record may have. */
|
|
55
|
+
export const SOURCE_KINDS = ['git', 'zip', 'files']
|
|
56
|
+
|
|
57
|
+
/** Git providers supported by the library (self-hosted GitLab is out of scope). */
|
|
58
|
+
export const GIT_PROVIDERS = ['github', 'gitlab']
|
|
59
|
+
|
|
60
|
+
/** Outcomes of one "check for updates" run, stored on the source (§2.1). */
|
|
61
|
+
export const CHECK_STATUSES = ['up-to-date', 'update-available', 'error']
|
|
62
|
+
|
|
63
|
+
/** Switches the panel may patch. */
|
|
64
|
+
export const SETTING_KEYS = ['enabled', 'mcpGate', 'injectSummary', 'gateDefaultSkills']
|
|
65
|
+
|
|
66
|
+
/** Conservative identifier grammar for resource names and mode ids. */
|
|
67
|
+
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/
|
|
68
|
+
|
|
69
|
+
/** Resolve the DSH home directory (env override, else `~/.dsh`). */
|
|
70
|
+
export function dshHome() {
|
|
71
|
+
const fromEnv = process.env.DSH_HOME
|
|
72
|
+
if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
|
|
73
|
+
return join(homedir(), '.dsh')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Absolute path of the state document. */
|
|
77
|
+
export function statePath() {
|
|
78
|
+
return join(dshHome(), STATE_FILE_NAME)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Generate a short, collision-resistant id. */
|
|
82
|
+
export function newId(prefix) {
|
|
83
|
+
return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Whether a value is a plain object (not an array, not null). */
|
|
87
|
+
function isObject(value) {
|
|
88
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Trim a candidate name, returning '' when unusable. */
|
|
92
|
+
function cleanName(value) {
|
|
93
|
+
if (typeof value !== 'string') return ''
|
|
94
|
+
const name = value.trim()
|
|
95
|
+
return NAME_RE.test(name) ? name : ''
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Normalize a resource/mode name.
|
|
100
|
+
* @param {unknown} value - candidate name.
|
|
101
|
+
* @returns {string} the name when it satisfies the identifier grammar, else ''.
|
|
102
|
+
*/
|
|
103
|
+
export function normalizeItemName(value) {
|
|
104
|
+
return cleanName(value)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Trim an optional string, returning '' when absent. */
|
|
108
|
+
function optionalString(value, limit = 4096) {
|
|
109
|
+
if (typeof value !== 'string') return ''
|
|
110
|
+
return value.trim().slice(0, limit)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Timestamp helper: keep a stored value, else use now. */
|
|
114
|
+
function timestamp(value) {
|
|
115
|
+
const text = optionalString(value, 64)
|
|
116
|
+
return text.length > 0 ? text : new Date().toISOString()
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Deduplicate strings, preserving order. */
|
|
120
|
+
function unique(values) {
|
|
121
|
+
const seen = new Set()
|
|
122
|
+
const out = []
|
|
123
|
+
for (const value of values) {
|
|
124
|
+
if (seen.has(value)) continue
|
|
125
|
+
seen.add(value)
|
|
126
|
+
out.push(value)
|
|
127
|
+
}
|
|
128
|
+
return out
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Normalize one filesystem path for workspace matching (lexical, no realpath).
|
|
133
|
+
* @param {unknown} value - candidate path.
|
|
134
|
+
* @returns {string} absolute path with forward slashes and no trailing slash.
|
|
135
|
+
*/
|
|
136
|
+
export function normalizePath(value) {
|
|
137
|
+
if (typeof value !== 'string') return ''
|
|
138
|
+
let path = value.trim().replace(/\\/g, '/')
|
|
139
|
+
if (path.length === 0) return ''
|
|
140
|
+
const windowsDrive = /^[A-Za-z]:\//.test(path)
|
|
141
|
+
if (!path.startsWith('/') && !windowsDrive) return ''
|
|
142
|
+
path = path.replace(/\/{2,}/g, '/')
|
|
143
|
+
while (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1)
|
|
144
|
+
return path
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Normalize a list of resource/mode names. */
|
|
148
|
+
function cleanNameList(value) {
|
|
149
|
+
if (!Array.isArray(value)) return []
|
|
150
|
+
const names = []
|
|
151
|
+
for (const item of value) {
|
|
152
|
+
const name = cleanName(item)
|
|
153
|
+
if (name.length > 0) names.push(name)
|
|
154
|
+
}
|
|
155
|
+
return unique(names)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Normalize a list of workspace paths. */
|
|
159
|
+
function cleanPathList(value) {
|
|
160
|
+
if (!Array.isArray(value)) return []
|
|
161
|
+
const paths = []
|
|
162
|
+
for (const item of value) {
|
|
163
|
+
const path = normalizePath(item)
|
|
164
|
+
if (path.length > 0) paths.push(path)
|
|
165
|
+
}
|
|
166
|
+
return unique(paths)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Normalize a source's repository subdirectory. */
|
|
170
|
+
function cleanSubdir(value) {
|
|
171
|
+
const text = optionalString(value, 512).replace(/\\/g, '/')
|
|
172
|
+
return text.replace(/^\/+|\/+$/g, '').replace(/\/{2,}/g, '/')
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Default settings of a fresh document (§2.1). */
|
|
176
|
+
export function defaultSettings() {
|
|
177
|
+
return { enabled: true, mcpGate: true, injectSummary: true, gateDefaultSkills: false }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** A fresh, empty document. */
|
|
181
|
+
export function defaultState() {
|
|
182
|
+
return { version: STATE_VERSION, settings: defaultSettings(), skills: {}, mcp: {}, sources: {}, groups: {} }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Normalize one activation scope.
|
|
187
|
+
* @param {unknown} raw - candidate scope.
|
|
188
|
+
* @returns {{enabled: boolean, modes: string[], workspaces: string[]}|null} scope, or null when unusable.
|
|
189
|
+
*/
|
|
190
|
+
export function normalizeScope(raw) {
|
|
191
|
+
if (!isObject(raw)) return null
|
|
192
|
+
return {
|
|
193
|
+
enabled: raw.enabled !== false,
|
|
194
|
+
modes: cleanNameList(raw.modes),
|
|
195
|
+
workspaces: cleanPathList(raw.workspaces),
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Normalize the provenance fields of one member (`sourceId`/`digest`/`installedAt`).
|
|
201
|
+
* Empty optional values are omitted; `installedAt` is always present.
|
|
202
|
+
*
|
|
203
|
+
* @param {'skill'|'mcp'} kind - member namespace.
|
|
204
|
+
* @param {unknown} extra - values supplied by an install/update.
|
|
205
|
+
* @param {unknown} base - the member's previous entry, if any.
|
|
206
|
+
* @returns {object} provenance fields to merge over the scope.
|
|
207
|
+
*/
|
|
208
|
+
function itemExtras(kind, extra, base) {
|
|
209
|
+
const provided = isObject(extra) ? extra : {}
|
|
210
|
+
const previous = isObject(base) ? base : {}
|
|
211
|
+
const pick = (key) => {
|
|
212
|
+
if (typeof provided[key] === 'string') return provided[key].trim()
|
|
213
|
+
if (typeof previous[key] === 'string') return previous[key]
|
|
214
|
+
return ''
|
|
215
|
+
}
|
|
216
|
+
const out = {}
|
|
217
|
+
if (kind === 'skill') {
|
|
218
|
+
const sourceId = pick('sourceId')
|
|
219
|
+
if (sourceId.length > 0) out.sourceId = sourceId
|
|
220
|
+
const digest = pick('digest')
|
|
221
|
+
if (digest.length > 0) out.digest = digest
|
|
222
|
+
// Inheritance is a member choice, not provenance: carry whichever side of
|
|
223
|
+
// the write supplies it, so a scope edit never resets it to a default.
|
|
224
|
+
for (const key of ['modesFrom', 'workspacesFrom']) {
|
|
225
|
+
const value = provided[key]
|
|
226
|
+
if (value === 'self' || value === 'group') out[key] = value
|
|
227
|
+
else if (previous[key] === 'self' || previous[key] === 'group') out[key] = previous[key]
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (kind === 'mcp') {
|
|
231
|
+
// A scope-only edit (enable/disable, mode or workspace change) must not drop
|
|
232
|
+
// the connection definition that makes the member survive a Host restart.
|
|
233
|
+
const defined = cleanMcpDefinition(provided.definition) ?? cleanMcpDefinition(previous.definition)
|
|
234
|
+
if (defined !== undefined) out.definition = defined
|
|
235
|
+
}
|
|
236
|
+
out.installedAt = pick('installedAt') || new Date().toISOString()
|
|
237
|
+
return out
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Transports a stored MCP definition may name. */
|
|
241
|
+
const MCP_TRANSPORTS = ['stdio', 'streamable-http']
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Normalize the stored connection definition of one MCP member.
|
|
245
|
+
*
|
|
246
|
+
* The definition is what lets a Host restart rebuild the `mcp-client` Loader
|
|
247
|
+
* row: without it the member survived a restart while its connection did not,
|
|
248
|
+
* leaving a pool entry that lists zero tools. Only the fields the mcp-client
|
|
249
|
+
* plugin understands are kept, every value is length-capped, and an empty
|
|
250
|
+
* result is dropped so the document never grows junk.
|
|
251
|
+
*
|
|
252
|
+
* @param {unknown} raw - candidate definition (`{url|command, ...}`).
|
|
253
|
+
* @returns {object|undefined} cleaned definition, or undefined when unusable.
|
|
254
|
+
*/
|
|
255
|
+
export function cleanMcpDefinition(raw) {
|
|
256
|
+
if (!isObject(raw)) return undefined
|
|
257
|
+
const out = {}
|
|
258
|
+
const serverName = optionalString(raw.serverName, 64)
|
|
259
|
+
if (serverName.length > 0) out.serverName = serverName
|
|
260
|
+
if (MCP_TRANSPORTS.includes(raw.transport)) out.transport = raw.transport
|
|
261
|
+
const url = optionalString(raw.url, 2048)
|
|
262
|
+
if (url.length > 0) out.url = url
|
|
263
|
+
const command = optionalString(raw.command, 2048)
|
|
264
|
+
if (command.length > 0) out.command = command
|
|
265
|
+
if (Array.isArray(raw.args)) {
|
|
266
|
+
const args = raw.args.filter((arg) => typeof arg === 'string').slice(0, 64).map((arg) => arg.slice(0, 2048))
|
|
267
|
+
if (args.length > 0) out.args = args
|
|
268
|
+
}
|
|
269
|
+
for (const key of ['headers', 'env']) {
|
|
270
|
+
if (!isObject(raw[key])) continue
|
|
271
|
+
const table = {}
|
|
272
|
+
for (const [name, value] of Object.entries(raw[key])) {
|
|
273
|
+
if (typeof value !== 'string') continue
|
|
274
|
+
if (name.length === 0 || name.length > 256) continue
|
|
275
|
+
table[name] = value.slice(0, 4096)
|
|
276
|
+
}
|
|
277
|
+
if (Object.keys(table).length > 0) out[key] = table
|
|
278
|
+
}
|
|
279
|
+
const cwd = optionalString(raw.cwd, 2048)
|
|
280
|
+
if (cwd.length > 0) out.cwd = cwd
|
|
281
|
+
return Object.keys(out).length > 0 ? out : undefined
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Normalize one pool member entry (deterministic: never invents a timestamp). */
|
|
285
|
+
function normalizeMember(kind, raw) {
|
|
286
|
+
const scope = normalizeScope(raw)
|
|
287
|
+
if (scope === null) return null
|
|
288
|
+
const member = { ...scope }
|
|
289
|
+
if (kind === 'skill') {
|
|
290
|
+
const sourceId = optionalString(raw.sourceId, 128)
|
|
291
|
+
if (sourceId.length > 0) member.sourceId = sourceId
|
|
292
|
+
const digest = optionalString(raw.digest, 128)
|
|
293
|
+
if (digest.length > 0) member.digest = digest
|
|
294
|
+
// A member with its own non-empty list is "custom" unless it says otherwise:
|
|
295
|
+
// that keeps documents written before v4 gating exactly the same.
|
|
296
|
+
member.modesFrom = raw.modesFrom === 'self' ? 'self' : raw.modesFrom === 'group' ? 'group' : member.modes.length > 0 ? 'self' : 'group'
|
|
297
|
+
member.workspacesFrom =
|
|
298
|
+
raw.workspacesFrom === 'self' ? 'self' : raw.workspacesFrom === 'group' ? 'group' : member.workspaces.length > 0 ? 'self' : 'group'
|
|
299
|
+
}
|
|
300
|
+
if (kind === 'mcp') {
|
|
301
|
+
const definition = cleanMcpDefinition(raw.definition)
|
|
302
|
+
if (definition !== undefined) member.definition = definition
|
|
303
|
+
}
|
|
304
|
+
const installedAt = optionalString(raw.installedAt, 64)
|
|
305
|
+
member.installedAt = installedAt
|
|
306
|
+
return member
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Normalize one member map (`skills` or `mcp`). */
|
|
310
|
+
function normalizeMembers(raw, kind) {
|
|
311
|
+
if (!isObject(raw)) return {}
|
|
312
|
+
const out = {}
|
|
313
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
314
|
+
const name = cleanName(key)
|
|
315
|
+
if (name.length === 0) continue
|
|
316
|
+
const member = normalizeMember(kind, value)
|
|
317
|
+
if (member === null) continue
|
|
318
|
+
out[name] = member
|
|
319
|
+
}
|
|
320
|
+
return out
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Normalize one `lastCheck` record (§2.1). */
|
|
324
|
+
function normalizeLastCheck(raw) {
|
|
325
|
+
if (!isObject(raw)) return undefined
|
|
326
|
+
const status = CHECK_STATUSES.includes(raw.status) ? raw.status : 'error'
|
|
327
|
+
return {
|
|
328
|
+
at: timestamp(raw.at),
|
|
329
|
+
status,
|
|
330
|
+
remote: optionalString(raw.remote, 128),
|
|
331
|
+
error: optionalString(raw.error, 1024),
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Derive the Git identity of a source from either the explicit fields or its
|
|
337
|
+
* URL. The library re-parses `source.url` on check/update, so the URL is always
|
|
338
|
+
* stored for Git sources.
|
|
339
|
+
*
|
|
340
|
+
* @param {object} raw - candidate source record.
|
|
341
|
+
* @returns {{url: string, provider: string, project: string}|null} identity, or null.
|
|
342
|
+
*/
|
|
343
|
+
function deriveGit(raw) {
|
|
344
|
+
const url = optionalString(raw.url, 2048)
|
|
345
|
+
let provider = GIT_PROVIDERS.includes(raw.provider) ? raw.provider : ''
|
|
346
|
+
let project = optionalString(raw.project, 512).replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')
|
|
347
|
+
let parsedUrl = url
|
|
348
|
+
|
|
349
|
+
if (provider.length === 0 || project.split('/').length < 2) {
|
|
350
|
+
if (url.length === 0) return null
|
|
351
|
+
let text = url
|
|
352
|
+
const ssh = /^git@([^:]+):(.+)$/.exec(text)
|
|
353
|
+
if (ssh !== null) text = `https://${ssh[1]}/${ssh[2]}`
|
|
354
|
+
let parsed
|
|
355
|
+
try {
|
|
356
|
+
parsed = new URL(text)
|
|
357
|
+
} catch {
|
|
358
|
+
return null
|
|
359
|
+
}
|
|
360
|
+
const host = parsed.hostname.toLowerCase()
|
|
361
|
+
const derivedProvider = host.endsWith('github.com') ? 'github' : host.endsWith('gitlab.com') ? 'gitlab' : ''
|
|
362
|
+
const derivedProject = parsed.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')
|
|
363
|
+
if (derivedProvider.length === 0 || derivedProject.split('/').length < 2) return null
|
|
364
|
+
provider = derivedProvider
|
|
365
|
+
project = derivedProject
|
|
366
|
+
parsedUrl = `${parsed.protocol}//${parsed.hostname}${parsed.pathname}`.replace(/\.git$/i, '')
|
|
367
|
+
}
|
|
368
|
+
if (parsedUrl.length === 0) {
|
|
369
|
+
const host = provider === 'gitlab' ? 'gitlab.com' : 'github.com'
|
|
370
|
+
parsedUrl = `https://${host}/${project}`
|
|
371
|
+
}
|
|
372
|
+
return { url: parsedUrl, provider, project }
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Normalize one skill source record. */
|
|
376
|
+
function normalizeSource(raw) {
|
|
377
|
+
if (!isObject(raw)) return null
|
|
378
|
+
const kind = SOURCE_KINDS.includes(raw.kind) ? raw.kind : ''
|
|
379
|
+
if (kind.length === 0) return null
|
|
380
|
+
const id = cleanName(raw.id) || newId('src')
|
|
381
|
+
const label = optionalString(raw.label, 160) || defaultLabel(kind)
|
|
382
|
+
const source = {
|
|
383
|
+
id,
|
|
384
|
+
kind,
|
|
385
|
+
label,
|
|
386
|
+
skills: cleanNameList(raw.skills),
|
|
387
|
+
// Names the user deleted from this source: an update must not reinstall
|
|
388
|
+
// them. Kept apart from `skills` so "installed" stays the truth.
|
|
389
|
+
excluded: cleanNameList(raw.excluded),
|
|
390
|
+
createdAt: timestamp(raw.createdAt ?? raw.installedAt ?? raw.updatedAt),
|
|
391
|
+
}
|
|
392
|
+
const digest = optionalString(raw.digest, 128)
|
|
393
|
+
if (digest.length > 0) source.digest = digest
|
|
394
|
+
if (kind === 'git') {
|
|
395
|
+
const git = deriveGit(raw)
|
|
396
|
+
if (git === null) return null
|
|
397
|
+
source.url = git.url
|
|
398
|
+
source.provider = git.provider
|
|
399
|
+
source.project = git.project
|
|
400
|
+
source.branch = optionalString(raw.branch, 256) || 'main'
|
|
401
|
+
source.subdir = cleanSubdir(raw.subdir)
|
|
402
|
+
const sha = optionalString(raw.sha, 128)
|
|
403
|
+
if (sha.length > 0) source.sha = sha
|
|
404
|
+
const tokenCredential = optionalString(raw.tokenCredential, 128)
|
|
405
|
+
if (tokenCredential.length > 0) source.tokenCredential = tokenCredential
|
|
406
|
+
const lastCheck = normalizeLastCheck(raw.lastCheck)
|
|
407
|
+
if (lastCheck !== undefined) source.lastCheck = lastCheck
|
|
408
|
+
}
|
|
409
|
+
return source
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Fallback display label for one source kind. */
|
|
413
|
+
function defaultLabel(kind) {
|
|
414
|
+
if (kind === 'git') return 'Git source'
|
|
415
|
+
if (kind === 'zip') return 'ZIP import'
|
|
416
|
+
return 'File upload'
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Normalize one group record (`repo:<project>` / `import:<sourceId>`). */
|
|
420
|
+
function normalizeGroup(raw, fallbackKey) {
|
|
421
|
+
if (!isObject(raw)) return null
|
|
422
|
+
const key = optionalString(raw.key, 512) || optionalString(fallbackKey, 512)
|
|
423
|
+
if (key.length === 0) return null
|
|
424
|
+
const kind = GROUP_KINDS.includes(raw.kind) ? raw.kind : key.startsWith('import:') ? 'import' : 'repo'
|
|
425
|
+
return {
|
|
426
|
+
key,
|
|
427
|
+
kind,
|
|
428
|
+
// One switch for the whole repository: off means every member is off,
|
|
429
|
+
// without rewriting the per-member flags (they keep their own state).
|
|
430
|
+
enabled: raw.enabled !== false,
|
|
431
|
+
modes: cleanNameList(raw.modes),
|
|
432
|
+
workspaces: cleanPathList(raw.workspaces),
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Normalize the `groups` map. */
|
|
437
|
+
function normalizeGroups(raw) {
|
|
438
|
+
if (!isObject(raw)) return {}
|
|
439
|
+
const out = {}
|
|
440
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
441
|
+
const group = normalizeGroup(value, key)
|
|
442
|
+
if (group === null) continue
|
|
443
|
+
out[group.key] = group
|
|
444
|
+
}
|
|
445
|
+
return out
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Whether two name lists hold the same values in the same order. */
|
|
449
|
+
function sameNames(left, right) {
|
|
450
|
+
if (!Array.isArray(left) || !Array.isArray(right)) return false
|
|
451
|
+
if (left.length !== right.length) return false
|
|
452
|
+
return left.every((value, index) => value === right[index])
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Derive v4 groups from a v3 document: one group per repository (or per
|
|
457
|
+
* non-git import), seeded with the value its members already share. A mixed
|
|
458
|
+
* group starts empty, so the members that differ keep their own list.
|
|
459
|
+
*/
|
|
460
|
+
function deriveGroups(sources, skills) {
|
|
461
|
+
const membersByKey = new Map()
|
|
462
|
+
for (const member of Object.values(skills)) {
|
|
463
|
+
const source = member.sourceId === undefined ? undefined : sources[member.sourceId]
|
|
464
|
+
const key = groupKeyOfSource(source)
|
|
465
|
+
if (key.length === 0) continue
|
|
466
|
+
if (!membersByKey.has(key)) membersByKey.set(key, [])
|
|
467
|
+
membersByKey.get(key).push(member)
|
|
468
|
+
}
|
|
469
|
+
const groups = {}
|
|
470
|
+
for (const [key, members] of membersByKey) {
|
|
471
|
+
const first = members[0]
|
|
472
|
+
const uniformModes = members.every((member) => sameNames(member.modes, first.modes))
|
|
473
|
+
const uniformWorkspaces = members.every((member) => sameNames(member.workspaces, first.workspaces))
|
|
474
|
+
groups[key] = {
|
|
475
|
+
key,
|
|
476
|
+
kind: key.startsWith('import:') ? 'import' : 'repo',
|
|
477
|
+
modes: uniformModes ? [...first.modes] : [],
|
|
478
|
+
workspaces: uniformWorkspaces ? [...first.workspaces] : [],
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return groups
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Upgrade a v3 document to v4.
|
|
486
|
+
*
|
|
487
|
+
* Groups are inferred so that every member keeps the exact scope it had: a
|
|
488
|
+
* repository whose members all agree gives that shared value to the group and
|
|
489
|
+
* the members inherit it; a mixed repository starts empty and only the members
|
|
490
|
+
* that already said something stay `self`. Nothing becomes more or less
|
|
491
|
+
* visible.
|
|
492
|
+
*
|
|
493
|
+
* @param {object} source - raw v3 document.
|
|
494
|
+
* @returns {object} v4 document.
|
|
495
|
+
*/
|
|
496
|
+
function migrateV3(source) {
|
|
497
|
+
const rawSettings = isObject(source.settings) ? source.settings : {}
|
|
498
|
+
const settings = {
|
|
499
|
+
enabled: rawSettings.enabled !== false,
|
|
500
|
+
mcpGate: rawSettings.mcpGate !== false,
|
|
501
|
+
injectSummary: rawSettings.injectSummary !== false,
|
|
502
|
+
gateDefaultSkills: rawSettings.gateDefaultSkills === true,
|
|
503
|
+
}
|
|
504
|
+
const sources = {}
|
|
505
|
+
if (isObject(source.sources)) {
|
|
506
|
+
for (const value of Object.values(source.sources)) {
|
|
507
|
+
const normalized = normalizeSource(value)
|
|
508
|
+
if (normalized === null) continue
|
|
509
|
+
sources[normalized.id] = normalized
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const skills = normalizeMembers(source.skills, 'skill')
|
|
513
|
+
const groups = deriveGroups(sources, skills)
|
|
514
|
+
for (const member of Object.values(skills)) {
|
|
515
|
+
const key = groupKeyOfSource(member.sourceId === undefined ? undefined : sources[member.sourceId])
|
|
516
|
+
const group = groups[key]
|
|
517
|
+
if (group === undefined) {
|
|
518
|
+
member.modesFrom = 'self'
|
|
519
|
+
member.workspacesFrom = 'self'
|
|
520
|
+
continue
|
|
521
|
+
}
|
|
522
|
+
member.modesFrom = sameNames(member.modes, group.modes) ? 'group' : 'self'
|
|
523
|
+
member.workspacesFrom = sameNames(member.workspaces, group.workspaces) ? 'group' : 'self'
|
|
524
|
+
}
|
|
525
|
+
return {
|
|
526
|
+
version: STATE_VERSION,
|
|
527
|
+
settings,
|
|
528
|
+
skills,
|
|
529
|
+
mcp: normalizeMembers(source.mcp, 'mcp'),
|
|
530
|
+
sources,
|
|
531
|
+
groups,
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Normalize one group patch over the stored record (create when absent).
|
|
537
|
+
*
|
|
538
|
+
* @param {object} state - normalized document.
|
|
539
|
+
* @param {unknown} patch - `{key, modes?, workspaces?}`.
|
|
540
|
+
* @returns {object} normalized document (unchanged when the key is unusable).
|
|
541
|
+
*/
|
|
542
|
+
export function upsertGroup(state, patch) {
|
|
543
|
+
const provided = isObject(patch) ? patch : {}
|
|
544
|
+
const key = optionalString(provided.key, 512)
|
|
545
|
+
if (key.length === 0) return state
|
|
546
|
+
const existing = isObject(state.groups) ? state.groups[key] : undefined
|
|
547
|
+
const group = normalizeGroup({ ...existing, ...provided, key }, key)
|
|
548
|
+
if (group === null) return state
|
|
549
|
+
return normalizeState({ ...state, groups: { ...state.groups, [key]: group } })
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Normalize a complete document.
|
|
554
|
+
* @param {unknown} raw - candidate document.
|
|
555
|
+
* @returns {object} normalized v4 document.
|
|
556
|
+
*/
|
|
557
|
+
export function normalizeState(raw) {
|
|
558
|
+
const source = isObject(raw) ? raw : {}
|
|
559
|
+
if (source.version === LEGACY_VERSION) return normalizeState(migrateV3(source))
|
|
560
|
+
if (source.version !== STATE_VERSION) return defaultState()
|
|
561
|
+
|
|
562
|
+
const rawSettings = isObject(source.settings) ? source.settings : {}
|
|
563
|
+
const settings = {
|
|
564
|
+
enabled: rawSettings.enabled !== false,
|
|
565
|
+
mcpGate: rawSettings.mcpGate !== false,
|
|
566
|
+
injectSummary: rawSettings.injectSummary !== false,
|
|
567
|
+
gateDefaultSkills: rawSettings.gateDefaultSkills === true,
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const sources = {}
|
|
571
|
+
if (isObject(source.sources)) {
|
|
572
|
+
for (const value of Object.values(source.sources)) {
|
|
573
|
+
const normalized = normalizeSource(value)
|
|
574
|
+
if (normalized === null) continue
|
|
575
|
+
sources[normalized.id] = normalized
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
return {
|
|
580
|
+
version: STATE_VERSION,
|
|
581
|
+
settings,
|
|
582
|
+
skills: normalizeMembers(source.skills, 'skill'),
|
|
583
|
+
mcp: normalizeMembers(source.mcp, 'mcp'),
|
|
584
|
+
sources,
|
|
585
|
+
groups: normalizeGroups(source.groups),
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Merge a settings patch over a normalized document.
|
|
591
|
+
* Unknown keys (including the retired `enforcePool`) are ignored.
|
|
592
|
+
*
|
|
593
|
+
* @param {object} state - normalized document.
|
|
594
|
+
* @param {unknown} patch - partial settings object.
|
|
595
|
+
* @returns {object} normalized document.
|
|
596
|
+
*/
|
|
597
|
+
export function applySettingsPatch(state, patch) {
|
|
598
|
+
const provided = isObject(patch) ? patch : {}
|
|
599
|
+
const merged = { ...state.settings }
|
|
600
|
+
for (const key of SETTING_KEYS) {
|
|
601
|
+
if (typeof provided[key] === 'boolean') merged[key] = provided[key]
|
|
602
|
+
}
|
|
603
|
+
return normalizeState({ ...state, settings: merged })
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Add or update one pool member. Passing a null scope removes it, so the same
|
|
608
|
+
* helper serves both edits and deletions.
|
|
609
|
+
*
|
|
610
|
+
* @param {object} state - normalized document.
|
|
611
|
+
* @param {'skill'|'mcp'} kind - member namespace.
|
|
612
|
+
* @param {unknown} name - resource name.
|
|
613
|
+
* @param {unknown} scope - `{enabled,modes,workspaces}`, or null to remove from the pool.
|
|
614
|
+
* @param {unknown} [extra] - provenance (`sourceId`, `digest`, `installedAt`); omitted values keep the stored ones.
|
|
615
|
+
* @returns {object} normalized document.
|
|
616
|
+
*/
|
|
617
|
+
export function upsertItem(state, kind, name, scope, extra) {
|
|
618
|
+
if (!KINDS.includes(kind)) return state
|
|
619
|
+
const key = cleanName(name)
|
|
620
|
+
if (key.length === 0) return state
|
|
621
|
+
const bucket = kind === 'skill' ? 'skills' : 'mcp'
|
|
622
|
+
const currentBucket = isObject(state[bucket]) ? state[bucket] : {}
|
|
623
|
+
const next = { ...currentBucket }
|
|
624
|
+
if (scope === null || scope === undefined) {
|
|
625
|
+
delete next[key]
|
|
626
|
+
} else {
|
|
627
|
+
const normalized = normalizeScope(scope)
|
|
628
|
+
if (normalized === null) return state
|
|
629
|
+
next[key] = { ...normalized, ...itemExtras(kind, extra, currentBucket[key]) }
|
|
630
|
+
}
|
|
631
|
+
return normalizeState({ ...state, [bucket]: next })
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Remove one pool member (membership only; callers remove files/loader rows).
|
|
636
|
+
* @param {object} state - normalized document.
|
|
637
|
+
* @param {'skill'|'mcp'} kind - member namespace.
|
|
638
|
+
* @param {unknown} name - resource name.
|
|
639
|
+
* @returns {object} normalized document.
|
|
640
|
+
*/
|
|
641
|
+
export function removeItem(state, kind, name) {
|
|
642
|
+
if (!KINDS.includes(kind)) return state
|
|
643
|
+
const key = cleanName(name)
|
|
644
|
+
if (key.length === 0) return state
|
|
645
|
+
const bucket = kind === 'skill' ? 'skills' : 'mcp'
|
|
646
|
+
const currentBucket = isObject(state[bucket]) ? state[bucket] : {}
|
|
647
|
+
if (!Object.hasOwn(currentBucket, key)) return state
|
|
648
|
+
const next = { ...currentBucket }
|
|
649
|
+
delete next[key]
|
|
650
|
+
return normalizeState({ ...state, [bucket]: next })
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** Upsert one skill source. */
|
|
654
|
+
export function upsertSource(state, source) {
|
|
655
|
+
const normalized = normalizeSource(source)
|
|
656
|
+
if (normalized === null) return state
|
|
657
|
+
return normalizeState({ ...state, sources: { ...state.sources, [normalized.id]: normalized } })
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Remove one skill source, and its group when it was the repository's last
|
|
662
|
+
* source: an empty repository has no members left to scope.
|
|
663
|
+
*
|
|
664
|
+
* @param {object} state - normalized document.
|
|
665
|
+
* @param {unknown} id - source id.
|
|
666
|
+
* @returns {object} normalized document.
|
|
667
|
+
*/
|
|
668
|
+
export function removeSource(state, id) {
|
|
669
|
+
const key = cleanName(id)
|
|
670
|
+
if (key.length === 0) return state
|
|
671
|
+
const removed = isObject(state.sources) ? state.sources[key] : undefined
|
|
672
|
+
const next = { ...state.sources }
|
|
673
|
+
delete next[key]
|
|
674
|
+
const groups = isObject(state.groups) ? { ...state.groups } : {}
|
|
675
|
+
const groupKey = groupKeyOfSource(removed)
|
|
676
|
+
if (groupKey.length > 0 && !Object.values(next).some((source) => groupKeyOfSource(source) === groupKey)) {
|
|
677
|
+
delete groups[groupKey]
|
|
678
|
+
}
|
|
679
|
+
return normalizeState({ ...state, sources: next, groups })
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Record that one skill was deleted by the user: drop it from every source that
|
|
684
|
+
* installed it and remember it as excluded, so a later update skips it.
|
|
685
|
+
*
|
|
686
|
+
* @param {object} state - normalized document.
|
|
687
|
+
* @param {unknown} name - skill name.
|
|
688
|
+
* @returns {object} normalized document.
|
|
689
|
+
*/
|
|
690
|
+
export function excludeSourceSkill(state, name) {
|
|
691
|
+
const key = cleanName(name)
|
|
692
|
+
if (key.length === 0) return state
|
|
693
|
+
let next = state
|
|
694
|
+
for (const source of Object.values(isObject(state.sources) ? state.sources : {})) {
|
|
695
|
+
if (!Array.isArray(source.skills) || !source.skills.includes(key)) continue
|
|
696
|
+
next = upsertSource(next, {
|
|
697
|
+
...source,
|
|
698
|
+
skills: source.skills.filter((skill) => skill !== key),
|
|
699
|
+
excluded: [...(Array.isArray(source.excluded) ? source.excluded : []), key],
|
|
700
|
+
})
|
|
701
|
+
}
|
|
702
|
+
return next
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Names one source may install again: its excluded list removed.
|
|
707
|
+
*
|
|
708
|
+
* @param {Array<string>} names - candidate names.
|
|
709
|
+
* @param {Array<string>} excluded - excluded names.
|
|
710
|
+
* @returns {Array<string>} names that are not excluded.
|
|
711
|
+
*/
|
|
712
|
+
export function withoutExcluded(names, excluded) {
|
|
713
|
+
const blocked = new Set(Array.isArray(excluded) ? excluded : [])
|
|
714
|
+
return (Array.isArray(names) ? names : []).filter((name) => !blocked.has(name))
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Durable JSON document with atomic, serialized writes.
|
|
719
|
+
*/
|
|
720
|
+
export class StateStore {
|
|
721
|
+
constructor({ file, logger, version = '0.3.0' } = {}) {
|
|
722
|
+
this.file = typeof file === 'string' && file.length > 0 ? file : statePath()
|
|
723
|
+
this.logger = logger
|
|
724
|
+
this.version = version
|
|
725
|
+
this.cached = undefined
|
|
726
|
+
this.writeChain = Promise.resolve()
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** Read the document, caching the normalized result. */
|
|
730
|
+
async read({ fresh = false } = {}) {
|
|
731
|
+
if (!fresh && this.cached !== undefined) return this.cached
|
|
732
|
+
let raw = null
|
|
733
|
+
try {
|
|
734
|
+
raw = JSON.parse(await readFile(this.file, 'utf8'))
|
|
735
|
+
} catch (error) {
|
|
736
|
+
if (error?.code !== 'ENOENT') this.logger?.warn?.('[skill-pool] state unreadable; starting from defaults')
|
|
737
|
+
raw = null
|
|
738
|
+
}
|
|
739
|
+
this.cached = normalizeState(raw)
|
|
740
|
+
return this.cached
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Persist a normalized document and update the cache. */
|
|
744
|
+
async write(state) {
|
|
745
|
+
const normalized = normalizeState(state)
|
|
746
|
+
const run = this.writeChain.then(async () => {
|
|
747
|
+
await mkdir(dirname(this.file), { recursive: true })
|
|
748
|
+
const temporary = `${this.file}.${process.pid}.${Date.now()}.tmp`
|
|
749
|
+
// 0600: an MCP member may carry an `Authorization` header, so the pool
|
|
750
|
+
// document holds the same secrets a profile patch would.
|
|
751
|
+
await writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
752
|
+
await rename(temporary, this.file)
|
|
753
|
+
this.cached = normalized
|
|
754
|
+
return normalized
|
|
755
|
+
})
|
|
756
|
+
this.writeChain = run.then(() => undefined, () => undefined)
|
|
757
|
+
return run
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Apply one mutation to a fresh read and persist the result. */
|
|
761
|
+
async update(mutate) {
|
|
762
|
+
const current = await this.read({ fresh: true })
|
|
763
|
+
return this.write(mutate(current))
|
|
764
|
+
}
|
|
765
|
+
}
|