universal-plugin-hub 1.0.50 → 1.3.1

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.50",
6
+ "version": "1.3.1",
7
7
  "engines": {
8
8
  "dsh": ">=0.1.5-rc.1"
9
9
  },
package/src/icons.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { statSync, realpathSync, readFileSync, readdirSync, openSync, readSync, closeSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
2
- import { mkdir, readFile, writeFile, stat } from 'node:fs/promises'
2
+ import { mkdir, readFile, writeFile, stat, realpath } from 'node:fs/promises'
3
3
  import { join, relative, isAbsolute, posix } from 'node:path'
4
4
  import { createHash } from 'node:crypto'
5
5
  import { PNG } from 'pngjs'
@@ -8,12 +8,43 @@ import { pluginPath } from './market.js'
8
8
 
9
9
  const MAX_BYTES = 2 * 1024 * 1024
10
10
  const CACHE_TTL = 7 * 24 * 60 * 60 * 1000
11
+ const MEMORY_LIMIT = 256
12
+ const PREVIEW_MEMORY_LIMIT = 512
13
+ const FAILURES_LIMIT = 256
14
+ const LOCAL_ICON_MEMORY_LIMIT = 512
15
+ const LOCAL_ICON_MAX_CACHE_BYTES = 256 * 1024
16
+ const LOCAL_ICON_MEMORY_MAX_BYTES = 32 * 1024 * 1024
11
17
  const memory = new Map()
12
18
  const pending = new Map()
13
19
  const failures = new Map()
20
+ const bundledCache = new Map()
21
+ const bundledPending = new Map()
22
+ const localIconMemory = new Map()
23
+ const localIconPending = new Map()
24
+ let localIconMemoryBytes = 0
14
25
  const bundledIconRoot = new URL('../assets/fluent-3d/', import.meta.url)
15
26
  const bundledIconFiles = new Map(Object.values(JSON.parse(readFileSync(new URL('manifest.json', bundledIconRoot), 'utf8')).icons).map(icon => [icon.url, icon.file]))
16
27
 
28
+ /** Compute a strong HTTP ETag from raw bytes. */
29
+ export function computeEtag(buffer) {
30
+ return `"${createHash('sha256').update(buffer).digest('base64url')}"`
31
+ }
32
+
33
+ /** Promote an existing Map entry to most-recently-used. */
34
+ export function touchLru(map, key, value) {
35
+ map.delete(key)
36
+ map.set(key, value)
37
+ return value
38
+ }
39
+
40
+ /** Insert or update a bounded Map entry with true LRU eviction. */
41
+ export function setLru(map, limit, key, value) {
42
+ if (map.has(key)) map.delete(key)
43
+ else if (map.size >= limit) map.delete(map.keys().next().value)
44
+ map.set(key, value)
45
+ return value
46
+ }
47
+
17
48
  export function imageContentType(buffer) {
18
49
  if (!buffer?.length) return null
19
50
  if (buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png'
@@ -39,6 +70,85 @@ export function readLocalIcon(root, path) {
39
70
  return { buffer, contentType }
40
71
  }
41
72
 
73
+ function deleteLocalIconEntry(key) {
74
+ const existing = localIconMemory.get(key)
75
+ if (!existing) return false
76
+ localIconMemoryBytes = Math.max(0, localIconMemoryBytes - existing.buffer.length)
77
+ return localIconMemory.delete(key)
78
+ }
79
+
80
+ function setLocalIconEntry(key, entry) {
81
+ const size = entry.buffer.length
82
+ if (size > LOCAL_ICON_MAX_CACHE_BYTES) return entry
83
+ deleteLocalIconEntry(key)
84
+ while (
85
+ localIconMemory.size > 0
86
+ && (localIconMemory.size >= LOCAL_ICON_MEMORY_LIMIT || localIconMemoryBytes + size > LOCAL_ICON_MEMORY_MAX_BYTES)
87
+ ) {
88
+ deleteLocalIconEntry(localIconMemory.keys().next().value)
89
+ }
90
+ localIconMemory.set(key, entry)
91
+ localIconMemoryBytes += size
92
+ return entry
93
+ }
94
+
95
+ /** Snapshot local icon cache entry count and retained bytes. */
96
+ export function getLocalIconCacheStats() {
97
+ return {
98
+ size: localIconMemory.size,
99
+ bytes: localIconMemoryBytes,
100
+ maxItemBytes: LOCAL_ICON_MAX_CACHE_BYTES,
101
+ maxTotalBytes: LOCAL_ICON_MEMORY_MAX_BYTES,
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Resolve, verify containment, and read/cache a local icon asynchronously.
107
+ * Always validates directory traversal containment and current file stat so
108
+ * removed or out-of-bounds files fail immediately instead of hitting cache.
109
+ * Skips caching payloads above 256 KB and caps total retained memory at 32 MB.
110
+ */
111
+ export async function readLocalIconCached(root, path, scopeParts = []) {
112
+ const candidate = pluginPath(root, path)
113
+ const [realRoot, realFile] = await Promise.all([realpath(root), realpath(candidate)])
114
+ const rel = relative(realRoot, realFile)
115
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) {
116
+ throw new Error('Icon is outside plugin directory')
117
+ }
118
+ const info = await stat(realFile)
119
+ if (!info.isFile() || info.size > MAX_BYTES) throw new Error('Invalid icon size')
120
+ const fileVersion = `${info.mtimeMs}-${info.size}`
121
+ const scopePrefix = JSON.stringify(scopeParts)
122
+ const key = `${scopePrefix}\0${realFile}\0${fileVersion}`
123
+ const hit = localIconMemory.get(key)
124
+ if (hit) return touchLru(localIconMemory, key, hit)
125
+ const inflight = localIconPending.get(key)
126
+ if (inflight) return inflight
127
+ const task = (async () => {
128
+ const buffer = await readFile(realFile)
129
+ const contentType = imageContentType(buffer)
130
+ if (!contentType) throw new Error('Unsupported icon content')
131
+ const entry = { buffer, contentType, etag: computeEtag(buffer), fileVersion }
132
+ return setLocalIconEntry(key, entry)
133
+ })()
134
+ localIconPending.set(key, task)
135
+ try { return await task } finally { localIconPending.delete(key) }
136
+ }
137
+
138
+ /** Drop cached local icon bytes for one sourceId (or all entries when omitted). */
139
+ export function invalidateLocalIconCache(sourceId) {
140
+ if (!sourceId) {
141
+ localIconMemory.clear()
142
+ localIconMemoryBytes = 0
143
+ return
144
+ }
145
+ const prefix = JSON.stringify([sourceId])
146
+ const head = prefix.slice(0, -1) + ','
147
+ for (const key of [...localIconMemory.keys()]) {
148
+ if (key.startsWith(head)) deleteLocalIconEntry(key)
149
+ }
150
+ }
151
+
42
152
  // Claude's plugin manifest has no icon field and marketplace entries do not
43
153
  // carry one either, so a plugin's artwork can only be found on disk. Matching a
44
154
  // fixed list of nine filenames missed most of it, which sent those rows to the
@@ -173,6 +283,7 @@ const PREVIEW_LIMIT = 64 * 1024
173
283
  // Decoding runs synchronously inside catalog parsing, once per row, so the
174
284
  // bound has to cover the decode itself and not just the file size.
175
285
  const PREVIEW_MAX_PIXELS = 262144
286
+ const LOCAL_PREVIEW_MAX_PIXELS = 1024 * 1024
176
287
  const PREVIEWS_DIR = 'previews'
177
288
  const PREVIEW_CACHE_KEEP = 200
178
289
  const previewMemory = new Map()
@@ -189,14 +300,34 @@ function inlineFile(file) {
189
300
  } catch { return null }
190
301
  }
191
302
 
192
- function inlinePreview(buffer) {
303
+ function buildSamplingAxes(srcLen, dstLen) {
304
+ const starts = new Int32Array(dstLen)
305
+ const ends = new Int32Array(dstLen)
306
+ const weights = new Array(dstLen)
307
+ const spans = new Float64Array(dstLen)
308
+ for (let i = 0; i < dstLen; i++) {
309
+ const start = (i * srcLen) / dstLen
310
+ const end = ((i + 1) * srcLen) / dstLen
311
+ const s0 = Math.floor(start)
312
+ const s1 = Math.min(srcLen, Math.ceil(end))
313
+ const w = new Float64Array(s1 - s0)
314
+ for (let s = s0; s < s1; s++) w[s - s0] = Math.min(end, s + 1) - Math.max(start, s)
315
+ starts[i] = s0
316
+ ends[i] = s1
317
+ weights[i] = w
318
+ spans[i] = end - start
319
+ }
320
+ return { starts, ends, weights, spans }
321
+ }
322
+
323
+ function inlinePreview(buffer, maxPixels = PREVIEW_MAX_PIXELS) {
193
324
  const contentType = imageContentType(buffer)
194
325
  if (!contentType) return null
195
326
  if (contentType === 'image/png' && buffer.length > INLINE_LIMIT) {
196
327
  if (buffer.length < 24) return null
197
328
  const w = buffer.readUInt32BE(16), h = buffer.readUInt32BE(20)
198
329
  // Reject before decoding: the decode is the expensive part.
199
- if (!w || !h || w * h > PREVIEW_MAX_PIXELS) return null
330
+ if (!w || !h || w * h > maxPixels) return null
200
331
  // Version the derived cache by content and algorithm, so replacing artwork
201
332
  // cannot leave an old thumbnail behind. Originals are never overwritten.
202
333
  const key = createHash('sha256').update(buffer).digest('hex')
@@ -211,22 +342,43 @@ function inlinePreview(buffer) {
211
342
  const ratio = Math.min(1, 96 / Math.max(w, h))
212
343
  const width = Math.max(1, Math.round(w * ratio)), height = Math.max(1, Math.round(h * ratio))
213
344
  const data = Buffer.alloc(width * height * 4)
345
+ // Precompute source index spans and overlap weights outside inner pixel loops.
346
+ const xAxis = buildSamplingAxes(w, width)
347
+ const yAxis = buildSamplingAxes(h, height)
348
+ const src = image.data
349
+ const rowStride = w * 4
214
350
  // Area sampling with premultiplied alpha preserves fine edges on both
215
351
  // themes; simply averaging transparent RGB creates dark logo fringes.
216
- for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
217
- const left = x * w / width, right = (x + 1) * w / width
218
- const top = y * h / height, bottom = (y + 1) * h / height
219
- let red = 0, green = 0, blue = 0, alpha = 0
220
- for (let sy = Math.floor(top); sy < Math.ceil(bottom); sy++) for (let sx = Math.floor(left); sx < Math.ceil(right); sx++) {
221
- const weight = (Math.min(right, sx + 1) - Math.max(left, sx)) * (Math.min(bottom, sy + 1) - Math.max(top, sy))
222
- const i = (sy * w + sx) * 4, a = image.data[i + 3] / 255 * weight
223
- alpha += a; red += image.data[i] * a; green += image.data[i + 1] * a; blue += image.data[i + 2] * a
352
+ for (let y = 0; y < height; y++) {
353
+ const sy0 = yAxis.starts[y], sy1 = yAxis.ends[y], yw = yAxis.weights[y], ySpan = yAxis.spans[y]
354
+ const dstRow = y * width * 4
355
+ for (let x = 0; x < width; x++) {
356
+ const sx0 = xAxis.starts[x], sx1 = xAxis.ends[x], xw = xAxis.weights[x]
357
+ const area = xAxis.spans[x] * ySpan
358
+ let red = 0, green = 0, blue = 0, alpha = 0
359
+ for (let sy = sy0, yi = 0; sy < sy1; sy++, yi++) {
360
+ const wy = yw[yi]
361
+ let rowOff = sy * rowStride + sx0 * 4
362
+ for (let sx = sx0, xi = 0; sx < sx1; sx++, xi++, rowOff += 4) {
363
+ const aByte = src[rowOff + 3]
364
+ if (aByte === 0) continue
365
+ const a = aByte * xw[xi] * wy
366
+ alpha += a
367
+ red += src[rowOff] * a
368
+ green += src[rowOff + 1] * a
369
+ blue += src[rowOff + 2] * a
370
+ }
371
+ }
372
+ const dst = dstRow + x * 4
373
+ if (alpha) {
374
+ data[dst] = Math.round(red / alpha)
375
+ data[dst + 1] = Math.round(green / alpha)
376
+ data[dst + 2] = Math.round(blue / alpha)
377
+ }
378
+ data[dst + 3] = Math.round(alpha / area)
224
379
  }
225
- const i = (y * width + x) * 4
226
- if (alpha) { data[i] = Math.round(red / alpha); data[i + 1] = Math.round(green / alpha); data[i + 2] = Math.round(blue / alpha) }
227
- data[i + 3] = Math.round(255 * alpha / ((right - left) * (bottom - top)))
228
380
  }
229
- const thumbnail = PNG.sync.write({ width, height, data }, { deflateLevel: 9, deflateStrategy: 0 })
381
+ const thumbnail = PNG.sync.write({ width, height, data }, { deflateLevel: 6, deflateStrategy: 0 })
230
382
  if (thumbnail.length > INLINE_LIMIT) return null
231
383
  try {
232
384
  mkdirSync(directory, { recursive: true })
@@ -256,24 +408,27 @@ function prunePreviewCache(directory) {
256
408
  } catch {}
257
409
  }
258
410
 
259
- function previewFile(file) {
411
+ function previewFile(file, maxPixels = PREVIEW_MAX_PIXELS) {
260
412
  try {
261
413
  const info = statSync(file)
262
414
  if (!info.isFile() || info.size > MAX_BYTES) return null
263
- const key = `${file}:${info.mtimeMs}:${info.size}`
264
- if (previewMemory.has(key)) return previewMemory.get(key)
265
- const preview = inlinePreview(readFileSync(file))
266
- if (previewMemory.size >= 256) previewMemory.delete(previewMemory.keys().next().value)
267
- previewMemory.set(key, preview)
268
- return preview
415
+ const key = `${file}:${info.mtimeMs}:${info.size}:${maxPixels}`
416
+ if (previewMemory.has(key)) return touchLru(previewMemory, key, previewMemory.get(key))
417
+ const preview = inlinePreview(readFileSync(file), maxPixels)
418
+ return setLru(previewMemory, PREVIEW_MEMORY_LIMIT, key, preview)
269
419
  } catch { return null }
270
420
  }
271
421
 
272
422
  function cachedIconPreview(url) {
273
423
  const cached = memory.get(url)
274
424
  if (cached) {
425
+ touchLru(memory, url, cached)
275
426
  try { return inlinePreview(cached.buffer) } catch { return null }
276
427
  }
428
+ const bundled = bundledCache.get(url)
429
+ if (bundled) {
430
+ try { return inlinePreview(bundled.buffer) } catch { return null }
431
+ }
277
432
  return previewFile(iconCacheFile(url))
278
433
  }
279
434
 
@@ -339,7 +494,7 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
339
494
  if (!inline && urls[0]) {
340
495
  const first = urls[0]
341
496
  const remote = first.startsWith('/universal-plugin-hub/api/icon?') ? new URL(first, 'http://localhost').searchParams.get('u') : null
342
- const preview = files.has(first) ? previewFile(files.get(first)) : remote && cachedIconPreview(remote)
497
+ const preview = files.has(first) ? previewFile(files.get(first), LOCAL_PREVIEW_MAX_PIXELS) : remote && cachedIconPreview(remote)
343
498
  if (preview) previews[first] = preview
344
499
  }
345
500
  return inline ? [inline, ...urls.filter((url) => url !== inline)] : urls
@@ -372,9 +527,14 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
372
527
  }
373
528
 
374
529
  function remember(key, value) {
375
- if (memory.size >= 256) memory.delete(memory.keys().next().value)
376
- memory.set(key, { ...value, time: Date.now() })
377
- return value
530
+ failures.delete(key)
531
+ const entry = {
532
+ ...value,
533
+ etag: value.etag || computeEtag(value.buffer),
534
+ immutable: Boolean(value.immutable),
535
+ time: Date.now(),
536
+ }
537
+ return setLru(memory, MEMORY_LIMIT, key, entry)
378
538
  }
379
539
 
380
540
  function iconCacheFile(url) {
@@ -409,11 +569,34 @@ export async function getOrFetchIcon(url) {
409
569
  if (parsed.hostname === 'avatars.githubusercontent.com' && /^\/[a-z0-9_-]+\/?$/i.test(parsed.pathname)) {
410
570
  url = `https://github.com/${parsed.pathname.split('/')[1]}.png?size=${parsed.searchParams.get('s') || '80'}`
411
571
  }
412
- const cached = memory.get(url)
413
- if (cached && Date.now() - cached.time < CACHE_TTL) return cached
414
572
  const bundledFile = bundledIconFiles.get(url)
415
- if (bundledFile) return remember(url, { buffer: readFileSync(new URL(bundledFile, bundledIconRoot)), contentType: 'image/png' })
416
- if (failures.get(url) > Date.now()) throw new Error('Icon temporarily unavailable')
573
+ if (bundledFile) {
574
+ const hit = bundledCache.get(url)
575
+ if (hit) return hit
576
+ if (bundledPending.has(url)) return bundledPending.get(url)
577
+ const load = (async () => {
578
+ const buffer = await readFile(new URL(bundledFile, bundledIconRoot))
579
+ const entry = { buffer, contentType: 'image/png', etag: computeEtag(buffer), immutable: true }
580
+ bundledCache.set(url, entry)
581
+ return entry
582
+ })()
583
+ bundledPending.set(url, load)
584
+ try { return await load } finally { bundledPending.delete(url) }
585
+ }
586
+ const now = Date.now()
587
+ const cached = memory.get(url)
588
+ if (cached) {
589
+ if (now - cached.time < CACHE_TTL) return touchLru(memory, url, cached)
590
+ memory.delete(url)
591
+ }
592
+ const failedUntil = failures.get(url)
593
+ if (failedUntil !== undefined) {
594
+ if (failedUntil > now) {
595
+ touchLru(failures, url, failedUntil)
596
+ throw new Error('Icon temporarily unavailable')
597
+ }
598
+ failures.delete(url)
599
+ }
417
600
  if (pending.has(url)) return pending.get(url)
418
601
  const task = (async () => {
419
602
  const file = iconCacheFile(url)
@@ -437,18 +620,18 @@ export async function getOrFetchIcon(url) {
437
620
  // Record the failure in the same cooldown the foreground path uses, or a
438
621
  // permanently dead URL launches a fresh 4s fetch on every request while
439
622
  // continuing to serve the stale bytes.
440
- downloadIcon(url, file).catch(() => {
441
- if (failures.size >= 256) failures.delete(failures.keys().next().value)
442
- failures.set(url, Date.now() + 60_000)
443
- })
623
+ downloadIcon(url, file)
624
+ .then((fresh) => remember(url, fresh))
625
+ .catch(() => {
626
+ setLru(failures, FAILURES_LIMIT, url, Date.now() + 60_000)
627
+ })
444
628
  return remember(url, expired)
445
629
  }
446
630
  return remember(url, await downloadIcon(url, file))
447
631
  })()
448
632
  pending.set(url, task)
449
633
  try { return await task } catch (error) {
450
- if (failures.size >= 256) failures.delete(failures.keys().next().value)
451
- failures.set(url, Date.now() + 60_000)
634
+ setLru(failures, FAILURES_LIMIT, url, Date.now() + 60_000)
452
635
  throw error
453
636
  } finally { pending.delete(url) }
454
637
  }
package/src/index.js CHANGED
@@ -8,9 +8,11 @@
8
8
  */
9
9
  import { mountRoutes } from './routes.js'
10
10
  import { cancelAllOAuthVerifications } from './oauth.js'
11
- import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
11
+ import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, toolCallIconGroups, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
12
12
  import { createSkillsManager } from './skills.js'
13
+ import { sweepTrash } from './store.js'
13
14
  import { restoreUploadedSkills } from './skill-uploads.js'
15
+ import { removeDuplicateLocalMarketTabs } from './local.js'
14
16
  import { createProfileApplicator } from './runtime.js'
15
17
  import { createRequire } from 'node:module'
16
18
  import { join } from 'node:path'
@@ -26,15 +28,21 @@ export function apply(ctx) {
26
28
  // Everything below that resolves a profile path has to run *after* this, so
27
29
  // it lives inside the injection rather than beside it.
28
30
  let provisioned = Promise.resolve()
29
- ctx.inject(['profileContext'], (hostCtx) => {
31
+ ctx.inject(['profileContext'], async (hostCtx) => {
30
32
  const name = hostCtx.profileContext?.name
31
33
  if (typeof name === 'string' && name.trim()) process.env.DSH_PROFILE = name.trim()
32
34
 
33
35
  // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
34
36
  try {
37
+ sweepTrash()
35
38
  restoreUploadedSkills()
36
39
 
37
- syncAllInstalledSkillsToDsh()
40
+ // Earlier versions created one tab per uploaded marketplace and named it
41
+ // after the local tab, producing two identical tabs. Drop the duplicate.
42
+ const { removed } = removeDuplicateLocalMarketTabs()
43
+ if (removed.length) ctx.logger?.info?.(`[universal-plugin-hub] removed duplicate local tabs: ${removed.join(', ')}`)
44
+
45
+ await syncAllInstalledSkillsToDsh()
38
46
  } catch (err) {
39
47
  ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
40
48
  }
@@ -76,7 +84,23 @@ export function apply(ctx) {
76
84
  ctx.inject(['webServer'], (hostCtx) => {
77
85
  hostCtx.effect(() => {
78
86
  const unmount = mountRoutes(hostCtx.webServer, skills, createProfileApplicator(ctx))
79
- return () => { unmount(); cancelAllOAuthVerifications() }
87
+ const offBoot = hostCtx.on?.('webserver/index-inject', (table) => {
88
+ try {
89
+ const value = []
90
+ let bytes = 2
91
+ for (const group of toolCallIconGroups()) {
92
+ const size = Buffer.byteLength(JSON.stringify(group)) + 1
93
+ if (bytes + size > 128 * 1024) continue
94
+ value.push(group)
95
+ bytes += size
96
+ if (value.length === 12) break
97
+ }
98
+ if (value.length) table.push({ kind: 'global', name: '__UPH_TOOL_CALL_ICONS__', value })
99
+ } catch (error) {
100
+ ctx.logger?.warn?.(`[universal-plugin-hub] MCP tool icon boot data unavailable: ${error.message}`)
101
+ }
102
+ })
103
+ return () => { offBoot?.(); unmount(); cancelAllOAuthVerifications() }
80
104
  }, 'universal-plugin-hub: http routes')
81
105
  })
82
106
  }