prepare-prebuilds.mjs 38 KB

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