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/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,44 @@ 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
25
+ let localIconCacheRevisionCounter = 0
14
26
  const bundledIconRoot = new URL('../assets/fluent-3d/', import.meta.url)
15
27
  const bundledIconFiles = new Map(Object.values(JSON.parse(readFileSync(new URL('manifest.json', bundledIconRoot), 'utf8')).icons).map(icon => [icon.url, icon.file]))
16
28
 
29
+ /** Compute a strong HTTP ETag from raw bytes. */
30
+ export function computeEtag(buffer) {
31
+ return `"${createHash('sha256').update(buffer).digest('base64url')}"`
32
+ }
33
+
34
+ /** Promote an existing Map entry to most-recently-used. */
35
+ export function touchLru(map, key, value) {
36
+ map.delete(key)
37
+ map.set(key, value)
38
+ return value
39
+ }
40
+
41
+ /** Insert or update a bounded Map entry with true LRU eviction. */
42
+ export function setLru(map, limit, key, value) {
43
+ if (map.has(key)) map.delete(key)
44
+ else if (map.size >= limit) map.delete(map.keys().next().value)
45
+ map.set(key, value)
46
+ return value
47
+ }
48
+
17
49
  export function imageContentType(buffer) {
18
50
  if (!buffer?.length) return null
19
51
  if (buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'image/png'
@@ -39,6 +71,91 @@ export function readLocalIcon(root, path) {
39
71
  return { buffer, contentType }
40
72
  }
41
73
 
74
+ function deleteLocalIconEntry(key) {
75
+ const existing = localIconMemory.get(key)
76
+ if (!existing) return false
77
+ localIconMemoryBytes = Math.max(0, localIconMemoryBytes - existing.buffer.length)
78
+ return localIconMemory.delete(key)
79
+ }
80
+
81
+ function setLocalIconEntry(key, entry) {
82
+ const size = entry.buffer.length
83
+ if (size > LOCAL_ICON_MAX_CACHE_BYTES) return entry
84
+ deleteLocalIconEntry(key)
85
+ while (
86
+ localIconMemory.size > 0
87
+ && (localIconMemory.size >= LOCAL_ICON_MEMORY_LIMIT || localIconMemoryBytes + size > LOCAL_ICON_MEMORY_MAX_BYTES)
88
+ ) {
89
+ deleteLocalIconEntry(localIconMemory.keys().next().value)
90
+ }
91
+ localIconMemory.set(key, entry)
92
+ localIconMemoryBytes += size
93
+ return entry
94
+ }
95
+
96
+ /** Snapshot local icon cache entry count and retained bytes. */
97
+ export function getLocalIconCacheStats() {
98
+ return {
99
+ size: localIconMemory.size,
100
+ bytes: localIconMemoryBytes,
101
+ maxItemBytes: LOCAL_ICON_MAX_CACHE_BYTES,
102
+ maxTotalBytes: LOCAL_ICON_MEMORY_MAX_BYTES,
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Resolve, verify containment, and read/cache a local icon asynchronously.
108
+ * Always validates directory traversal containment and current file stat so
109
+ * removed or out-of-bounds files fail immediately instead of hitting cache.
110
+ * Skips caching payloads above 256 KB and caps total retained memory at 32 MB.
111
+ */
112
+ export async function readLocalIconCached(root, path, scopeParts = []) {
113
+ const candidate = pluginPath(root, path)
114
+ const [realRoot, realFile] = await Promise.all([realpath(root), realpath(candidate)])
115
+ const rel = relative(realRoot, realFile)
116
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) {
117
+ throw new Error('Icon is outside plugin directory')
118
+ }
119
+ const info = await stat(realFile)
120
+ if (!info.isFile() || info.size > MAX_BYTES) throw new Error('Invalid icon size')
121
+ const fileVersion = `${info.mtimeMs}-${info.size}`
122
+ const scopePrefix = JSON.stringify(scopeParts)
123
+ const key = `${scopePrefix}\0${realFile}\0${fileVersion}`
124
+ const hit = localIconMemory.get(key)
125
+ if (hit) return touchLru(localIconMemory, key, hit)
126
+ const inflight = localIconPending.get(key)
127
+ if (inflight) return inflight
128
+ const task = (async () => {
129
+ const buffer = await readFile(realFile)
130
+ const contentType = imageContentType(buffer)
131
+ if (!contentType) throw new Error('Unsupported icon content')
132
+ const entry = { buffer, contentType, etag: computeEtag(buffer), fileVersion }
133
+ return setLocalIconEntry(key, entry)
134
+ })()
135
+ localIconPending.set(key, task)
136
+ try { return await task } finally { localIconPending.delete(key) }
137
+ }
138
+
139
+ /** Monotonic counter incremented when cached local icons are invalidated. */
140
+ export function localIconCacheRevision() {
141
+ return localIconCacheRevisionCounter
142
+ }
143
+
144
+ /** Drop cached local icon bytes for one sourceId (or all entries when omitted). */
145
+ export function invalidateLocalIconCache(sourceId) {
146
+ localIconCacheRevisionCounter += 1
147
+ if (!sourceId) {
148
+ localIconMemory.clear()
149
+ localIconMemoryBytes = 0
150
+ return
151
+ }
152
+ const prefix = JSON.stringify([sourceId])
153
+ const head = prefix.slice(0, -1) + ','
154
+ for (const key of [...localIconMemory.keys()]) {
155
+ if (key.startsWith(head)) deleteLocalIconEntry(key)
156
+ }
157
+ }
158
+
42
159
  // Claude's plugin manifest has no icon field and marketplace entries do not
43
160
  // carry one either, so a plugin's artwork can only be found on disk. Matching a
44
161
  // fixed list of nine filenames missed most of it, which sent those rows to the
@@ -173,6 +290,7 @@ const PREVIEW_LIMIT = 64 * 1024
173
290
  // Decoding runs synchronously inside catalog parsing, once per row, so the
174
291
  // bound has to cover the decode itself and not just the file size.
175
292
  const PREVIEW_MAX_PIXELS = 262144
293
+ const LOCAL_PREVIEW_MAX_PIXELS = 1024 * 1024
176
294
  const PREVIEWS_DIR = 'previews'
177
295
  const PREVIEW_CACHE_KEEP = 200
178
296
  const previewMemory = new Map()
@@ -189,14 +307,34 @@ function inlineFile(file) {
189
307
  } catch { return null }
190
308
  }
191
309
 
192
- function inlinePreview(buffer) {
310
+ function buildSamplingAxes(srcLen, dstLen) {
311
+ const starts = new Int32Array(dstLen)
312
+ const ends = new Int32Array(dstLen)
313
+ const weights = new Array(dstLen)
314
+ const spans = new Float64Array(dstLen)
315
+ for (let i = 0; i < dstLen; i++) {
316
+ const start = (i * srcLen) / dstLen
317
+ const end = ((i + 1) * srcLen) / dstLen
318
+ const s0 = Math.floor(start)
319
+ const s1 = Math.min(srcLen, Math.ceil(end))
320
+ const w = new Float64Array(s1 - s0)
321
+ for (let s = s0; s < s1; s++) w[s - s0] = Math.min(end, s + 1) - Math.max(start, s)
322
+ starts[i] = s0
323
+ ends[i] = s1
324
+ weights[i] = w
325
+ spans[i] = end - start
326
+ }
327
+ return { starts, ends, weights, spans }
328
+ }
329
+
330
+ function inlinePreview(buffer, maxPixels = PREVIEW_MAX_PIXELS) {
193
331
  const contentType = imageContentType(buffer)
194
332
  if (!contentType) return null
195
333
  if (contentType === 'image/png' && buffer.length > INLINE_LIMIT) {
196
334
  if (buffer.length < 24) return null
197
335
  const w = buffer.readUInt32BE(16), h = buffer.readUInt32BE(20)
198
336
  // Reject before decoding: the decode is the expensive part.
199
- if (!w || !h || w * h > PREVIEW_MAX_PIXELS) return null
337
+ if (!w || !h || w * h > maxPixels) return null
200
338
  // Version the derived cache by content and algorithm, so replacing artwork
201
339
  // cannot leave an old thumbnail behind. Originals are never overwritten.
202
340
  const key = createHash('sha256').update(buffer).digest('hex')
@@ -211,22 +349,43 @@ function inlinePreview(buffer) {
211
349
  const ratio = Math.min(1, 96 / Math.max(w, h))
212
350
  const width = Math.max(1, Math.round(w * ratio)), height = Math.max(1, Math.round(h * ratio))
213
351
  const data = Buffer.alloc(width * height * 4)
352
+ // Precompute source index spans and overlap weights outside inner pixel loops.
353
+ const xAxis = buildSamplingAxes(w, width)
354
+ const yAxis = buildSamplingAxes(h, height)
355
+ const src = image.data
356
+ const rowStride = w * 4
214
357
  // Area sampling with premultiplied alpha preserves fine edges on both
215
358
  // 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
359
+ for (let y = 0; y < height; y++) {
360
+ const sy0 = yAxis.starts[y], sy1 = yAxis.ends[y], yw = yAxis.weights[y], ySpan = yAxis.spans[y]
361
+ const dstRow = y * width * 4
362
+ for (let x = 0; x < width; x++) {
363
+ const sx0 = xAxis.starts[x], sx1 = xAxis.ends[x], xw = xAxis.weights[x]
364
+ const area = xAxis.spans[x] * ySpan
365
+ let red = 0, green = 0, blue = 0, alpha = 0
366
+ for (let sy = sy0, yi = 0; sy < sy1; sy++, yi++) {
367
+ const wy = yw[yi]
368
+ let rowOff = sy * rowStride + sx0 * 4
369
+ for (let sx = sx0, xi = 0; sx < sx1; sx++, xi++, rowOff += 4) {
370
+ const aByte = src[rowOff + 3]
371
+ if (aByte === 0) continue
372
+ const a = aByte * xw[xi] * wy
373
+ alpha += a
374
+ red += src[rowOff] * a
375
+ green += src[rowOff + 1] * a
376
+ blue += src[rowOff + 2] * a
377
+ }
378
+ }
379
+ const dst = dstRow + x * 4
380
+ if (alpha) {
381
+ data[dst] = Math.round(red / alpha)
382
+ data[dst + 1] = Math.round(green / alpha)
383
+ data[dst + 2] = Math.round(blue / alpha)
384
+ }
385
+ data[dst + 3] = Math.round(alpha / area)
224
386
  }
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
387
  }
229
- const thumbnail = PNG.sync.write({ width, height, data }, { deflateLevel: 9, deflateStrategy: 0 })
388
+ const thumbnail = PNG.sync.write({ width, height, data }, { deflateLevel: 6, deflateStrategy: 0 })
230
389
  if (thumbnail.length > INLINE_LIMIT) return null
231
390
  try {
232
391
  mkdirSync(directory, { recursive: true })
@@ -256,24 +415,27 @@ function prunePreviewCache(directory) {
256
415
  } catch {}
257
416
  }
258
417
 
259
- function previewFile(file) {
418
+ function previewFile(file, maxPixels = PREVIEW_MAX_PIXELS) {
260
419
  try {
261
420
  const info = statSync(file)
262
421
  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
422
+ const key = `${file}:${info.mtimeMs}:${info.size}:${maxPixels}`
423
+ if (previewMemory.has(key)) return touchLru(previewMemory, key, previewMemory.get(key))
424
+ const preview = inlinePreview(readFileSync(file), maxPixels)
425
+ return setLru(previewMemory, PREVIEW_MEMORY_LIMIT, key, preview)
269
426
  } catch { return null }
270
427
  }
271
428
 
272
429
  function cachedIconPreview(url) {
273
430
  const cached = memory.get(url)
274
431
  if (cached) {
432
+ touchLru(memory, url, cached)
275
433
  try { return inlinePreview(cached.buffer) } catch { return null }
276
434
  }
435
+ const bundled = bundledCache.get(url)
436
+ if (bundled) {
437
+ try { return inlinePreview(bundled.buffer) } catch { return null }
438
+ }
277
439
  return previewFile(iconCacheFile(url))
278
440
  }
279
441
 
@@ -339,7 +501,7 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
339
501
  if (!inline && urls[0]) {
340
502
  const first = urls[0]
341
503
  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)
504
+ const preview = files.has(first) ? previewFile(files.get(first), LOCAL_PREVIEW_MAX_PIXELS) : remote && cachedIconPreview(remote)
343
505
  if (preview) previews[first] = preview
344
506
  }
345
507
  return inline ? [inline, ...urls.filter((url) => url !== inline)] : urls
@@ -372,9 +534,14 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
372
534
  }
373
535
 
374
536
  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
537
+ failures.delete(key)
538
+ const entry = {
539
+ ...value,
540
+ etag: value.etag || computeEtag(value.buffer),
541
+ immutable: Boolean(value.immutable),
542
+ time: Date.now(),
543
+ }
544
+ return setLru(memory, MEMORY_LIMIT, key, entry)
378
545
  }
379
546
 
380
547
  function iconCacheFile(url) {
@@ -409,11 +576,34 @@ export async function getOrFetchIcon(url) {
409
576
  if (parsed.hostname === 'avatars.githubusercontent.com' && /^\/[a-z0-9_-]+\/?$/i.test(parsed.pathname)) {
410
577
  url = `https://github.com/${parsed.pathname.split('/')[1]}.png?size=${parsed.searchParams.get('s') || '80'}`
411
578
  }
412
- const cached = memory.get(url)
413
- if (cached && Date.now() - cached.time < CACHE_TTL) return cached
414
579
  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')
580
+ if (bundledFile) {
581
+ const hit = bundledCache.get(url)
582
+ if (hit) return hit
583
+ if (bundledPending.has(url)) return bundledPending.get(url)
584
+ const load = (async () => {
585
+ const buffer = await readFile(new URL(bundledFile, bundledIconRoot))
586
+ const entry = { buffer, contentType: 'image/png', etag: computeEtag(buffer), immutable: true }
587
+ bundledCache.set(url, entry)
588
+ return entry
589
+ })()
590
+ bundledPending.set(url, load)
591
+ try { return await load } finally { bundledPending.delete(url) }
592
+ }
593
+ const now = Date.now()
594
+ const cached = memory.get(url)
595
+ if (cached) {
596
+ if (now - cached.time < CACHE_TTL) return touchLru(memory, url, cached)
597
+ memory.delete(url)
598
+ }
599
+ const failedUntil = failures.get(url)
600
+ if (failedUntil !== undefined) {
601
+ if (failedUntil > now) {
602
+ touchLru(failures, url, failedUntil)
603
+ throw new Error('Icon temporarily unavailable')
604
+ }
605
+ failures.delete(url)
606
+ }
417
607
  if (pending.has(url)) return pending.get(url)
418
608
  const task = (async () => {
419
609
  const file = iconCacheFile(url)
@@ -437,18 +627,18 @@ export async function getOrFetchIcon(url) {
437
627
  // Record the failure in the same cooldown the foreground path uses, or a
438
628
  // permanently dead URL launches a fresh 4s fetch on every request while
439
629
  // 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
- })
630
+ downloadIcon(url, file)
631
+ .then((fresh) => remember(url, fresh))
632
+ .catch(() => {
633
+ setLru(failures, FAILURES_LIMIT, url, Date.now() + 60_000)
634
+ })
444
635
  return remember(url, expired)
445
636
  }
446
637
  return remember(url, await downloadIcon(url, file))
447
638
  })()
448
639
  pending.set(url, task)
449
640
  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)
641
+ setLru(failures, FAILURES_LIMIT, url, Date.now() + 60_000)
452
642
  throw error
453
643
  } finally { pending.delete(url) }
454
644
  }
package/src/index.js CHANGED
@@ -8,10 +8,18 @@
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'
17
+ import {
18
+ attachAtPluginsAgentHook,
19
+ attachAtPluginsSessionTitleHook,
20
+ atPluginsBootPayload,
21
+ invalidateAtPluginsCache,
22
+ } from './at-plugins.js'
15
23
  import { createRequire } from 'node:module'
16
24
  import { join } from 'node:path'
17
25
 
@@ -32,9 +40,16 @@ export function apply(ctx) {
32
40
 
33
41
  // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
34
42
  try {
43
+ sweepTrash()
35
44
  restoreUploadedSkills()
36
45
 
46
+ // Earlier versions created one tab per uploaded marketplace and named it
47
+ // after the local tab, producing two identical tabs. Drop the duplicate.
48
+ const { removed } = removeDuplicateLocalMarketTabs()
49
+ if (removed.length) ctx.logger?.info?.(`[universal-plugin-hub] removed duplicate local tabs: ${removed.join(', ')}`)
50
+
37
51
  await syncAllInstalledSkillsToDsh()
52
+ invalidateAtPluginsCache()
38
53
  } catch (err) {
39
54
  ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
40
55
  }
@@ -73,10 +88,37 @@ export function apply(ctx) {
73
88
  }
74
89
  hostCtx.effect(() => skills.attachAgents(hostCtx, createScope), 'universal-plugin-hub: scoped skill switches')
75
90
  })
91
+ ctx.inject(['agents'], (hostCtx) => {
92
+ hostCtx.effect(() => attachAtPluginsAgentHook(hostCtx), 'universal-plugin-hub: @ plugins routing')
93
+ })
94
+ ctx.inject(['sessions'], (hostCtx) => {
95
+ hostCtx.effect(() => attachAtPluginsSessionTitleHook(hostCtx), 'universal-plugin-hub: @ plugins session title')
96
+ })
76
97
  ctx.inject(['webServer'], (hostCtx) => {
77
98
  hostCtx.effect(() => {
78
99
  const unmount = mountRoutes(hostCtx.webServer, skills, createProfileApplicator(ctx))
79
- return () => { unmount(); cancelAllOAuthVerifications() }
100
+ const offBoot = hostCtx.on?.('webserver/index-inject', (table) => {
101
+ try {
102
+ const value = []
103
+ let bytes = 2
104
+ for (const group of toolCallIconGroups()) {
105
+ const size = Buffer.byteLength(JSON.stringify(group)) + 1
106
+ if (bytes + size > 128 * 1024) continue
107
+ value.push(group)
108
+ bytes += size
109
+ if (value.length === 12) break
110
+ }
111
+ if (value.length) table.push({ kind: 'global', name: '__UPH_TOOL_CALL_ICONS__', value })
112
+ } catch (error) {
113
+ ctx.logger?.warn?.(`[universal-plugin-hub] MCP tool icon boot data unavailable: ${error.message}`)
114
+ }
115
+ try {
116
+ table.push({ kind: 'global', name: '__UPH_AT_PLUGINS__', value: atPluginsBootPayload() })
117
+ } catch (error) {
118
+ ctx.logger?.warn?.(`[universal-plugin-hub] @ plugins boot data unavailable: ${error.message}`)
119
+ }
120
+ })
121
+ return () => { offBoot?.(); unmount(); cancelAllOAuthVerifications() }
80
122
  }, 'universal-plugin-hub: http routes')
81
123
  })
82
124
  }