universal-plugin-hub 1.1.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/README.zh.md +14 -2
- package/client/client.js +5421 -1199
- package/package.json +1 -1
- package/src/at-plugins.js +823 -0
- package/src/icons.js +226 -36
- package/src/index.js +44 -2
- package/src/install.js +1618 -852
- package/src/local.js +439 -71
- package/src/market.js +112 -56
- package/src/oauth-bridge.js +1 -2
- package/src/oauth-config.js +4 -0
- package/src/oauth-store.js +24 -11
- package/src/oauth.js +5 -4
- package/src/parser.js +1272 -462
- package/src/routes.js +410 -128
- package/src/runtime.js +3 -1
- package/src/skill-uploads.js +116 -12
- package/src/skills.js +12 -5
- package/src/store.js +258 -40
package/src/runtime.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { resolveOptionalService } from './store.js'
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Apply saved hub changes to the running DSH profile.
|
|
3
5
|
*
|
|
@@ -57,7 +59,7 @@ export function createProfileApplicator(ctx) {
|
|
|
57
59
|
try {
|
|
58
60
|
// Resolve inside the try: a throwing service lookup must become a
|
|
59
61
|
// reported failure, not a rejection that strands the status.
|
|
60
|
-
const hmr = ctx?.root
|
|
62
|
+
const hmr = resolveOptionalService(ctx?.root, 'hmr') || resolveOptionalService(ctx, 'hmr')
|
|
61
63
|
if (!hmr || typeof hmr.reconcileProfile !== 'function') {
|
|
62
64
|
return { application: 'restart-required', restartReason: 'no-hmr', token: pending.token }
|
|
63
65
|
}
|
package/src/skill-uploads.js
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
* DSH's native user-dsh root. Directory bundles use junctions on Windows (and
|
|
4
4
|
* directory symlinks elsewhere); a bare SKILL.md is copied as <name>.md.
|
|
5
5
|
*/
|
|
6
|
-
import { cpSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync } from 'node:fs'
|
|
6
|
+
import { cpSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync } from 'node:fs'
|
|
7
7
|
import { createHash } from 'node:crypto'
|
|
8
8
|
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
9
|
-
import {
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { dshSkillsDir, installedDir, readState, safeRmDir, uploadedSkillsDir, writeState } from './store.js'
|
|
10
11
|
|
|
11
12
|
const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
12
13
|
|
|
@@ -16,6 +17,15 @@ function samePath(a, b) {
|
|
|
16
17
|
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
function canonical(path) {
|
|
21
|
+
try { return realpathSync.native(path) } catch { return resolve(path) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pathKey(path) {
|
|
25
|
+
const value = canonical(path)
|
|
26
|
+
return process.platform === 'win32' ? value.toLowerCase() : value
|
|
27
|
+
}
|
|
28
|
+
|
|
19
29
|
/**
|
|
20
30
|
* The switch state is keyed by this hash (see skillId in skills.js), and the
|
|
21
31
|
* junction means the discovered path resolves to the private original, so both
|
|
@@ -92,25 +102,107 @@ function readFileSyncSafe(file) {
|
|
|
92
102
|
try { return readFileSync(file, 'utf8') } catch { return '' }
|
|
93
103
|
}
|
|
94
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Every name that already answers to a skill, scanned once per import. The
|
|
107
|
+
* name a skill answers to is its frontmatter `name` — the directory is only a
|
|
108
|
+
* fallback, exactly as the Skills tab reads it — so a collection member can
|
|
109
|
+
* be detected even when its folder is named differently.
|
|
110
|
+
*/
|
|
111
|
+
export function takenSkillNames() {
|
|
112
|
+
return collectTakenNames(pluginMirrorPaths())
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function collectTakenNames(mirrors) {
|
|
116
|
+
const names = new Set()
|
|
117
|
+
for (const record of readState().uploadedSkills || []) names.add(record.name)
|
|
118
|
+
for (const root of [dshSkillsDir(), join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')]) {
|
|
119
|
+
let children
|
|
120
|
+
try { children = readdirSync(root, { withFileTypes: true }) } catch { continue }
|
|
121
|
+
for (const entry of children) {
|
|
122
|
+
const path = join(root, entry.name)
|
|
123
|
+
try {
|
|
124
|
+
// A junction reads as a link, not a directory, so the entry alone
|
|
125
|
+
// cannot decide the shape — the stat the Skills tab uses does.
|
|
126
|
+
const stat = entry.isSymbolicLink() ? statSync(path) : entry
|
|
127
|
+
if (stat.isDirectory()) {
|
|
128
|
+
if (mirrors.has(pathKey(path))) continue
|
|
129
|
+
const manifest = readdirSync(path).find((file) => /^skill\.md$/i.test(file))
|
|
130
|
+
if (!manifest) continue
|
|
131
|
+
names.add(declaredName(readFileSyncSafe(join(path, manifest))) || entry.name)
|
|
132
|
+
} else if (stat.isFile() && /\.md$/i.test(entry.name)) {
|
|
133
|
+
names.add(declaredName(readFileSyncSafe(path)) || entry.name.replace(/\.md$/i, ''))
|
|
134
|
+
}
|
|
135
|
+
} catch {}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return names
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A plugin's skills are mirrored into the user-dsh root by the plugin pipeline.
|
|
143
|
+
* The Skills tab hides them, so reporting one as taken would offer an overwrite
|
|
144
|
+
* that permanently costs the plugin its own copy. Ownership is decided the way
|
|
145
|
+
* the tab decides it: the mirror is a byte copy of the plugin's SKILL.md.
|
|
146
|
+
*
|
|
147
|
+
* This reads files, so it is scanned once per batch and passed down rather
|
|
148
|
+
* than cached module-wide: nothing would tell such a cache when to expire.
|
|
149
|
+
*/
|
|
150
|
+
function pluginMirrorPaths() {
|
|
151
|
+
const owned = new Set()
|
|
152
|
+
for (const plugin of readState().plugins || []) {
|
|
153
|
+
let children
|
|
154
|
+
try { children = readdirSync(join(installedDir(plugin.name), 'skills'), { withFileTypes: true }) } catch { continue }
|
|
155
|
+
for (const child of children) {
|
|
156
|
+
try {
|
|
157
|
+
const source = readFileSync(join(installedDir(plugin.name), 'skills', child.name, 'SKILL.md'), 'utf8')
|
|
158
|
+
const target = join(dshSkillsDir(), child.name)
|
|
159
|
+
if (isUploadedSkillTarget(target)) continue
|
|
160
|
+
if (readFileSyncSafe(join(target, 'SKILL.md')) !== source) continue
|
|
161
|
+
owned.add(pathKey(target))
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return owned
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function declaredName(raw) {
|
|
169
|
+
const frontmatter = raw.match(/^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/)
|
|
170
|
+
if (!frontmatter) return ''
|
|
171
|
+
return (frontmatter[1].match(/^name:\s*(.+)$/m)?.[1] || '').trim().replace(/^['"]|['"]$/g, '')
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Both shapes a skill can be exposed as, since one name may leave a stale other. */
|
|
175
|
+
function targetPaths(name) {
|
|
176
|
+
return [recordPaths(name, 'directory').target, recordPaths(name, 'file').target]
|
|
177
|
+
}
|
|
178
|
+
|
|
95
179
|
/** Every rejection this import can raise, so a batch can be checked up front. */
|
|
96
|
-
function preflight(entry, { overwrite, singleFile, fileDir = null }) {
|
|
180
|
+
function preflight(entry, { overwrite, overwriteNames, singleFile, fileDir = null, taken = null }) {
|
|
97
181
|
const { name, file } = validateEntry(entry)
|
|
98
182
|
const kind = singleFile ? 'file' : 'directory'
|
|
99
183
|
const paths = recordPaths(name, kind)
|
|
100
184
|
const previous = uploadedSkillRecord(name)
|
|
101
|
-
|
|
102
|
-
|
|
185
|
+
// Overwriting one clashing member of a collection must not silently replace
|
|
186
|
+
// the others, so a named list wins over the blanket flag: it names exactly
|
|
187
|
+
// what the user was shown.
|
|
188
|
+
const replace = Array.isArray(overwriteNames) && overwriteNames.length
|
|
189
|
+
? overwriteNames.includes(name)
|
|
190
|
+
: overwrite === true
|
|
191
|
+
if (!replace && (taken || takenSkillNames()).has(name)) throw new Error(`已存在同名 Skill「${name}」`)
|
|
192
|
+
// A recorded upload is already in `taken`, so reaching here means nothing
|
|
193
|
+
// answers to the name yet and whatever sits at the target is the user's own.
|
|
194
|
+
if (!replace && targetPaths(name).some(pathExists)) {
|
|
103
195
|
throw new Error(`DSH Skills 目录已存在「${name}」,为避免覆盖你的文件,本次未导入`)
|
|
104
196
|
}
|
|
105
197
|
const source = resolve(entry.dir)
|
|
106
198
|
if (contains(uploadedSkillsDir(), source) || contains(source, uploadedSkillsDir())) {
|
|
107
199
|
throw new Error('导入源与技能存储目录重叠,请从独立文件夹导入')
|
|
108
200
|
}
|
|
109
|
-
return { name, file, kind, paths, previous, source }
|
|
201
|
+
return { name, file, kind, paths, previous, source, replace }
|
|
110
202
|
}
|
|
111
203
|
|
|
112
204
|
function installOne(entry, options) {
|
|
113
|
-
const { name, file, kind, paths, previous, source } = preflight(entry, options)
|
|
205
|
+
const { name, file, kind, paths, previous, source, replace } = preflight(entry, options)
|
|
114
206
|
// A bare SKILL.md file, or a flat `<name>.md` sitting beside other skills in
|
|
115
207
|
// one folder, has no assets to carry: only the manifest is copied.
|
|
116
208
|
const manifestOnly = options.singleFile || options.fileDir
|
|
@@ -131,6 +223,13 @@ function installOne(entry, options) {
|
|
|
131
223
|
if (previous) {
|
|
132
224
|
removeTarget(previous)
|
|
133
225
|
safeRmDir(recordPaths(previous.name, previous.kind).sourceDir)
|
|
226
|
+
} else if (replace) {
|
|
227
|
+
// A copy the user placed in the DSH root themselves: they just agreed to
|
|
228
|
+
// replace it. Clear both exposed shapes: a leftover of the other one
|
|
229
|
+
// answers to the same name and splits one command across two cards.
|
|
230
|
+
removeTarget({ name, kind })
|
|
231
|
+
removeTarget({ name, kind: kind === 'file' ? 'directory' : 'file' })
|
|
232
|
+
if (pathExists(paths.sourceDir)) safeRmDir(paths.sourceDir)
|
|
134
233
|
}
|
|
135
234
|
renameSync(staging, paths.sourceDir)
|
|
136
235
|
staged = false
|
|
@@ -142,7 +241,7 @@ function installOne(entry, options) {
|
|
|
142
241
|
state.uploadedSkills = [...(state.uploadedSkills || []).filter(item => item.name !== name),
|
|
143
242
|
{ name, kind, ...paths, uploadedAt: previous?.uploadedAt || Date.now(), updatedAt: Date.now() }]
|
|
144
243
|
writeState(state)
|
|
145
|
-
return { name, kind }
|
|
244
|
+
return { name, kind, replace }
|
|
146
245
|
} catch (error) {
|
|
147
246
|
// Roll back only what this attempt created; never delete an old original
|
|
148
247
|
// that was already removed before the failure (its target is gone too, so
|
|
@@ -155,20 +254,25 @@ function installOne(entry, options) {
|
|
|
155
254
|
}
|
|
156
255
|
}
|
|
157
256
|
|
|
158
|
-
export function installUploadedSkills(entries, { overwrite = false, singleFile = false } = {}) {
|
|
257
|
+
export function installUploadedSkills(entries, { overwrite = false, overwriteNames = null, singleFile = false } = {}) {
|
|
159
258
|
if (!Array.isArray(entries) || entries.length === 0) throw new Error('未检测到可上传的 Skill')
|
|
160
259
|
// A batch must not half-install: every rejection this import can predict is
|
|
161
260
|
// raised before the first file moves, so a duplicate name in the middle of
|
|
162
261
|
// the package cannot leave the earlier skills live while the UI reports a
|
|
163
262
|
// failure.
|
|
164
|
-
|
|
263
|
+
const taken = takenSkillNames()
|
|
264
|
+
const options = { overwrite, overwriteNames, singleFile, taken }
|
|
265
|
+
for (const entry of entries) preflight(entry, { ...options, fileDir: entry.singleFile })
|
|
165
266
|
const installed = []
|
|
166
267
|
try {
|
|
167
268
|
for (const entry of entries) {
|
|
168
269
|
const replaced = !!uploadedSkillRecord(String(entry?.row?.name || ''))
|
|
169
|
-
|
|
270
|
+
const installedOne = installOne(entry, { ...options, fileDir: entry.singleFile })
|
|
271
|
+
// An overwrite has already destroyed whatever it replaced, so undoing it
|
|
272
|
+
// would leave nothing behind, not even the copy this import just wrote.
|
|
273
|
+
installed.push({ ...installedOne, replaced: replaced || installedOne.replace })
|
|
170
274
|
}
|
|
171
|
-
return installed.map(({ replaced, ...skill }) => skill)
|
|
275
|
+
return installed.map(({ replaced, replace, ...skill }) => skill)
|
|
172
276
|
} catch (error) {
|
|
173
277
|
// Only a failure preflight cannot see (disk, permissions) gets here. Undo
|
|
174
278
|
// the entries this batch created; an overwrite has already replaced its
|
package/src/skills.js
CHANGED
|
@@ -3,7 +3,7 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, watch }
|
|
|
3
3
|
import { homedir } from 'node:os'
|
|
4
4
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
5
5
|
import { load as parseYaml } from 'js-yaml'
|
|
6
|
-
import { readState, writeState, dshSkillsDir, installedDir } from './store.js'
|
|
6
|
+
import { readState, writeState, dshSkillsDir, installedDir, resolveOptionalService } from './store.js'
|
|
7
7
|
import { isUploadedSkillTarget, uploadedSkillRecord } from './skill-uploads.js'
|
|
8
8
|
import { formatDisplayName } from './parser.js'
|
|
9
9
|
|
|
@@ -431,7 +431,14 @@ export function createSkillsManager(root) {
|
|
|
431
431
|
const after = await status(item)
|
|
432
432
|
const desired = enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
|
|
433
433
|
if (!after.available || !after.invocations.every(policy => policy.modelInvocable === desired.modelInvocable && policy.userInvocable === desired.userInvocable)) {
|
|
434
|
-
|
|
434
|
+
const current = readState()
|
|
435
|
+
const restored = { ...(current.disabledLocalSkills || {}) }
|
|
436
|
+
for (const location of item.locations) {
|
|
437
|
+
if (Object.prototype.hasOwnProperty.call(previous, location.id)) restored[location.id] = previous[location.id]
|
|
438
|
+
else delete restored[location.id]
|
|
439
|
+
}
|
|
440
|
+
current.disabledLocalSkills = restored
|
|
441
|
+
writeState(current); invalidateAll()
|
|
435
442
|
catalogChanged?.()
|
|
436
443
|
throw new Error(after.message || 'DSH 未确认开关状态,已恢复原状态')
|
|
437
444
|
}
|
|
@@ -533,7 +540,7 @@ export function createSkillsManager(root) {
|
|
|
533
540
|
// A preset's filesystem provider shadows the global layer regardless of
|
|
534
541
|
// rank. Explicit off choices must also live in the exact agent scope.
|
|
535
542
|
// Enabled skills continue to resolve through their native providers.
|
|
536
|
-
const serviceFor = () => ctx
|
|
543
|
+
const serviceFor = () => resolveOptionalService(ctx, 'agentPresets')?.serviceFor(agent, 'skills') ?? registry
|
|
537
544
|
const service = serviceFor()
|
|
538
545
|
if (service !== registry && !presetProviders.has(service)) {
|
|
539
546
|
let invalidatePreset
|
|
@@ -548,13 +555,13 @@ export function createSkillsManager(root) {
|
|
|
548
555
|
}
|
|
549
556
|
if (service !== registry && presetProviders.has(service)) presetProviders.get(service).users++
|
|
550
557
|
const dispose = (createScope ? (() => { const policy = scopePolicies.get(agent); scopePolicies.delete(agent); return policy?.dispose() })
|
|
551
|
-
: guard('agent provider', () => agent
|
|
558
|
+
: guard('agent provider', () => resolveOptionalService(agent?.ctx, 'skills')?.registerProvider?.(() => disabledProvider()))) || (() => {})
|
|
552
559
|
agentViews.set(agent, { dispose: () => {
|
|
553
560
|
const pending = dispose()
|
|
554
561
|
const preset = presetProviders.get(service)
|
|
555
562
|
if (preset && --preset.users === 0) { preset.dispose(); presetProviders.delete(service) }
|
|
556
563
|
return pending
|
|
557
|
-
}, registry: serviceFor, lookup: () => ({ scope: agent, cwd: ctx
|
|
564
|
+
}, registry: serviceFor, lookup: () => ({ scope: agent, cwd: resolveOptionalService(ctx, 'workingDirectory')?.get(agent.session) ?? agent.session?.header?.cwd }) })
|
|
558
565
|
}
|
|
559
566
|
const unbind = (agent) => { const view = agentViews.get(agent); agentViews.delete(agent); return view?.dispose() }
|
|
560
567
|
const offCreated = ctx.on('agent/created', ({ agent }) => bind(agent))
|
package/src/store.js
CHANGED
|
@@ -7,59 +7,174 @@
|
|
|
7
7
|
* installed/<name>/ — installed plugin copies
|
|
8
8
|
*/
|
|
9
9
|
import { homedir } from 'node:os'
|
|
10
|
-
import { dirname, join } from 'node:path'
|
|
11
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, lstatSync, rmSync, unlinkSync } from 'node:fs'
|
|
10
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, lstatSync, rmSync, rmdirSync, unlinkSync, readdirSync } from 'node:fs'
|
|
12
|
+
import { rm } from 'node:fs/promises'
|
|
12
13
|
import { execFileSync } from 'node:child_process'
|
|
13
14
|
|
|
15
|
+
let TRASH_SEQ = 0
|
|
16
|
+
let TRASH_SWEEP_TIMER = null
|
|
17
|
+
const PENDING_TRASH_PATHS = new Set()
|
|
18
|
+
let STATE_TMP_SEQ = 0
|
|
19
|
+
|
|
20
|
+
function canonicalComparePath(p) {
|
|
21
|
+
const resolved = resolve(p)
|
|
22
|
+
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isSameOrInsidePath(child, parent) {
|
|
26
|
+
if (!child || !parent) return false
|
|
27
|
+
const c = canonicalComparePath(child)
|
|
28
|
+
const p = canonicalComparePath(parent)
|
|
29
|
+
if (c === p) return true
|
|
30
|
+
const rel = relative(p, c)
|
|
31
|
+
return rel !== '' && !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function scheduleTrashSweep(trashed) {
|
|
35
|
+
if (trashed) PENDING_TRASH_PATHS.add(trashed)
|
|
36
|
+
if (TRASH_SWEEP_TIMER) return
|
|
37
|
+
TRASH_SWEEP_TIMER = setTimeout(() => {
|
|
38
|
+
TRASH_SWEEP_TIMER = null
|
|
39
|
+
try { sweepTrash() } catch {}
|
|
40
|
+
}, 5000)
|
|
41
|
+
TRASH_SWEEP_TIMER.unref?.()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function moveToTrash(dir, quarantineRoot) {
|
|
45
|
+
mkdirSync(quarantineRoot, { recursive: true })
|
|
46
|
+
const seq = (TRASH_SEQ = (TRASH_SEQ + 1) & 0xffffff).toString(36)
|
|
47
|
+
const trashed = join(quarantineRoot, `${basename(dir) || 'dir'}-${process.pid}-${Date.now().toString(36)}-${seq}`)
|
|
48
|
+
renameSync(dir, trashed)
|
|
49
|
+
return trashed
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function unlinkReparsePointsSync(dir) {
|
|
53
|
+
let entries
|
|
54
|
+
try {
|
|
55
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
56
|
+
} catch {
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
const child = join(dir, entry.name)
|
|
61
|
+
if (entry.isSymbolicLink()) {
|
|
62
|
+
try { unlinkSync(child) } catch { try { rmdirSync(child) } catch {} }
|
|
63
|
+
} else if (entry.isDirectory()) {
|
|
64
|
+
unlinkReparsePointsSync(child)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
14
69
|
/** Robust directory deletion handling Windows readonly/locked files. */
|
|
15
|
-
export function safeRmDir(dir, { allowTrash = true } = {}) {
|
|
70
|
+
export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot() } = {}) {
|
|
16
71
|
if (!dir) return
|
|
17
72
|
// A dangling junction is invisible to existsSync. Unlink junctions directly
|
|
18
73
|
// so the Windows directory fallbacks never operate on their targets.
|
|
19
74
|
let entry
|
|
20
|
-
|
|
75
|
+
let lstatErr = null
|
|
76
|
+
try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch (err) { lstatErr = err }
|
|
21
77
|
if (entry?.isSymbolicLink()) {
|
|
22
|
-
|
|
78
|
+
try {
|
|
79
|
+
unlinkSync(dir)
|
|
80
|
+
} catch {
|
|
81
|
+
try { rmdirSync(dir) } catch {
|
|
82
|
+
try { rmSync(dir, { recursive: true, force: true }) } catch {}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
23
85
|
return
|
|
24
86
|
}
|
|
25
|
-
if (!entry && !existsSync(dir)) return
|
|
87
|
+
if (!entry && !lstatErr && !existsSync(dir)) return
|
|
88
|
+
if (entry && !entry.isDirectory()) {
|
|
89
|
+
try {
|
|
90
|
+
rmSync(dir, { force: true })
|
|
91
|
+
return
|
|
92
|
+
} catch {}
|
|
93
|
+
}
|
|
26
94
|
try {
|
|
27
|
-
rmSync(dir, { recursive: true, force: true
|
|
95
|
+
rmSync(dir, { recursive: true, force: true })
|
|
28
96
|
return
|
|
29
97
|
} catch (err) {
|
|
30
|
-
if (
|
|
98
|
+
if (allowTrash && quarantineRoot && !isSameOrInsidePath(dir, quarantineRoot) && !isSameOrInsidePath(quarantineRoot, dir)) {
|
|
31
99
|
try {
|
|
32
|
-
|
|
33
|
-
rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
|
|
100
|
+
scheduleTrashSweep(moveToTrash(dir, quarantineRoot))
|
|
34
101
|
return
|
|
35
102
|
} catch {}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const trash = `${dir}.trash-${Date.now()}`
|
|
43
|
-
renameSync(dir, trash)
|
|
103
|
+
}
|
|
104
|
+
if (process.platform === 'win32') {
|
|
105
|
+
// Never let attrib.exe or rd traverse into a junction target outside `dir`.
|
|
106
|
+
unlinkReparsePointsSync(dir)
|
|
107
|
+
const isPermErr = err?.code === 'EPERM' || err?.code === 'EACCES'
|
|
108
|
+
if (isPermErr) {
|
|
44
109
|
try {
|
|
45
|
-
execFileSync('
|
|
110
|
+
execFileSync('attrib.exe', ['-r', '-s', '-h', dir], { stdio: 'ignore', windowsHide: true })
|
|
46
111
|
} catch {}
|
|
47
|
-
|
|
48
|
-
|
|
112
|
+
try {
|
|
113
|
+
execFileSync('attrib.exe', ['-r', '-s', '-h', join(dir, '*'), '/s', '/d'], { stdio: 'ignore', windowsHide: true })
|
|
114
|
+
rmSync(dir, { recursive: true, force: true })
|
|
115
|
+
return
|
|
116
|
+
} catch {}
|
|
117
|
+
}
|
|
118
|
+
if (err?.code !== 'EBUSY') {
|
|
119
|
+
try {
|
|
120
|
+
execFileSync('cmd.exe', ['/d', '/s', '/c', `rd /s /q "${dir}"`], { stdio: 'ignore', windowsHide: true })
|
|
121
|
+
let remaining = null
|
|
122
|
+
try { remaining = lstatSync(dir, { throwIfNoEntry: false }) } catch { remaining = true }
|
|
123
|
+
if (!remaining) return
|
|
124
|
+
} catch {}
|
|
125
|
+
}
|
|
49
126
|
}
|
|
50
127
|
}
|
|
51
128
|
}
|
|
52
129
|
|
|
53
130
|
/** Remove managed files before forgetting the record needed to retry cleanup. */
|
|
54
|
-
export function removeManagedDir(dir) {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
131
|
+
export function removeManagedDir(dir, { allowTrash = false, deferCleanup = false } = {}) {
|
|
132
|
+
if (deferCleanup) {
|
|
133
|
+
try {
|
|
134
|
+
if (!lstatSync(dir, { throwIfNoEntry: false })) return
|
|
135
|
+
// Detach the checkout as a unit. An open Windows handle can block the
|
|
136
|
+
// move, in which case the caller retries while the checkout stays intact.
|
|
137
|
+
const quarantineRoot = trashRoot()
|
|
138
|
+
const trashed = moveToTrash(dir, quarantineRoot)
|
|
139
|
+
void rm(trashed, { recursive: true, force: true }).then(
|
|
140
|
+
() => { try { rmdirSync(quarantineRoot) } catch {} },
|
|
141
|
+
() => scheduleTrashSweep(trashed),
|
|
142
|
+
)
|
|
143
|
+
return
|
|
144
|
+
} catch (cause) {
|
|
145
|
+
throw Object.assign(new Error(`无法清理目录:${dir}`, { cause }), {
|
|
146
|
+
code: cause.code,
|
|
147
|
+
syscall: cause.syscall,
|
|
148
|
+
path: dir,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
safeRmDir(dir, { allowTrash })
|
|
153
|
+
let remaining = null
|
|
154
|
+
let lstatErr = null
|
|
155
|
+
try {
|
|
156
|
+
remaining = lstatSync(dir, { throwIfNoEntry: false })
|
|
157
|
+
} catch (err) {
|
|
158
|
+
lstatErr = err
|
|
159
|
+
}
|
|
160
|
+
if (remaining || lstatErr) {
|
|
161
|
+
throw Object.assign(new Error(`无法清理目录:${dir}`), {
|
|
162
|
+
code: lstatErr?.code || 'EBUSY',
|
|
163
|
+
syscall: lstatErr?.syscall || 'rmdir',
|
|
164
|
+
path: dir,
|
|
165
|
+
})
|
|
58
166
|
}
|
|
59
167
|
}
|
|
60
168
|
|
|
61
169
|
let STATE_CACHE = null
|
|
170
|
+
let STATE_CACHE_PATH = ''
|
|
62
171
|
let STATE_CACHE_MTIME = 0
|
|
172
|
+
let STATE_CACHE_SIZE = -1
|
|
173
|
+
let STATE_REVISION = 0
|
|
174
|
+
|
|
175
|
+
export function stateRevision() {
|
|
176
|
+
return STATE_REVISION
|
|
177
|
+
}
|
|
63
178
|
|
|
64
179
|
export const ROOT_DIR_NAME = 'universal-plugin-hub'
|
|
65
180
|
|
|
@@ -87,11 +202,66 @@ export function installedDir(name) {
|
|
|
87
202
|
return join(marketRoot(), 'installed', name)
|
|
88
203
|
}
|
|
89
204
|
|
|
205
|
+
/** Persistent per-plugin data directory (${PLUGIN_DATA} / ${CLAUDE_PLUGIN_DATA}). */
|
|
206
|
+
export function pluginDataDir(name) {
|
|
207
|
+
return join(marketRoot(), 'plugin-data', name)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Compiled normalized JSON hook file used when hooks need compilation/expansion. */
|
|
211
|
+
export function compiledHooksPath(name) {
|
|
212
|
+
return join(marketRoot(), 'compiled-hooks', `${name}.json`)
|
|
213
|
+
}
|
|
214
|
+
|
|
90
215
|
/** Original copies of skills imported directly into the Skills tab. */
|
|
91
216
|
export function uploadedSkillsDir() {
|
|
92
217
|
return join(marketRoot(), 'uploaded')
|
|
93
218
|
}
|
|
94
219
|
|
|
220
|
+
export function trashRoot() {
|
|
221
|
+
return join(marketRoot(), '.trash')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function sweepTrash() {
|
|
225
|
+
for (const trashed of Array.from(PENDING_TRASH_PATHS)) {
|
|
226
|
+
try { safeRmDir(trashed, { allowTrash: false }) } catch {}
|
|
227
|
+
try {
|
|
228
|
+
if (!lstatSync(trashed, { throwIfNoEntry: false })) {
|
|
229
|
+
PENDING_TRASH_PATHS.delete(trashed)
|
|
230
|
+
const parent = dirname(trashed)
|
|
231
|
+
try { if (readdirSync(parent).length === 0) rmdirSync(parent) } catch {}
|
|
232
|
+
}
|
|
233
|
+
} catch {}
|
|
234
|
+
}
|
|
235
|
+
const root = trashRoot()
|
|
236
|
+
if (existsSync(root)) {
|
|
237
|
+
try {
|
|
238
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
239
|
+
try { safeRmDir(join(root, entry.name), { allowTrash: false }) } catch {}
|
|
240
|
+
}
|
|
241
|
+
if (readdirSync(root).length === 0) {
|
|
242
|
+
try { rmdirSync(root) } catch {}
|
|
243
|
+
}
|
|
244
|
+
} catch {}
|
|
245
|
+
}
|
|
246
|
+
const legacyParents = [
|
|
247
|
+
dshSkillsDir(),
|
|
248
|
+
join(marketRoot(), 'installed'),
|
|
249
|
+
join(marketRoot(), 'market'),
|
|
250
|
+
join(marketRoot(), 'plugin-data'),
|
|
251
|
+
uploadedSkillsDir(),
|
|
252
|
+
]
|
|
253
|
+
for (const parent of legacyParents) {
|
|
254
|
+
if (!existsSync(parent)) continue
|
|
255
|
+
try {
|
|
256
|
+
for (const entry of readdirSync(parent, { withFileTypes: true })) {
|
|
257
|
+
if (/\.trash-\d+$/.test(entry.name)) {
|
|
258
|
+
try { safeRmDir(join(parent, entry.name), { allowTrash: false }) } catch {}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
} catch {}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
95
265
|
/** Default state: the built-in Anthropic source. */
|
|
96
266
|
export function defaultState() {
|
|
97
267
|
return {
|
|
@@ -109,18 +279,29 @@ export function defaultState() {
|
|
|
109
279
|
}
|
|
110
280
|
}
|
|
111
281
|
|
|
112
|
-
/** Read state.json with 0ms in-memory cache and mtime invalidation. */
|
|
282
|
+
/** Read state.json with 0ms in-memory cache and path + mtime + size invalidation. */
|
|
113
283
|
export function readState() {
|
|
114
284
|
const path = statePath()
|
|
115
285
|
if (!existsSync(path)) {
|
|
286
|
+
if (STATE_CACHE_PATH === path) {
|
|
287
|
+
STATE_CACHE = null
|
|
288
|
+
STATE_CACHE_PATH = ''
|
|
289
|
+
STATE_CACHE_MTIME = 0
|
|
290
|
+
STATE_CACHE_SIZE = -1
|
|
291
|
+
}
|
|
116
292
|
const fresh = defaultState()
|
|
117
293
|
writeState(fresh)
|
|
118
|
-
return fresh
|
|
294
|
+
return structuredClone(fresh)
|
|
119
295
|
}
|
|
120
296
|
try {
|
|
121
297
|
const stat = statSync(path)
|
|
122
|
-
if (
|
|
123
|
-
|
|
298
|
+
if (
|
|
299
|
+
STATE_CACHE &&
|
|
300
|
+
STATE_CACHE_PATH === path &&
|
|
301
|
+
STATE_CACHE_MTIME === stat.mtimeMs &&
|
|
302
|
+
STATE_CACHE_SIZE === stat.size
|
|
303
|
+
) {
|
|
304
|
+
return structuredClone(STATE_CACHE)
|
|
124
305
|
}
|
|
125
306
|
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
126
307
|
const base = defaultState()
|
|
@@ -131,9 +312,17 @@ export function readState() {
|
|
|
131
312
|
plugins: Array.isArray(parsed.plugins) ? parsed.plugins : [],
|
|
132
313
|
}
|
|
133
314
|
STATE_CACHE = merged
|
|
315
|
+
STATE_CACHE_PATH = path
|
|
134
316
|
STATE_CACHE_MTIME = stat.mtimeMs
|
|
135
|
-
|
|
317
|
+
STATE_CACHE_SIZE = stat.size
|
|
318
|
+
return structuredClone(merged)
|
|
136
319
|
} catch {
|
|
320
|
+
if (STATE_CACHE_PATH === path) {
|
|
321
|
+
STATE_CACHE = null
|
|
322
|
+
STATE_CACHE_PATH = ''
|
|
323
|
+
STATE_CACHE_MTIME = 0
|
|
324
|
+
STATE_CACHE_SIZE = -1
|
|
325
|
+
}
|
|
137
326
|
return defaultState()
|
|
138
327
|
}
|
|
139
328
|
}
|
|
@@ -141,14 +330,21 @@ export function readState() {
|
|
|
141
330
|
export function writeState(state) {
|
|
142
331
|
const file = statePath()
|
|
143
332
|
mkdirSync(dirname(file), { recursive: true })
|
|
144
|
-
const
|
|
145
|
-
|
|
333
|
+
const seq = (STATE_TMP_SEQ = (STATE_TMP_SEQ + 1) & 0xffffff).toString(36)
|
|
334
|
+
const tmp = join(dirname(file), `.state.${process.pid}.${Date.now().toString(36)}.${seq}.tmp`)
|
|
335
|
+
const snapshot = structuredClone(state)
|
|
336
|
+
writeFileSync(tmp, JSON.stringify(snapshot, null, 2), 'utf8')
|
|
146
337
|
renameSync(tmp, file)
|
|
147
|
-
|
|
338
|
+
STATE_REVISION += 1
|
|
339
|
+
STATE_CACHE = snapshot
|
|
340
|
+
STATE_CACHE_PATH = file
|
|
148
341
|
try {
|
|
149
|
-
|
|
342
|
+
const stat = statSync(file)
|
|
343
|
+
STATE_CACHE_MTIME = stat.mtimeMs
|
|
344
|
+
STATE_CACHE_SIZE = stat.size
|
|
150
345
|
} catch {
|
|
151
346
|
STATE_CACHE_MTIME = Date.now()
|
|
347
|
+
STATE_CACHE_SIZE = -1
|
|
152
348
|
}
|
|
153
349
|
}
|
|
154
350
|
|
|
@@ -213,12 +409,18 @@ export function parseGitUrl(url) {
|
|
|
213
409
|
return null
|
|
214
410
|
}
|
|
215
411
|
|
|
216
|
-
|
|
217
|
-
|
|
412
|
+
function formatMarketLabel(name) {
|
|
413
|
+
// Keep spaced labels intact and preserve casing within each slug word.
|
|
414
|
+
if (/\s/.test(name)) return name
|
|
415
|
+
return name.replace(/[-_]+/g, ' ').replace(/(^| )([a-z])/g, (_, space, initial) => space + initial.toUpperCase())
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Prefer the market title and fall back to a readable Git repository name. */
|
|
419
|
+
export function suggestSourceName(url, marketName) {
|
|
218
420
|
const parsed = parseGitUrl(url)
|
|
219
421
|
if (!parsed) {
|
|
220
422
|
const raw = String(url).split('/').pop()?.replace(/\.git$/, '') || 'Custom'
|
|
221
|
-
return
|
|
423
|
+
return formatMarketLabel(marketName || raw)
|
|
222
424
|
}
|
|
223
425
|
const { owner, repo } = parsed
|
|
224
426
|
const ownerLower = (owner || '').toLowerCase()
|
|
@@ -229,10 +431,12 @@ export function suggestSourceName(url) {
|
|
|
229
431
|
if (repoLower === 'claude-plugins-community') return 'Community'
|
|
230
432
|
|
|
231
433
|
const genericRepoNames = new Set([
|
|
232
|
-
'skills', 'plugins', 'agents', 'tools', 'marketplace', 'hub',
|
|
233
|
-
'claude-skills', 'claude-plugins', 'claude-agents', 'dsh-plugins', 'extensions', 'packages',
|
|
434
|
+
'skill', 'skills', 'plugin', 'plugins', 'agent', 'agents', 'tool', 'tools', 'marketplace', 'hub',
|
|
435
|
+
'claude-skills', 'claude-plugins', 'claude-agents', 'dsh-plugins', 'extensions', 'packages', 'repo', 'repository', 'custom',
|
|
234
436
|
])
|
|
235
437
|
|
|
438
|
+
if (marketName && !genericRepoNames.has(marketName.toLowerCase())) return formatMarketLabel(marketName)
|
|
439
|
+
|
|
236
440
|
// If repo is generic (e.g. "skills", "plugins", "tools"), use capitalized owner (e.g. Mattpocock)
|
|
237
441
|
if (genericRepoNames.has(repoLower) && owner) {
|
|
238
442
|
return owner.charAt(0).toUpperCase() + owner.slice(1)
|
|
@@ -242,7 +446,10 @@ export function suggestSourceName(url) {
|
|
|
242
446
|
.replace(/^(claude|dsh|anthropic)[-_]?(plugins?)?[-_]?/i, '')
|
|
243
447
|
.replace(/[-_]?(plugins?|skills?|agents?|official|marketplace)$/i, '')
|
|
244
448
|
const name = simplified || repo
|
|
245
|
-
|
|
449
|
+
if (genericRepoNames.has(name.toLowerCase()) && owner) {
|
|
450
|
+
return owner.charAt(0).toUpperCase() + owner.slice(1)
|
|
451
|
+
}
|
|
452
|
+
return formatMarketLabel(name)
|
|
246
453
|
}
|
|
247
454
|
|
|
248
455
|
/** Find an existing source that duplicates the given id, normalized URL, or git repo. */
|
|
@@ -276,3 +483,14 @@ export function findDuplicateSource(state, id, url) {
|
|
|
276
483
|
return null
|
|
277
484
|
}
|
|
278
485
|
|
|
486
|
+
/**
|
|
487
|
+
* Read an optional Cordis service without tripping its inject proxy check
|
|
488
|
+
* (`ctx.get` returns `undefined` when missing or inactive), falling back to
|
|
489
|
+
* direct property lookup only on plain mock objects without `.get`.
|
|
490
|
+
*/
|
|
491
|
+
export function resolveOptionalService(ctx, name) {
|
|
492
|
+
if (!ctx || typeof name !== 'string') return undefined
|
|
493
|
+
if (typeof ctx.get === 'function') return ctx.get(name)
|
|
494
|
+
return ctx[name]
|
|
495
|
+
}
|
|
496
|
+
|