universal-plugin-hub 1.3.1 → 1.5.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.
@@ -0,0 +1,823 @@
1
+ /**
2
+ * Codex-style `@` Plugin selector catalog, mention grammar, and on-demand capability routing.
3
+ *
4
+ * Exposes installed & enabled plugins (excluding disabled plugins, `user-mcp`, and
5
+ * standalone/uploaded skills) for the DSH composer `@` trigger menu, reuses plugin
6
+ * browse-card smart descriptions (`shortDescription || description || "by <author>"`)
7
+ * and icons, and injects a compact Codex-style capability notice on `agent/pre-step`
8
+ * so the model selectively loads only relevant skills via the native `skill` tool.
9
+ */
10
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
11
+ import { randomUUID } from 'node:crypto'
12
+ import { createRequire } from 'node:module'
13
+ import { basename, dirname, isAbsolute, join } from 'node:path'
14
+ import { dshHome, dshSkillsDir, installedDir, isSameOrInsidePath, readState, resolveOptionalService, statePath, stateRevision } from './store.js'
15
+ import {
16
+ formatDisplayName,
17
+ listAgents,
18
+ listPrompts,
19
+ parserCacheRevision,
20
+ readMarketplace,
21
+ readPluginManifest,
22
+ readPluginShortDescription,
23
+ } from './parser.js'
24
+ import {
25
+ findDshMainNodeModules,
26
+ getConnectorEntry,
27
+ getPluginConnectors,
28
+ installedPluginIconIdentity,
29
+ } from './install.js'
30
+ import { localIconCacheRevision } from './icons.js'
31
+ import { isUploadedSkillTarget } from './skill-uploads.js'
32
+ import { discoverSkills } from './skills.js'
33
+
34
+ export const PLUGIN_MENTION_SCHEME = 'uph-plugin:'
35
+ export const AT_PLUGINS_BOOT_LIMIT = 128 * 1024
36
+
37
+ const WIRE_MENTION_RE = /@\[([^\]\n]+)\]\(uph-plugin:([^)\s]+)\)/uy
38
+ const WIRE_MENTION_TEXT_RE = /@\[([^\]\n]+)\]\(uph-plugin:([^)\s]+)\)/gu
39
+ const WIRE_MENTION_TRUNCATED_TAIL_RE = /@\[([^\]\n]+)\]\(uph-plugin:([^)\s]*)$/u
40
+ const TITLE_OSC_SEQUENCE_RE = /(?:\u001B\]|\u009D)(?:(?!\u0007|\u001B\\)[\s\S])*(?:\u0007|\u001B\\|$)/gu
41
+ const TITLE_CSI_SEQUENCE_RE = /(?:\u001B\[|\u009B)[0-?]*[ -/]*[@-~]/gu
42
+ const TITLE_ESC_SEQUENCE_RE = /\u001B[@-_]/gu
43
+ const TITLE_CONTROL_CHARACTER_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/gu
44
+ const TITLE_DIRECTIONAL_CONTROL_RE = /[\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]/gu
45
+ const DEFAULT_TITLE_FALLBACK_MAX_WORDS = 5
46
+ const DEFAULT_TITLE_FALLBACK_MAX_BYTES = 40
47
+ const DEFAULT_TITLE_MAX_BYTES = 80
48
+ const RAW_AT_TOKEN_RE = /@([^\s\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul},。;:、!?()【】《》“”‘’」』]+)/uy
49
+ const LEFT_ALLOWED_RE = /[\s(\[{"'“‘(【《,。;:、!?\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u
50
+ const TRAILING_PUNCT_RE = /[.,;:!?,。;:!?)"'\]”’)】》]+$/u
51
+ const SUMMARY_MAX_CHARS = 180
52
+
53
+ let cacheEpoch = 0
54
+ let cachedCatalog = null // { home, stamp, plugins }
55
+ let cachedCreateUserMessage = null
56
+
57
+ export function invalidateAtPluginsCache() {
58
+ cacheEpoch += 1
59
+ cachedCatalog = null
60
+ }
61
+
62
+ function statSignature(path) {
63
+ try {
64
+ const st = statSync(path)
65
+ return `${st.mtimeMs}:${st.size}`
66
+ } catch {
67
+ return 'missing'
68
+ }
69
+ }
70
+
71
+ function computeCatalogStamp(state) {
72
+ const plugins = Array.isArray(state?.plugins) ? state.plugins : []
73
+ const parts = [
74
+ String(cacheEpoch),
75
+ String(stateRevision()),
76
+ String(parserCacheRevision()),
77
+ String(localIconCacheRevision()),
78
+ statSignature(statePath()),
79
+ ]
80
+ for (const rec of plugins) {
81
+ if (!rec?.name || rec.name === 'user-mcp' || rec.enabled === false) continue
82
+ const dir = installedDir(rec.name)
83
+ parts.push(
84
+ `${rec.name}=${statSignature(dir)}`,
85
+ statSignature(join(dir, 'plugin.json')),
86
+ statSignature(join(dir, '.claude-plugin', 'plugin.json')),
87
+ statSignature(join(dir, '.codex-plugin', 'plugin.json')),
88
+ statSignature(join(dir, 'manifest.json')),
89
+ statSignature(join(dir, '.well-known', 'agent-card.json')),
90
+ statSignature(join(dir, '.claude-plugin')),
91
+ statSignature(join(dir, '.codex-plugin')),
92
+ statSignature(join(dir, 'icons')),
93
+ )
94
+ }
95
+ return parts.join('|')
96
+ }
97
+
98
+ function summarizePlugin(shortDescription, description, author) {
99
+ return shortDescription || description || (author ? `by ${author}` : '')
100
+ }
101
+
102
+ function buildMarketplaceLookup(plugins) {
103
+ const bySource = new Map()
104
+ for (const rec of plugins) {
105
+ const sourceId = rec?.sourceId
106
+ if (!sourceId || bySource.has(sourceId)) continue
107
+ const map = new Map()
108
+ try {
109
+ for (const row of readMarketplace(sourceId)) {
110
+ if (row?.name) map.set(row.name, row)
111
+ }
112
+ } catch {
113
+ // Missing/uncloned source metadata gracefully falls back to installed manifest fields.
114
+ }
115
+ bySource.set(sourceId, map)
116
+ }
117
+ return bySource
118
+ }
119
+
120
+ function buildAtPluginEntry(rec, marketRow) {
121
+ const target = installedDir(rec.name)
122
+ if (!existsSync(target)) return null
123
+ const manifest = readPluginManifest(target)
124
+ const identity = installedPluginIconIdentity(rec, target, manifest, marketRow)
125
+ const displayName = rec.displayName || manifest?.displayName || marketRow?.displayName || formatDisplayName(rec.name)
126
+ const shortDescription = rec.shortDescription || readPluginShortDescription(target) || marketRow?.shortDescription || ''
127
+ const description = rec.description || manifest?.description || marketRow?.description || ''
128
+ const author = typeof identity.author === 'string' ? identity.author : (identity.author?.name || '')
129
+ return {
130
+ name: rec.name,
131
+ displayName,
132
+ shortDescription,
133
+ description,
134
+ summary: summarizePlugin(shortDescription, description, author),
135
+ sourceId: rec.sourceId || '',
136
+ author,
137
+ homepage: identity.homepage,
138
+ source: identity.source,
139
+ icons: identity.icons,
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Return currently installed & enabled plugins for the `@` selector popup.
145
+ * Excludes disabled plugins, `user-mcp`, and standalone/uploaded skills.
146
+ */
147
+ export function listAtPlugins() {
148
+ const home = dshHome()
149
+ const state = readState()
150
+ const stamp = computeCatalogStamp(state)
151
+ if (cachedCatalog && cachedCatalog.home === home && cachedCatalog.stamp === stamp) {
152
+ return cachedCatalog.plugins
153
+ }
154
+
155
+ const rawPlugins = Array.isArray(state.plugins) ? state.plugins : []
156
+ const marketLookup = buildMarketplaceLookup(rawPlugins)
157
+ const items = []
158
+ for (const rec of rawPlugins) {
159
+ if (!rec || !rec.name || rec.name === 'user-mcp' || rec.enabled === false) continue
160
+ const entry = buildAtPluginEntry(rec, marketLookup.get(rec.sourceId)?.get(rec.name) || null)
161
+ if (entry) items.push(entry)
162
+ }
163
+ items.sort((a, b) => (a.displayName || a.name).localeCompare(b.displayName || b.name, undefined, { sensitivity: 'base' }))
164
+ cachedCatalog = { home, stamp, plugins: items }
165
+ return items
166
+ }
167
+
168
+ function compactAtPluginEntry(entry, { includePreviews = true, includeDescriptions = true } = {}) {
169
+ let icons
170
+ if (entry.icons && typeof entry.icons === 'object') {
171
+ icons = includePreviews ? entry.icons : { light: entry.icons.light || [], dark: entry.icons.dark || [] }
172
+ }
173
+ if (!includeDescriptions) {
174
+ return {
175
+ name: entry.name,
176
+ displayName: entry.displayName,
177
+ summary: entry.summary,
178
+ sourceId: entry.sourceId,
179
+ author: entry.author,
180
+ homepage: entry.homepage,
181
+ source: entry.source,
182
+ ...(icons ? { icons } : {}),
183
+ }
184
+ }
185
+ return {
186
+ ...entry,
187
+ ...(icons ? { icons } : {}),
188
+ }
189
+ }
190
+
191
+ /** Build a 128 KB-bounded boot global payload so cold `@` popups render with zero HTTP round-trip. */
192
+ export function atPluginsBootPayload(limitBytes = AT_PLUGINS_BOOT_LIMIT) {
193
+ const items = listAtPlugins()
194
+ const profiles = [
195
+ { includePreviews: true, includeDescriptions: true },
196
+ { includePreviews: false, includeDescriptions: true },
197
+ { includePreviews: false, includeDescriptions: false },
198
+ ]
199
+ for (const profile of profiles) {
200
+ const candidate = items.map(item => compactAtPluginEntry(item, profile))
201
+ if (Buffer.byteLength(JSON.stringify(candidate), 'utf8') <= limitBytes) {
202
+ return candidate
203
+ }
204
+ }
205
+ const bounded = []
206
+ let bytes = 2
207
+ for (const item of items) {
208
+ const compact = compactAtPluginEntry(item, { includePreviews: false, includeDescriptions: false })
209
+ const size = Buffer.byteLength(JSON.stringify(compact), 'utf8') + (bounded.length ? 1 : 0)
210
+ if (bytes + size > limitBytes) break
211
+ bounded.push(compact)
212
+ bytes += size
213
+ }
214
+ return bounded
215
+ }
216
+
217
+ /** Format a selected `@` plugin mention using durable markdown link wire syntax. */
218
+ export function formatPluginMention(pluginName, displayName) {
219
+ const id = String(pluginName || '').trim()
220
+ const label = String(displayName || id).replace(/[\r\n\[\]]+/g, ' ').trim() || id
221
+ return `@[${label}](${PLUGIN_MENTION_SCHEME}${encodeURIComponent(id)})`
222
+ }
223
+
224
+ function isAtLeftBoundary(text, index) {
225
+ return index === 0 || LEFT_ALLOWED_RE.test(text[index - 1])
226
+ }
227
+
228
+ /**
229
+ * Scan text for explicit `@[Display](uph-plugin:name)` chips and single-token `@plugin-id` mentions.
230
+ * Enforces strict token boundaries so `@computer use` never matches `computer-use` across spaces and
231
+ * `@remotion/player` or `user@remotion.com` never falsely trigger `@remotion`.
232
+ */
233
+ export function extractPluginMentions(text, knownByName) {
234
+ if (typeof text !== 'string' || !text.includes('@') || !(knownByName instanceof Map) || knownByName.size === 0) {
235
+ return []
236
+ }
237
+ const matches = []
238
+ let cursor = 0
239
+ while (cursor < text.length) {
240
+ const at = text.indexOf('@', cursor)
241
+ if (at < 0) break
242
+ WIRE_MENTION_RE.lastIndex = at
243
+ const wire = WIRE_MENTION_RE.exec(text)
244
+ if (wire !== null) {
245
+ if (isAtLeftBoundary(text, at)) {
246
+ try {
247
+ const decoded = decodeURIComponent(wire[2])
248
+ const plugin = knownByName.get(decoded.toLowerCase())
249
+ if (plugin) {
250
+ matches.push({ start: at, end: at + wire[0].length, via: 'chip', plugin })
251
+ }
252
+ } catch {
253
+ // Malformed percent encoding inside wire target stays ignored as ordinary text.
254
+ }
255
+ }
256
+ cursor = at + wire[0].length
257
+ continue
258
+ }
259
+
260
+ if (!isAtLeftBoundary(text, at)) {
261
+ cursor = at + 1
262
+ continue
263
+ }
264
+
265
+ RAW_AT_TOKEN_RE.lastIndex = at
266
+ const raw = RAW_AT_TOKEN_RE.exec(text)
267
+ if (raw !== null && !raw[1].startsWith('"')) {
268
+ const cleaned = raw[1].replace(TRAILING_PUNCT_RE, '')
269
+ if (cleaned.length > 0) {
270
+ const plugin = knownByName.get(cleaned.toLowerCase())
271
+ if (plugin) {
272
+ matches.push({ start: at, end: at + 1 + cleaned.length, via: 'manual', plugin })
273
+ cursor = at + 1 + cleaned.length
274
+ continue
275
+ }
276
+ }
277
+ }
278
+ cursor = at + 1
279
+ }
280
+ return matches
281
+ }
282
+
283
+ function truncateOneLine(text, max = SUMMARY_MAX_CHARS) {
284
+ const clean = String(text || '').replace(/\s+/g, ' ').trim()
285
+ if (clean.length <= max) return clean
286
+ return `${clean.slice(0, max - 1)}…`
287
+ }
288
+
289
+ function pluginOwnsSkillFile(target, installedRoot, mirrorRoot, file) {
290
+ if (typeof file !== 'string' || !isAbsolute(file)) return false
291
+ const nativeRoot = dshSkillsDir()
292
+ const isInstalled = isSameOrInsidePath(file, target) || isSameOrInsidePath(file, installedRoot)
293
+ const mirrorDir = dirname(file)
294
+ const isMirror = basename(file).toLowerCase() === 'skill.md' &&
295
+ [nativeRoot, mirrorRoot].some(root => isSameOrInsidePath(dirname(mirrorDir), root) && isSameOrInsidePath(root, dirname(mirrorDir)))
296
+ if (!isInstalled && !isMirror) return false
297
+ try {
298
+ const canonical = realpathSync.native(file)
299
+ if (isInstalled) return isSameOrInsidePath(canonical, installedRoot)
300
+ if (isUploadedSkillTarget(join(nativeRoot, basename(mirrorDir)))) return false
301
+ // Native discovery resolves the active copy. Its content must still match
302
+ // this plugin's normalized mirror source, even when another plugin shares its folder name.
303
+ const mirrorFile = mirrorRoot && join(mirrorRoot, basename(mirrorDir), basename(file))
304
+ if (!isSameOrInsidePath(canonical, mirrorFile)) return false
305
+ const original = join(target, 'skills', basename(mirrorDir), 'SKILL.md')
306
+ return isSameOrInsidePath(realpathSync.native(original), installedRoot) &&
307
+ readFileSync(original).equals(readFileSync(canonical))
308
+ } catch {
309
+ return false
310
+ }
311
+ }
312
+
313
+ function resolveCallablePluginSkills(target, snapshotSkills) {
314
+ let installedRoot
315
+ try { installedRoot = realpathSync.native(target) } catch { return [] }
316
+ let mirrorRoot
317
+ try { mirrorRoot = realpathSync.native(dshSkillsDir()) } catch {}
318
+ const candidates = snapshotSkills ?? discoverSkills(join(target, 'skills'))
319
+ const seen = new Set()
320
+ const resolved = []
321
+ for (const skill of candidates) {
322
+ if (typeof skill?.name !== 'string' || !skill.name || skill.error || skill.enabled === false ||
323
+ skill.modelInvocable === false || skill.invocation?.modelInvocable === false) continue
324
+ const lower = skill.name.toLowerCase()
325
+ if (seen.has(lower) || !pluginOwnsSkillFile(target, installedRoot, mirrorRoot, skill.path)) continue
326
+ seen.add(lower)
327
+ resolved.push({
328
+ name: skill.name,
329
+ description: truncateOneLine(skill.description),
330
+ })
331
+ }
332
+ return resolved
333
+ }
334
+
335
+ /** Collect a plugin's loadable skills, enabled MCP servers, agents/subagents, and prompts. */
336
+ export function collectPluginCapabilities(pluginName, options = {}) {
337
+ const target = installedDir(pluginName)
338
+ if (!existsSync(target)) {
339
+ return { skills: [], mcpServers: [], agents: [], prompts: [] }
340
+ }
341
+ const manifest = readPluginManifest(target)
342
+ const snapshotSkills = Array.isArray(options.snapshotSkills) ? options.snapshotSkills : null
343
+ const skills = resolveCallablePluginSkills(target, snapshotSkills)
344
+ const connectors = getPluginConnectors(target, manifest)
345
+ const mcpServers = []
346
+ for (const connector of connectors) {
347
+ if (!connector?.name) continue
348
+ const entry = getConnectorEntry(pluginName, connector.name)
349
+ if (!entry || entry.enabled === false) continue
350
+ mcpServers.push({
351
+ id: entry.id,
352
+ name: connector.name,
353
+ transport: connector.transport || entry.config?.type || 'stdio',
354
+ })
355
+ }
356
+ const agents = listAgents(target, manifest).map((a) => ({
357
+ name: a.name,
358
+ description: truncateOneLine(a.description),
359
+ }))
360
+ const prompts = listPrompts(target, manifest)
361
+ .map((p) => (typeof p === 'string'
362
+ ? { name: p, description: '' }
363
+ : { name: p?.name || '', description: truncateOneLine(p?.description) }))
364
+ .filter((p) => p.name)
365
+ return { skills, mcpServers, agents, prompts }
366
+ }
367
+
368
+ function escapeXmlAttr(value) {
369
+ return String(value || '')
370
+ .replace(/&/g, '&amp;')
371
+ .replace(/"/g, '&quot;')
372
+ .replace(/</g, '&lt;')
373
+ .replace(/>/g, '&gt;')
374
+ }
375
+
376
+ /** Build the Codex-style on-demand capability routing reminder text for one or more referenced plugins. */
377
+ export function renderExplicitPluginInstructions(entries) {
378
+ const sections = [
379
+ '<system-reminder>',
380
+ 'The user explicitly referenced the following installed plugin(s). Prioritize their capabilities for this turn using Codex-style selective on-demand loading:',
381
+ '',
382
+ ]
383
+ for (const { plugin, capabilities } of entries) {
384
+ const attrs = [
385
+ `name="${escapeXmlAttr(plugin.displayName || plugin.name)}"`,
386
+ `id="${escapeXmlAttr(plugin.name)}"`,
387
+ plugin.summary ? `summary="${escapeXmlAttr(truncateOneLine(plugin.summary))}"` : '',
388
+ ].filter(Boolean).join(' ')
389
+ sections.push(`<explicit_plugin ${attrs}>`)
390
+ const hasAny = capabilities.skills.length || capabilities.mcpServers.length || capabilities.agents.length || capabilities.prompts.length
391
+ if (!hasAny) {
392
+ sections.push('No active skills or enabled MCP servers are currently available for this plugin (any MCP connectors may be disabled or awaiting authentication).')
393
+ } else {
394
+ if (capabilities.skills.length) {
395
+ sections.push('Available skills (call the `skill` tool ONLY for the specific skill(s) relevant to the request):')
396
+ for (const s of capabilities.skills) {
397
+ sections.push(s.description ? `- ${s.name}: ${s.description}` : `- ${s.name}`)
398
+ }
399
+ }
400
+ if (capabilities.mcpServers.length) {
401
+ sections.push('Enabled MCP servers (use their exposed MCP tools directly when relevant; disabled connectors are excluded):')
402
+ for (const m of capabilities.mcpServers) {
403
+ sections.push(`- ${m.name} (${m.id})`)
404
+ }
405
+ }
406
+ if (capabilities.agents.length) {
407
+ sections.push('Available subagents / agents:')
408
+ for (const a of capabilities.agents) {
409
+ sections.push(a.description ? `- ${a.name}: ${a.description}` : `- ${a.name}`)
410
+ }
411
+ }
412
+ if (capabilities.prompts.length) {
413
+ sections.push('Available plugin prompts / commands:')
414
+ for (const p of capabilities.prompts) {
415
+ sections.push(p.description ? `- ${p.name}: ${p.description}` : `- ${p.name}`)
416
+ }
417
+ }
418
+ }
419
+ sections.push('</explicit_plugin>', '')
420
+ }
421
+ sections.push(
422
+ 'Routing rules:',
423
+ '1. Select intelligently: call the `skill` tool (`{ "name": "<skill-name>" }`) ONLY for the skill(s) clearly needed for the user task — never load unrelated skills just because they share a plugin.',
424
+ '2. Follow loaded skill instructions before taking action.',
425
+ '3. Use the listed enabled MCP tools directly when helpful; do not assume disabled or unlisted MCP servers are active.',
426
+ '</system-reminder>',
427
+ )
428
+ return sections.join('\n')
429
+ }
430
+
431
+ function getUserMessageCreator(resolveDshModules = findDshMainNodeModules) {
432
+ if (cachedCreateUserMessage) return cachedCreateUserMessage
433
+ try {
434
+ const main = resolveDshModules?.()
435
+ if (main) {
436
+ const req = createRequire(join(main, '.universal-plugin-hub-resolve.cjs'))
437
+ const llm = req('@deepseek-ai/dsh-llm')
438
+ if (typeof llm?.createUserMessage === 'function') {
439
+ cachedCreateUserMessage = llm.createUserMessage
440
+ return cachedCreateUserMessage
441
+ }
442
+ }
443
+ } catch {
444
+ // Fall back when running outside a live DSH host tree (e.g. standalone unit tests).
445
+ }
446
+ const deepFreeze = (value) => {
447
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
448
+ Object.freeze(value)
449
+ for (const v of Object.values(value)) deepFreeze(v)
450
+ return value
451
+ }
452
+ return (input) => deepFreeze(structuredClone({
453
+ role: 'user',
454
+ ...input,
455
+ id: randomUUID(),
456
+ }))
457
+ }
458
+
459
+ async function resolveAgentWorkingDirectory(hostCtx, agent, signal) {
460
+ if (agent === undefined) return undefined
461
+ const workingDirectory = resolveOptionalService(hostCtx, 'workingDirectory')
462
+ if (typeof workingDirectory?.ensure === 'function') {
463
+ return workingDirectory.ensure(agent, signal)
464
+ }
465
+ if (agent?.session && typeof workingDirectory?.get === 'function') {
466
+ return workingDirectory.get(agent.session)
467
+ }
468
+ return undefined
469
+ }
470
+
471
+ /**
472
+ * Register the `agent/pre-step` waterfall interceptor on DSH's agent service.
473
+ * Inspects only step-incoming user messages (`source.kind === 'user'`) for `@` plugin
474
+ * references and appends a compact `notice`-form context injection after workspace rules.
475
+ */
476
+ export function attachAtPluginsAgentHook(hostCtx, options = {}) {
477
+ const listPluginsFn = options.listPlugins || listAtPlugins
478
+ const collectCapsFn = options.collectCapabilities || collectPluginCapabilities
479
+ const createMessageFn = options.createUserMessage || getUserMessageCreator(options.findDshMainNodeModules)
480
+
481
+ if (typeof hostCtx?.on !== 'function') return () => {}
482
+ return hostCtx.on('agent/pre-step', async ({ agent, messages, signal } = {}, next) => {
483
+ const decision = await next()
484
+ if (!decision || decision.kind === 'reject') return decision
485
+ if (!Array.isArray(messages) || messages.length === 0) return decision
486
+
487
+ const plugins = listPluginsFn()
488
+ if (!plugins.length) return decision
489
+
490
+ const knownByName = new Map(plugins.map((p) => [p.name.toLowerCase(), p]))
491
+ const mentioned = []
492
+ const seenNames = new Set()
493
+
494
+ for (const msg of messages) {
495
+ if (!msg || msg.source?.kind !== 'user' || !Array.isArray(msg.content)) continue
496
+ for (const block of msg.content) {
497
+ if (!block || block.type !== 'text' || typeof block.text !== 'string') continue
498
+ for (const match of extractPluginMentions(block.text, knownByName)) {
499
+ const lower = match.plugin.name.toLowerCase()
500
+ if (seenNames.has(lower)) continue
501
+ seenNames.add(lower)
502
+ mentioned.push(match.plugin)
503
+ }
504
+ }
505
+ }
506
+
507
+ if (mentioned.length === 0) return decision
508
+ if (Array.isArray(decision.messages) && decision.messages.some((m) => m?.source?.kind === 'plugin-routing')) {
509
+ return decision
510
+ }
511
+ signal?.throwIfAborted?.()
512
+
513
+ let snapshotSkills = null
514
+ try {
515
+ const skillsService = resolveOptionalService(hostCtx, 'skills')
516
+ if (typeof skillsService?.snapshot === 'function') {
517
+ const cwd = await resolveAgentWorkingDirectory(hostCtx, agent, signal)
518
+ signal?.throwIfAborted?.()
519
+ const snapshot = await skillsService.snapshot({ cwd, signal, scope: agent })
520
+ if (snapshot && Array.isArray(snapshot.skills)) {
521
+ snapshotSkills = snapshot.skills
522
+ }
523
+ }
524
+ } catch (err) {
525
+ if (err?.name === 'AbortError' || signal?.aborted) throw err
526
+ // Snapshot lookup failed cleanly; fall back to local plugin skill manifest scan.
527
+ }
528
+ signal?.throwIfAborted?.()
529
+
530
+ const entries = mentioned.map((plugin) => ({
531
+ plugin,
532
+ capabilities: collectCapsFn(plugin.name, { snapshotSkills }),
533
+ }))
534
+ const injection = createMessageFn({
535
+ content: [{ type: 'text', text: renderExplicitPluginInstructions(entries) }],
536
+ source: {
537
+ kind: 'plugin-routing',
538
+ form: 'notice',
539
+ },
540
+ })
541
+
542
+ return {
543
+ ...decision,
544
+ messages: [...(Array.isArray(decision.messages) ? decision.messages : []), injection],
545
+ }
546
+ })
547
+ }
548
+
549
+ function safeDecodePluginTarget(rawTarget) {
550
+ try {
551
+ return decodeURIComponent(rawTarget)
552
+ } catch {
553
+ return rawTarget
554
+ }
555
+ }
556
+
557
+ function cleanDshTitleText(input) {
558
+ if (typeof input !== 'string') return ''
559
+ return input
560
+ .replace(TITLE_OSC_SEQUENCE_RE, '')
561
+ .replace(TITLE_CSI_SEQUENCE_RE, '')
562
+ .replace(TITLE_ESC_SEQUENCE_RE, '')
563
+ .replace(TITLE_CONTROL_CHARACTER_RE, '')
564
+ .replace(TITLE_DIRECTIONAL_CONTROL_RE, '')
565
+ .replace(/\s+/gu, ' ')
566
+ .trim()
567
+ }
568
+
569
+ function truncateTitleUtf8(input, maxBytes) {
570
+ let used = 0
571
+ let out = ''
572
+ for (const character of input) {
573
+ const bytes = Buffer.byteLength(character, 'utf8')
574
+ if (used + bytes > maxBytes) break
575
+ used += bytes
576
+ out += character
577
+ }
578
+ return out
579
+ }
580
+
581
+ function normalizeDshTitle(input, maxBytes) {
582
+ return truncateTitleUtf8(cleanDshTitleText(input), maxBytes).trimEnd()
583
+ }
584
+
585
+ function fallbackDshTitle(input, maxWords, maxBytes) {
586
+ return truncateTitleUtf8(
587
+ cleanDshTitleText(input).split(' ').filter(Boolean).slice(0, maxWords).join(' '),
588
+ maxBytes,
589
+ ).trimEnd()
590
+ }
591
+
592
+ /**
593
+ * Replace `@[DisplayName](uph-plugin:id)` wire mentions (including truncated
594
+ * trailing `uph-plugin:` fragments) with readable plugin display names.
595
+ */
596
+ export function stripPluginMentionsFromTitle(text) {
597
+ if (typeof text !== 'string') return ''
598
+ if (!text.includes('@[')) return text
599
+ const replaceMention = (_full, displayName, rawId) => {
600
+ if (cleanDshTitleText(displayName).length > 0) return displayName
601
+ return rawId ? safeDecodePluginTarget(rawId) : ''
602
+ }
603
+ return text
604
+ .replace(WIRE_MENTION_TEXT_RE, replaceMention)
605
+ .replace(WIRE_MENTION_TRUNCATED_TAIL_RE, replaceMention)
606
+ }
607
+
608
+ function resolvePositiveInt(value, fallback) {
609
+ return Number.isInteger(value) && value > 0 ? value : fallback
610
+ }
611
+
612
+ function resolveTitleLimits(sessionTitle) {
613
+ const cfg = sessionTitle && typeof sessionTitle === 'object' ? sessionTitle.config : null
614
+ return {
615
+ fallbackMaxWords: resolvePositiveInt(cfg?.fallbackMaxWords, DEFAULT_TITLE_FALLBACK_MAX_WORDS),
616
+ fallbackMaxBytes: resolvePositiveInt(cfg?.fallbackMaxBytes, DEFAULT_TITLE_FALLBACK_MAX_BYTES),
617
+ maxTitleBytes: resolvePositiveInt(cfg?.maxTitleBytes, DEFAULT_TITLE_MAX_BYTES),
618
+ }
619
+ }
620
+
621
+ function extractUserMessageText(event) {
622
+ if (!event || event.type !== 'user/message' || event.data?.source?.kind !== 'user') return undefined
623
+ const content = Array.isArray(event.data.content) ? event.data.content : []
624
+ const text = content
625
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
626
+ .map((block) => block.text)
627
+ .join('\n')
628
+ return normalizeDshTitle(text, Number.MAX_SAFE_INTEGER).length > 0 ? text : undefined
629
+ }
630
+
631
+ function isLiveSession(sessions, session) {
632
+ if (!session || typeof session.append !== 'function') return false
633
+ if (sessions && typeof sessions.get === 'function') {
634
+ return sessions.get(session.id) === session
635
+ }
636
+ return true
637
+ }
638
+
639
+ function readSessionEvent(session, seq) {
640
+ if (typeof seq !== 'number') return undefined
641
+ if (typeof session.eventAt === 'function') {
642
+ return session.eventAt(seq)
643
+ }
644
+ if (typeof session.snapshotEvents === 'function') {
645
+ return session.snapshotEvents().find((item) => item?.seq === seq)
646
+ }
647
+ return undefined
648
+ }
649
+
650
+ function readFirstTitleUserMessage(session) {
651
+ if (typeof session?.snapshotEvents !== 'function') return undefined
652
+ for (const item of session.snapshotEvents()) {
653
+ const text = extractUserMessageText(item)
654
+ if (text !== undefined) {
655
+ return { seq: item.seq, text }
656
+ }
657
+ }
658
+ return undefined
659
+ }
660
+
661
+ function readCurrentTitleSnapshot(sessionTitle, session) {
662
+ if (typeof sessionTitle?.get === 'function') {
663
+ return sessionTitle.get(session)
664
+ }
665
+ if (typeof session?.snapshotEvents === 'function') {
666
+ const events = session.snapshotEvents()
667
+ for (let i = events.length - 1; i >= 0; i--) {
668
+ const item = events[i]
669
+ if (item?.type === 'session/title') {
670
+ return {
671
+ title: item.data?.title,
672
+ messageSeqs: item.data?.messageSeqs,
673
+ source: item.data?.source,
674
+ eventSeq: item.seq,
675
+ }
676
+ }
677
+ }
678
+ }
679
+ return undefined
680
+ }
681
+
682
+ function cloneTitleSource(source) {
683
+ if (source?.kind === 'provider') {
684
+ const cloned = {
685
+ kind: 'provider',
686
+ provider: source.provider,
687
+ }
688
+ if (source.model && typeof source.model === 'object') {
689
+ cloned.model = {
690
+ provider: source.model.provider,
691
+ model: source.model.model,
692
+ }
693
+ }
694
+ return cloned
695
+ }
696
+ return { kind: 'fallback' }
697
+ }
698
+
699
+ function safeAppendCleanedTitle(session, payload) {
700
+ if (!payload?.title) return
701
+ try {
702
+ session.append('session/title', payload)
703
+ } catch {
704
+ // Ignore store detachment or concurrent disposal races.
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Subscribe to DSH `session/event` so fallback and LLM provider session titles
710
+ * strip `@[DisplayName](uph-plugin:id)` wire markup while preserving the raw
711
+ * `user/message` events used by `@` routing and chat chips.
712
+ */
713
+ export function attachAtPluginsSessionTitleHook(hostCtx) {
714
+ if (typeof hostCtx?.on !== 'function') return () => {}
715
+ let disposed = false
716
+
717
+ const handleUserMessage = (session, event) => {
718
+ const sessionTitle = resolveOptionalService(hostCtx, 'sessionTitle')
719
+ if (!sessionTitle) return
720
+ const rawText = extractUserMessageText(event)
721
+ if (rawText === undefined || !rawText.includes('uph-plugin:')) return
722
+
723
+ // 1-hop microtask beats DSH SessionTitleService's 2-hop defer -> ensureFallback
724
+ // while keeping onUserMessage's synchronous state.pending scheduling intact.
725
+ queueMicrotask(() => {
726
+ if (disposed) return
727
+ const liveSessions = resolveOptionalService(hostCtx, 'sessions')
728
+ const liveTitleService = resolveOptionalService(hostCtx, 'sessionTitle')
729
+ if (!liveTitleService || !isLiveSession(liveSessions, session)) return
730
+ if (readCurrentTitleSnapshot(liveTitleService, session) !== undefined) return
731
+
732
+ const first = readFirstTitleUserMessage(session)
733
+ if (!first) return
734
+ const limits = resolveTitleLimits(liveTitleService)
735
+ const nativeFallback = fallbackDshTitle(first.text, limits.fallbackMaxWords, limits.fallbackMaxBytes)
736
+ const cleanedFallback = fallbackDshTitle(
737
+ stripPluginMentionsFromTitle(first.text),
738
+ limits.fallbackMaxWords,
739
+ limits.fallbackMaxBytes,
740
+ )
741
+ if (!cleanedFallback || cleanedFallback === nativeFallback) return
742
+
743
+ safeAppendCleanedTitle(session, {
744
+ title: cleanedFallback,
745
+ messageSeqs: [first.seq],
746
+ source: { kind: 'fallback' },
747
+ })
748
+ })
749
+ }
750
+
751
+ const handleSessionTitle = (session, event) => {
752
+ const source = event?.data?.source
753
+ if (!source || source.kind === 'user') return
754
+ if (source.kind !== 'fallback' && source.kind !== 'provider') return
755
+ const rawTitle = event?.data?.title
756
+ if (typeof rawTitle !== 'string' || rawTitle.length === 0) return
757
+
758
+ const sessionTitle = resolveOptionalService(hostCtx, 'sessionTitle')
759
+ if (!sessionTitle) return
760
+ if (source.kind === 'provider' && !rawTitle.includes('uph-plugin:')) return
761
+
762
+ queueMicrotask(() => {
763
+ if (disposed) return
764
+ const liveSessions = resolveOptionalService(hostCtx, 'sessions')
765
+ const liveTitleService = resolveOptionalService(hostCtx, 'sessionTitle')
766
+ if (!liveTitleService || !isLiveSession(liveSessions, session)) return
767
+
768
+ const current = readCurrentTitleSnapshot(liveTitleService, session)
769
+ if (!current || current.eventSeq !== event.seq || current.source?.kind === 'user') return
770
+
771
+ const limits = resolveTitleLimits(liveTitleService)
772
+ const messageSeqs = Array.isArray(event.data.messageSeqs) ? [...event.data.messageSeqs] : []
773
+ let cleanedTitle = ''
774
+
775
+ if (source.kind === 'fallback') {
776
+ const firstSeq = messageSeqs[0]
777
+ const firstEvent = firstSeq !== undefined ? readSessionEvent(session, firstSeq) : undefined
778
+ const sourceText = extractUserMessageText(firstEvent)
779
+ if (sourceText !== undefined) {
780
+ if (!sourceText.includes('uph-plugin:')) return
781
+ cleanedTitle = fallbackDshTitle(
782
+ stripPluginMentionsFromTitle(sourceText),
783
+ limits.fallbackMaxWords,
784
+ limits.fallbackMaxBytes,
785
+ )
786
+ } else if (rawTitle.includes('uph-plugin:')) {
787
+ cleanedTitle = fallbackDshTitle(
788
+ stripPluginMentionsFromTitle(rawTitle),
789
+ limits.fallbackMaxWords,
790
+ limits.fallbackMaxBytes,
791
+ )
792
+ } else {
793
+ return
794
+ }
795
+ } else {
796
+ if (!rawTitle.includes('uph-plugin:')) return
797
+ cleanedTitle = normalizeDshTitle(stripPluginMentionsFromTitle(rawTitle), limits.maxTitleBytes)
798
+ }
799
+
800
+ if (!cleanedTitle || cleanedTitle === rawTitle) return
801
+
802
+ safeAppendCleanedTitle(session, {
803
+ title: cleanedTitle,
804
+ messageSeqs,
805
+ source: cloneTitleSource(source),
806
+ })
807
+ })
808
+ }
809
+
810
+ const off = hostCtx.on('session/event', (session, event) => {
811
+ if (disposed || !event || typeof event !== 'object') return
812
+ if (event.type === 'user/message') {
813
+ handleUserMessage(session, event)
814
+ } else if (event.type === 'session/title') {
815
+ handleSessionTitle(session, event)
816
+ }
817
+ })
818
+
819
+ return () => {
820
+ disposed = true
821
+ if (typeof off === 'function') off()
822
+ }
823
+ }