universal-plugin-hub 1.3.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/market.js CHANGED
@@ -5,10 +5,11 @@
5
5
  * is derived from a slug validated with `safeSegment`. Errors carry a
6
6
  * user-facing message; network/git failures are retryable at the UI level.
7
7
  */
8
+ import { createHash } from 'node:crypto'
8
9
  import { execFile } from 'node:child_process'
9
- import { existsSync, mkdirSync, readFileSync } from 'node:fs'
10
- import { join, resolve, relative, isAbsolute } from 'node:path'
11
- import { sourceCacheDir, safeRmDir, readState } from './store.js'
10
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
+ import { dirname, join, resolve, relative, isAbsolute } from 'node:path'
12
+ import { sourceCacheDir, removeManagedDir, safeRmDir, readState } from './store.js'
12
13
 
13
14
  const SEGMENT_RE = /^[a-z0-9][a-z0-9._-]*$/i
14
15
 
@@ -49,9 +50,9 @@ export function normalizeRemotePluginSource(source) {
49
50
  if (!source || typeof source !== 'object' || Array.isArray(source)) return source
50
51
  if (source.source === 'github') {
51
52
  const repo = typeof source.repo === 'string' ? source.repo.trim().replace(/^\/+|\.git$/gi, '') : ''
52
- const url = typeof source.url === 'string' && source.url.trim()
53
- ? source.url.trim()
54
- : (SHORTHAND_REPO_RE.test(repo) ? `https://github.com/${repo}.git` : '')
53
+ let url = ''
54
+ if (typeof source.url === 'string' && source.url.trim()) url = source.url.trim()
55
+ else if (SHORTHAND_REPO_RE.test(repo)) url = `https://github.com/${repo}.git`
55
56
  return { ...source, ...(url ? { url } : {}) }
56
57
  }
57
58
  if (source.source === 'git-subdir' && typeof source.url === 'string') {
@@ -63,6 +64,17 @@ export function normalizeRemotePluginSource(source) {
63
64
  return source
64
65
  }
65
66
 
67
+ function readCheckoutOrigin(dir) {
68
+ try {
69
+ const config = readFileSync(join(dir, '.git', 'config'), 'utf8')
70
+ return config.match(/(?:^|\r?\n)\[remote "origin"\][^\n]*\r?\n([\s\S]*?)(?=\r?\n\[|$)/)?.[1]
71
+ .match(/^\s*url\s*=\s*(.+)$/m)?.[1].trim()
72
+ } catch (error) {
73
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error
74
+ return undefined
75
+ }
76
+ }
77
+
66
78
  /** A marketplace can point back to its own checkout (including a subdirectory). */
67
79
  export function sourceRepositoryDir(cache, source) {
68
80
  const resolved = normalizeRemotePluginSource(source)
@@ -74,8 +86,7 @@ export function sourceRepositoryDir(cache, source) {
74
86
  } catch { return null }
75
87
  }
76
88
  try {
77
- const config = readFileSync(join(cache, '.git', 'config'), 'utf8')
78
- const origin = config.match(/\[remote "origin"\]([^\[]*)/)?.[1].match(/^\s*url\s*=\s*(.+)$/m)?.[1].trim()
89
+ const origin = readCheckoutOrigin(cache)
79
90
  if (!origin || !repoKey(resolved.url) || repoKey(origin) !== repoKey(resolved.url)) return null
80
91
  const head = readFileSync(join(cache, '.git', 'HEAD'), 'utf8').trim()
81
92
  // Reuse only the requested revision; another branch is a different plugin snapshot.
@@ -105,11 +116,11 @@ function formatGitError(stderr, errorMsg) {
105
116
  return last.length > 50 ? last.slice(0, 48) + '…' : last
106
117
  }
107
118
 
108
- function runGit(args, cwd) {
119
+ function runGit(args, cwd, timeout) {
109
120
  return new Promise((resolve, reject) => {
110
- execFile('git', args, { cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
121
+ execFile('git', args, { cwd, timeout, maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
111
122
  if (error) {
112
- const detail = formatGitError(stderr, error.message)
123
+ const detail = error.killed && timeout ? 'Git 操作超时,请检查网络后重试' : formatGitError(stderr, error.message)
113
124
  reject(new Error(detail))
114
125
  return
115
126
  }
@@ -118,41 +129,61 @@ function runGit(args, cwd) {
118
129
  })
119
130
  }
120
131
 
132
+ function hasSourceCheckout(dir) {
133
+ const git = join(dir, '.git')
134
+ // Legacy clones wrote their first index after checking out the worktree.
135
+ return existsSync(join(git, 'uph-clone-complete')) || existsSync(join(git, 'index'))
136
+ }
137
+
138
+ async function cloneRepoToCache(dir, url, { branch, timeoutMs } = {}) {
139
+ const hadCheckout = hasSourceCheckout(dir)
140
+ if (hadCheckout && readCheckoutOrigin(dir) === url) return false
141
+
142
+ if (!hadCheckout) removeManagedDir(dir, { allowTrash: true })
143
+ const parent = dirname(dir)
144
+ mkdirSync(parent, { recursive: true })
145
+ const staging = mkdtempSync(join(parent, '.clone-'))
146
+ try {
147
+ const args = ['clone', '--depth', '1']
148
+ if (branch) args.push('--branch', String(branch))
149
+ args.push(url, staging)
150
+ await runGit(args, undefined, timeoutMs)
151
+ // Empty repositories can be cloned successfully without an index.
152
+ writeFileSync(join(staging, '.git', 'uph-clone-complete'), '')
153
+ // The slug can collide with an abandoned preview from another repository.
154
+ // Keep that checkout until the requested clone has completed successfully.
155
+ if (hadCheckout) removeManagedDir(dir, { deferCleanup: true })
156
+ renameSync(staging, dir)
157
+ return true
158
+ } finally {
159
+ safeRmDir(staging)
160
+ }
161
+ }
162
+
163
+ /** Derive a collision-free cache key for a remote plugin repository checkout. */
164
+ export function remoteCheckoutKey(url, ref = '') {
165
+ const identity = ref ? `${url}\0${ref}` : String(url)
166
+ const digest = createHash('sha256').update(identity).digest('hex').slice(0, 8)
167
+ return `${slugFromUrl(url)}-${digest}`
168
+ }
169
+
170
+ /** Resolve the cache directory for a materialized remote plugin repository. */
171
+ export function remoteCheckoutDir(url, ref = '') {
172
+ return join(sourceCacheDir('remote'), remoteCheckoutKey(url, ref))
173
+ }
174
+
121
175
  /** Clone a source repository into its cache dir (idempotent, concurrency-safe). */
122
- export async function ensureSourceCloned(sourceId, url) {
176
+ export async function ensureSourceCloned(sourceId, url, { onCloned } = {}) {
123
177
  safeSegment(sourceId, 'source id')
124
178
  const dir = sourceCacheDir(sourceId)
125
179
  if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(url || ''))) {
126
180
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
127
181
  return dir
128
182
  }
129
- if (existsSync(join(dir, '.git'))) return dir
183
+ if (hasSourceCheckout(dir) && readCheckoutOrigin(dir) === url) return dir
130
184
 
131
185
  return withGitLock(`src:${sourceId}`, async () => {
132
- // Another request may have completed the clone while we waited on the lock.
133
- if (existsSync(join(dir, '.git'))) return dir
134
-
135
- // Clean incomplete cache if previous clone failed
136
- if (existsSync(dir)) {
137
- try {
138
- safeRmDir(dir)
139
- } catch {
140
- // ignore rm error
141
- }
142
- }
143
-
144
- try {
145
- await runGit(['clone', '--depth', '1', url, dir])
146
- } catch (err) {
147
- if (existsSync(dir) && !existsSync(join(dir, '.git'))) {
148
- try {
149
- safeRmDir(dir)
150
- } catch {
151
- // ignore rm error
152
- }
153
- }
154
- throw err
155
- }
186
+ if (await cloneRepoToCache(dir, url, { timeoutMs: 120_000 })) onCloned?.()
156
187
  return dir
157
188
  })
158
189
  }
@@ -205,17 +236,11 @@ export async function materializePlugin(sourceId, pluginName, source, { refresh
205
236
  if (typeof normalized.url !== 'string' || !/^https?:\/\//.test(normalized.url)) {
206
237
  throw new Error(`plugin ${pluginName}: unsupported remote url`)
207
238
  }
208
- const remoteKey = slugFromUrl(normalized.url)
239
+ const remoteKey = remoteCheckoutKey(normalized.url, normalized.ref)
209
240
  const checkout = join(sourceCacheDir('remote'), remoteKey)
210
241
  await withGitLock(`remote:${remoteKey}`, async () => {
211
- if (!existsSync(join(checkout, '.git'))) {
212
- // --depth 1 keeps clones small; `ref` (branch/tag) is honored when
213
- // the marketplace pins one.
214
- const args = ['clone', '--depth', '1']
215
- if (normalized.ref) args.push('--branch', String(normalized.ref))
216
- args.push(normalized.url, checkout)
217
- await runGit(args)
218
- } else if (refresh) {
242
+ const cloned = await cloneRepoToCache(checkout, normalized.url, { branch: normalized.ref })
243
+ if (!cloned && refresh) {
219
244
  // The cached checkout is otherwise reused forever, so updates would
220
245
  // reinstall the first clone's commit. Re-fetch the tracked ref.
221
246
  const args = ['fetch', '--depth', '1', 'origin']
@@ -208,7 +208,6 @@ async function connectRemote() {
208
208
  async function proxyCapabilities(client, server) {
209
209
  const capabilities = client.getServerCapabilities() || {}
210
210
  if (capabilities.tools) {
211
- const tools = await client.listTools()
212
211
  server.setRequestHandler(ListToolsRequestSchema, (request) => client.listTools(request.params))
213
212
  server.setRequestHandler(CallToolRequestSchema, (request) => client.callTool(request.params))
214
213
  client.setNotificationHandler(ToolListChangedNotificationSchema, () => server.sendToolListChanged())
@@ -36,6 +36,10 @@ export function oauthRuntimeConfig(config) {
36
36
  }
37
37
  }
38
38
 
39
+ export function bridgeRuntimeEnv(env = {}, versions = process.versions) {
40
+ return versions?.electron ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : { ...env }
41
+ }
42
+
39
43
  export function remoteConfigFromEntry(config = {}) {
40
44
  const remote = decodeOAuthConfig(config.env?.UPH_MCP_REMOTE_CONFIG)
41
45
  if (!remote) return null
@@ -108,20 +108,37 @@ export function openOAuthRecordWriter(key) {
108
108
  }
109
109
  }
110
110
 
111
+ /**
112
+ * Block new bridges and remove existing staging directories so a concurrent or
113
+ * stale writer cannot republish superseded credentials.
114
+ */
115
+ function revokeOAuthWriters(file) {
116
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
117
+ writeFileSync(`${file}.revoked`, '', { mode: 0o600 })
118
+ rmSync(`${file}.writers`, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
119
+ }
120
+
111
121
  export function saveOAuthClientCredentials(key, client) {
112
- const record = readOAuthRecord(key)
113
- const sameClient = record.customClient?.client_id === String(client.clientId || '').trim()
122
+ const record = { ...readOAuthRecord(key) }
123
+ const nextClientId = String(client.clientId || '').trim()
124
+ const sameClient = record.customClient?.client_id === nextClientId
114
125
  const changedSecret = !!client.clientSecret && client.clientSecret !== record.customClient?.client_secret
115
126
  if (!sameClient || changedSecret) {
116
127
  delete record.tokens
117
128
  delete record.clientInformation
118
129
  delete record.discovery
119
130
  }
120
- record.customClient = {
121
- client_id: String(client.clientId || '').trim(),
122
- token_endpoint_auth_method: (client.clientSecret || (sameClient && record.customClient?.client_secret)) ? 'client_secret_post' : 'none',
123
- ...((client.clientSecret || (sameClient && record.customClient?.client_secret)) ? { client_secret: String(client.clientSecret || record.customClient?.client_secret) } : {}),
131
+ const nextSecret = client.clientSecret || (sameClient ? record.customClient?.client_secret : '')
132
+ const nextCustomClient = {
133
+ client_id: nextClientId,
134
+ token_endpoint_auth_method: nextSecret ? 'client_secret_post' : 'none',
135
+ ...(nextSecret ? { client_secret: String(nextSecret) } : {}),
136
+ }
137
+ if (sameClient && !changedSecret && JSON.stringify(record.customClient) === JSON.stringify(nextCustomClient)) {
138
+ return
124
139
  }
140
+ if (!sameClient || changedSecret) revokeOAuthWriters(oauthCredentialPath(key))
141
+ record.customClient = nextCustomClient
125
142
  writeOAuthRecord(key, record)
126
143
  }
127
144
 
@@ -135,11 +152,7 @@ export function deleteOAuthRecord(key, { required = false, ifPresent = false } =
135
152
  RECORD_CACHE.delete(file)
136
153
  try {
137
154
  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 })
155
+ revokeOAuthWriters(file)
143
156
  rmSync(file, { force: true })
144
157
  } catch (error) {
145
158
  if (required) throw error
package/src/oauth.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { fileURLToPath } from 'node:url'
3
- import { encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
3
+ import { bridgeRuntimeEnv, encodeOAuthConfig, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
4
4
  import { allowOAuthRecordWrites, readOAuthRecord, oauthStoreDir, saveOAuthClientCredentials } from './oauth-store.js'
5
5
 
6
6
  const sessions = new Map()
@@ -58,7 +58,7 @@ function finish(session, result) {
58
58
 
59
59
  function startProcess(session) {
60
60
  let stderrBuffer = ''
61
- const env = {
61
+ const env = bridgeRuntimeEnv({
62
62
  ...process.env,
63
63
  UPH_MCP_REMOTE_CONFIG: encodeOAuthConfig(session.config),
64
64
  UPH_OAUTH_STORE_DIR: oauthStoreDir(),
@@ -66,7 +66,7 @@ function startProcess(session) {
66
66
  UPH_MCP_VERIFY: '1',
67
67
  ...(session.noBrowser ? { UPH_MCP_NO_BROWSER: '1' } : {}),
68
68
  ...(session.callbackTimeout ? { UPH_OAUTH_CALLBACK_TIMEOUT_MS: String(session.callbackTimeout) } : {}),
69
- }
69
+ })
70
70
  const child = spawn(process.execPath, [bridgePath], { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
71
71
  session.child = child
72
72
  let stdout = ''
package/src/parser.js CHANGED
@@ -12,12 +12,17 @@ import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, copyFileSyn
12
12
  import { join, basename, dirname, isAbsolute, relative, resolve } from 'node:path'
13
13
  import { load as parseYaml } from 'js-yaml'
14
14
  import { sourceCacheDir, installedDir, pluginDataDir } from './store.js'
15
- import { safeSegment, pluginPath, sourceRepositoryDir, normalizeRemotePluginSource } from './market.js'
15
+ import { safeSegment, pluginPath, sourceRepositoryDir, normalizeRemotePluginSource, remoteCheckoutDir } from './market.js'
16
16
  import { parseAgentDefinition } from './agents-map.js'
17
17
  import { buildPluginIcons, touchLru, setLru } from './icons.js'
18
18
 
19
19
  const DIR_PARSER_CACHE = new Map()
20
20
  const DIR_PARSER_CACHE_TTL = 20000 // 20s TTL for file scanning
21
+ let PARSER_CACHE_REVISION = 0
22
+
23
+ export function parserCacheRevision() {
24
+ return PARSER_CACHE_REVISION
25
+ }
21
26
  const VALID_PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]*$/i
22
27
  const MANIFEST_CANDIDATE_PARTS = [
23
28
  ['.claude-plugin', 'marketplace.json'],
@@ -184,6 +189,7 @@ function resolveMarketplacePluginSource(rawSource, pluginRootMeta) {
184
189
 
185
190
  export function invalidateParserCaches() {
186
191
  DIR_PARSER_CACHE.clear()
192
+ PARSER_CACHE_REVISION += 1
187
193
  }
188
194
 
189
195
  export function formatDisplayName(name) {
@@ -231,7 +237,7 @@ function extractMdDescription(text) {
231
237
 
232
238
  // Presentation only: read Codex's card copy without changing which manifest
233
239
  // owns the plugin's description, components, or installation behavior.
234
- function readPluginShortDescription(dir) {
240
+ export function readPluginShortDescription(dir) {
235
241
  if (!dir) return ''
236
242
  const text = value => typeof value === 'string' ? value.trim() : ''
237
243
  try {
@@ -337,6 +343,7 @@ export function invalidateMarketplaceCache(sourceId) {
337
343
  MARKETPLACE_SELECTION_CACHE.clear()
338
344
  PLUGIN_DIR_INDEX_CACHE.clear()
339
345
  }
346
+ PARSER_CACHE_REVISION += 1
340
347
  }
341
348
 
342
349
  /**
@@ -802,6 +809,18 @@ export function parseMarketplaceFromDisk(sourceId, cache, names, options = {}) {
802
809
  return []
803
810
  }
804
811
 
812
+ /** Display metadata from the same marketplace formats used for listing. */
813
+ export function readMarketplaceName(cache) {
814
+ for (const parts of MANIFEST_CANDIDATE_PARTS) {
815
+ try {
816
+ const market = JSON.parse(readFileSync(join(cache, ...parts), 'utf8'))
817
+ if (!Array.isArray(market?.plugins) || !market.plugins.length) continue
818
+ return [market.displayName, market.title, market.name]
819
+ .find((value) => typeof value === 'string' && value.trim())?.trim()
820
+ } catch {}
821
+ }
822
+ }
823
+
805
824
  /** Resolve the directory that holds a plugin's content (cache or remote checkout). */
806
825
  export function pluginContentDir(sourceId, pluginName, source, preferInstalled = true) {
807
826
  safeSegment(sourceId, 'source id')
@@ -828,9 +847,7 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
828
847
  if (typeof remoteSrc.url === 'string' && remoteSrc.url) {
829
848
  const ownDir = sourceRepositoryDir(sourceCacheDir(sourceId), remoteSrc)
830
849
  if (ownDir) return ownDir
831
- const clean = String(remoteSrc.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
832
- const remoteKey = clean.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'repo'
833
- const checkout = join(sourceCacheDir('remote'), remoteKey)
850
+ const checkout = remoteCheckoutDir(remoteSrc.url, remoteSrc.ref)
834
851
  const dir = remoteSrc.path ? pluginPath(checkout, remoteSrc.path) : checkout
835
852
  return existsSync(dir) ? dir : null
836
853
  }
@@ -1000,10 +1017,14 @@ export function resolvePluginCommandEntries(dir, manifest = readPluginManifest(d
1000
1017
 
1001
1018
  const candidateCmdRoots = [
1002
1019
  join(dir, 'commands'),
1003
- join(dir, '..', 'commands'),
1004
1020
  join(dir, '.claude', 'commands'),
1005
- join(dir, '..', '.claude', 'commands'),
1006
1021
  ]
1022
+ // A Claude plugin manifest owns a package root. Siblings are often
1023
+ // implementations for other hosts, not capabilities of this plugin.
1024
+ if (!existsSync(join(dir, '.claude-plugin', 'plugin.json'))) {
1025
+ candidateCmdRoots.splice(1, 0, join(dir, '..', 'commands'))
1026
+ candidateCmdRoots.push(join(dir, '..', '.claude', 'commands'))
1027
+ }
1007
1028
  const inlineFallbacks = []
1008
1029
  const declared = manifest?.commands
1009
1030
  if (typeof declared === 'string') {
@@ -1117,7 +1138,9 @@ export function listSkills(dir, manifest = readPluginManifest(dir)) {
1117
1138
  .filter(Boolean)
1118
1139
  const candidateSkillRoots = []
1119
1140
  const seenSkillRoots = new Set()
1120
- for (const rootCandidate of [...declaredSkillPaths, join(dir, 'skills'), join(dir, '..', 'skills')]) {
1141
+ const skillRoots = [...declaredSkillPaths, join(dir, 'skills')]
1142
+ if (!existsSync(join(dir, '.claude-plugin', 'plugin.json'))) skillRoots.push(join(dir, '..', 'skills'))
1143
+ for (const rootCandidate of skillRoots) {
1121
1144
  const resolvedRoot = resolve(rootCandidate)
1122
1145
  if (seenSkillRoots.has(resolvedRoot)) continue
1123
1146
  seenSkillRoots.add(resolvedRoot)
package/src/routes.js CHANGED
@@ -11,10 +11,10 @@ import {
11
11
  readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir, sourceCacheDir, safeRmDir,
12
12
  } from './store.js'
13
13
  import { ensureSourceCloned, pullSource, safeSegment, materializePlugin } from './market.js'
14
- import { readMarketplace, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
14
+ import { readMarketplace, readMarketplaceName, pluginDetail, invalidateMarketplaceCache, resolveMarketplacePluginDir } from './parser.js'
15
15
  import { getOrFetchIcon, readLocalIconCached, invalidateLocalIconCache } from './icons.js'
16
16
  import {
17
- installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered, toolCallIconGroups,
17
+ installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, installedPluginDetail, isScanDirRegistered, toolCallIconGroups,
18
18
  toggleConnector, isConnectorActive, isOAuthConnectorAuthenticated, verifyConnectorAuth, saveConnectorAuth, enableConnector, probeConnectorAuth, probeUserMcpUpdate,
19
19
  fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
20
20
  withPluginLock, withSourceLock, removeManagedDirAsync, cancelActivePluginProbes,
@@ -24,12 +24,17 @@ import { uninstallUploadedSkill, uploadedSkillRecord } from './skill-uploads.js'
24
24
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
25
25
  import { remoteConfigFromEntry } from './oauth-config.js'
26
26
  import { scheduledResult } from './runtime.js'
27
+ import { listAtPlugins, invalidateAtPluginsCache } from './at-plugins.js'
27
28
 
28
29
  function scheduledIfOk(result, applyProfile, ids) {
29
30
  if (!result || result.ok === false) return result
30
31
  return scheduledResult(result, applyProfile, ids)
31
32
  }
32
33
 
34
+ function withPluginDetail(outcome, pluginName) {
35
+ return outcome && outcome.ok !== false ? { ...outcome, plugin: installedPluginDetail(pluginName) } : outcome
36
+ }
37
+
33
38
  const API_PREFIX = '/universal-plugin-hub/api'
34
39
  const STAGED_UPLOADS = new Map()
35
40
  const STAGED_UPLOAD_TTL = 3_600_000
@@ -210,6 +215,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
210
215
  return sendJson(res, 200, { groups: toolCallIconGroups() })
211
216
  }
212
217
 
218
+ if (method === 'GET' && path === '/at-plugins') {
219
+ return sendJson(res, 200, { plugins: listAtPlugins() })
220
+ }
221
+
213
222
  if (method === 'GET' && path === '/state') {
214
223
  const state = readState()
215
224
  const details = installedDetails()
@@ -284,12 +293,15 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
284
293
  if (method === 'GET' && path === '/market') {
285
294
  const rawSource = url.searchParams.get('sourceId') || url.searchParams.get('source') || 'anthropic'
286
295
  const sourceId = safeSegment(rawSource, 'source id')
287
- await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
288
- let rows = readMarketplace(sourceId)
289
- if (sourceId === 'local') {
290
- const names = new Set(rows.map(r => r.name))
291
- rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
292
- }
296
+ const rows = await withSourceLock(sourceId, async () => {
297
+ await ensureMarketCheckout(sourceId, sourceUrlOf(sourceId))
298
+ let plugins = readMarketplace(sourceId)
299
+ if (sourceId === 'local') {
300
+ const names = new Set(plugins.map(r => r.name))
301
+ plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
302
+ }
303
+ return plugins
304
+ })
293
305
  return sendJson(res, 200, { plugins: rows })
294
306
  }
295
307
 
@@ -300,10 +312,11 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
300
312
  const plugins = await withSourceLock(sourceId, async () => {
301
313
  // Clone first if the source has never been fetched (fresh install), so a
302
314
  // first-launch refresh does not fail with "尚未克隆".
303
- await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
315
+ await ensureMarketCheckout(sourceId, sourceUrlOf(sourceId))
304
316
  await pullSource(sourceId)
305
317
  invalidateMarketplaceCache(sourceId)
306
318
  invalidateLocalIconCache(sourceId)
319
+ invalidateAtPluginsCache()
307
320
  let rows = readMarketplace(sourceId)
308
321
  if (sourceId === 'local') {
309
322
  const names = new Set(rows.map(r => r.name))
@@ -327,7 +340,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
327
340
  const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
328
341
  if (!id) throw new Error('无法从该地址识别仓库')
329
342
 
330
- const count = await withSourceLock(id, async () => {
343
+ const { pluginCount, marketName } = await withSourceLock(id, async () => {
331
344
  // Check duplicates BEFORE cloning
332
345
  const state = readState()
333
346
  const duplicate = findDuplicateSource(state, id, url)
@@ -335,9 +348,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
335
348
  throw new Error(`该插件源已存在(${duplicate.name})`)
336
349
  }
337
350
  // Validate by cloning into the cache
338
- await ensureSourceCloned(id, url)
339
- const rows = readMarketplace(id)
340
- return Array.isArray(rows) ? rows.length : 0
351
+ const checkout = await ensureMarketCheckout(id, url)
352
+ return { pluginCount: readMarketplace(id).length, marketName: readMarketplaceName(checkout) }
341
353
  })
342
354
 
343
355
  const repoLabel = parsed ? `${parsed.owner}/${parsed.repo}` : (url.replace(/^https?:\/\//i, '').replace(/\.git$/i, ''))
@@ -347,8 +359,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
347
359
  sourceId: id,
348
360
  repoLabel,
349
361
  normalizedUrl: url,
350
- pluginCount: count,
351
- suggestedName: suggestSourceName(url),
362
+ pluginCount,
363
+ suggestedName: suggestSourceName(url, marketName),
352
364
  })
353
365
  }
354
366
 
@@ -415,6 +427,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
415
427
  }
416
428
  if (stagedId) discardStagedUpload(stagedId)
417
429
  invalidateLocalIconCache('local')
430
+ invalidateAtPluginsCache()
418
431
  return sendJson(res, 200, result)
419
432
  }
420
433
 
@@ -455,6 +468,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
455
468
  if (result?.sourceId) {
456
469
  invalidateLocalIconCache(result.sourceId)
457
470
  }
471
+ invalidateAtPluginsCache()
458
472
  return sendJson(res, 200, result)
459
473
  }
460
474
 
@@ -484,9 +498,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
484
498
 
485
499
  return sendJson(res, 200, await withSourceLock(id, async () => {
486
500
  validateUnique(readState())
487
- await ensureSourceCloned(id, url)
488
- const rows = readMarketplace(id)
489
- const count = Array.isArray(rows) ? rows.length : 0
501
+ await ensureMarketCheckout(id, url)
502
+ const plugins = readMarketplace(id)
490
503
 
491
504
  // Re-read state after awaiting clone so concurrent mutations (e.g. plugin toggles) are preserved.
492
505
  const latestState = readState()
@@ -494,7 +507,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
494
507
  const source = { id, name, url, addedAt: Date.now() }
495
508
  latestState.sources.push(source)
496
509
  writeState(latestState)
497
- return { ok: true, source, pluginCount: count }
510
+ return { ok: true, source, plugins, pluginCount: plugins.length }
498
511
  }))
499
512
  }
500
513
 
@@ -539,13 +552,16 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
539
552
  // The remote checkout pool is shared by marketplaces. Only remove this
540
553
  // source's own clone or uploaded marketplace copy.
541
554
  if (sourceId === 'local') cleanupAllStagedUploads()
542
- if (sourceId !== 'remote') await removeManagedDirAsync(sourceCacheDir(sourceId), { allowTrash: false })
555
+ if (sourceId !== 'remote') {
556
+ await removeManagedDirAsync(sourceCacheDir(sourceId), { deferCleanup: /^https?:\/\//i.test(source.url) })
557
+ }
543
558
  const latestState = readState()
544
559
  latestState.sources = latestState.sources.filter((s) => s.id !== sourceId)
545
560
  if (Array.isArray(latestState.tabOrder)) latestState.tabOrder = latestState.tabOrder.filter((id) => id !== sourceId)
546
561
  writeState(latestState)
547
562
  invalidateMarketplaceCache(sourceId)
548
563
  invalidateLocalIconCache(sourceId)
564
+ invalidateAtPluginsCache()
549
565
  })
550
566
  return sendJson(res, 200, { ok: true })
551
567
  }
@@ -572,7 +588,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
572
588
  const cfg = item.config || {}
573
589
  const ownership = pluginTools?.[`user-mcp::${cfg.serverName}`]
574
590
  if (ownership?.pluginConnectorOwned || (ownership?.pluginOAuthOwned && remoteConfigFromEntry(cfg))) continue
575
- if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
591
+ if (typeof cfg.serverName === 'string' && cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
576
592
  state.userMcps.push(userMcpConfig(cfg.serverName, {
577
593
  transport: cfg.transport, url: cfg.url, command: cfg.command,
578
594
  args: Array.isArray(cfg.args) ? cfg.args : [], cwd: cfg.cwd,
@@ -798,9 +814,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
798
814
  if (!pluginRec) return { ok: false, error: '插件未安装或已卸载' }
799
815
  const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
800
816
  if (!canEnable() && body.enabled !== false) return { ok: false, error: '请先启用所属插件' }
801
- return body.enabled !== false
802
- ? await enableConnector(pluginName, connectorName, undefined, { pluginOwned: true, canEnable })
803
- : toggleConnector(pluginName, connectorName, false)
817
+ const result = await toggleConnector(pluginName, connectorName, body.enabled !== false, { canEnable })
818
+ return withPluginDetail(result, pluginName)
804
819
  })
805
820
  return sendJson(res, 200, scheduledIfOk(outcome, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
806
821
  }
@@ -831,8 +846,8 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
831
846
  }
832
847
  const canEnable = () => readState().plugins.some(plugin => plugin.name === pluginName && plugin.enabled !== false)
833
848
  if (!canEnable()) return { status: 200, body: { ok: false, error: '请先启用所属插件' } }
834
- const result = await enableConnector(pluginName, connectorName, body, { pluginOwned: true, canEnable })
835
- return { status: 200, body: scheduledIfOk(result, applyProfile, [getConnectorId(pluginName, connectorName)]) }
849
+ const result = await enableConnector(pluginName, connectorName, body, { pluginOwned: true, canEnable, reuseStdioCache: false })
850
+ return { status: 200, body: scheduledIfOk(withPluginDetail(result, pluginName), applyProfile, [getConnectorId(pluginName, connectorName)]) }
836
851
  })
837
852
  return sendJson(res, outcome.status, outcome.body)
838
853
  }
@@ -854,6 +869,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
854
869
  await materializePlugin(sourceId, pluginName, row.source)
855
870
  invalidateMarketplaceCache(sourceId)
856
871
  invalidateLocalIconCache(sourceId)
872
+ invalidateAtPluginsCache()
857
873
  row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
858
874
  detail = pluginDetail(sourceId, pluginName, row.source, row)
859
875
  }
@@ -912,6 +928,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
912
928
  })
913
929
  invalidateMarketplaceCache(sourceId)
914
930
  invalidateLocalIconCache(sourceId)
931
+ invalidateAtPluginsCache()
915
932
  return sendJson(res, 200, scheduledIfOk(result, applyProfile))
916
933
  }
917
934
 
@@ -919,7 +936,10 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
919
936
  requireSameOrigin(req)
920
937
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
921
938
  const body = await readJsonBody(req)
922
- return sendJson(res, 200, scheduledIfOk(await togglePlugin(pluginName, body.enabled === true), applyProfile))
939
+ const result = await togglePlugin(pluginName, body.enabled === true, { onConnectorReady: (id) => applyProfile?.([id]) })
940
+ const payload = scheduledIfOk(withPluginDetail(result, pluginName), applyProfile)
941
+ invalidateAtPluginsCache()
942
+ return sendJson(res, 200, payload)
923
943
  }
924
944
 
925
945
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
@@ -928,6 +948,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
928
948
  const result = await updatePlugin(pluginName)
929
949
  invalidateMarketplaceCache()
930
950
  invalidateLocalIconCache()
951
+ invalidateAtPluginsCache()
931
952
  return sendJson(res, 200, scheduledIfOk(result, applyProfile))
932
953
  }
933
954
 
@@ -972,6 +993,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
972
993
  const result = await uninstallPlugin(pluginName)
973
994
  invalidateMarketplaceCache()
974
995
  invalidateLocalIconCache()
996
+ invalidateAtPluginsCache()
975
997
  return sendJson(res, 200, scheduledIfOk(result, applyProfile))
976
998
  }
977
999
 
@@ -993,6 +1015,16 @@ function requireSameOrigin(req) {
993
1015
  }
994
1016
  }
995
1017
 
1018
+ function ensureMarketCheckout(sourceId, url) {
1019
+ return ensureSourceCloned(sourceId, url, {
1020
+ onCloned() {
1021
+ invalidateMarketplaceCache(sourceId)
1022
+ invalidateLocalIconCache(sourceId)
1023
+ invalidateAtPluginsCache()
1024
+ },
1025
+ })
1026
+ }
1027
+
996
1028
  function sourceUrlOf(sourceId) {
997
1029
  const state = readState()
998
1030
  const source = state.sources.find((s) => s.id === sourceId)
package/src/runtime.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { resolveOptionalService } from './store.js'
2
+
1
3
  /**
2
4
  * Apply saved hub changes to the running DSH profile.
3
5
  *
@@ -57,7 +59,7 @@ export function createProfileApplicator(ctx) {
57
59
  try {
58
60
  // Resolve inside the try: a throwing service lookup must become a
59
61
  // reported failure, not a rejection that strands the status.
60
- const hmr = ctx?.root?.get?.('hmr') || ctx?.get?.('hmr')
62
+ const hmr = resolveOptionalService(ctx?.root, 'hmr') || resolveOptionalService(ctx, 'hmr')
61
63
  if (!hmr || typeof hmr.reconcileProfile !== 'function') {
62
64
  return { application: 'restart-required', restartReason: 'no-hmr', token: pending.token }
63
65
  }