prepare-prebuilds.mjs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. #!/usr/bin/env node
  2. /* eslint-disable max-lines */
  3. import {
  4. chmodSync,
  5. copyFileSync,
  6. cpSync,
  7. createWriteStream,
  8. existsSync,
  9. mkdirSync,
  10. mkdtempSync,
  11. readdirSync,
  12. readFileSync,
  13. renameSync,
  14. rmSync,
  15. writeFileSync,
  16. } from "node:fs";
  17. import { createHash } from "node:crypto";
  18. import { tmpdir } from "node:os";
  19. import { basename, dirname, join, resolve } from "node:path";
  20. import process from "node:process";
  21. import { Readable } from "node:stream";
  22. import { pipeline } from "node:stream/promises";
  23. import { fileURLToPath, pathToFileURL } from "node:url";
  24. import { createRequire } from "node:module";
  25. import {
  26. LEGACY_REMOTE_RIPGREP_VERSION,
  27. NATIVE_SEARCH_PREBUILT_RELEASES,
  28. resolveNativeSearchArtifactSource,
  29. resolveNativeSearchPrebuiltRelease,
  30. } from "./native-search-tools-config.mjs";
  31. import { resolveRemoteNativeSearchPrebuiltPlan } from "./remote-native-search-tools-config.mjs";
  32. import { prepareNativeSearchTools } from "./prepare-native-search-tools.mjs";
  33. import {
  34. stageNativeSearchNotices,
  35. stageNodeNotices,
  36. stageThirdPartyNotices,
  37. } from "./third-party-notices.mjs";
  38. import {
  39. computeDeterministicSourceSha256 as computeComponentSourceSha256,
  40. packSourceAsDeterministicTarGzip as packComponentSourceAsArchive,
  41. } from "./deterministic-tar-archive.mjs";
  42. import { runCommand } from "./spawn-command.mjs";
  43. export { computeComponentSourceSha256, packComponentSourceAsArchive };
  44. const require = createRequire(import.meta.url);
  45. const scriptDir = dirname(fileURLToPath(import.meta.url));
  46. const rootDir = resolve(scriptDir, "..");
  47. const desktopDir = join(rootDir, "packages/desktop");
  48. const mockCdnDir = join(desktopDir, "mock-cdn");
  49. const version = require(join(rootDir, "package.json")).version;
  50. const ZCODE_AGENT_RUNTIME = {
  51. glm: {
  52. version: readZCodeAgentRuntimeVersion(),
  53. },
  54. };
  55. const releaseDir = join(mockCdnDir, "releases", version);
  56. const nodeVersion = "v22.16.0";
  57. const componentSchemaVersion = 1;
  58. const remotePlatforms = ["linux-arm64", "linux-x64", "darwin-arm64", "darwin-x64"];
  59. const pnpmCommand = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
  60. const isBootstrapWithRemote = process.env.ZCODE_BOOTSTRAP_WITH_REMOTE === "1";
  61. /**
  62. * Node dist 下载源。默认走国内镜像,`ZCODE_NODE_DIST_MIRROR` 可覆盖(与
  63. * `.gitlab/ci/00-workflow.yml` 的同名 CI 变量、`scripts/cua-helper-sea-base.mjs` 同一约定)。
  64. *
  65. * 这里原本硬编码 `https://nodejs.org/dist`,而 macOS
  66. * runner 连不上它 —— 3 次尝试全部 `UND_ERR_CONNECT_TIMEOUT`(10s)。更糟的是本文件的报错文案
  67. * 一直在让人「检查 Node.js 镜像地址」,可当时根本没有这个旋钮。
  68. *
  69. * 为什么之前没暴露:`mock-cdn` 靠 GIT_CLEAN_FLAGS 排除项跨 job 持久化,而
  70. * `build:remote:assets` 每次都 `rm -rf` 掉除自己 $VERSION 以外的所有 release 目录。
  71. * 不同版本目录因此互相驱逐持久化产物,谁被驱逐谁就必须回源下载。
  72. * 平时都是 `[skip] already exists`,所以这条网络路径长期没被真正走过。
  73. */
  74. export const DEFAULT_NODE_DIST_BASE = "https://cdn.npmmirror.com/binaries/node";
  75. export function nodeDistBase(env = process.env) {
  76. const mirror = env.ZCODE_NODE_DIST_MIRROR?.trim();
  77. return (mirror || DEFAULT_NODE_DIST_BASE).replace(/\/+$/u, "");
  78. }
  79. const BROWSER_USE_PLUGIN_PACKAGE_NAME = "@zcode/browser-use-plugin";
  80. // node_repl 宿主抽成独立包 @zcode/node-repl-host 之后,browser-use
  81. // 不再产出 dist/mcp/server.js,CUA 资产也已归 @zcode/zcode-cua-plugin。这是**第三份**平行清单
  82. // (另两份:packages/desktop/scripts/prepare-agent-node-bundle.mjs 的生产打包、
  83. // scripts/build-desktop-agent-cli.mjs 的 dev 构建),当时只改了 dev 那份,于是先后在
  84. // build:macos:arm64 与 build:remote:assets 上以 "missing runtime" 挂掉两次。
  85. // 权威归属见 bootstrap/official-plugin-definitions.ts。
  86. const browserUseRequiredRuntimePaths = [
  87. "scripts/browser-client.mjs",
  88. "docs/api.json",
  89. "docs/documents.json",
  90. "docs/overview.md",
  91. // remote prebuild 必须和桌面 seed 使用同一录屏文档完整性合同。
  92. "docs/recording.md",
  93. "docs/workflow.md",
  94. "skills/control-browser/SKILL.md",
  95. "skills/web-gui-tester/SKILL.md",
  96. ];
  97. const remoteOfficialPluginPackages = [
  98. {
  99. packageName: "@zcode/android-emulator-plugin",
  100. relativePath: "apps/zcode-cli/packages/android-emulator-plugin",
  101. requiresRuntime: true,
  102. requiredRuntimePaths: ["dist/mcp/server.js"],
  103. runtimeBuildScript: "scripts/build-mcp.mjs",
  104. stagedPath: "packages/android-emulator-plugin",
  105. },
  106. {
  107. packageName: "@zcode/documents-plugin",
  108. relativePath: "apps/zcode-cli/packages/documents-plugin",
  109. requiresRuntime: false,
  110. stagedPath: "packages/documents-plugin",
  111. },
  112. {
  113. packageName: "@zcode/image-search-plugin",
  114. relativePath: "apps/zcode-cli/packages/image-search-plugin",
  115. requiresRuntime: false,
  116. stagedPath: "packages/image-search-plugin",
  117. },
  118. {
  119. packageName: "@zcode/pdf-plugin",
  120. relativePath: "apps/zcode-cli/packages/pdf-plugin",
  121. requiresRuntime: false,
  122. stagedPath: "packages/pdf-plugin",
  123. },
  124. {
  125. packageName: "@zcode/presentations-plugin",
  126. relativePath: "apps/zcode-cli/packages/presentations-plugin",
  127. requiresRuntime: false,
  128. stagedPath: "packages/presentations-plugin",
  129. },
  130. {
  131. packageName: "@zcode/spreadsheets-plugin",
  132. relativePath: "apps/zcode-cli/packages/spreadsheets-plugin",
  133. requiresRuntime: false,
  134. stagedPath: "packages/spreadsheets-plugin",
  135. },
  136. {
  137. packageName: "@zcode/visualize-plugin",
  138. relativePath: "apps/zcode-cli/packages/visualize-plugin",
  139. requiresRuntime: false,
  140. requiredSeedPaths: [
  141. "skills/visualize/SKILL.md",
  142. "skills/visualize/references/api.md",
  143. "skills/visualize/references/styles.md",
  144. "skills/visualize/tweak.md",
  145. "skills/visualize/LICENSE.md",
  146. "skills/visualize/scripts/render.py",
  147. "skills/visualize/assets/visualize.css",
  148. "skills/visualize/assets/visualize.html",
  149. "skills/visualize/assets/calendar.js",
  150. "skills/visualize/assets/runtime-manifest.json",
  151. "skills/visualize/scripts/vendor.py",
  152. "skills/visualize/assets/vendor/manifest.json",
  153. "skills/visualize/assets/vendor/floating-ui-core-1.7.3.min.js",
  154. "skills/visualize/assets/vendor/floating-ui-core-1.7.3.min.js.LICENSE",
  155. "skills/visualize/assets/vendor/floating-ui-dom-1.7.4.min.js",
  156. "skills/visualize/assets/vendor/floating-ui-dom-1.7.4.min.js.LICENSE",
  157. "skills/visualize/assets/vendor/lucide-1.17.0.js",
  158. "skills/visualize/assets/vendor/lucide-1.17.0.js.LICENSE",
  159. "skills/visualize/assets/vendor/d3-7.9.0.min.js",
  160. "skills/visualize/assets/vendor/d3-7.9.0.min.js.LICENSE",
  161. "skills/visualize/widgets/calendar.md",
  162. "skills/visualize/examples/calendar.html",
  163. "skills/visualize/assets/standalone-host-bridge.js",
  164. "skills/visualize/assets/standalone-shell.js",
  165. ],
  166. requiredRuntimePaths: [],
  167. stagedPath: "packages/visualize-plugin",
  168. },
  169. {
  170. // 远端 shared-host 必须部署 node_repl runtime,否则只剩 skill 而没有 mcp__node_repl__js ——
  171. // 该 runtime 现由 @zcode/node-repl-host 提供(见下一个条目),browser-use 只带自己的
  172. // client script 与 skill/docs。
  173. packageName: "@zcode/browser-use-plugin",
  174. relativePath: "apps/zcode-cli/packages/browser-use-plugin",
  175. requiresRuntime: true,
  176. requiredRuntimePaths: browserUseRequiredRuntimePaths,
  177. runtimeBuildScript: "scripts/build.mjs",
  178. stagedPath: "packages/browser-use-plugin",
  179. },
  180. {
  181. // node_repl 宿主:Browser Use 与 Computer Use 共用的 MCP runtime。远端 shared-host 缺它
  182. // 就没有 mcp__node_repl__js,bua/cua 两边都会连不上。
  183. packageName: "@zcode/node-repl-host",
  184. relativePath: "apps/zcode-cli/packages/node-repl-host",
  185. requiresRuntime: true,
  186. requiredRuntimePaths: ["dist/mcp/server.js"],
  187. runtimeBuildScript: "scripts/build.mjs",
  188. stagedPath: "packages/node-repl-host",
  189. },
  190. {
  191. // CUA 远端只部署 SDK/skill/docs;runtime 仍必须 attachment 到 desktop shared host,
  192. // 不在 remote workspace 安装或启动 native Helper。
  193. packageName: "@zcode/zcode-cua-plugin",
  194. relativePath: "apps/zcode-cli/packages/zcode-cua-plugin",
  195. requiresRuntime: false,
  196. stagedPath: "packages/zcode-cua-plugin",
  197. },
  198. {
  199. packageName: "@zcode/ios-simulator-plugin",
  200. relativePath: "apps/zcode-cli/packages/ios-simulator-plugin",
  201. requiresRuntime: true,
  202. requiredRuntimePaths: ["dist/mcp/server.js"],
  203. runtimeBuildScript: "scripts/build-mcp.mjs",
  204. stagedPath: "packages/ios-simulator-plugin",
  205. },
  206. {
  207. packageName: "@zcode/restore-legacy-sessions-plugin",
  208. relativePath: "apps/zcode-cli/packages/restore-legacy-sessions-plugin",
  209. requiresRuntime: false,
  210. stagedPath: "packages/restore-legacy-sessions-plugin",
  211. },
  212. {
  213. packageName: "@zcode/skill-creator-plugin",
  214. relativePath: "apps/zcode-cli/packages/skill-creator-plugin",
  215. requiresRuntime: false,
  216. stagedPath: "packages/skill-creator-plugin",
  217. },
  218. {
  219. packageName: "@zcode/plugin-creator-plugin",
  220. relativePath: "apps/zcode-cli/packages/plugin-creator-plugin",
  221. requiresRuntime: false,
  222. stagedPath: "packages/plugin-creator-plugin",
  223. },
  224. {
  225. packageName: "@zcode/zcode-guide-plugin",
  226. relativePath: "apps/zcode-cli/packages/zcode-guide-plugin",
  227. requiresRuntime: false,
  228. stagedPath: "packages/zcode-guide-plugin",
  229. },
  230. ];
  231. // 随 CLI 内置的技能包(不是插件):远端 agent 的 bootstrap 沿官方插件同款候选目录在 zcode.cjs 旁
  232. // 找 packages/bundled-skills 并原地读取;与 packages/desktop/scripts/prepare-agent-node-bundle.mjs 同一份清单。
  233. const remoteBundledSkillPack = {
  234. relativePath: "apps/zcode-cli/packages/bundled-skills",
  235. requiredPaths: [
  236. "skills/dynamic-workflows/SKILL.md",
  237. "skills/dynamic-workflows/patterns.md",
  238. "skills/dynamic-workflows/examples.md",
  239. ],
  240. stagedPath: "packages/bundled-skills",
  241. topLevelPaths: ["README.md", "skills"],
  242. };
  243. const remoteOfficialPluginTopLevelPaths = new Set([
  244. ".mcp.json",
  245. ".zcode-plugin",
  246. "README.md",
  247. // 生产远程预构建有独立顶层白名单,遗漏 agents 会在上传前永久裁掉子代理。
  248. "agents",
  249. "commands",
  250. "dist",
  251. "docs",
  252. "hooks",
  253. "output-styles",
  254. "package.json",
  255. "scripts",
  256. "skills",
  257. "templates",
  258. ]);
  259. const excludedOfficialPluginAssetNames = new Set([
  260. ".DS_Store",
  261. ".venv",
  262. "__pycache__",
  263. "node_modules",
  264. ]);
  265. function shouldCopyOfficialPluginAsset(sourcePath) {
  266. const name = basename(sourcePath);
  267. return !excludedOfficialPluginAssetNames.has(name) && !name.endsWith(".pyc");
  268. }
  269. const remoteOfficialPluginRequiredPaths = [
  270. "packages/android-emulator-plugin/.zcode-plugin/plugin.json",
  271. "packages/browser-use-plugin/.zcode-plugin/plugin.json",
  272. "packages/zcode-cua-plugin/.zcode-plugin/plugin.json",
  273. "packages/image-search-plugin/.zcode-plugin/plugin.json",
  274. "packages/image-search-plugin/.mcp.json",
  275. "packages/documents-plugin/.zcode-plugin/plugin.json",
  276. "packages/pdf-plugin/.zcode-plugin/plugin.json",
  277. "packages/presentations-plugin/.zcode-plugin/plugin.json",
  278. "packages/spreadsheets-plugin/.zcode-plugin/plugin.json",
  279. "packages/ios-simulator-plugin/.zcode-plugin/plugin.json",
  280. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  281. "packages/skill-creator-plugin/.zcode-plugin/plugin.json",
  282. "packages/plugin-creator-plugin/.zcode-plugin/plugin.json",
  283. "packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md",
  284. "packages/zcode-guide-plugin/.zcode-plugin/plugin.json",
  285. // 修复原因:文档技能正文与 visual-judge 都是必需 seed 资产,不能只校验 manifest。
  286. "packages/documents-plugin/agents/visual-judge.md",
  287. "packages/documents-plugin/skills/docx/SKILL.md",
  288. "packages/pdf-plugin/agents/visual-judge.md",
  289. "packages/pdf-plugin/skills/pdf/SKILL.md",
  290. "packages/presentations-plugin/agents/visual-judge.md",
  291. "packages/presentations-plugin/skills/pptx/SKILL.md",
  292. "packages/spreadsheets-plugin/agents/visual-judge.md",
  293. "packages/spreadsheets-plugin/skills/xlsx/SKILL.md",
  294. "packages/visualize-plugin/.zcode-plugin/plugin.json",
  295. "packages/visualize-plugin/skills/visualize/SKILL.md",
  296. ];
  297. function readZCodeAgentRuntimeVersion() {
  298. const runtimeSourcePath = join(rootDir, "packages/shared/src/zcode-agent-runtime.ts");
  299. const runtimeSource = readFileSync(runtimeSourcePath, "utf8");
  300. const match = runtimeSource.match(/version:\s*["']([^"']+)["']/);
  301. if (!match?.[1]) {
  302. throw new Error("Unable to parse ZCode Agent runtime version");
  303. }
  304. return match[1];
  305. }
  306. async function download(url, destinationPath) {
  307. const response = await fetch(url, { redirect: "follow" });
  308. if (!response.ok) {
  309. throw new Error(`Download failed: HTTP ${response.status} (${url})`);
  310. }
  311. if (!response.body) {
  312. throw new Error(`Download failed: empty response body (${url})`);
  313. }
  314. // 原实现使用 response.pipe(file) + finish 监听,网络中断时可能既不 resolve 也不 reject,
  315. // 最终触发 Node 24 的 unsettled top-level await。改为 pipeline,确保异常路径可观测且可失败退出。
  316. await pipeline(
  317. Readable.fromWeb(response.body),
  318. createWriteStream(destinationPath, { flags: "w" }),
  319. );
  320. }
  321. async function downloadWithRetry(url, destinationPath, maxAttempts = 3) {
  322. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
  323. try {
  324. await download(url, destinationPath);
  325. return;
  326. } catch (error) {
  327. if (attempt >= maxAttempts) {
  328. throw error;
  329. }
  330. console.warn(` [warn] download attempt ${attempt}/${maxAttempts} failed: ${url}`);
  331. console.warn(` [warn] retry reason: ${String(error)}`);
  332. }
  333. }
  334. }
  335. async function extractArchiveMember(url, destinationDir, archiveMember) {
  336. const tempDir = mkdtempSync(join(tmpdir(), "zcode-node-dist-"));
  337. const archivePath = join(tempDir, "node.tar.xz");
  338. try {
  339. await downloadWithRetry(url, archivePath);
  340. // Bugfix: Windows 下绝对路径带盘符冒号(C:\...),GNU tar(Git Bash)会把 "C:" 当成
  341. // 远程主机名报 "Cannot connect to C"。改用 cwd + 相对归档名,避开 -f 参数里的冒号。
  342. // 反斜杠路径同样会被 MSYS tar 参数转换破坏(\3 被当转义),-C 目标统一转正斜杠,
  343. // 对 bsdtar 与 Linux/macOS CI 无影响。
  344. runCommand(
  345. "tar",
  346. [
  347. "-xJf",
  348. "node.tar.xz",
  349. "--strip-components=2",
  350. "-C",
  351. destinationDir.replaceAll("\\", "/"),
  352. archiveMember,
  353. ],
  354. {
  355. cwd: tempDir,
  356. },
  357. );
  358. } finally {
  359. // Bugfix: Windows 下刚写完的归档可能被杀毒/索引器或尚未退出的 xz 子进程短暂持有句柄,
  360. // rmSync 立即删除会 EPERM,且 finally 里抛出的异常会掩盖真正的下载/解压错误。
  361. // 带重试删除,失败时仅告警,让原始错误正常抛出。
  362. try {
  363. rmSync(tempDir, { force: true, recursive: true, maxRetries: 10, retryDelay: 500 });
  364. } catch (error) {
  365. console.warn(` [warn] 清理临时目录失败(可忽略): ${tempDir}`);
  366. console.warn(` [warn] ${String(error)}`);
  367. }
  368. }
  369. }
  370. function resolveDedicatedPackageRoot(packageName, fromDir) {
  371. const packageEntryPath = require.resolve(packageName, { paths: [fromDir] });
  372. let currentDir = dirname(packageEntryPath);
  373. while (true) {
  374. const packageJsonPath = join(currentDir, "package.json");
  375. if (existsSync(packageJsonPath)) {
  376. const packageJson = require(packageJsonPath);
  377. if (packageJson?.name === packageName) {
  378. return currentDir;
  379. }
  380. }
  381. const parentDir = dirname(currentDir);
  382. if (parentDir === currentDir) {
  383. break;
  384. }
  385. currentDir = parentDir;
  386. }
  387. throw new Error(
  388. `Unable to resolve package root for ${packageName} from entry ${packageEntryPath}`,
  389. );
  390. }
  391. function resolveNodePtyPackageName(platformKey) {
  392. return `@lydell/node-pty-${platformKey}`;
  393. }
  394. function resolveNodePtyPackageVersion(platformKey) {
  395. const packageName = resolveNodePtyPackageName(platformKey);
  396. const packageRoot = resolveDedicatedPackageRoot(packageName, join(rootDir, "packages/server"));
  397. const packageJson = require(join(packageRoot, "package.json"));
  398. if (typeof packageJson?.version !== "string" || !packageJson.version.trim()) {
  399. throw new Error(`Unable to resolve version for ${packageName}`);
  400. }
  401. return packageJson.version.trim();
  402. }
  403. async function prepareNodeBinaries() {
  404. for (const platformKey of remotePlatforms) {
  405. const nodeDir = join(releaseDir, "node", platformKey);
  406. const nodeBinaryPath = join(nodeDir, "node");
  407. // 远端 node 组件独立下载;复用缓存时也要刷新精确版本的 Node 许可原文。
  408. await stageNodeNotices(nodeDir, nodeVersion, rootDir);
  409. if (existsSync(nodeBinaryPath)) {
  410. console.log(` [skip] mock-cdn node/${platformKey} already exists`);
  411. continue;
  412. }
  413. mkdirSync(nodeDir, { recursive: true });
  414. const archiveName = `node-${nodeVersion}-${platformKey}.tar.xz`;
  415. const url = `${nodeDistBase()}/${nodeVersion}/${archiveName}`;
  416. console.log(` [download] ${url}`);
  417. try {
  418. await extractArchiveMember(url, nodeDir, `node-${nodeVersion}-${platformKey}/bin/node`);
  419. chmodSync(nodeBinaryPath, 0o755);
  420. console.log(` [ok] mock-cdn node/${platformKey}`);
  421. } catch (error) {
  422. console.error(` [error] 下载或解压失败: ${url}`);
  423. console.error(
  424. ` [error] 请检查 CI runner 的外网访问、tar/xz 依赖,或用 ZCODE_NODE_DIST_MIRROR 覆盖下载源(当前 ${nodeDistBase()})`,
  425. );
  426. throw error;
  427. }
  428. }
  429. }
  430. function buildServerBundle() {
  431. console.log("==> Building server bundle");
  432. try {
  433. if (isBootstrapWithRemote) {
  434. runBootstrapServerRemoteBuild();
  435. return;
  436. }
  437. // Windows CI(Node 24)里直接 spawnSync("pnpm.cmd") 会在拉起子进程前就抛 EINVAL。
  438. // 这里统一走跨平台启动封装,让 .cmd 通过 shell/cmd.exe 执行,避免远端资源准备阶段提前中断。
  439. runCommand(pnpmCommand, ["run", "build:remote"], {
  440. cwd: join(rootDir, "packages/server"),
  441. });
  442. } catch (error) {
  443. console.error(
  444. " [error] packages/server build:remote 失败,请优先检查 CI 日志中的 TypeScript / esbuild 输出",
  445. );
  446. throw error;
  447. }
  448. }
  449. function runBootstrapServerRemoteBuild() {
  450. // bootstrap:with-remote 会在本地串联 install、remote assets、workspace build。
  451. // 这里不能复用已有 zcode-server.cjs:开发时 package version 常不变,旧 bundle 会把缺少新 RPC 的
  452. // server 部署到 SSH 远端。只保留“直接用当前 Node 启动 tsx”的低内存优化,不改变 CI 的 build:remote。
  453. runCommand(
  454. process.execPath,
  455. [join(rootDir, "node_modules/tsx/dist/cli.mjs"), "build-remote.ts"],
  456. {
  457. cwd: join(rootDir, "packages/server"),
  458. env: process.env,
  459. },
  460. );
  461. }
  462. function copyServerBundle() {
  463. const serverDir = join(releaseDir, "server");
  464. mkdirSync(serverDir, { recursive: true });
  465. copyFileSync(
  466. join(rootDir, "packages/server/dist/remote/zcode-server.cjs"),
  467. join(serverDir, "zcode-server.cjs"),
  468. );
  469. console.log(" [ok] mock-cdn server/zcode-server.cjs");
  470. }
  471. function copyNodePtyPrebuilds() {
  472. console.log("==> Copying node-pty prebuilds from @lydell/node-pty");
  473. for (const platformKey of remotePlatforms) {
  474. const ptyDir = join(releaseDir, "node-pty", platformKey);
  475. const targetBinaryPath = join(ptyDir, "pty.node");
  476. const targetSpawnHelperPath = join(ptyDir, "spawn-helper");
  477. const requiresSpawnHelper = platformKey.startsWith("darwin-");
  478. if (
  479. existsSync(targetBinaryPath) &&
  480. (!requiresSpawnHelper || existsSync(targetSpawnHelperPath))
  481. ) {
  482. console.log(` [skip] mock-cdn node-pty/${platformKey} already exists`);
  483. continue;
  484. }
  485. mkdirSync(ptyDir, { recursive: true });
  486. const packageName = resolveNodePtyPackageName(platformKey);
  487. let packageRoot;
  488. try {
  489. packageRoot = resolveDedicatedPackageRoot(packageName, join(rootDir, "packages/server"));
  490. } catch {
  491. console.log(` [warn] ${packageName} not found, run: pnpm install`);
  492. continue;
  493. }
  494. const sourcePrebuildDir = join(packageRoot, "prebuilds", platformKey);
  495. const sourceBinaryPath = join(sourcePrebuildDir, "pty.node");
  496. if (!existsSync(sourceBinaryPath)) {
  497. console.log(` [warn] binary not found at ${sourceBinaryPath}`);
  498. continue;
  499. }
  500. // Darwin 平台 node-pty 除了 pty.node 还依赖 spawn-helper。
  501. // 之前 mock-cdn 只复制了 pty.node,远端部署后会在 terminal.create 阶段报 posix_spawn ENOENT。
  502. // 这里把 spawn-helper 一并拷贝进 remote 资产目录,避免远端终端启动时缺关键二进制。
  503. copyFileSync(sourceBinaryPath, targetBinaryPath);
  504. if (requiresSpawnHelper) {
  505. const sourceSpawnHelperPath = join(sourcePrebuildDir, "spawn-helper");
  506. if (!existsSync(sourceSpawnHelperPath)) {
  507. console.log(` [warn] spawn-helper not found at ${sourceSpawnHelperPath}`);
  508. continue;
  509. }
  510. copyFileSync(sourceSpawnHelperPath, targetSpawnHelperPath);
  511. chmodSync(targetSpawnHelperPath, 0o755);
  512. }
  513. console.log(` [ok] mock-cdn node-pty/${platformKey} (copied from ${packageName})`);
  514. }
  515. }
  516. function buildRemoteOfficialPluginRuntimes() {
  517. for (const plugin of remoteOfficialPluginPackages) {
  518. if (!plugin.requiresRuntime) continue;
  519. console.log(`==> Building remote official plugin runtime: ${plugin.packageName}`);
  520. if (isBootstrapWithRemote) {
  521. buildRemoteOfficialPluginRuntimeForBootstrap(plugin);
  522. assertRemoteOfficialPluginRuntime(plugin);
  523. continue;
  524. }
  525. runCommand(
  526. pnpmCommand,
  527. ["--dir", join(rootDir, "apps/zcode-cli"), "--filter", plugin.packageName, "build"],
  528. {
  529. cwd: rootDir,
  530. env: process.env,
  531. },
  532. );
  533. assertRemoteOfficialPluginRuntime(plugin);
  534. }
  535. }
  536. function buildRemoteOfficialPluginRuntimeForBootstrap(plugin) {
  537. const pluginRoot = join(rootDir, plugin.relativePath);
  538. const hasCompleteRuntime = plugin.requiredRuntimePaths.every((relativePath) =>
  539. existsSync(join(pluginRoot, ...relativePath.split("/"))),
  540. );
  541. if (plugin.packageName !== BROWSER_USE_PLUGIN_PACKAGE_NAME && hasCompleteRuntime) {
  542. console.log(` [skip] reuse existing remote official plugin runtime: ${plugin.packageName}`);
  543. return;
  544. }
  545. // bootstrap:with-remote 会串行准备远端资源和工作区构建。
  546. // 官方插件 runtime 只在 stage 资源时需要,这里用当前 Node 执行等价构建,避免再嵌套 pnpm/tsc shim。
  547. // browser-use 的 MCP server 与 browser-client 必须来自同一次构建;只凭旧 server.js 判定可复用
  548. // 会让远端资源混入陈旧或缺失的 client,因此 bootstrap 模式下对该插件无条件重建。
  549. runCommand(process.execPath, ["../../node_modules/typescript/bin/tsc"], {
  550. cwd: pluginRoot,
  551. env: process.env,
  552. });
  553. runCommand(process.execPath, [plugin.runtimeBuildScript], {
  554. cwd: pluginRoot,
  555. env: process.env,
  556. });
  557. }
  558. function assertRemoteOfficialPluginRuntime(plugin) {
  559. const pluginRoot = join(rootDir, plugin.relativePath);
  560. for (const relativePath of plugin.requiredRuntimePaths) {
  561. const runtimePath = join(pluginRoot, ...relativePath.split("/"));
  562. if (!existsSync(runtimePath)) {
  563. throw new Error(`[prepare-prebuilds] missing remote official plugin runtime: ${runtimePath}`);
  564. }
  565. }
  566. }
  567. function stageRemoteOfficialPlugins(glmDir) {
  568. for (const plugin of remoteOfficialPluginPackages) {
  569. const sourceRoot = join(rootDir, plugin.relativePath);
  570. const manifestPath = join(sourceRoot, ".zcode-plugin", "plugin.json");
  571. if (!existsSync(manifestPath)) {
  572. throw new Error(
  573. `[prepare-prebuilds] missing remote official plugin manifest: ${manifestPath}`,
  574. );
  575. }
  576. const targetRoot = join(glmDir, ...plugin.stagedPath.split("/"));
  577. mkdirSync(targetRoot, { recursive: true });
  578. for (const entryName of remoteOfficialPluginTopLevelPaths) {
  579. const sourcePath = join(sourceRoot, entryName);
  580. if (!existsSync(sourcePath)) continue;
  581. cpSync(sourcePath, join(targetRoot, entryName), {
  582. recursive: true,
  583. filter: shouldCopyOfficialPluginAsset,
  584. });
  585. }
  586. for (const relativePath of remoteOfficialPluginRequiredPaths) {
  587. if (!relativePath.startsWith(`${plugin.stagedPath}/`)) continue;
  588. const stagedAssetPath = join(glmDir, ...relativePath.split("/"));
  589. if (!existsSync(stagedAssetPath)) {
  590. throw new Error(
  591. `[prepare-prebuilds] missing staged remote official plugin seed asset: ${stagedAssetPath}`,
  592. );
  593. }
  594. }
  595. console.log(` [ok] mock-cdn glm official plugin ${plugin.stagedPath}`);
  596. }
  597. }
  598. function stageRemoteBundledSkillPack(glmDir) {
  599. const sourceRoot = join(rootDir, remoteBundledSkillPack.relativePath);
  600. const targetRoot = join(glmDir, ...remoteBundledSkillPack.stagedPath.split("/"));
  601. mkdirSync(targetRoot, { recursive: true });
  602. for (const entryName of remoteBundledSkillPack.topLevelPaths) {
  603. const sourcePath = join(sourceRoot, entryName);
  604. if (!existsSync(sourcePath)) continue;
  605. cpSync(sourcePath, join(targetRoot, entryName), {
  606. recursive: true,
  607. filter: shouldCopyOfficialPluginAsset,
  608. });
  609. }
  610. for (const relativePath of remoteBundledSkillPack.requiredPaths) {
  611. const stagedAssetPath = join(targetRoot, ...relativePath.split("/"));
  612. if (!existsSync(stagedAssetPath)) {
  613. throw new Error(
  614. `[prepare-prebuilds] missing staged remote bundled skill asset: ${stagedAssetPath}`,
  615. );
  616. }
  617. }
  618. console.log(` [ok] mock-cdn glm bundled skill pack ${remoteBundledSkillPack.stagedPath}`);
  619. }
  620. // 远端 agent 现在跑编译出来的 zcode.cjs(而不是各平台独立的原生二进制):
  621. // 远端部署时已经有一份独立 node(跑 zcode-server.cjs),agent 复用它执行 zcode.cjs 即可,
  622. // 不必再为每个平台准备一份内嵌 node 的 SEA 二进制。zcode.cjs 跨平台同一份,逐平台只是放进各自的
  623. // glm/<platform> 组件目录,保持现有 manifest 组件结构不变。
  624. function stageRemoteAgentBundles() {
  625. console.log("==> Building zcode-cli bundle for remote agents");
  626. // 复用桌面同款构建脚本(turbo build:desktop-agent --filter=@zcode/cli),命中缓存时几乎瞬时。
  627. runCommand(process.execPath, [join(rootDir, "scripts/build-desktop-agent-cli.mjs")], {
  628. cwd: rootDir,
  629. env: process.env,
  630. });
  631. // browser-use runtime 的 tsc 依赖 @zcode/core/dist。远端资产也必须先构建
  632. // agent CLI 依赖,避免 CI 干净检出时被开发机缓存掩盖的 TS2307。
  633. buildRemoteOfficialPluginRuntimes();
  634. const cliBundlePath = join(rootDir, "apps/zcode-cli/packages/cli/dist/zcode.cjs");
  635. if (!existsSync(cliBundlePath)) {
  636. throw new Error(`[prepare-prebuilds] expected cli bundle missing: ${cliBundlePath}`);
  637. }
  638. for (const platformKey of remotePlatforms) {
  639. const glmDir = join(releaseDir, "glm", platformKey);
  640. // 干净重建:glm 组件现在只含 zcode.cjs,清掉历史遗留的原生二进制 / 旧 meta,
  641. // 避免被打进组件 tar 把远端资源撑大。
  642. rmSync(glmDir, { recursive: true, force: true });
  643. mkdirSync(glmDir, { recursive: true });
  644. copyFileSync(cliBundlePath, join(glmDir, "zcode.cjs"));
  645. stageRemoteOfficialPlugins(glmDir);
  646. stageRemoteBundledSkillPack(glmDir);
  647. console.log(` [ok] mock-cdn glm/${platformKey}/zcode.cjs`);
  648. }
  649. }
  650. function downloadRemoteNativeSearchToolsFromIntranet(platformKey, targetOs, targetArch) {
  651. try {
  652. if (targetOs === "linux") {
  653. // 修复原因:Linux remote 过去仍走 legacy rg13 单工具下载链,导致 WSL 的 Bash
  654. // 找不到随包 bfs/ugrep。这里复用 desktop/SEA 已验证的同一 release plan,
  655. // 一次准备 glibc 2.28 的 bfs/ugrep -2 与 Microsoft musl rg14。
  656. runCommand(
  657. process.execPath,
  658. [
  659. join(rootDir, "scripts/download-native-search-tools.mjs"),
  660. "--platform",
  661. targetOs,
  662. "--arch",
  663. targetArch,
  664. "--output-dir",
  665. join(releaseDir, "tools", platformKey),
  666. ],
  667. {
  668. cwd: rootDir,
  669. env: process.env,
  670. },
  671. );
  672. } else {
  673. runCommand(
  674. process.execPath,
  675. [
  676. join(rootDir, "scripts/download-ripgrep.mjs"),
  677. LEGACY_REMOTE_RIPGREP_VERSION,
  678. targetOs,
  679. targetArch,
  680. ],
  681. {
  682. cwd: rootDir,
  683. env: {
  684. ...process.env,
  685. ZCODE_FORCE_REMOTE_MOCK_CDN: "1",
  686. },
  687. },
  688. );
  689. }
  690. } catch (error) {
  691. console.error(
  692. ` [error] native search 下载失败 (${platformKey}),请检查依赖镜像和 runner 网络访问`,
  693. );
  694. throw error;
  695. }
  696. }
  697. // 远端 native search 与 desktop/SEA 使用同一来源判定:内网依赖源已配置时保持原有下载命令
  698. // (Linux 走 release plan,macOS 保留 legacy rg13 单工具下载),未配置时按远端 plan 解包仓库归档。
  699. // 两条路径都在组件哈希计算前把许可声明写进各工具目录,保证组件归档自带材料。
  700. async function prepareRemoteNativeSearchTools({ env = process.env } = {}) {
  701. const source = resolveNativeSearchArtifactSource(env);
  702. console.log(
  703. source === "intranet"
  704. ? "==> Downloading native search binaries for remote platforms"
  705. : "==> Preparing native search binaries for remote platforms from repository archives",
  706. );
  707. for (const platformKey of remotePlatforms) {
  708. const [targetOs, targetArch] = platformKey.split("-");
  709. if (!targetOs || !targetArch) {
  710. throw new Error(`Invalid remote platform key: ${platformKey}`);
  711. }
  712. const prebuiltPlan = resolveRemoteNativeSearchPrebuiltPlan({
  713. platform: targetOs,
  714. arch: targetArch,
  715. outputDir: join(releaseDir, "tools", platformKey),
  716. });
  717. if (source === "intranet") {
  718. downloadRemoteNativeSearchToolsFromIntranet(platformKey, targetOs, targetArch);
  719. await stageNativeSearchNotices(prebuiltPlan, rootDir, { origin: "intranet-mirror" });
  720. } else {
  721. await prepareNativeSearchTools({ prebuiltPlan, source: "repository" });
  722. }
  723. }
  724. }
  725. function joinPosix(...segments) {
  726. return segments.join("/").replace(/\/+/g, "/");
  727. }
  728. function normalizeSemanticPrefix(rawPrefix, fallback = "v1") {
  729. const prefix = String(rawPrefix ?? "").trim();
  730. if (!prefix) {
  731. return fallback;
  732. }
  733. const normalized = prefix.replace(/\+/g, "-");
  734. if (!normalized) {
  735. return fallback;
  736. }
  737. return normalized.startsWith("v") ? normalized : `v${normalized}`;
  738. }
  739. function computeFileSha256(filePath) {
  740. return createHash("sha256").update(readFileSync(filePath)).digest("hex");
  741. }
  742. function isSha256(value) {
  743. return /^[a-f0-9]{64}$/u.test(
  744. String(value ?? "")
  745. .trim()
  746. .toLowerCase(),
  747. );
  748. }
  749. function buildComponentVersion(semanticPrefix) {
  750. return normalizeSemanticPrefix(semanticPrefix);
  751. }
  752. export function buildContentAddressedComponentVersion(semanticPrefix, sha256) {
  753. const normalizedSha = String(sha256 ?? "")
  754. .trim()
  755. .toLowerCase();
  756. if (!/^[a-f0-9]{64}$/.test(normalizedSha)) {
  757. throw new Error(`Invalid component sha256: ${sha256}`);
  758. }
  759. return `${buildComponentVersion(semanticPrefix)}+${normalizedSha.slice(0, 12)}`;
  760. }
  761. export function buildComponentArtifactRelativePath(platformKey, componentId, componentVersion) {
  762. return joinPosix("components", platformKey, componentId, `${componentVersion}.tar.gz`);
  763. }
  764. function resolveComponentSemanticVersion(componentVersion) {
  765. const version = String(componentVersion ?? "").trim();
  766. const plusIndex = version.lastIndexOf("+");
  767. if (plusIndex < 0 || plusIndex === version.length - 1) {
  768. return version;
  769. }
  770. const suffix = version.slice(plusIndex + 1).toLowerCase();
  771. return /^[a-f0-9]{12,64}$/.test(suffix) ? version.slice(0, plusIndex) : version;
  772. }
  773. // glm 承载 zcode-cli app-server 协议 schema。即使 runtime 版本未变化,
  774. // zcode.cjs 也可能随 app 代码变更;跨 release 复用旧 glm 会让远端 agent 拒绝新协议字段。
  775. const nonReusableReleaseAssetIds = new Set(["server-bundle", "glm"]);
  776. function readJsonFile(filePath) {
  777. try {
  778. return JSON.parse(readFileSync(filePath, "utf8"));
  779. } catch {
  780. return null;
  781. }
  782. }
  783. function compareVersionSegments(left, right) {
  784. const leftParts = String(left).split(/[.-]/);
  785. const rightParts = String(right).split(/[.-]/);
  786. const length = Math.max(leftParts.length, rightParts.length);
  787. for (let index = 0; index < length; index += 1) {
  788. const leftPart = leftParts[index] ?? "0";
  789. const rightPart = rightParts[index] ?? "0";
  790. const leftNumber = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
  791. const rightNumber = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
  792. if (leftNumber !== null && rightNumber !== null) {
  793. if (leftNumber !== rightNumber) {
  794. return leftNumber - rightNumber;
  795. }
  796. continue;
  797. }
  798. const compared = leftPart.localeCompare(rightPart, undefined, {
  799. numeric: true,
  800. });
  801. if (compared !== 0) {
  802. return compared;
  803. }
  804. }
  805. return 0;
  806. }
  807. function findReusableReleaseDirs({ mockCdnDir, currentVersion }) {
  808. const releasesDir = join(mockCdnDir, "releases");
  809. if (!existsSync(releasesDir)) {
  810. return [];
  811. }
  812. return readdirSync(releasesDir, { withFileTypes: true })
  813. .filter((entry) => entry.isDirectory() && entry.name !== currentVersion)
  814. .map((entry) => entry.name)
  815. .filter((candidate) => compareVersionSegments(candidate, currentVersion) < 0)
  816. .sort((left, right) => compareVersionSegments(right, left))
  817. .map((candidate) => join(releasesDir, candidate));
  818. }
  819. function normalizeManifestComponents(manifest) {
  820. if (!manifest || !Array.isArray(manifest.components)) {
  821. return new Map();
  822. }
  823. return new Map(
  824. manifest.components
  825. .filter((component) => typeof component?.id === "string")
  826. .map((component) => [component.id, component]),
  827. );
  828. }
  829. export function restoreReusableReleaseAssets({
  830. mockCdnDir,
  831. currentVersion,
  832. releaseDir,
  833. componentDefinitionsByPlatform,
  834. }) {
  835. const previousReleaseDirs = findReusableReleaseDirs({
  836. mockCdnDir,
  837. currentVersion,
  838. });
  839. if (previousReleaseDirs.length === 0) {
  840. return;
  841. }
  842. for (const [platformKey, componentDefinitions] of componentDefinitionsByPlatform.entries()) {
  843. for (const componentDefinition of componentDefinitions) {
  844. if (nonReusableReleaseAssetIds.has(componentDefinition.id)) {
  845. continue;
  846. }
  847. for (const previousReleaseDir of previousReleaseDirs) {
  848. const previousManifest = readJsonFile(
  849. join(previousReleaseDir, `manifest-${platformKey}.json`),
  850. );
  851. const previousComponents = normalizeManifestComponents(previousManifest);
  852. const previousComponent = previousComponents.get(componentDefinition.id);
  853. if (
  854. resolveComponentSemanticVersion(previousComponent?.version) !==
  855. resolveComponentSemanticVersion(componentDefinition.version)
  856. ) {
  857. continue;
  858. }
  859. const sourcePath = join(previousReleaseDir, ...componentDefinition.mount.split("/"));
  860. const targetPath = join(releaseDir, ...componentDefinition.mount.split("/"));
  861. if (!existsSync(sourcePath)) {
  862. continue;
  863. }
  864. const requiredPaths = componentDefinition.requiredPaths ?? [];
  865. const hasTargetRequiredPaths =
  866. existsSync(targetPath) &&
  867. requiredPaths.every((relativePath) =>
  868. existsSync(join(targetPath, ...relativePath.split("/"))),
  869. );
  870. if (hasTargetRequiredPaths) {
  871. continue;
  872. }
  873. const hasRequiredPaths = requiredPaths.every((relativePath) =>
  874. existsSync(join(sourcePath, ...relativePath.split("/"))),
  875. );
  876. if (!hasRequiredPaths) {
  877. continue;
  878. }
  879. // app version 变更会生成新的 releases/<version> 目录,mock-cdn cache 命中不能依赖该路径。
  880. // 这里仅在组件自身版本一致且关键文件完整时复制历史 release,避免稳定 runtime 重复下载。
  881. mkdirSync(dirname(targetPath), { recursive: true });
  882. if (existsSync(targetPath)) {
  883. // 上一次 bootstrap 中断可能留下只有 .part 文件的残缺目标目录。
  884. // 目标目录存在但关键文件不完整时不能跳过复用,先清掉再用历史 release 的完整资源修复。
  885. rmSync(targetPath, { force: true, recursive: true });
  886. }
  887. cpSync(sourcePath, targetPath, { recursive: true });
  888. console.log(
  889. ` [reuse] ${componentDefinition.id} ${platformKey} from ${basename(previousReleaseDir)}`,
  890. );
  891. break;
  892. }
  893. }
  894. }
  895. }
  896. function buildReusableComponentDefinitionsByPlatform() {
  897. return new Map(
  898. remotePlatforms.map((platformKey) => [
  899. platformKey,
  900. buildRemoteComponentDefinitions(platformKey).map((component) => ({
  901. id: component.id,
  902. version: buildComponentVersion(component.semanticPrefix),
  903. mount: component.mount,
  904. requiredPaths: buildReusableComponentRequiredPaths(component.id, platformKey),
  905. })),
  906. ]),
  907. );
  908. }
  909. function buildReusableComponentRequiredPaths(componentId, platformKey) {
  910. switch (componentId) {
  911. case "node-runtime":
  912. return ["node"];
  913. case "node-pty":
  914. return platformKey.startsWith("darwin-") ? ["pty.node", "spawn-helper"] : ["pty.node"];
  915. case "glm":
  916. // GLM 现在是编译产物 zcode.cjs(跨平台同一份),远端用已部署的 node 执行它。
  917. // 复用时还要确认官方插件 seed 资源完整,否则旧 release 会继续产出 0 builtin plugin 的远端资源包。
  918. return ["zcode.cjs", ...remoteOfficialPluginRequiredPaths];
  919. case "bfs":
  920. return ["bfs"];
  921. case "ripgrep":
  922. return [platformKey.startsWith("win32-") ? "rg.exe" : "rg"];
  923. case "ugrep":
  924. return ["ugrep"];
  925. default:
  926. return [];
  927. }
  928. }
  929. export function buildRemoteComponentDefinitions(platformKey) {
  930. const baseComponents = [
  931. {
  932. id: "server-bundle",
  933. semanticPrefix: version,
  934. mount: "server",
  935. sourcePath: join(releaseDir, "server"),
  936. },
  937. {
  938. id: "node-runtime",
  939. semanticPrefix: nodeVersion,
  940. mount: joinPosix("node", platformKey),
  941. sourcePath: join(releaseDir, "node", platformKey),
  942. },
  943. {
  944. id: "node-pty",
  945. // node-pty 组件之前固定成 v1,平台包升级后客户端仍会命中旧 cache。
  946. // 这里使用实际复制来源包的版本,让 @lydell/node-pty-<platform> 升级时组件 cache 自动失效。
  947. semanticPrefix: resolveNodePtyPackageVersion(platformKey),
  948. mount: joinPosix("node-pty", platformKey),
  949. sourcePath: join(releaseDir, "node-pty", platformKey),
  950. },
  951. {
  952. id: "glm",
  953. // GLM native binary 之前固定成 v1,二进制版本升级后不会触发组件 cache 失效。
  954. // 这里复用 ZCODE_AGENT_RUNTIME.glm.version,保持 manifest 版本与运行时描述一致。
  955. semanticPrefix: ZCODE_AGENT_RUNTIME.glm.version,
  956. mount: joinPosix("glm", platformKey),
  957. sourcePath: join(releaseDir, "glm", platformKey),
  958. },
  959. ];
  960. if (platformKey.startsWith("linux-")) {
  961. return [
  962. ...baseComponents,
  963. {
  964. id: "bfs",
  965. semanticPrefix: resolveNativeSearchPrebuiltRelease("bfs", "linux"),
  966. mount: joinPosix("tools", platformKey, "bfs"),
  967. sourcePath: join(releaseDir, "tools", platformKey, "bfs"),
  968. },
  969. {
  970. id: "ripgrep",
  971. semanticPrefix: NATIVE_SEARCH_PREBUILT_RELEASES.ripgrep,
  972. mount: joinPosix("tools", platformKey, "ripgrep"),
  973. sourcePath: join(releaseDir, "tools", platformKey, "ripgrep"),
  974. },
  975. {
  976. id: "ugrep",
  977. semanticPrefix: resolveNativeSearchPrebuiltRelease("ugrep", "linux"),
  978. mount: joinPosix("tools", platformKey, "ugrep"),
  979. sourcePath: join(releaseDir, "tools", platformKey, "ugrep"),
  980. },
  981. ];
  982. }
  983. return [
  984. ...baseComponents,
  985. {
  986. id: "ripgrep",
  987. semanticPrefix: LEGACY_REMOTE_RIPGREP_VERSION,
  988. mount: joinPosix("tools", platformKey, "ripgrep"),
  989. sourcePath: join(releaseDir, "tools", platformKey, "ripgrep"),
  990. },
  991. ];
  992. }
  993. function tryReuseRemoteComponentArtifact({
  994. mockCdnDir,
  995. component,
  996. previousComponent,
  997. sourceSha256,
  998. }) {
  999. if (!previousComponent) {
  1000. return null;
  1001. }
  1002. if (previousComponent.id !== component.id || previousComponent.mount !== component.mount) {
  1003. return null;
  1004. }
  1005. if (
  1006. resolveComponentSemanticVersion(previousComponent.version) !==
  1007. buildComponentVersion(component.semanticPrefix)
  1008. ) {
  1009. return null;
  1010. }
  1011. if (previousComponent.sourceSha256 !== sourceSha256) {
  1012. return null;
  1013. }
  1014. if (
  1015. typeof previousComponent.artifactPath !== "string" ||
  1016. typeof previousComponent.sha256 !== "string" ||
  1017. !isSha256(previousComponent.sha256)
  1018. ) {
  1019. return null;
  1020. }
  1021. const artifactPath = join(mockCdnDir, ...previousComponent.artifactPath.split("/"));
  1022. if (!existsSync(artifactPath)) {
  1023. return null;
  1024. }
  1025. if (computeFileSha256(artifactPath) !== previousComponent.sha256) {
  1026. return null;
  1027. }
  1028. return previousComponent;
  1029. }
  1030. export function prepareRemoteComponentArtifact({
  1031. mockCdnDir,
  1032. platformKey,
  1033. component,
  1034. previousComponents = new Map(),
  1035. }) {
  1036. if (!existsSync(component.sourcePath)) {
  1037. throw new Error(
  1038. `Missing component source for ${component.id} (${platformKey}): ${component.sourcePath}`,
  1039. );
  1040. }
  1041. const sourceSha256 = computeComponentSourceSha256(component.sourcePath);
  1042. const previousComponent = previousComponents.get(component.id);
  1043. const reusedComponent = tryReuseRemoteComponentArtifact({
  1044. mockCdnDir,
  1045. component,
  1046. previousComponent,
  1047. sourceSha256,
  1048. });
  1049. if (reusedComponent) {
  1050. // remote mock-cdn 组件源内容没变时不能每次重打 tar.gz。
  1051. // 这里用源目录内容指纹命中已有 manifest 和 artifact,避免 bootstrap:with-remote 重复压缩大组件。
  1052. console.log(` [skip] component ${component.id} ${platformKey} unchanged`);
  1053. return reusedComponent;
  1054. }
  1055. const semanticComponentVersion = buildComponentVersion(component.semanticPrefix);
  1056. const stagingArtifactRelativePath = joinPosix(
  1057. "components",
  1058. platformKey,
  1059. component.id,
  1060. `${semanticComponentVersion}.tmp-${process.pid}-${Date.now()}.tar.gz`,
  1061. );
  1062. const stagingArtifactPath = join(mockCdnDir, ...stagingArtifactRelativePath.split("/"));
  1063. mkdirSync(dirname(stagingArtifactPath), { recursive: true });
  1064. // 同版本本地重跑时继续复用旧 tar 会让 manifest sha256 指向陈旧内容。
  1065. // 这里先打临时包再把内容 hash 写进最终文件名,避免 CDN 缓存继续命中同名旧对象。
  1066. packComponentSourceAsArchive(component.sourcePath, stagingArtifactPath);
  1067. const artifactSha256 = computeFileSha256(stagingArtifactPath);
  1068. const componentVersion = buildContentAddressedComponentVersion(
  1069. component.semanticPrefix,
  1070. artifactSha256,
  1071. );
  1072. const artifactRelativePath = buildComponentArtifactRelativePath(
  1073. platformKey,
  1074. component.id,
  1075. componentVersion,
  1076. );
  1077. const artifactPath = join(mockCdnDir, ...artifactRelativePath.split("/"));
  1078. if (artifactPath !== stagingArtifactPath) {
  1079. rmSync(artifactPath, { force: true });
  1080. mkdirSync(dirname(artifactPath), { recursive: true });
  1081. renameSync(stagingArtifactPath, artifactPath);
  1082. }
  1083. console.log(` [component] ${component.id} ${platformKey} -> ${artifactRelativePath}`);
  1084. return {
  1085. id: component.id,
  1086. version: componentVersion,
  1087. sha256: artifactSha256,
  1088. sourceSha256,
  1089. artifactPath: artifactRelativePath,
  1090. mount: component.mount,
  1091. };
  1092. }
  1093. function prepareRemoteComponentArtifacts() {
  1094. console.log("==> Packaging component artifacts and manifests");
  1095. const componentRootDir = join(mockCdnDir, "components");
  1096. mkdirSync(componentRootDir, { recursive: true });
  1097. for (const platformKey of remotePlatforms) {
  1098. const componentManifestEntries = [];
  1099. const componentDefinitions = buildRemoteComponentDefinitions(platformKey);
  1100. const previousComponents = normalizeManifestComponents(
  1101. readJsonFile(join(releaseDir, `manifest-${platformKey}.json`)),
  1102. );
  1103. for (const component of componentDefinitions) {
  1104. componentManifestEntries.push(
  1105. prepareRemoteComponentArtifact({
  1106. mockCdnDir,
  1107. platformKey,
  1108. component,
  1109. previousComponents,
  1110. }),
  1111. );
  1112. }
  1113. const manifestPath = join(releaseDir, `manifest-${platformKey}.json`);
  1114. writeFileSync(
  1115. manifestPath,
  1116. `${JSON.stringify(
  1117. {
  1118. schemaVersion: componentSchemaVersion,
  1119. appVersion: version,
  1120. platformArch: platformKey,
  1121. components: componentManifestEntries,
  1122. },
  1123. null,
  1124. 2,
  1125. )}\n`,
  1126. "utf8",
  1127. );
  1128. console.log(` [ok] mock-cdn releases/${version}/manifest-${platformKey}.json`);
  1129. }
  1130. }
  1131. async function main() {
  1132. console.log(`==> Preparing mock CDN release in ${releaseDir}`);
  1133. mkdirSync(releaseDir, { recursive: true });
  1134. restoreReusableReleaseAssets({
  1135. mockCdnDir,
  1136. currentVersion: version,
  1137. releaseDir,
  1138. componentDefinitionsByPlatform: buildReusableComponentDefinitionsByPlatform(),
  1139. });
  1140. await prepareNodeBinaries();
  1141. buildServerBundle();
  1142. copyServerBundle();
  1143. copyNodePtyPrebuilds();
  1144. stageRemoteAgentBundles();
  1145. await prepareRemoteNativeSearchTools();
  1146. // 修复:server、pty、agent 均可独立下载,需在组件哈希计算前补齐各自的声明。
  1147. await stageThirdPartyNotices(join(releaseDir, "server"), rootDir);
  1148. for (const platformKey of remotePlatforms) {
  1149. await stageThirdPartyNotices(join(releaseDir, "node-pty", platformKey), rootDir);
  1150. await stageThirdPartyNotices(join(releaseDir, "glm", platformKey), rootDir);
  1151. }
  1152. prepareRemoteComponentArtifacts();
  1153. console.log(`==> Done! Mock CDN release ready at ${releaseDir}`);
  1154. }
  1155. const entryHref = process.argv[1] ? pathToFileURL(process.argv[1]).href : null;
  1156. if (entryHref === import.meta.url) {
  1157. await main();
  1158. }