universal-plugin-hub 0.0.0-stage → 1.0.6

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,4 @@
1
+ # dsh bundle patch: inserts this plugin into a profile's layer stack.
2
+ - insert:
3
+ - id: universal-plugin-hub
4
+ name: 'universal-plugin-hub'
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "universal-plugin-hub",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "title": "Universal Plugin Hub",
4
+ "displayName": "Universal Plugin Hub",
5
+ "description": "DSH 插件市场:安装 Claude Code 与 Codex 插件、Skills 和命令,接入子代理、MCP、Hooks 与 LSP。",
6
+ "version": "1.0.6",
7
+ "type": "module",
8
+ "main": "src/index.js",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/Ultmebius/universal-plugin-hub.git"
13
+ },
14
+ "homepage": "https://github.com/Ultmebius/universal-plugin-hub#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/Ultmebius/universal-plugin-hub/issues"
17
+ },
18
+ "keywords": [
19
+ "deepseek",
20
+ "harness",
21
+ "dsh",
22
+ "dsh-plugin",
23
+ "dsh-bundle",
24
+ "marketplace",
25
+ "claude",
26
+ "plugins",
27
+ "claude-code",
28
+ "codex",
29
+ "agent-skills",
30
+ "mcp"
31
+ ],
32
+ "dependencies": {
33
+ "js-yaml": "^5.3.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@deepseek-ai/cordis": ">=4.0.1 <5.0.0"
37
+ },
38
+ "scripts": {
39
+ "postinstall": "node scripts/postinstall.js"
40
+ },
41
+ "dsh": {
42
+ "bundle": {
43
+ "patch": "./cordis.patch.yml"
44
+ },
45
+ "client": {
46
+ "inject": [
47
+ "@deepseek-ai/dsh-client-runtime",
48
+ "@deepseek-ai/dsh-client-locale",
49
+ "@deepseek-ai/dsh-client-ui-sidebar",
50
+ "@deepseek-ai/dsh-client-ui-layout",
51
+ "@deepseek-ai/dsh-client-ui-theme"
52
+ ],
53
+ "platform": "web"
54
+ }
55
+ },
56
+ "exports": {
57
+ ".": {
58
+ "default": "./src/index.js"
59
+ },
60
+ "./client": "./client/client.js",
61
+ "./cordis.patch.yml": "./cordis.patch.yml",
62
+ "./package.json": "./package.json"
63
+ },
64
+ "files": [
65
+ "src",
66
+ "client",
67
+ "scripts/postinstall.js",
68
+ "cordis.patch.yml",
69
+ "assets/hero.png"
70
+ ]
71
+ }
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Hub postinstall: pre-provision host packages that DSH's LSP provider
4
+ * and Claude hooks bridge need at runtime, into DSH's node_modules tree.
5
+ * Non-fatal: if provisioning is skipped or fails, warn and exit 0 so hub
6
+ * installation always succeeds.
7
+ */
8
+ import { installProfilePackages, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from '../src/install.js'
9
+
10
+ const ALL_HOST_PACKAGES = [...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]
11
+
12
+ try {
13
+ const result = await installProfilePackages(ALL_HOST_PACKAGES)
14
+ if (!result.ok) {
15
+ console.warn(`universal-plugin-hub: host package provisioning skipped: ${result.error}`)
16
+ } else if (result.installed?.length > 0) {
17
+ console.log(`universal-plugin-hub: installed host packages (${result.installed.join(', ')})`)
18
+ } else {
19
+ console.log('universal-plugin-hub: host packages already present, nothing to do')
20
+ }
21
+ } catch (err) {
22
+ console.warn(`universal-plugin-hub: host package provisioning skipped (${err.message})`)
23
+ }
@@ -0,0 +1,515 @@
1
+ /**
2
+ * Claude Code Agent Definitions → DSH Subagent Hub & Delegation Architecture.
3
+ *
4
+ * In Claude Code:
5
+ * 1. commands/ (and explicit skills/) are user-facing slash commands (/commit, /review-pr).
6
+ * 2. agents/ (agents/*.md, agents/*.yaml, agent.json) are autonomous subagent personas
7
+ * invoked internally by the orchestrator via tool delegation (subagent/Task), NOT spammed
8
+ * as dozens of top-level user slash commands.
9
+ *
10
+ * This adapter parses Claude subagent definitions and compiles a consolidated, high-fidelity
11
+ * Subagent Hub Skill (`skills/<pluginName>-agents/SKILL.md`) for DSH.
12
+ * DSH's primary model in Standard Mode reads the Hub Skill and autonomously delegates
13
+ * complex tasks to the specialized subagents via DSH's native `@deepseek-ai/dsh-tool-subagent` tool,
14
+ * completely avoiding slash command palette clutter, preset pollution, and naming collisions.
15
+ */
16
+ import { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { load as parseYaml } from 'js-yaml'
19
+ import { dshHome, safeRmDir } from './store.js'
20
+ import { safeSegment } from './market.js'
21
+
22
+ export const PRESET_ROOT = () => join(dshHome(), '.agent-presets')
23
+
24
+ /**
25
+ * Legacy Preset Cleanup:
26
+ * Removes any leftover top-level presets in ~/.dsh/.agent-presets created by earlier versions.
27
+ */
28
+ export function cleanupLegacyPresets(pluginName) {
29
+ try {
30
+ const root = PRESET_ROOT()
31
+ if (!existsSync(root)) return
32
+ const prefix = pluginName ? `${pluginName}-` : ''
33
+ for (const entry of readdirSync(root)) {
34
+ if (!prefix || entry.startsWith(prefix) || entry === pluginName) {
35
+ const dir = join(root, entry)
36
+ safeRmDir(dir)
37
+ }
38
+ }
39
+ } catch {
40
+ // ignore cleanup errors
41
+ }
42
+ }
43
+
44
+
45
+ /**
46
+ * Parse one Claude agent definition file (.yaml|.yml|.md|.json).
47
+ *
48
+ * @param {string} pluginName - Plugin name
49
+ * @param {string} agentFile - Filename (e.g. 'code-reviewer.md')
50
+ * @param {string} rawText - File contents
51
+ * @returns {object|null} - Parsed agent descriptor or { error }
52
+ */
53
+ export function parseAgentDefinition(pluginName, agentFile, rawText) {
54
+ safeSegment(pluginName, 'plugin name')
55
+ const cleanText = (rawText ?? '').trim()
56
+ if (!cleanText) return null
57
+
58
+ let doc = null
59
+ let bodyContent = ''
60
+
61
+ if (/\.json$/i.test(agentFile)) {
62
+ try {
63
+ doc = JSON.parse(cleanText)
64
+ bodyContent = doc.prompt || doc.system_prompt || doc.instructions || doc.description || ''
65
+ } catch {
66
+ return { error: `${agentFile}: invalid JSON` }
67
+ }
68
+ } else if (/\.md$/i.test(agentFile)) {
69
+ const match = cleanText.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/)
70
+ if (match) {
71
+ try {
72
+ doc = parseYaml(match[1]) || {}
73
+ bodyContent = match[2] ? match[2].trim() : (doc.prompt || doc.system_prompt || doc.instructions || '')
74
+ } catch {
75
+ return { error: `${agentFile}: invalid Markdown frontmatter` }
76
+ }
77
+ } else {
78
+ doc = { description: cleanText.slice(0, 160) }
79
+ bodyContent = cleanText
80
+ }
81
+ } else {
82
+ try {
83
+ doc = parseYaml(cleanText)
84
+ bodyContent = doc?.prompt || doc?.system_prompt || doc?.instructions || ''
85
+ } catch {
86
+ return { error: `${agentFile}: invalid YAML` }
87
+ }
88
+ }
89
+
90
+ if (!doc || typeof doc !== 'object') return { error: `${agentFile}: empty agent definition` }
91
+
92
+ const baseName = agentFile.replace(/\.(ya?ml|md|json)$/i, '')
93
+ const iface = doc.interface && typeof doc.interface === 'object' ? doc.interface : {}
94
+ const rawName = typeof doc.name === 'string' ? doc.name : (typeof iface.display_name === 'string' ? iface.display_name : baseName)
95
+ const name = rawName.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || baseName
96
+ const displayName = typeof iface.display_name === 'string' ? iface.display_name : (typeof doc.name === 'string' ? doc.name : baseName)
97
+
98
+ let description = typeof iface.short_description === 'string'
99
+ ? iface.short_description
100
+ : (typeof doc.description === 'string' ? doc.description : '')
101
+
102
+ if (!description && bodyContent) {
103
+ const firstLine = bodyContent.split(/\r?\n/).find((l) => l.trim() && !l.startsWith('#') && !l.startsWith('---'))
104
+ if (firstLine) description = firstLine.trim().slice(0, 200)
105
+ }
106
+ if (!description) {
107
+ description = `Specialized subagent for ${displayName} from ${pluginName}.`
108
+ }
109
+
110
+ const tools = doc.tools || doc.allowedTools || iface.tools || null
111
+ const model = doc.model || null
112
+
113
+ return {
114
+ file: agentFile,
115
+ name,
116
+ displayName,
117
+ description,
118
+ tools: Array.isArray(tools) ? tools.join(', ') : (tools ? String(tools) : null),
119
+ model: model ? String(model) : null,
120
+ instructions: bodyContent || `You are ${displayName}, a specialized subagent for ${pluginName}.`,
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Universal Semantic Domain Taxonomy for AI & Claude Subagents across ALL disciplines.
126
+ * Covers Software, Cloud, Data, AI, Security, Testing, Design, Media, Writing, Marketing,
127
+ * Finance, Legal, Healthcare, Ops, Open Source, and beyond.
128
+ */
129
+ export const AGENT_DOMAINS = [
130
+ // 1. Software & Languages
131
+ {
132
+ id: 'code-review',
133
+ title: 'Code Review & Language Analysis',
134
+ icon: '💻',
135
+ description: 'Code review, syntax patterns, linting, code refactoring and language-specific best practices',
136
+ patterns: [
137
+ /\b(review|reviewer|reviewing|audit|lint|linter|style|pattern|idiom|syntax|refactor|refactoring|clean-code|simplifier|comment-analyzer|convention)\b/i,
138
+ /\b(python|golang|go|java|javascript|typescript|ts|js|csharp|c#|cpp|c\+\+|swift|kotlin|rust|php|dart|ruby|scala|fsharp|f#|html|css|sql|vue|react|angular|svelte)[-_]?(reviewer|lint|style|pattern|refactor)/i,
139
+ ],
140
+ },
141
+ // 2. Build & Runtime
142
+ {
143
+ id: 'build-troubleshoot',
144
+ title: 'Build, Runtime & Troubleshooting',
145
+ icon: '🔧',
146
+ description: 'Build error diagnosis, runtime crash fixes, dependency troubleshooting and compiler issue resolution',
147
+ patterns: [
148
+ /\b(build|resolver|compiler|compile|error|bug|crash|fault|troubleshoot|troubleshooter|fix|repair|diagnos|diagnosis|exception|stacktrace|log-analyzer|patcher|healthcheck)\b/i,
149
+ /\b(python|golang|go|java|javascript|typescript|ts|js|csharp|cpp|swift|kotlin|rust|php|dart|fsharp|django|fastapi|harmonyos)[-_]?(build|resolver|fixer)/i,
150
+ ],
151
+ },
152
+ // 3. Architecture & Modularity
153
+ {
154
+ id: 'architecture-design',
155
+ title: 'System Architecture & Modularity',
156
+ icon: '🏛️',
157
+ description: 'System modularity, service boundaries, architecture review, RFC specs and technical planning',
158
+ patterns: [
159
+ /\b(architect|architecture|design|modularity|boundary|boundaries|system-design|infrastructure|diagram|rfc|spec|homelab|network-architect|chief-of-staff|a11y-architect)\b/i,
160
+ ],
161
+ },
162
+ // 4. Performance & Profiling
163
+ {
164
+ id: 'performance-optimization',
165
+ title: 'Performance, Speed & Profiling',
166
+ icon: '⚡',
167
+ description: 'Latency profiling, memory leak detection, resource tuning, query optimization and throughput boosting',
168
+ patterns: [
169
+ /\b(perform|performance|optimizer|optimize|optimization|profiler|profile|profiling|speed|fast|latency|throughput|memory-leak|leak|tuning|tuner|cache|caching|benchmark|harness-optimizer)\b/i,
170
+ ],
171
+ },
172
+ // 5. Security & Privacy
173
+ {
174
+ id: 'security-compliance',
175
+ title: 'Security, Privacy & Compliance',
176
+ icon: '🛡️',
177
+ description: 'Security audits, vulnerability scanning, authentication, secrets sanitization and compliance checks',
178
+ patterns: [
179
+ /\b(security|secure|vuln|vulnerability|cve|owasp|auth|authentication|oauth|sanitizer|sanitize|firewall|guard|compliance|privacy|secret|token|encrypt|safety|penetration|risk)\b/i,
180
+ ],
181
+ },
182
+ // 6. Database & Storage
183
+ {
184
+ id: 'database-data',
185
+ title: 'Database, Storage & Data Analytics',
186
+ icon: '🗄️',
187
+ description: 'Database schema design, SQL queries, migrations, storage optimization, data pipelines and analytics',
188
+ patterns: [
189
+ /\b(database|db|sql|postgres|mysql|sqlite|mongo|redis|prisma|orm|migration|schema|storage|data|dataset|etl|mle|analytics|bi|warehouse|snowflake|databricks)\b/i,
190
+ ],
191
+ },
192
+ // 7. Testing & QA
193
+ {
194
+ id: 'testing-qa',
195
+ title: 'Testing, QA & Verification',
196
+ icon: '🧪',
197
+ description: 'Unit testing, integration testing, E2E test suites, QA evaluation, grading and assertion verifications',
198
+ patterns: [
199
+ /\b(test|tester|testing|e2e|e2e-runner|qa|quality|assert|assertion|eval|evaluator|evaluation|grading|mock|stub|suite|regression|ui-tester|unit-test|coverage)\b/i,
200
+ ],
201
+ },
202
+ // 8. Cloud & DevOps
203
+ {
204
+ id: 'network-cloud-ops',
205
+ title: 'Network, Cloud & DevOps Infrastructure',
206
+ icon: '🌐',
207
+ description: 'Network configuration, cloud orchestration, container management, networking diagnostics and CI/CD ops',
208
+ patterns: [
209
+ /\b(network|networking|cloud|aws|azure|gcp|k8s|kubernetes|docker|container|devops|deploy|deployment|cluster|router|dns|server|loop-operator|sysadmin|zero-downtime|terraform|ansible|sre)\b/i,
210
+ ],
211
+ },
212
+ // 9. AI & Autonomous Workflows
213
+ {
214
+ id: 'ai-workflows',
215
+ title: 'AI, Model Planning & Autonomous Workflows',
216
+ icon: '🤖',
217
+ description: 'Autonomous generation, multi-stage planning, GAN pipelines, workflow synthesis and agent orchestration',
218
+ patterns: [
219
+ /\b(gan|generator|gan-generator|gan-planner|gan-evaluator|planner|planning|agent-evaluator|prompt|workflow|workflow-automator|orchestrat|autonomous|coordinator|llm|deeplearning|neural|cognitive)\b/i,
220
+ ],
221
+ },
222
+ // 10. Design & Creative Media
223
+ {
224
+ id: 'design-uiux',
225
+ title: 'Design, UI/UX & Visual Media',
226
+ icon: '🎨',
227
+ description: 'UI/UX interface design, layout wireframes, design tokens, color palettes, visual assets and typography',
228
+ patterns: [
229
+ /\b(design|designer|ui|ux|frontend|layout|wireframe|figma|palette|color|theme|visual|graphic|artwork|canvas|icon|typography|font|tailwind|css-in-js)\b/i,
230
+ ],
231
+ },
232
+ // 11. Video & Audio Media
233
+ {
234
+ id: 'video-audio-media',
235
+ title: 'Video, Audio & Multimedia Processing',
236
+ icon: '🎬',
237
+ description: 'Video editing, speech/audio synthesis, subtitle generation, transcription and multimedia stream processing',
238
+ patterns: [
239
+ /\b(video|film|movie|clip|record|obs|ffmpeg|render|capcut|premiere|vfx|motion|animation|reels|subtitle|caption|audio|voice|speech|tts|whisper|sound|music|podcast|vocal|elevenlabs)\b/i,
240
+ ],
241
+ },
242
+ // 12. Writing, Docs & Knowledge
243
+ {
244
+ id: 'docs-writing-research',
245
+ title: 'Writing, Documentation & Knowledge Synthesis',
246
+ icon: '📝',
247
+ description: 'Technical writing, documentation generation, markdown formatting, wiki maintenance and research summarization',
248
+ patterns: [
249
+ /\b(doc|docs|documentation|updater|doc-updater|lookup|docs-lookup|readme|wiki|manual|handbook|knowledge|writer|writing|copywriting|article|essay|blog|summary|summarizer|translate|translation|research|researcher)\b/i,
250
+ ],
251
+ },
252
+ // 13. Marketing, Growth & Social Media
253
+ {
254
+ id: 'marketing-growth',
255
+ title: 'Marketing, Growth & Social Outreach',
256
+ icon: '📢',
257
+ description: 'SEO strategy, social media campaigns, copywriting, advertising, outreach and audience growth',
258
+ patterns: [
259
+ /\b(market|marketing|growth|seo|social|outreach|campaign|ads|copywriter|ad-copy|newsletter|twitter|weibo|wechat|discord|xhs|viral|audience|brand|branding)\b/i,
260
+ ],
261
+ },
262
+ // 14. Finance, Business, Legal & E-Commerce
263
+ {
264
+ id: 'finance-business-legal',
265
+ title: 'Finance, Business, Legal & E-Commerce',
266
+ icon: '📈',
267
+ description: 'Financial analysis, accounting, tax estimation, legal contract review, e-commerce catalog and business analytics',
268
+ patterns: [
269
+ /\b(finance|financial|money|cash|invoice|billing|accounting|tax|taxation|ledger|coin|crypto|tokenomics|contract|legal|lawyer|clause|compliance-legal|shop|store|cart|commerce|ecommerce|product-catalog|pricing|revenue)\b/i,
270
+ ],
271
+ },
272
+ // 15. Healthcare, Medical & Life Sciences
273
+ {
274
+ id: 'healthcare-medical',
275
+ title: 'Healthcare, Medical & Life Sciences',
276
+ icon: '🏥',
277
+ description: 'Clinical summaries, medical diagnostics assistance, healthcare workflow analysis and bioinformatics',
278
+ patterns: [
279
+ /\b(health|healthcare|medical|medicine|clinical|clinic|doctor|patient|diagnosis|radiology|pathology|biotech|bioinformatics|pharma|pharmacy|drug|genomic|hipaa)\b/i,
280
+ ],
281
+ },
282
+ // 16. Open Source & Release Delivery
283
+ {
284
+ id: 'opensource-packaging',
285
+ title: 'Open Source, Packaging & Delivery',
286
+ icon: '📦',
287
+ description: 'Open source repository management, forking, packaging, distribution and artifact publishing',
288
+ patterns: [
289
+ /\b(opensource|open-source|forker|fork|packager|package|packaging|release|release-manager|publisher|publish|bundle|distribution|tarball|npm|pip|cargo|nuget)\b/i,
290
+ ],
291
+ },
292
+ ]
293
+
294
+ /**
295
+ * Dynamic Topic Extractor for unknown/exotic domains.
296
+ * Generates an adaptive domain cluster name from agent title/words.
297
+ */
298
+ function extractDynamicDomain(agent) {
299
+ const raw = String(agent?.displayName || agent?.name || 'Specialist').trim()
300
+ const clean = raw
301
+ .replace(/[-_]+/g, ' ')
302
+ .replace(/\b(agent|subagent|assistant|specialist|bot|tool|expert|helper|resolver|reviewer|advisor|manager)\b/gi, '')
303
+ .trim()
304
+
305
+ const topicName = clean.length > 2
306
+ ? clean.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ')
307
+ : raw
308
+
309
+ return {
310
+ id: `custom-${topicName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`,
311
+ title: `${topicName} Specialists`,
312
+ icon: '🎯',
313
+ description: `Domain-specific autonomous task specialists for ${topicName} and specialized workflows`,
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Classify a subagent into its best-matching semantic domain (with universal multi-signal scoring + dynamic adaptive fallback).
319
+ */
320
+ export function classifyAgent(agent) {
321
+ const name = String(agent?.name || '').toLowerCase()
322
+ const displayName = String(agent?.displayName || '').toLowerCase()
323
+ const description = String(agent?.description || '').toLowerCase()
324
+ const file = String(agent?.file || '').toLowerCase()
325
+ const instructionsHead = String(agent?.instructions || '').slice(0, 300).toLowerCase()
326
+
327
+ let bestDomain = null
328
+ let highestScore = 0
329
+
330
+ for (const domain of AGENT_DOMAINS) {
331
+ let score = 0
332
+ for (const pattern of domain.patterns) {
333
+ if (pattern.test(name) || pattern.test(file)) score += 6
334
+ if (pattern.test(displayName)) score += 4
335
+ if (pattern.test(description)) score += 3
336
+ if (pattern.test(instructionsHead)) score += 1
337
+ }
338
+ if (score > highestScore) {
339
+ highestScore = score
340
+ bestDomain = domain
341
+ }
342
+ }
343
+
344
+ // Dynamic fallback: extract semantic topic if score is 0
345
+ if (!bestDomain || highestScore === 0) {
346
+ return extractDynamicDomain(agent)
347
+ }
348
+
349
+ return bestDomain
350
+ }
351
+
352
+ /**
353
+ * Group a list of agents into active semantic domains.
354
+ */
355
+ export function groupAgentsByDomain(agentsList) {
356
+ if (!Array.isArray(agentsList) || agentsList.length === 0) return []
357
+
358
+ const domainMap = new Map()
359
+
360
+ for (const agent of agentsList) {
361
+ const domain = classifyAgent(agent)
362
+ if (!domainMap.has(domain.id)) {
363
+ domainMap.set(domain.id, { domain, agents: [] })
364
+ }
365
+ domainMap.get(domain.id).agents.push(agent)
366
+ }
367
+
368
+ // Sort domains: defined order first, then count descending
369
+ return Array.from(domainMap.values()).sort((a, b) => b.agents.length - a.agents.length)
370
+ }
371
+
372
+ /**
373
+ * Generate Level 1 Frontmatter description with high-density domain clustering.
374
+ */
375
+ export function generateLevel1Description(pluginName, pluginDisplayName, agentsList, domainGroups) {
376
+ const title = pluginDisplayName || pluginName
377
+ const count = agentsList.length
378
+
379
+ if (count === 1) {
380
+ const a = agentsList[0]
381
+ const cleanDesc = a.description ? `: ${a.description.slice(0, 100)}` : ''
382
+ return `Specialized autonomous agent for ${a.displayName}${cleanDesc}. Use when task matches ${a.name}. MANDATORY: Proactively delegate to this subagent using DSH's subagent tool.`
383
+ }
384
+
385
+ if (count <= 3) {
386
+ const listStr = agentsList.map((a) => a.displayName).join(', ')
387
+ return `Specialized autonomous subagents from ${title} (${listStr}). Use when encountering matching domain tasks. MANDATORY: Proactively delegate execution via DSH's subagent tool.`
388
+ }
389
+
390
+ // Multi-agent (4+ to 100+ agents): high-density semantic domain clustering
391
+ const topDomainNames = domainGroups
392
+ .slice(0, 4)
393
+ .map((g) => g.domain.title.split('&')[0].trim())
394
+ .join(', ')
395
+
396
+ return `Autonomous subagent suite from ${title} (${count} specialist roles) covering: ${topDomainNames}, and more. Use when user requests matching domain tasks. MANDATORY: Proactively delegate matching execution to the respective subagent via DSH's subagent tool.`
397
+ }
398
+
399
+ /**
400
+ * Compile a set of Claude subagents into a clean, consolidated DSH Subagent Hub Skill.
401
+ *
402
+ * @param {string} pluginName - Plugin name
403
+ * @param {string} pluginDisplayName - Display title
404
+ * @param {Array<object>} agentsList - List of parsed agent descriptors
405
+ * @param {string} skillsDir - Target skills/ directory for the plugin
406
+ * @returns {object} - { skillName, skillPath, command, subagentCount }
407
+ */
408
+ export function compileSubagentsHubSkill(pluginName, pluginDisplayName, agentsList, skillsDir) {
409
+ safeSegment(pluginName, 'plugin name')
410
+ if (!agentsList || agentsList.length === 0) return null
411
+
412
+ const isSingle = agentsList.length === 1
413
+ const subName = (agentsList[0]?.name || '').toLowerCase()
414
+ let skillName
415
+ if (isSingle) {
416
+ if (!subName || subName === pluginName.toLowerCase()) {
417
+ skillName = `${pluginName}-subagent`
418
+ } else if (subName.startsWith(`${pluginName.toLowerCase()}-`)) {
419
+ skillName = subName
420
+ } else {
421
+ skillName = `${pluginName}-${subName}`
422
+ }
423
+ } else {
424
+ skillName = `${pluginName}-agents`
425
+ }
426
+ const hubDir = join(skillsDir, skillName)
427
+ mkdirSync(hubDir, { recursive: true })
428
+ const hubFile = join(hubDir, 'SKILL.md')
429
+
430
+ const domainGroups = groupAgentsByDomain(agentsList)
431
+ const descText = generateLevel1Description(pluginName, pluginDisplayName, agentsList, domainGroups)
432
+
433
+ const lines = [
434
+ '---',
435
+ `name: ${skillName}`,
436
+ `description: ${yamlScalar(descText)}`,
437
+ '---',
438
+ '',
439
+ `# ${pluginDisplayName || pluginName} — Specialized Subagents Hub`,
440
+ '',
441
+ `> **Plugin**: \`${pluginName}\` | **Specialist Subagents**: ${agentsList.length} roles across ${domainGroups.length} semantic domains`,
442
+ '> **Execution Model**: Autonomous task-level subagent delegation via DSH `@deepseek-ai/dsh-tool-subagent` (`subagent`).',
443
+ '',
444
+ '## ⚡ Autonomous Subagent Delegation Protocol (MANDATORY)',
445
+ '',
446
+ 'When the user requests complex or domain-specific work matching any of the specialized subagents listed below:',
447
+ '1. **DO NOT** attempt to perform the specialized task yourself with general tools if a specialized subagent exists.',
448
+ '2. **PROACTIVELY DELEGATE**: Immediately invoke DSH\'s native `subagent` tool.',
449
+ '3. **Parameter Construction**:',
450
+ ' - `description`: `"[Subagent Name] - [Brief task summary]"` (e.g. `"go-reviewer - Review Go concurrency code"`).',
451
+ ' - `prompt`: Combine the **Subagent System Prompt** provided below with the specific user task context, file paths, requirements, and diffs.',
452
+ ' - `run_in_background`: `false` (default for synchronous analysis) or `true` (for parallel background exploration).',
453
+ '4. **Synthesize & Report**: When the subagent execution finishes, review its findings and present a clean, structured report to the user.',
454
+ '',
455
+ '## 🗺️ Categorized Subagent Routing Index',
456
+ '',
457
+ ]
458
+
459
+ // Level 2: Categorized Routing Index Table
460
+ for (const group of domainGroups) {
461
+ lines.push(`### ${group.domain.icon} ${group.domain.title} (${group.agents.length} roles)`)
462
+ lines.push(`> ${group.domain.description}`)
463
+ lines.push('')
464
+ lines.push('| Subagent | Role / Display Name | Primary Focus & Capabilities | Recommended Tools | Model |')
465
+ lines.push('| :--- | :--- | :--- | :--- | :--- |')
466
+ for (const a of group.agents) {
467
+ const toolStr = a.tools ? `\`${a.tools}\`` : '`default`'
468
+ const modelStr = a.model ? `\`${a.model}\`` : '`default`'
469
+ const cleanDesc = (a.description || 'Specialist subagent').replace(/\|/g, '\\|')
470
+ lines.push(`| \`${a.name}\` | **${a.displayName}** | ${cleanDesc} | ${toolStr} | ${modelStr} |`)
471
+ }
472
+ lines.push('')
473
+ }
474
+
475
+ lines.push('---')
476
+ lines.push('')
477
+ lines.push('## 📋 Detailed Subagent Roles & System Prompts')
478
+ lines.push('')
479
+
480
+ let globalIndex = 1
481
+ for (const group of domainGroups) {
482
+ lines.push(`### ${group.domain.icon} ${group.domain.title}`)
483
+ lines.push('')
484
+ for (const a of group.agents) {
485
+ lines.push(`#### ${globalIndex}. \`${a.name}\` — ${a.displayName}`)
486
+ lines.push(`- **Role Summary**: ${a.description}`)
487
+ if (a.tools) lines.push(`- **Recommended Tools**: ${a.tools}`)
488
+ if (a.model) lines.push(`- **Preferred Model Tier**: ${a.model}`)
489
+ lines.push(`- **Source Definition**: \`agents/${a.file}\``)
490
+ lines.push('')
491
+ lines.push('##### Subagent System Prompt for Delegation:')
492
+ lines.push('```markdown')
493
+ lines.push(a.instructions)
494
+ lines.push('```')
495
+ lines.push('')
496
+ globalIndex++
497
+ }
498
+ }
499
+
500
+ writeFileSync(hubFile, lines.join('\n'), 'utf8')
501
+
502
+ return {
503
+ skillName,
504
+ skillPath: hubFile,
505
+ command: `/${skillName}`,
506
+ subagentCount: agentsList.length,
507
+ domainCount: domainGroups.length,
508
+ }
509
+ }
510
+
511
+ function yamlScalar(value) {
512
+ const text = String(value || '')
513
+ if (/^[A-Za-z0-9 _./:-]+$/.test(text) && !text.includes('\n')) return text
514
+ return JSON.stringify(text)
515
+ }
package/src/http.js ADDED
@@ -0,0 +1,46 @@
1
+ /** Minimal HTTP helpers for webServer route handlers. */
2
+
3
+ export function sendJson(res, status, payload) {
4
+ const body = JSON.stringify(payload ?? {})
5
+ res.writeHead(status, {
6
+ 'Content-Type': 'application/json; charset=utf-8',
7
+ 'Cache-Control': 'no-store',
8
+ })
9
+ res.end(body)
10
+ }
11
+
12
+ export function readJsonBody(req, maxBytes = 1_000_000) {
13
+ return new Promise((resolve, reject) => {
14
+ let data = ''
15
+ req.on('data', (chunk) => {
16
+ data += chunk
17
+ if (data.length > maxBytes) {
18
+ reject(new Error('request body too large'))
19
+ req.destroy()
20
+ }
21
+ })
22
+ req.on('end', () => {
23
+ if (!data) return resolve({})
24
+ try {
25
+ resolve(JSON.parse(data))
26
+ } catch (error) {
27
+ reject(error)
28
+ }
29
+ })
30
+ req.on('error', reject)
31
+ })
32
+ }
33
+
34
+ /** Same-origin check (all market writes mutate the host filesystem). */
35
+ export function sameOrigin(req) {
36
+ const origin = req.headers.origin
37
+ if (!origin) return true // non-browser clients (curl) are allowed
38
+ const host = req.headers.host
39
+ if (!host) return false
40
+ try {
41
+ const o = new URL(origin)
42
+ return o.host === host
43
+ } catch {
44
+ return false
45
+ }
46
+ }