bundled-plugins.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. import { createHash } from "node:crypto";
  2. import {
  3. chmodSync,
  4. existsSync,
  5. mkdirSync,
  6. readdirSync,
  7. readFileSync,
  8. statSync,
  9. writeFileSync,
  10. } from "node:fs";
  11. import { dirname, join, resolve, sep } from "node:path";
  12. import { writeBundledOfficialMarketplacePartitionSync } from "@zcode/adapters";
  13. import { ZCODE_OFFICIAL_PLUGIN_MARKETPLACE, type Logger } from "@zcode/contracts";
  14. import { isZCodeCuaInternalFeatureEnabled, ZCODE_CUA_OFFICIAL_PLUGIN_ID } from "@zcode/shared";
  15. import {
  16. createOfficialPluginCacheRetryBudget,
  17. getOfficialPluginCacheRetryAttempts,
  18. isTransientOfficialPluginCacheFsError,
  19. type OfficialPluginCacheRetryBudget,
  20. removeOfficialPluginCacheDirectory,
  21. renameOfficialPluginCachePath,
  22. } from "./official-plugin-cache-fs.js";
  23. import {
  24. OFFICIAL_PLUGIN_DEFINITIONS,
  25. type OfficialPluginDefinition,
  26. } from "./official-plugin-definitions.js";
  27. import { writeOfficialPluginRuntimeManifest } from "./official-plugin-runtime.js";
  28. import {
  29. isOfficialPluginSeedLockTimeoutError,
  30. withOfficialPluginSeedLock,
  31. } from "./official-plugin-seed-lock.js";
  32. const OFFICIAL_PLUGIN_MARKETPLACE = ZCODE_OFFICIAL_PLUGIN_MARKETPLACE;
  33. const SEA_PLUGIN_ASSET_PREFIX = "zcode-official-plugins/";
  34. const SEA_PLUGIN_MANIFEST_ASSET_KEY = `${SEA_PLUGIN_ASSET_PREFIX}manifest.json`;
  35. const SEED_MARKER_FILE = ".zcode-plugin-seed.json";
  36. const SEED_LOCK_TOTAL_BUDGET_MS = 15_000;
  37. const includedTopLevelPaths = new Set([
  38. ".mcp.json",
  39. ".zcode-plugin",
  40. "README.md",
  41. // 官方内容插件新增 agents 后,filesystem seed 的顶层白名单未同步,目录被静默裁掉。
  42. "agents",
  43. "commands",
  44. "dist",
  45. "docs",
  46. "hooks",
  47. "output-styles",
  48. "package.json",
  49. // Browser skill 会从官方插件根目录动态导入 scripts/browser-client.mjs。
  50. // filesystem seed 若漏掉 scripts,Dev 会连接 node_repl 成功却在首次 Browser Use 时导入失败。
  51. "scripts",
  52. "skills",
  53. "templates",
  54. ]);
  55. interface OfficialPluginSeedFile {
  56. mode?: number;
  57. path: string;
  58. sha256: string;
  59. sourcePath?: string;
  60. }
  61. interface OfficialPluginSeedPluginSource {
  62. definition: OfficialPluginDefinition;
  63. files: OfficialPluginSeedFile[];
  64. hash: string;
  65. missingSeedPaths: string[];
  66. rootPath?: string;
  67. }
  68. interface OfficialPluginSeedSource {
  69. kind: "filesystem" | "sea";
  70. plugins: OfficialPluginSeedPluginSource[];
  71. }
  72. interface SeaOfficialPluginManifest {
  73. hash: string;
  74. plugins: Array<{
  75. files: OfficialPluginSeedFile[];
  76. marketplace: string;
  77. name: string;
  78. version: string;
  79. }>;
  80. version: 1;
  81. }
  82. type SeaModule = typeof import("node:sea");
  83. function seedBundledOfficialPlugins(input: {
  84. logger?: Logger;
  85. storageRoot: string;
  86. }): OfficialPluginDefinition[] {
  87. const source = resolveSeedSource();
  88. if (!source) return [];
  89. // Catalog/cache 是内置插件的不可变产品资产;Runtime 是否加载由 discovery 的抑制态决定,
  90. // 不能在 seed 阶段删除或过滤,否则卸载后详情页无法读取组件,也无法恢复。
  91. writeOfficialMarketplace(input.storageRoot, source);
  92. const retryBudget = createOfficialPluginCacheRetryBudget();
  93. // 等锁超时降级后循环会继续;若每个插件独立重置 15s 等待预算,成组遗留的
  94. // 锁会让启动同步冻结 N×15s。全部插件共享同一截止时间:无争用的锁仍瞬时获取(mkdir
  95. // 一次成功不查预算),预算耗尽后有争用的锁立即降级,seeding 总等待封顶 15s。
  96. const seedLockDeadlineAt = Date.now() + SEED_LOCK_TOTAL_BUDGET_MS;
  97. const failedSeeds: OfficialPluginDefinition[] = [];
  98. for (const plugin of source.plugins) {
  99. const pluginId = `${plugin.definition.name}@${OFFICIAL_PLUGIN_MARKETPLACE}`;
  100. const targetRoot = officialPluginCacheRoot(input.storageRoot, plugin.definition);
  101. // 入口旁的插件拷贝可能与新定义错配(升级中的桌面包、旧 checkout 未构建 dist)。
  102. // 缺 requiredSeedPaths 时 seed 源解析曾直接抛错,一个残缺插件把全部插件连同会话恢复
  103. // 一起炸成 resumeFailed。残缺只作用于单插件:拒绝写缓存,按既有降级协议告警并回退到可用旧缓存。
  104. if (plugin.missingSeedPaths.length > 0) {
  105. warnCacheDegraded(input.logger, {
  106. error: Object.assign(
  107. new Error(
  108. `Bundled official plugin ${plugin.definition.name} is missing required seed assets: ${plugin.missingSeedPaths.join(", ")}`,
  109. ),
  110. { code: "ZCODE_PLUGIN_SEED_INCOMPLETE" },
  111. ),
  112. missingSeedPaths: plugin.missingSeedPaths,
  113. operation: "seed_plugin",
  114. pluginId,
  115. targetRoot,
  116. });
  117. failedSeeds.push(plugin.definition);
  118. continue;
  119. }
  120. try {
  121. withOfficialPluginSeedLock(
  122. targetRoot,
  123. () => {
  124. // 桌面会并发预热多个 workspace Agent;复制插件资源时,
  125. // 多进程会互删 target 并在 Windows rename 时触发 EPERM。拿锁后必须二次检查,
  126. // 让等待者直接复用首个进程已经提交的完整缓存。
  127. if (isSeedCurrent(targetRoot, plugin)) {
  128. cleanupLegacySeedBackup(targetRoot, retryBudget);
  129. const manifestWritten = tryWriteOfficialPluginRuntimeManifest({
  130. pluginName: plugin.definition.name,
  131. retryBudget,
  132. rootPath: targetRoot,
  133. });
  134. if (manifestWritten) return;
  135. }
  136. const temporaryRoot = `${targetRoot}.tmp-${process.pid}-${Date.now()}`;
  137. removeOfficialPluginCacheDirectory(temporaryRoot, retryBudget);
  138. mkdirSync(temporaryRoot, { recursive: true });
  139. try {
  140. for (const file of plugin.files) {
  141. const bytes = readSeedFileBytes(source, plugin, file);
  142. if (hashBytes(bytes) !== file.sha256) {
  143. throw new Error(
  144. `Bundled plugin asset hash mismatch: ${plugin.definition.name}/${file.path}`,
  145. );
  146. }
  147. const outputPath = join(temporaryRoot, ...file.path.split("/"));
  148. mkdirSync(dirname(outputPath), { recursive: true });
  149. writeFileSync(outputPath, bytes);
  150. chmodSync(outputPath, modeForSeedFile(file.path, file.mode));
  151. }
  152. writeFileSync(
  153. join(temporaryRoot, SEED_MARKER_FILE),
  154. JSON.stringify(seedMarker(source, plugin), null, 2),
  155. );
  156. replaceSeedRoot(temporaryRoot, targetRoot, plugin, retryBudget);
  157. writeOfficialPluginRuntimeManifest({
  158. pluginName: plugin.definition.name,
  159. retryBudget,
  160. rootPath: targetRoot,
  161. });
  162. } catch (error) {
  163. try {
  164. removeOfficialPluginCacheDirectory(temporaryRoot, retryBudget);
  165. } catch {
  166. // 临时目录清理失败不能覆盖真正的 seed 错误;目录名唯一,不会污染后续加载。
  167. }
  168. throw error;
  169. }
  170. },
  171. { timeoutMs: Math.max(0, seedLockDeadlineAt - Date.now()) },
  172. );
  173. } catch (error) {
  174. if (
  175. isTransientOfficialPluginCacheFsError(error) ||
  176. // seed lock 等待超时只说明同版本缓存锁被别的进程持有或遗留(Windows 上
  177. // 删不掉的遗留锁 + PID 复用会让接管长期不触发)。seeding 只是刷新缓存,超时必须
  178. // 走既有降级协议回退到可用缓存并告警,不能把会话恢复整体炸成 resumeFailed。
  179. isOfficialPluginSeedLockTimeoutError(error) ||
  180. // 多个 workspace app 会并发 seed 同一份官方插件缓存。当前进程
  181. // 写 runtime manifest 时,并发赢家可能已经原子替换整个 targetRoot,连同本进程
  182. // 的临时文件一起移走,rename 因此返回 ENOENT。只在新 target 已由 marker 证明
  183. // 完整时降级;目标缺失或仍旧时继续抛错,不能掩盖真实缓存损坏。
  184. (isNotFoundFsError(error) && isSeedCurrent(targetRoot, plugin))
  185. ) {
  186. warnCacheDegraded(input.logger, {
  187. error,
  188. operation: "seed_plugin",
  189. pluginId,
  190. targetRoot,
  191. });
  192. failedSeeds.push(plugin.definition);
  193. continue;
  194. }
  195. throw error;
  196. }
  197. }
  198. return failedSeeds;
  199. }
  200. function tryWriteOfficialPluginRuntimeManifest(input: {
  201. pluginName: string;
  202. retryBudget: OfficialPluginCacheRetryBudget;
  203. rootPath: string;
  204. }): boolean {
  205. try {
  206. writeOfficialPluginRuntimeManifest(input);
  207. return true;
  208. } catch (error) {
  209. if (isTransientOfficialPluginCacheFsError(error)) throw error;
  210. return false;
  211. }
  212. }
  213. export function resolveOfficialPluginRoots(input: {
  214. env?: NodeJS.ProcessEnv;
  215. extraRoots?: string[];
  216. logger?: Logger;
  217. storageRoot: string;
  218. suppressedBuiltins?: ReadonlySet<string>;
  219. }): string[] {
  220. const suppressedBuiltins = new Set(input.suppressedBuiltins ?? []);
  221. // zcode-cua 内置 plugin 默认不启用,由 feature flag 控制加载。在 seed/discovery 层门控
  222. // (而非只隐藏某个 UI 面),这样开关关闭时用户无法经 plugin 列表/marketplace/MCP 设置/CLI 命令看到它。
  223. if (!isZCodeCuaInternalFeatureEnabled(input.env ?? process.env)) {
  224. suppressedBuiltins.add(ZCODE_CUA_OFFICIAL_PLUGIN_ID);
  225. }
  226. const failedSeeds = seedBundledOfficialPlugins({
  227. logger: input.logger,
  228. storageRoot: input.storageRoot,
  229. });
  230. const fallbackRoots = failedSeeds.flatMap((definition) => {
  231. // CUA 的 frame contract 随 wrapper 与 producer 原子升级。加载旧版本
  232. // cache 会把旧 block 布局接到新 consumer 上;当前 cache 不可用时宁可不注册 CUA。
  233. if (`${definition.name}@${OFFICIAL_PLUGIN_MARKETPLACE}` === ZCODE_CUA_OFFICIAL_PLUGIN_ID) {
  234. return [];
  235. }
  236. const fallbackRoot = findUsableOfficialPluginFallback(input.storageRoot, definition);
  237. return fallbackRoot ? [fallbackRoot] : [];
  238. });
  239. return uniquePaths([...(input.extraRoots ?? []), ...fallbackRoots]);
  240. }
  241. function resolveSeedSource(): OfficialPluginSeedSource | undefined {
  242. const seaSource = resolveSeaSeedSource();
  243. if (seaSource) return seaSource;
  244. return resolveFilesystemSeedSource();
  245. }
  246. function resolveSeaSeedSource(): OfficialPluginSeedSource | undefined {
  247. const sea = getSeaModule();
  248. if (!sea?.isSea()) return undefined;
  249. const manifest = readSeaManifest(sea);
  250. if (!manifest) return undefined;
  251. const plugins = OFFICIAL_PLUGIN_DEFINITIONS.flatMap((definition) => {
  252. const plugin = manifest.plugins.find(
  253. (item) =>
  254. item.marketplace === OFFICIAL_PLUGIN_MARKETPLACE &&
  255. item.name === definition.name &&
  256. item.version === definition.version,
  257. );
  258. if (!plugin) return [];
  259. return [
  260. {
  261. definition,
  262. files: plugin.files,
  263. hash: hashSeedFiles(plugin.files),
  264. missingSeedPaths: findMissingOfficialPluginSeedPaths(definition, plugin.files),
  265. },
  266. ];
  267. });
  268. if (plugins.length === 0) return undefined;
  269. return {
  270. kind: "sea",
  271. plugins,
  272. };
  273. }
  274. function resolveFilesystemSeedSource(): OfficialPluginSeedSource | undefined {
  275. const plugins = OFFICIAL_PLUGIN_DEFINITIONS.flatMap((definition) => {
  276. const rootPath = resolveFilesystemPluginRoot(definition);
  277. if (!rootPath) return [];
  278. const files = collectFilesystemPluginFiles(rootPath, definition);
  279. return [
  280. {
  281. definition,
  282. files,
  283. hash: hashSeedFiles(files),
  284. missingSeedPaths: findMissingOfficialPluginSeedPaths(definition, files),
  285. rootPath,
  286. },
  287. ];
  288. });
  289. if (plugins.length === 0) return undefined;
  290. return {
  291. kind: "filesystem",
  292. plugins,
  293. };
  294. }
  295. function findMissingOfficialPluginSeedPaths(
  296. definition: Pick<OfficialPluginDefinition, "requiredSeedPaths">,
  297. files: ReadonlyArray<{ path: string }>,
  298. ): string[] {
  299. const availablePaths = new Set(files.map((file) => file.path));
  300. return (definition.requiredSeedPaths ?? []).filter(
  301. (requiredPath) => !availablePaths.has(requiredPath),
  302. );
  303. }
  304. function getSeaModule(): SeaModule | undefined {
  305. const getBuiltinModule = process.getBuiltinModule as ((id: "node:sea") => SeaModule) | undefined;
  306. try {
  307. return getBuiltinModule?.("node:sea");
  308. } catch {
  309. return undefined;
  310. }
  311. }
  312. function readSeaManifest(sea: SeaModule): SeaOfficialPluginManifest | undefined {
  313. try {
  314. const raw = sea.getAsset(SEA_PLUGIN_MANIFEST_ASSET_KEY, "utf8");
  315. const manifest = JSON.parse(raw) as SeaOfficialPluginManifest;
  316. return manifest.version === 1 && Array.isArray(manifest.plugins) ? manifest : undefined;
  317. } catch {
  318. return undefined;
  319. }
  320. }
  321. function resolveFilesystemPluginRoot(definition: OfficialPluginDefinition): string | undefined {
  322. for (const baseDir of candidateBaseDirs()) {
  323. for (const relativePath of definition.rootCandidates) {
  324. const rootPath = resolve(baseDir, relativePath);
  325. if (existsSync(join(rootPath, ".zcode-plugin", "plugin.json"))) return rootPath;
  326. }
  327. }
  328. return undefined;
  329. }
  330. function collectFilesystemPluginFiles(
  331. rootPath: string,
  332. definition: OfficialPluginDefinition,
  333. ): OfficialPluginSeedFile[] {
  334. const files: OfficialPluginSeedFile[] = [];
  335. const allowedTopLevelPaths = new Set([
  336. ...includedTopLevelPaths,
  337. ...(definition.runtimeTopLevelPaths ?? []),
  338. ]);
  339. for (const sourcePath of walkFiles(rootPath, allowedTopLevelPaths)) {
  340. const relativePath = toPosixPath(sourcePath.slice(rootPath.length + 1));
  341. if (!shouldIncludePluginFile(relativePath, allowedTopLevelPaths)) continue;
  342. const bytes = readFileSync(sourcePath);
  343. files.push({
  344. mode: modeForSeedFile(relativePath, statSync(sourcePath).mode),
  345. path: relativePath,
  346. sha256: hashBytes(bytes),
  347. sourcePath,
  348. });
  349. }
  350. return files.sort((left, right) => left.path.localeCompare(right.path));
  351. }
  352. function* walkFiles(
  353. directory: string,
  354. allowedTopLevelPaths: ReadonlySet<string>,
  355. depth = 0,
  356. ): Generator<string> {
  357. for (const entry of readdirSync(directory, { withFileTypes: true })) {
  358. if (shouldSkipDirectory(entry.name, depth, allowedTopLevelPaths)) continue;
  359. const fullPath = join(directory, entry.name);
  360. if (entry.isDirectory()) {
  361. yield* walkFiles(fullPath, allowedTopLevelPaths, depth + 1);
  362. continue;
  363. }
  364. if (entry.isFile()) yield fullPath;
  365. }
  366. }
  367. function readSeedFileBytes(
  368. source: OfficialPluginSeedSource,
  369. plugin: OfficialPluginSeedPluginSource,
  370. file: OfficialPluginSeedFile,
  371. ): Buffer {
  372. if (source.kind === "filesystem" && file.sourcePath) return readFileSync(file.sourcePath);
  373. const sea = getSeaModule();
  374. if (!sea?.isSea()) throw new Error("SEA plugin asset is unavailable outside SEA runtime.");
  375. return Buffer.from(
  376. sea.getRawAsset(
  377. `${SEA_PLUGIN_ASSET_PREFIX}${OFFICIAL_PLUGIN_MARKETPLACE}/${plugin.definition.name}/${plugin.definition.version}/${file.path}`,
  378. ),
  379. );
  380. }
  381. function writeOfficialMarketplace(storageRoot: string, source: OfficialPluginSeedSource): void {
  382. writeBundledOfficialMarketplacePartitionSync({
  383. manifest: {
  384. name: OFFICIAL_PLUGIN_MARKETPLACE,
  385. plugins: source.plugins.map((plugin) => {
  386. // 商店信息(listing)与描述随目录条目下发:键名与 CDN 目录 schema 一致,
  387. // 由 adapter 的同一套 parseEntryStoreListing 解析,UI 才能给内置插件渲染
  388. // 显示名/分类/作者/示例提示词。描述取自插件包内 plugin.json(单一事实源)。
  389. const description = readSeedPluginDescription(source, plugin);
  390. return {
  391. cachePath: officialPluginCacheRoot(storageRoot, plugin.definition),
  392. ...(description ? { description } : {}),
  393. name: plugin.definition.name,
  394. source: source.kind,
  395. version: plugin.definition.version,
  396. ...(plugin.definition.listing ?? {}),
  397. };
  398. }),
  399. version: 1,
  400. },
  401. storageRoot,
  402. });
  403. }
  404. /** 从 seed 文件集中读插件 plugin.json 的 description;读取/解析失败按 undefined 降级。 */
  405. function readSeedPluginDescription(
  406. source: OfficialPluginSeedSource,
  407. plugin: OfficialPluginSeedPluginSource,
  408. ): string | undefined {
  409. const manifestFile = plugin.files.find((file) => file.path === ".zcode-plugin/plugin.json");
  410. if (!manifestFile) return undefined;
  411. try {
  412. const parsed = JSON.parse(readSeedFileBytes(source, plugin, manifestFile).toString("utf8")) as {
  413. description?: unknown;
  414. };
  415. return typeof parsed.description === "string" && parsed.description.trim().length > 0
  416. ? parsed.description
  417. : undefined;
  418. } catch {
  419. return undefined;
  420. }
  421. }
  422. function isSeedCurrent(targetRoot: string, plugin: OfficialPluginSeedPluginSource): boolean {
  423. const markerPath = join(targetRoot, SEED_MARKER_FILE);
  424. if (!existsSync(markerPath)) return false;
  425. try {
  426. const marker = JSON.parse(readFileSync(markerPath, "utf8")) as ReturnType<typeof seedMarker>;
  427. return marker.hash === plugin.hash && marker.pluginVersion === plugin.definition.version;
  428. } catch {
  429. return false;
  430. }
  431. }
  432. /**
  433. * 旧版本缓存只要插件清单和运行所需文件完整,就可以继续服务当前会话。
  434. * marker hash 不匹配只表示需要升级,不能把一个可用的旧缓存当成启动失败。
  435. */
  436. function isSeedUsable(targetRoot: string, definition: OfficialPluginDefinition): boolean {
  437. try {
  438. const manifest = JSON.parse(
  439. readFileSync(join(targetRoot, ".zcode-plugin", "plugin.json"), "utf8"),
  440. ) as { name?: unknown };
  441. if (manifest.name !== definition.name) return false;
  442. } catch {
  443. return false;
  444. }
  445. return (definition.requiredSeedPaths ?? []).every((requiredPath) =>
  446. existsSync(join(targetRoot, ...requiredPath.split("/"))),
  447. );
  448. }
  449. function findUsableOfficialPluginFallback(
  450. storageRoot: string,
  451. definition: OfficialPluginDefinition,
  452. ): string | undefined {
  453. const targetRoot = officialPluginCacheRoot(storageRoot, definition);
  454. if (isSeedUsable(targetRoot, definition)) return undefined;
  455. let entries;
  456. try {
  457. entries = readdirSync(dirname(targetRoot), { withFileTypes: true });
  458. } catch (error) {
  459. if (isNotFoundFsError(error)) return undefined;
  460. throw error;
  461. }
  462. return entries
  463. .filter(
  464. (entry) =>
  465. entry.isDirectory() &&
  466. entry.name !== definition.version &&
  467. !entry.name.includes(".backup") &&
  468. // 锁目录(含 .seed-lock.stale-*)与版本目录同级;超时降级后锁必然在场,
  469. // 不能依赖 isSeedUsable 的内容检查兜底,按名字直接排除。
  470. !entry.name.includes(".seed-lock") &&
  471. !entry.name.includes(".tmp-"),
  472. )
  473. .sort((left, right) =>
  474. right.name.localeCompare(left.name, undefined, { numeric: true, sensitivity: "base" }),
  475. )
  476. .map((entry) => join(dirname(targetRoot), entry.name))
  477. .find((rootPath) => isSeedUsable(rootPath, definition));
  478. }
  479. function replaceSeedRoot(
  480. temporaryRoot: string,
  481. targetRoot: string,
  482. plugin: OfficialPluginSeedPluginSource,
  483. retryBudget: OfficialPluginCacheRetryBudget,
  484. ): void {
  485. const backupRoot = createSeedBackupRoot(targetRoot);
  486. let movedTargetToBackup = false;
  487. mkdirSync(dirname(targetRoot), { recursive: true });
  488. if (existsSync(targetRoot)) {
  489. try {
  490. renameOfficialPluginCachePath(targetRoot, backupRoot, retryBudget);
  491. movedTargetToBackup = true;
  492. } catch (error) {
  493. // 官方插件缓存由桌面窗口、协议与 CLI 入口共享。existsSync 之后,
  494. // 另一个进程可能先移走 target;此处只收敛这个 TOCTOU 的 ENOENT,随后继续
  495. // promote 或由 isSeedCurrent 识别并发赢家,其他缺失错误仍保持原有 fatal 语义。
  496. if (!isNotFoundFsError(error)) throw error;
  497. }
  498. }
  499. try {
  500. renameOfficialPluginCachePath(temporaryRoot, targetRoot, retryBudget);
  501. } catch (error) {
  502. if (isSeedCurrent(targetRoot, plugin)) {
  503. removeOfficialPluginCacheDirectory(temporaryRoot, retryBudget);
  504. if (movedTargetToBackup) {
  505. removeOfficialPluginCacheDirectory(backupRoot, retryBudget);
  506. }
  507. cleanupLegacySeedBackup(targetRoot, retryBudget);
  508. return;
  509. }
  510. if (movedTargetToBackup && !existsSync(targetRoot) && existsSync(backupRoot)) {
  511. renameOfficialPluginCachePath(backupRoot, targetRoot, retryBudget);
  512. }
  513. throw error;
  514. }
  515. if (movedTargetToBackup) {
  516. removeOfficialPluginCacheDirectory(backupRoot, retryBudget);
  517. }
  518. cleanupLegacySeedBackup(targetRoot, retryBudget);
  519. }
  520. function cleanupLegacySeedBackup(
  521. targetRoot: string,
  522. retryBudget: OfficialPluginCacheRetryBudget,
  523. ): void {
  524. const backupRoot = `${targetRoot}.backup`;
  525. if (!existsSync(backupRoot)) return;
  526. // 旧版固定 backup 没有事务归属,target 暂时缺失时可能属于另一个仍在
  527. // promote 的进程,不能把它恢复回去。仅在当前 seed 已确认可用后清理这个遗留目录。
  528. removeOfficialPluginCacheDirectory(backupRoot, retryBudget);
  529. }
  530. function createSeedBackupRoot(targetRoot: string): string {
  531. // 固定 backup 会被并发启动进程共同当作 rollback 点;每次替换使用唯一目录,
  532. // catch 分支只恢复自己移动出的 target,避免一个进程窃取另一个进程的事务状态。
  533. return `${targetRoot}.backup-${process.pid}-${Date.now()}`;
  534. }
  535. function isNotFoundFsError(error: unknown): error is NodeJS.ErrnoException {
  536. return (
  537. typeof error === "object" &&
  538. error !== null &&
  539. String((error as NodeJS.ErrnoException).code) === "ENOENT"
  540. );
  541. }
  542. function warnCacheDegraded(
  543. logger: Logger | undefined,
  544. input: {
  545. error: NodeJS.ErrnoException;
  546. missingSeedPaths?: readonly string[];
  547. operation: "remove_suppressed_plugin" | "seed_plugin";
  548. pluginId: string;
  549. targetRoot: string;
  550. },
  551. ): void {
  552. logger?.warn("Official plugin cache operation degraded", {
  553. attempts: getOfficialPluginCacheRetryAttempts(input.error),
  554. degraded: true,
  555. errorCode: input.error.code,
  556. ...(input.missingSeedPaths ? { missingSeedPaths: input.missingSeedPaths } : {}),
  557. module: "bootstrap.official_plugin_cache",
  558. operation: input.operation,
  559. pluginId: input.pluginId,
  560. targetRoot: input.targetRoot,
  561. });
  562. }
  563. function seedMarker(source: OfficialPluginSeedSource, plugin: OfficialPluginSeedPluginSource) {
  564. return {
  565. hash: plugin.hash,
  566. marketplace: OFFICIAL_PLUGIN_MARKETPLACE,
  567. plugin: plugin.definition.name,
  568. pluginVersion: plugin.definition.version,
  569. source: source.kind,
  570. version: 1,
  571. };
  572. }
  573. function officialPluginCacheRoot(
  574. storageRoot: string,
  575. definition: OfficialPluginDefinition,
  576. ): string {
  577. return join(
  578. storageRoot,
  579. "cache",
  580. OFFICIAL_PLUGIN_MARKETPLACE,
  581. definition.name,
  582. definition.version,
  583. );
  584. }
  585. /** 内置技能包(bundled-skills.ts)沿同一组候选目录定位,保证两类内置资产在每种运行布局下同进同出。 */
  586. export function candidateBaseDirs(): string[] {
  587. // 修复原因:Electron app-server 运行在 resources/glm/zcode.cjs,官方插件资源也随桌面包
  588. // stage 到同级 packages/*-plugin。候选目录必须优先看入口文件目录,避免生产态退回到
  589. // monorepo-only 的 __dirname 查找假设。
  590. return [entrypointDir(), runtimeDir(), process.cwd()].filter(
  591. (dir): dir is string => typeof dir === "string",
  592. );
  593. }
  594. function runtimeDir(): string | undefined {
  595. return typeof __dirname === "string" ? __dirname : undefined;
  596. }
  597. function entrypointDir(): string | undefined {
  598. return process.argv[1] ? dirname(process.argv[1]) : undefined;
  599. }
  600. function shouldSkipDirectory(
  601. name: string,
  602. depth: number,
  603. allowedTopLevelPaths: ReadonlySet<string>,
  604. ): boolean {
  605. if (name === ".turbo" || name === "coverage" || name === ".venv" || name === "__pycache__") {
  606. return true;
  607. }
  608. return name === "node_modules" && !(depth === 0 && allowedTopLevelPaths.has(name));
  609. }
  610. function shouldIncludePluginFile(
  611. relativePath: string,
  612. allowedTopLevelPaths: ReadonlySet<string>,
  613. ): boolean {
  614. const segments = relativePath.split("/");
  615. if (segments.includes(".DS_Store") || segments.some((segment) => segment.endsWith(".pyc"))) {
  616. return false;
  617. }
  618. const [topLevel] = relativePath.split("/");
  619. return topLevel !== undefined && allowedTopLevelPaths.has(topLevel);
  620. }
  621. function modeForSeedFile(filePath: string, sourceMode?: number): number {
  622. if (sourceMode !== undefined && (sourceMode & 0o111) !== 0) return 0o755;
  623. const normalizedPath = toPosixPath(filePath);
  624. // official plugin seed 会重写缓存文件权限。部分插件通过 polyglot shell wrapper
  625. // 直接执行 hook 脚本,若落盘成 0644 会 permission denied。这里保留源码执行位,
  626. // 并对 SEA/旧 manifest 缺少 mode 的 hook 脚本兜底。
  627. if (/(?:^|\/)dist\/mcp\/server\.js$/i.test(normalizedPath)) return 0o755;
  628. if (/^hooks\//u.test(normalizedPath) && !/\.(json|md|txt)$/iu.test(normalizedPath)) {
  629. return 0o755;
  630. }
  631. return 0o644;
  632. }
  633. function hashSeedFiles(files: OfficialPluginSeedFile[]): string {
  634. return hashText(
  635. JSON.stringify(
  636. files.map((file) => [file.path, file.sha256, modeForSeedFile(file.path, file.mode)]),
  637. ),
  638. );
  639. }
  640. function toPosixPath(value: string): string {
  641. return value.split(sep).join("/");
  642. }
  643. function uniquePaths(paths: string[]): string[] {
  644. return paths.filter((path, index) => paths.indexOf(path) === index);
  645. }
  646. function hashBytes(bytes: Buffer): string {
  647. return createHash("sha256").update(bytes).digest("hex");
  648. }
  649. function hashText(text: string): string {
  650. return hashBytes(Buffer.from(text));
  651. }