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.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/README.zh.md +94 -0
- package/assets/hero.png +0 -0
- package/client/client.js +10504 -0
- package/cordis.patch.yml +4 -0
- package/package.json +69 -4
- package/scripts/postinstall.js +23 -0
- package/src/agents-map.js +515 -0
- package/src/http.js +46 -0
- package/src/icons.js +123 -0
- package/src/index.js +32 -0
- package/src/install.js +2017 -0
- package/src/local.js +251 -0
- package/src/market.js +218 -0
- package/src/parser.js +1038 -0
- package/src/routes.js +559 -0
- package/src/store.js +254 -0
package/src/install.js
ADDED
|
@@ -0,0 +1,2017 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Install / uninstall / toggle / update lifecycle for plugins.
|
|
3
|
+
*
|
|
4
|
+
* On install the plugin directory is copied into the hub's own
|
|
5
|
+
* `installed/` tree and its `skills/` directory is registered in the
|
|
6
|
+
* dsh-agent-skills scan state (`$DSH_HOME/agent-skills/state.json`), so the
|
|
7
|
+
* next DSH restart (or registry re-scan) exposes the plugin's skills to
|
|
8
|
+
* agents.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync, renameSync, readdirSync, copyFileSync, statSync, accessSync, constants as fsConstants } from 'node:fs'
|
|
11
|
+
import { dirname, join, basename, isAbsolute, resolve, extname, delimiter } from 'node:path'
|
|
12
|
+
import { spawn, execFile, execFileSync } from 'node:child_process'
|
|
13
|
+
import { gunzipSync } from 'node:zlib'
|
|
14
|
+
import { homedir } from 'node:os'
|
|
15
|
+
import * as yaml from 'js-yaml'
|
|
16
|
+
import { installedDir, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir } from './store.js'
|
|
17
|
+
import { materializePlugin, pullSource, pluginPath } from './market.js'
|
|
18
|
+
import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, resolveHookConfigPath, invalidateParserCaches, invalidateMarketplaceCache } from './parser.js'
|
|
19
|
+
import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
|
|
20
|
+
import { buildPluginIcons } from './icons.js'
|
|
21
|
+
|
|
22
|
+
/** Active profile name: env DSH_PROFILE -> desktop (if present) -> web. */
|
|
23
|
+
export function resolveActiveProfileName() {
|
|
24
|
+
if (process.env.DSH_PROFILE) return process.env.DSH_PROFILE
|
|
25
|
+
const desktopDir = join(dshHome(), 'profiles', 'desktop')
|
|
26
|
+
if (existsSync(desktopDir)) return 'desktop'
|
|
27
|
+
return 'web'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** cordis.patch.yml path (auto-detects desktop or web profile). */
|
|
31
|
+
export function cordisPatchPath() {
|
|
32
|
+
const profileName = resolveActiveProfileName()
|
|
33
|
+
const profilePatch = join(dshHome(), 'profiles', profileName, 'cordis.patch.yml')
|
|
34
|
+
if (existsSync(profilePatch)) return profilePatch
|
|
35
|
+
const homePatch = join(dshHome(), 'cordis.patch.yml')
|
|
36
|
+
if (existsSync(homePatch)) return homePatch
|
|
37
|
+
return profilePatch
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function readCordisPatch() {
|
|
41
|
+
const file = cordisPatchPath()
|
|
42
|
+
if (!existsSync(file)) return []
|
|
43
|
+
try {
|
|
44
|
+
const parsed = yaml.load(readFileSync(file, 'utf8'))
|
|
45
|
+
return Array.isArray(parsed) ? parsed : []
|
|
46
|
+
} catch {
|
|
47
|
+
return []
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function writeCordisPatch(patch) {
|
|
52
|
+
const file = cordisPatchPath()
|
|
53
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
54
|
+
const content = yaml.dump(patch, { indent: 2, lineWidth: -1 })
|
|
55
|
+
const tmp = join(dirname(file), `.cordis.patch.${process.pid}.${Date.now().toString(36)}.tmp`)
|
|
56
|
+
writeFileSync(tmp, content, 'utf8')
|
|
57
|
+
renameSync(tmp, file)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function getConnectorId(pluginName, connectorName) {
|
|
61
|
+
return `mcp-${slugify(pluginName)}-${slugify(connectorName)}`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function getConnectorEntry(pluginName, connectorName) {
|
|
65
|
+
const patch = readCordisPatch()
|
|
66
|
+
const id = getConnectorId(pluginName, connectorName)
|
|
67
|
+
for (const block of patch) {
|
|
68
|
+
if (block && Array.isArray(block.insert)) {
|
|
69
|
+
const found = block.insert.find((item) => item && item.id === id)
|
|
70
|
+
if (found) return found
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function connectorRequiresAuth(cfg) {
|
|
77
|
+
if (!cfg) return true
|
|
78
|
+
const isHttp = (cfg.type === 'http' || cfg.type === 'sse' || (!cfg.command && (!!cfg.url || !cfg.args?.length)))
|
|
79
|
+
|
|
80
|
+
// 1. If HTTP / SSE connector has NO valid URL or empty placeholder URL, it ALWAYS requires configuration/auth!
|
|
81
|
+
if (isHttp) {
|
|
82
|
+
if (!cfg.url || typeof cfg.url !== 'string' || !cfg.url.trim() || !/^https?:\/\//i.test(cfg.url.trim())) {
|
|
83
|
+
return true
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
// Stdio connector with NO command ALWAYS requires configuration/auth!
|
|
87
|
+
if (!cfg.command || typeof cfg.command !== 'string' || !cfg.command.trim()) {
|
|
88
|
+
return true
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 2. If URL explicitly embeds a concrete API key / token query parameter (e.g. Tavily: ?api_key=tvly-...)
|
|
93
|
+
if (cfg.url && typeof cfg.url === 'string' && /[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i.test(cfg.url)) {
|
|
94
|
+
const match = cfg.url.match(/[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i)
|
|
95
|
+
if (match && !match[2].includes('${') && match[2].trim().length > 3) {
|
|
96
|
+
return false // Ready to connect directly without separate header
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// 3. Explicit template placeholders in headers (e.g. ${GITHUB_PERSONAL_ACCESS_TOKEN})
|
|
100
|
+
if (cfg.headers && typeof cfg.headers === 'object') {
|
|
101
|
+
if (Object.values(cfg.headers).some((v) => typeof v === 'string' && v.includes('${'))) return true
|
|
102
|
+
if (Object.keys(cfg.headers).some((k) => /auth|token|key|secret/i.test(k) && !cfg.headers[k])) return true
|
|
103
|
+
}
|
|
104
|
+
// 4. Explicit template placeholders in env (e.g. ${NOTION_API_KEY} or ${API_KEY})
|
|
105
|
+
if (cfg.env && typeof cfg.env === 'object') {
|
|
106
|
+
if (Object.values(cfg.env).some((v) => typeof v === 'string' && v.includes('${'))) return true
|
|
107
|
+
if (Object.keys(cfg.env).some((k) => /auth|token|key|secret|password/i.test(k) && !cfg.env[k])) return true
|
|
108
|
+
}
|
|
109
|
+
// 5. Known cloud MCP services that mandate authentication tokens
|
|
110
|
+
const nameLower = String(cfg.name || '').toLowerCase()
|
|
111
|
+
if (['github', 'notion', 'discord', 'gitlab', 'figma', 'linear', 'slack', 'sentry', 'atlassian', 'box', 'gong', 'granola', 'jira', 'confluence', 'hubspot', 'salesforce', 'zendesk', 'stripe', 'intercom', 'airtable', 'asana', 'clickup', 'trello', 'benchling'].includes(nameLower)) {
|
|
112
|
+
return true
|
|
113
|
+
}
|
|
114
|
+
// 6. Headers with auth/token keywords
|
|
115
|
+
if (cfg.headers && typeof cfg.headers === 'object' && Object.keys(cfg.headers).some((k) => /auth|token|key|secret/i.test(k))) {
|
|
116
|
+
return true
|
|
117
|
+
}
|
|
118
|
+
// 7. Remote HTTP / SSE MCP services (public cloud endpoints require authentication unless local or public)
|
|
119
|
+
if (isHttp) {
|
|
120
|
+
if (cfg.url && /^https?:\/\//i.test(cfg.url) && !/localhost|127\.0\.0\.1/i.test(cfg.url)) {
|
|
121
|
+
const authHeader = cfg.headers?.Authorization || cfg.headers?.authorization
|
|
122
|
+
if (!authHeader || authHeader.includes('${')) {
|
|
123
|
+
return true
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function isConnectorAuthenticated(pluginName, connectorName) {
|
|
131
|
+
const target = installedDir(pluginName)
|
|
132
|
+
const connectors = existsSync(target) ? getPluginConnectors(target) : []
|
|
133
|
+
const found = connectors.find((c) => c.name === connectorName)
|
|
134
|
+
const entry = getConnectorEntry(pluginName, connectorName)
|
|
135
|
+
const cfg = entry?.config || found || {}
|
|
136
|
+
|
|
137
|
+
const isHttp = (entry?.config?.transport === 'streamable-http' || found?.type === 'http' || found?.type === 'sse' || (!found?.command && (found?.url || cfg.url)) || (!found?.command && !found?.args?.length))
|
|
138
|
+
if (isHttp) {
|
|
139
|
+
const url = cfg.url || found?.url || ''
|
|
140
|
+
if (!url || typeof url !== 'string' || !/^https?:\/\//i.test(url.trim())) {
|
|
141
|
+
return false
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
const cmd = cfg.command || found?.command || ''
|
|
145
|
+
if (!cmd || typeof cmd !== 'string' || !cmd.trim()) {
|
|
146
|
+
return false
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (!found || !connectorRequiresAuth(found)) {
|
|
151
|
+
return true
|
|
152
|
+
}
|
|
153
|
+
if (!entry) return false
|
|
154
|
+
|
|
155
|
+
// Check embedded URL token
|
|
156
|
+
const url = cfg.url || found.url || ''
|
|
157
|
+
if (url && typeof url === 'string' && /[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i.test(url)) {
|
|
158
|
+
const match = url.match(/[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i)
|
|
159
|
+
if (match && !match[2].includes('${') && match[2].trim().length > 3) {
|
|
160
|
+
return true
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const authHeader = cfg.headers?.Authorization || cfg.headers?.authorization || ''
|
|
164
|
+
if (authHeader && !authHeader.includes('${') && authHeader.trim().length > 0) {
|
|
165
|
+
return true
|
|
166
|
+
}
|
|
167
|
+
if (cfg.headers && Object.values(cfg.headers).some((v) => typeof v === 'string' && !v.includes('${') && v.trim().length > 0)) {
|
|
168
|
+
return true
|
|
169
|
+
}
|
|
170
|
+
if (cfg.env && Object.values(cfg.env).some((v) => typeof v === 'string' && !v.includes('${') && v.trim().length > 0)) {
|
|
171
|
+
return true
|
|
172
|
+
}
|
|
173
|
+
return false
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function isConnectorActive(pluginName, connectorName) {
|
|
177
|
+
const entry = getConnectorEntry(pluginName, connectorName)
|
|
178
|
+
if (!entry) return false
|
|
179
|
+
return isConnectorAuthenticated(pluginName, connectorName)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export const getPluginConnectors = listConnectors
|
|
183
|
+
|
|
184
|
+
export function substitutePluginRoot(val, pluginRoot) {
|
|
185
|
+
if (typeof val === 'string') {
|
|
186
|
+
const normalizedRoot = pluginRoot.replace(/\\/g, '/')
|
|
187
|
+
return val
|
|
188
|
+
.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, normalizedRoot)
|
|
189
|
+
.replace(/\$CLAUDE_PLUGIN_ROOT\b/g, normalizedRoot)
|
|
190
|
+
}
|
|
191
|
+
if (Array.isArray(val)) {
|
|
192
|
+
return val.map((item) => substitutePluginRoot(item, pluginRoot))
|
|
193
|
+
}
|
|
194
|
+
if (val && typeof val === 'object') {
|
|
195
|
+
const res = {}
|
|
196
|
+
for (const [k, v] of Object.entries(val)) {
|
|
197
|
+
res[k] = substitutePluginRoot(v, pluginRoot)
|
|
198
|
+
}
|
|
199
|
+
return res
|
|
200
|
+
}
|
|
201
|
+
return val
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function registerConnector(pluginName, connectorName, connectorConfig) {
|
|
205
|
+
const patch = readCordisPatch()
|
|
206
|
+
const id = getConnectorId(pluginName, connectorName)
|
|
207
|
+
const pluginRoot = installedDir(pluginName)
|
|
208
|
+
const resolvedConfig = substitutePluginRoot(connectorConfig, pluginRoot)
|
|
209
|
+
|
|
210
|
+
let insertBlock = patch.find((item) => item && Array.isArray(item.insert))
|
|
211
|
+
if (!insertBlock) {
|
|
212
|
+
insertBlock = { insert: [] }
|
|
213
|
+
patch.push(insertBlock)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
insertBlock.insert = insertBlock.insert.filter((item) => item && item.id !== id)
|
|
217
|
+
|
|
218
|
+
const isHttp = resolvedConfig.type === 'http' || resolvedConfig.type === 'sse' || (!resolvedConfig.command && (!!resolvedConfig.url || !resolvedConfig.args?.length))
|
|
219
|
+
if (isHttp && (!resolvedConfig.url || !resolvedConfig.url.trim() || !/^https?:\/\//i.test(resolvedConfig.url.trim()))) {
|
|
220
|
+
return { ok: false, connected: false, error: '缺少有效的服务 URL' }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const clientConfig = {
|
|
224
|
+
serverName: connectorName,
|
|
225
|
+
transport: isHttp ? 'streamable-http' : 'stdio',
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (resolvedConfig.url) clientConfig.url = resolvedConfig.url
|
|
229
|
+
if (resolvedConfig.headers && Object.keys(resolvedConfig.headers).length > 0) {
|
|
230
|
+
clientConfig.headers = resolvedConfig.headers
|
|
231
|
+
}
|
|
232
|
+
if (resolvedConfig.command) clientConfig.command = resolvedConfig.command
|
|
233
|
+
if (resolvedConfig.args && resolvedConfig.args.length > 0) clientConfig.args = resolvedConfig.args
|
|
234
|
+
if (resolvedConfig.env && Object.keys(resolvedConfig.env).length > 0) clientConfig.env = resolvedConfig.env
|
|
235
|
+
|
|
236
|
+
insertBlock.insert.push({
|
|
237
|
+
id,
|
|
238
|
+
name: '@deepseek-ai/dsh-mcp-client',
|
|
239
|
+
config: clientConfig,
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
writeCordisPatch(patch)
|
|
243
|
+
return { ok: true, connected: true }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function unregisterConnector(pluginName, connectorName) {
|
|
247
|
+
const patch = readCordisPatch()
|
|
248
|
+
const id = getConnectorId(pluginName, connectorName)
|
|
249
|
+
|
|
250
|
+
for (const item of patch) {
|
|
251
|
+
if (item && Array.isArray(item.insert)) {
|
|
252
|
+
item.insert = item.insert.filter((entry) => entry && entry.id !== id)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
257
|
+
writeCordisPatch(cleaned)
|
|
258
|
+
return { ok: true, connected: false }
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ── LSP server registration (cordis.patch.yml → @deepseek-ai/dsh-lsp-stdio) ──
|
|
262
|
+
//
|
|
263
|
+
// DSH exposes LSP as a capability seam with three packages:
|
|
264
|
+
// @deepseek-ai/dsh-lsp (service definition, mounted once)
|
|
265
|
+
// @deepseek-ai/dsh-lsp-stdio (stdio provider, one instance per server)
|
|
266
|
+
// @deepseek-ai/dsh-tool-lsp (model-facing tool, mounted once)
|
|
267
|
+
// Claude plugin marketplaces declare these in the `lspServers` field, whose
|
|
268
|
+
// shape (command/args/extensionToLanguage/env) matches dsh-lsp-stdio's
|
|
269
|
+
// `servers` table directly, so registration is a straight pass-through.
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Replicate @deepseek-ai/dsh-subprocess-local's `resolveExecutable` check to
|
|
273
|
+
* test whether a bare command name would be resolvable at DSH load time.
|
|
274
|
+
*
|
|
275
|
+
* Returns the resolved absolute path, or null when no PATH entry satisfies
|
|
276
|
+
* `stat.isFile()` + `X_OK` — the same probe DSH runs when wiring up a
|
|
277
|
+
* stdio LSP provider. Without this pre-flight, registering a server whose
|
|
278
|
+
* binary is missing poisons `cordis.patch.yml`: the loader resolves the
|
|
279
|
+
* package fine, then `lsp-stdio.apply()` rejects the command at load time
|
|
280
|
+
* and the entire DSH plugin tree fails to come up.
|
|
281
|
+
*/
|
|
282
|
+
export function resolveCommandPath(command, env = process.env) {
|
|
283
|
+
if (typeof command !== 'string') return null
|
|
284
|
+
const trimmed = command.trim()
|
|
285
|
+
if (!trimmed) return null
|
|
286
|
+
if (isAbsolute(trimmed)) {
|
|
287
|
+
try {
|
|
288
|
+
if (!statSync(trimmed).isFile()) return null
|
|
289
|
+
accessSync(trimmed, fsConstants.X_OK)
|
|
290
|
+
return trimmed
|
|
291
|
+
} catch {
|
|
292
|
+
return null
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (trimmed.includes('/') || (process.platform === 'win32' && trimmed.includes('\\'))) {
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
const pathEnv = (env && (env.PATH || env.Path)) || ''
|
|
299
|
+
if (!pathEnv) return null
|
|
300
|
+
const exts = process.platform === 'win32' && !extname(trimmed)
|
|
301
|
+
? String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
302
|
+
: ['']
|
|
303
|
+
for (const dir of pathEnv.split(delimiter).filter(Boolean)) {
|
|
304
|
+
for (const ext of exts) {
|
|
305
|
+
const candidate = resolve(dir, trimmed + ext)
|
|
306
|
+
try {
|
|
307
|
+
if (!statSync(candidate).isFile()) continue
|
|
308
|
+
accessSync(candidate, fsConstants.X_OK)
|
|
309
|
+
return candidate
|
|
310
|
+
} catch {
|
|
311
|
+
// not a match, try next candidate
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return null
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export const LSP_CORE_ID = 'lsp-core'
|
|
319
|
+
export const LSP_TOOL_ID = 'lsp-tool'
|
|
320
|
+
const LSP_DEF_PKG = '@deepseek-ai/dsh-lsp'
|
|
321
|
+
const LSP_STDIO_PKG = '@deepseek-ai/dsh-lsp-stdio'
|
|
322
|
+
const LSP_TOOL_PKG = '@deepseek-ai/dsh-tool-lsp'
|
|
323
|
+
|
|
324
|
+
/** Host-side packages that LSP registration depends on (installed into the DSH installation). */
|
|
325
|
+
export const LSP_HOST_PACKAGES = [LSP_DEF_PKG, LSP_STDIO_PKG, LSP_TOOL_PKG]
|
|
326
|
+
|
|
327
|
+
/** DSH's Claude Code hook bridge + its wire-protocol peer, provisioned like LSP packages. */
|
|
328
|
+
const HOOK_BRIDGE_PKG = '@deepseek-ai/dsh-hooks-claude-code'
|
|
329
|
+
const HOOK_PROTOCOL_PKG = '@deepseek-ai/dsh-hook-protocol'
|
|
330
|
+
export const HOOK_HOST_PACKAGES = [HOOK_BRIDGE_PKG, HOOK_PROTOCOL_PKG]
|
|
331
|
+
|
|
332
|
+
const NPM_BIN = process.platform === 'win32' ? 'npm.cmd' : 'npm'
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Locate the running DSH installation's node_modules.
|
|
336
|
+
*
|
|
337
|
+
* A user-started `dsh web` (npx) boots the cordis loader without a
|
|
338
|
+
* `bareModuleBaseUrl`, so bare package names in cordis.patch.yml resolve from
|
|
339
|
+
* the loader's own location — the DSH installation's node_modules, which npm
|
|
340
|
+
* puts under the npx cache (`~/.npm/_npx/<hash>/node_modules` on POSIX,
|
|
341
|
+
* `%LocalAppData%\npm-cache\_npx\<hash>\node_modules` on Windows). We also
|
|
342
|
+
* accept profile and global install trees so other install modes provision
|
|
343
|
+
* host packages (hooks bridge, LSP) into the tree DSH actually loads from.
|
|
344
|
+
*/
|
|
345
|
+
/** Candidate base installation directories for DeepSeek Harness Desktop across platforms. */
|
|
346
|
+
function resolveDesktopCandidateDirs() {
|
|
347
|
+
const dirs = [
|
|
348
|
+
dirname(process.execPath),
|
|
349
|
+
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Programs', 'DeepSeek Harness'),
|
|
350
|
+
join(homedir(), 'AppData', 'Local', 'Programs', 'DeepSeek Harness'),
|
|
351
|
+
'/Applications/DeepSeek Harness.app/Contents/Resources',
|
|
352
|
+
'/opt/DeepSeek Harness/resources',
|
|
353
|
+
]
|
|
354
|
+
if (process.platform === 'win32') {
|
|
355
|
+
try {
|
|
356
|
+
const regOut = String(execFileSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'DeepSeek Harness'], { encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }))
|
|
357
|
+
const match = regOut.match(/InstallLocation\s+REG_SZ\s+(.+)/i)
|
|
358
|
+
if (match && match[1]) dirs.unshift(match[1].trim())
|
|
359
|
+
} catch {}
|
|
360
|
+
}
|
|
361
|
+
return dirs.filter(Boolean)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Locate the `node_modules` root containing `@deepseek-ai/dsh-app-boot`.
|
|
366
|
+
*
|
|
367
|
+
* Scans in priority order:
|
|
368
|
+
* 1) $DSH_HOME/profiles/node_modules (shared runtime directory)
|
|
369
|
+
* 2) $DSH_HOME/profiles/<profile>/node_modules (per-profile directory)
|
|
370
|
+
* 2.5) Desktop application bundle resources (Electron app)
|
|
371
|
+
* 3) NODE_PATH (set by npx exec)
|
|
372
|
+
* 4) npm npx cache (_npx/<hash>/node_modules)
|
|
373
|
+
* 5) Global npm install (`npm root -g`)
|
|
374
|
+
*/
|
|
375
|
+
export function findDshMainNodeModules() {
|
|
376
|
+
const hasLoader = (nm) => existsSync(join(nm, '@deepseek-ai', 'dsh-app-boot'))
|
|
377
|
+
|
|
378
|
+
// 1) $DSH_HOME/profiles/node_modules — the DSH runtime tree the loader
|
|
379
|
+
// resolves from when running a profile (e.g. `dsh web`). Survives
|
|
380
|
+
// `npx` cache wipes; the npx cache is transient and must not be the
|
|
381
|
+
// primary target for host packages we want to persist across starts.
|
|
382
|
+
const profilesShared = join(dshHome(), 'profiles', 'node_modules')
|
|
383
|
+
if (hasLoader(profilesShared)) return profilesShared
|
|
384
|
+
|
|
385
|
+
// 2) Per-profile node_modules ($DSH_HOME/profiles/<profile>/node_modules)
|
|
386
|
+
const profilesRoot = join(dshHome(), 'profiles')
|
|
387
|
+
try {
|
|
388
|
+
if (existsSync(profilesRoot)) {
|
|
389
|
+
for (const entry of readdirSync(profilesRoot)) {
|
|
390
|
+
const nm = join(profilesRoot, entry, 'node_modules')
|
|
391
|
+
if (hasLoader(nm)) return nm
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
} catch {}
|
|
395
|
+
|
|
396
|
+
// 2.5) Desktop application bundle resources (Electron app)
|
|
397
|
+
for (const base of resolveDesktopCandidateDirs()) {
|
|
398
|
+
for (const sub of [
|
|
399
|
+
join(base, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules'),
|
|
400
|
+
join(base, 'resources', 'app.asar', 'dsh', 'node_modules'),
|
|
401
|
+
]) {
|
|
402
|
+
try {
|
|
403
|
+
if (existsSync(sub) && hasLoader(sub)) return sub
|
|
404
|
+
} catch {}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
// 3) NODE_PATH (npx exec sets it to the cached install for bin scripts)
|
|
408
|
+
const np = process.env.NODE_PATH
|
|
409
|
+
if (np) {
|
|
410
|
+
for (const p of np.split(/[;:]/).filter(Boolean)) {
|
|
411
|
+
if (hasLoader(p)) return p
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
// 4) npm npx cache scan (Windows then POSIX) — transient, last resort.
|
|
415
|
+
const cacheRoots = []
|
|
416
|
+
if (process.platform === 'win32') {
|
|
417
|
+
cacheRoots.push(join(homedir(), 'AppData', 'Local', 'npm-cache', '_npx'))
|
|
418
|
+
} else {
|
|
419
|
+
cacheRoots.push(join(homedir(), '.npm', '_npx'))
|
|
420
|
+
}
|
|
421
|
+
for (const cacheRoot of cacheRoots) {
|
|
422
|
+
try {
|
|
423
|
+
if (!existsSync(cacheRoot)) continue
|
|
424
|
+
for (const hash of readdirSync(cacheRoot)) {
|
|
425
|
+
const nm = join(cacheRoot, hash, 'node_modules')
|
|
426
|
+
if (hasLoader(nm)) return nm
|
|
427
|
+
}
|
|
428
|
+
} catch {
|
|
429
|
+
// keep scanning
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
// 5) Global npm install (`npm i -g @deepseek-ai/dsh`)
|
|
433
|
+
try {
|
|
434
|
+
const g = globalNpmRoot()
|
|
435
|
+
if (g && hasLoader(g)) return g
|
|
436
|
+
} catch {}
|
|
437
|
+
return null
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** `npm root -g` (sync; used by the install-tree discovery fallback). */
|
|
441
|
+
function globalNpmRoot() {
|
|
442
|
+
const args = ['root', '-g']
|
|
443
|
+
if (process.platform === 'win32') {
|
|
444
|
+
return String(execFileSync('cmd', ['/c', NPM_BIN, ...args], { encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })).trim()
|
|
445
|
+
}
|
|
446
|
+
return String(execFileSync(NPM_BIN, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })).trim()
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function execFileP(bin, args, cwd) {
|
|
450
|
+
// Windows: npm ships as a .cmd shim, which execFile cannot spawn directly
|
|
451
|
+
// (EINVAL) — route through `cmd /c`. POSIX spawns the binary as-is.
|
|
452
|
+
const useCmd = process.platform === 'win32'
|
|
453
|
+
const realBin = useCmd ? 'cmd' : bin
|
|
454
|
+
const realArgs = useCmd ? ['/c', bin, ...args] : args
|
|
455
|
+
return new Promise((resolve, reject) => {
|
|
456
|
+
execFile(realBin, realArgs, { cwd, windowsHide: true, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
457
|
+
if (err) {
|
|
458
|
+
const tail = String(stderr || err.message || '').trim().split('\n').filter(Boolean).slice(-3).join(' | ')
|
|
459
|
+
reject(Object.assign(new Error(tail || `${bin} ${args[0]} 失败 (${err.message})`), { code: err.code }))
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
resolve(String(stdout))
|
|
463
|
+
})
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function runNpm(args, cwd) {
|
|
468
|
+
// npm may exist as `npm.cmd` (native Windows install) or as a bare script
|
|
469
|
+
// (nvm / managed shims); probe the candidates when the first is missing.
|
|
470
|
+
const bins = [NPM_BIN, ...(NPM_BIN === 'npm' ? [] : ['npm'])]
|
|
471
|
+
const attempt = (i) => {
|
|
472
|
+
if (i >= bins.length) return Promise.reject(new Error(`npm 命令不可用(尝试了 ${bins.join(', ')})`))
|
|
473
|
+
return execFileP(bins[i], args, cwd).catch((e) => {
|
|
474
|
+
if (e.code === 'ENOENT') return attempt(i + 1)
|
|
475
|
+
throw e
|
|
476
|
+
})
|
|
477
|
+
}
|
|
478
|
+
return attempt(0)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Major.minor line of a semver string (e.g. "1.2.3-rc.1" -> "1.2"). */
|
|
482
|
+
function versionLine(v) {
|
|
483
|
+
return String(v).split('-')[0].split('.').slice(0, 2).join('.')
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Read the running DSH release version from its installation, or '' when unknown. */
|
|
487
|
+
export function findDshVersion() {
|
|
488
|
+
const main = findDshMainNodeModules()
|
|
489
|
+
if (main) {
|
|
490
|
+
for (const anchor of ['dsh-app-boot', 'dsh-session', 'dsh']) {
|
|
491
|
+
try {
|
|
492
|
+
const pkg = JSON.parse(readFileSync(join(main, '@deepseek-ai', anchor, 'package.json'), 'utf8'))
|
|
493
|
+
if (typeof pkg.version === 'string' && pkg.version.trim()) return pkg.version.trim()
|
|
494
|
+
} catch {}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
// Desktop runtime metadata fallback (reads Electron runtime manifest)
|
|
498
|
+
for (const desktopDir of resolveDesktopCandidateDirs()) {
|
|
499
|
+
try {
|
|
500
|
+
const runtimeJsonPath = join(desktopDir, 'resources', 'runtime', 'primary-runtime', 'runtime.json')
|
|
501
|
+
if (existsSync(runtimeJsonPath)) {
|
|
502
|
+
const meta = JSON.parse(readFileSync(runtimeJsonPath, 'utf8'))
|
|
503
|
+
if (typeof meta.desktopVersion === 'string' && meta.desktopVersion.trim()) return meta.desktopVersion.trim()
|
|
504
|
+
}
|
|
505
|
+
} catch {}
|
|
506
|
+
}
|
|
507
|
+
return ''
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Highest published version of a package whose major.minor line matches the
|
|
512
|
+
* running DSH release — the host bridge packages the hub provisions
|
|
513
|
+
* (@deepseek-ai/dsh-hooks-claude-code, dsh-lsp-stdio, ...) are published in
|
|
514
|
+
* lockstep with DSH, so the same line is the compatible one. Falls back to the
|
|
515
|
+
* highest overall when the running DSH's line has no published match. This is
|
|
516
|
+
* deliberately neither the `latest` dist-tag (which can lag behind — e.g. the
|
|
517
|
+
* hooks bridge latest=0.0.1-rc.5 while 0.1.1-rc.2 exists) nor a hard pin (which
|
|
518
|
+
* would break once the user's DSH moves to a new line).
|
|
519
|
+
*/
|
|
520
|
+
export async function matchingPublishedVersion(packageName) {
|
|
521
|
+
try {
|
|
522
|
+
const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageName)}`, { headers: { accept: 'application/json' } })
|
|
523
|
+
let versions = []
|
|
524
|
+
if (res.ok) {
|
|
525
|
+
const data = await res.json()
|
|
526
|
+
versions = Object.keys(data.versions || {})
|
|
527
|
+
} else {
|
|
528
|
+
const out = await runNpm(['view', packageName, 'versions', '--json'], dirname(cordisPatchPath()))
|
|
529
|
+
const parsed = JSON.parse(out)
|
|
530
|
+
if (Array.isArray(parsed)) versions = parsed.filter((v) => typeof v === 'string')
|
|
531
|
+
}
|
|
532
|
+
if (versions.length === 0) return ''
|
|
533
|
+
const line = versionLine(findDshVersion())
|
|
534
|
+
const pool = line ? versions.filter((v) => versionLine(v) === line) : []
|
|
535
|
+
const candidates = pool.length > 0 ? pool : versions
|
|
536
|
+
let best = ''
|
|
537
|
+
for (const v of candidates) {
|
|
538
|
+
if (semverGt(v, best)) best = v
|
|
539
|
+
}
|
|
540
|
+
return best
|
|
541
|
+
} catch {
|
|
542
|
+
return ''
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Compare two semver strings (prerelease-aware). */
|
|
547
|
+
function semverGt(a, b) {
|
|
548
|
+
if (!b) return true
|
|
549
|
+
const parse = (v) => {
|
|
550
|
+
const [core, pre] = String(v).split('-')
|
|
551
|
+
const [maj, min, pat] = core.split('.').map((n) => parseInt(n, 10) || 0)
|
|
552
|
+
return { maj, min, pat, pre: pre || '' }
|
|
553
|
+
}
|
|
554
|
+
const pa = parse(a)
|
|
555
|
+
const pb = parse(b)
|
|
556
|
+
for (const k of ['maj', 'min', 'pat']) {
|
|
557
|
+
if (pa[k] !== pb[k]) return pa[k] > pb[k]
|
|
558
|
+
}
|
|
559
|
+
if (!pa.pre && !pb.pre) return false
|
|
560
|
+
if (!pa.pre) return true
|
|
561
|
+
if (!pb.pre) return false
|
|
562
|
+
return pa.pre > pb.pre
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Provision host-side packages into the DSH installation's node_modules,
|
|
567
|
+
* pinned to the newest published version. Packages already present are left
|
|
568
|
+
* untouched. This mirrors what installing a forum plugin does — the plugin
|
|
569
|
+
* brings its host dependencies with it, and DSH picks them up on restart.
|
|
570
|
+
*/
|
|
571
|
+
export async function installProfilePackages(packageNames) {
|
|
572
|
+
const names = Array.from(new Set((packageNames || []).filter((n) => typeof n === 'string' && n.trim())))
|
|
573
|
+
if (names.length === 0) return { ok: true, installed: [] }
|
|
574
|
+
|
|
575
|
+
let main = findDshMainNodeModules()
|
|
576
|
+
if (!main) {
|
|
577
|
+
const sharedNm = join(dshHome(), 'profiles', 'node_modules')
|
|
578
|
+
const activeNm = join(dshHome(), 'profiles', resolveActiveProfileName(), 'node_modules')
|
|
579
|
+
// The shared tree is the loader's primary runtime directory; prefer it
|
|
580
|
+
// whenever it exists. `findDshMainNodeModules` can miss it when its
|
|
581
|
+
// dsh-app-boot probe is a dangling symlink (e.g. left by an npx cache wipe).
|
|
582
|
+
main = existsSync(sharedNm) ? sharedNm : activeNm
|
|
583
|
+
try { mkdirSync(main, { recursive: true }) } catch {}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// A host package from a different major.minor line than the running DSH
|
|
587
|
+
// release is stale: skipping it because the directory exists left the hooks
|
|
588
|
+
// and LSP bridges pinned to whatever line was current at first provision.
|
|
589
|
+
const dshLine = versionLine(findDshVersion())
|
|
590
|
+
const need = []
|
|
591
|
+
for (const name of names) {
|
|
592
|
+
const installedManifest = join(main, name, 'package.json')
|
|
593
|
+
if (!existsSync(installedManifest)) {
|
|
594
|
+
need.push(name)
|
|
595
|
+
continue
|
|
596
|
+
}
|
|
597
|
+
if (!dshLine) continue
|
|
598
|
+
try {
|
|
599
|
+
const present = JSON.parse(readFileSync(installedManifest, 'utf8')).version
|
|
600
|
+
if (typeof present !== 'string' || versionLine(present) === dshLine) continue
|
|
601
|
+
// Re-provision only when a build for the running line actually exists;
|
|
602
|
+
// otherwise the same mismatched version would be reinstalled every start.
|
|
603
|
+
if (versionLine(await matchingPublishedVersion(name)) === dshLine) need.push(name)
|
|
604
|
+
} catch {}
|
|
605
|
+
}
|
|
606
|
+
if (need.length === 0) return { ok: true, installed: [] }
|
|
607
|
+
|
|
608
|
+
// Install each package by downloading its tarball and extracting it into the
|
|
609
|
+
// installation's node_modules. Do NOT run `npm install` against the DSH
|
|
610
|
+
// installation root: npm's reify re-resolves the whole tree and prunes
|
|
611
|
+
// packages that are not in the manifest, which has deleted DSH runtime
|
|
612
|
+
// packages in the wild. A raw tarball extract has zero side effects.
|
|
613
|
+
const installed = []
|
|
614
|
+
for (const name of need) {
|
|
615
|
+
try {
|
|
616
|
+
// Resolve a version compatible with the running DSH release (same major.minor
|
|
617
|
+
// line as the installed DSH), not the `latest` dist-tag which can lag behind.
|
|
618
|
+
const ver = await matchingPublishedVersion(name)
|
|
619
|
+
if (!ver) return { ok: false, error: `无法确定 ${name} 的匹配版本`, installed }
|
|
620
|
+
let url = null
|
|
621
|
+
try {
|
|
622
|
+
const resMeta = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`, { headers: { accept: 'application/json' } })
|
|
623
|
+
if (resMeta.ok) {
|
|
624
|
+
const meta = await resMeta.json()
|
|
625
|
+
url = meta.versions?.[ver]?.dist?.tarball
|
|
626
|
+
}
|
|
627
|
+
} catch {}
|
|
628
|
+
if (!url) {
|
|
629
|
+
try {
|
|
630
|
+
const tarballOut = await runNpm(['view', `${name}@${ver}`, 'dist.tarball'], dirname(main))
|
|
631
|
+
url = tarballOut.trim().split('\n').pop()?.trim()
|
|
632
|
+
} catch {}
|
|
633
|
+
}
|
|
634
|
+
if (!url) return { ok: false, error: `无法获取 ${name} 的 tarball 地址`, installed }
|
|
635
|
+
const res = await fetch(url)
|
|
636
|
+
if (!res.ok) throw new Error(`tarball 下载失败 (HTTP ${res.status})`)
|
|
637
|
+
const buffer = Buffer.from(await res.arrayBuffer())
|
|
638
|
+
const dest = join(main, name)
|
|
639
|
+
mkdirSync(dirname(dest), { recursive: true })
|
|
640
|
+
// Extract beside the target and swap only once the tarball is verified:
|
|
641
|
+
// replacing a stale version must not destroy the working one on failure.
|
|
642
|
+
const staging = `${dest}.staging-${process.pid}-${Date.now()}`
|
|
643
|
+
safeRmDir(staging)
|
|
644
|
+
untarStripFirst(buffer, staging)
|
|
645
|
+
// Verify the tarball actually unpacked a usable package — `untarStripFirst`
|
|
646
|
+
// walks the UStar header stream and silently exits on any malformed input
|
|
647
|
+
// (e.g. a 404 HTML page mistakenly returned as a gzipped stream), which
|
|
648
|
+
// would leave the package directory empty and downstream gates blind.
|
|
649
|
+
if (!existsSync(join(staging, 'package.json'))) {
|
|
650
|
+
safeRmDir(staging)
|
|
651
|
+
return { ok: false, error: `${name} 解包后缺少 package.json(tarball 可能不完整)`, installed }
|
|
652
|
+
}
|
|
653
|
+
safeRmDir(dest)
|
|
654
|
+
try {
|
|
655
|
+
renameSync(staging, dest)
|
|
656
|
+
} catch {
|
|
657
|
+
copyDir(staging, dest)
|
|
658
|
+
safeRmDir(staging)
|
|
659
|
+
}
|
|
660
|
+
installed.push(name)
|
|
661
|
+
} catch (error) {
|
|
662
|
+
return { ok: false, error: `${name} 安装失败: ${error.message}`, installed }
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return { ok: true, installed }
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Minimal UStar tar extractor that strips the leading `package/` component. */
|
|
669
|
+
function untarStripFirst(tgz, dest) {
|
|
670
|
+
const data = gunzipSync(tgz)
|
|
671
|
+
let offset = 0
|
|
672
|
+
while (offset + 512 <= data.length) {
|
|
673
|
+
const header = data.subarray(offset, offset + 512)
|
|
674
|
+
if (header.every((b) => b === 0)) break
|
|
675
|
+
const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '')
|
|
676
|
+
const size = parseInt(header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim(), 8) || 0
|
|
677
|
+
const type = header[156] || 0x30
|
|
678
|
+
const body = data.subarray(offset + 512, offset + 512 + size)
|
|
679
|
+
if ((type === 0x30 || type === 0) && name) { // regular file
|
|
680
|
+
const rel = name.split('/').slice(1).join('/')
|
|
681
|
+
if (rel) {
|
|
682
|
+
const file = join(dest, rel)
|
|
683
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
684
|
+
writeFileSync(file, body)
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
offset += 512 + Math.ceil(size / 512) * 512
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
export function getLspServerId(pluginName, serverName) {
|
|
692
|
+
return `lsp-${slugify(pluginName)}-${slugify(serverName)}`
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function getLspEntry(pluginName, serverName) {
|
|
696
|
+
const patch = readCordisPatch()
|
|
697
|
+
const id = getLspServerId(pluginName, serverName)
|
|
698
|
+
for (const block of patch) {
|
|
699
|
+
if (block && Array.isArray(block.insert)) {
|
|
700
|
+
const found = block.insert.find((item) => item && item.id === id)
|
|
701
|
+
if (found) return found
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return null
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function hasLspEntryWithName(patch, pkgName) {
|
|
708
|
+
for (const block of patch) {
|
|
709
|
+
if (block && Array.isArray(block.insert)) {
|
|
710
|
+
if (block.insert.some((item) => item && item.name === pkgName)) return true
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return false
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function ensureInsertBlock(patch) {
|
|
717
|
+
let block = patch.find((item) => item && Array.isArray(item.insert))
|
|
718
|
+
if (!block) {
|
|
719
|
+
block = { insert: [] }
|
|
720
|
+
patch.push(block)
|
|
721
|
+
}
|
|
722
|
+
return block
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** Mount the shared LSP service definition + model tool once (idempotent). */
|
|
726
|
+
function ensureLspInfra(patch) {
|
|
727
|
+
const block = ensureInsertBlock(patch)
|
|
728
|
+
if (!hasLspEntryWithName(patch, LSP_DEF_PKG)) {
|
|
729
|
+
block.insert.push({ id: LSP_CORE_ID, name: LSP_DEF_PKG })
|
|
730
|
+
}
|
|
731
|
+
if (!hasLspEntryWithName(patch, LSP_TOOL_PKG)) {
|
|
732
|
+
block.insert.push({ id: LSP_TOOL_ID, name: LSP_TOOL_PKG })
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Read LSP servers declared by an installed plugin (from its manifest copy). */
|
|
737
|
+
export function getPluginLspServers(pluginName) {
|
|
738
|
+
const target = installedDir(pluginName)
|
|
739
|
+
if (!existsSync(target)) return []
|
|
740
|
+
return listLspServers(target)
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Register one LSP server into cordis.patch.yml (idempotent). */
|
|
744
|
+
export function registerLspServer(pluginName, serverName, serverConfig) {
|
|
745
|
+
const patch = readCordisPatch()
|
|
746
|
+
const id = getLspServerId(pluginName, serverName)
|
|
747
|
+
const pluginRoot = installedDir(pluginName)
|
|
748
|
+
const resolved = substitutePluginRoot(serverConfig || {}, pluginRoot)
|
|
749
|
+
|
|
750
|
+
if (!resolved.command || typeof resolved.command !== 'string' || !resolved.command.trim()) {
|
|
751
|
+
return { ok: false, active: false, error: `LSP server ${serverName} 缺少有效的 command` }
|
|
752
|
+
}
|
|
753
|
+
if (!resolved.extensionToLanguage || typeof resolved.extensionToLanguage !== 'object' || Object.keys(resolved.extensionToLanguage).length === 0) {
|
|
754
|
+
return { ok: false, active: false, error: `LSP server ${serverName} 缺少 extensionToLanguage 映射` }
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// Pre-flight: refuse to write the patch entry when the binary cannot be
|
|
758
|
+
// resolved. DSH's lsp-stdio provider calls `resolveExecutable` at load
|
|
759
|
+
// time and throws if the command is missing — that exception aborts the
|
|
760
|
+
// entire plugin tree. Returning here keeps DSH bootable and surfaces a
|
|
761
|
+
// concrete remediation hint to the caller (UI / install result).
|
|
762
|
+
if (!resolveCommandPath(resolved.command)) {
|
|
763
|
+
return {
|
|
764
|
+
ok: false,
|
|
765
|
+
active: false,
|
|
766
|
+
error: `LSP server ${serverName} 注册失败:未找到可执行文件 "${resolved.command}"。` +
|
|
767
|
+
`请先安装并确保其在 PATH 中(常见做法:npm install -g ${resolved.command}),` +
|
|
768
|
+
`然后在管理页点击「更新」重新注册。`,
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
ensureLspInfra(patch)
|
|
773
|
+
|
|
774
|
+
const block = ensureInsertBlock(patch)
|
|
775
|
+
block.insert = block.insert.filter((item) => item && item.id !== id)
|
|
776
|
+
|
|
777
|
+
const serverEntry = {
|
|
778
|
+
command: resolved.command,
|
|
779
|
+
extensionToLanguage: resolved.extensionToLanguage,
|
|
780
|
+
}
|
|
781
|
+
if (Array.isArray(resolved.args) && resolved.args.length > 0) serverEntry.args = resolved.args
|
|
782
|
+
if (resolved.env && typeof resolved.env === 'object' && Object.keys(resolved.env).length > 0) serverEntry.env = resolved.env
|
|
783
|
+
if (resolved.initializationOptions != null) serverEntry.initializationOptions = resolved.initializationOptions
|
|
784
|
+
if (resolved.configuration != null) serverEntry.configuration = resolved.configuration
|
|
785
|
+
|
|
786
|
+
block.insert.push({
|
|
787
|
+
id,
|
|
788
|
+
name: LSP_STDIO_PKG,
|
|
789
|
+
config: { servers: { [serverName]: serverEntry } },
|
|
790
|
+
})
|
|
791
|
+
|
|
792
|
+
writeCordisPatch(patch)
|
|
793
|
+
return { ok: true, active: true }
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** Remove a plugin's LSP server entries; reclaim shared infra when unused. */
|
|
797
|
+
export function unregisterPluginLsp(pluginName) {
|
|
798
|
+
const patch = readCordisPatch()
|
|
799
|
+
const prefix = `lsp-${slugify(pluginName)}-`
|
|
800
|
+
let changed = false
|
|
801
|
+
for (const block of patch) {
|
|
802
|
+
if (block && Array.isArray(block.insert)) {
|
|
803
|
+
const before = block.insert.length
|
|
804
|
+
block.insert = block.insert.filter((item) => !(item && item.id && item.id.startsWith(prefix)))
|
|
805
|
+
if (block.insert.length !== before) changed = true
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
if (changed) {
|
|
810
|
+
const hasAnyServer = patch.some((block) => block && Array.isArray(block.insert) && block.insert.some((item) => item && item.name === LSP_STDIO_PKG))
|
|
811
|
+
if (!hasAnyServer) {
|
|
812
|
+
for (const block of patch) {
|
|
813
|
+
if (block && Array.isArray(block.insert)) {
|
|
814
|
+
block.insert = block.insert.filter((item) => !(item && (item.id === LSP_CORE_ID || item.id === LSP_TOOL_ID)))
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
821
|
+
writeCordisPatch(cleaned)
|
|
822
|
+
return { ok: true, active: false }
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/** Register every LSP server of an installed plugin. */
|
|
826
|
+
export function registerPluginLsp(pluginName) {
|
|
827
|
+
const servers = getPluginLspServers(pluginName)
|
|
828
|
+
const results = []
|
|
829
|
+
for (const s of servers) {
|
|
830
|
+
results.push(registerLspServer(pluginName, s.name, s))
|
|
831
|
+
}
|
|
832
|
+
return results
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** Patch id of a plugin's Claude hooks bridge entry. */
|
|
836
|
+
export function getHookBridgeId(pluginName) {
|
|
837
|
+
return `hooks-${slugify(pluginName)}`
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* Register an installed plugin's Claude/Codex hooks into DSH by inserting a
|
|
842
|
+
* `@deepseek-ai/dsh-hooks-claude-code` bridge entry into cordis.patch.yml. The
|
|
843
|
+
* bridge runs an unmodified Claude Code hooks.json on DSH's interception points
|
|
844
|
+
* (SessionStart / UserPromptSubmit / PreToolUse / PostToolUse / Stop /
|
|
845
|
+
* SubagentStart / SubagentStop), with `${CLAUDE_PLUGIN_ROOT}` substituted from
|
|
846
|
+
* `pluginRoot`. DSH's HMR re-applies the tree within ~1s, no restart needed.
|
|
847
|
+
*
|
|
848
|
+
* The bridge and its hook-protocol peer are pre-provisioned by the hub's
|
|
849
|
+
* `apply()` on DSH startup, so a per-plugin install is a single patch write.
|
|
850
|
+
*/
|
|
851
|
+
export async function registerPluginHooks(pluginName) {
|
|
852
|
+
const target = installedDir(pluginName)
|
|
853
|
+
const configPath = resolveHookConfigPath(target)
|
|
854
|
+
// A version that dropped its hooks must also lose the previous bridge entry,
|
|
855
|
+
// otherwise the old hooks keep firing after reinstall.
|
|
856
|
+
if (!configPath) {
|
|
857
|
+
unregisterPluginHooks(pluginName)
|
|
858
|
+
return { ok: true, registered: [] }
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const patch = readCordisPatch()
|
|
862
|
+
const id = getHookBridgeId(pluginName)
|
|
863
|
+
const block = ensureInsertBlock(patch)
|
|
864
|
+
block.insert = block.insert.filter((item) => item && item.id !== id)
|
|
865
|
+
block.insert.push({
|
|
866
|
+
id,
|
|
867
|
+
name: HOOK_BRIDGE_PKG,
|
|
868
|
+
config: {
|
|
869
|
+
configPath,
|
|
870
|
+
pluginRoot: target,
|
|
871
|
+
},
|
|
872
|
+
})
|
|
873
|
+
writeCordisPatch(patch)
|
|
874
|
+
return { ok: true, registered: [configPath] }
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Remove a plugin's hooks bridge entry from cordis.patch.yml. */
|
|
878
|
+
export function unregisterPluginHooks(pluginName) {
|
|
879
|
+
const patch = readCordisPatch()
|
|
880
|
+
const id = getHookBridgeId(pluginName)
|
|
881
|
+
for (const item of patch) {
|
|
882
|
+
if (item && Array.isArray(item.insert)) {
|
|
883
|
+
item.insert = item.insert.filter((entry) => entry && entry.id !== id)
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
887
|
+
writeCordisPatch(cleaned)
|
|
888
|
+
return { ok: true }
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/** Active state for one LSP server of an installed plugin. */
|
|
892
|
+
export function isLspActive(pluginName, serverName) {
|
|
893
|
+
return !!getLspEntry(pluginName, serverName)
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* LSP servers this process has already auto-activated via `installedDetails`.
|
|
898
|
+
* Once a server is auto-registered, we never auto-register it again, even if
|
|
899
|
+
* it later disappears from the patch — the user manually removing the entry
|
|
900
|
+
* (e.g. to disable the LSP without uninstalling the plugin) must be honored.
|
|
901
|
+
*/
|
|
902
|
+
const autoActivatedLspServers = new Set()
|
|
903
|
+
|
|
904
|
+
export function toggleConnector(pluginName, connectorName, enabled) {
|
|
905
|
+
const target = installedDir(pluginName)
|
|
906
|
+
const connectors = getPluginConnectors(target)
|
|
907
|
+
const found = connectors.find((c) => c.name === connectorName) || { name: connectorName }
|
|
908
|
+
|
|
909
|
+
if (enabled) {
|
|
910
|
+
if (connectorRequiresAuth(found) && !isConnectorAuthenticated(pluginName, connectorName)) {
|
|
911
|
+
throw new Error(`请先验证并配置 ${connectorName} 的授权访问 Token`)
|
|
912
|
+
}
|
|
913
|
+
return registerConnector(pluginName, connectorName, found)
|
|
914
|
+
} else {
|
|
915
|
+
return unregisterConnector(pluginName, connectorName)
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
export async function verifyConnectorAuth(pluginName, connectorName, payload) {
|
|
920
|
+
const target = installedDir(pluginName)
|
|
921
|
+
const connectors = getPluginConnectors(target)
|
|
922
|
+
const found = connectors.find((c) => c.name === connectorName)
|
|
923
|
+
|
|
924
|
+
const token = typeof payload === 'string' ? payload : (payload?.token || '')
|
|
925
|
+
const customHeaders = (typeof payload === 'object' && payload?.headers) ? { ...payload.headers } : {}
|
|
926
|
+
const transport = (typeof payload === 'object' && payload?.transport) ? payload.transport : (found?.type || 'http')
|
|
927
|
+
const url = (typeof payload === 'object' && payload?.url) || found?.url || (connectorName === 'notion' ? 'https://mcp.notion.com/mcp' : null)
|
|
928
|
+
const command = (typeof payload === 'object' && payload?.command) || found?.command || null
|
|
929
|
+
|
|
930
|
+
if (transport === 'stdio') {
|
|
931
|
+
if (found && found.url && !command) {
|
|
932
|
+
return {
|
|
933
|
+
ok: false,
|
|
934
|
+
status: 400,
|
|
935
|
+
message: `${connectorName} 仅支持远程 HTTP 连接,未提供本地可执行程序`,
|
|
936
|
+
server: connectorName,
|
|
937
|
+
transport: 'stdio',
|
|
938
|
+
endpoint: 'local stdio',
|
|
939
|
+
errorDetails: 'Remote-only MCP server does not support stdio transport',
|
|
940
|
+
duration: 5,
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (!command) {
|
|
944
|
+
return {
|
|
945
|
+
ok: false,
|
|
946
|
+
status: 400,
|
|
947
|
+
message: '未配置有效的 stdio 启动命令 (command)',
|
|
948
|
+
server: connectorName,
|
|
949
|
+
transport: 'stdio',
|
|
950
|
+
endpoint: 'local stdio',
|
|
951
|
+
errorDetails: 'Missing executable command in connector configuration',
|
|
952
|
+
duration: 5,
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const args = (typeof payload === 'object' && Array.isArray(payload?.args)) ? payload.args : (found?.args || [])
|
|
956
|
+
return {
|
|
957
|
+
ok: true,
|
|
958
|
+
message: '本地 Connector (stdio) 服务已就绪',
|
|
959
|
+
server: connectorName,
|
|
960
|
+
transport: 'stdio',
|
|
961
|
+
endpoint: `${command} ${args.join(' ')}`.trim(),
|
|
962
|
+
duration: 10,
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
if (!url) {
|
|
966
|
+
return {
|
|
967
|
+
ok: false,
|
|
968
|
+
message: '请输入有效的服务 URL',
|
|
969
|
+
server: connectorName,
|
|
970
|
+
transport,
|
|
971
|
+
endpoint: '',
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
const reqHeaders = {
|
|
976
|
+
'Content-Type': 'application/json',
|
|
977
|
+
...customHeaders,
|
|
978
|
+
}
|
|
979
|
+
if (token && token.trim()) {
|
|
980
|
+
if (!reqHeaders.Authorization && !reqHeaders.authorization) {
|
|
981
|
+
reqHeaders['Authorization'] = token.trim().startsWith('Bearer ') ? token.trim() : `Bearer ${token.trim()}`
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const startTime = Date.now()
|
|
986
|
+
try {
|
|
987
|
+
const controller = new AbortController()
|
|
988
|
+
const timer = setTimeout(() => controller.abort(), 8000)
|
|
989
|
+
const res = await fetch(url, {
|
|
990
|
+
method: 'POST',
|
|
991
|
+
headers: reqHeaders,
|
|
992
|
+
signal: controller.signal,
|
|
993
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
|
|
994
|
+
}).finally(() => clearTimeout(timer))
|
|
995
|
+
|
|
996
|
+
const duration = Date.now() - startTime
|
|
997
|
+
if (res.status === 200) {
|
|
998
|
+
return {
|
|
999
|
+
ok: true,
|
|
1000
|
+
message: '验证成功!已连接到 MCP 远程服务并激活权限。',
|
|
1001
|
+
server: connectorName,
|
|
1002
|
+
transport: transport === 'sse' ? 'sse' : 'http',
|
|
1003
|
+
endpoint: url,
|
|
1004
|
+
status: 200,
|
|
1005
|
+
duration,
|
|
1006
|
+
}
|
|
1007
|
+
} else {
|
|
1008
|
+
const body = await res.json().catch(() => ({}))
|
|
1009
|
+
const desc = body.error_description || body.error?.message || body.error || `HTTP 错误状态码 ${res.status}`
|
|
1010
|
+
const authHeader = res.headers.get('www-authenticate') || ''
|
|
1011
|
+
let userFriendly = `认证未通过:${desc}`
|
|
1012
|
+
if ((res.status === 401 || res.status === 403) && !reqHeaders.Authorization && !/[?&](api_key|apiKey|token|key)=/i.test(url)) {
|
|
1013
|
+
if (authHeader.includes('Bearer') || authHeader.includes('oauth') || /token|oauth|unauthorized|access token/i.test(String(desc))) {
|
|
1014
|
+
userFriendly = `认证未通过:缺少访问令牌 (Access Token) 或需要 OAuth 授权`
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
return {
|
|
1018
|
+
ok: false,
|
|
1019
|
+
message: userFriendly,
|
|
1020
|
+
server: connectorName,
|
|
1021
|
+
transport: transport === 'sse' ? 'sse' : 'http',
|
|
1022
|
+
endpoint: url,
|
|
1023
|
+
status: res.status,
|
|
1024
|
+
errorDetails: String(desc),
|
|
1025
|
+
duration,
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
} catch (e) {
|
|
1029
|
+
const duration = Date.now() - startTime
|
|
1030
|
+
if (e.name === 'AbortError') {
|
|
1031
|
+
return {
|
|
1032
|
+
ok: false,
|
|
1033
|
+
message: '连接超时(8 秒未响应),请检查服务 URL 与网络',
|
|
1034
|
+
server: connectorName,
|
|
1035
|
+
transport,
|
|
1036
|
+
endpoint: url,
|
|
1037
|
+
errorDetails: 'Connection timed out (8s limit)',
|
|
1038
|
+
duration,
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return {
|
|
1042
|
+
ok: false,
|
|
1043
|
+
message: `连接异常:${e.message}`,
|
|
1044
|
+
server: connectorName,
|
|
1045
|
+
transport,
|
|
1046
|
+
endpoint: url,
|
|
1047
|
+
errorDetails: e.message,
|
|
1048
|
+
duration,
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
export function saveConnectorAuth(pluginName, connectorName, payload) {
|
|
1054
|
+
const target = installedDir(pluginName)
|
|
1055
|
+
const connectors = getPluginConnectors(target)
|
|
1056
|
+
const found = connectors.find((c) => c.name === connectorName) || { name: connectorName }
|
|
1057
|
+
|
|
1058
|
+
let token = typeof payload === 'string' ? payload : (payload?.token || '')
|
|
1059
|
+
let url = (typeof payload === 'object' && payload?.url) || found.url || null
|
|
1060
|
+
let transport = (typeof payload === 'object' && payload?.transport) || found.type || (url ? 'http' : 'stdio')
|
|
1061
|
+
let customHeaders = typeof payload === 'object' && payload?.headers ? { ...payload.headers } : {}
|
|
1062
|
+
let customEnv = typeof payload === 'object' && payload?.env ? { ...payload.env } : { ...(found.env || {}) }
|
|
1063
|
+
let customArgs = typeof payload === 'object' && Array.isArray(payload?.args) ? payload.args : (found.args || [])
|
|
1064
|
+
let oauth = typeof payload === 'object' && payload?.oauth ? payload.oauth : 'none'
|
|
1065
|
+
|
|
1066
|
+
if (token && token.trim()) {
|
|
1067
|
+
const authVal = token.trim().startsWith('Bearer ') ? token.trim() : `Bearer ${token.trim()}`
|
|
1068
|
+
customHeaders['Authorization'] = authVal
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const baseHeaders = { ...(found.headers || {}) }
|
|
1072
|
+
for (const [k, v] of Object.entries(baseHeaders)) {
|
|
1073
|
+
if (typeof v === 'string' && v.includes('${')) delete baseHeaders[k]
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
const baseEnv = { ...(found.env || {}) }
|
|
1077
|
+
for (const [k, v] of Object.entries(baseEnv)) {
|
|
1078
|
+
if (typeof v === 'string' && v.includes('${')) delete baseEnv[k]
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const isStdio = (transport === 'stdio')
|
|
1082
|
+
const result = registerConnector(pluginName, connectorName, {
|
|
1083
|
+
...found,
|
|
1084
|
+
type: isStdio ? 'stdio' : (transport === 'sse' ? 'sse' : 'http'),
|
|
1085
|
+
url: isStdio ? null : (url || found.url || null),
|
|
1086
|
+
command: (typeof payload === 'object' && payload?.command) || found.command || null,
|
|
1087
|
+
args: customArgs,
|
|
1088
|
+
env: { ...baseEnv, ...customEnv },
|
|
1089
|
+
headers: { ...baseHeaders, ...customHeaders },
|
|
1090
|
+
oauth: isStdio ? 'none' : oauth,
|
|
1091
|
+
})
|
|
1092
|
+
// Re-auth (or transport switch) changes which remote the connector talks to.
|
|
1093
|
+
// The cached tool list was captured against the old connection, so drop it
|
|
1094
|
+
// here — fetchConnectorTools will repopulate on the next list call.
|
|
1095
|
+
const toolsKey = `${pluginName}::${connectorName}`
|
|
1096
|
+
if (MEMORY_TOOLS_CACHE.has(toolsKey)) {
|
|
1097
|
+
const mem = MEMORY_TOOLS_CACHE.get(toolsKey)
|
|
1098
|
+
MEMORY_TOOLS_CACHE.set(toolsKey, { ...mem, tools: [], disabledTools: mem.disabledTools || [] })
|
|
1099
|
+
}
|
|
1100
|
+
return result
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** MCP Tools Cache & State store */
|
|
1104
|
+
const MCP_TOOLS_STATE_PATH = () => join(dshHome(), '.mcp-tools-state.json')
|
|
1105
|
+
|
|
1106
|
+
export function readMcpToolsState() {
|
|
1107
|
+
const file = MCP_TOOLS_STATE_PATH()
|
|
1108
|
+
if (!existsSync(file)) return {}
|
|
1109
|
+
try {
|
|
1110
|
+
return JSON.parse(readFileSync(file, 'utf8')) || {}
|
|
1111
|
+
} catch {
|
|
1112
|
+
return {}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
export function writeMcpToolsState(state) {
|
|
1117
|
+
try {
|
|
1118
|
+
const file = MCP_TOOLS_STATE_PATH()
|
|
1119
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
1120
|
+
writeFileSync(file, JSON.stringify(state, null, 2), 'utf8')
|
|
1121
|
+
} catch {}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
export function getDisabledTools(pluginName, connectorName) {
|
|
1125
|
+
const state = readMcpToolsState()
|
|
1126
|
+
const key = `${pluginName}::${connectorName}`
|
|
1127
|
+
return Array.isArray(state[key]?.disabledTools) ? state[key].disabledTools : []
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
export function setToolDisabled(pluginName, connectorName, toolName, disabled) {
|
|
1131
|
+
const state = readMcpToolsState()
|
|
1132
|
+
const key = `${pluginName}::${connectorName}`
|
|
1133
|
+
if (!state[key]) state[key] = { disabledTools: [], cachedTools: [] }
|
|
1134
|
+
const list = new Set(Array.isArray(state[key].disabledTools) ? state[key].disabledTools : [])
|
|
1135
|
+
if (disabled) {
|
|
1136
|
+
list.add(toolName)
|
|
1137
|
+
} else {
|
|
1138
|
+
list.delete(toolName)
|
|
1139
|
+
}
|
|
1140
|
+
state[key].disabledTools = Array.from(list)
|
|
1141
|
+
writeMcpToolsState(state)
|
|
1142
|
+
|
|
1143
|
+
// Immediately synchronize in-memory cache
|
|
1144
|
+
if (MEMORY_TOOLS_CACHE.has(key)) {
|
|
1145
|
+
const mem = MEMORY_TOOLS_CACHE.get(key)
|
|
1146
|
+
MEMORY_TOOLS_CACHE.set(key, { ...mem, disabledTools: state[key].disabledTools })
|
|
1147
|
+
} else {
|
|
1148
|
+
MEMORY_TOOLS_CACHE.set(key, { tools: state[key].cachedTools || [], disabledTools: state[key].disabledTools })
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
return state[key].disabledTools
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/**
|
|
1155
|
+
* Package-manager shims are the only commands that need a shell (Windows
|
|
1156
|
+
* resolves npx.cmd/npm.cmd through cmd.exe). Running everything through a
|
|
1157
|
+
* shell split unquoted paths at their spaces — "G:\...\computer use\server.js"
|
|
1158
|
+
* arrived at node as "G:\...\computer" — so the probe always failed.
|
|
1159
|
+
*/
|
|
1160
|
+
const SHELL_COMMANDS = /^(npx|npm|pnpm|pnpx|yarn|yarnpkg|bunx?|corepack)(\.cmd|\.bat)?$/i
|
|
1161
|
+
|
|
1162
|
+
function quoteArgForShell(value) {
|
|
1163
|
+
const s = String(value)
|
|
1164
|
+
return /[\s"&|<>^]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/**
|
|
1168
|
+
* Query an MCP stdio server for its tool list.
|
|
1169
|
+
* Resolves { tools, error } — error stays null when the server answered with
|
|
1170
|
+
* an (possibly empty) tool list, so callers can tell "no tools" from "the
|
|
1171
|
+
* probe never reached the server".
|
|
1172
|
+
*/
|
|
1173
|
+
function queryStdioToolsList(cmd, args, extraEnv = {}) {
|
|
1174
|
+
return new Promise((resolve) => {
|
|
1175
|
+
const argv = Array.isArray(args) ? args : []
|
|
1176
|
+
const useShell = SHELL_COMMANDS.test(String(cmd).trim())
|
|
1177
|
+
let cp
|
|
1178
|
+
try {
|
|
1179
|
+
cp = useShell
|
|
1180
|
+
? spawn([cmd, ...argv].map(quoteArgForShell).join(' '), {
|
|
1181
|
+
shell: true,
|
|
1182
|
+
env: { ...process.env, ...extraEnv },
|
|
1183
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1184
|
+
})
|
|
1185
|
+
: spawn(cmd, argv, {
|
|
1186
|
+
shell: false,
|
|
1187
|
+
env: { ...process.env, ...extraEnv },
|
|
1188
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1189
|
+
})
|
|
1190
|
+
} catch (err) {
|
|
1191
|
+
return resolve({ tools: [], error: `无法启动 ${cmd}: ${err.message}` })
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
let output = ''
|
|
1195
|
+
let stderr = ''
|
|
1196
|
+
let answered = false
|
|
1197
|
+
let settled = false
|
|
1198
|
+
|
|
1199
|
+
const finish = (tools, error) => {
|
|
1200
|
+
if (settled) return
|
|
1201
|
+
settled = true
|
|
1202
|
+
try { cp.kill() } catch {}
|
|
1203
|
+
resolve({ tools: tools || [], error: tools ? null : error })
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
cp.stderr.on('data', (d) => { stderr += d.toString() })
|
|
1207
|
+
|
|
1208
|
+
cp.stdout.on('data', (d) => {
|
|
1209
|
+
output += d.toString()
|
|
1210
|
+
for (const line of output.split('\n')) {
|
|
1211
|
+
if (!line.trim()) continue
|
|
1212
|
+
try {
|
|
1213
|
+
const json = JSON.parse(line.trim())
|
|
1214
|
+
if (json.id === 1 && Array.isArray(json.result?.tools)) {
|
|
1215
|
+
answered = true
|
|
1216
|
+
finish(json.result.tools, null)
|
|
1217
|
+
return
|
|
1218
|
+
}
|
|
1219
|
+
} catch {}
|
|
1220
|
+
}
|
|
1221
|
+
})
|
|
1222
|
+
|
|
1223
|
+
cp.on('error', (err) => finish([], `无法启动 ${cmd}: ${err.message}`))
|
|
1224
|
+
|
|
1225
|
+
cp.on('close', (code) => {
|
|
1226
|
+
if (!answered) {
|
|
1227
|
+
const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
|
|
1228
|
+
finish([], detail || `MCP 服务提前退出(exit ${code})`)
|
|
1229
|
+
}
|
|
1230
|
+
})
|
|
1231
|
+
|
|
1232
|
+
const initReq = JSON.stringify({
|
|
1233
|
+
jsonrpc: '2.0',
|
|
1234
|
+
id: 0,
|
|
1235
|
+
method: 'initialize',
|
|
1236
|
+
params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'claude-market', version: '1.0' } }
|
|
1237
|
+
}) + '\n'
|
|
1238
|
+
|
|
1239
|
+
const toolsReq = JSON.stringify({
|
|
1240
|
+
jsonrpc: '2.0',
|
|
1241
|
+
id: 1,
|
|
1242
|
+
method: 'tools/list',
|
|
1243
|
+
params: {}
|
|
1244
|
+
}) + '\n'
|
|
1245
|
+
|
|
1246
|
+
try {
|
|
1247
|
+
cp.stdin.write(initReq)
|
|
1248
|
+
setTimeout(() => {
|
|
1249
|
+
if (!settled) {
|
|
1250
|
+
try {
|
|
1251
|
+
cp.stdin.write(toolsReq)
|
|
1252
|
+
} catch {}
|
|
1253
|
+
}
|
|
1254
|
+
}, 300)
|
|
1255
|
+
} catch {}
|
|
1256
|
+
|
|
1257
|
+
setTimeout(() => {
|
|
1258
|
+
if (!settled) {
|
|
1259
|
+
const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
|
|
1260
|
+
finish([], detail || 'MCP 服务在 25 秒内没有返回工具列表')
|
|
1261
|
+
}
|
|
1262
|
+
}, 25000)
|
|
1263
|
+
})
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
const MEMORY_TOOLS_CACHE = new Map()
|
|
1267
|
+
|
|
1268
|
+
export async function fetchConnectorTools(pluginName, connectorName, forceFresh = false) {
|
|
1269
|
+
const key = `${pluginName}::${connectorName}`
|
|
1270
|
+
const state = readMcpToolsState()
|
|
1271
|
+
const disabledTools = Array.isArray(state[key]?.disabledTools) ? state[key].disabledTools : []
|
|
1272
|
+
|
|
1273
|
+
if (!forceFresh && MEMORY_TOOLS_CACHE.has(key)) {
|
|
1274
|
+
const mem = MEMORY_TOOLS_CACHE.get(key)
|
|
1275
|
+
return { ok: true, tools: mem.tools || [], disabledTools }
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
const target = installedDir(pluginName)
|
|
1279
|
+
const connectors = existsSync(target) ? getPluginConnectors(target) : []
|
|
1280
|
+
const found = connectors.find((c) => c.name === connectorName)
|
|
1281
|
+
const entry = getConnectorEntry(pluginName, connectorName)
|
|
1282
|
+
const entryCfg = entry?.config || {}
|
|
1283
|
+
|
|
1284
|
+
const cached = state[key]?.cachedTools || []
|
|
1285
|
+
|
|
1286
|
+
// If cached tools exist, cache in memory and return immediately (0ms instant response)
|
|
1287
|
+
if (!forceFresh && cached.length > 0) {
|
|
1288
|
+
MEMORY_TOOLS_CACHE.set(key, { tools: cached, disabledTools })
|
|
1289
|
+
return { ok: true, tools: cached, disabledTools }
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
const transport = entryCfg.transport === 'stdio' ? 'stdio' : (found?.type === 'stdio' ? 'stdio' : 'http')
|
|
1293
|
+
const url = entryCfg.url || found?.url
|
|
1294
|
+
const headers = entryCfg.headers || found?.headers || {}
|
|
1295
|
+
|
|
1296
|
+
// Nothing to connect to (unknown server, or a config with neither URL nor
|
|
1297
|
+
// command) must read as an error, not as "this server exposes no tools".
|
|
1298
|
+
let probeError = null
|
|
1299
|
+
if (transport !== 'stdio' && !url) {
|
|
1300
|
+
probeError = `未找到 MCP 服务 ${connectorName} 的连接配置`
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// 1. HTTP / SSE fetch
|
|
1304
|
+
if (transport !== 'stdio' && url) {
|
|
1305
|
+
try {
|
|
1306
|
+
const controller = new AbortController()
|
|
1307
|
+
const timer = setTimeout(() => controller.abort(), 6000)
|
|
1308
|
+
const res = await fetch(url, {
|
|
1309
|
+
method: 'POST',
|
|
1310
|
+
headers: {
|
|
1311
|
+
'Content-Type': 'application/json',
|
|
1312
|
+
...headers,
|
|
1313
|
+
},
|
|
1314
|
+
signal: controller.signal,
|
|
1315
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
|
|
1316
|
+
}).finally(() => clearTimeout(timer))
|
|
1317
|
+
|
|
1318
|
+
if (res.status === 200) {
|
|
1319
|
+
const text = await res.text()
|
|
1320
|
+
let tools = []
|
|
1321
|
+
try {
|
|
1322
|
+
const data = JSON.parse(text)
|
|
1323
|
+
if (Array.isArray(data.result?.tools)) tools = data.result.tools
|
|
1324
|
+
} catch {
|
|
1325
|
+
const lines = text.split('\n')
|
|
1326
|
+
for (const line of lines) {
|
|
1327
|
+
if (line.startsWith('data:')) {
|
|
1328
|
+
try {
|
|
1329
|
+
const data = JSON.parse(line.slice(5).trim())
|
|
1330
|
+
if (Array.isArray(data.result?.tools)) {
|
|
1331
|
+
tools = data.result.tools
|
|
1332
|
+
break
|
|
1333
|
+
}
|
|
1334
|
+
} catch {}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
if (tools.length > 0) {
|
|
1340
|
+
if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
|
|
1341
|
+
state[key].cachedTools = tools
|
|
1342
|
+
writeMcpToolsState(state)
|
|
1343
|
+
return { ok: true, tools, disabledTools }
|
|
1344
|
+
}
|
|
1345
|
+
} else {
|
|
1346
|
+
probeError = `MCP 服务返回 HTTP ${res.status}`
|
|
1347
|
+
}
|
|
1348
|
+
} catch (err) {
|
|
1349
|
+
probeError = `连接 MCP 服务失败: ${err.message}`
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
// 2. Stdio fetch
|
|
1354
|
+
if (transport === 'stdio') {
|
|
1355
|
+
const cmd = entryCfg.command || found?.command
|
|
1356
|
+
const args = entryCfg.args || found?.args || []
|
|
1357
|
+
if (cmd) {
|
|
1358
|
+
try {
|
|
1359
|
+
const probe = await queryStdioToolsList(cmd, args, entryCfg.env || found?.env || {})
|
|
1360
|
+
if (probe.tools.length > 0) {
|
|
1361
|
+
if (!state[key]) state[key] = { disabledTools, cachedTools: [] }
|
|
1362
|
+
state[key].cachedTools = probe.tools
|
|
1363
|
+
writeMcpToolsState(state)
|
|
1364
|
+
return { ok: true, tools: probe.tools, disabledTools }
|
|
1365
|
+
}
|
|
1366
|
+
probeError = probe.error
|
|
1367
|
+
} catch (err) {
|
|
1368
|
+
probeError = err.message
|
|
1369
|
+
}
|
|
1370
|
+
} else {
|
|
1371
|
+
probeError = '该 MCP 服务没有配置启动命令'
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
// 3. Return cached fallback
|
|
1376
|
+
if (cached.length > 0) {
|
|
1377
|
+
return { ok: true, tools: cached, disabledTools }
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
// A probe that never reached the server is an error, not an empty tool list;
|
|
1381
|
+
// reporting ok:true here made the UI claim the server exposes no tools.
|
|
1382
|
+
if (probeError) {
|
|
1383
|
+
return { ok: false, tools: [], disabledTools, message: probeError }
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
return { ok: true, tools: [], disabledTools }
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
export function isScanDirRegistered(path) {
|
|
1390
|
+
const state = readState()
|
|
1391
|
+
const target = (path || '').replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '')
|
|
1392
|
+
const plugin = state.plugins.find((p) => {
|
|
1393
|
+
const pPath = join(installedDir(p.name), 'skills').replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '')
|
|
1394
|
+
return pPath === target
|
|
1395
|
+
})
|
|
1396
|
+
return plugin ? plugin.enabled !== false : existsSync(path)
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
function ensureSkillFrontmatter(content, skillName, description) {
|
|
1400
|
+
const desc = description || skillName
|
|
1401
|
+
if (content.startsWith('---')) {
|
|
1402
|
+
const end = content.indexOf('---', 3)
|
|
1403
|
+
if (end > 0) {
|
|
1404
|
+
const yamlStr = content.slice(3, end)
|
|
1405
|
+
let extra = ''
|
|
1406
|
+
if (!/^\s*name\s*:/m.test(yamlStr)) {
|
|
1407
|
+
extra += `name: ${skillName}\n`
|
|
1408
|
+
}
|
|
1409
|
+
if (!/^\s*description\s*:/m.test(yamlStr)) {
|
|
1410
|
+
extra += `description: ${desc}\n`
|
|
1411
|
+
}
|
|
1412
|
+
if (!/^\s*user-invocable\s*:/m.test(yamlStr)) {
|
|
1413
|
+
extra += `user-invocable: true\n`
|
|
1414
|
+
}
|
|
1415
|
+
if (extra) {
|
|
1416
|
+
return `---\n${extra}${yamlStr.trim()}\n---` + content.slice(end + 3)
|
|
1417
|
+
}
|
|
1418
|
+
return content
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return `---\nname: ${skillName}\ndescription: ${desc}\nuser-invocable: true\n---\n\n` + content
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/**
|
|
1425
|
+
* Synchronize all skills from an installed plugin into $DSH_HOME/skills.
|
|
1426
|
+
* This ensures DSH Desktop's @deepseek-ai/dsh-skill-filesystem discovers them
|
|
1427
|
+
* natively and hot-reloads them into the composer's "/" slash command menu.
|
|
1428
|
+
*/
|
|
1429
|
+
export function syncPluginSkillsToDsh(pluginName) {
|
|
1430
|
+
const target = installedDir(pluginName)
|
|
1431
|
+
const pluginSkillsDir = join(target, 'skills')
|
|
1432
|
+
if (!existsSync(pluginSkillsDir)) return []
|
|
1433
|
+
|
|
1434
|
+
const dshSkills = dshSkillsDir()
|
|
1435
|
+
mkdirSync(dshSkills, { recursive: true })
|
|
1436
|
+
|
|
1437
|
+
const synced = []
|
|
1438
|
+
for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
|
|
1439
|
+
if (entry.isDirectory()) {
|
|
1440
|
+
const srcSkillDir = join(pluginSkillsDir, entry.name)
|
|
1441
|
+
const srcSkillFile = join(srcSkillDir, 'SKILL.md')
|
|
1442
|
+
if (existsSync(srcSkillFile)) {
|
|
1443
|
+
const destSkillDir = join(dshSkills, entry.name)
|
|
1444
|
+
safeRmDir(destSkillDir)
|
|
1445
|
+
copyDir(srcSkillDir, destSkillDir)
|
|
1446
|
+
synced.push(entry.name)
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
return synced
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
/**
|
|
1454
|
+
* Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
|
|
1455
|
+
*/
|
|
1456
|
+
export function removePluginSkillsFromDsh(pluginName) {
|
|
1457
|
+
const target = installedDir(pluginName)
|
|
1458
|
+
const pluginSkillsDir = join(target, 'skills')
|
|
1459
|
+
const dshSkills = dshSkillsDir()
|
|
1460
|
+
if (!existsSync(dshSkills)) return
|
|
1461
|
+
|
|
1462
|
+
// 1. If installed copy exists, remove matching skill directories
|
|
1463
|
+
if (existsSync(pluginSkillsDir)) {
|
|
1464
|
+
for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
|
|
1465
|
+
if (entry.isDirectory()) {
|
|
1466
|
+
const destSkillDir = join(dshSkills, entry.name)
|
|
1467
|
+
safeRmDir(destSkillDir)
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// 2. Also remove any skills prefixed with plugin name or compiled subagent hub
|
|
1473
|
+
const subagentHubName = `${pluginName}-agents`
|
|
1474
|
+
safeRmDir(join(dshSkills, subagentHubName))
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
/**
|
|
1478
|
+
* Sync all installed and enabled plugins into $DSH_HOME/skills.
|
|
1479
|
+
* Called at boot or after configuration change.
|
|
1480
|
+
*/
|
|
1481
|
+
export function syncAllInstalledSkillsToDsh() {
|
|
1482
|
+
const state = readState()
|
|
1483
|
+
const dshSkills = dshSkillsDir()
|
|
1484
|
+
mkdirSync(dshSkills, { recursive: true })
|
|
1485
|
+
|
|
1486
|
+
const results = {}
|
|
1487
|
+
for (const plugin of state.plugins || []) {
|
|
1488
|
+
if (plugin.enabled !== false) {
|
|
1489
|
+
results[plugin.name] = syncPluginSkillsToDsh(plugin.name)
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
return results
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
/**
|
|
1496
|
+
* Install a plugin from the marketplace into the installed tree.
|
|
1497
|
+
* Returns a result summary for the UI.
|
|
1498
|
+
*/
|
|
1499
|
+
export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
1500
|
+
const state = readState()
|
|
1501
|
+
const source = state.sources.find((s) => s.id === sourceId)
|
|
1502
|
+
if (!source) throw new Error(`unknown source: ${sourceId}`)
|
|
1503
|
+
|
|
1504
|
+
const row = await findMarketRow(sourceId, pluginName)
|
|
1505
|
+
if (!row) throw new Error(`plugin not found in marketplace: ${pluginName}`)
|
|
1506
|
+
|
|
1507
|
+
const { dir } = await materializePlugin(sourceId, pluginName, row.source, { refresh })
|
|
1508
|
+
const target = installedDir(pluginName)
|
|
1509
|
+
|
|
1510
|
+
// Reinstalling must not inherit the previous copy's registrations: skills it
|
|
1511
|
+
// no longer ships and MCP servers it dropped would otherwise stay visible.
|
|
1512
|
+
const prevConnectors = existsSync(target) ? getPluginConnectors(target).map((c) => c.name) : []
|
|
1513
|
+
if (existsSync(target)) removePluginSkillsFromDsh(pluginName)
|
|
1514
|
+
|
|
1515
|
+
// Idempotent reinstall: clear the previous copy first.
|
|
1516
|
+
safeRmDir(target)
|
|
1517
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
1518
|
+
copyDir(dir, target)
|
|
1519
|
+
|
|
1520
|
+
// Persist marketplace-declared LSP servers into the installed copy's
|
|
1521
|
+
// manifest, so installedDetails / detail views can read them back even when
|
|
1522
|
+
// the plugin directory itself is only a README placeholder (official LSP
|
|
1523
|
+
// plugins declare `lspServers` in marketplace.json, not in the plugin tree).
|
|
1524
|
+
if (row.lspServers && typeof row.lspServers === 'object' && !Array.isArray(row.lspServers)) {
|
|
1525
|
+
const manifestDir = join(target, '.claude-plugin')
|
|
1526
|
+
mkdirSync(manifestDir, { recursive: true })
|
|
1527
|
+
const manifestPath = join(manifestDir, 'plugin.json')
|
|
1528
|
+
let installedManifest = {}
|
|
1529
|
+
try {
|
|
1530
|
+
if (existsSync(manifestPath)) installedManifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
|
1531
|
+
} catch {
|
|
1532
|
+
// ignore malformed existing manifest
|
|
1533
|
+
}
|
|
1534
|
+
installedManifest.lspServers = row.lspServers
|
|
1535
|
+
writeFileSync(manifestPath, JSON.stringify(installedManifest, null, 2), 'utf8')
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
// Ensure skills/ directory exists
|
|
1539
|
+
const skillsDir = join(target, 'skills')
|
|
1540
|
+
mkdirSync(skillsDir, { recursive: true })
|
|
1541
|
+
|
|
1542
|
+
// Codex manifests may point at a skills collection outside the default skills/.
|
|
1543
|
+
const declaredSkills = readPluginManifest(target)?.skills
|
|
1544
|
+
const skillPaths = typeof declaredSkills === 'string' ? [declaredSkills] : (Array.isArray(declaredSkills) ? declaredSkills.filter((p) => typeof p === 'string' && p.startsWith('./')) : [])
|
|
1545
|
+
for (const path of skillPaths) {
|
|
1546
|
+
let root = pluginPath(target, path)
|
|
1547
|
+
if (!existsSync(root) || resolve(root) === resolve(skillsDir)) continue
|
|
1548
|
+
if (statSync(root).isFile()) root = dirname(root)
|
|
1549
|
+
const dirs = existsSync(join(root, 'SKILL.md')) || existsSync(join(root, 'skill.md')) ? [root] : readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join(root, e.name))
|
|
1550
|
+
for (const dir of dirs) {
|
|
1551
|
+
if (resolve(dir) === resolve(target)) continue // handled as a root skill below
|
|
1552
|
+
if (!existsSync(join(dir, 'SKILL.md')) && !existsSync(join(dir, 'skill.md'))) continue
|
|
1553
|
+
const dest = join(skillsDir, basename(dir))
|
|
1554
|
+
if (resolve(dest) !== resolve(dir)) copyDir(dir, dest)
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// 1. If the plugin uses commands/ (Claude Code slash commands), mirror them into skills/
|
|
1559
|
+
const commandsDir = join(target, 'commands')
|
|
1560
|
+
if (existsSync(commandsDir)) {
|
|
1561
|
+
for (const entry of readdirSync(commandsDir, { withFileTypes: true })) {
|
|
1562
|
+
if (entry.isFile() && entry.name.endsWith('.md')) {
|
|
1563
|
+
const cmdName = entry.name.replace(/\.md$/, '')
|
|
1564
|
+
const cmdSkillDir = join(skillsDir, cmdName)
|
|
1565
|
+
mkdirSync(cmdSkillDir, { recursive: true })
|
|
1566
|
+
const rawContent = readFileSync(join(commandsDir, entry.name), 'utf8')
|
|
1567
|
+
const formatted = ensureSkillFrontmatter(rawContent, cmdName)
|
|
1568
|
+
writeFileSync(join(cmdSkillDir, 'SKILL.md'), formatted, 'utf8')
|
|
1569
|
+
} else if (entry.isDirectory()) {
|
|
1570
|
+
const subSkillDir = join(skillsDir, entry.name)
|
|
1571
|
+
mkdirSync(subSkillDir, { recursive: true })
|
|
1572
|
+
copyDir(join(commandsDir, entry.name), subSkillDir)
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
// 2. If the plugin has a root SKILL.md, mirror it into skills/<pluginName>/SKILL.md
|
|
1578
|
+
const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(target, f)).find(existsSync)
|
|
1579
|
+
if (rootSkillMd) {
|
|
1580
|
+
const rootSkillDir = join(skillsDir, pluginName)
|
|
1581
|
+
if (!existsSync(rootSkillDir)) {
|
|
1582
|
+
mkdirSync(rootSkillDir, { recursive: true })
|
|
1583
|
+
// Keep relative scripts/references/assets usable when DSH copies the skill.
|
|
1584
|
+
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
1585
|
+
if (entry.isDirectory() && !['skills', '.git', 'node_modules'].includes(entry.name)) copyDir(join(target, entry.name), join(rootSkillDir, entry.name))
|
|
1586
|
+
else if (entry.isFile()) copyFileSync(join(target, entry.name), join(rootSkillDir, entry.name))
|
|
1587
|
+
}
|
|
1588
|
+
const rawContent = readFileSync(rootSkillMd, 'utf8')
|
|
1589
|
+
const formatted = ensureSkillFrontmatter(rawContent, pluginName)
|
|
1590
|
+
writeFileSync(join(rootSkillDir, 'SKILL.md'), formatted, 'utf8')
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// 2.5. If the plugin repository has skill directories directly under root, mirror into skills/
|
|
1595
|
+
try {
|
|
1596
|
+
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
1597
|
+
if (
|
|
1598
|
+
entry.isDirectory() &&
|
|
1599
|
+
entry.name !== 'skills' &&
|
|
1600
|
+
entry.name !== 'commands' &&
|
|
1601
|
+
entry.name !== 'agents' &&
|
|
1602
|
+
entry.name !== '.agents' &&
|
|
1603
|
+
entry.name !== 'node_modules' &&
|
|
1604
|
+
entry.name !== '.git'
|
|
1605
|
+
) {
|
|
1606
|
+
const sMd = join(target, entry.name, 'SKILL.md')
|
|
1607
|
+
if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
|
|
1608
|
+
const subDir = join(skillsDir, entry.name)
|
|
1609
|
+
mkdirSync(subDir, { recursive: true })
|
|
1610
|
+
copyDir(join(target, entry.name), subDir)
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
} catch {}
|
|
1615
|
+
|
|
1616
|
+
// 4. Compile Claude Agents into a clean Subagents Hub Skill (task-level specialized delegates)
|
|
1617
|
+
const agents = listAgents(target)
|
|
1618
|
+
const validAgents = []
|
|
1619
|
+
const convertErrors = []
|
|
1620
|
+
|
|
1621
|
+
for (const agent of agents) {
|
|
1622
|
+
const text = readAgentYaml(target, agent.file)
|
|
1623
|
+
const parsed = parseAgentDefinition(pluginName, agent.file, text)
|
|
1624
|
+
if (parsed?.error) {
|
|
1625
|
+
convertErrors.push(parsed.error)
|
|
1626
|
+
} else if (parsed) {
|
|
1627
|
+
validAgents.push(parsed)
|
|
1628
|
+
// Also generate individual skill for direct user invocation and model task-delegation
|
|
1629
|
+
const agentSkillDir = join(skillsDir, parsed.name)
|
|
1630
|
+
mkdirSync(agentSkillDir, { recursive: true })
|
|
1631
|
+
const agentSkillContent = ensureSkillFrontmatter(
|
|
1632
|
+
`# ${parsed.displayName || parsed.name}\n\n` +
|
|
1633
|
+
`Specialized subagent from **${pluginName}**.\n\n` +
|
|
1634
|
+
`${parsed.description}\n\n` +
|
|
1635
|
+
`## Autonomous Subagent Delegation\n` +
|
|
1636
|
+
`When delegating a task to this specialized agent using the \`subagent\` tool:\n\n` +
|
|
1637
|
+
'```markdown\n' +
|
|
1638
|
+
parsed.instructions + '\n' +
|
|
1639
|
+
'```\n',
|
|
1640
|
+
parsed.name,
|
|
1641
|
+
parsed.description
|
|
1642
|
+
)
|
|
1643
|
+
writeFileSync(join(agentSkillDir, 'SKILL.md'), agentSkillContent, 'utf8')
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
let subagentsHub = null
|
|
1648
|
+
if (validAgents.length > 0) {
|
|
1649
|
+
subagentsHub = compileSubagentsHubSkill(pluginName, row.displayName || pluginName, validAgents, skillsDir)
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
// Ensure all SKILL.md in skills/ have valid frontmatter with name:
|
|
1653
|
+
for (const entry of readdirSync(skillsDir, { withFileTypes: true })) {
|
|
1654
|
+
if (entry.isDirectory()) {
|
|
1655
|
+
const skillFile = join(skillsDir, entry.name, 'SKILL.md')
|
|
1656
|
+
const altSkillFile = join(skillsDir, entry.name, 'skill.md')
|
|
1657
|
+
if (!existsSync(skillFile) && existsSync(altSkillFile)) copyFileSync(altSkillFile, skillFile)
|
|
1658
|
+
if (existsSync(skillFile)) {
|
|
1659
|
+
const raw = readFileSync(skillFile, 'utf8')
|
|
1660
|
+
const fixed = ensureSkillFrontmatter(raw, entry.name)
|
|
1661
|
+
if (fixed !== raw) {
|
|
1662
|
+
writeFileSync(skillFile, fixed, 'utf8')
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// Clean any legacy preset directories left by prior versions
|
|
1669
|
+
cleanupLegacyPresets(pluginName)
|
|
1670
|
+
|
|
1671
|
+
const skills = listSkills(target)
|
|
1672
|
+
const prompts = listPrompts(target)
|
|
1673
|
+
const connectors = listConnectors(target)
|
|
1674
|
+
const hooks = listHooks(target)
|
|
1675
|
+
|
|
1676
|
+
// Sync skills and subagent delegates to DSH native skills directory.
|
|
1677
|
+
if (existsSync(skillsDir)) {
|
|
1678
|
+
syncPluginSkillsToDsh(pluginName)
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// Auto-register and connect any MCP connectors defined in the plugin that do NOT require auth and have valid URLs/commands.
|
|
1682
|
+
const pluginConnectors = getPluginConnectors(target)
|
|
1683
|
+
for (const name of prevConnectors) {
|
|
1684
|
+
if (!pluginConnectors.some((c) => c.name === name)) unregisterConnector(pluginName, name)
|
|
1685
|
+
}
|
|
1686
|
+
for (const c of pluginConnectors) {
|
|
1687
|
+
if (!connectorRequiresAuth(c)) {
|
|
1688
|
+
const isHttp = (c.type === 'http' || c.type === 'sse' || (!c.command && (!!c.url || !c.args?.length)))
|
|
1689
|
+
if (isHttp && (!c.url || !c.url.trim() || !/^https?:\/\//i.test(c.url.trim()))) {
|
|
1690
|
+
continue
|
|
1691
|
+
}
|
|
1692
|
+
registerConnector(pluginName, c.name, c)
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
// Auto-register LSP servers declared by the plugin. The host packages
|
|
1697
|
+
// (dsh-lsp / dsh-lsp-stdio / dsh-tool-lsp) were pre-provisioned by the
|
|
1698
|
+
// hub's `apply()` at DSH startup — this step is a single, race-free
|
|
1699
|
+
// patch write. `lspErrors` still surface other failures (the user-installed
|
|
1700
|
+
// language server binary not on PATH, missing extensionToLanguage, etc.).
|
|
1701
|
+
// Drop the previous version's server entries; the loop re-adds the ones this
|
|
1702
|
+
// version still declares, so removed servers stop loading.
|
|
1703
|
+
unregisterPluginLsp(pluginName)
|
|
1704
|
+
const lspServers = listLspServers(target)
|
|
1705
|
+
const lspErrors = []
|
|
1706
|
+
for (const r of registerPluginLsp(pluginName)) {
|
|
1707
|
+
if (!r.ok && r.error) lspErrors.push(r.error)
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// Register the plugin's Claude/Codex hooks into DSH via the hooks bridge.
|
|
1711
|
+
// The bridge package was pre-provisioned by the hub's `apply()`; this is a
|
|
1712
|
+
// single patch write.
|
|
1713
|
+
await registerPluginHooks(pluginName)
|
|
1714
|
+
|
|
1715
|
+
const record = {
|
|
1716
|
+
id: `${sourceId}/${pluginName}`,
|
|
1717
|
+
sourceId,
|
|
1718
|
+
name: pluginName,
|
|
1719
|
+
displayName: row.displayName || pluginName,
|
|
1720
|
+
description: row.description || '',
|
|
1721
|
+
author: row.author ?? null,
|
|
1722
|
+
enabled: true,
|
|
1723
|
+
installedAt: Date.now(),
|
|
1724
|
+
skillCount: skills.length,
|
|
1725
|
+
agentCount: agents.length,
|
|
1726
|
+
promptCount: prompts.length,
|
|
1727
|
+
connectorCount: connectors.length,
|
|
1728
|
+
hookCount: hooks.length,
|
|
1729
|
+
lspServerCount: lspServers.length,
|
|
1730
|
+
version: readInstalledVersion(target) ?? row.version ?? null,
|
|
1731
|
+
}
|
|
1732
|
+
// Same-name replace: installed files live under a name-only directory, so a
|
|
1733
|
+
// plugin with the same name from any source supersedes the previous record.
|
|
1734
|
+
state.plugins = state.plugins.filter((p) => p.name !== pluginName)
|
|
1735
|
+
state.plugins.push(record)
|
|
1736
|
+
writeState(state)
|
|
1737
|
+
invalidateParserCaches()
|
|
1738
|
+
|
|
1739
|
+
// Proactively warm up and cache tools for local stdio/npx MCP servers in the background
|
|
1740
|
+
for (const c of pluginConnectors) {
|
|
1741
|
+
if (c.command === 'npx' || (c.args && c.args.some((a) => typeof a === 'string' && a.includes('@')))) {
|
|
1742
|
+
setTimeout(() => {
|
|
1743
|
+
fetchConnectorTools(pluginName, c.name, true).catch(() => {});
|
|
1744
|
+
}, 500);
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
return {
|
|
1749
|
+
ok: true,
|
|
1750
|
+
plugin: record,
|
|
1751
|
+
skills: skills.map((s) => s.command),
|
|
1752
|
+
subagents: validAgents,
|
|
1753
|
+
converted: validAgents,
|
|
1754
|
+
subagentsHub,
|
|
1755
|
+
connectors: connectors.map((c) => c.name),
|
|
1756
|
+
lspServers: lspServers.map((s) => s.name),
|
|
1757
|
+
lspErrors: lspErrors.length > 0 ? lspErrors : undefined,
|
|
1758
|
+
convertErrors,
|
|
1759
|
+
droppedFields: [],
|
|
1760
|
+
restartRequired: false,
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
function readAgentYaml(target, file) {
|
|
1765
|
+
const candidates = [
|
|
1766
|
+
join(target, 'agents', file),
|
|
1767
|
+
join(target, file),
|
|
1768
|
+
join(target, '.well-known', file),
|
|
1769
|
+
]
|
|
1770
|
+
for (const p of candidates) {
|
|
1771
|
+
if (existsSync(p)) {
|
|
1772
|
+
try {
|
|
1773
|
+
return readFileSync(p, 'utf8')
|
|
1774
|
+
} catch {}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return ''
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
function readInstalledVersion(target) {
|
|
1781
|
+
const manifest = readPluginManifest(target)
|
|
1782
|
+
return manifest?.version
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
/** Uninstall: remove copy, unregister scan dir, clean legacy presets and connectors. */
|
|
1786
|
+
export function uninstallPlugin(pluginName) {
|
|
1787
|
+
const state = readState()
|
|
1788
|
+
const target = installedDir(pluginName)
|
|
1789
|
+
if (existsSync(target)) {
|
|
1790
|
+
const pluginConnectors = getPluginConnectors(target)
|
|
1791
|
+
for (const c of pluginConnectors) {
|
|
1792
|
+
unregisterConnector(pluginName, c.name)
|
|
1793
|
+
}
|
|
1794
|
+
unregisterPluginLsp(pluginName)
|
|
1795
|
+
unregisterPluginHooks(pluginName)
|
|
1796
|
+
}
|
|
1797
|
+
removePluginSkillsFromDsh(pluginName)
|
|
1798
|
+
try { safeRmDir(target) } catch {}
|
|
1799
|
+
|
|
1800
|
+
// Clean any legacy preset directories left by prior versions
|
|
1801
|
+
cleanupLegacyPresets(pluginName)
|
|
1802
|
+
|
|
1803
|
+
// Clean MCP tools state and memory cache for this plugin
|
|
1804
|
+
const mcpToolsState = readMcpToolsState()
|
|
1805
|
+
let mcpToolsStateChanged = false
|
|
1806
|
+
for (const k of Object.keys(mcpToolsState)) {
|
|
1807
|
+
if (k.startsWith(`${pluginName}::`)) {
|
|
1808
|
+
delete mcpToolsState[k]
|
|
1809
|
+
mcpToolsStateChanged = true
|
|
1810
|
+
MEMORY_TOOLS_CACHE.delete(k)
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
if (mcpToolsStateChanged) {
|
|
1814
|
+
writeMcpToolsState(mcpToolsState)
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
state.plugins = state.plugins.filter((p) => p.name !== pluginName)
|
|
1818
|
+
writeState(state)
|
|
1819
|
+
invalidateParserCaches()
|
|
1820
|
+
return { ok: true }
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
/** Toggle a plugin's skills scanning and connectors on/off. */
|
|
1824
|
+
export async function togglePlugin(pluginName, enabled) {
|
|
1825
|
+
const state = readState()
|
|
1826
|
+
const rec = state.plugins.find((p) => p.name === pluginName)
|
|
1827
|
+
if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
|
|
1828
|
+
const target = installedDir(pluginName)
|
|
1829
|
+
const skillsDir = join(target, 'skills')
|
|
1830
|
+
const skills = listSkills(target)
|
|
1831
|
+
const skillNames = skills.map((s) => s.command || s.name || pluginName)
|
|
1832
|
+
const pluginConnectors = getPluginConnectors(target)
|
|
1833
|
+
const lspErrors = []
|
|
1834
|
+
|
|
1835
|
+
if (enabled) {
|
|
1836
|
+
if (existsSync(skillsDir)) {
|
|
1837
|
+
syncPluginSkillsToDsh(pluginName)
|
|
1838
|
+
}
|
|
1839
|
+
for (const c of pluginConnectors) {
|
|
1840
|
+
registerConnector(pluginName, c.name, c)
|
|
1841
|
+
}
|
|
1842
|
+
for (const r of registerPluginLsp(pluginName)) {
|
|
1843
|
+
if (!r.ok && r.error) lspErrors.push(r.error)
|
|
1844
|
+
}
|
|
1845
|
+
await registerPluginHooks(pluginName)
|
|
1846
|
+
} else {
|
|
1847
|
+
removePluginSkillsFromDsh(pluginName)
|
|
1848
|
+
for (const c of pluginConnectors) {
|
|
1849
|
+
unregisterConnector(pluginName, c.name)
|
|
1850
|
+
}
|
|
1851
|
+
unregisterPluginLsp(pluginName)
|
|
1852
|
+
unregisterPluginHooks(pluginName)
|
|
1853
|
+
}
|
|
1854
|
+
rec.enabled = enabled
|
|
1855
|
+
writeState(state)
|
|
1856
|
+
return { ok: true, enabled, lspErrors: lspErrors.length > 0 ? lspErrors : undefined }
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
/**
|
|
1860
|
+
* Update: pull the source (for local sources) or re-clone the remote, then
|
|
1861
|
+
* reinstall the plugin copy and re-run conversions.
|
|
1862
|
+
*/
|
|
1863
|
+
export async function updatePlugin(pluginName) {
|
|
1864
|
+
const state = readState()
|
|
1865
|
+
const rec = state.plugins.find((p) => p.name === pluginName)
|
|
1866
|
+
if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
|
|
1867
|
+
const source = state.sources.find((s) => s.id === rec.sourceId)
|
|
1868
|
+
if (source && typeof source.url === 'string') {
|
|
1869
|
+
const cacheDir = join(marketRoot(), 'market', rec.sourceId)
|
|
1870
|
+
if (existsSync(join(cacheDir, '.git'))) {
|
|
1871
|
+
await pullSource(rec.sourceId)
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
// Clear memory cache so fresh MCP tool lists can be queried
|
|
1876
|
+
for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
|
|
1877
|
+
if (k.startsWith(`${pluginName}::`)) {
|
|
1878
|
+
MEMORY_TOOLS_CACHE.delete(k)
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// The marketplace rows are cached for 30s; without this the install below
|
|
1883
|
+
// re-reads the pre-pull catalog and installs the old revision.
|
|
1884
|
+
invalidateMarketplaceCache(rec.sourceId)
|
|
1885
|
+
|
|
1886
|
+
// Freshly materialized install (re-copies, re-registers, re-converts).
|
|
1887
|
+
return installPlugin({ sourceId: rec.sourceId, pluginName, refresh: true })
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
/** Find one marketplace row by name. */
|
|
1891
|
+
export async function findMarketRow(sourceId, pluginName) {
|
|
1892
|
+
const { readMarketplace } = await import('./parser.js')
|
|
1893
|
+
const rows = readMarketplace(sourceId)
|
|
1894
|
+
return rows.find((r) => r.name === pluginName) ?? null
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
/** Re-exported for routes: list installed plugins with details. */
|
|
1898
|
+
export function installedDetails() {
|
|
1899
|
+
const state = readState()
|
|
1900
|
+
return state.plugins.map((rec) => {
|
|
1901
|
+
const target = installedDir(rec.name)
|
|
1902
|
+
if (existsSync(target)) {
|
|
1903
|
+
const skillsDir = join(target, 'skills')
|
|
1904
|
+
if (!existsSync(skillsDir)) {
|
|
1905
|
+
try { mkdirSync(skillsDir, { recursive: true }) } catch {}
|
|
1906
|
+
}
|
|
1907
|
+
try {
|
|
1908
|
+
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
1909
|
+
if (
|
|
1910
|
+
entry.isDirectory() &&
|
|
1911
|
+
entry.name !== 'skills' &&
|
|
1912
|
+
entry.name !== 'commands' &&
|
|
1913
|
+
entry.name !== 'agents' &&
|
|
1914
|
+
entry.name !== '.agents' &&
|
|
1915
|
+
entry.name !== 'node_modules' &&
|
|
1916
|
+
entry.name !== '.git'
|
|
1917
|
+
) {
|
|
1918
|
+
const sMd = join(target, entry.name, 'SKILL.md')
|
|
1919
|
+
if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
|
|
1920
|
+
const subDir = join(skillsDir, entry.name)
|
|
1921
|
+
mkdirSync(subDir, { recursive: true })
|
|
1922
|
+
copyDir(join(target, entry.name), subDir)
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
} catch {}
|
|
1927
|
+
}
|
|
1928
|
+
const connectors = existsSync(target) ? getPluginConnectors(target).map((c) => {
|
|
1929
|
+
const needsAuth = connectorRequiresAuth(c)
|
|
1930
|
+
const authenticated = isConnectorAuthenticated(rec.name, c.name)
|
|
1931
|
+
const connected = isConnectorActive(rec.name, c.name)
|
|
1932
|
+
const savedEntry = getConnectorEntry(rec.name, c.name)
|
|
1933
|
+
const savedConfig = savedEntry?.config || {}
|
|
1934
|
+
const savedHeaders = (savedConfig.headers && Object.keys(savedConfig.headers).length > 0) ? savedConfig.headers : c.headers
|
|
1935
|
+
const savedEnv = (savedConfig.env && Object.keys(savedConfig.env).length > 0) ? savedConfig.env : c.env
|
|
1936
|
+
const savedUrl = savedConfig.url || c.url
|
|
1937
|
+
const savedArgs = (savedConfig.args && savedConfig.args.length > 0) ? savedConfig.args : c.args
|
|
1938
|
+
const savedTransport = savedConfig.transport ? (savedConfig.transport === 'streamable-http' ? 'http' : (savedConfig.transport === 'stdio' ? 'stdio' : c.type)) : c.type
|
|
1939
|
+
|
|
1940
|
+
return {
|
|
1941
|
+
...c,
|
|
1942
|
+
type: savedTransport,
|
|
1943
|
+
url: savedUrl,
|
|
1944
|
+
headers: savedHeaders,
|
|
1945
|
+
env: savedEnv,
|
|
1946
|
+
args: savedArgs,
|
|
1947
|
+
oauth: savedConfig.oauth || c.oauth || 'none',
|
|
1948
|
+
needsAuth,
|
|
1949
|
+
authenticated,
|
|
1950
|
+
connected,
|
|
1951
|
+
}
|
|
1952
|
+
}) : []
|
|
1953
|
+
let lspServers = existsSync(target) ? listLspServers(target) : []
|
|
1954
|
+
// Auto-activate: if an LSP server's binary is now on PATH but the entry
|
|
1955
|
+
// hasn't been written to cordis.patch.yml yet (e.g. the user installed the
|
|
1956
|
+
// binary after the plugin — registration was previously skipped because the
|
|
1957
|
+
// command was missing), register it on the spot. Registration is idempotent
|
|
1958
|
+
// and only writes the patch; it does not require a manual "Update" click.
|
|
1959
|
+
// DSH's HMR watches this patch file and re-applies the plugin tree within
|
|
1960
|
+
// ~1s, so the newly registered server becomes truly active immediately —
|
|
1961
|
+
// no DSH restart needed (verified against @deepseek-ai/dsh-app-boot's
|
|
1962
|
+
// `watchUserPatches`, which registers cordis.patch.yml with Cordis HMR).
|
|
1963
|
+
if (existsSync(target) && lspServers.length > 0) {
|
|
1964
|
+
const autoRegistered = lspServers.filter((s) => {
|
|
1965
|
+
if (isLspActive(rec.name, s.name)) return false
|
|
1966
|
+
// Honor an explicit removal: if we already auto-activated this server
|
|
1967
|
+
// once but it is no longer in the patch, the user (or a manual patch
|
|
1968
|
+
// edit) removed it deliberately — do not silently re-add it.
|
|
1969
|
+
if (autoActivatedLspServers.has(`${rec.name}::${s.name}`)) return false
|
|
1970
|
+
// Host packages must actually be in DSH's node_modules — otherwise
|
|
1971
|
+
// auto-registering would write a patch entry that DSH can't load.
|
|
1972
|
+
return !!s.command
|
|
1973
|
+
&& resolveCommandPath(s.command)
|
|
1974
|
+
&& Object.keys(s.extensionToLanguage || {}).length > 0
|
|
1975
|
+
})
|
|
1976
|
+
if (autoRegistered.length > 0) {
|
|
1977
|
+
for (const s of autoRegistered) {
|
|
1978
|
+
try {
|
|
1979
|
+
const r = registerLspServer(rec.name, s.name, s)
|
|
1980
|
+
if (r.ok) autoActivatedLspServers.add(`${rec.name}::${s.name}`)
|
|
1981
|
+
} catch {}
|
|
1982
|
+
}
|
|
1983
|
+
lspServers = listLspServers(target)
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
lspServers = lspServers.map((s) => {
|
|
1987
|
+
const active = isLspActive(rec.name, s.name)
|
|
1988
|
+
// For inactive servers, surface *why*: a missing command is the only
|
|
1989
|
+
// reason registration fails that the UI can help the user resolve
|
|
1990
|
+
// (install the binary, then hit Update). Other reasons (missing
|
|
1991
|
+
// extensionToLanguage) are manifest bugs and don't need this hint.
|
|
1992
|
+
const missingCommand = !active && !!s.command && !resolveCommandPath(s.command)
|
|
1993
|
+
return { ...s, active, missingCommand }
|
|
1994
|
+
})
|
|
1995
|
+
const detail = existsSync(target) ? {
|
|
1996
|
+
icons: buildPluginIcons(readPluginManifest(target), { sourceId: rec.sourceId, name: rec.name, dir: target }),
|
|
1997
|
+
skills: listSkills(target),
|
|
1998
|
+
agents: listAgents(target),
|
|
1999
|
+
prompts: listPrompts(target),
|
|
2000
|
+
connectors,
|
|
2001
|
+
hooks: listHooks(target),
|
|
2002
|
+
lspServers,
|
|
2003
|
+
version: readInstalledVersion(target) ?? null,
|
|
2004
|
+
} : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
|
|
2005
|
+
return {
|
|
2006
|
+
...rec,
|
|
2007
|
+
...detail,
|
|
2008
|
+
skillCount: detail.skills.length,
|
|
2009
|
+
agentCount: detail.agents.length,
|
|
2010
|
+
promptCount: detail.prompts.length,
|
|
2011
|
+
connectorCount: connectors.length,
|
|
2012
|
+
hookCount: detail.hooks.length,
|
|
2013
|
+
lspServerCount: lspServers.length,
|
|
2014
|
+
dir: target,
|
|
2015
|
+
}
|
|
2016
|
+
})
|
|
2017
|
+
}
|