universal-plugin-hub 1.0.30 → 1.0.45

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/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "title": "Universal Plugin Hub",
4
4
  "displayName": "Universal Plugin Hub",
5
5
  "description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加 Git 插件源和 marketplace、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
- "version": "1.0.30",
6
+ "version": "1.0.45",
7
7
  "engines": {
8
8
  "dsh": ">=0.1.5-rc.1"
9
9
  },
package/src/icons.js CHANGED
@@ -1,4 +1,4 @@
1
- import { statSync, realpathSync, readFileSync } from 'node:fs'
1
+ import { statSync, realpathSync, readFileSync, readdirSync, openSync, readSync, closeSync } from 'node:fs'
2
2
  import { mkdir, readFile, writeFile, stat } from 'node:fs/promises'
3
3
  import { join, relative, isAbsolute, posix } from 'node:path'
4
4
  import { createHash } from 'node:crypto'
@@ -38,10 +38,165 @@ export function readLocalIcon(root, path) {
38
38
  return { buffer, contentType }
39
39
  }
40
40
 
41
- /** Carry manifest assets through marketplace rows without exposing filesystem paths. */
41
+ // Claude's plugin manifest has no icon field and marketplace entries do not
42
+ // carry one either, so a plugin's artwork can only be found on disk. Matching a
43
+ // fixed list of nine filenames missed most of it, which sent those rows to the
44
+ // network for the author's GitHub avatar: the wrong picture, and a round trip
45
+ // on every cold start.
46
+ const ICON_FILE = /\.(?:svg|png|webp|jpe?g|ico)$/i
47
+ // Names that promise artwork, names that promise a different kind of picture.
48
+ const ICON_STRONG = /(?:^|[-_. ])(?:app[-_]?icon|icon|glyph|favicon|emblem)(?:[-_. ]|$)/i
49
+ const ICON_WEAK = /(?:^|[-_. ])(?:logo|brand|avatar|mark)(?:[-_. ]|$)/i
50
+ // Anchored like the two patterns above: an unanchored substring test rejected
51
+ // `heroku-icon.png` on "hero" and `photon-logo.png` on "photo", which is the
52
+ // very failure this discovery is meant to remove.
53
+ const ICON_NOISE = /(?:^|[-_. ])(?:screenshots?|screen[-_]?shots?|examples?|previews?|banners?|covers?|thumbs?|thumbnails?|hero|demo|readme|illustrations?|diagrams?|charts?|backgrounds?|wallpapers?|social|samples?|fixtures?|mocks?|placeholders?|spinners?|loaders?|sprites?|swatches?|captures?|photos?)(?:[-_. ]|$)/i
54
+ const ICON_SKIP_DIRS = new Set([
55
+ 'node_modules', '.git', '.github', 'skills', 'skill', 'commands', 'command', 'agents', 'hooks',
56
+ 'docs', 'doc', 'tests', 'test', '__tests__', 'scripts', 'src', 'lib', 'dist', 'build',
57
+ 'examples', 'templates', 'locales', 'i18n',
58
+ ])
59
+
60
+ /**
61
+ * Pixel size read from a file header.
62
+ *
63
+ * Cheap enough to run on every candidate, and it is the only signal that
64
+ * separates an icon from a banner or a screenshot regardless of its name.
65
+ *
66
+ * The format is decided by `imageContentType` so there is one answer to "what
67
+ * is this file" — the PNG branch below only reads fields, it does not re-sniff
68
+ * magic numbers. Note the PNG branch needs a full 24-byte IHDR, which is
69
+ * checked before reading.
70
+ */
71
+ function imageSize(file) {
72
+ let handle
73
+ try {
74
+ handle = openSync(file, 'r')
75
+ const head = Buffer.alloc(4096)
76
+ const read = readSync(handle, head, 0, head.length, 0)
77
+ const bytes = head.subarray(0, read)
78
+ const kind = imageContentType(bytes)
79
+ if (kind === 'image/png') {
80
+ if (bytes.length < 24) return null
81
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
82
+ }
83
+ if (kind !== 'image/svg+xml') return null
84
+ const svg = bytes.toString('utf8').match(/<svg\b[^>]*>/i)
85
+ if (!svg) return null
86
+ const attribute = (name) => {
87
+ const found = svg[0].match(new RegExp(`\\b${name}\\s*=\\s*["']\\s*([0-9.]+)`, 'i'))
88
+ return found ? Number(found[1]) : null
89
+ }
90
+ const width = attribute('width')
91
+ const height = attribute('height')
92
+ if (width > 0 && height > 0) return { width, height }
93
+ const box = svg[0].match(/\bviewBox\s*=\s*["']\s*([-\d.]+)[ ,]+([-\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)/i)
94
+ if (box && Number(box[3]) > 0 && Number(box[4]) > 0) return { width: Number(box[3]), height: Number(box[4]) }
95
+ } catch {
96
+ } finally {
97
+ if (handle !== undefined) try { closeSync(handle) } catch {}
98
+ }
99
+ return null
100
+ }
101
+
102
+ /**
103
+ * Icon files a plugin ships without declaring, best candidate first.
104
+ *
105
+ * Ranked the way a desktop picks an application icon: artwork by name first,
106
+ * then squareness and size, then how close the file sits to the plugin root.
107
+ * A file needs at least one naming signal, so a passing diagram cannot win.
108
+ */
109
+ function discoverIconFiles(dir, pluginName) {
110
+ if (!dir) return []
111
+ const key = String(pluginName || '').replace(/[^a-z0-9]/gi, '').toLowerCase()
112
+ const found = []
113
+ let visited = 0
114
+
115
+ const walk = (relative, depth) => {
116
+ if (depth > 2 || visited > 400) return
117
+ let entries
118
+ try { entries = readdirSync(relative ? join(dir, relative) : dir, { withFileTypes: true }) } catch { return }
119
+ for (const entry of entries) {
120
+ const path = relative ? `${relative}/${entry.name}` : entry.name
121
+ if (entry.isDirectory()) {
122
+ if (!ICON_SKIP_DIRS.has(entry.name.toLowerCase())) walk(path, depth + 1)
123
+ continue
124
+ }
125
+ visited++
126
+ if (!ICON_FILE.test(entry.name) || ICON_NOISE.test(entry.name)) continue
127
+
128
+ const base = entry.name.replace(/\.[^.]+$/, '').toLowerCase()
129
+ const flat = base.replace(/[^a-z0-9]/g, '')
130
+ let score = 0
131
+ if (ICON_STRONG.test(base)) score += 12
132
+ else if (ICON_WEAK.test(base)) score += 8
133
+ if (key && (flat === key || (flat.length >= 3 && key.startsWith(flat)) || (key.length >= 3 && flat.startsWith(key)))) score += 9
134
+ if (score === 0) continue
135
+
136
+ const size = imageSize(join(dir, path))
137
+ // A portrait mark is a logotype, not an app tile: it is authored to sit on
138
+ // the publisher's own background, so drawing it into our rounded container
139
+ // shows a bare glyph over whatever our well is. Exa's 151x182 blue line
140
+ // art looked like a blank blue tile this way. It is kept — dropping it
141
+ // only moved the problem to a GitHub avatar — but flagged so it is tried
142
+ // after the brand artwork the client already knows.
143
+ const portrait = !!size && Math.abs(size.width - size.height) / Math.max(size.width, size.height) > 0.15
144
+ if (size && !portrait) {
145
+ // An icon is square, and a 4:1 file is a banner however it is named.
146
+ score += 6
147
+ const edge = Math.min(size.width, size.height)
148
+ if (edge >= 96) score += 3
149
+ else if (edge < 32) score -= 14
150
+ // A file too small to read is not artwork at any shape.
151
+ if (edge < 24) score -= 20
152
+ }
153
+ score += Math.max(0, 3 - depth)
154
+ if (/\.svg$/i.test(entry.name)) score += 1
155
+ found.push({ path, score, dark: /dark/i.test(base), portrait })
156
+ }
157
+ }
158
+
159
+ walk('', 0)
160
+ return found.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))
161
+ }
162
+
163
+ // A plugin-local icon is at most a few hundred KB and sits on a local disk, so
164
+ // carrying its bytes in the row costs one decode and removes the request the
165
+ // first paint would otherwise wait on. Remote avatars (GitHub, favicons) stay
166
+ // behind the proxy: they are not ours to inline and would be far too big.
167
+ //
168
+ // The inline set is a budget, not a rule: every icon carried in the list is
169
+ // paid again on each /state fetch, and the card renders at 38px. At 12KB the
170
+ // whole marketplace payload stays under 1MB and 67 rows still paint with no
171
+ // request; the rest keep the served URL, which is a local disk read.
172
+
173
+ const INLINE_LIMIT = 12 * 1024
174
+
175
+ /** A local file's bytes as a data URL, or null when it is too big or unreadable. */
176
+ function inlineFile(file) {
177
+ try {
178
+ const info = statSync(file)
179
+ if (!info.isFile() || info.size > INLINE_LIMIT) return null
180
+ const buffer = readFileSync(file)
181
+ const contentType = imageContentType(buffer)
182
+ return contentType ? `data:${contentType};base64,${buffer.toString('base64')}` : null
183
+ } catch { return null }
184
+ }
185
+
186
+ /**
187
+ * Carry manifest assets through marketplace rows without exposing filesystem paths.
188
+ *
189
+ * Local artwork is inlined as a data URL so a cold start paints it in the same
190
+ * frame as the row itself. Rows still carry a `/api/plugin-icon` URL for the
191
+ * full-size copy and for the installed-plugin route, but the first candidate is
192
+ * always something the client can draw without a round trip.
193
+ */
42
194
  export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
43
195
  const ui = meta?.interface || {}
44
196
  const proxy = (url) => `/universal-plugin-hub/api/icon?v=2&u=${encodeURIComponent(url)}`
197
+ // Local files are stat'd once here and the same File is reused for the inline
198
+ // copy, so discovering artwork and inlining it is one pass over the disk.
199
+ const files = new Map()
45
200
  const toUrl = (value) => {
46
201
  if (typeof value !== 'string' || !value.trim()) return null
47
202
  if (/^https?:\/\//i.test(value)) return proxy(value)
@@ -51,7 +206,9 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
51
206
  const file = pluginPath(dir, value)
52
207
  const info = statSync(file)
53
208
  if (!info.isFile() || info.size > MAX_BYTES) return null
54
- return `/universal-plugin-hub/api/plugin-icon?sourceId=${encodeURIComponent(sourceId)}&name=${encodeURIComponent(name)}&path=${encodeURIComponent(value)}&v=${info.mtimeMs}-${info.size}`
209
+ const url = `/universal-plugin-hub/api/plugin-icon?sourceId=${encodeURIComponent(sourceId)}&name=${encodeURIComponent(name)}&path=${encodeURIComponent(value)}&v=${info.mtimeMs}-${info.size}`
210
+ files.set(url, file)
211
+ return url
55
212
  } catch { return null }
56
213
  }
57
214
  const repo = source?.url?.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+?)(?:\.git)?\/?$/i)
@@ -65,10 +222,35 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
65
222
  }
66
223
  const common = [ui.composerIcon, ui.icon, ui.iconSmall, ui.iconLarge, ui.logo, meta?.icon, meta?.iconUrl, meta?.logo]
67
224
  const values = (theme) => common.flatMap((v) => typeof v === 'object' && v ? [v[theme], v.default, v.url, v.src, v[theme === 'dark' ? 'light' : 'dark']] : [v])
68
- const defaults = dir ? ['assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/codex-icon.png', 'assets/logo.png', 'icon.svg', 'logo.svg', 'icon.png', 'logo.png'] : []
69
- const light = [...new Set([ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...defaults].map(toUrl).filter(Boolean))]
70
- const dark = [...new Set([ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...defaults].map(toUrl).filter(Boolean))]
71
- return { light, dark }
225
+ const found = discoverIconFiles(dir, name)
226
+ // Portrait artwork is not a tile candidate: it leaves the normal ranking
227
+ // entirely and is reported separately, so nothing can arrange it back into
228
+ // the lead position.
229
+ const tiles = found.filter((f) => !f.portrait)
230
+ const plain = tiles.filter((f) => !f.dark).map((f) => f.path)
231
+ // A dark-mode variant is a bonus, not a requirement: a plugin that ships only
232
+ // one dark-named logo still needs a light-mode picture.
233
+ const shade = tiles.filter((f) => f.dark).map((f) => f.path)
234
+ const portrait = found.filter((f) => f.portrait).map((f) => f.path)
235
+ const build = (theme) => {
236
+ const declared = theme === 'dark'
237
+ ? [ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...shade, ...plain]
238
+ : [ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...plain, ...shade]
239
+ const urls = [...new Set(declared.map(toUrl).filter(Boolean))]
240
+ // The inline copy leads, so the first candidate needs no request at all.
241
+ // Only the local files this call already stat'd are considered; a remote
242
+ // candidate never reaches the disk and so can never be inlined.
243
+ const inline = urls.map((url) => files.get(url) && inlineFile(files.get(url))).find(Boolean)
244
+ return inline ? [inline, ...urls.filter((url) => url !== inline)] : urls
245
+ }
246
+ const served = (paths) => [...new Set(paths.map(toUrl).filter(Boolean))]
247
+ // Reported apart from the tile candidates so the client can try them after
248
+ // the brand artwork it knows about, instead of leading every row with them.
249
+ return {
250
+ light: build('light'),
251
+ dark: build('dark'),
252
+ portrait: { light: served(portrait), dark: served(portrait) },
253
+ }
72
254
  }
73
255
 
74
256
  function remember(key, value) {
@@ -77,6 +259,29 @@ function remember(key, value) {
77
259
  return value
78
260
  }
79
261
 
262
+ function iconCacheFile(url) {
263
+ return join(marketRoot(), 'icons', `icon_${createHash('md5').update(url).digest('hex')}.bin`)
264
+ }
265
+
266
+ /** Fetch one icon from upstream and store it. Throws so callers can decide. */
267
+ async function downloadIcon(url, file) {
268
+ const response = await fetch(url, { signal: AbortSignal.timeout(4000), headers: { Accept: 'image/avif,image/webp,image/svg+xml,image/*;q=0.8' } })
269
+ if (!response.ok) throw new Error(`Icon request failed: ${response.status}`)
270
+ if (Number(response.headers.get('content-length')) > MAX_BYTES) { await response.body?.cancel(); throw new Error('Icon too large') }
271
+ const chunks = []
272
+ let size = 0
273
+ for await (const chunk of response.body) {
274
+ size += chunk.length
275
+ if (size > MAX_BYTES) throw new Error('Icon too large')
276
+ chunks.push(chunk)
277
+ }
278
+ const buffer = Buffer.concat(chunks)
279
+ const contentType = imageContentType(buffer)
280
+ if (!contentType) throw new Error('Unsupported icon content')
281
+ try { await mkdir(join(marketRoot(), 'icons'), { recursive: true }); await writeFile(file, buffer) } catch {}
282
+ return { buffer, contentType }
283
+ }
284
+
80
285
  /** Share concurrent loads, cache successful images, and briefly suppress failed URLs. */
81
286
  export async function getOrFetchIcon(url) {
82
287
  if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) throw new Error('Invalid icon URL')
@@ -93,30 +298,34 @@ export async function getOrFetchIcon(url) {
93
298
  if (failures.get(url) > Date.now()) throw new Error('Icon temporarily unavailable')
94
299
  if (pending.has(url)) return pending.get(url)
95
300
  const task = (async () => {
96
- const file = join(marketRoot(), 'icons', `icon_${createHash('md5').update(url).digest('hex')}.bin`)
301
+ const file = iconCacheFile(url)
302
+ let expired = null
97
303
  try {
98
304
  const info = await stat(file)
99
- if (info.size <= MAX_BYTES && Date.now() - info.mtimeMs < CACHE_TTL) {
305
+ if (info.size <= MAX_BYTES) {
100
306
  const buffer = await readFile(file)
101
307
  const contentType = imageContentType(buffer)
102
- if (contentType) return remember(url, { buffer, contentType })
308
+ if (contentType) {
309
+ if (Date.now() - info.mtimeMs < CACHE_TTL) return remember(url, { buffer, contentType })
310
+ expired = { buffer, contentType }
311
+ }
103
312
  }
104
313
  } catch {}
105
- const response = await fetch(url, { signal: AbortSignal.timeout(4000), headers: { Accept: 'image/avif,image/webp,image/svg+xml,image/*;q=0.8' } })
106
- if (!response.ok) throw new Error(`Icon request failed: ${response.status}`)
107
- if (Number(response.headers.get('content-length')) > MAX_BYTES) { await response.body?.cancel(); throw new Error('Icon too large') }
108
- const chunks = []
109
- let size = 0
110
- for await (const chunk of response.body) {
111
- size += chunk.length
112
- if (size > MAX_BYTES) throw new Error('Icon too large')
113
- chunks.push(chunk)
314
+ // Stale-while-revalidate: an expired copy is still the right picture, so
315
+ // hand it back immediately and refresh behind the scenes. Waiting on the
316
+ // network here is what made those icons appear to reload on every restart —
317
+ // and a failed refresh must never turn a usable icon into a 502.
318
+ if (expired) {
319
+ // Record the failure in the same cooldown the foreground path uses, or a
320
+ // permanently dead URL launches a fresh 4s fetch on every request while
321
+ // continuing to serve the stale bytes.
322
+ downloadIcon(url, file).catch(() => {
323
+ if (failures.size >= 256) failures.delete(failures.keys().next().value)
324
+ failures.set(url, Date.now() + 60_000)
325
+ })
326
+ return remember(url, expired)
114
327
  }
115
- const buffer = Buffer.concat(chunks)
116
- const contentType = imageContentType(buffer)
117
- if (!contentType) throw new Error('Unsupported icon content')
118
- try { await mkdir(join(marketRoot(), 'icons'), { recursive: true }); await writeFile(file, buffer) } catch {}
119
- return remember(url, { buffer, contentType })
328
+ return remember(url, await downloadIcon(url, file))
120
329
  })()
121
330
  pending.set(url, task)
122
331
  try { return await task } catch (error) {
package/src/index.js CHANGED
@@ -10,12 +10,48 @@ import { mountRoutes } from './routes.js'
10
10
  import { cancelAllOAuthVerifications } from './oauth.js'
11
11
  import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
12
12
  import { createSkillsManager } from './skills.js'
13
+ import { restoreUploadedSkills } from './skill-uploads.js'
14
+ import { createProfileApplicator } from './runtime.js'
13
15
  import { createRequire } from 'node:module'
14
16
  import { join } from 'node:path'
15
17
 
16
18
  export const name = 'universal-plugin-hub'
17
19
 
18
20
  export function apply(ctx) {
21
+ // The running host knows which profile it booted. Guessing from the
22
+ // filesystem writes patches into the wrong profile (e.g. a custom profile
23
+ // name would land in `web`), and the change then never loads.
24
+ // `profileContext` is provided asynchronously, so it must be injected —
25
+ // reading it eagerly here returns undefined on a real host.
26
+ // Everything below that resolves a profile path has to run *after* this, so
27
+ // it lives inside the injection rather than beside it.
28
+ let provisioned = Promise.resolve()
29
+ ctx.inject(['profileContext'], (hostCtx) => {
30
+ const name = hostCtx.profileContext?.name
31
+ if (typeof name === 'string' && name.trim()) process.env.DSH_PROFILE = name.trim()
32
+
33
+ // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
34
+ try {
35
+ restoreUploadedSkills()
36
+
37
+ syncAllInstalledSkillsToDsh()
38
+ } catch (err) {
39
+ ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
40
+ }
41
+
42
+ // Host packages disappear when a package manager re-resolves the profile
43
+ // (pnpm moves unrecognized packages to node_modules/.ignored), so repair
44
+ // them on every start instead of trusting a one-time install step.
45
+ // Detached on purpose: Cordis awaits whatever apply returns, and this does
46
+ // network probes and tarball extraction — the hub fiber must not wait on it.
47
+ // Exposed on the callback for tests that need to await it.
48
+ const provisioning = installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
49
+ ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
50
+ })
51
+ provisioned = provisioning
52
+ })
53
+ // Exposed only so a test can await the detached provisioning.
54
+ apply.provisioned = () => provisioned
19
55
  const skills = createSkillsManager()
20
56
  ctx.inject(['skills'], (hostCtx) => {
21
57
  hostCtx.effect(() => skills.attach(hostCtx.skills, () => {
@@ -37,23 +73,9 @@ export function apply(ctx) {
37
73
  }
38
74
  hostCtx.effect(() => skills.attachAgents(hostCtx, createScope), 'universal-plugin-hub: scoped skill switches')
39
75
  })
40
- // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
41
- try {
42
- syncAllInstalledSkillsToDsh()
43
- } catch (err) {
44
- ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
45
- }
46
-
47
- // Host packages disappear when a package manager re-resolves the profile
48
- // (pnpm moves unrecognized packages to node_modules/.ignored), so repair
49
- // them on every start instead of trusting a one-time install step.
50
- installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
51
- ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
52
- })
53
-
54
76
  ctx.inject(['webServer'], (hostCtx) => {
55
77
  hostCtx.effect(() => {
56
- const unmount = mountRoutes(hostCtx.webServer, skills)
78
+ const unmount = mountRoutes(hostCtx.webServer, skills, createProfileApplicator(ctx))
57
79
  return () => { unmount(); cancelAllOAuthVerifications() }
58
80
  }, 'universal-plugin-hub: http routes')
59
81
  })