plugins.ts 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. import { rm } from "node:fs/promises";
  2. import { basename, dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
  3. import { isDeepStrictEqual } from "node:util";
  4. import {
  5. addSuppressedBuiltinInFileConfig,
  6. createConfig,
  7. createConfigWithPluginMigrations,
  8. resolvePath,
  9. enablePluginsByDefaultInFileConfig,
  10. normalizePluginConfigPathForComparison,
  11. removePluginEnabledFromFileConfig,
  12. removePluginFromFileConfig,
  13. removeSuppressedBuiltinInFileConfig,
  14. updatePluginEnabledInFileConfig,
  15. type ConfigResult,
  16. } from "@zcode/adapters/config";
  17. import {
  18. addMarketplace,
  19. comparePluginUpdate,
  20. describeMarketplacePlugin,
  21. enrichCachedClaudeMarketplaceIcons,
  22. ensureDefaultPluginMarketplaces,
  23. discoverNodePlugins,
  24. ensureMarketplaceManifestAvailable,
  25. getPluginSourceDiagnosticCode,
  26. getPluginDataDir,
  27. installMarketplacePlugin,
  28. listInstalledPluginRecords,
  29. loadKnownMarketplacesSync,
  30. loadMarketplaceManifestSync,
  31. parseMarketplaceSourceInput,
  32. parseEntryExtensionSummary,
  33. parseEntryStoreListing,
  34. readPluginSourceIdentityPin,
  35. removeMarketplace,
  36. uninstallMarketplacePlugin,
  37. updateMarketplace,
  38. validateLocalPluginPath,
  39. validateMarketplacePlugin,
  40. validateMarketplaceSource,
  41. type DescribeMarketplacePluginResult,
  42. type InstalledPluginRecord,
  43. type KnownMarketplaceRecord,
  44. type MarketplaceSource,
  45. type PluginExtensionSummary,
  46. type PluginMarketplaceEntry,
  47. } from "@zcode/adapters/plugins";
  48. import type {
  49. Logger,
  50. PluginHookDetail,
  51. PluginLoadOutcome,
  52. PluginMetadata,
  53. PluginStoreListing,
  54. PluginPort,
  55. } from "@zcode/contracts";
  56. import { ZCODE_OFFICIAL_PLUGIN_MARKETPLACE, isOfficialMarketplaceId } from "@zcode/contracts";
  57. import {
  58. DEFAULT_PLUGIN_MARKETPLACES,
  59. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  60. isZCodeCuaInternalFeatureEnabled,
  61. } from "@zcode/shared";
  62. import {
  63. resolveOfficialPluginRoots,
  64. type OfficialPluginPreparation,
  65. } from "./app/bundled-plugins.js";
  66. import {
  67. DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS,
  68. OFFICIAL_NODE_REPL_HOST_PLUGIN_NAME,
  69. OFFICIAL_PLUGIN_DEFINITIONS,
  70. } from "./app/official-plugin-definitions.js";
  71. import { getCliStorageRoot, getPluginStorageRoot } from "./app/paths.js";
  72. import { type PluginStorageLock, withPluginStorageLock } from "./lib/plugin-storage-lock.js";
  73. import {
  74. removeStoredPluginSecrets,
  75. resolvePluginSecretsPath,
  76. savePluginOptions,
  77. withPluginSecrets,
  78. } from "./plugin-secrets.js";
  79. export interface ResolveZCodePluginsOptions {
  80. pluginStorageLock?: PluginStorageLock;
  81. abortSignal?: AbortSignal;
  82. workspaceIdentity?: string;
  83. remoteSessionId?: string;
  84. pluginPreparation?: OfficialPluginPreparation;
  85. pluginDiscovery?: PluginPort;
  86. configResult?: ConfigResult;
  87. env?: NodeJS.ProcessEnv;
  88. logger?: Logger;
  89. officialPluginRoots?: string[];
  90. pluginStorageRoot?: string;
  91. projectConfigPath?: string;
  92. skipUserConfig?: boolean;
  93. userConfigPath?: string;
  94. workingDirectory?: string;
  95. }
  96. /** 所有写入入口(包括独立 CLI)共用此边界。组合操作显式传递当次锁,避免递归等待。 */
  97. function pluginMutation<O extends ResolveZCodePluginsOptions, T>(
  98. operation: (options: O) => Promise<T>,
  99. ): (options: O) => Promise<T> {
  100. return async (options) => {
  101. const root =
  102. options.pluginStorageRoot ?? (await resolvePluginContext(options)).pluginStorageRoot;
  103. return withPluginStorageLock(
  104. root,
  105. (lock) =>
  106. operation({
  107. ...options,
  108. pluginStorageRoot: lock.root,
  109. pluginStorageLock: lock,
  110. }),
  111. options.pluginStorageLock,
  112. options.abortSignal ?? options.pluginPreparation?.signal,
  113. );
  114. };
  115. }
  116. export interface ListZCodePluginsOptions extends ResolveZCodePluginsOptions {}
  117. export interface SetZCodePluginEnabledOptions extends ResolveZCodePluginsOptions {
  118. enabled: boolean;
  119. plugin: string;
  120. scope?: "user" | "workspace";
  121. }
  122. export interface SetZCodePluginEnabledResult {
  123. enabled: boolean;
  124. path: string;
  125. plugin: PluginMetadata;
  126. }
  127. export interface ZCodeMarketplaceSummaryData {
  128. id: string;
  129. name: string;
  130. source: Record<string, unknown>;
  131. description?: string;
  132. lastUpdated?: string;
  133. pluginCount: number;
  134. isOfficial: boolean;
  135. refreshFailure?: {
  136. code: string;
  137. failedAt: string;
  138. message: string;
  139. };
  140. // 目录顶层 featured 策展名单(商店「公开」分段 Featured 区),随 manifest 下发。
  141. featured?: string[];
  142. }
  143. export interface ZCodeAvailablePluginData {
  144. id: string;
  145. name: string;
  146. marketplace: string;
  147. description?: string;
  148. version?: string;
  149. installed: boolean;
  150. componentTypes?: string[];
  151. hookDetails?: PluginHookDetail[];
  152. // 商店信息(显示名/icon/分类/作者/链接/hero/示例提示词),来自目录条目。
  153. listing?: PluginStoreListing;
  154. // 目录条目的扩展摘要(plugin-publishing.md §4.2)。协议层按请求参数决定是否放进 listing(§4.3)。
  155. extensionSummary?: PluginExtensionSummary;
  156. }
  157. export interface ZCodeInstalledPluginData {
  158. id: string;
  159. name: string;
  160. marketplace: string;
  161. description?: string;
  162. version?: string;
  163. enabled: boolean;
  164. scope: "user" | "workspace";
  165. installPath?: string;
  166. installedAt?: string;
  167. componentTypes?: string[];
  168. hookDetails?: PluginHookDetail[];
  169. updateStatus?: "none" | "update-available" | "version-changed";
  170. latestVersion?: string;
  171. // 已安装插件的商店信息由目录条目按 id join 得到(市场被移除时缺失,UI 走降级)。
  172. listing?: PluginStoreListing;
  173. // 目录里最新版条目的扩展摘要(不是已装版本的);App 据此判断最新版能不能装。
  174. extensionSummary?: PluginExtensionSummary;
  175. }
  176. export interface ZCodePluginsOverviewData {
  177. marketplaces: ZCodeMarketplaceSummaryData[];
  178. availablePlugins: ZCodeAvailablePluginData[];
  179. installedPlugins: ZCodeInstalledPluginData[];
  180. restorableBuiltins: ZCodeAvailablePluginData[];
  181. diagnostics: PluginLoadOutcome["diagnostics"];
  182. }
  183. export interface ZCodeMarketplaceUpdateData {
  184. diagnostics: PluginLoadOutcome["diagnostics"];
  185. marketplaces: ZCodeMarketplaceSummaryData[];
  186. }
  187. export interface AddZCodeMarketplaceOptions extends ResolveZCodePluginsOptions {
  188. dryRun?: boolean;
  189. source: string;
  190. /** `marketplace add --sparse`:仅 git/github 源支持 sparse checkout 子目录。 */
  191. sparsePaths?: string[];
  192. }
  193. export interface RemoveZCodeMarketplaceOptions extends ResolveZCodePluginsOptions {
  194. marketplace: string;
  195. }
  196. export interface UpdateZCodeMarketplaceOptions extends ResolveZCodePluginsOptions {
  197. marketplace?: string;
  198. }
  199. export interface InstallZCodeMarketplacePluginOptions extends ResolveZCodePluginsOptions {
  200. dryRun?: boolean;
  201. marketplace: string;
  202. pluginName: string;
  203. scope?: "user" | "workspace";
  204. }
  205. export interface UninstallZCodeMarketplacePluginOptions extends ResolveZCodePluginsOptions {
  206. pluginId?: string;
  207. pluginName?: string;
  208. marketplace?: string;
  209. removeCache?: boolean;
  210. /** 保留 data/<plugin-id> 用户数据目录(`zcode plugins uninstall --keep-data`)。 */
  211. keepData?: boolean;
  212. }
  213. export interface UpdateZCodeMarketplacePluginOptions extends ResolveZCodePluginsOptions {
  214. pluginId: string;
  215. }
  216. export interface ValidateZCodePluginPathOptions extends ResolveZCodePluginsOptions {
  217. path: string;
  218. }
  219. export interface ZCodePluginUpdateData extends ZCodePluginInstallData {
  220. previousVersion: string;
  221. }
  222. export interface RestoreBuiltinPluginOptions extends ResolveZCodePluginsOptions {
  223. pluginId: string;
  224. }
  225. export interface ConfigureZCodePluginOptions extends ResolveZCodePluginsOptions {
  226. clearOptionKeys?: string[];
  227. dryRun?: boolean;
  228. options: Record<string, unknown>;
  229. pluginId: string;
  230. scope?: "user" | "workspace";
  231. }
  232. export interface ResetZCodePluginConfigOptions extends ResolveZCodePluginsOptions {
  233. pluginId: string;
  234. scope?: "user" | "workspace";
  235. }
  236. export interface ValidateZCodePluginOptions extends ResolveZCodePluginsOptions {
  237. marketplace?: string;
  238. pluginName?: string;
  239. source?: string;
  240. }
  241. export interface DescribeZCodePluginOptions extends ResolveZCodePluginsOptions {
  242. marketplace: string;
  243. pluginName: string;
  244. }
  245. export interface ZCodePluginInstallData {
  246. dependencyClosure: string[];
  247. installedPlugins: ZCodeInstalledPluginData[];
  248. diagnostics: PluginLoadOutcome["diagnostics"];
  249. }
  250. /**
  251. * 市场插件计数只数用户可见条目。
  252. *
  253. * node-repl-host 是 Browser Use 与 Computer Use 共用的运行时宿主:它必须留在官方 manifest 里
  254. * (否则不会被发现、安装、启用),但没有 skill、没有 listing,也不该出现在设置页。计进去会让
  255. * 显示的插件数比它能列出的条目多一个。
  256. *
  257. * 判据故意是「官方市场里的这个具名条目」,而不是「没有 listing 的条目」—— 后者会误伤第三方
  258. * 市场:自定义 manifest 里的条目本来就可以不带 listing,它们是真实可见的插件。
  259. */
  260. function countVisibleMarketplacePlugins(
  261. marketplaceId: string,
  262. plugins: readonly { name: string }[] | undefined,
  263. ): number | undefined {
  264. if (!plugins) return undefined;
  265. if (marketplaceId !== ZCODE_OFFICIAL_PLUGIN_MARKETPLACE) return plugins.length;
  266. return plugins.filter((entry) => entry.name !== OFFICIAL_NODE_REPL_HOST_PLUGIN_NAME).length;
  267. }
  268. export async function resolveZCodePlugins(
  269. options: ResolveZCodePluginsOptions = {},
  270. ): Promise<PluginLoadOutcome> {
  271. const resolve = async (): Promise<PluginLoadOutcome> => {
  272. options.pluginPreparation?.signal.throwIfAborted();
  273. const context = await resolvePluginContext(options);
  274. const { pluginStorageRoot, workingDirectory } = context;
  275. // 敏感选项在私有文件里;按层叠加后再交给发现,运行时展开与投影读到的是同一份有效值。
  276. const secrets = await withPluginSecrets(
  277. context.configResult,
  278. context.pluginSecretsPath,
  279. options.logger,
  280. );
  281. const configResult = secrets.configResult;
  282. const outcome = await (
  283. options.pluginDiscovery
  284. ? options.pluginDiscovery.discoverPlugins.bind(options.pluginDiscovery)
  285. : discoverNodePlugins
  286. )(
  287. {
  288. workspaceIdentity: options.workspaceIdentity,
  289. remoteSessionId: options.remoteSessionId,
  290. config: configResult.config.plugins,
  291. env: options.env ?? process.env,
  292. officialPluginRoots: await resolveOfficialPluginRoots({
  293. preparation: options.pluginPreparation,
  294. extraRoots: options.officialPluginRoots,
  295. // cache 锁冲突已从 fatal 改为 degraded,普通插件入口也必须保留诊断日志。
  296. logger: options.logger,
  297. storageRoot: pluginStorageRoot,
  298. suppressedBuiltins: new Set(configResult.config.plugins.suppressedBuiltins),
  299. }),
  300. officialPluginsEnabledByDefault: DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS,
  301. storageRoot: pluginStorageRoot,
  302. workingDirectory,
  303. },
  304. { signal: options.pluginPreparation?.signal },
  305. );
  306. return secrets.diagnostics.length > 0
  307. ? { ...outcome, diagnostics: [...outcome.diagnostics, ...secrets.diagnostics] }
  308. : outcome;
  309. };
  310. return options.pluginPreparation
  311. ? await options.pluginPreparation.resolvePlugins(resolve)
  312. : await resolve();
  313. }
  314. /**
  315. * 叠加敏感选项私有文件后的配置视图,给协议投影读 `optionSources` 用。
  316. * resolveZCodePlugins 内部会对同一视图再叠加一次;叠加只读原始配置层,结果不变。
  317. */
  318. export async function resolveZCodePluginConfigWithSecrets(
  319. options: ResolveZCodePluginsOptions,
  320. ): Promise<ConfigResult> {
  321. const { configResult, pluginSecretsPath } = await resolvePluginContext(options);
  322. return (await withPluginSecrets(configResult, pluginSecretsPath)).configResult;
  323. }
  324. export async function getZCodePluginsOverview(
  325. options: ResolveZCodePluginsOptions = {},
  326. ): Promise<ZCodePluginsOverviewData> {
  327. const { configResult, pluginStorageRoot, workingDirectory } = await resolvePluginContext(options);
  328. const knownIds = new Set(loadKnownMarketplacesSync(pluginStorageRoot).map(({ id }) => id));
  329. if (DEFAULT_PLUGIN_MARKETPLACES.some(({ id }) => !knownIds.has(id))) {
  330. // 只有首次登记缺失的默认市场才写入,锁内重读;已有目录的普通浏览无需等下载。
  331. await withPluginStorageLock(
  332. pluginStorageRoot,
  333. async () => ensureDefaultPluginMarketplaces(pluginStorageRoot),
  334. options.pluginStorageLock,
  335. options.abortSignal ?? options.pluginPreparation?.signal,
  336. );
  337. }
  338. const outcome = await resolveZCodePlugins({
  339. ...options,
  340. configResult,
  341. pluginStorageRoot,
  342. });
  343. const known = loadKnownMarketplacesSync(pluginStorageRoot);
  344. const effectiveMarketplaces = resolveEffectiveMarketplaceRecords({
  345. configResult,
  346. known,
  347. workingDirectory,
  348. });
  349. const marketplaceDeclarationDiagnostics = resolveMarketplaceDeclarationDiagnostics({
  350. configResult,
  351. known,
  352. workingDirectory,
  353. });
  354. const installed = listInstalledPluginRecords(pluginStorageRoot);
  355. const installedIds = new Set(installed.map((record) => record.id));
  356. // 每个市场的 manifest 只读一次:同时取 entries(目录条目)与 featured(策展名单)。
  357. // zcode-plugins-official 的内置与 CDN 分片已在 adapter 层合并为唯一 canonical manifest。
  358. const catalogs: Array<{
  359. summary: ZCodeMarketplaceSummaryData;
  360. entries: PluginMarketplaceEntry[];
  361. }> = [];
  362. for (const { record, useCachedManifest } of effectiveMarketplaces) {
  363. // Marketplace source 只来自 User/Host 配置。只有目标 Host 已经通过显式 refresh/install
  364. // 物化了同一 source 时,才读取 Host cache;同 id 不同 source 必须 fail closed,避免
  365. // 不同 Host 或旧配置误用错误的全局 marketplace 快照。
  366. const manifest = useCachedManifest
  367. ? loadMarketplaceManifestSync(pluginStorageRoot, record.id)
  368. : null;
  369. catalogs.push({
  370. summary: toMarketplaceSummaryData(
  371. record,
  372. manifest?.featured,
  373. countVisibleMarketplacePlugins(record.id, manifest?.plugins),
  374. ),
  375. entries: manifest?.plugins ?? [],
  376. });
  377. }
  378. // 边遍历 marketplace catalog 边记录每个插件 id 的最新「版本 pin」用于更新检测。
  379. // 条目可能只有 version、只有 sha 或两者兼有,因此同时收集 version 与 sha
  380. // 两个轴,由 comparePluginUpdate 决定用哪条轴比对 installed 记录。
  381. const latestPinByPluginId = new Map<string, { version?: string; sha?: string }>();
  382. // 同时按 id 收集目录条目的商店信息,供已安装插件 join(详情/图标条/管理视图共用)。
  383. const listingByPluginId = new Map<string, PluginStoreListing>();
  384. const extensionSummaryByPluginId = new Map<string, PluginExtensionSummary>();
  385. const availablePlugins = catalogs.flatMap((catalog) =>
  386. catalog.entries.map((entry) => {
  387. const data = toAvailablePluginData(entry, catalog.summary.id, installedIds);
  388. latestPinByPluginId.set(data.id, {
  389. ...(entry.version ? { version: entry.version } : {}),
  390. ...(readPluginSourceIdentityPin(entry.source)
  391. ? { sha: readPluginSourceIdentityPin(entry.source) }
  392. : {}),
  393. });
  394. if (entry.listing) listingByPluginId.set(data.id, entry.listing);
  395. if (data.extensionSummary) extensionSummaryByPluginId.set(data.id, data.extensionSummary);
  396. return data;
  397. }),
  398. );
  399. const loadedById = new Map(outcome.plugins.map((plugin) => [plugin.id, plugin]));
  400. // 被抑制(uninstall)的内置(官方)插件可一键恢复:从 OFFICIAL_PLUGIN_DEFINITIONS
  401. // 里挑出 id 落在 suppressedBuiltins 集合内的,映射成 available 形态供 UI 的「恢复」入口使用。
  402. // 完整 Catalog/cache 仍然保留,restorable 只是 Runtime 抑制态的投影,商店信息直接取定义里的 listing seed。
  403. const suppressed = new Set(configResult.config.plugins.suppressedBuiltins);
  404. const restorableBuiltins: ZCodeAvailablePluginData[] = OFFICIAL_PLUGIN_DEFINITIONS.filter(
  405. (def) =>
  406. suppressed.has(`${def.name}@${ZCODE_OFFICIAL_PLUGIN_MARKETPLACE}`) &&
  407. // computer-use 的恢复入口需要 internal 特性开启(与 restoreBuiltinPluginCore 同口径)。
  408. (def.name !== "computer-use" || isZCodeCuaInternalFeatureEnabled(options.env ?? process.env)),
  409. ).map((def) => {
  410. const listing = def.listing
  411. ? parseEntryStoreListing({ name: def.name, ...def.listing })
  412. : undefined;
  413. return {
  414. id: `${def.name}@${ZCODE_OFFICIAL_PLUGIN_MARKETPLACE}`,
  415. name: def.name,
  416. marketplace: ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
  417. version: def.version,
  418. installed: false,
  419. // Bugfix:可恢复条目只带 listing 时丢了 "ui",卸载后的文档插件从「UI 插件」掉进分类分组。
  420. ...(def.componentTypes ? { componentTypes: [...def.componentTypes] } : {}),
  421. ...(listing ? { listing } : {}),
  422. };
  423. });
  424. return {
  425. marketplaces: catalogs.map((catalog) => catalog.summary),
  426. availablePlugins,
  427. installedPlugins: installed.map((record) => {
  428. const enabled = configResult.config.plugins.enabledPlugins[record.id] ?? false;
  429. const data = toInstalledPluginData(record, enabled, loadedById.get(record.id));
  430. const pin = latestPinByPluginId.get(record.id);
  431. const installedSha = readPluginSourceIdentityPin(record.source);
  432. const updateStatus = comparePluginUpdate({
  433. installedVersion: data.version,
  434. installedSha,
  435. latestVersion: pin?.version,
  436. latestSha: pin?.sha,
  437. });
  438. // latestVersion 展示:优先用 manifest 的 version;否则用最新 sha(短 7 位)让 UI 有可读提示。
  439. const latestLabel = pin?.version ?? (pin?.sha ? pin.sha.slice(0, 7) : undefined);
  440. const listing = listingByPluginId.get(record.id);
  441. const extensionSummary = extensionSummaryByPluginId.get(record.id);
  442. return {
  443. ...data,
  444. updateStatus,
  445. ...(latestLabel ? { latestVersion: latestLabel } : {}),
  446. ...(listing ? { listing } : {}),
  447. ...(extensionSummary ? { extensionSummary } : {}),
  448. };
  449. }),
  450. restorableBuiltins,
  451. diagnostics: [
  452. ...outcome.diagnostics,
  453. ...marketplaceDeclarationDiagnostics,
  454. ...known.flatMap((record): PluginLoadOutcome["diagnostics"] =>
  455. record.lastRefreshFailure
  456. ? [
  457. {
  458. code: record.lastRefreshFailure.code,
  459. message: record.lastRefreshFailure.message,
  460. pluginId: record.id,
  461. severity: "error",
  462. },
  463. ]
  464. : [],
  465. ),
  466. ],
  467. };
  468. }
  469. export function enrichCachedClaudeMarketplaceIconsForOverview(
  470. options: ResolveZCodePluginsOptions = {},
  471. ): void {
  472. const configResult = options.configResult ?? createConfig(options);
  473. const pluginStorageRoot =
  474. options.pluginStorageRoot ??
  475. getPluginStorageRoot(getCliStorageRoot(resolvePath(configResult.config.storage.dir)));
  476. // 图标是可选展示增强:overview 不等待网络;仅写回阶段进入 storage lock。
  477. void enrichCachedClaudeMarketplaceIcons(pluginStorageRoot, (write) =>
  478. withPluginStorageLock(pluginStorageRoot, write),
  479. );
  480. }
  481. export async function listZCodePlugins(
  482. options: ListZCodePluginsOptions = {},
  483. ): Promise<PluginLoadOutcome> {
  484. const outcome = await resolveZCodePlugins(options);
  485. const { pluginStorageRoot } = await resolvePluginContext(options);
  486. return {
  487. ...outcome,
  488. // 用户可见名称必须从 marketplace listing 解析;这里按完整 id 传递给 CLI,
  489. // 不把展示元数据混入 adapter 的运行时 PluginMetadata,也不按裸 name 猜测。
  490. pluginListingsById: loadPluginListingsById(pluginStorageRoot),
  491. };
  492. }
  493. function loadPluginListingsById(storageRoot: string): Record<string, PluginStoreListing> {
  494. const listings = new Map<string, PluginStoreListing>();
  495. // 没有 marketplace 快照时,bundled official definition 仍是内置插件 listing 的安全回退。
  496. for (const definition of OFFICIAL_PLUGIN_DEFINITIONS) {
  497. if (!definition.listing) continue;
  498. const listing = parseEntryStoreListing({ name: definition.name, ...definition.listing });
  499. if (listing) {
  500. listings.set(`${definition.name}@${ZCODE_OFFICIAL_PLUGIN_MARKETPLACE}`, listing);
  501. }
  502. }
  503. // 目录条目按完整 `${name}@${marketplace}` 关联;同名插件不会互相覆盖。
  504. for (const marketplace of loadKnownMarketplacesSync(storageRoot)) {
  505. const manifest = loadMarketplaceManifestSync(storageRoot, marketplace.id);
  506. for (const entry of manifest?.plugins ?? []) {
  507. if (entry.listing) listings.set(`${entry.name}@${marketplace.id}`, entry.listing);
  508. }
  509. }
  510. return Object.fromEntries(listings);
  511. }
  512. export const setZCodePluginEnabled = pluginMutation(setZCodePluginEnabledLocked);
  513. async function setZCodePluginEnabledLocked(
  514. options: SetZCodePluginEnabledOptions,
  515. ): Promise<SetZCodePluginEnabledResult> {
  516. const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
  517. const configResult =
  518. options.configResult ??
  519. (await createConfigWithPluginMigrations({
  520. env: options.env,
  521. projectConfigPath: options.projectConfigPath,
  522. workingDirectory,
  523. skipUserConfig: options.skipUserConfig,
  524. userConfigPath: options.userConfigPath,
  525. }));
  526. const outcome = await resolveZCodePlugins({
  527. ...options,
  528. configResult,
  529. workingDirectory,
  530. });
  531. const plugin = resolvePluginSelector(options.plugin, outcome.plugins);
  532. const patch = await updatePluginEnabledInFileConfig(
  533. resolvePluginConfigPath(options, configResult, workingDirectory),
  534. plugin.id,
  535. options.enabled,
  536. );
  537. return {
  538. enabled: patch.enabled,
  539. path: patch.path,
  540. plugin: {
  541. ...plugin,
  542. enabled: patch.enabled,
  543. },
  544. };
  545. }
  546. export const addZCodePluginMarketplace = pluginMutation(addZCodePluginMarketplaceLocked);
  547. async function addZCodePluginMarketplaceLocked(
  548. options: AddZCodeMarketplaceOptions,
  549. ): Promise<ZCodeMarketplaceSummaryData> {
  550. const { pluginStorageRoot } = await resolvePluginContext(options);
  551. const source = applySparsePaths(
  552. await parseMarketplaceSourceInput(options.source),
  553. options.sparsePaths,
  554. );
  555. if (options.dryRun === true) {
  556. return {
  557. id: "dry-run",
  558. name: "dry-run",
  559. source: source as unknown as Record<string, unknown>,
  560. pluginCount: 0,
  561. isOfficial: false,
  562. };
  563. }
  564. const record = await addMarketplace({
  565. signal: options.abortSignal,
  566. source,
  567. storageRoot: pluginStorageRoot,
  568. });
  569. return toMarketplaceSummaryData(record);
  570. }
  571. export const removeZCodePluginMarketplace = pluginMutation(removeZCodePluginMarketplaceLocked);
  572. async function removeZCodePluginMarketplaceLocked(
  573. options: RemoveZCodeMarketplaceOptions,
  574. ): Promise<void> {
  575. const { pluginStorageRoot } = await resolvePluginContext(options);
  576. await removeMarketplace({
  577. marketplace: options.marketplace,
  578. storageRoot: pluginStorageRoot,
  579. });
  580. }
  581. const updateMarketplaceWithLock = pluginMutation(updateZCodePluginMarketplaceLocked);
  582. export async function updateZCodePluginMarketplace(
  583. options: UpdateZCodeMarketplaceOptions,
  584. ): Promise<ZCodeMarketplaceUpdateData> {
  585. try {
  586. return await updateMarketplaceWithLock(options);
  587. } catch (error) {
  588. // 刷新接口以 diagnostics 返回取消;锁的准入检查可能先于市场初始化,不能因此改成抛错或写入默认目录。
  589. if (!options.abortSignal?.aborted || options.abortSignal.reason !== error) throw error;
  590. return {
  591. marketplaces: [],
  592. diagnostics: [toMarketplaceRefreshDiagnostic(error, options.marketplace)],
  593. };
  594. }
  595. }
  596. async function updateZCodePluginMarketplaceLocked(
  597. options: UpdateZCodeMarketplaceOptions,
  598. ): Promise<ZCodeMarketplaceUpdateData> {
  599. const { configResult, pluginStorageRoot, workingDirectory } = await resolvePluginContext(options);
  600. await ensureDefaultPluginMarketplaces(pluginStorageRoot);
  601. const declared = resolveDeclaredMarketplaceSources({
  602. configResult,
  603. });
  604. const known = loadKnownMarketplacesSync(pluginStorageRoot);
  605. const knownById = new Map(known.map((record) => [record.id, record]));
  606. const targetIds = resolveMarketplaceRefreshTargetIds({
  607. declaredIds: declared.keys(),
  608. knownIds: knownById.keys(),
  609. marketplace: options.marketplace,
  610. });
  611. if (
  612. options.marketplace &&
  613. !knownById.has(options.marketplace) &&
  614. !declared.has(options.marketplace)
  615. ) {
  616. throw new Error(`Marketplace not found: ${options.marketplace}`);
  617. }
  618. const updated: KnownMarketplaceRecord[] = [];
  619. const declarationDiagnostics: PluginLoadOutcome["diagnostics"] = [];
  620. for (const marketplaceId of targetIds) {
  621. const declarationSource = declared.get(marketplaceId);
  622. const knownRecord = knownById.get(marketplaceId);
  623. if (
  624. options.marketplace &&
  625. declarationSource &&
  626. knownRecord &&
  627. !isDeepStrictEqual(knownRecord.source, declarationSource)
  628. ) {
  629. declarationDiagnostics.push(createMarketplaceSourceRepointDiagnostic(marketplaceId));
  630. continue;
  631. }
  632. if (declarationSource && !knownRecord) {
  633. try {
  634. updated.push(
  635. await addMarketplace({
  636. expectedId: marketplaceId,
  637. signal: options.abortSignal,
  638. source: declarationSource,
  639. storageRoot: pluginStorageRoot,
  640. }),
  641. );
  642. } catch (error) {
  643. declarationDiagnostics.push(toMarketplaceRefreshDiagnostic(error, marketplaceId));
  644. }
  645. continue;
  646. }
  647. updated.push(
  648. ...(await updateMarketplace({
  649. marketplace: marketplaceId,
  650. signal: options.abortSignal,
  651. storageRoot: pluginStorageRoot,
  652. })),
  653. );
  654. }
  655. // map 回调只吃第一个参数:toMarketplaceSummaryData 的第二参是 featured,不能接 map 的 index。
  656. const records = loadKnownMarketplacesSync(pluginStorageRoot);
  657. const selectedFailures = records.flatMap((record): PluginLoadOutcome["diagnostics"] => {
  658. if (options.marketplace && record.id !== options.marketplace) return [];
  659. if (!record.lastRefreshFailure) return [];
  660. return [
  661. {
  662. code: record.lastRefreshFailure.code,
  663. message: record.lastRefreshFailure.message,
  664. pluginId: record.id,
  665. severity: "error",
  666. },
  667. ];
  668. });
  669. return {
  670. marketplaces: updated.map((record) => toMarketplaceSummaryData(record)),
  671. diagnostics: [...declarationDiagnostics, ...selectedFailures],
  672. };
  673. }
  674. export const installZCodeMarketplacePlugin = pluginMutation(installZCodeMarketplacePluginLocked);
  675. async function installZCodeMarketplacePluginLocked(
  676. options: InstallZCodeMarketplacePluginOptions,
  677. ): Promise<ZCodePluginInstallData> {
  678. const { configResult, pluginStorageRoot, workingDirectory } = await resolvePluginContext(options);
  679. await ensureDefaultPluginMarketplaces(pluginStorageRoot);
  680. if (options.dryRun === true) {
  681. const declarationSource = resolveDeclaredMarketplaceSources({
  682. configResult,
  683. }).get(options.marketplace);
  684. const known = loadKnownMarketplacesSync(pluginStorageRoot).find(
  685. (record) => record.id === options.marketplace,
  686. );
  687. if (declarationSource && known && !isDeepStrictEqual(known.source, declarationSource)) {
  688. return {
  689. dependencyClosure: [],
  690. installedPlugins: [],
  691. diagnostics: [createMarketplaceSourceRepointDiagnostic(options.marketplace)],
  692. };
  693. }
  694. if (
  695. declarationSource &&
  696. (!known || !loadMarketplaceManifestSync(pluginStorageRoot, options.marketplace))
  697. ) {
  698. return {
  699. dependencyClosure: [],
  700. installedPlugins: [],
  701. diagnostics: (
  702. await validateMarketplaceSource({
  703. expectedId: options.marketplace,
  704. pluginName: options.pluginName,
  705. signal: options.abortSignal,
  706. source: declarationSource,
  707. storageRoot: pluginStorageRoot,
  708. })
  709. ).map(toPluginDiagnostic),
  710. };
  711. }
  712. return {
  713. dependencyClosure: [],
  714. installedPlugins: [],
  715. diagnostics: (
  716. await validateMarketplacePlugin({
  717. marketplace: options.marketplace,
  718. name: options.pluginName,
  719. storageRoot: pluginStorageRoot,
  720. })
  721. ).map(toPluginDiagnostic),
  722. };
  723. }
  724. const pluginId = `${options.pluginName}@${options.marketplace}`;
  725. const bundledEntry = loadMarketplaceManifestSync(
  726. pluginStorageRoot,
  727. options.marketplace,
  728. )?.plugins.find((entry) => entry.name === options.pluginName);
  729. const isSuppressedBundledOfficial =
  730. options.marketplace === ZCODE_OFFICIAL_PLUGIN_MARKETPLACE &&
  731. configResult.config.plugins.suppressedBuiltins.includes(pluginId) &&
  732. (bundledEntry?.source === "filesystem" || bundledEntry?.source === "sea");
  733. if (isSuppressedBundledOfficial) {
  734. // 内置插件的 filesystem/SEA entry 只是 Catalog 指针,不是普通 Marketplace source。
  735. // 直接安装必须复用 restore,避免把同一份官方 cache 写进 installed_plugins.json,
  736. // 否则卸载/更新会把内置资产误判成用户安装并破坏恢复语义。
  737. // 安装与恢复属于同一次持锁操作;复用核心,不重复获取文件锁。
  738. await restoreBuiltinPluginCore({ ...options, configResult, pluginId });
  739. const fresh = await resolvePluginContext({ ...options, configResult: undefined });
  740. const outcome = await resolveZCodePlugins({
  741. ...options,
  742. configResult: fresh.configResult,
  743. pluginStorageRoot: fresh.pluginStorageRoot,
  744. });
  745. const restored = outcome.plugins.find((plugin) => plugin.id === pluginId);
  746. if (!restored) {
  747. return {
  748. dependencyClosure: [],
  749. installedPlugins: [],
  750. diagnostics: [
  751. toPluginDiagnostic({
  752. code: "plugin_not_found",
  753. message: `Bundled plugin could not be restored: ${pluginId}`,
  754. pluginId,
  755. severity: "error",
  756. }),
  757. ],
  758. };
  759. }
  760. const now = new Date().toISOString();
  761. return {
  762. dependencyClosure: [pluginId],
  763. installedPlugins: [
  764. toInstalledPluginData(
  765. {
  766. id: restored.id,
  767. name: restored.name,
  768. marketplace: restored.marketplace,
  769. version: restored.version ?? "",
  770. installPath: restored.rootPath,
  771. installedAt: now,
  772. updatedAt: now,
  773. scope: "user",
  774. },
  775. restored.enabled,
  776. restored,
  777. ),
  778. ],
  779. diagnostics: [],
  780. };
  781. }
  782. let installed: Awaited<ReturnType<typeof installMarketplacePlugin>>;
  783. try {
  784. await materializeDeclaredMarketplaceForExplicitAction({
  785. configResult,
  786. marketplaceId: options.marketplace,
  787. pluginStorageRoot,
  788. abortSignal: options.abortSignal,
  789. workingDirectory,
  790. });
  791. installed = await installMarketplacePlugin({
  792. signal: options.abortSignal,
  793. marketplace: options.marketplace,
  794. name: options.pluginName,
  795. // package/cache/installed record 是目标 Host 的 User inventory;
  796. // 旧协议的 Workspace scope 仅为兼容保留,不能改变 Marketplace 默认启用写入 User config
  797. // 的语义。installed record 没有 workspace identity,不能让它参与 Workspace 配置归属。
  798. scope: "user",
  799. storageRoot: pluginStorageRoot,
  800. });
  801. } catch (error) {
  802. return {
  803. dependencyClosure: [],
  804. installedPlugins: [],
  805. diagnostics: [
  806. toMarketplaceInstallDiagnostic(error, `${options.pluginName}@${options.marketplace}`),
  807. ],
  808. };
  809. }
  810. if (options.marketplace === ZCODE_OFFICIAL_PLUGIN_MARKETPLACE) {
  811. // 官方 marketplace 复用内置插件的 id 空间。若同名 CDN 插件重新安装,
  812. // 清掉历史内置 suppression,否则 Runtime 仍会把已拥有的安装误判为 suppressed。
  813. for (const record of installed.installed) {
  814. await removeSuppressedBuiltinInFileConfig(configResult.sources.user.path, record.id);
  815. }
  816. }
  817. // Marketplace 只管理 Host User inventory;即使旧协议调用方传入 workspace scope,
  818. // 安装即默认启用也必须写入 User config,不能把 Marketplace 动作变成 Workspace override。
  819. // 仅作用于用户配置里尚未显式声明的 id(停用后重装等显式选择不被覆盖)。
  820. const { enabledIds } = await enablePluginsByDefaultInFileConfig(
  821. configResult.sources.user.path,
  822. installed.installed.map((record) => record.id),
  823. );
  824. const enabledIdSet = new Set(enabledIds);
  825. // 已有显式配置的,沿用其当前启用态;本次新置默认启用的标记为 true。
  826. const enabledById = (id: string): boolean =>
  827. enabledIdSet.has(id) || (configResult.config.plugins.enabledPlugins[id] ?? false);
  828. return {
  829. dependencyClosure: installed.closure,
  830. installedPlugins: installed.installed.map((record) =>
  831. toInstalledPluginData(record, enabledById(record.id)),
  832. ),
  833. diagnostics: [],
  834. };
  835. }
  836. export const uninstallZCodeMarketplacePlugin = pluginMutation(
  837. async (
  838. options: UninstallZCodeMarketplacePluginOptions,
  839. ): Promise<ZCodeInstalledPluginData | null> => {
  840. const { configResult, pluginSecretsPath, pluginStorageRoot, workingDirectory } =
  841. await resolvePluginContext(options);
  842. const pluginId = resolvePluginIdForMutation(options);
  843. // 官方 CDN marketplace 与内置插件共享 zcode-plugins-official id 空间,且其缓存
  844. // 也位于 official cache 下。若先看 runtime source="official",会把已有
  845. // installed_plugins.json 记录的 CDN 插件误判成内置插件,只写 suppression 却不删安装记录,
  846. // 导致 UI 永远保持 installed、无法重装。持久化安装记录是 marketplace 所有权的权威证据,
  847. // 必须优先于运行时来源分类;同时清掉可能遗留的错误 suppression,让状态自愈。
  848. const installedRecord = listInstalledPluginRecords(pluginStorageRoot).find(
  849. (record) => record.id === pluginId,
  850. );
  851. if (installedRecord) {
  852. const removed = await uninstallMarketplacePlugin({
  853. pluginId,
  854. // 卸载语义即彻底清除:除非调用方显式传 removeCache=false,否则连缓存与 data 目录一起删。
  855. removeCache: options.removeCache ?? true,
  856. keepData: options.keepData,
  857. storageRoot: pluginStorageRoot,
  858. });
  859. if (!removed) return null;
  860. await removePluginFromFileConfig(configResult.sources.user.path, removed.id);
  861. await removeSuppressedBuiltinInFileConfig(configResult.sources.user.path, removed.id);
  862. // 卸载是彻底清理:私有文件里 user 与全部 workspaces 的条目一起删。
  863. await removeStoredPluginSecrets(pluginSecretsPath, removed.id, "all");
  864. return toInstalledPluginData(removed, false);
  865. }
  866. // 内置(官方)插件不在 installed_plugins.json 里,无法走 marketplace 卸载路径。
  867. // 卸载只改变 Runtime 抑制态并清理用户数据/config;Catalog 与不可变 cache 必须保留,
  868. // 这样详情页仍能离线读取组件,且恢复动作不依赖重新下载或重新构造目录。
  869. const outcome = await resolveZCodePlugins({
  870. ...options,
  871. configResult,
  872. pluginStorageRoot,
  873. workingDirectory,
  874. });
  875. const builtin = outcome.plugins.find(
  876. (plugin) => plugin.id === pluginId && plugin.source === "official",
  877. );
  878. if (builtin) {
  879. await addSuppressedBuiltinInFileConfig(configResult.sources.user.path, pluginId);
  880. // 先清掉 user config 里的 enabledPlugins[id] 与 options[id],再删目录:抑制标记已是
  881. // 唯一真相源(写入用原子 temp+rename),即使后续删除抛错,下次 resolve 也会跳过并补删
  882. // 缓存;把 config 清理放在删除之前可保证「恢复时从干净状态开始」即便删除中途失败。
  883. await removePluginFromFileConfig(configResult.sources.user.path, pluginId);
  884. await removeStoredPluginSecrets(pluginSecretsPath, pluginId, "all");
  885. // 不删除官方 cache:它与 Marketplace Catalog 同属详情/恢复所需的只读资产。
  886. if (options.keepData !== true) {
  887. await rm(getPluginDataDir(pluginStorageRoot, pluginId), { force: true, recursive: true });
  888. }
  889. const now = new Date().toISOString();
  890. return toInstalledPluginData(
  891. {
  892. id: builtin.id,
  893. name: builtin.name,
  894. marketplace: builtin.marketplace,
  895. version: builtin.version ?? "",
  896. installPath: builtin.rootPath,
  897. installedAt: now,
  898. updatedAt: now,
  899. scope: "user",
  900. },
  901. false,
  902. );
  903. }
  904. return null;
  905. },
  906. );
  907. /**
  908. * `zcode plugins update <plugin>`:先刷新所属 marketplace 目录,再按同一条目重装。
  909. * cacheMarketplacePlugin 对已存在的安装记录做原地覆盖并保留 installedAt;启用态只会给
  910. * 用户配置里尚未显式声明的 id 补默认值,因此更新不会改变用户已经做过的开关选择。
  911. */
  912. export const updateZCodeMarketplacePlugin = pluginMutation(updateZCodeMarketplacePluginLocked);
  913. async function updateZCodeMarketplacePluginLocked(
  914. options: UpdateZCodeMarketplacePluginOptions,
  915. ): Promise<ZCodePluginUpdateData> {
  916. const { pluginStorageRoot } = await resolvePluginContext(options);
  917. const record = listInstalledPluginRecords(pluginStorageRoot).find(
  918. (installed) => installed.id === options.pluginId,
  919. );
  920. if (!record) throw new Error(`Plugin not installed: ${options.pluginId}`);
  921. const refreshed = await updateZCodePluginMarketplace({
  922. ...options,
  923. marketplace: record.marketplace,
  924. });
  925. const refreshErrors = refreshed.diagnostics.filter((item) => item.severity === "error");
  926. if (refreshErrors.length > 0) {
  927. return {
  928. dependencyClosure: [],
  929. installedPlugins: [],
  930. diagnostics: refreshErrors,
  931. previousVersion: record.version,
  932. };
  933. }
  934. const installed = await installZCodeMarketplacePlugin({
  935. ...options,
  936. marketplace: record.marketplace,
  937. pluginName: record.name,
  938. scope: record.scope,
  939. });
  940. return { ...installed, previousVersion: record.version };
  941. }
  942. /** `zcode plugins validate <path>`:只读校验本地插件目录或 marketplace 目录。 */
  943. export async function validateZCodePluginPath(
  944. options: ValidateZCodePluginPathOptions,
  945. ): Promise<PluginLoadOutcome["diagnostics"]> {
  946. const { pluginStorageRoot } = await resolvePluginContext(options);
  947. return (
  948. await validateLocalPluginPath({
  949. path: options.path,
  950. signal: options.abortSignal,
  951. storageRoot: pluginStorageRoot,
  952. })
  953. ).map(toPluginDiagnostic);
  954. }
  955. function applySparsePaths(
  956. source: MarketplaceSource,
  957. sparsePaths: string[] | undefined,
  958. ): MarketplaceSource {
  959. const paths = (sparsePaths ?? []).map((item) => item.trim()).filter((item) => item.length > 0);
  960. if (paths.length === 0) return source;
  961. if (source.source !== "git" && source.source !== "github") {
  962. throw new Error("--sparse only applies to git or GitHub marketplace sources");
  963. }
  964. return { ...source, sparsePaths: paths };
  965. }
  966. /**
  967. * 恢复一个被抑制(uninstall)的内置(官方)插件的无锁核心。
  968. *
  969. * 调用方可能已经持有同一 storageRoot 的 storage lock(例如协议 install handler),
  970. * 因此核心不能再次获取 promise-chain lock;公开入口再负责提供锁保护。
  971. */
  972. async function restoreBuiltinPluginCore(options: RestoreBuiltinPluginOptions): Promise<void> {
  973. const zcodeCuaPluginId = ZCODE_CUA_OFFICIAL_PLUGIN_ID;
  974. if (
  975. options.pluginId === zcodeCuaPluginId &&
  976. !isZCodeCuaInternalFeatureEnabled(options.env ?? process.env)
  977. ) {
  978. // overview 虽然隐藏了恢复入口,但协议调用仍可绕过 UI 写用户配置。
  979. // 功能开关关闭时在写盘前失败,确保用户配置与插件缓存都保持零痕迹。
  980. throw new Error("computer-use built-in plugin requires ZCODE_CUA_PRODUCT_HELPER to be enabled");
  981. }
  982. const { configResult, pluginStorageRoot } = await resolvePluginContext(options);
  983. // 准备取消或失败时不能先改变配置;seed 不按抑制态过滤,成功后再提交恢复。
  984. options.pluginPreparation?.signal.throwIfAborted();
  985. options.pluginPreparation?.invalidate();
  986. await resolveOfficialPluginRoots({
  987. preparation: options.pluginPreparation,
  988. storageRoot: pluginStorageRoot,
  989. });
  990. options.pluginPreparation?.signal.throwIfAborted();
  991. await removeSuppressedBuiltinInFileConfig(configResult.sources.user.path, options.pluginId);
  992. }
  993. export const restoreBuiltinPlugin = pluginMutation(restoreBuiltinPluginCore);
  994. export const configureZCodePlugin = pluginMutation(configureZCodePluginLocked);
  995. async function configureZCodePluginLocked(options: ConfigureZCodePluginOptions): Promise<void> {
  996. const normalizedOptions = normalizePluginOptions(options.options);
  997. const clearOptionKeys = normalizePluginOptionKeys(options.clearOptionKeys);
  998. const { configResult, pluginSecretsPath, pluginStorageRoot, workingDirectory } =
  999. await resolvePluginContext(options);
  1000. const outcome = await resolveZCodePlugins({
  1001. ...options,
  1002. configResult,
  1003. pluginStorageRoot,
  1004. workingDirectory,
  1005. });
  1006. const plugin = resolvePluginSelector(options.pluginId, outcome.plugins);
  1007. if (options.dryRun === true) return;
  1008. await savePluginOptions({
  1009. clearOptionKeys,
  1010. configPath: resolvePluginConfigPath(options, configResult, workingDirectory),
  1011. options: normalizedOptions,
  1012. plugin,
  1013. // workspace 配置固定写 <workingDirectory>/.zcode/config.json,它的 baseDir 就是 workingDirectory。
  1014. scope:
  1015. options.scope === "workspace"
  1016. ? { kind: "workspace", root: workingDirectory }
  1017. : { kind: "user" },
  1018. secretsPath: pluginSecretsPath,
  1019. });
  1020. }
  1021. /** 删除指定 scope 的 Plugin 配置键,使 Workspace scope 回退到 User。 */
  1022. export const resetZCodePluginConfig = pluginMutation(resetZCodePluginConfigLocked);
  1023. async function resetZCodePluginConfigLocked(
  1024. options: ResetZCodePluginConfigOptions,
  1025. ): Promise<{ path: string; pluginId: string }> {
  1026. const { configResult, pluginSecretsPath, workingDirectory } = await resolvePluginContext(options);
  1027. const path = resolvePluginConfigPath(options, configResult, workingDirectory);
  1028. if (options.scope === "workspace") {
  1029. // “恢复继承”只删除 Workspace 的 enable override。options 是独立配置维度,
  1030. // 不能因为用户恢复开关继承而把 Workspace options/secret 一并抹掉(私有文件同语义,保留)。
  1031. await removePluginEnabledFromFileConfig(path, options.pluginId);
  1032. } else {
  1033. await removePluginFromFileConfig(path, options.pluginId);
  1034. await removeStoredPluginSecrets(pluginSecretsPath, options.pluginId, { kind: "user" });
  1035. }
  1036. return { path, pluginId: options.pluginId };
  1037. }
  1038. export const validateZCodePlugin = pluginMutation(validateZCodePluginLocked);
  1039. async function validateZCodePluginLocked(
  1040. options: ValidateZCodePluginOptions,
  1041. ): Promise<PluginLoadOutcome["diagnostics"]> {
  1042. const { pluginStorageRoot } = await resolvePluginContext(options);
  1043. await ensureDefaultPluginMarketplaces(pluginStorageRoot);
  1044. if (options.source) {
  1045. try {
  1046. const source = await parseMarketplaceSourceInput(options.source);
  1047. return (
  1048. await validateMarketplaceSource({
  1049. source,
  1050. storageRoot: pluginStorageRoot,
  1051. })
  1052. ).map(toPluginDiagnostic);
  1053. } catch (error) {
  1054. return [
  1055. {
  1056. code: "plugin_marketplace_invalid",
  1057. message: error instanceof Error ? error.message : String(error),
  1058. severity: "error",
  1059. },
  1060. ];
  1061. }
  1062. }
  1063. if (options.marketplace && options.pluginName) {
  1064. try {
  1065. await ensureMarketplaceManifestAvailable({
  1066. marketplace: options.marketplace,
  1067. storageRoot: pluginStorageRoot,
  1068. });
  1069. } catch (error) {
  1070. return [
  1071. {
  1072. code: "plugin_marketplace_invalid",
  1073. message: error instanceof Error ? error.message : String(error),
  1074. pluginId: `${options.pluginName}@${options.marketplace}`,
  1075. severity: "error",
  1076. },
  1077. ];
  1078. }
  1079. return (
  1080. await validateMarketplacePlugin({
  1081. marketplace: options.marketplace,
  1082. name: options.pluginName,
  1083. storageRoot: pluginStorageRoot,
  1084. })
  1085. ).map(toPluginDiagnostic);
  1086. }
  1087. return [];
  1088. }
  1089. export async function describeZCodePlugin(
  1090. options: DescribeZCodePluginOptions,
  1091. ): Promise<DescribeMarketplacePluginResult> {
  1092. const { pluginStorageRoot } = await resolvePluginContext(options);
  1093. // 默认市场登记由 ensureMarketplaceManifestAvailable 在写锁内完成;这里不再无锁写 known 列表。
  1094. return await describeMarketplacePlugin({
  1095. marketplace: options.marketplace,
  1096. name: options.pluginName,
  1097. storageRoot: pluginStorageRoot,
  1098. withWriteLock: (write) =>
  1099. withPluginStorageLock(
  1100. pluginStorageRoot,
  1101. write,
  1102. options.pluginStorageLock,
  1103. options.abortSignal,
  1104. ),
  1105. });
  1106. }
  1107. async function resolvePluginContext(options: ResolveZCodePluginsOptions): Promise<{
  1108. configResult: ConfigResult;
  1109. pluginSecretsPath: string;
  1110. pluginStorageRoot: string;
  1111. workingDirectory: string;
  1112. }> {
  1113. const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
  1114. const configResult =
  1115. options.configResult ??
  1116. (await createConfigWithPluginMigrations({
  1117. env: options.env,
  1118. projectConfigPath: options.projectConfigPath,
  1119. workingDirectory,
  1120. skipUserConfig: options.skipUserConfig,
  1121. userConfigPath: options.userConfigPath,
  1122. }));
  1123. const storageRoot = resolvePath(configResult.config.storage.dir);
  1124. const pluginStorageRoot =
  1125. options.pluginStorageRoot ?? getPluginStorageRoot(getCliStorageRoot(storageRoot));
  1126. return {
  1127. configResult,
  1128. pluginSecretsPath: resolvePluginSecretsPath(pluginStorageRoot),
  1129. pluginStorageRoot,
  1130. workingDirectory,
  1131. };
  1132. }
  1133. function resolveDeclaredMarketplaceSources(input: {
  1134. configResult: ConfigResult;
  1135. }): Map<string, MarketplaceSource> {
  1136. return new Map(
  1137. Object.entries(input.configResult.config.plugins.extraKnownMarketplaces ?? {}).map(
  1138. ([marketplaceId, declaration]) => {
  1139. const baseDirectory = dirname(input.configResult.sources.plugins.paths.user);
  1140. return [marketplaceId, resolveDeclaredMarketplaceSource(declaration.source, baseDirectory)];
  1141. },
  1142. ),
  1143. );
  1144. }
  1145. function resolveDeclaredMarketplaceSource(
  1146. source: ConfigResult["config"]["plugins"]["extraKnownMarketplaces"][string]["source"],
  1147. baseDirectory: string,
  1148. ): MarketplaceSource {
  1149. // User Marketplace 的相对路径按 User config 所在目录解析;配置读取不触碰 source,
  1150. // 只有显式 refresh/install 才会真正读取、复制或联网。
  1151. if (source.source === "file" || source.source === "directory") {
  1152. return {
  1153. ...source,
  1154. path: isAbsolute(source.path) ? resolve(source.path) : resolve(baseDirectory, source.path),
  1155. };
  1156. }
  1157. return source;
  1158. }
  1159. function resolveEffectiveMarketplaceRecords(input: {
  1160. configResult: ConfigResult;
  1161. known: KnownMarketplaceRecord[];
  1162. workingDirectory: string;
  1163. }): Array<{ record: KnownMarketplaceRecord; useCachedManifest: boolean }> {
  1164. const declared = resolveDeclaredMarketplaceSources(input);
  1165. const knownIds = new Set(input.known.map((record) => record.id));
  1166. const records = input.known.map((record) => {
  1167. const declarationSource = declared.get(record.id);
  1168. if (!declarationSource) return { record, useCachedManifest: true };
  1169. if (isDeepStrictEqual(record.source, declarationSource)) {
  1170. return { record, useCachedManifest: true };
  1171. }
  1172. // 官方 marketplace id 是 Host 保留身份。Workspace 声明同 id 异 source
  1173. // 只能产生诊断,不能把官方缓存投影替换成 pluginCount=0 的空目录。
  1174. if (isOfficialMarketplaceId(record.id)) {
  1175. return { record, useCachedManifest: true };
  1176. }
  1177. return {
  1178. record: createDeclaredMarketplaceRecord(record.id, declarationSource),
  1179. useCachedManifest: false,
  1180. };
  1181. });
  1182. for (const [marketplaceId, source] of declared) {
  1183. if (knownIds.has(marketplaceId)) continue;
  1184. if (isOfficialMarketplaceId(marketplaceId)) continue;
  1185. records.push({
  1186. record: createDeclaredMarketplaceRecord(marketplaceId, source),
  1187. useCachedManifest: false,
  1188. });
  1189. }
  1190. return records;
  1191. }
  1192. function resolveMarketplaceDeclarationDiagnostics(input: {
  1193. configResult: ConfigResult;
  1194. known: KnownMarketplaceRecord[];
  1195. workingDirectory: string;
  1196. }): PluginLoadOutcome["diagnostics"] {
  1197. const declared = resolveDeclaredMarketplaceSources(input);
  1198. const knownById = new Map(input.known.map((record) => [record.id, record]));
  1199. return [...declared.entries()].flatMap(([marketplaceId, source]) => {
  1200. if (!isOfficialMarketplaceId(marketplaceId)) return [];
  1201. const known = knownById.get(marketplaceId);
  1202. if (known && isDeepStrictEqual(known.source, source)) return [];
  1203. return [createReservedMarketplaceDeclarationDiagnostic(marketplaceId)];
  1204. });
  1205. }
  1206. function createDeclaredMarketplaceRecord(
  1207. marketplaceId: string,
  1208. source: MarketplaceSource,
  1209. ): KnownMarketplaceRecord {
  1210. return {
  1211. id: marketplaceId,
  1212. source,
  1213. name: marketplaceId,
  1214. addedAt: "",
  1215. pluginCount: 0,
  1216. };
  1217. }
  1218. async function materializeDeclaredMarketplaceForExplicitAction(input: {
  1219. abortSignal?: AbortSignal;
  1220. configResult: ConfigResult;
  1221. marketplaceId: string;
  1222. pluginStorageRoot: string;
  1223. workingDirectory: string;
  1224. }): Promise<void> {
  1225. const source = resolveDeclaredMarketplaceSources(input).get(input.marketplaceId);
  1226. if (!source) return;
  1227. const known = loadKnownMarketplacesSync(input.pluginStorageRoot).find(
  1228. (record) => record.id === input.marketplaceId,
  1229. );
  1230. if (known && !isDeepStrictEqual(known.source, source)) {
  1231. throw new MarketplaceSourceRepointError(
  1232. createMarketplaceSourceRepointDiagnostic(input.marketplaceId).message,
  1233. );
  1234. }
  1235. if (known && loadMarketplaceManifestSync(input.pluginStorageRoot, input.marketplaceId)) {
  1236. return;
  1237. }
  1238. await addMarketplace({
  1239. expectedId: input.marketplaceId,
  1240. signal: input.abortSignal,
  1241. source,
  1242. storageRoot: input.pluginStorageRoot,
  1243. });
  1244. }
  1245. function resolvePluginSelector(selector: string, plugins: PluginMetadata[]): PluginMetadata {
  1246. const normalized = selector.trim();
  1247. const exact = plugins.find((plugin) => plugin.id === normalized);
  1248. if (exact) return exact;
  1249. const nameMatches = plugins.filter((plugin) => plugin.name === normalized);
  1250. if (nameMatches.length === 1 && nameMatches[0]) return nameMatches[0];
  1251. if (nameMatches.length > 1) {
  1252. throw new Error(`Plugin name is ambiguous, use full plugin id: ${normalized}`);
  1253. }
  1254. throw new Error(`Plugin not found: ${normalized}`);
  1255. }
  1256. function toMarketplaceSummaryData(
  1257. record: KnownMarketplaceRecord,
  1258. featured?: string[],
  1259. pluginCount?: number,
  1260. ): ZCodeMarketplaceSummaryData {
  1261. return {
  1262. id: record.id,
  1263. name: record.name,
  1264. source: record.source as unknown as Record<string, unknown>,
  1265. ...(record.description ? { description: record.description } : {}),
  1266. ...(record.lastUpdated ? { lastUpdated: record.lastUpdated } : {}),
  1267. pluginCount: pluginCount ?? record.pluginCount,
  1268. isOfficial: isOfficialMarketplaceId(record.id),
  1269. ...(record.lastRefreshFailure
  1270. ? {
  1271. refreshFailure: {
  1272. code: record.lastRefreshFailure.code,
  1273. failedAt: record.lastRefreshFailure.failedAt,
  1274. message: record.lastRefreshFailure.message,
  1275. },
  1276. }
  1277. : {}),
  1278. ...(featured && featured.length > 0 ? { featured } : {}),
  1279. };
  1280. }
  1281. function toAvailablePluginData(
  1282. entry: PluginMarketplaceEntry,
  1283. marketplace: string,
  1284. installedIds: ReadonlySet<string>,
  1285. ): ZCodeAvailablePluginData {
  1286. const id = `${entry.name}@${marketplace}`;
  1287. // 从原始条目读:旧版本缓存的目录不用迁移,下次 overview 就能读到。
  1288. const extensionSummary = parseEntryExtensionSummary(entry.raw);
  1289. return {
  1290. id,
  1291. name: entry.name,
  1292. marketplace,
  1293. ...(entry.description ? { description: entry.description } : {}),
  1294. ...(entry.version ? { version: entry.version } : {}),
  1295. installed: installedIds.has(id),
  1296. componentTypes: inferComponentTypes(entry.raw),
  1297. ...(entry.listing ? { listing: entry.listing } : {}),
  1298. ...(extensionSummary ? { extensionSummary } : {}),
  1299. };
  1300. }
  1301. function toInstalledPluginData(
  1302. record: InstalledPluginRecord,
  1303. enabled: boolean,
  1304. loaded?: PluginMetadata,
  1305. ): ZCodeInstalledPluginData {
  1306. return {
  1307. id: record.id,
  1308. name: record.name,
  1309. marketplace: record.marketplace,
  1310. ...((loaded?.description ?? undefined) ? { description: loaded?.description } : {}),
  1311. version: loaded?.version ?? record.version,
  1312. enabled,
  1313. scope: record.scope,
  1314. installPath: record.installPath,
  1315. installedAt: record.installedAt,
  1316. componentTypes: loaded ? inferComponentTypesFromMetadata(loaded) : undefined,
  1317. ...(loaded ? { hookDetails: loaded.hookDetails } : {}),
  1318. };
  1319. }
  1320. /** 只能由目录条目自报的组件类型(docs/plugins/plugin-publishing.md §4.2)。 */
  1321. const CATALOG_CLAIMED_COMPONENT_TYPES = ["ui", "extension"] as const;
  1322. function inferComponentTypes(raw: Record<string, unknown>): string[] {
  1323. const types: string[] = [];
  1324. if ("agents" in raw) types.push("agent");
  1325. if ("commands" in raw) types.push("command");
  1326. if ("skills" in raw) types.push("skill");
  1327. if ("hooks" in raw) types.push("hook");
  1328. if ("mcpServers" in raw) types.push("mcp");
  1329. if ("lspServers" in raw) types.push("lsp");
  1330. // 目录自报的 ui / extension 只是安装前的宣传,装上后以实际清单为准;CLI 只透传、不判断兼容。
  1331. for (const claimed of CATALOG_CLAIMED_COMPONENT_TYPES) {
  1332. if (Array.isArray(raw.componentTypes) && raw.componentTypes.includes(claimed)) {
  1333. types.push(claimed);
  1334. }
  1335. }
  1336. return types;
  1337. }
  1338. function inferComponentTypesFromMetadata(plugin: PluginMetadata): string[] {
  1339. const types: string[] = [];
  1340. // agent 由约定目录枚举,不一定出现在 manifest;只看 manifest 会让已安装列表漏报子代理能力。
  1341. if (plugin.components.some((group) => group.kind === "agent" && group.items.length > 0)) {
  1342. types.push("agent");
  1343. }
  1344. if (plugin.commandRootCount > 0) types.push("command");
  1345. if (plugin.skillRootCount > 0 || plugin.skillCount > 0) types.push("skill");
  1346. if (plugin.declaredMcpServerNames.length > 0 || plugin.mcpServerNames.length > 0) {
  1347. types.push("mcp");
  1348. }
  1349. if (plugin.hookDetails.length > 0) types.push("hook");
  1350. if (plugin.uiSurfaces?.length) types.push("ui");
  1351. return types;
  1352. }
  1353. function resolvePluginIdForMutation(options: UninstallZCodeMarketplacePluginOptions): string {
  1354. if (options.pluginId) return options.pluginId;
  1355. if (options.pluginName && options.marketplace) {
  1356. return `${options.pluginName}@${options.marketplace}`;
  1357. }
  1358. throw new Error("pluginId or pluginName + marketplace is required");
  1359. }
  1360. function normalizePluginOptions(
  1361. options: Record<string, unknown>,
  1362. ): Record<string, string | number | boolean> {
  1363. const result: Record<string, string | number | boolean> = {};
  1364. for (const [key, value] of Object.entries(options)) {
  1365. if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
  1366. result[key] = value;
  1367. }
  1368. }
  1369. return result;
  1370. }
  1371. function normalizePluginOptionKeys(keys: string[] | undefined): string[] {
  1372. return [...new Set((keys ?? []).map((key) => key.trim()).filter((key) => key.length > 0))];
  1373. }
  1374. function resolvePluginConfigPath(
  1375. options: ResolveZCodePluginsOptions & { scope?: "user" | "workspace" },
  1376. configResult: ConfigResult,
  1377. workingDirectory: string,
  1378. ): string {
  1379. if (options.scope !== "workspace") {
  1380. return configResult.sources.user.path;
  1381. }
  1382. // Workspace Plugin 配置固定落在当前 `<workspace>/.zcode/config.json`。嵌套 workspace
  1383. // 可能同时发现仓库根与自身的配置,读取端 innermost 优先;写入端也必须锁定当前
  1384. // workspace,不能用 project discovery 的第一个 outermost 文件。
  1385. const workspaceConfigPath = join(workingDirectory, ".zcode", "config.json");
  1386. const projectConfigPaths = [
  1387. ...(options.projectConfigPath ? [options.projectConfigPath] : []),
  1388. ...configResult.sources.project.paths,
  1389. ];
  1390. const existingWorkspaceConfig = projectConfigPaths.find(
  1391. (path) =>
  1392. normalizePluginConfigPathForComparison(path) ===
  1393. normalizePluginConfigPathForComparison(workspaceConfigPath),
  1394. );
  1395. if (existingWorkspaceConfig) return existingWorkspaceConfig;
  1396. return workspaceConfigPath;
  1397. }
  1398. export function isWorkspacePluginConfigPath(
  1399. path: string,
  1400. platform: NodeJS.Platform = process.platform,
  1401. ): boolean {
  1402. if (platform === "win32") {
  1403. return (
  1404. win32.basename(path).toLowerCase() === "config.json" &&
  1405. win32.basename(win32.dirname(path)).toLowerCase() === ".zcode"
  1406. );
  1407. }
  1408. return basename(path) === "config.json" && basename(dirname(path)) === ".zcode";
  1409. }
  1410. export function resolveMarketplaceRefreshTargetIds(input: {
  1411. declaredIds: Iterable<string>;
  1412. knownIds: Iterable<string>;
  1413. marketplace?: string;
  1414. }): string[] {
  1415. if (input.marketplace) return [input.marketplace];
  1416. // refresh-all 只刷新已经物化的 Host known records;项目声明必须逐个显式物化,
  1417. // 避免一次全量刷新把任意 Workspace 声明写进全局 marketplace 状态。
  1418. return [...new Set(input.knownIds)];
  1419. }
  1420. function createMarketplaceSourceRepointDiagnostic(
  1421. marketplaceId: string,
  1422. ): PluginLoadOutcome["diagnostics"][number] {
  1423. return {
  1424. code: "plugin_marketplace_invalid",
  1425. message:
  1426. `Workspace marketplace declaration "${marketplaceId}" conflicts with an existing Host source. ` +
  1427. "Remove the existing marketplace or use a different marketplace id before materializing it.",
  1428. pluginId: marketplaceId,
  1429. severity: "error",
  1430. };
  1431. }
  1432. function createReservedMarketplaceDeclarationDiagnostic(
  1433. marketplaceId: string,
  1434. ): PluginLoadOutcome["diagnostics"][number] {
  1435. return {
  1436. code: "plugin_marketplace_declaration_reserved",
  1437. message:
  1438. `Workspace marketplace declaration "${marketplaceId}" uses a reserved official id and was ignored. ` +
  1439. "Use a different marketplace id for project declarations.",
  1440. pluginId: marketplaceId,
  1441. severity: "warning",
  1442. };
  1443. }
  1444. class MarketplaceSourceRepointError extends Error {}
  1445. function toPluginDiagnostic(diagnostic: {
  1446. code: string;
  1447. message: string;
  1448. pluginId?: string;
  1449. severity: "warning" | "error";
  1450. }): PluginLoadOutcome["diagnostics"][number] {
  1451. return {
  1452. code: diagnostic.code as PluginLoadOutcome["diagnostics"][number]["code"],
  1453. message: diagnostic.message,
  1454. ...(diagnostic.pluginId ? { pluginId: diagnostic.pluginId } : {}),
  1455. severity: diagnostic.severity,
  1456. };
  1457. }
  1458. function toMarketplaceInstallDiagnostic(
  1459. error: unknown,
  1460. pluginId: string,
  1461. ): PluginLoadOutcome["diagnostics"][number] {
  1462. const message = error instanceof Error ? error.message : String(error);
  1463. if (error instanceof MarketplaceSourceRepointError) {
  1464. return toPluginDiagnostic({
  1465. code: "plugin_marketplace_invalid",
  1466. message,
  1467. pluginId,
  1468. severity: "error",
  1469. });
  1470. }
  1471. const sourceCode = getPluginSourceDiagnosticCode(error);
  1472. if (sourceCode) {
  1473. return toPluginDiagnostic({
  1474. code: sourceCode,
  1475. message,
  1476. pluginId,
  1477. severity: "error",
  1478. });
  1479. }
  1480. if (message.startsWith("Plugin not found:")) {
  1481. return toPluginDiagnostic({
  1482. code: "plugin_not_found",
  1483. message,
  1484. pluginId,
  1485. severity: "error",
  1486. });
  1487. }
  1488. if (message.includes("Cross-marketplace dependency")) {
  1489. return toPluginDiagnostic({
  1490. code: "plugin_dependency_cross_marketplace",
  1491. message,
  1492. pluginId,
  1493. severity: "error",
  1494. });
  1495. }
  1496. if (message.includes("dependency cycle")) {
  1497. return toPluginDiagnostic({
  1498. code: "plugin_dependency_cycle",
  1499. message,
  1500. pluginId,
  1501. severity: "error",
  1502. });
  1503. }
  1504. if (
  1505. message.includes("Dependency not found") ||
  1506. message.includes("Marketplace not found for dependency")
  1507. ) {
  1508. return toPluginDiagnostic({
  1509. code: "plugin_dependency_missing",
  1510. message,
  1511. pluginId,
  1512. severity: "error",
  1513. });
  1514. }
  1515. if (message.includes("source is recognized but not supported")) {
  1516. return toPluginDiagnostic({
  1517. code: "plugin_marketplace_source_unsupported",
  1518. message,
  1519. pluginId,
  1520. severity: "error",
  1521. });
  1522. }
  1523. return toPluginDiagnostic({
  1524. code: "plugin_marketplace_invalid",
  1525. message,
  1526. pluginId,
  1527. severity: "error",
  1528. });
  1529. }
  1530. function toMarketplaceRefreshDiagnostic(
  1531. error: unknown,
  1532. marketplaceId?: string,
  1533. ): PluginLoadOutcome["diagnostics"][number] {
  1534. const message = error instanceof Error ? error.message : String(error);
  1535. return toPluginDiagnostic({
  1536. code: getPluginSourceDiagnosticCode(error) ?? "plugin_marketplace_invalid",
  1537. message,
  1538. pluginId: marketplaceId,
  1539. severity: "error",
  1540. });
  1541. }