universal-plugin-hub 1.1.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/README.zh.md +14 -2
- package/client/client.js +5421 -1199
- package/package.json +1 -1
- package/src/at-plugins.js +823 -0
- package/src/icons.js +226 -36
- package/src/index.js +44 -2
- package/src/install.js +1618 -852
- package/src/local.js +439 -71
- package/src/market.js +112 -56
- package/src/oauth-bridge.js +1 -2
- package/src/oauth-config.js +4 -0
- package/src/oauth-store.js +24 -11
- package/src/oauth.js +5 -4
- package/src/parser.js +1272 -462
- package/src/routes.js +410 -128
- package/src/runtime.js +3 -1
- package/src/skill-uploads.js +116 -12
- package/src/skills.js +12 -5
- package/src/store.js +258 -40
package/src/install.js
CHANGED
|
@@ -9,22 +9,26 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { existsSync, lstatSync, mkdirSync, rmSync, readFileSync, writeFileSync, renameSync, readdirSync, copyFileSync, statSync, accessSync, constants as fsConstants } from 'node:fs'
|
|
11
11
|
import { fileURLToPath } from 'node:url'
|
|
12
|
-
import { dirname, join, basename, isAbsolute, resolve, extname, delimiter } from 'node:path'
|
|
13
|
-
import {
|
|
12
|
+
import { dirname, join, basename, isAbsolute, resolve, extname, delimiter, sep } from 'node:path'
|
|
13
|
+
import { execFile, execFileSync } from 'node:child_process'
|
|
14
14
|
import { gunzipSync } from 'node:zlib'
|
|
15
15
|
import { createHash } from 'node:crypto'
|
|
16
16
|
import { homedir } from 'node:os'
|
|
17
17
|
import { setImmediate as yieldToHost, setTimeout as delay } from 'node:timers/promises'
|
|
18
18
|
import * as yaml from 'js-yaml'
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
19
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
|
|
20
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
|
|
21
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
|
|
22
|
+
import { ErrorCode } from '@modelcontextprotocol/sdk/types.js'
|
|
23
|
+
import { installedDir, pluginDataDir, compiledHooksPath, readState, writeState, slugify, dshHome, dshSkillsDir, safeRmDir, removeManagedDir, sourceCacheDir, trashRoot, isSameOrInsidePath } from './store.js'
|
|
24
|
+
import { materializePlugin, pullSource } from './market.js'
|
|
25
|
+
import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, readPluginShortDescription, formatDisplayName, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName, PLUGIN_RUNTIME_ENV_KEYS, hasUnresolvedVarPlaceholder, isDotRelativePath, expandPluginVars, resolvePluginCommand, resolvePluginCwd, resolvePluginSpecPath, resolveConnectorDisplay, resolvePluginCommandEntries, compileResolvedHooks, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
|
|
22
26
|
import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
|
|
23
27
|
import { isUploadedSkillTarget } from './skill-uploads.js'
|
|
24
28
|
import { buildPluginIcons } from './icons.js'
|
|
25
29
|
import { beginOAuthVerification, completeOAuthVerification, cancelPluginOAuthVerifications, standaloneOAuthConnectorNames, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
|
|
26
|
-
import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
|
|
27
|
-
import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord } from './oauth-store.js'
|
|
30
|
+
import { bridgeRuntimeEnv, encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
|
|
31
|
+
import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord, openOAuthRecordWriter } from './oauth-store.js'
|
|
28
32
|
|
|
29
33
|
const OAUTH_BRIDGE_PATH = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
|
|
30
34
|
|
|
@@ -46,24 +50,92 @@ export function cordisPatchPath() {
|
|
|
46
50
|
return profilePatch
|
|
47
51
|
}
|
|
48
52
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
53
|
+
function loadCordisPatch(file) {
|
|
54
|
+
let source
|
|
55
|
+
try {
|
|
56
|
+
source = readFileSync(file, 'utf8')
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (error.code === 'ENOENT') return []
|
|
59
|
+
throw new Error(`无法读取 ${file},已中止写入以保护现有配置。`, { cause: error })
|
|
60
|
+
}
|
|
61
|
+
// js-yaml can reject an empty stream. An explicit null value is still a document.
|
|
62
|
+
if (source.replace(/^\uFEFF/, '').split(/\r\n?|\n/).every((line) => /^[ \t]*(?:#.*)?$/.test(line))) return []
|
|
63
|
+
|
|
64
|
+
let parsed
|
|
65
|
+
try {
|
|
66
|
+
parsed = yaml.load(source)
|
|
67
|
+
} catch (error) {
|
|
68
|
+
throw new Error(`无法解析 ${file},已中止写入以保护现有配置。请通过 DSH 配置文件手动修改。`, { cause: error })
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(parsed)) {
|
|
71
|
+
throw new Error(`${file} 的顶层必须是数组,已中止写入以保护现有配置。`)
|
|
72
|
+
}
|
|
73
|
+
return parsed
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let PATCH_TMP_SEQ = 0
|
|
77
|
+
let ACTIVE_CORDIS_BATCH = null
|
|
78
|
+
|
|
79
|
+
function readCordisPatchRaw() {
|
|
52
80
|
try {
|
|
53
|
-
|
|
54
|
-
return Array.isArray(parsed) ? parsed : []
|
|
81
|
+
return loadCordisPatch(cordisPatchPath())
|
|
55
82
|
} catch {
|
|
56
83
|
return []
|
|
57
84
|
}
|
|
58
85
|
}
|
|
59
86
|
|
|
60
|
-
|
|
87
|
+
function writeCordisPatchRaw(patch) {
|
|
61
88
|
const file = cordisPatchPath()
|
|
89
|
+
// A tolerant read can return [] for a DSH-specific or damaged document.
|
|
90
|
+
// Check the on-disk document before any mutation can replace it.
|
|
91
|
+
loadCordisPatch(file)
|
|
62
92
|
mkdirSync(dirname(file), { recursive: true })
|
|
63
93
|
const content = yaml.dump(patch, { indent: 2, lineWidth: -1 })
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
94
|
+
const seq = (PATCH_TMP_SEQ = (PATCH_TMP_SEQ + 1) & 0xffffff).toString(36)
|
|
95
|
+
const tmp = join(dirname(file), `.cordis.patch.${process.pid}.${Date.now().toString(36)}.${seq}.tmp`)
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(tmp, content, 'utf8')
|
|
98
|
+
renameSync(tmp, file)
|
|
99
|
+
} catch (error) {
|
|
100
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
101
|
+
throw error
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function readCordisPatch() {
|
|
106
|
+
if (ACTIVE_CORDIS_BATCH) {
|
|
107
|
+
return (ACTIVE_CORDIS_BATCH.patch ??= readCordisPatchRaw())
|
|
108
|
+
}
|
|
109
|
+
return readCordisPatchRaw()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function writeCordisPatch(patch) {
|
|
113
|
+
if (ACTIVE_CORDIS_BATCH) {
|
|
114
|
+
ACTIVE_CORDIS_BATCH.patch = patch
|
|
115
|
+
ACTIVE_CORDIS_BATCH.dirty = true
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
writeCordisPatchRaw(patch)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function withCordisPatchBatch(fn) {
|
|
122
|
+
if (ACTIVE_CORDIS_BATCH) return fn()
|
|
123
|
+
const batch = { patch: null, dirty: false }
|
|
124
|
+
ACTIVE_CORDIS_BATCH = batch
|
|
125
|
+
let completed = false
|
|
126
|
+
try {
|
|
127
|
+
const result = fn()
|
|
128
|
+
completed = true
|
|
129
|
+
return result
|
|
130
|
+
} finally {
|
|
131
|
+
ACTIVE_CORDIS_BATCH = null
|
|
132
|
+
if (batch.dirty && batch.patch !== null) {
|
|
133
|
+
if (completed) writeCordisPatchRaw(batch.patch)
|
|
134
|
+
else {
|
|
135
|
+
try { writeCordisPatchRaw(batch.patch) } catch {}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
67
139
|
}
|
|
68
140
|
|
|
69
141
|
export function getConnectorId(pluginName, connectorName) {
|
|
@@ -101,18 +173,18 @@ export function connectorRequiresAuth(cfg) {
|
|
|
101
173
|
// 2. If URL explicitly embeds a concrete API key / token query parameter (e.g. Tavily: ?api_key=tvly-...)
|
|
102
174
|
if (cfg.url && typeof cfg.url === 'string' && /[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i.test(cfg.url)) {
|
|
103
175
|
const match = cfg.url.match(/[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i)
|
|
104
|
-
if (match && !match[2]
|
|
176
|
+
if (match && !hasUnresolvedVarPlaceholder(match[2]) && match[2].trim().length > 3) {
|
|
105
177
|
return false // Ready to connect directly without separate header
|
|
106
178
|
}
|
|
107
179
|
}
|
|
108
180
|
// 3. Explicit template placeholders in headers (e.g. ${GITHUB_PERSONAL_ACCESS_TOKEN})
|
|
109
181
|
if (cfg.headers && typeof cfg.headers === 'object') {
|
|
110
|
-
if (Object.values(cfg.headers).some((v) => typeof v === 'string' && v
|
|
182
|
+
if (Object.values(cfg.headers).some((v) => typeof v === 'string' && hasUnresolvedVarPlaceholder(v))) return true
|
|
111
183
|
if (Object.keys(cfg.headers).some((k) => /auth|token|key|secret/i.test(k) && !cfg.headers[k])) return true
|
|
112
184
|
}
|
|
113
185
|
// 4. Explicit template placeholders in env (e.g. ${NOTION_API_KEY} or ${API_KEY})
|
|
114
186
|
if (cfg.env && typeof cfg.env === 'object') {
|
|
115
|
-
if (Object.values(cfg.env).some((v) => typeof v === 'string' && v
|
|
187
|
+
if (Object.values(cfg.env).some((v) => typeof v === 'string' && hasUnresolvedVarPlaceholder(v))) return true
|
|
116
188
|
if (Object.keys(cfg.env).some((k) => /auth|token|key|secret|password/i.test(k) && !cfg.env[k])) return true
|
|
117
189
|
}
|
|
118
190
|
// 5. Known cloud MCP services that mandate authentication tokens
|
|
@@ -128,7 +200,7 @@ export function connectorRequiresAuth(cfg) {
|
|
|
128
200
|
if (isHttp) {
|
|
129
201
|
if (cfg.url && /^https?:\/\//i.test(cfg.url) && !/localhost|127\.0\.0\.1/i.test(cfg.url)) {
|
|
130
202
|
const authHeader = cfg.headers?.Authorization || cfg.headers?.authorization
|
|
131
|
-
if (!authHeader || authHeader
|
|
203
|
+
if (!authHeader || hasUnresolvedVarPlaceholder(authHeader)) {
|
|
132
204
|
return true
|
|
133
205
|
}
|
|
134
206
|
}
|
|
@@ -168,18 +240,18 @@ function connectorAuthenticated(found, entry) {
|
|
|
168
240
|
const url = cfg.url || found.url || ''
|
|
169
241
|
if (url && typeof url === 'string' && /[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i.test(url)) {
|
|
170
242
|
const match = url.match(/[?&](api_key|apiKey|token|key|access_token)=([^&]+)/i)
|
|
171
|
-
if (match && !match[2]
|
|
243
|
+
if (match && !hasUnresolvedVarPlaceholder(match[2]) && match[2].trim().length > 3) {
|
|
172
244
|
return true
|
|
173
245
|
}
|
|
174
246
|
}
|
|
175
247
|
const authHeader = cfg.headers?.Authorization || cfg.headers?.authorization || ''
|
|
176
|
-
if (authHeader && !authHeader
|
|
248
|
+
if (authHeader && !hasUnresolvedVarPlaceholder(authHeader) && authHeader.trim().length > 0) {
|
|
177
249
|
return true
|
|
178
250
|
}
|
|
179
|
-
if (cfg.headers && Object.values(cfg.headers).some((v) => typeof v === 'string' && !v
|
|
251
|
+
if (cfg.headers && Object.values(cfg.headers).some((v) => typeof v === 'string' && !hasUnresolvedVarPlaceholder(v) && v.trim().length > 0)) {
|
|
180
252
|
return true
|
|
181
253
|
}
|
|
182
|
-
if (cfg.env && Object.values(cfg.env).some((v) => typeof v === 'string' && !v
|
|
254
|
+
if (cfg.env && Object.values(cfg.env).some((v) => typeof v === 'string' && !hasUnresolvedVarPlaceholder(v) && v.trim().length > 0)) {
|
|
183
255
|
return true
|
|
184
256
|
}
|
|
185
257
|
return false
|
|
@@ -189,32 +261,58 @@ function isRemoteConnector(config = {}) {
|
|
|
189
261
|
return isRemoteTransportName(config.transport) || isRemoteTransportName(config.type) || (!config.command && (!!config.url || !config.args?.length))
|
|
190
262
|
}
|
|
191
263
|
|
|
264
|
+
function stdioConfigFingerprint(definition = {}) {
|
|
265
|
+
const normalized = {
|
|
266
|
+
transport: 'stdio',
|
|
267
|
+
command: String(definition.command || '').trim(),
|
|
268
|
+
args: Array.isArray(definition.args) ? definition.args.map(String) : [],
|
|
269
|
+
...(definition.cwd ? { cwd: String(definition.cwd) } : {}),
|
|
270
|
+
env: Object.fromEntries(
|
|
271
|
+
Object.entries(definition.env || {}).sort(([a], [b]) => a.localeCompare(b)),
|
|
272
|
+
),
|
|
273
|
+
}
|
|
274
|
+
return createHash('sha256').update(JSON.stringify(normalized)).digest('hex')
|
|
275
|
+
}
|
|
276
|
+
|
|
192
277
|
function remoteConfigFingerprint(config = {}) {
|
|
278
|
+
const usesOAuth = isOAuthMode(config.oauth)
|
|
193
279
|
const normalized = {
|
|
194
280
|
transport: 'http',
|
|
195
281
|
url: String(config.url || '').trim(),
|
|
196
282
|
headers: Object.fromEntries(Object.entries(config.headers || {}).filter(([key]) => {
|
|
197
283
|
const name = key.toLowerCase()
|
|
198
|
-
return name !== 'content-type' && (!
|
|
284
|
+
return name !== 'content-type' && (!usesOAuth || name !== 'authorization')
|
|
199
285
|
}).sort(([a], [b]) => a.localeCompare(b))),
|
|
200
|
-
oauth: config.oauth
|
|
201
|
-
oauthClientId: config.oauthClientId || '',
|
|
202
|
-
oauthScope: config.oauthScope || '',
|
|
203
|
-
oauthCallbackPort: Number(config.oauthCallbackPort) || null,
|
|
286
|
+
oauth: usesOAuth ? config.oauth : 'none',
|
|
287
|
+
oauthClientId: usesOAuth ? config.oauthClientId || '' : '',
|
|
288
|
+
oauthScope: usesOAuth ? config.oauthScope || '' : '',
|
|
289
|
+
oauthCallbackPort: usesOAuth ? Number(config.oauthCallbackPort) || null : null,
|
|
204
290
|
}
|
|
205
291
|
return createHash('sha256').update(JSON.stringify(normalized)).digest('hex')
|
|
206
292
|
}
|
|
207
293
|
|
|
208
294
|
function setRemoteVerification(pluginName, connectorName, payload, verified) {
|
|
295
|
+
const fingerprint = remoteConfigFingerprint(payload)
|
|
296
|
+
const live = getConnectorEntry(pluginName, connectorName)?.config
|
|
297
|
+
if (live && remoteConfigFingerprint(remoteConfigFromEntry(live) || live) !== fingerprint) return
|
|
209
298
|
const key = `${pluginName}::${connectorName}`
|
|
210
299
|
const state = readMcpToolsState()
|
|
211
300
|
state[key] = {
|
|
212
301
|
...(state[key] || {}),
|
|
213
|
-
verifiedRemoteConfig: verified ?
|
|
302
|
+
verifiedRemoteConfig: verified ? fingerprint : null,
|
|
214
303
|
}
|
|
215
304
|
writeMcpToolsState(state)
|
|
216
305
|
}
|
|
217
306
|
|
|
307
|
+
export function isOAuthConnectorAuthenticated(pluginName, connectorName, remote, toolsState) {
|
|
308
|
+
if (!remote || !isOAuthMode(remote.oauth) || !remote.credentialKey) return false
|
|
309
|
+
const record = readOAuthRecord(remote.credentialKey)
|
|
310
|
+
if (!record?.tokens) return false
|
|
311
|
+
if (remote.oauth === 'custom' && record.customClient?.client_id !== remote.oauthClientId) return false
|
|
312
|
+
const stateEntry = (toolsState || readMcpToolsState())[`${pluginName}::${connectorName}`]
|
|
313
|
+
return stateEntry?.verifiedRemoteConfig === remoteConfigFingerprint(remote)
|
|
314
|
+
}
|
|
315
|
+
|
|
218
316
|
export function isConnectorActive(pluginName, connectorName) {
|
|
219
317
|
const entry = getConnectorEntry(pluginName, connectorName)
|
|
220
318
|
return connectorActive(entry, () => isConnectorAuthenticated(pluginName, connectorName),
|
|
@@ -230,32 +328,47 @@ function connectorActive(entry, authenticated, toolState) {
|
|
|
230
328
|
|
|
231
329
|
export const getPluginConnectors = listConnectors
|
|
232
330
|
|
|
233
|
-
export function substitutePluginRoot(val, pluginRoot) {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
res[k] = substitutePluginRoot(v, pluginRoot)
|
|
331
|
+
export function substitutePluginRoot(val, pluginRoot, explicitDataDir) {
|
|
332
|
+
return expandPluginVars(val, pluginRoot, explicitDataDir)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function stripSyntheticRuntimeEnv(envObj, pluginName, pluginRoot) {
|
|
336
|
+
if (!envObj || typeof envObj !== 'object') return {}
|
|
337
|
+
const normRoot = pluginRoot ? pluginRoot.replace(/\\/g, '/') : ''
|
|
338
|
+
const normData = pluginName && pluginName !== 'user-mcp' ? pluginDataDir(pluginName).replace(/\\/g, '/') : ''
|
|
339
|
+
const out = {}
|
|
340
|
+
for (const [k, v] of Object.entries(envObj)) {
|
|
341
|
+
if (PLUGIN_RUNTIME_ENV_KEYS.includes(k)) {
|
|
342
|
+
const val = typeof v === 'string' ? v.replace(/\\/g, '/') : v
|
|
343
|
+
if (val === normRoot || val === normData) continue
|
|
247
344
|
}
|
|
248
|
-
|
|
345
|
+
out[k] = v
|
|
346
|
+
}
|
|
347
|
+
return out
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function pluginRuntimeEnv(pluginName, pluginRoot, existingEnv = {}, pluginOwned = pluginName !== 'user-mcp') {
|
|
351
|
+
if (!pluginOwned || !pluginRoot) return { ...(existingEnv || {}) }
|
|
352
|
+
const normRoot = pluginRoot.replace(/\\/g, '/')
|
|
353
|
+
const dataDir = pluginDataDir(pluginName)
|
|
354
|
+
mkdirSync(dataDir, { recursive: true })
|
|
355
|
+
const normData = dataDir.replace(/\\/g, '/')
|
|
356
|
+
return {
|
|
357
|
+
PLUGIN_ROOT: normRoot,
|
|
358
|
+
PLUGIN_DATA: normData,
|
|
359
|
+
CLAUDE_PLUGIN_ROOT: normRoot,
|
|
360
|
+
CLAUDE_PLUGIN_DATA: normData,
|
|
361
|
+
...(existingEnv || {}),
|
|
249
362
|
}
|
|
250
|
-
return val
|
|
251
363
|
}
|
|
252
364
|
|
|
253
365
|
export function registerConnector(pluginName, connectorName, connectorConfig) {
|
|
254
366
|
const patch = readCordisPatch()
|
|
255
367
|
const id = getConnectorId(pluginName, connectorName)
|
|
256
|
-
const
|
|
257
|
-
const pluginRoot = installedDir(pluginName)
|
|
258
|
-
const
|
|
368
|
+
const pluginOwned = pluginName !== 'user-mcp'
|
|
369
|
+
const pluginRoot = pluginOwned ? installedDir(pluginName) : ''
|
|
370
|
+
const dataDir = pluginOwned ? pluginDataDir(pluginName) : ''
|
|
371
|
+
const resolvedConfig = substitutePluginRoot(connectorConfig || {}, pluginRoot, dataDir)
|
|
259
372
|
|
|
260
373
|
let insertBlock = patch.find((item) => item && Array.isArray(item.insert))
|
|
261
374
|
if (!insertBlock) {
|
|
@@ -279,9 +392,25 @@ export function registerConnector(pluginName, connectorName, connectorConfig) {
|
|
|
279
392
|
if (resolvedConfig.headers && Object.keys(resolvedConfig.headers).length > 0) {
|
|
280
393
|
clientConfig.headers = resolvedConfig.headers
|
|
281
394
|
}
|
|
282
|
-
if (
|
|
283
|
-
|
|
284
|
-
|
|
395
|
+
if (!isHttp) {
|
|
396
|
+
const resolvedCmd = resolvePluginCommand(connectorConfig?.command, pluginRoot, dataDir)
|
|
397
|
+
if (resolvedCmd) clientConfig.command = resolvedCmd
|
|
398
|
+
if (resolvedConfig.args && resolvedConfig.args.length > 0) clientConfig.args = resolvedConfig.args
|
|
399
|
+
const resolvedCwd = resolvePluginCwd(connectorConfig?.cwd, pluginRoot, dataDir, {
|
|
400
|
+
command: connectorConfig?.command,
|
|
401
|
+
args: connectorConfig?.args,
|
|
402
|
+
})
|
|
403
|
+
if (resolvedCwd) clientConfig.cwd = resolvedCwd
|
|
404
|
+
const isOAuthBridge = Array.isArray(resolvedConfig.args) && resolvedConfig.args[0] === OAUTH_BRIDGE_PATH
|
|
405
|
+
const mergedEnv = isOAuthBridge
|
|
406
|
+
? (resolvedConfig.env || {})
|
|
407
|
+
: pluginRuntimeEnv(pluginName, pluginRoot, resolvedConfig.env, pluginOwned)
|
|
408
|
+
if (Object.keys(mergedEnv).length > 0) clientConfig.env = mergedEnv
|
|
409
|
+
} else {
|
|
410
|
+
if (resolvedConfig.command) clientConfig.command = resolvedConfig.command
|
|
411
|
+
if (resolvedConfig.args && resolvedConfig.args.length > 0) clientConfig.args = resolvedConfig.args
|
|
412
|
+
if (resolvedConfig.env && Object.keys(resolvedConfig.env).length > 0) clientConfig.env = resolvedConfig.env
|
|
413
|
+
}
|
|
285
414
|
|
|
286
415
|
insertBlock.insert.push({
|
|
287
416
|
id,
|
|
@@ -293,25 +422,98 @@ export function registerConnector(pluginName, connectorName, connectorConfig) {
|
|
|
293
422
|
return { ok: true, connected: true }
|
|
294
423
|
}
|
|
295
424
|
|
|
296
|
-
|
|
425
|
+
function canonicalConnectorSpec(cfg = {}, pluginName, pluginRoot) {
|
|
426
|
+
const isHttp = isRemoteConnector(cfg)
|
|
427
|
+
const rawEnv = cfg.env ? stripSyntheticRuntimeEnv(cfg.env, pluginName, pluginRoot) : {}
|
|
428
|
+
const sortEntries = (obj) => Object.entries(obj || {}).sort(([a], [b]) => a.localeCompare(b))
|
|
429
|
+
return JSON.stringify({
|
|
430
|
+
transport: isHttp ? 'http' : 'stdio',
|
|
431
|
+
url: isHttp ? (cfg.url || null) : null,
|
|
432
|
+
command: cfg.command || null,
|
|
433
|
+
args: Array.isArray(cfg.args) ? cfg.args : [],
|
|
434
|
+
cwd: !isHttp ? (cfg.cwd || '') : '',
|
|
435
|
+
headers: sortEntries(cfg.headers),
|
|
436
|
+
env: sortEntries(rawEnv),
|
|
437
|
+
})
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export function unregisterConnector(pluginName, connectorName, { keepDefinition = false } = {}) {
|
|
441
|
+
const key = `${pluginName}::${connectorName}`
|
|
442
|
+
MCP_ACTIVATIONS.delete(key)
|
|
443
|
+
MCP_TOOLS_INFLIGHT.delete(key)
|
|
444
|
+
MEMORY_TOOLS_CACHE.delete(key)
|
|
445
|
+
cancelActivePluginProbes(pluginName, connectorName)
|
|
297
446
|
const patch = readCordisPatch()
|
|
298
447
|
const id = getConnectorId(pluginName, connectorName)
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
const key = `${pluginName}::${connectorName}`
|
|
302
|
-
const state = readMcpToolsState()
|
|
303
|
-
state[key] = { ...(state[key] || {}), savedOAuthRemoteConfig: remote }
|
|
304
|
-
writeMcpToolsState(state)
|
|
305
|
-
}
|
|
306
|
-
|
|
448
|
+
let existingEntry = null
|
|
449
|
+
let changed = false
|
|
307
450
|
for (const item of patch) {
|
|
308
451
|
if (item && Array.isArray(item.insert)) {
|
|
309
|
-
|
|
452
|
+
const nextInsert = []
|
|
453
|
+
for (const entry of item.insert) {
|
|
454
|
+
if (entry && entry.id === id) {
|
|
455
|
+
if (!existingEntry) existingEntry = entry
|
|
456
|
+
changed = true
|
|
457
|
+
} else if (entry) {
|
|
458
|
+
nextInsert.push(entry)
|
|
459
|
+
} else {
|
|
460
|
+
changed = true
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (nextInsert.length !== item.insert.length) item.insert = nextInsert
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const config = existingEntry?.config
|
|
467
|
+
const remote = remoteConfigFromEntry(config)
|
|
468
|
+
if (remote || (keepDefinition && config)) {
|
|
469
|
+
const state = readMcpToolsState()
|
|
470
|
+
const prevSaved = state[key]
|
|
471
|
+
const pluginTarget = pluginName !== 'user-mcp' ? installedDir(pluginName) : ''
|
|
472
|
+
const cleanedConfig = config?.env
|
|
473
|
+
? { ...config, env: stripSyntheticRuntimeEnv(config.env, pluginName, pluginTarget) }
|
|
474
|
+
: config
|
|
475
|
+
const manifestDefault = !remote && pluginTarget && existsSync(pluginTarget)
|
|
476
|
+
? getPluginConnectors(pluginTarget).find((c) => c.name === connectorName)
|
|
477
|
+
: null
|
|
478
|
+
const matchesDefault = Boolean(
|
|
479
|
+
manifestDefault
|
|
480
|
+
&& !connectorRequiresAuth(manifestDefault)
|
|
481
|
+
&& !prevSaved?.savedConnectorDefinition
|
|
482
|
+
&& !prevSaved?.savedConnectorTemplate
|
|
483
|
+
&& canonicalConnectorSpec(cleanedConfig, pluginName, pluginTarget)
|
|
484
|
+
=== canonicalConnectorSpec(connectorDefinition(pluginName, connectorName, manifestDefault, true), pluginName, pluginTarget),
|
|
485
|
+
)
|
|
486
|
+
if (remote || !matchesDefault) {
|
|
487
|
+
const prev = state[key]
|
|
488
|
+
const saved = (state[key] = prev ? { ...prev } : {})
|
|
489
|
+
let changedEntry = !prev
|
|
490
|
+
if (remote) {
|
|
491
|
+
if (JSON.stringify(saved.savedOAuthRemoteConfig) !== JSON.stringify(remote)) {
|
|
492
|
+
saved.savedOAuthRemoteConfig = remote
|
|
493
|
+
changedEntry = true
|
|
494
|
+
}
|
|
495
|
+
} else {
|
|
496
|
+
const nextDef = {
|
|
497
|
+
...cleanedConfig,
|
|
498
|
+
transport: connectorTransport(cleanedConfig.transport, cleanedConfig.url, cleanedConfig.command),
|
|
499
|
+
}
|
|
500
|
+
if (JSON.stringify(saved.savedConnectorDefinition) !== JSON.stringify(nextDef)) {
|
|
501
|
+
saved.savedConnectorDefinition = nextDef
|
|
502
|
+
changedEntry = true
|
|
503
|
+
}
|
|
504
|
+
if (saved.pluginConnectorOwned !== true) {
|
|
505
|
+
saved.pluginConnectorOwned = true
|
|
506
|
+
changedEntry = true
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (changedEntry) writeMcpToolsState(state, { required: keepDefinition })
|
|
310
510
|
}
|
|
311
511
|
}
|
|
312
512
|
|
|
313
513
|
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
314
|
-
|
|
514
|
+
if (changed || cleaned.length !== patch.length) {
|
|
515
|
+
writeCordisPatch(cleaned)
|
|
516
|
+
}
|
|
315
517
|
return { ok: true, connected: false }
|
|
316
518
|
}
|
|
317
519
|
|
|
@@ -374,13 +576,16 @@ export function userMcpConfig(name, body = {}, fallback = {}) {
|
|
|
374
576
|
for (const candidate of [fallback.url, body.url]) {
|
|
375
577
|
if (typeof candidate === 'string' && candidate.trim()) usedUrls.add(candidate)
|
|
376
578
|
}
|
|
579
|
+
const rawCwd = pick(body.cwd, fallback.cwd ?? null)
|
|
580
|
+
const cwd = typeof rawCwd === 'string' && rawCwd.trim() ? rawCwd.trim() : null
|
|
377
581
|
return {
|
|
378
582
|
name,
|
|
379
583
|
usedUrls: [...usedUrls],
|
|
380
|
-
transport: (body.transport || fallback.transport
|
|
584
|
+
transport: connectorTransport(body.transport || fallback.transport, body.url ?? fallback.url, body.command ?? fallback.command),
|
|
381
585
|
url: pick(body.url, fallback.url ?? null),
|
|
382
586
|
command: pick(body.command, fallback.command ?? null),
|
|
383
587
|
args: Array.isArray(body.args) ? body.args : (fallback.args || []),
|
|
588
|
+
...(cwd ? { cwd } : {}),
|
|
384
589
|
env: body.env && typeof body.env === 'object' ? body.env : (fallback.env || {}),
|
|
385
590
|
headers: body.headers && typeof body.headers === 'object' ? body.headers : (fallback.headers || {}),
|
|
386
591
|
oauth: body.oauth || fallback.oauth || 'none',
|
|
@@ -398,7 +603,7 @@ export function userMcpConfig(name, body = {}, fallback = {}) {
|
|
|
398
603
|
* before the re-registration so the new registration reuses the existing
|
|
399
604
|
* sign-in instead of starting a new browser handshake.
|
|
400
605
|
*/
|
|
401
|
-
export function renameUserMcp(oldName, newName, payload) {
|
|
606
|
+
export function renameUserMcp(oldName, newName, payload, { enable = false, probe } = {}) {
|
|
402
607
|
if (oldName === newName) {
|
|
403
608
|
return saveConnectorAuth('user-mcp', newName, payload)
|
|
404
609
|
}
|
|
@@ -422,22 +627,30 @@ export function renameUserMcp(oldName, newName, payload) {
|
|
|
422
627
|
const urls = [...new Set([url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
|
|
423
628
|
.filter((u) => typeof u === 'string' && u.trim()))]
|
|
424
629
|
|
|
630
|
+
const copiedRecords = new Map()
|
|
425
631
|
for (const source of urls) {
|
|
426
632
|
for (const mode of modes) {
|
|
427
633
|
const from = oauthCredentialKey('user-mcp', oldName, source, mode)
|
|
428
634
|
const to = oauthCredentialKey('user-mcp', newName, source, mode)
|
|
429
635
|
const record = readOAuthRecord(from)
|
|
430
|
-
|
|
636
|
+
const existing = readOAuthRecord(to)
|
|
637
|
+
if (Object.keys(record).length > 0 && !existing.tokens) {
|
|
638
|
+
writeOAuthRecord(to, record)
|
|
639
|
+
copiedRecords.set(to, existing)
|
|
640
|
+
}
|
|
431
641
|
}
|
|
432
642
|
}
|
|
433
643
|
|
|
434
|
-
if (wasEnabled) {
|
|
644
|
+
if (wasEnabled || enable) {
|
|
435
645
|
const clientId = url ? readSavedOAuthClient('user-mcp', newName, url, 'custom').clientId : ''
|
|
436
646
|
// `saveConnectorAuth` reports failure both by returning `{ok:false}` and by
|
|
437
647
|
// throwing (e.g. a missing OAuth client id), so the rollback lives in one
|
|
438
648
|
// place that both paths reach.
|
|
439
649
|
const rollback = () => {
|
|
440
|
-
for (const
|
|
650
|
+
for (const [key, record] of copiedRecords) {
|
|
651
|
+
if (Object.keys(record).length > 0) writeOAuthRecord(key, record)
|
|
652
|
+
else deleteOAuthRecord(key)
|
|
653
|
+
}
|
|
441
654
|
}
|
|
442
655
|
let result
|
|
443
656
|
try {
|
|
@@ -447,7 +660,7 @@ export function renameUserMcp(oldName, newName, payload) {
|
|
|
447
660
|
// the old client back into the live registration while the definition
|
|
448
661
|
// says empty, and the next toggle would fail on the mismatch.
|
|
449
662
|
oauthClientId: payload?.oauthClientId !== undefined ? payload.oauthClientId : (clientId || ''),
|
|
450
|
-
})
|
|
663
|
+
}, { probe })
|
|
451
664
|
} catch (error) {
|
|
452
665
|
// Leave the old server untouched: a failed rename must not strand the
|
|
453
666
|
// user with neither name registered.
|
|
@@ -462,7 +675,7 @@ export function renameUserMcp(oldName, newName, payload) {
|
|
|
462
675
|
// normalized but ids are slugified, so `a.dot` and `a-dot` share one id —
|
|
463
676
|
// unregistering by the old name would delete the entry just written and
|
|
464
677
|
// leave the server silently disabled.
|
|
465
|
-
if (getConnectorId('user-mcp', oldName) !== getConnectorId('user-mcp', newName)) {
|
|
678
|
+
if (wasEnabled && getConnectorId('user-mcp', oldName) !== getConnectorId('user-mcp', newName)) {
|
|
466
679
|
unregisterConnector('user-mcp', oldName)
|
|
467
680
|
}
|
|
468
681
|
}
|
|
@@ -473,7 +686,10 @@ export function renameUserMcp(oldName, newName, payload) {
|
|
|
473
686
|
if (toolsState[oldKey] || toolsState[newKey]) {
|
|
474
687
|
const merged = { ...(toolsState[oldKey] || {}), ...(toolsState[newKey] || {}) }
|
|
475
688
|
if (Array.isArray(toolsState[oldKey]?.disabledTools)) merged.disabledTools = toolsState[oldKey].disabledTools
|
|
476
|
-
|
|
689
|
+
if (!probe?.ok) {
|
|
690
|
+
delete merged.cachedTools
|
|
691
|
+
delete merged.cachedToolsResolved
|
|
692
|
+
}
|
|
477
693
|
toolsState[newKey] = merged
|
|
478
694
|
delete toolsState[oldKey]
|
|
479
695
|
writeMcpToolsState(toolsState)
|
|
@@ -513,38 +729,37 @@ export function renameUserMcp(oldName, newName, payload) {
|
|
|
513
729
|
* package fine, then `lsp-stdio.apply()` rejects the command at load time
|
|
514
730
|
* and the entire DSH plugin tree fails to come up.
|
|
515
731
|
*/
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
if (!trimmed) return null
|
|
520
|
-
if (isAbsolute(trimmed)) {
|
|
732
|
+
function findExecutable(basePath, exts) {
|
|
733
|
+
for (const ext of exts) {
|
|
734
|
+
const candidate = basePath + ext
|
|
521
735
|
try {
|
|
522
|
-
if (!statSync(
|
|
523
|
-
accessSync(
|
|
524
|
-
return
|
|
736
|
+
if (!statSync(candidate).isFile()) continue
|
|
737
|
+
accessSync(candidate, fsConstants.X_OK)
|
|
738
|
+
return candidate
|
|
525
739
|
} catch {
|
|
526
|
-
|
|
740
|
+
// try next extension candidate
|
|
527
741
|
}
|
|
528
742
|
}
|
|
743
|
+
return null
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
export function resolveCommandPath(command, env = process.env, { cwd } = {}) {
|
|
747
|
+
if (typeof command !== 'string') return null
|
|
748
|
+
const trimmed = command.trim()
|
|
749
|
+
if (!trimmed) return null
|
|
750
|
+
const exts = process.platform === 'win32' && !extname(trimmed)
|
|
751
|
+
? String(env?.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
752
|
+
: ['']
|
|
753
|
+
if (isAbsolute(trimmed)) return findExecutable(trimmed, exts)
|
|
754
|
+
if (cwd && isDotRelativePath(trimmed)) return findExecutable(resolve(cwd, trimmed), exts)
|
|
529
755
|
if (trimmed.includes('/') || (process.platform === 'win32' && trimmed.includes('\\'))) {
|
|
530
756
|
return null
|
|
531
757
|
}
|
|
532
758
|
const pathEnv = (env && (env.PATH || env.Path)) || ''
|
|
533
759
|
if (!pathEnv) return null
|
|
534
|
-
const exts = process.platform === 'win32' && !extname(trimmed)
|
|
535
|
-
? String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
536
|
-
: ['']
|
|
537
760
|
for (const dir of pathEnv.split(delimiter).filter(Boolean)) {
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
try {
|
|
541
|
-
if (!statSync(candidate).isFile()) continue
|
|
542
|
-
accessSync(candidate, fsConstants.X_OK)
|
|
543
|
-
return candidate
|
|
544
|
-
} catch {
|
|
545
|
-
// not a match, try next candidate
|
|
546
|
-
}
|
|
547
|
-
}
|
|
761
|
+
const hit = findExecutable(resolve(dir, trimmed), exts)
|
|
762
|
+
if (hit) return hit
|
|
548
763
|
}
|
|
549
764
|
return null
|
|
550
765
|
}
|
|
@@ -981,9 +1196,11 @@ export function registerLspServer(pluginName, serverName, serverConfig) {
|
|
|
981
1196
|
const patch = readCordisPatch()
|
|
982
1197
|
const id = getLspServerId(pluginName, serverName)
|
|
983
1198
|
const pluginRoot = installedDir(pluginName)
|
|
984
|
-
const
|
|
1199
|
+
const dataDir = pluginDataDir(pluginName)
|
|
1200
|
+
const resolved = substitutePluginRoot(serverConfig || {}, pluginRoot, dataDir)
|
|
1201
|
+
const resolvedCmd = resolvePluginCommand(serverConfig?.command, pluginRoot, dataDir)
|
|
985
1202
|
|
|
986
|
-
if (!
|
|
1203
|
+
if (!resolvedCmd || typeof resolvedCmd !== 'string' || !resolvedCmd.trim()) {
|
|
987
1204
|
return { ok: false, active: false, error: `LSP server ${serverName} 缺少有效的 command` }
|
|
988
1205
|
}
|
|
989
1206
|
if (!resolved.extensionToLanguage || typeof resolved.extensionToLanguage !== 'object' || Object.keys(resolved.extensionToLanguage).length === 0) {
|
|
@@ -995,12 +1212,12 @@ export function registerLspServer(pluginName, serverName, serverConfig) {
|
|
|
995
1212
|
// time and throws if the command is missing — that exception aborts the
|
|
996
1213
|
// entire plugin tree. Returning here keeps DSH bootable and surfaces a
|
|
997
1214
|
// concrete remediation hint to the caller (UI / install result).
|
|
998
|
-
if (!resolveCommandPath(
|
|
1215
|
+
if (!resolveCommandPath(resolvedCmd, process.env, { cwd: pluginRoot })) {
|
|
999
1216
|
return {
|
|
1000
1217
|
ok: false,
|
|
1001
1218
|
active: false,
|
|
1002
|
-
error: `LSP server ${serverName} 注册失败:未找到可执行文件 "${
|
|
1003
|
-
`请先安装并确保其在 PATH 中(常见做法:npm install -g ${
|
|
1219
|
+
error: `LSP server ${serverName} 注册失败:未找到可执行文件 "${resolvedCmd}"。` +
|
|
1220
|
+
`请先安装并确保其在 PATH 中(常见做法:npm install -g ${resolvedCmd}),` +
|
|
1004
1221
|
`然后在管理页点击「更新」重新注册。`,
|
|
1005
1222
|
}
|
|
1006
1223
|
}
|
|
@@ -1011,7 +1228,7 @@ export function registerLspServer(pluginName, serverName, serverConfig) {
|
|
|
1011
1228
|
block.insert = block.insert.filter((item) => item && item.id !== id)
|
|
1012
1229
|
|
|
1013
1230
|
const serverEntry = {
|
|
1014
|
-
command:
|
|
1231
|
+
command: resolvedCmd,
|
|
1015
1232
|
extensionToLanguage: resolved.extensionToLanguage,
|
|
1016
1233
|
}
|
|
1017
1234
|
if (Array.isArray(resolved.args) && resolved.args.length > 0) serverEntry.args = resolved.args
|
|
@@ -1051,10 +1268,10 @@ export function unregisterPluginLsp(pluginName) {
|
|
|
1051
1268
|
}
|
|
1052
1269
|
}
|
|
1053
1270
|
}
|
|
1271
|
+
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
1272
|
+
writeCordisPatch(cleaned)
|
|
1054
1273
|
}
|
|
1055
1274
|
|
|
1056
|
-
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
1057
|
-
writeCordisPatch(cleaned)
|
|
1058
1275
|
return { ok: true, active: false }
|
|
1059
1276
|
}
|
|
1060
1277
|
|
|
@@ -1086,14 +1303,20 @@ export function getHookBridgeId(pluginName) {
|
|
|
1086
1303
|
*/
|
|
1087
1304
|
export async function registerPluginHooks(pluginName) {
|
|
1088
1305
|
const target = installedDir(pluginName)
|
|
1089
|
-
const
|
|
1306
|
+
const dataDir = pluginDataDir(pluginName)
|
|
1307
|
+
const compiled = compileResolvedHooks(target, readPluginManifest(target), dataDir)
|
|
1090
1308
|
// A version that dropped its hooks must also lose the previous bridge entry,
|
|
1091
1309
|
// otherwise the old hooks keep firing after reinstall.
|
|
1092
|
-
if (!
|
|
1310
|
+
if (!compiled) {
|
|
1093
1311
|
unregisterPluginHooks(pluginName)
|
|
1094
1312
|
return { ok: true, registered: [] }
|
|
1095
1313
|
}
|
|
1096
1314
|
|
|
1315
|
+
const outPath = compiledHooksPath(pluginName)
|
|
1316
|
+
mkdirSync(dirname(outPath), { recursive: true })
|
|
1317
|
+
mkdirSync(dataDir, { recursive: true })
|
|
1318
|
+
writeFileSync(outPath, JSON.stringify(compiled, null, 2), 'utf8')
|
|
1319
|
+
|
|
1097
1320
|
const patch = readCordisPatch()
|
|
1098
1321
|
const id = getHookBridgeId(pluginName)
|
|
1099
1322
|
const block = ensureInsertBlock(patch)
|
|
@@ -1102,25 +1325,33 @@ export async function registerPluginHooks(pluginName) {
|
|
|
1102
1325
|
id,
|
|
1103
1326
|
name: HOOK_BRIDGE_PKG,
|
|
1104
1327
|
config: {
|
|
1105
|
-
configPath,
|
|
1328
|
+
configPath: outPath,
|
|
1106
1329
|
pluginRoot: target,
|
|
1107
1330
|
},
|
|
1108
1331
|
})
|
|
1109
1332
|
writeCordisPatch(patch)
|
|
1110
|
-
return { ok: true, registered: [
|
|
1333
|
+
return { ok: true, registered: [outPath] }
|
|
1111
1334
|
}
|
|
1112
1335
|
|
|
1113
1336
|
/** Remove a plugin's hooks bridge entry from cordis.patch.yml. */
|
|
1114
1337
|
export function unregisterPluginHooks(pluginName) {
|
|
1115
1338
|
const patch = readCordisPatch()
|
|
1116
1339
|
const id = getHookBridgeId(pluginName)
|
|
1340
|
+
let changed = false
|
|
1117
1341
|
for (const item of patch) {
|
|
1118
1342
|
if (item && Array.isArray(item.insert)) {
|
|
1343
|
+
const before = item.insert.length
|
|
1119
1344
|
item.insert = item.insert.filter((entry) => entry && entry.id !== id)
|
|
1345
|
+
if (item.insert.length !== before) changed = true
|
|
1120
1346
|
}
|
|
1121
1347
|
}
|
|
1122
1348
|
const cleaned = patch.filter((item) => !item || !Array.isArray(item.insert) || item.insert.length > 0)
|
|
1123
|
-
|
|
1349
|
+
if (changed || cleaned.length !== patch.length) {
|
|
1350
|
+
writeCordisPatch(cleaned)
|
|
1351
|
+
}
|
|
1352
|
+
try {
|
|
1353
|
+
rmSync(compiledHooksPath(pluginName), { force: true })
|
|
1354
|
+
} catch {}
|
|
1124
1355
|
return { ok: true }
|
|
1125
1356
|
}
|
|
1126
1357
|
|
|
@@ -1137,288 +1368,413 @@ export function isLspActive(pluginName, serverName) {
|
|
|
1137
1368
|
*/
|
|
1138
1369
|
const autoActivatedLspServers = new Set()
|
|
1139
1370
|
|
|
1140
|
-
export function toggleConnector(pluginName, connectorName, enabled) {
|
|
1141
|
-
|
|
1142
|
-
const
|
|
1143
|
-
const
|
|
1371
|
+
export function toggleConnector(pluginName, connectorName, enabled, { canEnable } = {}) {
|
|
1372
|
+
if (!enabled) return unregisterConnector(pluginName, connectorName, { keepDefinition: true })
|
|
1373
|
+
const saved = readMcpToolsState()[`${pluginName}::${connectorName}`]
|
|
1374
|
+
const rememberDefinition = Boolean(
|
|
1375
|
+
saved?.savedConnectorDefinition || saved?.savedConnectorTemplate || saved?.savedOAuthRemoteConfig,
|
|
1376
|
+
)
|
|
1377
|
+
return enableConnector(pluginName, connectorName, undefined, { pluginOwned: true, rememberDefinition, canEnable })
|
|
1378
|
+
}
|
|
1144
1379
|
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
oauth: { mode: remote.oauth, clientId: remote.oauthClientId, callbackPort: remote.oauthCallbackPort, scope: remote.oauthScope },
|
|
1154
|
-
})) },
|
|
1155
|
-
}
|
|
1156
|
-
return registerConnector(pluginName, connectorName, { ...remote, type: 'stdio', command: saved.command, args: saved.args, env: saved.env })
|
|
1157
|
-
}
|
|
1158
|
-
if (connectorRequiresAuth(found) && !isConnectorAuthenticated(pluginName, connectorName)) {
|
|
1159
|
-
throw new Error(`请先验证并配置 ${connectorName} 的授权访问 Token`)
|
|
1380
|
+
function savedConnectorDefinition(pluginName, connectorName) {
|
|
1381
|
+
const entry = getConnectorEntry(pluginName, connectorName)
|
|
1382
|
+
const state = readMcpToolsState()[`${pluginName}::${connectorName}`]
|
|
1383
|
+
const saved = state?.savedConnectorDefinition
|
|
1384
|
+
if (entry) {
|
|
1385
|
+
return remoteConfigFromEntry(entry.config) || {
|
|
1386
|
+
...entry.config,
|
|
1387
|
+
transport: connectorTransport(entry.config.transport, entry.config.url, entry.config.command),
|
|
1160
1388
|
}
|
|
1161
|
-
return registerConnector(pluginName, connectorName, found)
|
|
1162
|
-
} else {
|
|
1163
|
-
return unregisterConnector(pluginName, connectorName)
|
|
1164
1389
|
}
|
|
1390
|
+
return state?.savedConnectorTemplate || saved || state?.savedOAuthRemoteConfig
|
|
1165
1391
|
}
|
|
1166
1392
|
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1393
|
+
function connectorEnvironment(found, payload) {
|
|
1394
|
+
if (payload?.env && typeof payload.env === 'object' && !Array.isArray(payload.env)) {
|
|
1395
|
+
return { ...payload.env }
|
|
1396
|
+
}
|
|
1397
|
+
return Object.fromEntries(Object.entries(found?.env || {}).filter(([, value]) =>
|
|
1398
|
+
typeof value !== 'string' || !hasUnresolvedVarPlaceholder(value)))
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
function isOAuthExpiredError(err) {
|
|
1402
|
+
return /OAuth 授权已(?:失效|移除)|Unauthorized|HTTP 401|\b401\b|invalid_token|invalid_grant|Invalid OAuth/i.test(String(err || ''))
|
|
1403
|
+
}
|
|
1171
1404
|
|
|
1172
|
-
|
|
1173
|
-
const
|
|
1174
|
-
const
|
|
1175
|
-
const
|
|
1176
|
-
|
|
1405
|
+
function cleanOAuthProbeError(err) {
|
|
1406
|
+
const raw = String(err || '').trim()
|
|
1407
|
+
const marker = /MCP error -32000:\s*Connection closed[::]\s*/i
|
|
1408
|
+
const match = marker.exec(raw)
|
|
1409
|
+
if (match) return raw.slice(match.index + match[0].length).trim() || raw
|
|
1410
|
+
return raw.replace(/^无法启动\s+.+?:\s+(?!\/\/)/, '').trim() || raw
|
|
1411
|
+
}
|
|
1177
1412
|
|
|
1178
|
-
|
|
1413
|
+
export async function verifyConnectorAuth(pluginName, connectorName, payload, { pluginOwned = pluginName !== 'user-mcp' } = {}) {
|
|
1414
|
+
const definition = connectorDefinition(pluginName, connectorName, payload, pluginOwned)
|
|
1415
|
+
const { transport, url } = definition
|
|
1416
|
+
const isOAuthRemote = transport !== 'stdio' && url && isOAuthMode(definition.oauth)
|
|
1417
|
+
const probeOnly = payload?.probeOnly === true
|
|
1418
|
+
if (isOAuthRemote && !probeOnly) {
|
|
1419
|
+
payload = { ...payload, ...definition }
|
|
1179
1420
|
try {
|
|
1180
1421
|
if (pluginOwned) rememberPluginOAuthUrls(pluginName, connectorName, url)
|
|
1181
|
-
setRemoteVerification(pluginName, connectorName, payload, false)
|
|
1182
1422
|
saveCustomOAuthClient(pluginName, connectorName, payload)
|
|
1183
|
-
|
|
1423
|
+
let session
|
|
1424
|
+
session = beginOAuthVerification(pluginName, connectorName, { ...payload, url }, {
|
|
1184
1425
|
pluginOwned,
|
|
1185
|
-
onFinished: (result) =>
|
|
1426
|
+
onFinished: (result) => {
|
|
1427
|
+
if (!session?.cancelled) setRemoteVerification(pluginName, connectorName, payload, result.ok === true)
|
|
1428
|
+
},
|
|
1186
1429
|
})
|
|
1187
1430
|
const result = await Promise.race([
|
|
1188
1431
|
completeOAuthVerification(session),
|
|
1189
1432
|
new Promise((resolve) => setTimeout(() => resolve({ pending: true, sessionId: session.id, status: session.status, message: session.message || '正在准备 OAuth 授权…' }), 250)),
|
|
1190
1433
|
])
|
|
1191
|
-
if (!session.cancelled) setRemoteVerification(pluginName, connectorName, payload, result.ok === true)
|
|
1434
|
+
if (!session.cancelled && !result.pending) setRemoteVerification(pluginName, connectorName, payload, result.ok === true)
|
|
1192
1435
|
return { ...result, server: connectorName, transport: 'http', endpoint: url, statusCode: result.statusCode ?? result.status }
|
|
1193
1436
|
} catch (error) {
|
|
1194
1437
|
return { ok: false, message: error.message, server: connectorName, transport: 'http', endpoint: url }
|
|
1195
1438
|
}
|
|
1196
1439
|
}
|
|
1197
1440
|
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
errorDetails: 'Remote-only MCP server does not support stdio transport',
|
|
1209
|
-
duration: 5,
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
if (!command) {
|
|
1441
|
+
const started = Date.now()
|
|
1442
|
+
if (isOAuthRemote && probeOnly) {
|
|
1443
|
+
const credKey = oauthCredentialKey(pluginName, connectorName, url, definition.oauth)
|
|
1444
|
+
const oauthRecord = readOAuthRecord(credKey)
|
|
1445
|
+
const missingClient = definition.oauth === 'custom' && (
|
|
1446
|
+
!oauthRecord?.customClient ||
|
|
1447
|
+
oauthRecord.customClient.client_id !== definition.oauthClientId ||
|
|
1448
|
+
(payload?.oauthClientSecret && oauthRecord.customClient.client_secret !== payload.oauthClientSecret)
|
|
1449
|
+
)
|
|
1450
|
+
if (!oauthRecord?.tokens || missingClient) {
|
|
1213
1451
|
return {
|
|
1214
1452
|
ok: false,
|
|
1215
|
-
|
|
1216
|
-
|
|
1453
|
+
mode: 'probe',
|
|
1454
|
+
authExpired: true,
|
|
1455
|
+
message: 'OAuth 授权已失效,请点击「登录并连接」重新授权。',
|
|
1217
1456
|
server: connectorName,
|
|
1218
|
-
transport: '
|
|
1219
|
-
endpoint:
|
|
1220
|
-
|
|
1221
|
-
|
|
1457
|
+
transport: 'http',
|
|
1458
|
+
endpoint: url,
|
|
1459
|
+
status: 401,
|
|
1460
|
+
statusCode: 401,
|
|
1461
|
+
duration: 0,
|
|
1222
1462
|
}
|
|
1223
1463
|
}
|
|
1224
|
-
const args = (typeof payload === 'object' && Array.isArray(payload?.args)) ? payload.args : (found?.args || [])
|
|
1225
|
-
return {
|
|
1226
|
-
ok: true,
|
|
1227
|
-
message: '本地 Connector (stdio) 服务已就绪',
|
|
1228
|
-
server: connectorName,
|
|
1229
|
-
transport: 'stdio',
|
|
1230
|
-
endpoint: `${command} ${args.join(' ')}`.trim(),
|
|
1231
|
-
duration: 10,
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
if (!url) {
|
|
1235
|
-
setRemoteVerification(pluginName, connectorName, payload, false)
|
|
1236
|
-
return {
|
|
1237
|
-
ok: false,
|
|
1238
|
-
message: '请输入有效的服务 URL',
|
|
1239
|
-
server: connectorName,
|
|
1240
|
-
transport,
|
|
1241
|
-
endpoint: '',
|
|
1242
|
-
}
|
|
1243
1464
|
}
|
|
1244
1465
|
|
|
1245
|
-
const
|
|
1246
|
-
|
|
1247
|
-
|
|
1466
|
+
const probe = await probeConnectorDefinition(pluginName, connectorName, definition, MCP_AUTH_TIMEOUT_MS)
|
|
1467
|
+
const errorMessage = probe.error ? (isOAuthRemote ? cleanOAuthProbeError(probe.error) : probe.error) : null
|
|
1468
|
+
const authExpired = isOAuthRemote && !!errorMessage && isOAuthExpiredError(errorMessage)
|
|
1469
|
+
if (!probeOnly && transport !== 'stdio') {
|
|
1470
|
+
setRemoteVerification(pluginName, connectorName, definition, !probe.error)
|
|
1248
1471
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
}
|
|
1472
|
+
return {
|
|
1473
|
+
ok: !probe.error,
|
|
1474
|
+
...(probeOnly ? { mode: 'probe' } : {}),
|
|
1475
|
+
...(authExpired ? { authExpired: true } : {}),
|
|
1476
|
+
message: errorMessage || 'MCP 连接和工具列表验证通过',
|
|
1477
|
+
server: connectorName,
|
|
1478
|
+
transport,
|
|
1479
|
+
endpoint: url || definition.command || '',
|
|
1480
|
+
status: !probe.error ? (probe.status || 200) : (authExpired ? 401 : probe.status),
|
|
1481
|
+
duration: Date.now() - started,
|
|
1482
|
+
...(Array.isArray(probe.tools) ? { toolsCount: probe.tools.length } : {}),
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
function connectorTemplateDefinition(pluginName, connectorName, payload = {}, pluginOwned = pluginName !== 'user-mcp') {
|
|
1487
|
+
const target = pluginOwned ? installedDir(pluginName) : ''
|
|
1488
|
+
const found = (pluginOwned && getPluginConnectors(target).find(c => c.name === connectorName)) || {}
|
|
1489
|
+
const transport = connectorTransport(payload.transport || payload.type || found.type, payload.url ?? found.url, payload.command ?? found.command)
|
|
1490
|
+
const headers = new Map()
|
|
1491
|
+
const headerSource = (payload?.headers && typeof payload.headers === 'object' && !Array.isArray(payload.headers))
|
|
1492
|
+
? payload.headers
|
|
1493
|
+
: Object.fromEntries(Object.entries(found.headers || {}).filter(([, value]) =>
|
|
1494
|
+
typeof value !== 'string' || !hasUnresolvedVarPlaceholder(value)))
|
|
1495
|
+
for (const [key, value] of Object.entries(headerSource)) {
|
|
1496
|
+
headers.set(key.toLowerCase(), [key, value])
|
|
1497
|
+
}
|
|
1498
|
+
const token = (typeof payload === 'string' ? payload : payload.token)?.trim()
|
|
1499
|
+
const oauth = transport === 'stdio' ? 'none' : (payload.oauth || 'none')
|
|
1500
|
+
if (token && !isOAuthMode(oauth) && !headers.has('authorization')) {
|
|
1501
|
+
headers.set('authorization', ['Authorization', token.startsWith('Bearer ') ? token : `Bearer ${token}`])
|
|
1502
|
+
}
|
|
1503
|
+
const rawCwd = payload.cwd !== undefined
|
|
1504
|
+
? (typeof payload.cwd === 'string' ? payload.cwd.trim() : '')
|
|
1505
|
+
: (found.cwd !== undefined ? String(found.cwd).trim() : undefined)
|
|
1506
|
+
return {
|
|
1507
|
+
transport,
|
|
1508
|
+
type: transport,
|
|
1509
|
+
url: transport === 'http' ? (payload.url ?? found.url ?? (connectorName === 'notion' ? 'https://mcp.notion.com/mcp' : null))?.trim() : null,
|
|
1510
|
+
command: payload.command ?? found.command ?? null,
|
|
1511
|
+
args: Array.isArray(payload.args) ? payload.args : (found.args || []),
|
|
1512
|
+
...(rawCwd !== undefined ? { cwd: rawCwd } : {}),
|
|
1513
|
+
env: stripSyntheticRuntimeEnv(connectorEnvironment(found, payload), pluginName, target),
|
|
1514
|
+
headers: Object.fromEntries(headers.values()),
|
|
1515
|
+
oauth,
|
|
1516
|
+
oauthClientId: String(payload.oauthClientId || '').trim(),
|
|
1517
|
+
oauthCallbackPort: payload.oauthCallbackPort,
|
|
1518
|
+
oauthScope: payload.oauthScope || '',
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
function connectorDefinition(pluginName, connectorName, payload = {}, pluginOwned = pluginName !== 'user-mcp') {
|
|
1523
|
+
const rawTpl = connectorTemplateDefinition(pluginName, connectorName, payload, pluginOwned)
|
|
1524
|
+
const target = pluginOwned ? installedDir(pluginName) : ''
|
|
1525
|
+
const dataDir = pluginOwned ? pluginDataDir(pluginName) : ''
|
|
1526
|
+
const resolved = substitutePluginRoot(rawTpl, target, dataDir)
|
|
1527
|
+
if (resolved.transport === 'stdio') {
|
|
1528
|
+
resolved.command = resolvePluginCommand(rawTpl.command, target, dataDir)
|
|
1529
|
+
const resolvedCwd = resolvePluginCwd(rawTpl.cwd, target, dataDir, {
|
|
1530
|
+
command: rawTpl.command,
|
|
1531
|
+
args: rawTpl.args,
|
|
1532
|
+
})
|
|
1533
|
+
if (resolvedCwd) resolved.cwd = resolvedCwd
|
|
1534
|
+
else delete resolved.cwd
|
|
1535
|
+
if (pluginOwned) resolved.env = pluginRuntimeEnv(pluginName, target, resolved.env, true)
|
|
1536
|
+
} else {
|
|
1537
|
+
delete resolved.cwd
|
|
1253
1538
|
}
|
|
1539
|
+
return resolved
|
|
1540
|
+
}
|
|
1254
1541
|
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
|
|
1265
|
-
}).finally(() => clearTimeout(timer))
|
|
1266
|
-
|
|
1267
|
-
const duration = Date.now() - startTime
|
|
1268
|
-
if (res.status === 200) {
|
|
1269
|
-
result = {
|
|
1270
|
-
ok: true,
|
|
1271
|
-
message: '验证成功!已连接到 MCP 远程服务并激活权限。',
|
|
1272
|
-
server: connectorName,
|
|
1273
|
-
transport: transport === 'sse' ? 'sse' : 'http',
|
|
1274
|
-
endpoint: url,
|
|
1275
|
-
status: 200,
|
|
1276
|
-
duration,
|
|
1277
|
-
}
|
|
1278
|
-
} else {
|
|
1279
|
-
const body = await res.json().catch(() => ({}))
|
|
1280
|
-
const desc = body.error_description || body.error?.message || body.error || `HTTP 错误状态码 ${res.status}`
|
|
1281
|
-
const authHeader = res.headers.get('www-authenticate') || ''
|
|
1282
|
-
let userFriendly = `认证未通过:${desc}`
|
|
1283
|
-
if ((res.status === 401 || res.status === 403) && !reqHeaders.Authorization && !/[?&](api_key|apiKey|token|key)=/i.test(url)) {
|
|
1284
|
-
if (authHeader.includes('Bearer') || authHeader.includes('oauth') || /token|oauth|unauthorized|access token/i.test(String(desc))) {
|
|
1285
|
-
userFriendly = `认证未通过:缺少访问令牌 (Access Token) 或需要 OAuth 授权`
|
|
1286
|
-
}
|
|
1287
|
-
}
|
|
1288
|
-
result = {
|
|
1289
|
-
ok: false,
|
|
1290
|
-
message: userFriendly,
|
|
1291
|
-
server: connectorName,
|
|
1292
|
-
transport: transport === 'sse' ? 'sse' : 'http',
|
|
1293
|
-
endpoint: url,
|
|
1294
|
-
status: res.status,
|
|
1295
|
-
errorDetails: String(desc),
|
|
1296
|
-
duration,
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
} catch (e) {
|
|
1300
|
-
const duration = Date.now() - startTime
|
|
1301
|
-
if (e.name === 'AbortError') {
|
|
1302
|
-
result = {
|
|
1303
|
-
ok: false,
|
|
1304
|
-
message: `连接超时(${MCP_AUTH_TIMEOUT_MS / 1000} 秒未响应),请检查服务 URL 与网络`,
|
|
1305
|
-
server: connectorName,
|
|
1306
|
-
transport,
|
|
1307
|
-
endpoint: url,
|
|
1308
|
-
errorDetails: `Connection timed out (${MCP_AUTH_TIMEOUT_MS / 1000}s limit)`,
|
|
1309
|
-
duration,
|
|
1310
|
-
}
|
|
1311
|
-
} else {
|
|
1312
|
-
result = {
|
|
1313
|
-
ok: false,
|
|
1314
|
-
message: `连接异常:${e.message}`,
|
|
1315
|
-
server: connectorName,
|
|
1316
|
-
transport,
|
|
1317
|
-
endpoint: url,
|
|
1318
|
-
errorDetails: e.message,
|
|
1319
|
-
duration,
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1542
|
+
function oauthConnectorRegistration(pluginName, connectorName, definition) {
|
|
1543
|
+
const { url, headers, oauth, oauthClientId, oauthCallbackPort, oauthScope } = definition
|
|
1544
|
+
const remote = oauthRuntimeConfig({
|
|
1545
|
+
url, headers, credentialKey: oauthCredentialKey(pluginName, connectorName, url, oauth),
|
|
1546
|
+
oauth: { mode: oauth, clientId: oauthClientId, callbackPort: Number(oauthCallbackPort) || null, scope: oauthScope },
|
|
1547
|
+
})
|
|
1548
|
+
return {
|
|
1549
|
+
type: 'stdio', command: process.execPath, args: [OAUTH_BRIDGE_PATH],
|
|
1550
|
+
env: bridgeRuntimeEnv({ UPH_MCP_REMOTE_CONFIG: encodeOAuthConfig(remote), UPH_OAUTH_STORE_DIR: oauthStoreDir() }),
|
|
1322
1551
|
}
|
|
1323
|
-
setRemoteVerification(pluginName, connectorName, { transport, url, headers: reqHeaders, oauth: payload?.oauth }, result.ok === true)
|
|
1324
|
-
return result
|
|
1325
1552
|
}
|
|
1326
1553
|
|
|
1327
|
-
|
|
1328
|
-
const target = installedDir(pluginName)
|
|
1329
|
-
const connectors = getPluginConnectors(target)
|
|
1330
|
-
const found = connectors.find((c) => c.name === connectorName) || { name: connectorName }
|
|
1554
|
+
const ACTIVE_PLUGIN_PROBES = new Map()
|
|
1331
1555
|
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
let
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1556
|
+
function trackPluginProbe(pluginName, connectorName, run) {
|
|
1557
|
+
if (!pluginName) return run(undefined)
|
|
1558
|
+
const controller = new AbortController()
|
|
1559
|
+
let probes = ACTIVE_PLUGIN_PROBES.get(pluginName)
|
|
1560
|
+
if (!probes) {
|
|
1561
|
+
probes = new Set()
|
|
1562
|
+
ACTIVE_PLUGIN_PROBES.set(pluginName, probes)
|
|
1563
|
+
}
|
|
1564
|
+
const entry = { connectorName, controller, settled: null }
|
|
1565
|
+
entry.settled = (async () => run(controller.signal))().finally(() => {
|
|
1566
|
+
probes.delete(entry)
|
|
1567
|
+
if (probes.size === 0 && ACTIVE_PLUGIN_PROBES.get(pluginName) === probes) {
|
|
1568
|
+
ACTIVE_PLUGIN_PROBES.delete(pluginName)
|
|
1569
|
+
}
|
|
1570
|
+
})
|
|
1571
|
+
probes.add(entry)
|
|
1572
|
+
return entry.settled
|
|
1573
|
+
}
|
|
1340
1574
|
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1575
|
+
export function cancelActivePluginProbes(pluginName, connectorName) {
|
|
1576
|
+
const probes = ACTIVE_PLUGIN_PROBES.get(pluginName)
|
|
1577
|
+
if (!probes || probes.size === 0) return []
|
|
1578
|
+
const batch = []
|
|
1579
|
+
for (const entry of probes) {
|
|
1580
|
+
if (!connectorName || entry.connectorName === connectorName) {
|
|
1581
|
+
entry.controller.abort()
|
|
1582
|
+
batch.push(entry.settled)
|
|
1583
|
+
}
|
|
1344
1584
|
}
|
|
1585
|
+
return batch
|
|
1586
|
+
}
|
|
1345
1587
|
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1588
|
+
async function abortPluginConnectorProbes(pluginName, connectorName) {
|
|
1589
|
+
// Background warm-up probes spawn stdio processes whose cwd may be inside the
|
|
1590
|
+
// plugin directory; abort and await process exit before removing or replacing it.
|
|
1591
|
+
while (true) {
|
|
1592
|
+
const batch = cancelActivePluginProbes(pluginName, connectorName)
|
|
1593
|
+
if (batch.length === 0) break
|
|
1594
|
+
await Promise.allSettled(batch)
|
|
1349
1595
|
}
|
|
1596
|
+
}
|
|
1350
1597
|
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
if (
|
|
1598
|
+
async function probeConnectorDefinition(pluginName, connectorName, definition, timeout) {
|
|
1599
|
+
return trackPluginProbe(pluginName, connectorName, (signal) => {
|
|
1600
|
+
if (definition.transport === 'stdio') {
|
|
1601
|
+
return definition.command
|
|
1602
|
+
? queryStdioToolsList(definition.command, definition.args, definition.env, { cwd: definition.cwd, signal })
|
|
1603
|
+
: { tools: [], error: '未配置有效的 stdio 启动命令 (command)' }
|
|
1604
|
+
}
|
|
1605
|
+
if (!/^https?:\/\//i.test(definition.url || '')) return { tools: [], error: '缺少有效的服务 URL' }
|
|
1606
|
+
if (isOAuthMode(definition.oauth)) {
|
|
1607
|
+
return queryOAuthHttpToolsList(pluginName, connectorName, definition, timeout, signal)
|
|
1608
|
+
}
|
|
1609
|
+
return queryHttpToolsList(definition.url, definition.headers, timeout, signal)
|
|
1610
|
+
})
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
export async function probeConnectorAuth(pluginName, connectorName, payload, { pluginOwned, definition: prebuiltDefinition } = {}) {
|
|
1614
|
+
const definition = prebuiltDefinition || connectorDefinition(pluginName, connectorName, payload, pluginOwned)
|
|
1615
|
+
if (definition.oauth === 'custom' && definition.url) {
|
|
1616
|
+
const key = oauthCredentialKey(pluginName, connectorName, definition.url, 'custom')
|
|
1617
|
+
const client = readOAuthRecord(key)?.customClient
|
|
1618
|
+
if (!client || client.client_id !== definition.oauthClientId ||
|
|
1619
|
+
(payload?.oauthClientSecret && client.client_secret !== payload.oauthClientSecret)) {
|
|
1620
|
+
return { ok: false, error: '请先点击「登录并连接」完成 OAuth 授权' }
|
|
1621
|
+
}
|
|
1354
1622
|
}
|
|
1623
|
+
const probe = await probeConnectorDefinition(pluginName, connectorName, definition, MCP_AUTH_TIMEOUT_MS)
|
|
1624
|
+
return { ...probe, definition, ok: !probe.error }
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
export function probeUserMcpUpdate(oldName, newName, payload) {
|
|
1628
|
+
// The editor may have just authorized the renamed draft. Otherwise an
|
|
1629
|
+
// unchanged sign-in still belongs to the existing name until rename commits.
|
|
1630
|
+
const newRecord = oldName !== newName && isOAuthMode(payload.oauth) && payload.url
|
|
1631
|
+
? readOAuthRecord(oauthCredentialKey('user-mcp', newName, payload.url.trim(), payload.oauth))
|
|
1632
|
+
: null
|
|
1633
|
+
return probeConnectorAuth('user-mcp', newRecord?.tokens ? newName : oldName, payload)
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
const MCP_ACTIVATIONS = new Map()
|
|
1637
|
+
|
|
1638
|
+
export async function enableConnector(pluginName, connectorName, payload, options = {}) {
|
|
1639
|
+
const key = `${pluginName}::${connectorName}`
|
|
1640
|
+
const attempt = Symbol()
|
|
1641
|
+
MCP_ACTIVATIONS.set(key, attempt)
|
|
1642
|
+
const input = payload ?? savedConnectorDefinition(pluginName, connectorName) ?? {}
|
|
1643
|
+
try {
|
|
1644
|
+
const definition = connectorDefinition(pluginName, connectorName, input, options.pluginOwned)
|
|
1645
|
+
const toolsState = readMcpToolsState()
|
|
1646
|
+
const savedState = toolsState[key]
|
|
1647
|
+
const hasCachedTools = savedState?.cachedToolsResolved === true
|
|
1648
|
+
|| (Array.isArray(savedState?.cachedTools) && savedState.cachedTools.length > 0)
|
|
1649
|
+
if (options.reuseStdioCache !== false && hasCachedTools && definition.transport === 'stdio') {
|
|
1650
|
+
const stdioMatch = savedState?.verifiedStdioConfig === stdioConfigFingerprint(definition)
|
|
1651
|
+
const hasCmd = Boolean(definition.command && resolveCommandPath(definition.command, process.env, definition.cwd ? { cwd: definition.cwd } : undefined))
|
|
1652
|
+
if (stdioMatch && hasCmd) {
|
|
1653
|
+
if (MCP_ACTIVATIONS.get(key) !== attempt || options.canEnable?.() === false) {
|
|
1654
|
+
return { ok: false, error: 'MCP 配置或开关已变更,请刷新后重试' }
|
|
1655
|
+
}
|
|
1656
|
+
return saveConnectorAuth(pluginName, connectorName, input, {
|
|
1657
|
+
...options,
|
|
1658
|
+
probe: { ok: true, tools: savedState.cachedTools || [], definition },
|
|
1659
|
+
})
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1355
1662
|
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1663
|
+
const probe = await probeConnectorAuth(pluginName, connectorName, input, { ...options, definition })
|
|
1664
|
+
if (MCP_ACTIVATIONS.get(key) !== attempt || options.canEnable?.() === false) {
|
|
1665
|
+
return { ok: false, error: 'MCP 配置或开关已变更,请刷新后重试' }
|
|
1666
|
+
}
|
|
1667
|
+
if (!probe.ok) {
|
|
1668
|
+
if (definition.transport === 'http' && (probe.status === 401 || probe.status === 403 || isOAuthExpiredError(probe.error))) {
|
|
1669
|
+
setRemoteVerification(pluginName, connectorName, definition, false)
|
|
1670
|
+
}
|
|
1671
|
+
return { ok: false, error: probe.error }
|
|
1672
|
+
}
|
|
1673
|
+
return saveConnectorAuth(pluginName, connectorName, input, { ...options, probe })
|
|
1674
|
+
} finally {
|
|
1675
|
+
if (MCP_ACTIVATIONS.get(key) === attempt) MCP_ACTIVATIONS.delete(key)
|
|
1366
1676
|
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
export function saveConnectorAuth(pluginName, connectorName, payload, { pluginOwned = pluginName !== 'user-mcp', rememberDefinition = true, probe } = {}) {
|
|
1680
|
+
const definition = probe?.definition || connectorDefinition(pluginName, connectorName, payload, pluginOwned)
|
|
1681
|
+
const { transport, url, oauth } = definition
|
|
1682
|
+
const isStdio = transport === 'stdio'
|
|
1683
|
+
let registration = definition
|
|
1367
1684
|
if (pluginOwned) {
|
|
1368
1685
|
const previousRemote = remoteConfigFromEntry(getConnectorEntry(pluginName, connectorName)?.config)
|
|
1369
1686
|
rememberPluginOAuthUrls(pluginName, connectorName, !isStdio && isOAuthMode(oauth) ? url : null, previousRemote?.url)
|
|
1370
1687
|
}
|
|
1371
1688
|
if (!isStdio && isOAuthMode(oauth)) {
|
|
1372
1689
|
saveCustomOAuthClient(pluginName, connectorName, payload)
|
|
1373
|
-
|
|
1374
|
-
const remote = oauthRuntimeConfig({
|
|
1375
|
-
url, headers: customHeaders, credentialKey,
|
|
1376
|
-
oauth: {
|
|
1377
|
-
mode: oauth, clientId: payload.oauthClientId || '', callbackPort: Number(payload.oauthCallbackPort) || null,
|
|
1378
|
-
scope: payload.oauthScope || '',
|
|
1379
|
-
},
|
|
1380
|
-
})
|
|
1381
|
-
registration = {
|
|
1382
|
-
type: 'stdio', command: process.execPath, args: [OAUTH_BRIDGE_PATH],
|
|
1383
|
-
env: { UPH_MCP_REMOTE_CONFIG: encodeOAuthConfig(remote), UPH_OAUTH_STORE_DIR: oauthStoreDir() },
|
|
1384
|
-
}
|
|
1690
|
+
registration = oauthConnectorRegistration(pluginName, connectorName, definition)
|
|
1385
1691
|
}
|
|
1386
1692
|
const result = registerConnector(pluginName, connectorName, registration)
|
|
1387
|
-
const toolsKey = `${pluginName}::${connectorName}`
|
|
1388
|
-
if (result.ok && !isStdio) {
|
|
1389
|
-
const verifiedConfig = { transport, url, headers: customHeaders, oauth, oauthClientId: payload.oauthClientId || '', oauthScope: payload.oauthScope || '', oauthCallbackPort: payload.oauthCallbackPort }
|
|
1390
|
-
const savedState = readMcpToolsState()
|
|
1391
|
-
savedState[toolsKey] = { ...(savedState[toolsKey] || {}), savedOAuthRemoteConfig: isOAuthMode(oauth) ? remoteConfigFromEntry(registration.env ? { env: registration.env } : {}) : undefined }
|
|
1392
|
-
if (!isOAuthMode(oauth)) delete savedState[toolsKey].savedOAuthRemoteConfig
|
|
1393
|
-
writeMcpToolsState(savedState)
|
|
1394
|
-
if (savedState[toolsKey]?.verifiedRemoteConfig !== remoteConfigFingerprint(verifiedConfig)) {
|
|
1395
|
-
setRemoteVerification(pluginName, connectorName, verifiedConfig, false)
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
1693
|
if (result.ok) {
|
|
1399
|
-
const
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1694
|
+
const key = `${pluginName}::${connectorName}`
|
|
1695
|
+
const state = readMcpToolsState()
|
|
1696
|
+
const prevEntryJson = state[key] ? JSON.stringify(state[key]) : null
|
|
1697
|
+
const saved = state[key] ||= {}
|
|
1698
|
+
if (pluginOwned && !isOAuthMode(oauth)) {
|
|
1699
|
+
if (rememberDefinition) {
|
|
1700
|
+
saved.savedConnectorDefinition = definition
|
|
1701
|
+
saved.savedConnectorTemplate = connectorTemplateDefinition(pluginName, connectorName, payload, pluginOwned)
|
|
1702
|
+
}
|
|
1703
|
+
saved.pluginConnectorOwned = true
|
|
1704
|
+
} else {
|
|
1705
|
+
delete saved.savedConnectorDefinition
|
|
1706
|
+
delete saved.savedConnectorTemplate
|
|
1707
|
+
}
|
|
1708
|
+
const remote = remoteConfigFromEntry(registration)
|
|
1709
|
+
if (remote) saved.savedOAuthRemoteConfig = remote
|
|
1710
|
+
else delete saved.savedOAuthRemoteConfig
|
|
1711
|
+
if (!isStdio) {
|
|
1712
|
+
delete saved.verifiedStdioConfig
|
|
1713
|
+
const fingerprint = remoteConfigFingerprint(remote || definition)
|
|
1714
|
+
if (probe?.ok) saved.verifiedRemoteConfig = fingerprint
|
|
1715
|
+
else if (saved.verifiedRemoteConfig !== fingerprint) saved.verifiedRemoteConfig = null
|
|
1716
|
+
} else {
|
|
1717
|
+
delete saved.verifiedRemoteConfig
|
|
1718
|
+
const stdioFingerprint = stdioConfigFingerprint(definition)
|
|
1719
|
+
if (probe?.ok) saved.verifiedStdioConfig = stdioFingerprint
|
|
1720
|
+
else if (saved.verifiedStdioConfig !== stdioFingerprint) saved.verifiedStdioConfig = null
|
|
1721
|
+
}
|
|
1722
|
+
if (probe?.ok) {
|
|
1723
|
+
saved.cachedTools = probe.tools
|
|
1724
|
+
saved.cachedToolsResolved = true
|
|
1725
|
+
} else {
|
|
1726
|
+
delete saved.cachedTools
|
|
1727
|
+
delete saved.cachedToolsResolved
|
|
1403
1728
|
}
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
MEMORY_TOOLS_CACHE.delete(toolsKey)
|
|
1729
|
+
if (JSON.stringify(saved) !== prevEntryJson) writeMcpToolsState(state)
|
|
1730
|
+
MEMORY_TOOLS_CACHE.delete(key)
|
|
1407
1731
|
// A probe still running against the old configuration must not be reused.
|
|
1408
|
-
MCP_TOOLS_INFLIGHT.delete(
|
|
1732
|
+
MCP_TOOLS_INFLIGHT.delete(key)
|
|
1409
1733
|
}
|
|
1410
1734
|
return result
|
|
1411
1735
|
}
|
|
1412
1736
|
|
|
1413
1737
|
/** MCP Tools Cache & State store */
|
|
1414
1738
|
const MCP_TOOLS_STATE_PATH = () => join(dshHome(), '.mcp-tools-state.json')
|
|
1739
|
+
let MCP_TOOLS_STATE_CACHE = null
|
|
1740
|
+
|
|
1741
|
+
function cloneMcpToolsEntry(v) {
|
|
1742
|
+
return v && typeof v === 'object' ? structuredClone(v) : v
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
function cloneMcpToolsState(state) {
|
|
1746
|
+
const out = {}
|
|
1747
|
+
for (const [k, v] of Object.entries(state || {})) {
|
|
1748
|
+
out[k] = cloneMcpToolsEntry(v)
|
|
1749
|
+
}
|
|
1750
|
+
return out
|
|
1751
|
+
}
|
|
1415
1752
|
|
|
1416
1753
|
export function readMcpToolsState() {
|
|
1417
1754
|
const file = MCP_TOOLS_STATE_PATH()
|
|
1418
|
-
|
|
1755
|
+
let stat
|
|
1756
|
+
try {
|
|
1757
|
+
stat = statSync(file)
|
|
1758
|
+
} catch {
|
|
1759
|
+
MCP_TOOLS_STATE_CACHE = null
|
|
1760
|
+
return {}
|
|
1761
|
+
}
|
|
1762
|
+
if (
|
|
1763
|
+
MCP_TOOLS_STATE_CACHE
|
|
1764
|
+
&& MCP_TOOLS_STATE_CACHE.file === file
|
|
1765
|
+
&& MCP_TOOLS_STATE_CACHE.mtimeMs === stat.mtimeMs
|
|
1766
|
+
&& MCP_TOOLS_STATE_CACHE.ctimeMs === stat.ctimeMs
|
|
1767
|
+
&& MCP_TOOLS_STATE_CACHE.size === stat.size
|
|
1768
|
+
) {
|
|
1769
|
+
return cloneMcpToolsState(MCP_TOOLS_STATE_CACHE.state)
|
|
1770
|
+
}
|
|
1419
1771
|
try {
|
|
1420
|
-
|
|
1772
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) || {}
|
|
1773
|
+
const cached = cloneMcpToolsState(parsed)
|
|
1774
|
+
MCP_TOOLS_STATE_CACHE = { file, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, size: stat.size, state: cached }
|
|
1775
|
+
return cloneMcpToolsState(cached)
|
|
1421
1776
|
} catch {
|
|
1777
|
+
MCP_TOOLS_STATE_CACHE = null
|
|
1422
1778
|
return {}
|
|
1423
1779
|
}
|
|
1424
1780
|
}
|
|
@@ -1427,7 +1783,14 @@ export function writeMcpToolsState(state, { required = false } = {}) {
|
|
|
1427
1783
|
try {
|
|
1428
1784
|
const file = MCP_TOOLS_STATE_PATH()
|
|
1429
1785
|
mkdirSync(dirname(file), { recursive: true })
|
|
1430
|
-
|
|
1786
|
+
const nextState = cloneMcpToolsState(state)
|
|
1787
|
+
writeFileSync(file, JSON.stringify(nextState), 'utf8')
|
|
1788
|
+
try {
|
|
1789
|
+
const stat = statSync(file)
|
|
1790
|
+
MCP_TOOLS_STATE_CACHE = { file, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, size: stat.size, state: nextState }
|
|
1791
|
+
} catch {
|
|
1792
|
+
MCP_TOOLS_STATE_CACHE = null
|
|
1793
|
+
}
|
|
1431
1794
|
} catch (error) {
|
|
1432
1795
|
if (required) throw error
|
|
1433
1796
|
}
|
|
@@ -1458,7 +1821,7 @@ export function getDisabledTools(pluginName, connectorName) {
|
|
|
1458
1821
|
export function setToolDisabled(pluginName, connectorName, toolName, disabled) {
|
|
1459
1822
|
const state = readMcpToolsState()
|
|
1460
1823
|
const key = `${pluginName}::${connectorName}`
|
|
1461
|
-
if (!state[key]) state[key] = {
|
|
1824
|
+
if (!state[key]) state[key] = {}
|
|
1462
1825
|
const list = new Set(Array.isArray(state[key].disabledTools) ? state[key].disabledTools : [])
|
|
1463
1826
|
if (disabled) {
|
|
1464
1827
|
list.add(toolName)
|
|
@@ -1468,149 +1831,225 @@ export function setToolDisabled(pluginName, connectorName, toolName, disabled) {
|
|
|
1468
1831
|
state[key].disabledTools = Array.from(list)
|
|
1469
1832
|
writeMcpToolsState(state)
|
|
1470
1833
|
|
|
1471
|
-
// Immediately synchronize in-memory cache
|
|
1472
|
-
if (MEMORY_TOOLS_CACHE.has(key)) {
|
|
1473
|
-
const mem = MEMORY_TOOLS_CACHE.get(key)
|
|
1474
|
-
MEMORY_TOOLS_CACHE.set(key, { ...mem, disabledTools: state[key].disabledTools })
|
|
1475
|
-
} else {
|
|
1476
|
-
MEMORY_TOOLS_CACHE.set(key, { tools: state[key].cachedTools || [], disabledTools: state[key].disabledTools })
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
1834
|
return state[key].disabledTools
|
|
1480
1835
|
}
|
|
1481
1836
|
|
|
1482
|
-
/**
|
|
1483
|
-
* Package-manager shims are the only commands that need a shell (Windows
|
|
1484
|
-
* resolves npx.cmd/npm.cmd through cmd.exe). Running everything through a
|
|
1485
|
-
* shell split unquoted paths at their spaces — "G:\...\computer use\server.js"
|
|
1486
|
-
* arrived at node as "G:\...\computer" — so the probe always failed.
|
|
1487
|
-
*/
|
|
1488
|
-
const SHELL_COMMANDS = /^(npx|npm|pnpm|pnpx|yarn|yarnpkg|bunx?|corepack)(\.cmd|\.bat)?$/i
|
|
1489
|
-
|
|
1490
|
-
function quoteArgForShell(value) {
|
|
1491
|
-
const s = String(value)
|
|
1492
|
-
return /[\s"&|<>^]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s
|
|
1493
|
-
}
|
|
1494
|
-
|
|
1495
|
-
/**
|
|
1496
|
-
* Query an MCP stdio server for its tool list.
|
|
1497
|
-
* Resolves { tools, error } — error stays null when the server answered with
|
|
1498
|
-
* an (possibly empty) tool list, so callers can tell "no tools" from "the
|
|
1499
|
-
* probe never reached the server".
|
|
1500
|
-
*/
|
|
1501
1837
|
const MCP_STARTUP_TIMEOUT_MS = 180000
|
|
1502
1838
|
const MCP_TOOLS_TIMEOUT_MS = 60000
|
|
1503
|
-
// A user-initiated connection test is not the same wait as a background probe.
|
|
1504
1839
|
const MCP_AUTH_TIMEOUT_MS = 8000
|
|
1505
|
-
// Keep only the tail: a chatty server during a 180s startup window would
|
|
1506
|
-
// otherwise grow this string without bound (and `+=` copies it each time).
|
|
1507
1840
|
const STDERR_TAIL_BYTES = 8192
|
|
1508
1841
|
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1842
|
+
/** Use the same MCP transport as DSH, including Windows command shim resolution. */
|
|
1843
|
+
export async function queryStdioToolsList(cmd, args, extraEnv = {}, options = {}) {
|
|
1844
|
+
const externalSignal = options?.signal
|
|
1845
|
+
if (externalSignal?.aborted) {
|
|
1846
|
+
return { tools: [], error: 'MCP 探测已取消' }
|
|
1847
|
+
}
|
|
1848
|
+
// Windows treats env names case-insensitively. Normalize before merging so
|
|
1849
|
+
// an explicit Path/PATH overrides both the parent and the SDK default.
|
|
1850
|
+
const env = process.platform === 'win32'
|
|
1851
|
+
? Object.fromEntries([...Object.entries(process.env), ...Object.entries(extraEnv)].map(([key, value]) => [key.toUpperCase(), value]))
|
|
1852
|
+
: { ...process.env, ...extraEnv }
|
|
1853
|
+
const transport = new StdioClientTransport({
|
|
1854
|
+
command: cmd,
|
|
1855
|
+
args: Array.isArray(args) ? args : [],
|
|
1856
|
+
env,
|
|
1857
|
+
...(options?.cwd ? { cwd: options.cwd } : {}),
|
|
1858
|
+
stderr: 'pipe',
|
|
1859
|
+
})
|
|
1860
|
+
const client = new Client({ name: 'universal-plugin-hub', version: '1.0.0' })
|
|
1861
|
+
// The SDK starts cleanup itself if initialization fails. Wait for the same
|
|
1862
|
+
// close operation in finally before returning the probe result.
|
|
1863
|
+
const close = transport.close.bind(transport)
|
|
1864
|
+
let closing
|
|
1865
|
+
transport.close = () => closing ??= close()
|
|
1866
|
+
|
|
1867
|
+
let stderr = ''
|
|
1868
|
+
transport.stderr?.setEncoding('utf8').on('data', (chunk) => {
|
|
1869
|
+
stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES)
|
|
1870
|
+
})
|
|
1871
|
+
const onAbort = () => { void transport.close().catch(() => {}) }
|
|
1872
|
+
externalSignal?.addEventListener('abort', onAbort, { once: true })
|
|
1873
|
+
const combineSignal = (timeoutSignal) => (externalSignal ? AbortSignal.any([timeoutSignal, externalSignal]) : timeoutSignal)
|
|
1874
|
+
|
|
1875
|
+
let phase = '启动'
|
|
1876
|
+
let timeout = MCP_STARTUP_TIMEOUT_MS
|
|
1877
|
+
let timeoutSignal = AbortSignal.timeout(timeout)
|
|
1878
|
+
let signal = combineSignal(timeoutSignal)
|
|
1879
|
+
try {
|
|
1880
|
+
await client.connect(transport, { timeout, signal })
|
|
1881
|
+
phase = '工具解析'
|
|
1882
|
+
timeout = MCP_TOOLS_TIMEOUT_MS
|
|
1883
|
+
timeoutSignal = AbortSignal.timeout(timeout)
|
|
1884
|
+
signal = combineSignal(timeoutSignal)
|
|
1885
|
+
return { tools: await listMcpTools(client, { timeout, signal }), error: null }
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
const message = error?.message || String(error)
|
|
1888
|
+
const detail = stderr.trim().split('\n').filter(Boolean).slice(-2).join(' ')
|
|
1889
|
+
const reason = externalSignal?.aborted
|
|
1890
|
+
? 'MCP 探测已取消'
|
|
1891
|
+
: timeoutSignal.aborted || error?.code === ErrorCode.RequestTimeout
|
|
1892
|
+
? `MCP ${phase}超时(${timeout / 1000} 秒)`
|
|
1893
|
+
: phase === '启动' ? `无法启动 ${cmd}: ${message}` : message
|
|
1894
|
+
return { tools: [], error: detail ? `${reason}:${detail}` : reason }
|
|
1895
|
+
} finally {
|
|
1896
|
+
externalSignal?.removeEventListener('abort', onAbort)
|
|
1897
|
+
await transport.close()
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
async function listMcpTools(client, options) {
|
|
1902
|
+
const tools = []
|
|
1903
|
+
if (!client.getServerCapabilities()?.tools) return tools
|
|
1904
|
+
const cursors = new Set()
|
|
1905
|
+
let cursor
|
|
1906
|
+
do {
|
|
1907
|
+
const result = await client.listTools(cursor === undefined ? undefined : { cursor }, options)
|
|
1908
|
+
tools.push(...result.tools)
|
|
1909
|
+
cursor = result.nextCursor
|
|
1910
|
+
if (cursor === undefined) return tools
|
|
1911
|
+
if (cursors.has(cursor)) throw new Error('MCP 服务返回了重复的工具分页游标')
|
|
1912
|
+
cursors.add(cursor)
|
|
1913
|
+
} while (true)
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
async function connectHttpAndFetchTools(
|
|
1917
|
+
url,
|
|
1918
|
+
{ headers, authProvider } = {},
|
|
1919
|
+
timeout = MCP_TOOLS_TIMEOUT_MS,
|
|
1920
|
+
externalSignal,
|
|
1921
|
+
) {
|
|
1922
|
+
if (externalSignal?.aborted) return { tools: [], error: 'MCP 探测已取消' }
|
|
1923
|
+
const timeoutSignal = AbortSignal.timeout(timeout)
|
|
1924
|
+
const signal = externalSignal ? AbortSignal.any([timeoutSignal, externalSignal]) : timeoutSignal
|
|
1925
|
+
let transport
|
|
1926
|
+
try {
|
|
1927
|
+
transport = new StreamableHTTPClientTransport(new URL(url), {
|
|
1928
|
+
requestInit: { headers: headers || {} },
|
|
1929
|
+
...(authProvider ? { authProvider } : {}),
|
|
1930
|
+
fetch: (input, init) => fetch(input, {
|
|
1931
|
+
...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal,
|
|
1932
|
+
}),
|
|
1583
1933
|
})
|
|
1934
|
+
const client = new Client({ name: 'universal-plugin-hub', version: '1.0.0' })
|
|
1935
|
+
await client.connect(transport, { timeout, signal })
|
|
1936
|
+
const tools = await listMcpTools(client, { timeout, signal })
|
|
1937
|
+
return { tools, error: null, status: 200 }
|
|
1938
|
+
} catch (error) {
|
|
1939
|
+
const status = Number.isInteger(error?.code) && error.code >= 400 && error.code <= 599 ? error.code : undefined
|
|
1940
|
+
const message = externalSignal?.aborted
|
|
1941
|
+
? 'MCP 探测已取消'
|
|
1942
|
+
: timeoutSignal.aborted || error?.code === ErrorCode.RequestTimeout || error?.name === 'TimeoutError'
|
|
1943
|
+
? `连接或解析 MCP 工具超时(${timeout / 1000} 秒)`
|
|
1944
|
+
: error?.oauthAuthRequired
|
|
1945
|
+
? error.message
|
|
1946
|
+
: status === 401 || status === 403 ? `MCP 服务返回 HTTP ${status},请检查 Headers 或 OAuth 授权`
|
|
1947
|
+
: status ? `MCP 服务返回 HTTP ${status}`
|
|
1948
|
+
: `连接或解析 MCP 工具失败:${error.message}`
|
|
1949
|
+
return { tools: [], error: message, status }
|
|
1950
|
+
} finally {
|
|
1951
|
+
if (transport?.sessionId && !signal.aborted) await transport.terminateSession().catch(() => {})
|
|
1952
|
+
await transport?.close().catch(() => {})
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1584
1955
|
|
|
1585
|
-
|
|
1586
|
-
|
|
1956
|
+
async function queryHttpToolsList(url, headers, timeout = MCP_TOOLS_TIMEOUT_MS, externalSignal) {
|
|
1957
|
+
return connectHttpAndFetchTools(url, { headers }, timeout, externalSignal)
|
|
1958
|
+
}
|
|
1587
1959
|
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1960
|
+
function createNonInteractiveOAuthProvider(remote, recordState) {
|
|
1961
|
+
const persist = (mutator) => {
|
|
1962
|
+
const next = { ...recordState.record }
|
|
1963
|
+
if (!mutator(next)) return
|
|
1964
|
+
recordState.record = next
|
|
1965
|
+
recordState.writer?.write(next)
|
|
1966
|
+
}
|
|
1967
|
+
const hasSecret = Boolean(recordState.record?.customClient?.client_secret)
|
|
1968
|
+
const callback = recordState.record?.clientInformation?.redirect_uris?.[0]
|
|
1969
|
+
|| `http://localhost:${Number(remote.oauth?.callbackPort) || 0}/callback`
|
|
1970
|
+
const clientMetadata = {
|
|
1971
|
+
client_name: 'DeepSeek Harness',
|
|
1972
|
+
client_uri: 'https://www.deepseek.com/harness/',
|
|
1973
|
+
redirect_uris: [callback],
|
|
1974
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
1975
|
+
response_types: ['code'],
|
|
1976
|
+
token_endpoint_auth_method: hasSecret ? 'client_secret_post' : 'none',
|
|
1977
|
+
...(remote.oauth?.scope ? { scope: remote.oauth.scope } : {}),
|
|
1978
|
+
}
|
|
1979
|
+
const authError = () => Object.assign(new Error('OAuth 授权已失效或尚未完成,请重新进行 OAuth 授权'), { oauthAuthRequired: true })
|
|
1980
|
+
return {
|
|
1981
|
+
get redirectUrl() { return callback },
|
|
1982
|
+
get clientMetadata() { return clientMetadata },
|
|
1983
|
+
clientInformation() {
|
|
1984
|
+
const rec = recordState.record
|
|
1985
|
+
if (remote.oauth?.mode === 'custom') {
|
|
1986
|
+
const clientId = remote.oauth.clientId || rec?.customClient?.client_id
|
|
1987
|
+
if (!clientId) return undefined
|
|
1988
|
+
return rec?.clientInformation?.client_id === clientId
|
|
1989
|
+
? { ...rec.clientInformation, ...rec.customClient, client_id: clientId }
|
|
1990
|
+
: { ...rec?.customClient, client_id: clientId }
|
|
1592
1991
|
}
|
|
1593
|
-
|
|
1992
|
+
return rec?.clientInformation
|
|
1993
|
+
},
|
|
1994
|
+
saveClientInformation(info) {
|
|
1995
|
+
if (JSON.stringify(recordState.record?.clientInformation) === JSON.stringify(info)) return
|
|
1996
|
+
persist((next) => { next.clientInformation = info; return true })
|
|
1997
|
+
},
|
|
1998
|
+
tokens() { return recordState.record?.tokens },
|
|
1999
|
+
saveTokens(tokens) {
|
|
2000
|
+
if (JSON.stringify(recordState.record?.tokens) === JSON.stringify(tokens)) return
|
|
2001
|
+
persist((next) => { next.tokens = tokens; return true })
|
|
2002
|
+
},
|
|
2003
|
+
codeVerifier() { return recordState.record?.codeVerifier || '' },
|
|
2004
|
+
saveCodeVerifier(codeVerifier) {
|
|
2005
|
+
persist((next) => { next.codeVerifier = codeVerifier; return true })
|
|
2006
|
+
},
|
|
2007
|
+
discoveryState() { return recordState.record?.discovery },
|
|
2008
|
+
saveDiscoveryState(discovery) {
|
|
2009
|
+
if (JSON.stringify(recordState.record?.discovery) === JSON.stringify(discovery)) return
|
|
2010
|
+
persist((next) => { next.discovery = discovery; return true })
|
|
2011
|
+
},
|
|
2012
|
+
invalidateCredentials(scope) {
|
|
2013
|
+
persist((next) => {
|
|
2014
|
+
let changed = false
|
|
2015
|
+
if ((scope === 'all' || scope === 'tokens') && 'tokens' in next) { delete next.tokens; changed = true }
|
|
2016
|
+
if ((scope === 'all' || scope === 'client') && 'clientInformation' in next) { delete next.clientInformation; changed = true }
|
|
2017
|
+
if ((scope === 'all' || scope === 'client' || scope === 'discovery') && 'discovery' in next) { delete next.discovery; changed = true }
|
|
2018
|
+
if ((scope === 'all' || scope === 'verifier') && 'codeVerifier' in next) { delete next.codeVerifier; changed = true }
|
|
2019
|
+
return changed
|
|
2020
|
+
})
|
|
2021
|
+
},
|
|
2022
|
+
redirectToAuthorization() {
|
|
2023
|
+
throw authError()
|
|
2024
|
+
},
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
1594
2027
|
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
const toolsReq = JSON.stringify({
|
|
1603
|
-
jsonrpc: '2.0',
|
|
1604
|
-
id: 1,
|
|
1605
|
-
method: 'tools/list',
|
|
1606
|
-
params: {}
|
|
1607
|
-
}) + '\n'
|
|
1608
|
-
|
|
1609
|
-
armTimeout(MCP_STARTUP_TIMEOUT_MS, '启动')
|
|
1610
|
-
try {
|
|
1611
|
-
cp.stdin.write(initReq)
|
|
1612
|
-
} catch (err) { finish([], err.message) }
|
|
2028
|
+
async function queryOAuthHttpToolsList(pluginName, connectorName, definition, timeout = MCP_TOOLS_TIMEOUT_MS, externalSignal) {
|
|
2029
|
+
const { url, headers, oauth, oauthClientId, oauthCallbackPort, oauthScope } = definition
|
|
2030
|
+
const remote = oauthRuntimeConfig({
|
|
2031
|
+
url,
|
|
2032
|
+
headers,
|
|
2033
|
+
credentialKey: oauthCredentialKey(pluginName, connectorName, url, oauth),
|
|
2034
|
+
oauth: { mode: oauth, clientId: oauthClientId, callbackPort: Number(oauthCallbackPort) || null, scope: oauthScope },
|
|
1613
2035
|
})
|
|
2036
|
+
const writer = openOAuthRecordWriter(remote.credentialKey)
|
|
2037
|
+
const initial = readOAuthRecord(remote.credentialKey)
|
|
2038
|
+
if (!writer || (!initial?.tokens?.access_token && !initial?.tokens?.refresh_token)) {
|
|
2039
|
+
writer?.close()
|
|
2040
|
+
return { tools: [], error: 'OAuth 授权已失效或尚未完成,请重新进行 OAuth 授权', status: undefined }
|
|
2041
|
+
}
|
|
2042
|
+
const recordState = { record: { ...initial }, writer }
|
|
2043
|
+
try {
|
|
2044
|
+
return await connectHttpAndFetchTools(
|
|
2045
|
+
remote.url,
|
|
2046
|
+
{ headers: remote.headers, authProvider: createNonInteractiveOAuthProvider(remote, recordState) },
|
|
2047
|
+
timeout,
|
|
2048
|
+
externalSignal,
|
|
2049
|
+
)
|
|
2050
|
+
} finally {
|
|
2051
|
+
writer.close()
|
|
2052
|
+
}
|
|
1614
2053
|
}
|
|
1615
2054
|
|
|
1616
2055
|
const MEMORY_TOOLS_CACHE = new Map()
|
|
@@ -1623,21 +2062,23 @@ export async function fetchConnectorTools(pluginName, connectorName, forceFresh
|
|
|
1623
2062
|
// probe's stale answer (e.g. right after the user fixed a bad URL).
|
|
1624
2063
|
if (inflight && !(forceFresh && !inflight.forceFresh)) return inflight.promise
|
|
1625
2064
|
const entry = { forceFresh, promise: null }
|
|
1626
|
-
entry.promise = discoverConnectorTools(pluginName, connectorName, forceFresh)
|
|
2065
|
+
entry.promise = discoverConnectorTools(pluginName, connectorName, forceFresh, () => MCP_TOOLS_INFLIGHT.get(key) === entry)
|
|
1627
2066
|
MCP_TOOLS_INFLIGHT.set(key, entry)
|
|
1628
2067
|
try {
|
|
1629
2068
|
const result = await entry.promise
|
|
1630
2069
|
// A failure is transient; remembering it with no expiry pinned the UI to
|
|
1631
2070
|
// "解析失败" until the process restarted.
|
|
1632
|
-
if (
|
|
1633
|
-
|
|
2071
|
+
if (MCP_TOOLS_INFLIGHT.get(key) === entry) {
|
|
2072
|
+
if (result.ok === false || result.stale) MEMORY_TOOLS_CACHE.delete(key)
|
|
2073
|
+
else MEMORY_TOOLS_CACHE.set(key, { tools: result.tools || [], ok: result.ok, message: result.message })
|
|
2074
|
+
}
|
|
1634
2075
|
return result
|
|
1635
2076
|
} finally {
|
|
1636
2077
|
if (MCP_TOOLS_INFLIGHT.get(key) === entry) MCP_TOOLS_INFLIGHT.delete(key)
|
|
1637
2078
|
}
|
|
1638
2079
|
}
|
|
1639
2080
|
|
|
1640
|
-
async function discoverConnectorTools(pluginName, connectorName, forceFresh
|
|
2081
|
+
async function discoverConnectorTools(pluginName, connectorName, forceFresh, isCurrent) {
|
|
1641
2082
|
const key = `${pluginName}::${connectorName}`
|
|
1642
2083
|
const state = readMcpToolsState()
|
|
1643
2084
|
const disabledTools = Array.isArray(state[key]?.disabledTools) ? state[key].disabledTools : []
|
|
@@ -1647,112 +2088,38 @@ async function discoverConnectorTools(pluginName, connectorName, forceFresh = fa
|
|
|
1647
2088
|
return { ok: mem.ok !== false, tools: mem.tools || [], disabledTools, ...(mem.message ? { message: mem.message } : {}) }
|
|
1648
2089
|
}
|
|
1649
2090
|
|
|
1650
|
-
const target = installedDir(pluginName)
|
|
1651
|
-
const connectors = existsSync(target) ? getPluginConnectors(target) : []
|
|
1652
|
-
const found = connectors.find((c) => c.name === connectorName)
|
|
1653
2091
|
const entry = getConnectorEntry(pluginName, connectorName)
|
|
1654
|
-
const entryCfg = entry?.config || {}
|
|
1655
|
-
|
|
1656
2092
|
const cached = state[key]?.cachedTools || []
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
if (
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
const
|
|
1665
|
-
const
|
|
1666
|
-
|
|
1667
|
-
const
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
if (transport
|
|
1678
|
-
|
|
1679
|
-
const timer = setTimeout(() => controller.abort(), MCP_TOOLS_TIMEOUT_MS)
|
|
1680
|
-
try {
|
|
1681
|
-
const res = await fetch(url, {
|
|
1682
|
-
method: 'POST',
|
|
1683
|
-
headers: {
|
|
1684
|
-
'Content-Type': 'application/json',
|
|
1685
|
-
...headers,
|
|
1686
|
-
},
|
|
1687
|
-
signal: controller.signal,
|
|
1688
|
-
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
|
|
1689
|
-
})
|
|
1690
|
-
|
|
1691
|
-
if (res.status === 200) {
|
|
1692
|
-
const text = await res.text()
|
|
1693
|
-
let tools = null
|
|
1694
|
-
try {
|
|
1695
|
-
const data = JSON.parse(text)
|
|
1696
|
-
if (Array.isArray(data.result?.tools)) tools = data.result.tools
|
|
1697
|
-
else if (data.error) probeError = data.error.message || 'MCP 工具解析失败'
|
|
1698
|
-
} catch {
|
|
1699
|
-
const lines = text.split('\n')
|
|
1700
|
-
for (const line of lines) {
|
|
1701
|
-
if (line.startsWith('data:')) {
|
|
1702
|
-
try {
|
|
1703
|
-
const data = JSON.parse(line.slice(5).trim())
|
|
1704
|
-
if (Array.isArray(data.result?.tools)) {
|
|
1705
|
-
tools = data.result.tools
|
|
1706
|
-
break
|
|
1707
|
-
}
|
|
1708
|
-
} catch {}
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
|
|
1713
|
-
if (tools) {
|
|
1714
|
-
cacheConnectorTools(key, tools)
|
|
1715
|
-
return { ok: true, tools, disabledTools }
|
|
1716
|
-
}
|
|
1717
|
-
probeError ||= 'MCP 响应中未包含有效的工具列表'
|
|
1718
|
-
} else {
|
|
1719
|
-
probeError = `MCP 服务返回 HTTP ${res.status}`
|
|
1720
|
-
}
|
|
1721
|
-
} catch (err) {
|
|
1722
|
-
probeError = controller.signal.aborted ? `MCP 工具解析超时(${MCP_TOOLS_TIMEOUT_MS / 1000} 秒)` : `连接 MCP 服务失败: ${err.message}`
|
|
1723
|
-
} finally { clearTimeout(timer) }
|
|
1724
|
-
}
|
|
1725
|
-
|
|
1726
|
-
// 2. Stdio fetch
|
|
1727
|
-
if (transport === 'stdio') {
|
|
1728
|
-
const cmd = entryCfg.command || found?.command
|
|
1729
|
-
const args = entryCfg.args || found?.args || []
|
|
1730
|
-
if (cmd) {
|
|
1731
|
-
try {
|
|
1732
|
-
const probe = await queryStdioToolsList(cmd, args, entryCfg.env || found?.env || {})
|
|
1733
|
-
if (probe.tools.length > 0 || !probe.error) {
|
|
1734
|
-
cacheConnectorTools(key, probe.tools)
|
|
1735
|
-
return { ok: true, tools: probe.tools, disabledTools }
|
|
1736
|
-
}
|
|
1737
|
-
probeError = probe.error
|
|
1738
|
-
} catch (err) {
|
|
1739
|
-
probeError = err.message
|
|
1740
|
-
}
|
|
1741
|
-
} else {
|
|
1742
|
-
probeError = '该 MCP 服务没有配置启动命令'
|
|
1743
|
-
}
|
|
2093
|
+
const hasCachedTools = cached.length > 0 || state[key]?.cachedToolsResolved === true
|
|
2094
|
+
const inactiveStandalone = pluginName === 'user-mcp' && !entry
|
|
2095
|
+
if (hasCachedTools && (!forceFresh || inactiveStandalone)) return { ok: true, tools: cached, disabledTools }
|
|
2096
|
+
if (inactiveStandalone) return { ok: false, tools: [], disabledTools, message: 'MCP 服务未启用' }
|
|
2097
|
+
|
|
2098
|
+
const definition = connectorDefinition(pluginName, connectorName,
|
|
2099
|
+
entry ? { ...entry.config, ...remoteConfigFromEntry(entry.config) } : savedConnectorDefinition(pluginName, connectorName))
|
|
2100
|
+
const probe = await probeConnectorDefinition(pluginName, connectorName, definition)
|
|
2101
|
+
const probeError = probe.error
|
|
2102
|
+
// A response from the previous registration must not replace the current cache.
|
|
2103
|
+
const sameRegistration = isCurrent() && JSON.stringify(getConnectorEntry(pluginName, connectorName)) === JSON.stringify(entry)
|
|
2104
|
+
if (!probeError) {
|
|
2105
|
+
if (sameRegistration) {
|
|
2106
|
+
cacheConnectorTools(key, probe.tools)
|
|
2107
|
+
if (entry && definition.transport === 'http') setRemoteVerification(pluginName, connectorName, definition, true)
|
|
2108
|
+
}
|
|
2109
|
+
return { ok: true, tools: probe.tools, disabledTools }
|
|
2110
|
+
}
|
|
2111
|
+
const authFailure = probe.status === 401 || probe.status === 403 || probe.statusCode === 401 || probe.statusCode === 403
|
|
2112
|
+
|| isOAuthExpiredError(probe.error) || /\bHTTP 403\b/i.test(String(probe.error || ''))
|
|
2113
|
+
if (entry && definition.transport === 'http' && sameRegistration && authFailure) {
|
|
2114
|
+
setRemoteVerification(pluginName, connectorName, definition, false)
|
|
1744
2115
|
}
|
|
1745
2116
|
|
|
1746
2117
|
// A probe that never reached the server is an error, not an empty tool list;
|
|
1747
2118
|
// reporting ok:true with an empty list made the UI claim the server exposes
|
|
1748
2119
|
// no tools. A cached list is different: it is still usable, and surfacing it
|
|
1749
2120
|
// as an error replaced the whole row (and its toggles) with a failure notice.
|
|
1750
|
-
if (
|
|
1751
|
-
|
|
1752
|
-
return { ok: false, tools: [], disabledTools, message: probeError }
|
|
1753
|
-
}
|
|
1754
|
-
|
|
1755
|
-
return { ok: true, tools: [], disabledTools }
|
|
2121
|
+
if (hasCachedTools) return { ok: true, stale: true, tools: cached, disabledTools, message: probeError }
|
|
2122
|
+
return { ok: false, tools: [], disabledTools, message: probeError }
|
|
1756
2123
|
}
|
|
1757
2124
|
|
|
1758
2125
|
function cacheConnectorTools(key, tools) {
|
|
@@ -1762,14 +2129,22 @@ function cacheConnectorTools(key, tools) {
|
|
|
1762
2129
|
const owner = key.slice(0, key.indexOf('::'))
|
|
1763
2130
|
if (owner !== 'user-mcp' && !readState().plugins.some((p) => p.name === owner)) return
|
|
1764
2131
|
const state = readMcpToolsState()
|
|
1765
|
-
state[key] = { ...state[key], cachedTools: tools }
|
|
2132
|
+
state[key] = { ...state[key], cachedTools: tools, cachedToolsResolved: true }
|
|
1766
2133
|
writeMcpToolsState(state)
|
|
1767
2134
|
MEMORY_TOOLS_CACHE.set(key, { tools })
|
|
1768
2135
|
}
|
|
1769
2136
|
|
|
1770
|
-
function warmInstalledConnectorTools(pluginName, connectors) {
|
|
2137
|
+
function warmInstalledConnectorTools(pluginName, connectors, record, epoch = currentPluginEpoch(pluginName)) {
|
|
2138
|
+
const canEnable = () => currentPluginEpoch(pluginName) === epoch && readState().plugins.some(item =>
|
|
2139
|
+
item.name === pluginName && item.sourceId === record.sourceId && item.installedAt === record.installedAt && item.enabled !== false)
|
|
1771
2140
|
for (const connector of connectors) {
|
|
1772
|
-
|
|
2141
|
+
const entry = getConnectorEntry(pluginName, connector.name)
|
|
2142
|
+
const saved = readMcpToolsState()[`${pluginName}::${connector.name}`]
|
|
2143
|
+
if (!connectorRequiresAuth(connector) && !saved?.savedConnectorDefinition && !saved?.savedConnectorTemplate && !saved?.savedOAuthRemoteConfig) {
|
|
2144
|
+
// Installation stays responsive. DSH watches the profile patch and loads
|
|
2145
|
+
// the connector once its background probe succeeds.
|
|
2146
|
+
void enableConnector(pluginName, connector.name, connector, { pluginOwned: true, rememberDefinition: false, reuseStdioCache: false, canEnable }).catch(() => {})
|
|
2147
|
+
} else if (entry) {
|
|
1773
2148
|
void fetchConnectorTools(pluginName, connector.name, true).catch(() => {})
|
|
1774
2149
|
}
|
|
1775
2150
|
}
|
|
@@ -1823,19 +2198,33 @@ export async function syncPluginSkillsToDsh(pluginName, shouldSync = () => true,
|
|
|
1823
2198
|
const dshSkills = dshSkillsDir()
|
|
1824
2199
|
mkdirSync(dshSkills, { recursive: true })
|
|
1825
2200
|
|
|
1826
|
-
const
|
|
2201
|
+
const keepExisting = path => !shouldSync() || isUploadedSkillTarget(path)
|
|
2202
|
+
const candidates = []
|
|
1827
2203
|
for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
|
|
1828
2204
|
if (!entry.isDirectory()) continue
|
|
1829
2205
|
const srcSkillDir = join(pluginSkillsDir, entry.name)
|
|
1830
2206
|
if (!existsSync(join(srcSkillDir, 'SKILL.md'))) continue
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
2207
|
+
candidates.push({ name: entry.name, srcSkillDir, destSkillDir: join(dshSkills, entry.name) })
|
|
2208
|
+
}
|
|
2209
|
+
|
|
2210
|
+
const synced = []
|
|
2211
|
+
if (repairOnly) {
|
|
2212
|
+
for (const item of candidates) {
|
|
2213
|
+
if (await replaceManagedDir(item.srcSkillDir, item.destSkillDir, keepExisting, true, { allowTrash: true })) {
|
|
2214
|
+
synced.push(item.name)
|
|
2215
|
+
}
|
|
2216
|
+
await yieldToHost()
|
|
1836
2217
|
}
|
|
1837
|
-
|
|
2218
|
+
return synced
|
|
1838
2219
|
}
|
|
2220
|
+
|
|
2221
|
+
const settled = await Promise.allSettled(candidates.map(async (item) => {
|
|
2222
|
+
if (await replaceManagedDir(item.srcSkillDir, item.destSkillDir, keepExisting, false, { allowTrash: true })) {
|
|
2223
|
+
synced.push(item.name)
|
|
2224
|
+
}
|
|
2225
|
+
}))
|
|
2226
|
+
const rejected = settled.find((item) => item.status === 'rejected')
|
|
2227
|
+
if (rejected) throw rejected.reason
|
|
1839
2228
|
return synced
|
|
1840
2229
|
}
|
|
1841
2230
|
|
|
@@ -1860,6 +2249,51 @@ function hasMatchingSkillCopy(source, destination) {
|
|
|
1860
2249
|
}
|
|
1861
2250
|
}
|
|
1862
2251
|
|
|
2252
|
+
const PLUGIN_LOCKS = new Map()
|
|
2253
|
+
const SOURCE_LOCKS = new Map()
|
|
2254
|
+
const PLUGIN_EPOCHS = new Map()
|
|
2255
|
+
|
|
2256
|
+
function currentPluginEpoch(pluginName) {
|
|
2257
|
+
return PLUGIN_EPOCHS.get(pluginName) || 0
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
function bumpPluginEpoch(pluginName) {
|
|
2261
|
+
const next = currentPluginEpoch(pluginName) + 1
|
|
2262
|
+
PLUGIN_EPOCHS.set(pluginName, next)
|
|
2263
|
+
return next
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
async function acquireKeyedLock(locks, key, fn) {
|
|
2267
|
+
if (!key) return fn()
|
|
2268
|
+
const prior = locks.get(key)
|
|
2269
|
+
let release
|
|
2270
|
+
const current = new Promise((resolve) => { release = resolve })
|
|
2271
|
+
locks.set(key, current)
|
|
2272
|
+
try {
|
|
2273
|
+
if (prior) await prior
|
|
2274
|
+
return await fn()
|
|
2275
|
+
} finally {
|
|
2276
|
+
if (locks.get(key) === current) locks.delete(key)
|
|
2277
|
+
release()
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
/**
|
|
2282
|
+
* Serialize lifecycle operations on the same plugin while running immediately
|
|
2283
|
+
* when the lock is idle so startup repair reaches its first fs attempt synchronously.
|
|
2284
|
+
*/
|
|
2285
|
+
export function withPluginLock(pluginName, fn) {
|
|
2286
|
+
return acquireKeyedLock(PLUGIN_LOCKS, pluginName, fn)
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
/**
|
|
2290
|
+
* Serialize source-level mutations (clone, refresh, uninstall-source, install/update).
|
|
2291
|
+
* Always acquire after withPluginLock when both locks are required.
|
|
2292
|
+
*/
|
|
2293
|
+
export function withSourceLock(sourceId, fn) {
|
|
2294
|
+
return acquireKeyedLock(SOURCE_LOCKS, sourceId, fn)
|
|
2295
|
+
}
|
|
2296
|
+
|
|
1863
2297
|
async function retryManagedDirOperation(operation, destination) {
|
|
1864
2298
|
for (let attempt = 0; ; attempt++) {
|
|
1865
2299
|
try {
|
|
@@ -1867,19 +2301,24 @@ async function retryManagedDirOperation(operation, destination) {
|
|
|
1867
2301
|
} catch (err) {
|
|
1868
2302
|
// Windows can keep a deleted directory name reserved until the last
|
|
1869
2303
|
// handle closes. Keep retries scoped to directory cleanup and creation.
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
!['
|
|
2304
|
+
const insideDestination = !destination || !err.path || isSameOrInsidePath(err.path, destination)
|
|
2305
|
+
if (process.platform !== 'win32' || attempt >= 5 || !insideDestination ||
|
|
2306
|
+
![undefined, 'lstat', 'stat', 'scandir', 'unlink', 'rmdir', 'rm', 'mkdir', 'rename'].includes(err.syscall) ||
|
|
2307
|
+
!['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY'].includes(err.code)) throw err
|
|
1873
2308
|
await delay(50 * 2 ** attempt)
|
|
1874
2309
|
}
|
|
1875
2310
|
}
|
|
1876
2311
|
}
|
|
1877
2312
|
|
|
1878
|
-
function
|
|
2313
|
+
export async function removeManagedDirAsync(dir, options) {
|
|
2314
|
+
return retryManagedDirOperation(() => removeManagedDir(dir, options), dir)
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
function replaceManagedDir(from, to, keepExisting, repairOnly = false, { allowTrash = false } = {}) {
|
|
1879
2318
|
return retryManagedDirOperation(() => {
|
|
1880
2319
|
if (keepExisting?.(to)) return false
|
|
1881
2320
|
if (repairOnly && hasMatchingSkillCopy(from, to)) return true
|
|
1882
|
-
removeManagedDir(to)
|
|
2321
|
+
removeManagedDir(to, { allowTrash })
|
|
1883
2322
|
copyDir(from, to)
|
|
1884
2323
|
return true
|
|
1885
2324
|
}, to)
|
|
@@ -1888,26 +2327,67 @@ function replaceManagedDir(from, to, keepExisting, repairOnly = false) {
|
|
|
1888
2327
|
/**
|
|
1889
2328
|
* Remove a plugin's skills from $DSH_HOME/skills upon uninstall or disabling.
|
|
1890
2329
|
*/
|
|
1891
|
-
|
|
2330
|
+
function pathMayExist(targetPath) {
|
|
2331
|
+
try {
|
|
2332
|
+
if (lstatSync(targetPath, { throwIfNoEntry: false })) return true
|
|
2333
|
+
return existsSync(targetPath)
|
|
2334
|
+
} catch {
|
|
2335
|
+
return true
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
function skillOwnedByOtherEnabledPlugin(pluginName, skillName, plugins = readState().plugins) {
|
|
2340
|
+
for (const rec of plugins || []) {
|
|
2341
|
+
if (!rec || rec.name === pluginName || rec.enabled === false) continue
|
|
2342
|
+
const otherSkillDir = join(installedDir(rec.name), 'skills', skillName)
|
|
2343
|
+
if (existsSync(join(otherSkillDir, 'SKILL.md')) || existsSync(join(otherSkillDir, 'skill.md'))) {
|
|
2344
|
+
return true
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
return false
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
export async function removePluginSkillsFromDsh(pluginName, { allowQuarantine = true, preserveOtherEnabled = true } = {}) {
|
|
1892
2351
|
const target = installedDir(pluginName)
|
|
1893
2352
|
const pluginSkillsDir = join(target, 'skills')
|
|
1894
2353
|
const dshSkills = dshSkillsDir()
|
|
1895
|
-
if (!existsSync(dshSkills)) return
|
|
2354
|
+
if (!existsSync(dshSkills)) return []
|
|
1896
2355
|
|
|
1897
|
-
|
|
2356
|
+
const otherEnabledPlugins = preserveOtherEnabled
|
|
2357
|
+
? (readState().plugins || []).filter((rec) => rec && rec.name !== pluginName && rec.enabled !== false)
|
|
2358
|
+
: []
|
|
2359
|
+
const targets = []
|
|
1898
2360
|
if (existsSync(pluginSkillsDir)) {
|
|
1899
2361
|
for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
|
|
1900
|
-
if (entry.isDirectory())
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
}
|
|
2362
|
+
if (!entry.isDirectory()) continue
|
|
2363
|
+
const destSkillDir = join(dshSkills, entry.name)
|
|
2364
|
+
if (isUploadedSkillTarget(destSkillDir)) continue
|
|
2365
|
+
if (preserveOtherEnabled && skillOwnedByOtherEnabledPlugin(pluginName, entry.name, otherEnabledPlugins)) continue
|
|
2366
|
+
if (pathMayExist(destSkillDir)) targets.push({ name: entry.name, dest: destSkillDir })
|
|
1905
2367
|
}
|
|
1906
2368
|
}
|
|
1907
2369
|
|
|
1908
2370
|
// Older installs may have exposed the compiled subagent hub separately.
|
|
1909
2371
|
const subagentHubDir = join(dshSkills, `${pluginName}-agents`)
|
|
1910
|
-
if (!isUploadedSkillTarget(subagentHubDir)
|
|
2372
|
+
if (!isUploadedSkillTarget(subagentHubDir) && pathMayExist(subagentHubDir)) {
|
|
2373
|
+
targets.push({ name: `${pluginName}-agents`, dest: subagentHubDir })
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
const removed = []
|
|
2377
|
+
const settled = await Promise.allSettled(targets.map(async ({ name, dest }) => {
|
|
2378
|
+
const didRemove = await retryManagedDirOperation(() => {
|
|
2379
|
+
if (isUploadedSkillTarget(dest)) return false
|
|
2380
|
+
removeManagedDir(dest, { allowTrash: allowQuarantine })
|
|
2381
|
+
return true
|
|
2382
|
+
}, dest)
|
|
2383
|
+
if (didRemove) removed.push(name)
|
|
2384
|
+
}))
|
|
2385
|
+
const rejected = settled.find((item) => item.status === 'rejected')
|
|
2386
|
+
if (rejected) {
|
|
2387
|
+
rejected.reason.removedSkills = removed
|
|
2388
|
+
throw rejected.reason
|
|
2389
|
+
}
|
|
2390
|
+
return removed
|
|
1911
2391
|
}
|
|
1912
2392
|
|
|
1913
2393
|
/**
|
|
@@ -1921,11 +2401,13 @@ export async function syncAllInstalledSkillsToDsh() {
|
|
|
1921
2401
|
|
|
1922
2402
|
const results = {}
|
|
1923
2403
|
for (const plugin of state.plugins || []) {
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
2404
|
+
if (plugin.enabled === false) continue
|
|
2405
|
+
results[plugin.name] = await withPluginLock(plugin.name, async () => {
|
|
2406
|
+
const stillEnabled = () => readState().plugins.some(current =>
|
|
2407
|
+
current.name === plugin.name && current.installedAt === plugin.installedAt && current.enabled !== false)
|
|
2408
|
+
if (!stillEnabled()) return []
|
|
2409
|
+
return syncPluginSkillsToDsh(plugin.name, stillEnabled, { repairOnly: true })
|
|
2410
|
+
})
|
|
1929
2411
|
}
|
|
1930
2412
|
return results
|
|
1931
2413
|
}
|
|
@@ -1934,10 +2416,34 @@ export async function syncAllInstalledSkillsToDsh() {
|
|
|
1934
2416
|
* Install a plugin from the marketplace into the installed tree.
|
|
1935
2417
|
* Returns a result summary for the UI.
|
|
1936
2418
|
*/
|
|
1937
|
-
|
|
2419
|
+
const marketplaceInstalls = new Set()
|
|
2420
|
+
|
|
2421
|
+
export async function installPlugin(options) {
|
|
2422
|
+
const { pluginName } = options
|
|
2423
|
+
if (marketplaceInstalls.has(pluginName)) throw new Error(`插件 ${pluginName} 正在安装`)
|
|
2424
|
+
marketplaceInstalls.add(pluginName)
|
|
2425
|
+
bumpPluginEpoch(pluginName)
|
|
2426
|
+
cancelActivePluginProbes(pluginName)
|
|
2427
|
+
try {
|
|
2428
|
+
return await withPluginLock(pluginName, () => installMarketplacePluginUnlocked(options))
|
|
2429
|
+
} finally {
|
|
2430
|
+
marketplaceInstalls.delete(pluginName)
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
async function installMarketplacePluginUnlocked(options) {
|
|
2435
|
+
return withSourceLock(options.sourceId, () => installMarketplacePluginFromSourceLocked(options))
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
async function installMarketplacePluginFromSourceLocked({ sourceId, pluginName, refresh = false, initialEnabled = true }) {
|
|
1938
2439
|
const state = readState()
|
|
1939
2440
|
const source = state.sources.find((s) => s.id === sourceId)
|
|
1940
2441
|
if (!source) throw new Error(`unknown source: ${sourceId}`)
|
|
2442
|
+
const installed = state.plugins.find(plugin => plugin.name === pluginName)
|
|
2443
|
+
if (installed && installed.sourceId !== sourceId) {
|
|
2444
|
+
const owner = state.sources.find(item => item.id === installed.sourceId)
|
|
2445
|
+
throw new Error(`插件 ${pluginName} 已从 ${owner?.name || installed.sourceId} 安装,请在管理页操作`)
|
|
2446
|
+
}
|
|
1941
2447
|
|
|
1942
2448
|
const row = await findMarketRow(sourceId, pluginName)
|
|
1943
2449
|
if (!row) throw new Error(`plugin not found in marketplace: ${pluginName}`)
|
|
@@ -1947,27 +2453,34 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
1947
2453
|
|
|
1948
2454
|
// Reinstalling must not inherit the previous copy's registrations: skills it
|
|
1949
2455
|
// no longer ships and MCP servers it dropped would otherwise stay visible.
|
|
2456
|
+
await abortPluginConnectorProbes(pluginName)
|
|
1950
2457
|
const prevConnectors = existsSync(target) ? getPluginConnectors(target).map((c) => c.name) : []
|
|
1951
|
-
if (existsSync(target)) await
|
|
2458
|
+
if (existsSync(target)) await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true })
|
|
1952
2459
|
|
|
1953
2460
|
// Idempotent reinstall: clear the previous copy first.
|
|
1954
2461
|
await replaceManagedDir(dir, target)
|
|
1955
2462
|
|
|
1956
|
-
// Persist marketplace-declared
|
|
1957
|
-
//
|
|
1958
|
-
//
|
|
1959
|
-
|
|
1960
|
-
|
|
2463
|
+
// Persist marketplace-declared components into the installed copy's manifest
|
|
2464
|
+
// when `strict: false` or when absent on disk, preserving any existing
|
|
2465
|
+
// `.codex-plugin/plugin.json` / root `plugin.json` metadata.
|
|
2466
|
+
const existingDiskManifest = readPluginManifest(target)
|
|
2467
|
+
const keysToPersist = MARKETPLACE_COMPONENT_KEYS.filter((k) =>
|
|
2468
|
+
row[k] !== undefined && (row.strict === false || !existingDiskManifest || existingDiskManifest[k] === undefined))
|
|
2469
|
+
if (keysToPersist.length > 0) {
|
|
1961
2470
|
const manifestDir = join(target, '.claude-plugin')
|
|
1962
2471
|
mkdirSync(manifestDir, { recursive: true })
|
|
1963
2472
|
const manifestPath = join(manifestDir, 'plugin.json')
|
|
1964
|
-
let installedManifest = {}
|
|
2473
|
+
let installedManifest = existingDiskManifest && typeof existingDiskManifest === 'object' ? { ...existingDiskManifest } : {}
|
|
1965
2474
|
try {
|
|
1966
|
-
if (existsSync(manifestPath)) installedManifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
|
2475
|
+
if (existsSync(manifestPath)) installedManifest = { ...installedManifest, ...JSON.parse(readFileSync(manifestPath, 'utf8')) }
|
|
1967
2476
|
} catch {
|
|
1968
2477
|
// ignore malformed existing manifest
|
|
1969
2478
|
}
|
|
1970
|
-
installedManifest.
|
|
2479
|
+
if (!installedManifest.name) installedManifest.name = row.name
|
|
2480
|
+
if (!installedManifest.version && row.version) installedManifest.version = row.version
|
|
2481
|
+
if (!installedManifest.description && row.description) installedManifest.description = row.description
|
|
2482
|
+
if (row.strict !== undefined) installedManifest.strict = row.strict
|
|
2483
|
+
for (const k of keysToPersist) installedManifest[k] = row[k]
|
|
1971
2484
|
writeFileSync(manifestPath, JSON.stringify(installedManifest, null, 2), 'utf8')
|
|
1972
2485
|
}
|
|
1973
2486
|
|
|
@@ -1975,14 +2488,42 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
1975
2488
|
const skillsDir = join(target, 'skills')
|
|
1976
2489
|
mkdirSync(skillsDir, { recursive: true })
|
|
1977
2490
|
|
|
1978
|
-
// Codex manifests may
|
|
2491
|
+
// Codex / Agent Plugins manifests may declare `skills: ["."]` or custom paths outside skills/.
|
|
2492
|
+
const NON_SKILL_COPY_DIRS = new Set([
|
|
2493
|
+
'skills', 'commands', 'agents', '.agents', '.claude-plugin', '.codex-plugin', '.well-known',
|
|
2494
|
+
'hooks', 'prompts', 'mcp', 'lsp', 'scripts', 'server', 'node_modules', '.git', 'assets', 'docs',
|
|
2495
|
+
])
|
|
1979
2496
|
const declaredSkills = readPluginManifest(target)?.skills
|
|
1980
|
-
const skillPaths = typeof declaredSkills === 'string'
|
|
2497
|
+
const skillPaths = typeof declaredSkills === 'string'
|
|
2498
|
+
? (isDotRelativePath(declaredSkills) ? [declaredSkills] : [])
|
|
2499
|
+
: (Array.isArray(declaredSkills) ? declaredSkills.filter((p) => typeof p === 'string' && isDotRelativePath(p)) : [])
|
|
1981
2500
|
for (const path of skillPaths) {
|
|
1982
|
-
|
|
1983
|
-
if (!existsSync(root) || resolve(root) === resolve(skillsDir)) continue
|
|
1984
|
-
if (statSync(root).isFile())
|
|
1985
|
-
|
|
2501
|
+
const root = resolvePluginSpecPath(target, path)
|
|
2502
|
+
if (!root || !existsSync(root) || resolve(root) === resolve(skillsDir)) continue
|
|
2503
|
+
if (statSync(root).isFile()) {
|
|
2504
|
+
const base = basename(root)
|
|
2505
|
+
if (/^skill\.md$/i.test(base)) {
|
|
2506
|
+
const parent = dirname(root)
|
|
2507
|
+
if (resolve(parent) !== resolve(target)) {
|
|
2508
|
+
const dest = join(skillsDir, basename(parent))
|
|
2509
|
+
if (resolve(dest) !== resolve(parent)) copyDir(parent, dest)
|
|
2510
|
+
}
|
|
2511
|
+
} else if (/\.md$/i.test(base) && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(base)) {
|
|
2512
|
+
const skillName = base.replace(/\.md$/i, '')
|
|
2513
|
+
const singleDir = join(skillsDir, skillName)
|
|
2514
|
+
if (!existsSync(singleDir)) {
|
|
2515
|
+
mkdirSync(singleDir, { recursive: true })
|
|
2516
|
+
const rawContent = readFileSync(root, 'utf8')
|
|
2517
|
+
writeFileSync(join(singleDir, 'SKILL.md'), ensureSkillFrontmatter(rawContent, skillName), 'utf8')
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
continue
|
|
2521
|
+
}
|
|
2522
|
+
const dirs = existsSync(join(root, 'SKILL.md')) || existsSync(join(root, 'skill.md'))
|
|
2523
|
+
? [root]
|
|
2524
|
+
: readdirSync(root, { withFileTypes: true })
|
|
2525
|
+
.filter((e) => e.isDirectory() && !NON_SKILL_COPY_DIRS.has(e.name) && !e.name.startsWith('.'))
|
|
2526
|
+
.map((e) => join(root, e.name))
|
|
1986
2527
|
for (const dir of dirs) {
|
|
1987
2528
|
if (resolve(dir) === resolve(target)) continue // handled as a root skill below
|
|
1988
2529
|
if (!existsSync(join(dir, 'SKILL.md')) && !existsSync(join(dir, 'skill.md'))) continue
|
|
@@ -1991,22 +2532,25 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
1991
2532
|
}
|
|
1992
2533
|
}
|
|
1993
2534
|
|
|
1994
|
-
// 1.
|
|
1995
|
-
const
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2535
|
+
// 1. Mirror commands/ (nested subdirs, manifest string/array/object paths & inline commands) into skills/
|
|
2536
|
+
const { entries: commandEntries } = resolvePluginCommandEntries(target, readPluginManifest(target))
|
|
2537
|
+
for (const cmd of commandEntries) {
|
|
2538
|
+
const cmdSkillDir = join(skillsDir, cmd.name)
|
|
2539
|
+
if (existsSync(cmdSkillDir)) continue
|
|
2540
|
+
if (cmd.filePath) {
|
|
2541
|
+
if (/^skill\.md$/i.test(basename(cmd.filePath))) {
|
|
2542
|
+
mkdirSync(cmdSkillDir, { recursive: true })
|
|
2543
|
+
copyDir(dirname(cmd.filePath), cmdSkillDir)
|
|
2544
|
+
} else {
|
|
2001
2545
|
mkdirSync(cmdSkillDir, { recursive: true })
|
|
2002
|
-
const rawContent = readFileSync(
|
|
2003
|
-
const formatted = ensureSkillFrontmatter(rawContent,
|
|
2546
|
+
const rawContent = readFileSync(cmd.filePath, 'utf8')
|
|
2547
|
+
const formatted = ensureSkillFrontmatter(rawContent, cmd.name, cmd.description)
|
|
2004
2548
|
writeFileSync(join(cmdSkillDir, 'SKILL.md'), formatted, 'utf8')
|
|
2005
|
-
} else if (entry.isDirectory()) {
|
|
2006
|
-
const subSkillDir = join(skillsDir, entry.name)
|
|
2007
|
-
mkdirSync(subSkillDir, { recursive: true })
|
|
2008
|
-
copyDir(join(commandsDir, entry.name), subSkillDir)
|
|
2009
2549
|
}
|
|
2550
|
+
} else if (typeof cmd.content === 'string') {
|
|
2551
|
+
mkdirSync(cmdSkillDir, { recursive: true })
|
|
2552
|
+
const formatted = ensureSkillFrontmatter(cmd.content, cmd.name, cmd.description)
|
|
2553
|
+
writeFileSync(join(cmdSkillDir, 'SKILL.md'), formatted, 'utf8')
|
|
2010
2554
|
}
|
|
2011
2555
|
}
|
|
2012
2556
|
|
|
@@ -2056,7 +2600,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2056
2600
|
const convertErrors = []
|
|
2057
2601
|
|
|
2058
2602
|
for (const agent of agents) {
|
|
2059
|
-
const text = readAgentYaml(target, agent.file)
|
|
2603
|
+
const text = agent.raw || readAgentYaml(target, agent.file)
|
|
2060
2604
|
const parsed = parseAgentDefinition(pluginName, agent.file, text)
|
|
2061
2605
|
if (parsed?.error) {
|
|
2062
2606
|
convertErrors.push(parsed.error)
|
|
@@ -2086,7 +2630,8 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2086
2630
|
subagentsHub = compileSubagentsHubSkill(pluginName, row.displayName || pluginName, validAgents, skillsDir)
|
|
2087
2631
|
}
|
|
2088
2632
|
|
|
2089
|
-
// Ensure all SKILL.md in skills/ have valid frontmatter with name:
|
|
2633
|
+
// Ensure all SKILL.md in skills/ have valid frontmatter with name: and expanded runtime vars
|
|
2634
|
+
const dataDir = pluginDataDir(pluginName)
|
|
2090
2635
|
for (const entry of readdirSync(skillsDir, { withFileTypes: true })) {
|
|
2091
2636
|
if (entry.isDirectory()) {
|
|
2092
2637
|
const skillFile = join(skillsDir, entry.name, 'SKILL.md')
|
|
@@ -2094,7 +2639,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2094
2639
|
if (!existsSync(skillFile) && existsSync(altSkillFile)) copyFileSync(altSkillFile, skillFile)
|
|
2095
2640
|
if (existsSync(skillFile)) {
|
|
2096
2641
|
const raw = readFileSync(skillFile, 'utf8')
|
|
2097
|
-
const fixed = ensureSkillFrontmatter(raw, entry.name)
|
|
2642
|
+
const fixed = expandPluginVars(ensureSkillFrontmatter(raw, entry.name), target, dataDir)
|
|
2098
2643
|
if (fixed !== raw) {
|
|
2099
2644
|
writeFileSync(skillFile, fixed, 'utf8')
|
|
2100
2645
|
}
|
|
@@ -2110,8 +2655,8 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2110
2655
|
const connectors = listConnectors(target)
|
|
2111
2656
|
const hooks = listHooks(target)
|
|
2112
2657
|
|
|
2113
|
-
// Sync skills and subagent delegates to DSH native skills directory.
|
|
2114
|
-
if (existsSync(skillsDir)) {
|
|
2658
|
+
// Sync skills and subagent delegates to DSH native skills directory when enabled.
|
|
2659
|
+
if (initialEnabled && existsSync(skillsDir)) {
|
|
2115
2660
|
await syncPluginSkillsToDsh(pluginName)
|
|
2116
2661
|
}
|
|
2117
2662
|
|
|
@@ -2120,34 +2665,51 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2120
2665
|
for (const name of prevConnectors) {
|
|
2121
2666
|
if (!pluginConnectors.some((c) => c.name === name)) unregisterConnector(pluginName, name)
|
|
2122
2667
|
}
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2668
|
+
if (installed) {
|
|
2669
|
+
// The new copy may ship different tools behind an unchanged command/URL.
|
|
2670
|
+
const toolsState = readMcpToolsState()
|
|
2671
|
+
let changed = false
|
|
2672
|
+
for (const connector of pluginConnectors) {
|
|
2673
|
+
const key = `${pluginName}::${connector.name}`
|
|
2674
|
+
MEMORY_TOOLS_CACHE.delete(key)
|
|
2675
|
+
MCP_TOOLS_INFLIGHT.delete(key)
|
|
2676
|
+
const saved = toolsState[key]
|
|
2677
|
+
if (!saved) continue
|
|
2678
|
+
for (const field of ['cachedTools', 'cachedToolsResolved', 'verifiedStdioConfig', 'verifiedRemoteConfig']) {
|
|
2679
|
+
if (Object.hasOwn(saved, field)) {
|
|
2680
|
+
delete saved[field]
|
|
2681
|
+
changed = true
|
|
2682
|
+
}
|
|
2128
2683
|
}
|
|
2129
|
-
registerConnector(pluginName, c.name, c)
|
|
2130
2684
|
}
|
|
2685
|
+
if (changed) writeMcpToolsState(toolsState, { required: true })
|
|
2131
2686
|
}
|
|
2132
2687
|
|
|
2133
|
-
// Auto-register LSP servers declared by the plugin. The host packages
|
|
2134
|
-
// (dsh-lsp / dsh-lsp-stdio / dsh-tool-lsp) were pre-provisioned by the
|
|
2135
|
-
// hub's `apply()` at DSH startup — this step is a single, race-free
|
|
2136
|
-
// patch write. `lspErrors` still surface other failures (the user-installed
|
|
2137
|
-
// language server binary not on PATH, missing extensionToLanguage, etc.).
|
|
2138
|
-
// Drop the previous version's server entries; the loop re-adds the ones this
|
|
2139
|
-
// version still declares, so removed servers stop loading.
|
|
2140
|
-
unregisterPluginLsp(pluginName)
|
|
2141
2688
|
const lspServers = listLspServers(target)
|
|
2142
2689
|
const lspErrors = []
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2690
|
+
unregisterPluginLsp(pluginName)
|
|
2691
|
+
if (initialEnabled) {
|
|
2692
|
+
// Auto-register LSP servers declared by the plugin. The host packages
|
|
2693
|
+
// (dsh-lsp / dsh-lsp-stdio / dsh-tool-lsp) were pre-provisioned by the
|
|
2694
|
+
// hub's `apply()` at DSH startup — this step is a single, race-free
|
|
2695
|
+
// patch write. `lspErrors` still surface other failures (the user-installed
|
|
2696
|
+
// language server binary not on PATH, missing extensionToLanguage, etc.).
|
|
2697
|
+
// Drop the previous version's server entries; the loop re-adds the ones this
|
|
2698
|
+
// version still declares, so removed servers stop loading.
|
|
2699
|
+
for (const r of registerPluginLsp(pluginName)) {
|
|
2700
|
+
if (!r.ok && r.error) lspErrors.push(r.error)
|
|
2701
|
+
}
|
|
2146
2702
|
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2703
|
+
// Register the plugin's Claude/Codex hooks into DSH via the hooks bridge.
|
|
2704
|
+
// The bridge package was pre-provisioned by the hub's `apply()`; this is a
|
|
2705
|
+
// single patch write.
|
|
2706
|
+
await registerPluginHooks(pluginName)
|
|
2707
|
+
} else {
|
|
2708
|
+
for (const c of pluginConnectors) {
|
|
2709
|
+
toggleConnector(pluginName, c.name, false)
|
|
2710
|
+
}
|
|
2711
|
+
unregisterPluginHooks(pluginName)
|
|
2712
|
+
}
|
|
2151
2713
|
|
|
2152
2714
|
const record = {
|
|
2153
2715
|
id: `${sourceId}/${pluginName}`,
|
|
@@ -2156,7 +2718,7 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2156
2718
|
displayName: row.displayName || pluginName,
|
|
2157
2719
|
description: row.description || '',
|
|
2158
2720
|
author: row.author ?? null,
|
|
2159
|
-
enabled:
|
|
2721
|
+
enabled: initialEnabled,
|
|
2160
2722
|
installedAt: Date.now(),
|
|
2161
2723
|
skillCount: skills.length,
|
|
2162
2724
|
agentCount: agents.length,
|
|
@@ -2166,14 +2728,15 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2166
2728
|
lspServerCount: lspServers.length,
|
|
2167
2729
|
version: readInstalledVersion(target) ?? row.version ?? null,
|
|
2168
2730
|
}
|
|
2169
|
-
//
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
writeState(state)
|
|
2731
|
+
// Materialization can overlap edits to other plugins and to standalone MCPs.
|
|
2732
|
+
const latest = readState()
|
|
2733
|
+
latest.plugins = [...latest.plugins.filter((p) => p.name !== pluginName), record]
|
|
2734
|
+
writeState(latest)
|
|
2174
2735
|
invalidateParserCaches()
|
|
2175
2736
|
|
|
2176
|
-
|
|
2737
|
+
if (initialEnabled) {
|
|
2738
|
+
warmInstalledConnectorTools(pluginName, pluginConnectors, record)
|
|
2739
|
+
}
|
|
2177
2740
|
|
|
2178
2741
|
return {
|
|
2179
2742
|
ok: true,
|
|
@@ -2194,6 +2757,8 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
2194
2757
|
function readAgentYaml(target, file) {
|
|
2195
2758
|
const candidates = [
|
|
2196
2759
|
join(target, 'agents', file),
|
|
2760
|
+
join(target, '.agents', file),
|
|
2761
|
+
join(target, '.claude-plugin', 'agents', file),
|
|
2197
2762
|
join(target, file),
|
|
2198
2763
|
join(target, '.well-known', file),
|
|
2199
2764
|
]
|
|
@@ -2214,6 +2779,12 @@ function readInstalledVersion(target) {
|
|
|
2214
2779
|
|
|
2215
2780
|
/** Uninstall: remove copy, unregister scan dir, clean legacy presets and connectors. */
|
|
2216
2781
|
export async function uninstallPlugin(pluginName) {
|
|
2782
|
+
bumpPluginEpoch(pluginName)
|
|
2783
|
+
cancelActivePluginProbes(pluginName)
|
|
2784
|
+
return withPluginLock(pluginName, () => uninstallPluginUnlocked(pluginName))
|
|
2785
|
+
}
|
|
2786
|
+
|
|
2787
|
+
async function uninstallPluginUnlocked(pluginName) {
|
|
2217
2788
|
const sharedNamespace = pluginName === 'user-mcp'
|
|
2218
2789
|
const standaloneIds = () => new Set([
|
|
2219
2790
|
...(readState().userMcps || []).map(mcp => mcp.name),
|
|
@@ -2228,9 +2799,9 @@ export async function uninstallPlugin(pluginName) {
|
|
|
2228
2799
|
await stopping
|
|
2229
2800
|
stopping = stopVerifications()
|
|
2230
2801
|
}
|
|
2231
|
-
|
|
2802
|
+
await abortPluginConnectorProbes(pluginName)
|
|
2232
2803
|
const target = installedDir(pluginName)
|
|
2233
|
-
removePluginSkillsFromDsh(pluginName)
|
|
2804
|
+
await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true })
|
|
2234
2805
|
const prefix = `${pluginName}::`
|
|
2235
2806
|
const priorToolsState = readMcpToolsState()
|
|
2236
2807
|
const declared = new Map((existsSync(target) ? getPluginConnectors(target) : []).map(c => [c.name, c.url]))
|
|
@@ -2238,7 +2809,7 @@ export async function uninstallPlugin(pluginName) {
|
|
|
2238
2809
|
// shared namespace. Other cached entries are eligible only with provenance.
|
|
2239
2810
|
const claimed = sharedNamespace ? standaloneIds() : new Set()
|
|
2240
2811
|
const cachedNames = Object.entries(priorToolsState)
|
|
2241
|
-
.filter(([key, saved]) => key.startsWith(prefix) && (!sharedNamespace || saved?.pluginOAuthOwned))
|
|
2812
|
+
.filter(([key, saved]) => key.startsWith(prefix) && (!sharedNamespace || saved?.pluginOAuthOwned || saved?.pluginConnectorOwned))
|
|
2242
2813
|
.map(([key]) => key.slice(prefix.length))
|
|
2243
2814
|
const ownedNames = new Set()
|
|
2244
2815
|
for (const name of new Set([...declared.keys(), ...cachedNames])) {
|
|
@@ -2249,8 +2820,9 @@ export async function uninstallPlugin(pluginName) {
|
|
|
2249
2820
|
const remote = remoteConfigFromEntry(entry?.config)
|
|
2250
2821
|
const ownsRegistration = remote && remote.credentialKey === oauthCredentialKey(pluginName, name, remote.url, remote.oauth)
|
|
2251
2822
|
if (sharedNamespace && remote && !ownsRegistration) continue
|
|
2252
|
-
if (sharedNamespace && !entry && !saved?.pluginOAuthOwned) continue
|
|
2823
|
+
if (sharedNamespace && !entry && !saved?.pluginOAuthOwned && !saved?.pluginConnectorOwned) continue
|
|
2253
2824
|
ownedNames.add(name)
|
|
2825
|
+
MCP_ACTIVATIONS.delete(prefix + name)
|
|
2254
2826
|
if (remote ? ownsRegistration : declared.has(name)) unregisterConnector(pluginName, name)
|
|
2255
2827
|
const oauthUrls = new Set([
|
|
2256
2828
|
...(Array.isArray(saved?.oauthUrls) ? saved.oauthUrls : []),
|
|
@@ -2267,11 +2839,11 @@ export async function uninstallPlugin(pluginName) {
|
|
|
2267
2839
|
}
|
|
2268
2840
|
}
|
|
2269
2841
|
}
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
}
|
|
2274
|
-
|
|
2842
|
+
unregisterPluginLsp(pluginName)
|
|
2843
|
+
unregisterPluginHooks(pluginName)
|
|
2844
|
+
await abortPluginConnectorProbes(pluginName)
|
|
2845
|
+
await removeManagedDirAsync(target, { allowTrash: false })
|
|
2846
|
+
if (!sharedNamespace) await removeManagedDirAsync(pluginDataDir(pluginName), { allowTrash: false })
|
|
2275
2847
|
|
|
2276
2848
|
// Clean any legacy preset directories left by prior versions
|
|
2277
2849
|
cleanupLegacyPresets(pluginName)
|
|
@@ -2291,46 +2863,138 @@ export async function uninstallPlugin(pluginName) {
|
|
|
2291
2863
|
writeMcpToolsState(mcpToolsState, { required: true })
|
|
2292
2864
|
}
|
|
2293
2865
|
|
|
2294
|
-
state
|
|
2295
|
-
|
|
2866
|
+
// Re-read state after awaits so concurrent mutations to other plugins are preserved.
|
|
2867
|
+
const latestState = readState()
|
|
2868
|
+
latestState.plugins = latestState.plugins.filter((p) => p.name !== pluginName)
|
|
2869
|
+
writeState(latestState)
|
|
2296
2870
|
invalidateParserCaches()
|
|
2297
2871
|
return { ok: true }
|
|
2298
2872
|
}
|
|
2299
2873
|
|
|
2300
2874
|
/** Toggle a plugin's skills scanning and connectors on/off. */
|
|
2301
|
-
export async function togglePlugin(pluginName, enabled) {
|
|
2875
|
+
export async function togglePlugin(pluginName, enabled, options = {}) {
|
|
2876
|
+
const epoch = bumpPluginEpoch(pluginName)
|
|
2877
|
+
cancelActivePluginProbes(pluginName)
|
|
2878
|
+
return withPluginLock(pluginName, () => togglePluginUnlocked(pluginName, enabled, epoch, options))
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
async function togglePluginUnlocked(pluginName, enabled, epoch, options = {}) {
|
|
2302
2882
|
const state = readState()
|
|
2303
2883
|
const rec = state.plugins.find((p) => p.name === pluginName)
|
|
2304
2884
|
if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
|
|
2305
2885
|
const target = installedDir(pluginName)
|
|
2306
2886
|
const skillsDir = join(target, 'skills')
|
|
2307
|
-
const skills = listSkills(target)
|
|
2308
|
-
const skillNames = skills.map((s) => s.command || s.name || pluginName)
|
|
2309
2887
|
const pluginConnectors = getPluginConnectors(target)
|
|
2310
2888
|
const lspErrors = []
|
|
2889
|
+
const sameInstall = (item) => item.name === pluginName && item.sourceId === rec.sourceId && item.installedAt === rec.installedAt
|
|
2890
|
+
const stillCurrent = () => currentPluginEpoch(pluginName) === epoch
|
|
2891
|
+
const rollbackEnable = async () => {
|
|
2892
|
+
try { unregisterPluginHooks(pluginName) } catch {}
|
|
2893
|
+
try { unregisterPluginLsp(pluginName) } catch {}
|
|
2894
|
+
await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true }).catch(() => {})
|
|
2895
|
+
}
|
|
2311
2896
|
|
|
2312
2897
|
if (enabled) {
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2898
|
+
try {
|
|
2899
|
+
if (existsSync(skillsDir)) {
|
|
2900
|
+
await syncPluginSkillsToDsh(pluginName, () => stillCurrent() && readState().plugins.some(sameInstall))
|
|
2901
|
+
}
|
|
2902
|
+
if (!stillCurrent()) {
|
|
2903
|
+
if (rec.enabled === false) await rollbackEnable()
|
|
2904
|
+
return { ok: false, error: '插件状态已变更,请刷新后重试' }
|
|
2905
|
+
}
|
|
2906
|
+
withCordisPatchBatch(() => {
|
|
2907
|
+
for (const r of registerPluginLsp(pluginName)) {
|
|
2908
|
+
if (!r.ok && r.error) lspErrors.push(r.error)
|
|
2909
|
+
}
|
|
2910
|
+
})
|
|
2911
|
+
await registerPluginHooks(pluginName)
|
|
2912
|
+
} catch (err) {
|
|
2913
|
+
if (rec.enabled === false) await rollbackEnable()
|
|
2914
|
+
throw err
|
|
2321
2915
|
}
|
|
2322
|
-
await registerPluginHooks(pluginName)
|
|
2323
2916
|
} else {
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2917
|
+
cancelActivePluginProbes(pluginName)
|
|
2918
|
+
try {
|
|
2919
|
+
await removePluginSkillsFromDsh(pluginName, { allowQuarantine: true, preserveOtherEnabled: true })
|
|
2920
|
+
withCordisPatchBatch(() => {
|
|
2921
|
+
for (const c of pluginConnectors) {
|
|
2922
|
+
toggleConnector(pluginName, c.name, false)
|
|
2923
|
+
}
|
|
2924
|
+
unregisterPluginLsp(pluginName)
|
|
2925
|
+
unregisterPluginHooks(pluginName)
|
|
2926
|
+
})
|
|
2927
|
+
} catch (err) {
|
|
2928
|
+
if (rec.enabled !== false && existsSync(skillsDir)) {
|
|
2929
|
+
await syncPluginSkillsToDsh(
|
|
2930
|
+
pluginName,
|
|
2931
|
+
() => stillCurrent() && readState().plugins.some(item => sameInstall(item) && item.enabled !== false),
|
|
2932
|
+
{ repairOnly: true },
|
|
2933
|
+
).catch(() => {})
|
|
2934
|
+
}
|
|
2935
|
+
throw err
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
const latest = readState()
|
|
2939
|
+
if (!latest.plugins.some(sameInstall)) return { ok: false, error: '插件已变更,请刷新后重试' }
|
|
2940
|
+
if (enabled && !stillCurrent()) {
|
|
2941
|
+
if (rec.enabled === false) await rollbackEnable()
|
|
2942
|
+
return { ok: false, error: '插件状态已变更,请刷新后重试' }
|
|
2943
|
+
}
|
|
2944
|
+
writeState({ ...latest, plugins: latest.plugins.map(item => sameInstall(item) ? { ...item, enabled } : item) })
|
|
2945
|
+
let pendingConnectorNames = []
|
|
2946
|
+
if (enabled && pluginConnectors.length > 0) {
|
|
2947
|
+
const canEnable = () => stillCurrent() && readState().plugins.some(item => sameInstall(item) && item.enabled !== false)
|
|
2948
|
+
if (canEnable()) {
|
|
2949
|
+
const toolsState = readMcpToolsState()
|
|
2950
|
+
const pendingConnectors = []
|
|
2951
|
+
withCordisPatchBatch(() => {
|
|
2952
|
+
for (const c of pluginConnectors) {
|
|
2953
|
+
if (!canEnable()) break
|
|
2954
|
+
if (getConnectorEntry(pluginName, c.name)) continue
|
|
2955
|
+
const savedState = toolsState[`${pluginName}::${c.name}`]
|
|
2956
|
+
const savedDef = savedState?.savedConnectorTemplate || savedState?.savedConnectorDefinition || savedState?.savedOAuthRemoteConfig || null
|
|
2957
|
+
if (!savedDef && connectorRequiresAuth(c)) continue
|
|
2958
|
+
const input = savedDef || {}
|
|
2959
|
+
const def = connectorDefinition(pluginName, c.name, input, true)
|
|
2960
|
+
const isStdio = def.transport === 'stdio'
|
|
2961
|
+
const hasCachedTools = savedState?.cachedToolsResolved === true
|
|
2962
|
+
|| (Array.isArray(savedState?.cachedTools) && savedState.cachedTools.length > 0)
|
|
2963
|
+
const verifiedBefore = isStdio && hasCachedTools
|
|
2964
|
+
&& Boolean(def.command && resolveCommandPath(def.command, process.env, def.cwd ? { cwd: def.cwd } : undefined))
|
|
2965
|
+
&& (savedState?.verifiedStdioConfig
|
|
2966
|
+
? savedState.verifiedStdioConfig === stdioConfigFingerprint(def)
|
|
2967
|
+
: (Boolean(savedState?.savedConnectorDefinition || savedState?.savedConnectorTemplate) || !connectorRequiresAuth(c)))
|
|
2968
|
+
const rememberDefinition = Boolean(savedDef)
|
|
2969
|
+
if (verifiedBefore) {
|
|
2970
|
+
saveConnectorAuth(pluginName, c.name, input, {
|
|
2971
|
+
pluginOwned: true,
|
|
2972
|
+
rememberDefinition,
|
|
2973
|
+
probe: { ok: true, tools: savedState.cachedTools || [], definition: def },
|
|
2974
|
+
})
|
|
2975
|
+
} else {
|
|
2976
|
+
pendingConnectors.push({ name: c.name, rememberDefinition })
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
})
|
|
2980
|
+
pendingConnectorNames = pendingConnectors.map((item) => item.name)
|
|
2981
|
+
for (const item of pendingConnectors) {
|
|
2982
|
+
if (!canEnable()) break
|
|
2983
|
+
// Probe unverified connectors asynchronously so plugin switches return immediately.
|
|
2984
|
+
void enableConnector(pluginName, item.name, undefined, { pluginOwned: true, rememberDefinition: item.rememberDefinition, canEnable })
|
|
2985
|
+
.then((res) => {
|
|
2986
|
+
if (res?.ok && canEnable()) options.onConnectorReady?.(getConnectorId(pluginName, item.name))
|
|
2987
|
+
})
|
|
2988
|
+
.catch(() => {})
|
|
2989
|
+
}
|
|
2327
2990
|
}
|
|
2328
|
-
unregisterPluginLsp(pluginName)
|
|
2329
|
-
unregisterPluginHooks(pluginName)
|
|
2330
2991
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2992
|
+
return {
|
|
2993
|
+
ok: true,
|
|
2994
|
+
enabled,
|
|
2995
|
+
lspErrors: lspErrors.length > 0 ? lspErrors : undefined,
|
|
2996
|
+
...(pendingConnectorNames.length > 0 ? { pendingConnectors: pendingConnectorNames } : {}),
|
|
2997
|
+
}
|
|
2334
2998
|
}
|
|
2335
2999
|
|
|
2336
3000
|
/**
|
|
@@ -2338,33 +3002,82 @@ export async function togglePlugin(pluginName, enabled) {
|
|
|
2338
3002
|
* reinstall the plugin copy and re-run conversions.
|
|
2339
3003
|
*/
|
|
2340
3004
|
export async function updatePlugin(pluginName) {
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
throw new Error(
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
3005
|
+
bumpPluginEpoch(pluginName)
|
|
3006
|
+
cancelActivePluginProbes(pluginName)
|
|
3007
|
+
return withPluginLock(pluginName, async () => {
|
|
3008
|
+
const initialRec = readState().plugins.find((p) => p.name === pluginName)
|
|
3009
|
+
if (!initialRec) throw new Error(`plugin not installed: ${pluginName}`)
|
|
3010
|
+
return withSourceLock(initialRec.sourceId, async () => {
|
|
3011
|
+
const state = readState()
|
|
3012
|
+
const rec = state.plugins.find((p) => p.name === pluginName)
|
|
3013
|
+
if (!rec) throw new Error(`plugin not installed: ${pluginName}`)
|
|
3014
|
+
if (rec.sourceId === 'local' && !readMarketplace('local').some(row => row.name === pluginName)) {
|
|
3015
|
+
throw new Error('本地插件的原始来源不可用,请重新导入后再更新')
|
|
3016
|
+
}
|
|
3017
|
+
const source = state.sources.find((s) => s.id === rec.sourceId)
|
|
3018
|
+
if (source && typeof source.url === 'string') {
|
|
3019
|
+
const cacheDir = sourceCacheDir(rec.sourceId)
|
|
3020
|
+
if (existsSync(join(cacheDir, '.git'))) {
|
|
3021
|
+
await pullSource(rec.sourceId)
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
2354
3024
|
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
3025
|
+
// Clear memory cache so fresh MCP tool lists can be queried
|
|
3026
|
+
for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
|
|
3027
|
+
if (k.startsWith(`${pluginName}::`)) {
|
|
3028
|
+
MEMORY_TOOLS_CACHE.delete(k)
|
|
3029
|
+
}
|
|
3030
|
+
}
|
|
2361
3031
|
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
3032
|
+
// The marketplace rows are cached for 30s; without this the install below
|
|
3033
|
+
// re-reads the pre-pull catalog and installs the old revision.
|
|
3034
|
+
invalidateMarketplaceCache(rec.sourceId)
|
|
2365
3035
|
|
|
2366
|
-
|
|
2367
|
-
|
|
3036
|
+
// Freshly materialized install (re-copies, re-registers, re-converts).
|
|
3037
|
+
return installMarketplacePluginFromSourceLocked({
|
|
3038
|
+
sourceId: rec.sourceId,
|
|
3039
|
+
pluginName,
|
|
3040
|
+
refresh: true,
|
|
3041
|
+
initialEnabled: rec.enabled !== false,
|
|
3042
|
+
})
|
|
3043
|
+
})
|
|
3044
|
+
})
|
|
3045
|
+
}
|
|
3046
|
+
|
|
3047
|
+
/**
|
|
3048
|
+
* Re-materialize already-installed plugins belonging to `sourceId` whose names
|
|
3049
|
+
* appear in `pluginNames`, clearing cached metadata/tools while preserving any
|
|
3050
|
+
* prior disabled (`enabled === false`) state. Plugins from other sources stay
|
|
3051
|
+
* untouched so local overwrites never hijack foreign installs.
|
|
3052
|
+
*/
|
|
3053
|
+
export async function refreshInstalledPluginsFromSource(sourceId, pluginNames) {
|
|
3054
|
+
const names = new Set(Array.from(pluginNames || []).map((n) => String(n || '').toLowerCase()).filter(Boolean))
|
|
3055
|
+
if (!names.size) return []
|
|
3056
|
+
const targets = readState().plugins.filter(
|
|
3057
|
+
(rec) => rec && rec.sourceId === sourceId && names.has(String(rec.name || '').toLowerCase()),
|
|
3058
|
+
)
|
|
3059
|
+
const refreshed = []
|
|
3060
|
+
for (const rec of targets) {
|
|
3061
|
+
bumpPluginEpoch(rec.name)
|
|
3062
|
+
cancelActivePluginProbes(rec.name)
|
|
3063
|
+
await withPluginLock(rec.name, async () => {
|
|
3064
|
+
const current = readState().plugins.find((p) => p && p.name === rec.name && p.sourceId === sourceId)
|
|
3065
|
+
if (!current) return
|
|
3066
|
+
for (const k of Array.from(MEMORY_TOOLS_CACHE.keys())) {
|
|
3067
|
+
if (k.startsWith(`${current.name}::`)) MEMORY_TOOLS_CACHE.delete(k)
|
|
3068
|
+
}
|
|
3069
|
+
invalidateMarketplaceCache(sourceId)
|
|
3070
|
+
invalidateParserCaches()
|
|
3071
|
+
await installMarketplacePluginUnlocked({
|
|
3072
|
+
sourceId,
|
|
3073
|
+
pluginName: current.name,
|
|
3074
|
+
refresh: true,
|
|
3075
|
+
initialEnabled: current.enabled !== false,
|
|
3076
|
+
})
|
|
3077
|
+
refreshed.push(current.name)
|
|
3078
|
+
})
|
|
3079
|
+
}
|
|
3080
|
+
return refreshed
|
|
2368
3081
|
}
|
|
2369
3082
|
|
|
2370
3083
|
/** Find one marketplace row by name. */
|
|
@@ -2388,7 +3101,7 @@ function findMarketRowSync(sourceId, pluginName) {
|
|
|
2388
3101
|
}
|
|
2389
3102
|
}
|
|
2390
3103
|
|
|
2391
|
-
function installedPluginIconIdentity(rec, target, manifest, marketRow) {
|
|
3104
|
+
export function installedPluginIconIdentity(rec, target, manifest, marketRow) {
|
|
2392
3105
|
const author = typeof manifest?.author === 'string' ? manifest.author : manifest?.author?.name
|
|
2393
3106
|
const declared = buildPluginIcons(manifest, { sourceId: rec.sourceId, name: rec.name, dir: target, source: marketRow?.source })
|
|
2394
3107
|
return {
|
|
@@ -2487,163 +3200,216 @@ function hasOverlappingToolPrefix(publicName, name, servers) {
|
|
|
2487
3200
|
return false
|
|
2488
3201
|
}
|
|
2489
3202
|
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
if (installed) {
|
|
2499
|
-
const skillsDir = join(target, 'skills')
|
|
2500
|
-
if (!existsSync(skillsDir)) {
|
|
2501
|
-
try { mkdirSync(skillsDir, { recursive: true }) } catch {}
|
|
2502
|
-
}
|
|
2503
|
-
try {
|
|
2504
|
-
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
2505
|
-
if (
|
|
2506
|
-
entry.isDirectory() &&
|
|
2507
|
-
entry.name !== 'skills' &&
|
|
2508
|
-
entry.name !== 'commands' &&
|
|
2509
|
-
entry.name !== 'agents' &&
|
|
2510
|
-
entry.name !== '.agents' &&
|
|
2511
|
-
entry.name !== 'node_modules' &&
|
|
2512
|
-
entry.name !== '.git'
|
|
2513
|
-
) {
|
|
2514
|
-
const sMd = join(target, entry.name, 'SKILL.md')
|
|
2515
|
-
if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
|
|
2516
|
-
const subDir = join(skillsDir, entry.name)
|
|
2517
|
-
mkdirSync(subDir, { recursive: true })
|
|
2518
|
-
copyDir(join(target, entry.name), subDir)
|
|
2519
|
-
}
|
|
2520
|
-
}
|
|
3203
|
+
function buildInstalledPluginDetail(rec, shared = {}) {
|
|
3204
|
+
const getPatchEntries = () => {
|
|
3205
|
+
if (!shared.patchEntries) {
|
|
3206
|
+
const entries = new Map()
|
|
3207
|
+
for (const block of readCordisPatch()) {
|
|
3208
|
+
if (!Array.isArray(block?.insert)) continue
|
|
3209
|
+
for (const entry of block.insert) {
|
|
3210
|
+
if (entry && !entries.has(entry.id)) entries.set(entry.id, entry)
|
|
2521
3211
|
}
|
|
2522
|
-
}
|
|
3212
|
+
}
|
|
3213
|
+
shared.patchEntries = entries
|
|
2523
3214
|
}
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
3215
|
+
return shared.patchEntries
|
|
3216
|
+
}
|
|
3217
|
+
const getToolsState = () => (shared.toolsState ??= readMcpToolsState())
|
|
3218
|
+
const resolveCmdCached = (cmd, cwd) => {
|
|
3219
|
+
if (!shared.commandCache) return resolveCommandPath(cmd, process.env, { cwd })
|
|
3220
|
+
const cacheKey = `${cmd}\0${cwd || ''}`
|
|
3221
|
+
if (!shared.commandCache.has(cacheKey)) {
|
|
3222
|
+
shared.commandCache.set(cacheKey, resolveCommandPath(cmd, process.env, { cwd }))
|
|
3223
|
+
}
|
|
3224
|
+
return shared.commandCache.get(cacheKey)
|
|
3225
|
+
}
|
|
3226
|
+
|
|
3227
|
+
const target = installedDir(rec.name)
|
|
3228
|
+
const installed = existsSync(target)
|
|
3229
|
+
if (installed && !PLUGIN_LOCKS.has(rec.name)) {
|
|
3230
|
+
const skillsDir = join(target, 'skills')
|
|
3231
|
+
try {
|
|
3232
|
+
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
3233
|
+
if (
|
|
3234
|
+
entry.isDirectory() &&
|
|
3235
|
+
entry.name !== 'skills' &&
|
|
3236
|
+
entry.name !== 'commands' &&
|
|
3237
|
+
entry.name !== 'agents' &&
|
|
3238
|
+
entry.name !== '.agents' &&
|
|
3239
|
+
entry.name !== 'node_modules' &&
|
|
3240
|
+
entry.name !== '.git'
|
|
3241
|
+
) {
|
|
3242
|
+
const sMd = join(target, entry.name, 'SKILL.md')
|
|
3243
|
+
if (existsSync(sMd) && !existsSync(join(skillsDir, entry.name))) {
|
|
3244
|
+
const subDir = join(skillsDir, entry.name)
|
|
3245
|
+
mkdirSync(subDir, { recursive: true })
|
|
3246
|
+
copyDir(join(target, entry.name), subDir)
|
|
2532
3247
|
}
|
|
2533
3248
|
}
|
|
2534
3249
|
}
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
3250
|
+
} catch {}
|
|
3251
|
+
}
|
|
3252
|
+
const targetManifest = installed ? readPluginManifest(target) : null
|
|
3253
|
+
const connectors = installed ? getPluginConnectors(target, targetManifest).map((c) => {
|
|
3254
|
+
const needsAuth = connectorRequiresAuth(c)
|
|
3255
|
+
const savedEntry = getPatchEntries().get(getConnectorId(rec.name, c.name))
|
|
3256
|
+
const toolsKey = `${rec.name}::${c.name}`
|
|
3257
|
+
const toolState = () => getToolsState()[toolsKey]
|
|
3258
|
+
const authenticated = connectorAuthenticated(c, savedEntry)
|
|
3259
|
+
const connected = connectorActive(savedEntry, () => authenticated, toolState)
|
|
3260
|
+
const toolStateObj = toolState()
|
|
3261
|
+
const storedTemplate = toolStateObj?.savedConnectorTemplate
|
|
3262
|
+
const storedDefinition = toolStateObj?.savedConnectorDefinition
|
|
3263
|
+
const savedConfig = savedEntry?.config || storedDefinition || {}
|
|
3264
|
+
const remote = remoteConfigFromEntry(savedConfig) || (!savedEntry ? toolStateObj?.savedOAuthRemoteConfig : null)
|
|
3265
|
+
const editableUrl = remote ? remote.url : (storedTemplate?.url ?? storedDefinition?.url ?? c.url ?? savedConfig.url ?? null)
|
|
3266
|
+
const editableCmd = remote ? null : (storedTemplate?.command ?? storedDefinition?.command ?? c.command ?? savedConfig.command ?? null)
|
|
3267
|
+
const editableArgs = remote ? [] : (storedTemplate?.args ?? storedDefinition?.args ?? c.args ?? savedConfig.args ?? [])
|
|
3268
|
+
const hasStoredTplCwd = !!(storedTemplate && 'cwd' in storedTemplate)
|
|
3269
|
+
const hasStoredDefCwd = !!(storedDefinition && 'cwd' in storedDefinition)
|
|
3270
|
+
const rawCwd = hasStoredTplCwd
|
|
3271
|
+
? storedTemplate.cwd
|
|
3272
|
+
: (hasStoredDefCwd ? storedDefinition.cwd : c.cwd)
|
|
3273
|
+
const editableCwd = remote ? null : (rawCwd ?? null)
|
|
3274
|
+
const editableEnv = remote ? {} : stripSyntheticRuntimeEnv(
|
|
3275
|
+
storedTemplate?.env ?? storedDefinition?.env ?? c.env ?? savedConfig.env ?? {},
|
|
3276
|
+
rec.name,
|
|
3277
|
+
target,
|
|
3278
|
+
)
|
|
3279
|
+
const dataDir = pluginDataDir(rec.name)
|
|
3280
|
+
const expandedManifestHeaders = expandPluginVars(c.headers || {}, target, dataDir)
|
|
3281
|
+
const sortHeaders = (obj) => JSON.stringify(Object.entries(obj || {}).sort(([a], [b]) => a.localeCompare(b)))
|
|
3282
|
+
const hasCustomPatchHeaders = Boolean(
|
|
3283
|
+
savedConfig.headers
|
|
3284
|
+
&& Object.keys(savedConfig.headers).length > 0
|
|
3285
|
+
&& sortHeaders(savedConfig.headers) !== sortHeaders(expandedManifestHeaders),
|
|
3286
|
+
)
|
|
3287
|
+
const editableHeaders = remote
|
|
3288
|
+
? remote.headers
|
|
3289
|
+
: (storedTemplate?.headers ?? storedDefinition?.headers ?? (hasCustomPatchHeaders ? savedConfig.headers : undefined) ?? c.headers ?? {})
|
|
3290
|
+
const savedTransport = remote ? 'http' : connectorTransport(
|
|
3291
|
+
storedTemplate?.transport || storedTemplate?.type || savedConfig.transport || savedConfig.type,
|
|
3292
|
+
editableUrl,
|
|
3293
|
+
editableCmd,
|
|
3294
|
+
)
|
|
3295
|
+
const savedClient = remote?.oauth === 'custom' ? readSavedOAuthClient(rec.name, c.name, editableUrl, remote.oauth) : null
|
|
3296
|
+
const oauthAuthenticated = isOAuthConnectorAuthenticated(rec.name, c.name, remote, getToolsState())
|
|
3297
|
+
const disp = resolveConnectorDisplay({
|
|
3298
|
+
url: editableUrl,
|
|
3299
|
+
command: editableCmd,
|
|
3300
|
+
args: editableArgs,
|
|
3301
|
+
...(rawCwd !== undefined ? { cwd: rawCwd } : {}),
|
|
3302
|
+
}, target, dataDir)
|
|
2548
3303
|
|
|
2549
|
-
return {
|
|
2550
|
-
...c,
|
|
2551
|
-
type: savedTransport,
|
|
2552
|
-
url: savedUrl,
|
|
2553
|
-
headers: savedHeaders,
|
|
2554
|
-
env: savedEnv,
|
|
2555
|
-
args: savedArgs,
|
|
2556
|
-
oauth: remote?.oauth || savedConfig.oauth || c.oauth || 'none',
|
|
2557
|
-
oauthClientId: savedClient?.clientId || '',
|
|
2558
|
-
oauthHasClientSecret: savedClient?.hasClientSecret || false,
|
|
2559
|
-
oauthCallbackPort: remote?.oauthCallbackPort || '',
|
|
2560
|
-
oauthScope: remote?.oauthScope || '',
|
|
2561
|
-
needsAuth,
|
|
2562
|
-
authenticated,
|
|
2563
|
-
enabled: !!savedEntry,
|
|
2564
|
-
connected,
|
|
2565
|
-
}
|
|
2566
|
-
}) : []
|
|
2567
|
-
let lspServers = listLspServers(targetManifest)
|
|
2568
|
-
// Auto-activate: if an LSP server's binary is now on PATH but the entry
|
|
2569
|
-
// hasn't been written to cordis.patch.yml yet (e.g. the user installed the
|
|
2570
|
-
// binary after the plugin — registration was previously skipped because the
|
|
2571
|
-
// command was missing), register it on the spot. Registration is idempotent
|
|
2572
|
-
// and only writes the patch; it does not require a manual "Update" click.
|
|
2573
|
-
// DSH's HMR watches this patch file and re-applies the plugin tree within
|
|
2574
|
-
// ~1s, so the newly registered server becomes truly active immediately —
|
|
2575
|
-
// no DSH restart needed (verified against @deepseek-ai/dsh-app-boot's
|
|
2576
|
-
// `watchUserPatches`, which registers cordis.patch.yml with Cordis HMR).
|
|
2577
|
-
if (lspServers.length > 0) {
|
|
2578
|
-
const autoRegistered = lspServers.filter((s) => {
|
|
2579
|
-
if (isLspActive(rec.name, s.name)) return false
|
|
2580
|
-
// Honor an explicit removal: if we already auto-activated this server
|
|
2581
|
-
// once but it is no longer in the patch, the user (or a manual patch
|
|
2582
|
-
// edit) removed it deliberately — do not silently re-add it.
|
|
2583
|
-
if (autoActivatedLspServers.has(`${rec.name}::${s.name}`)) return false
|
|
2584
|
-
// Host packages must actually be in DSH's node_modules — otherwise
|
|
2585
|
-
// auto-registering would write a patch entry that DSH can't load.
|
|
2586
|
-
return !!s.command
|
|
2587
|
-
&& resolveCommandPath(s.command)
|
|
2588
|
-
&& Object.keys(s.extensionToLanguage || {}).length > 0
|
|
2589
|
-
})
|
|
2590
|
-
if (autoRegistered.length > 0) {
|
|
2591
|
-
for (const s of autoRegistered) {
|
|
2592
|
-
try {
|
|
2593
|
-
const r = registerLspServer(rec.name, s.name, s)
|
|
2594
|
-
if (r.ok) autoActivatedLspServers.add(`${rec.name}::${s.name}`)
|
|
2595
|
-
} catch {}
|
|
2596
|
-
}
|
|
2597
|
-
lspServers = listLspServers(target)
|
|
2598
|
-
}
|
|
2599
|
-
}
|
|
2600
|
-
lspServers = lspServers.map((s) => {
|
|
2601
|
-
const active = isLspActive(rec.name, s.name)
|
|
2602
|
-
// For inactive servers, surface *why*: a missing command is the only
|
|
2603
|
-
// reason registration fails that the UI can help the user resolve
|
|
2604
|
-
// (install the binary, then hit Update). Other reasons (missing
|
|
2605
|
-
// extensionToLanguage) are manifest bugs and don't need this hint.
|
|
2606
|
-
const missingCommand = !active && !!s.command && !resolveCommandPath(s.command)
|
|
2607
|
-
return { ...s, active, missingCommand }
|
|
2608
|
-
})
|
|
2609
|
-
// Author: the state record is written at install time, so installs made
|
|
2610
|
-
// before the marketplace reader learned to merge a plugin's own manifest
|
|
2611
|
-
// carry `author: null` forever. Fall back to the installed copy's manifest,
|
|
2612
|
-
// then to the live marketplace row, so those records self-heal on read.
|
|
2613
|
-
const marketRow = findMarketRowSync(rec.sourceId, rec.name)
|
|
2614
|
-
// The browse list and the connector rows render the same plugin through the
|
|
2615
|
-
// same icon component, so they must be handed the same identity fields the
|
|
2616
|
-
// detail page merges in. Without these a plugin whose manifest declares no
|
|
2617
|
-
// icon falls back to "author name as a GitHub handle" and shows a stranger's
|
|
2618
|
-
// avatar while its own page shows the real logo.
|
|
2619
|
-
const identity = installedPluginIconIdentity(rec, installed ? target : undefined, targetManifest, marketRow)
|
|
2620
|
-
const detail = installed ? {
|
|
2621
|
-
icons: identity.icons,
|
|
2622
|
-
skills: listSkills(target, targetManifest),
|
|
2623
|
-
agents: listAgents(target, targetManifest),
|
|
2624
|
-
prompts: listPrompts(target, targetManifest),
|
|
2625
|
-
connectors,
|
|
2626
|
-
hooks: listHooks(target, targetManifest),
|
|
2627
|
-
lspServers,
|
|
2628
|
-
version: targetManifest?.version ?? null,
|
|
2629
|
-
} : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
|
|
2630
3304
|
return {
|
|
2631
|
-
...
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
3305
|
+
...c,
|
|
3306
|
+
type: savedTransport,
|
|
3307
|
+
command: editableCmd,
|
|
3308
|
+
url: editableUrl,
|
|
3309
|
+
...(editableCwd !== null ? { cwd: editableCwd } : {}),
|
|
3310
|
+
headers: editableHeaders,
|
|
3311
|
+
env: editableEnv,
|
|
3312
|
+
args: editableArgs,
|
|
3313
|
+
...disp,
|
|
3314
|
+
oauth: remote?.oauth || savedConfig.oauth || c.oauth || 'none',
|
|
3315
|
+
oauthClientId: savedClient?.clientId || '',
|
|
3316
|
+
oauthHasClientSecret: savedClient?.hasClientSecret || false,
|
|
3317
|
+
oauthCallbackPort: remote?.oauthCallbackPort || '',
|
|
3318
|
+
oauthScope: remote?.oauthScope || '',
|
|
3319
|
+
configured: !!(savedEntry || storedDefinition || storedTemplate || remote),
|
|
3320
|
+
needsAuth,
|
|
3321
|
+
authenticated,
|
|
3322
|
+
oauthAuthenticated,
|
|
3323
|
+
enabled: !!savedEntry,
|
|
3324
|
+
connected,
|
|
3325
|
+
pending: MCP_ACTIVATIONS.has(toolsKey) || MCP_TOOLS_INFLIGHT.get(toolsKey)?.forceFresh === true,
|
|
3326
|
+
}
|
|
3327
|
+
}) : []
|
|
3328
|
+
let lspServers = installed ? listLspServers(target, targetManifest) : []
|
|
3329
|
+
const lspDataDir = pluginDataDir(rec.name)
|
|
3330
|
+
// Auto-activate only while plugin is enabled; disabled plugins must stay unregistered.
|
|
3331
|
+
if (rec.enabled !== false && lspServers.length > 0) {
|
|
3332
|
+
const patchEntries = getPatchEntries()
|
|
3333
|
+
const autoRegistered = lspServers.filter((s) => {
|
|
3334
|
+
if (patchEntries.has(getLspServerId(rec.name, s.name))) return false
|
|
3335
|
+
if (autoActivatedLspServers.has(`${rec.name}::${s.name}`)) return false
|
|
3336
|
+
const resolvedLspCmd = s.command ? resolvePluginCommand(s.command, target, lspDataDir) : null
|
|
3337
|
+
return !!resolvedLspCmd
|
|
3338
|
+
&& resolveCmdCached(resolvedLspCmd, target)
|
|
3339
|
+
&& Object.keys(s.extensionToLanguage || {}).length > 0
|
|
3340
|
+
})
|
|
3341
|
+
if (autoRegistered.length > 0) {
|
|
3342
|
+
try {
|
|
3343
|
+
const activated = withCordisPatchBatch(() => autoRegistered
|
|
3344
|
+
.filter(s => registerLspServer(rec.name, s.name, s).ok))
|
|
3345
|
+
for (const s of activated) autoActivatedLspServers.add(`${rec.name}::${s.name}`)
|
|
3346
|
+
shared.patchEntries = null
|
|
3347
|
+
} catch {
|
|
3348
|
+
// Detail and /state remain readable, and the next read can retry.
|
|
3349
|
+
}
|
|
2647
3350
|
}
|
|
3351
|
+
}
|
|
3352
|
+
const currentPatchEntries = lspServers.length > 0 ? getPatchEntries() : null
|
|
3353
|
+
lspServers = lspServers.map((s) => {
|
|
3354
|
+
const active = Boolean(currentPatchEntries?.has(getLspServerId(rec.name, s.name)))
|
|
3355
|
+
const resolvedLspCmd = s.command ? resolvePluginCommand(s.command, target, lspDataDir) : null
|
|
3356
|
+
const missingCommand = !active && !!resolvedLspCmd && !resolveCmdCached(resolvedLspCmd, target)
|
|
3357
|
+
return { ...s, active, missingCommand }
|
|
2648
3358
|
})
|
|
3359
|
+
// Author: the state record is written at install time, so installs made
|
|
3360
|
+
// before the marketplace reader learned to merge a plugin's own manifest
|
|
3361
|
+
// carry `author: null` forever. Fall back to the installed copy's manifest,
|
|
3362
|
+
// then to the live marketplace row, so those records self-heal on read.
|
|
3363
|
+
const marketRow = findMarketRowSync(rec.sourceId, rec.name)
|
|
3364
|
+
// The browse list and the connector rows render the same plugin through the
|
|
3365
|
+
// same icon component, so they must be handed the same identity fields the
|
|
3366
|
+
// detail page merges in. Without these a plugin whose manifest declares no
|
|
3367
|
+
// icon falls back to "author name as a GitHub handle" and shows a stranger's
|
|
3368
|
+
// avatar while its own page shows the real logo.
|
|
3369
|
+
const identity = installedPluginIconIdentity(rec, installed ? target : undefined, targetManifest, marketRow)
|
|
3370
|
+
const detail = installed ? {
|
|
3371
|
+
icons: identity.icons,
|
|
3372
|
+
skills: listSkills(target, targetManifest),
|
|
3373
|
+
agents: listAgents(target, targetManifest),
|
|
3374
|
+
prompts: listPrompts(target, targetManifest),
|
|
3375
|
+
connectors,
|
|
3376
|
+
hooks: listHooks(target, targetManifest),
|
|
3377
|
+
lspServers,
|
|
3378
|
+
version: targetManifest?.version ?? null,
|
|
3379
|
+
} : { skills: [], agents: [], prompts: [], connectors: [], hooks: [], lspServers: [], version: null }
|
|
3380
|
+
const shortDescription = rec.shortDescription || (installed ? readPluginShortDescription(target) : '') || marketRow?.shortDescription || ''
|
|
3381
|
+
return {
|
|
3382
|
+
...rec,
|
|
3383
|
+
...detail,
|
|
3384
|
+
displayName: rec.displayName || targetManifest?.displayName || marketRow?.displayName || formatDisplayName(rec.name),
|
|
3385
|
+
description: rec.description || targetManifest?.description || marketRow?.description || '',
|
|
3386
|
+
...(shortDescription ? { shortDescription } : {}),
|
|
3387
|
+
author: identity.author,
|
|
3388
|
+
// Identity fields the icon chain reads. The detail page already merges
|
|
3389
|
+
// these from the marketplace row before rendering, which is why the same
|
|
3390
|
+
// plugin showed one icon inline and another on its own page.
|
|
3391
|
+
homepage: identity.homepage,
|
|
3392
|
+
source: identity.source,
|
|
3393
|
+
skillCount: detail.skills.length,
|
|
3394
|
+
agentCount: detail.agents.length,
|
|
3395
|
+
promptCount: detail.prompts.length,
|
|
3396
|
+
connectorCount: connectors.length,
|
|
3397
|
+
hookCount: detail.hooks.length,
|
|
3398
|
+
lspServerCount: lspServers.length,
|
|
3399
|
+
dir: target,
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
|
|
3403
|
+
/** Re-exported for routes: get single installed plugin with details. */
|
|
3404
|
+
export function installedPluginDetail(pluginName) {
|
|
3405
|
+
const rec = readState().plugins.find((p) => p.name === pluginName)
|
|
3406
|
+
if (!rec) return null
|
|
3407
|
+
return buildInstalledPluginDetail(rec, { commandCache: new Map() })
|
|
3408
|
+
}
|
|
3409
|
+
|
|
3410
|
+
/** Re-exported for routes: list installed plugins with details. */
|
|
3411
|
+
export function installedDetails() {
|
|
3412
|
+
const state = readState()
|
|
3413
|
+
const shared = { commandCache: new Map() }
|
|
3414
|
+
return state.plugins.map((rec) => buildInstalledPluginDetail(rec, shared))
|
|
2649
3415
|
}
|