universal-plugin-hub 1.0.45 → 1.1.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.
@@ -15,7 +15,7 @@ import {
15
15
  PromptListChangedNotificationSchema,
16
16
  } from '@modelcontextprotocol/sdk/types.js'
17
17
  import { decodeOAuthConfig } from './oauth-config.js'
18
- import { readOAuthRecord, writeOAuthRecord } from './oauth-store.js'
18
+ import { openOAuthRecordWriter, readOAuthRecord } from './oauth-store.js'
19
19
 
20
20
  const interactive = process.env.UPH_MCP_INTERACTIVE === '1'
21
21
  const verifying = process.env.UPH_MCP_VERIFY === '1'
@@ -102,8 +102,13 @@ function waitForCallback() {
102
102
  }
103
103
 
104
104
  function provider() {
105
- let record = readOAuthRecord(config.credentialKey)
106
- const persist = () => writeOAuthRecord(config.credentialKey, record)
105
+ const writer = openOAuthRecordWriter(config.credentialKey)
106
+ if (!writer) throw new Error('OAuth 授权已移除,请重新登录。')
107
+ process.once('exit', () => { try { writer.close() } catch {} })
108
+ const record = readOAuthRecord(config.credentialKey)
109
+ const persist = () => {
110
+ if (!writer.write(record)) throw new Error('OAuth 授权已移除,请重新登录。')
111
+ }
107
112
  const callback = callbackUrl || record.clientInformation?.redirect_uris?.[0] || `http://localhost:${config.oauth.callbackPort || 0}/callback`
108
113
  const custom = config.oauth.mode === 'custom' ? record.customClient : undefined
109
114
  return {
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
2
2
  import { dirname, join } from 'node:path'
3
3
  import { execFileSync } from 'node:child_process'
4
4
  import { randomBytes } from 'node:crypto'
@@ -52,22 +52,62 @@ export function readOAuthRecord(key) {
52
52
  }
53
53
  }
54
54
 
55
- export function writeOAuthRecord(key, record) {
56
- const file = oauthCredentialPath(key)
57
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
55
+ function writeRecord(file, record, stagingDir) {
58
56
  const plainText = JSON.stringify(record)
59
57
  const stored = process.platform === 'win32'
60
58
  ? { version: 1, dpapi: true, data: protectDpapi(plainText) }
61
59
  : JSON.parse(plainText)
62
- const tmp = join(dirname(file), `.${process.pid}.${randomBytes(8).toString('hex')}.tmp`)
63
- writeFileSync(tmp, JSON.stringify(stored), { mode: 0o600 })
64
- renameSync(tmp, file)
65
- try { if (process.platform !== 'win32') writeFileSync(file, JSON.stringify(stored), { mode: 0o600 }) } catch {}
60
+ const tmp = join(stagingDir, `.${process.pid}.${randomBytes(8).toString('hex')}.tmp`)
61
+ try {
62
+ writeFileSync(tmp, JSON.stringify(stored), { mode: 0o600 })
63
+ renameSync(tmp, file)
64
+ } finally {
65
+ rmSync(tmp, { force: true })
66
+ }
66
67
  // Seed the read cache with what was just written: no pwsh round trip, and a
67
68
  // concurrent reader can never see the previous version.
68
69
  RECORD_CACHE.set(file, { raw: JSON.stringify(stored), record })
69
70
  }
70
71
 
72
+ export function allowOAuthRecordWrites(key) {
73
+ rmSync(`${oauthCredentialPath(key)}.revoked`, { force: true })
74
+ }
75
+
76
+ export function writeOAuthRecord(key, record) {
77
+ const file = oauthCredentialPath(key)
78
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
79
+ allowOAuthRecordWrites(key)
80
+ writeRecord(file, record, dirname(file))
81
+ }
82
+
83
+ /** A running bridge can publish only while its private staging directory exists. */
84
+ export function openOAuthRecordWriter(key) {
85
+ const file = oauthCredentialPath(key)
86
+ const revoked = `${file}.revoked`
87
+ if (existsSync(revoked)) return null
88
+ const root = `${file}.writers`
89
+ mkdirSync(root, { recursive: true, mode: 0o700 })
90
+ const directory = mkdtempSync(join(root, 'bridge-'))
91
+ const close = () => rmSync(directory, { recursive: true, force: true })
92
+ if (existsSync(revoked)) {
93
+ close()
94
+ return null
95
+ }
96
+ return {
97
+ write(record) {
98
+ if (!existsSync(directory) || existsSync(revoked)) return false
99
+ try {
100
+ writeRecord(file, record, directory)
101
+ return true
102
+ } catch (error) {
103
+ if (error.code === 'ENOENT' && !existsSync(directory)) return false
104
+ throw error
105
+ }
106
+ },
107
+ close,
108
+ }
109
+ }
110
+
71
111
  export function saveOAuthClientCredentials(key, client) {
72
112
  const record = readOAuthRecord(key)
73
113
  const sameClient = record.customClient?.client_id === String(client.clientId || '').trim()
@@ -90,8 +130,18 @@ export function saveOAuthClientCredentials(key, client) {
90
130
  * removed: leaving the file behind would resurrect a stale sign-in if a server
91
131
  * of the same name were added again with the same URL and OAuth mode.
92
132
  */
93
- export function deleteOAuthRecord(key) {
133
+ export function deleteOAuthRecord(key, { required = false, ifPresent = false } = {}) {
94
134
  const file = oauthCredentialPath(key)
95
135
  RECORD_CACHE.delete(file)
96
- try { rmSync(file, { force: true }) } catch {}
136
+ try {
137
+ if (ifPresent && !existsSync(file) && !existsSync(`${file}.writers`)) return
138
+ // Block new bridges first. Removing the old bridges' staging directories
139
+ // prevents even a refresh already in progress from publishing after cleanup.
140
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
141
+ writeFileSync(`${file}.revoked`, '', { mode: 0o600 })
142
+ rmSync(`${file}.writers`, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
143
+ rmSync(file, { force: true })
144
+ } catch (error) {
145
+ if (required) throw error
146
+ }
97
147
  }
package/src/oauth.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { fileURLToPath } from 'node:url'
3
3
  import { encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
4
- import { readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
4
+ import { allowOAuthRecordWrites, readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
5
5
 
6
6
  const sessions = new Map()
7
7
  const bridgePath = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
@@ -107,6 +107,7 @@ function startProcess(session) {
107
107
 
108
108
  export function beginOAuthVerification(pluginName, connectorName, payload, options = {}) {
109
109
  const credentialKey = oauthCredentialKey(pluginName, connectorName, payload.url, payload.oauth)
110
+ allowOAuthRecordWrites(credentialKey)
110
111
  const config = oauthRuntimeConfig({
111
112
  url: payload.url, headers: payload.headers,
112
113
  oauth: connectorOauthSettings(pluginName, connectorName, payload), credentialKey,
@@ -117,7 +118,8 @@ export function beginOAuthVerification(pluginName, connectorName, payload, optio
117
118
  let resolve
118
119
  const completion = new Promise((r) => { resolve = r })
119
120
  const session = {
120
- id, pluginName, connectorName, credentialKey, config, status: 'starting', startedAt: Date.now(), resolve, completion,
121
+ id, pluginName, connectorName, credentialKey, config, pluginOwned: options.pluginOwned,
122
+ status: 'starting', startedAt: Date.now(), resolve, completion,
121
123
  noBrowser: options.noBrowser || process.env.UPH_MCP_NO_BROWSER === '1', callbackTimeout: options.callbackTimeout, onFinished: options.onFinished,
122
124
  timeout: setTimeout(() => cancelOAuthVerification(id, '授权等待超时,请重新测试'), options.callbackTimeout || CALLBACK_TIMEOUT),
123
125
  }
@@ -151,6 +153,30 @@ export function cancelAllOAuthVerifications() {
151
153
  for (const session of sessions.values()) if (!session.done) cancelOAuthVerification(session.id)
152
154
  }
153
155
 
156
+ /** Stop pending verification for a plugin before removing its credentials. */
157
+ export function cancelPluginOAuthVerifications(pluginName, ownsConnector = () => true) {
158
+ const pending = []
159
+ for (const session of sessions.values()) {
160
+ if (session.pluginName !== pluginName) continue
161
+ if (pluginName === 'user-mcp' && (!session.pluginOwned || !ownsConnector(session.connectorName))) continue
162
+ session.cancelled = true
163
+ const child = session.child
164
+ if (child?.pid && child.exitCode === null && child.signalCode === null) {
165
+ pending.push(new Promise(resolve => child.once('close', resolve)))
166
+ // Do not leave the callback or a token exchange running during cleanup.
167
+ child.kill('SIGKILL')
168
+ }
169
+ finish(session, { ok: false, message: '插件已卸载,授权已取消' })
170
+ }
171
+ return pending.length ? Promise.all(pending) : null
172
+ }
173
+
174
+ export function standaloneOAuthConnectorNames() {
175
+ return [...sessions.values()]
176
+ .filter(session => session.pluginName === 'user-mcp' && !session.pluginOwned)
177
+ .map(session => session.connectorName)
178
+ }
179
+
154
180
  export function oauthSessionStatusUrl(pluginName, connectorName, sessionId, userMcp = false) {
155
181
  return userMcp
156
182
  ? `/mcps/oauth-status?sessionId=${encodeURIComponent(sessionId)}`
package/src/parser.js CHANGED
@@ -66,6 +66,23 @@ function extractMdDescription(text) {
66
66
  return ''
67
67
  }
68
68
 
69
+ // Presentation only: read Codex's card copy without changing which manifest
70
+ // owns the plugin's description, components, or installation behavior.
71
+ function readPluginShortDescription(dir) {
72
+ if (!dir) return ''
73
+ const text = value => typeof value === 'string' ? value.trim() : ''
74
+ try {
75
+ const root = JSON.parse(readFileSync(join(dir, 'plugin.json'), 'utf8'))
76
+ const openai = root?.extensions?.['com.openai']
77
+ // An inline OpenAI extension replaces the compatibility overlay entirely.
78
+ if (openai && typeof openai === 'object' && !Array.isArray(openai)) return text(openai.interface?.shortDescription)
79
+ } catch {}
80
+ try {
81
+ const codex = JSON.parse(readFileSync(join(dir, '.codex-plugin', 'plugin.json'), 'utf8'))
82
+ return text(codex?.interface?.shortDescription)
83
+ } catch { return '' }
84
+ }
85
+
69
86
  function normalizeRow(row, sourceId, dir) {
70
87
  if (!row) return null
71
88
  const name = typeof row.name === 'string' ? row.name : (typeof row.identifier === 'string' ? row.identifier : '')
@@ -81,6 +98,8 @@ function normalizeRow(row, sourceId, dir) {
81
98
  const description = typeof row.description === 'string'
82
99
  ? row.description
83
100
  : (row.interface?.shortDescription || meta.description || '')
101
+ const shortDescription = readPluginShortDescription(dir)
102
+ || (typeof row.interface?.shortDescription === 'string' ? row.interface.shortDescription.trim() : '')
84
103
 
85
104
  const source = row.source?.source === 'local' ? row.source.path : (row.source || './')
86
105
  if (row.source?.source === 'local' && (typeof source !== 'string' || !source.startsWith('./'))) return null
@@ -91,6 +110,7 @@ function normalizeRow(row, sourceId, dir) {
91
110
  name: cleanName,
92
111
  displayName,
93
112
  description,
113
+ ...(shortDescription ? { shortDescription } : {}),
94
114
  author: typeof author === 'string' ? author : (meta.author || undefined),
95
115
  version: typeof row.version === 'string' ? row.version : (meta.version || undefined),
96
116
  category: typeof row.category === 'string' ? row.category : (meta.category || undefined),
@@ -103,13 +123,16 @@ function normalizeRow(row, sourceId, dir) {
103
123
  }
104
124
 
105
125
  const MARKETPLACE_CACHE = new Map()
126
+ const MARKETPLACE_SELECTION_CACHE = new Map()
106
127
  const MARKETPLACE_CACHE_TTL = 30000 // 30 seconds
107
128
 
108
129
  export function invalidateMarketplaceCache(sourceId) {
109
130
  if (sourceId) {
110
131
  MARKETPLACE_CACHE.delete(sourceId)
132
+ MARKETPLACE_SELECTION_CACHE.delete(sourceId)
111
133
  } else {
112
134
  MARKETPLACE_CACHE.clear()
135
+ MARKETPLACE_SELECTION_CACHE.clear()
113
136
  }
114
137
  }
115
138
 
@@ -117,7 +140,7 @@ export function invalidateMarketplaceCache(sourceId) {
117
140
  * Universal Marketplace Reader.
118
141
  * Inspects a source repository cache and extracts all discoverable plugins.
119
142
  */
120
- export function readMarketplace(sourceId) {
143
+ export function readMarketplace(sourceId, names) {
121
144
  safeSegment(sourceId, 'source id')
122
145
  const cache = sourceCacheDir(sourceId)
123
146
  if (!existsSync(cache)) return []
@@ -125,9 +148,17 @@ export function readMarketplace(sourceId) {
125
148
  const now = Date.now()
126
149
  const cached = MARKETPLACE_CACHE.get(sourceId)
127
150
  if (cached && (now - cached.time < MARKETPLACE_CACHE_TTL)) {
128
- return cached.data
151
+ return names ? cached.data.filter(row => names.has(row.name)) : cached.data
129
152
  }
130
153
 
154
+ if (names) {
155
+ const key = JSON.stringify([...names].sort())
156
+ const selection = MARKETPLACE_SELECTION_CACHE.get(sourceId)
157
+ if (selection?.key === key && now - selection.time < MARKETPLACE_CACHE_TTL) return selection.data
158
+ const data = parseMarketplaceFromDisk(sourceId, cache, names).filter(row => names.has(row.name))
159
+ MARKETPLACE_SELECTION_CACHE.set(sourceId, { key, time: now, data })
160
+ return data
161
+ }
131
162
  const rows = parseMarketplaceFromDisk(sourceId, cache)
132
163
  MARKETPLACE_CACHE.set(sourceId, { time: now, data: rows })
133
164
  return rows
@@ -178,7 +209,7 @@ export function parsePluginRowFromDir(entryDir, fallbackName, sourceId) {
178
209
  }, sourceId, entryDir)
179
210
  }
180
211
 
181
- export function parseMarketplaceFromDisk(sourceId, cache) {
212
+ export function parseMarketplaceFromDisk(sourceId, cache, names) {
182
213
  // 1. Check Multi-Plugin Manifest Candidates
183
214
  const manifestCandidates = [
184
215
  join(cache, '.claude-plugin', 'marketplace.json'),
@@ -201,22 +232,26 @@ export function parseMarketplaceFromDisk(sourceId, cache) {
201
232
  const content = JSON.parse(readFileSync(manifestPath, 'utf8'))
202
233
  // Case A: Claude / standard manifest with plugins array
203
234
  if (Array.isArray(content.plugins)) {
235
+ let skipped = false
204
236
  const rows = content.plugins.map((r) => {
205
237
  const source = r.source?.source === 'local' ? r.source.path : r.source
206
- let manifest = null
207
- let dir = null
208
- if (typeof source === 'string' && source.startsWith('./')) {
209
- dir = pluginPath(cache, source)
210
- } else if (source && typeof source === 'object' && r.name) {
238
+ let dir = typeof source === 'string' && source.startsWith('./') ? pluginPath(cache, source) : null
239
+ if (source && typeof source === 'object' && r.name) {
211
240
  dir = sourceRepositoryDir(cache, source) || pluginContentDir(sourceId, r.name, source, false)
212
241
  }
213
- if (dir) manifest = readPluginManifest(dir, false)
242
+ if (names && typeof r.name === 'string' && !names.has(r.name.toLowerCase())) {
243
+ skipped = true
244
+ return null
245
+ }
246
+ const manifest = dir ? readPluginManifest(dir, false) : null
214
247
  return normalizeRow({ ...manifest, ...r,
215
248
  displayName: r.displayName || r.interface?.displayName || manifest?.displayName,
216
249
  description: r.description || r.interface?.shortDescription || manifest?.description,
217
250
  }, sourceId, dir)
218
251
  }).filter(Boolean)
219
252
  if (rows.length > 0) return rows
253
+ // Preserve manifest precedence and discovery fallbacks on a miss.
254
+ if (skipped) return parseMarketplaceFromDisk(sourceId, cache)
220
255
  }
221
256
  // Case B: Direct array of plugin descriptors
222
257
  if (Array.isArray(content)) {
@@ -405,10 +440,12 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
405
440
  export function readPluginManifest(dir, includeParent = true) {
406
441
  const rootManifest = join(dir, 'plugin.json')
407
442
  let portable = false
408
- try {
409
- const root = JSON.parse(readFileSync(rootManifest, 'utf8'))
410
- portable = /^https:\/\/agent-plugins\.org\//.test(root.$schema || '') || Boolean(root.extensions?.['com.openai'])
411
- } catch {}
443
+ if (existsSync(rootManifest)) {
444
+ try {
445
+ const root = JSON.parse(readFileSync(rootManifest, 'utf8'))
446
+ portable = /^https:\/\/agent-plugins\.org\//.test(root.$schema || '') || Boolean(root.extensions?.['com.openai'])
447
+ } catch {}
448
+ }
412
449
  const candidates = [
413
450
  join(dir, '.claude-plugin', 'plugin.json'),
414
451
  ...(portable ? [rootManifest] : []),
@@ -474,7 +511,7 @@ export function readPluginManifest(dir, includeParent = true) {
474
511
  }
475
512
 
476
513
  /** List skill & command directories/files (skills/*, commands/*, root SKILL.md, .cursor/rules). */
477
- export function listSkills(dir) {
514
+ export function listSkills(dir, manifest = readPluginManifest(dir)) {
478
515
  const out = []
479
516
  const seen = new Set()
480
517
 
@@ -491,7 +528,6 @@ export function listSkills(dir) {
491
528
  }
492
529
 
493
530
  // 1. Check skills/ subdirectory
494
- const manifest = readPluginManifest(dir)
495
531
  const declaredSkills = typeof manifest?.skills === 'string' ? [manifest.skills] : (Array.isArray(manifest?.skills) ? manifest.skills.filter((s) => typeof s === 'string' && s.startsWith('./')) : [])
496
532
  const candidateSkillRoots = [...declaredSkills.map((p) => pluginPath(dir, p)), join(dir, 'skills'), join(dir, '..', 'skills')]
497
533
  for (const sRoot of candidateSkillRoots) {
@@ -604,7 +640,7 @@ export function listSkills(dir) {
604
640
  }
605
641
 
606
642
  /** List agent definition files (agents/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json). */
607
- export function listAgents(dir) {
643
+ export function listAgents(dir, manifest = readPluginManifest(dir)) {
608
644
  const out = []
609
645
  const seen = new Set()
610
646
 
@@ -702,7 +738,6 @@ export function listAgents(dir) {
702
738
  }
703
739
 
704
740
  // Check manifest "agents" array
705
- const manifest = readPluginManifest(dir)
706
741
  if (manifest && Array.isArray(manifest.agents)) {
707
742
  for (const item of manifest.agents) {
708
743
  const rawName = typeof item === 'string' ? item : item?.name
@@ -728,7 +763,7 @@ export function listAgents(dir) {
728
763
  }
729
764
 
730
765
  /** Prompt-ish entries: prompts/*.md|txt|yaml or plugin.json "prompts". */
731
- export function listPrompts(dir) {
766
+ export function listPrompts(dir, manifest = readPluginManifest(dir)) {
732
767
  const prompts = []
733
768
  const pRoots = [join(dir, 'prompts'), join(dir, '..', 'prompts')]
734
769
  for (const pRoot of pRoots) {
@@ -742,7 +777,6 @@ export function listPrompts(dir) {
742
777
  } catch {}
743
778
  }
744
779
  }
745
- const manifest = readPluginManifest(dir)
746
780
  if (manifest && Array.isArray(manifest.prompts)) {
747
781
  prompts.push(...manifest.prompts.map((p) => (typeof p === 'string' ? p : p.name)).filter(Boolean))
748
782
  }
@@ -804,8 +838,7 @@ export function parseHookConfig(raw, isJson) {
804
838
  * path first, then `hooks/hooks.json|yaml|yml`, then `*-hooks.{json,yaml}` files.
805
839
  * Returns null when the plugin declares no hook config (e.g. only scripts).
806
840
  */
807
- export function resolveHookConfigPath(dir) {
808
- const manifest = readPluginManifest(dir)
841
+ export function resolveHookConfigPath(dir, manifest = readPluginManifest(dir)) {
809
842
  if (manifest && typeof manifest.hooks === 'string') {
810
843
  const p = isAbsolute(manifest.hooks) ? manifest.hooks : join(dir, manifest.hooks)
811
844
  if (existsSync(p) && statSync(p).isFile()) return p
@@ -828,12 +861,12 @@ export function resolveHookConfigPath(dir) {
828
861
  }
829
862
 
830
863
  /** Hook entries: follow the plugin manifest's `hooks` config, then hooks/ config files. */
831
- export function listHooks(dir) {
864
+ export function listHooks(dir, manifest = readPluginManifest(dir)) {
832
865
  const hooks = []
833
866
  const seen = new Set()
834
867
  const add = (h) => { if (h && !seen.has(h)) { seen.add(h); hooks.push(h) } }
835
868
 
836
- const cfg = resolveHookConfigPath(dir)
869
+ const cfg = resolveHookConfigPath(dir, manifest)
837
870
  if (cfg) {
838
871
  try {
839
872
  const raw = readFileSync(cfg, 'utf8')
@@ -843,7 +876,6 @@ export function listHooks(dir) {
843
876
 
844
877
  // Manifest `hooks` as inline object/array (no file path to follow).
845
878
  if (hooks.length === 0) {
846
- const manifest = readPluginManifest(dir)
847
879
  if (manifest && manifest.hooks) {
848
880
  if (Array.isArray(manifest.hooks)) {
849
881
  for (const h of manifest.hooks) add(typeof h === 'string' ? h : (h && h.name))
@@ -879,7 +911,7 @@ export function isRemoteTransportName(type) {
879
911
  }
880
912
 
881
913
  /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcp" / "connectors". */
882
- export function listConnectors(dir) {
914
+ export function listConnectors(dir, manifest = readPluginManifest(dir)) {
883
915
  const connectors = []
884
916
  const seen = new Set()
885
917
 
@@ -928,7 +960,6 @@ export function listConnectors(dir) {
928
960
  }
929
961
  }
930
962
 
931
- const manifest = readPluginManifest(dir)
932
963
  if (manifest) {
933
964
  let dict = null
934
965
  if (manifest.mcpServers && typeof manifest.mcpServers === 'object') {
package/src/routes.js CHANGED
@@ -7,13 +7,13 @@ import { existsSync } from 'node:fs'
7
7
  import { join } from 'node:path'
8
8
  import { sendJson, readJsonBody, sameOrigin } from './http.js'
9
9
  import {
10
- readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir,
10
+ readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir, removeManagedDir, sourceCacheDir,
11
11
  } from './store.js'
12
12
  import { ensureSourceCloned, pullSource, safeSegment, materializePlugin } from './market.js'
13
13
  import { readMarketplace, pluginDetail, pluginContentDir, invalidateMarketplaceCache } from './parser.js'
14
14
  import { getOrFetchIcon, readLocalIcon } from './icons.js'
15
15
  import {
16
- installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
16
+ installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered, toolCallIconGroups,
17
17
  toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
18
18
  fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
19
19
  } from './install.js'
@@ -82,6 +82,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
82
82
  }
83
83
 
84
84
  // ── state ────────────────────────────────────────────────────────────
85
+ if (method === 'GET' && path === '/tool-call-icons') {
86
+ return sendJson(res, 200, { groups: toolCallIconGroups() })
87
+ }
88
+
85
89
  if (method === 'GET' && path === '/state') {
86
90
  const state = readState()
87
91
  const details = installedDetails()
@@ -332,6 +336,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
332
336
  if (source.builtin) throw new Error('内置源不可删除')
333
337
  const used = state.plugins.some((p) => p.sourceId === sourceId)
334
338
  if (used) throw new Error('该源下仍有已安装插件,请先卸载')
339
+ // The remote checkout pool is shared by marketplaces. Only remove this
340
+ // source's own clone or uploaded marketplace copy.
341
+ if (sourceId !== 'remote') removeManagedDir(sourceCacheDir(sourceId))
335
342
  state.sources = state.sources.filter((s) => s.id !== sourceId)
336
343
  writeState(state)
337
344
  invalidateMarketplaceCache(sourceId)
@@ -352,11 +359,13 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
352
359
  }
353
360
  // Migrate legacy patch-only entries (saved before userMcps state existed)
354
361
  let changed = false
362
+ const pluginTools = state.plugins.some(plugin => plugin.name === 'user-mcp') ? readMcpToolsState() : null
355
363
  for (const block of patch) {
356
364
  if (!block || !Array.isArray(block.insert)) continue
357
365
  for (const item of block.insert) {
358
366
  if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
359
367
  const cfg = item.config || {}
368
+ if (pluginTools?.[`user-mcp::${cfg.serverName}`]?.pluginOAuthOwned && remoteConfigFromEntry(cfg)) continue
360
369
  if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
361
370
  state.userMcps.push(userMcpConfig(cfg.serverName, {
362
371
  transport: cfg.transport, url: cfg.url, command: cfg.command,
@@ -501,7 +510,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
501
510
  // ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
502
511
  if (method === 'GET' && path.startsWith('/mcps/') && path.endsWith('/tools')) {
503
512
  const name = safeSegment(normalizeMcpName(path.slice('/mcps/'.length, -'/tools'.length)), 'MCP 名称')
504
- const result = await fetchConnectorTools('user-mcp', name)
513
+ const result = await fetchConnectorTools('user-mcp', name, url.searchParams.get('fresh') === '1')
505
514
  return sendJson(res, 200, result)
506
515
  }
507
516
 
@@ -565,7 +574,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
565
574
  const pluginName = safeSegment(parts[0], 'plugin name')
566
575
  const connectorName = safeSegment(parts[2], 'connector name')
567
576
  const body = await readJsonBody(req)
568
- const result = await verifyConnectorAuth(pluginName, connectorName, body)
577
+ if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
578
+ return sendJson(res, 404, { ok: false, error: '插件未安装或已卸载' })
579
+ }
580
+ const result = await verifyConnectorAuth(pluginName, connectorName, body, { pluginOwned: true })
569
581
  return sendJson(res, 200, result)
570
582
  }
571
583
 
@@ -575,7 +587,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
575
587
  const pluginName = safeSegment(parts[0], 'plugin name')
576
588
  const connectorName = safeSegment(parts[2], 'connector name')
577
589
  const body = await readJsonBody(req)
578
- const result = saveConnectorAuth(pluginName, connectorName, body)
590
+ if (!readState().plugins.some(plugin => plugin.name === pluginName)) {
591
+ return sendJson(res, 404, { ok: false, error: '插件未安装或已卸载' })
592
+ }
593
+ const result = saveConnectorAuth(pluginName, connectorName, body, { pluginOwned: true })
579
594
  return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
580
595
  }
581
596
 
@@ -708,7 +723,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
708
723
  if (method === 'DELETE' && path.startsWith('/plugins/')) {
709
724
  requireSameOrigin(req)
710
725
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
711
- const result = uninstallPlugin(pluginName)
726
+ const result = await uninstallPlugin(pluginName)
712
727
  invalidateMarketplaceCache()
713
728
  return sendJson(res, 200, scheduledResult(result, applyProfile))
714
729
  }
package/src/store.js CHANGED
@@ -8,12 +8,21 @@
8
8
  */
9
9
  import { homedir } from 'node:os'
10
10
  import { dirname, join } from 'node:path'
11
- import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, rmSync } from 'node:fs'
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, lstatSync, rmSync, unlinkSync } from 'node:fs'
12
12
  import { execFileSync } from 'node:child_process'
13
13
 
14
14
  /** Robust directory deletion handling Windows readonly/locked files. */
15
- export function safeRmDir(dir) {
16
- if (!dir || !existsSync(dir)) return
15
+ export function safeRmDir(dir, { allowTrash = true } = {}) {
16
+ if (!dir) return
17
+ // A dangling junction is invisible to existsSync. Unlink junctions directly
18
+ // so the Windows directory fallbacks never operate on their targets.
19
+ let entry
20
+ try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch {}
21
+ if (entry?.isSymbolicLink()) {
22
+ unlinkSync(dir)
23
+ return
24
+ }
25
+ if (!entry && !existsSync(dir)) return
17
26
  try {
18
27
  rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
19
28
  return
@@ -28,6 +37,7 @@ export function safeRmDir(dir) {
28
37
  execFileSync('cmd.exe', ['/c', `rd /s /q "${dir}"`], { stdio: 'ignore', windowsHide: true })
29
38
  if (!existsSync(dir)) return
30
39
  } catch {}
40
+ if (!allowTrash) return
31
41
  try {
32
42
  const trash = `${dir}.trash-${Date.now()}`
33
43
  renameSync(dir, trash)
@@ -40,6 +50,14 @@ export function safeRmDir(dir) {
40
50
  }
41
51
  }
42
52
 
53
+ /** Remove managed files before forgetting the record needed to retry cleanup. */
54
+ export function removeManagedDir(dir) {
55
+ safeRmDir(dir, { allowTrash: false })
56
+ if (lstatSync(dir, { throwIfNoEntry: false })) {
57
+ throw Object.assign(new Error(`无法清理目录:${dir}`), { code: 'EBUSY', path: dir })
58
+ }
59
+ }
60
+
43
61
  let STATE_CACHE = null
44
62
  let STATE_CACHE_MTIME = 0
45
63
 
@@ -206,7 +224,8 @@ export function suggestSourceName(url) {
206
224
  const ownerLower = (owner || '').toLowerCase()
207
225
  const repoLower = (repo || '').toLowerCase()
208
226
 
209
- if (repoLower === 'claude-plugins-official' || ownerLower === 'anthropics') return 'Anthropic'
227
+ if (ownerLower === 'anthropics' && repoLower === 'knowledge-work-plugins') return 'Knowledge Work'
228
+ if (repoLower === 'claude-plugins-official') return 'Anthropic'
210
229
  if (repoLower === 'claude-plugins-community') return 'Community'
211
230
 
212
231
  const genericRepoNames = new Set([