prepare-prebuilds.mjs 36 KB

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