prepare-agent-node-bundle.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env node
  2. // 桌面打包态的 agent 运行时资产:把 agent 的 JS bundle(zcode.cjs)放进 bundled-agents/<platform>/glm,
  3. // 由 app 内置的 Electron Node runtime(ELECTRON_RUN_AS_NODE)执行,替代以前随包内置的独立 Node 二进制。
  4. //
  5. // 为什么这么做:
  6. // - agent 没有任何原生 NAPI 插件(ripgrep 是 WASM,其余纯 JS),可直接跑在 Electron 的 Node 上;
  7. // - Electron 41 内置 Node 24.x,与 zcode-cli 的目标运行时一致;
  8. // - 单平台体积从 ~180MB 降到 ~16MB,且同一份 JS 跨平台通用;
  9. // - app-server 命令路径不会加载 @zcode/tui,所以这里天然不打包 TUI。
  10. //
  11. // 远端(SSH/WSL/Docker)没有 Electron,仍走 prepare:remote-assets 的原生二进制,互不影响。
  12. import { cpSync, existsSync, mkdirSync } from "node:fs";
  13. import { basename, dirname, resolve } from "node:path";
  14. import process from "node:process";
  15. import { fileURLToPath } from "node:url";
  16. import { runCommand } from "../../../scripts/spawn-command.mjs";
  17. import { stageAgentBundle } from "./stage-agent-bundle.mjs";
  18. const scriptDir = dirname(fileURLToPath(import.meta.url));
  19. const desktopRoot = resolve(scriptDir, "..");
  20. const repoRoot = resolve(desktopRoot, "..", "..");
  21. const cliBundlePath = resolve(repoRoot, "apps/zcode-cli/packages/cli/dist/zcode.cjs");
  22. const adaptersRoot = resolve(repoRoot, "apps/zcode-cli/packages/adapters");
  23. const pnpmRunEnv = {
  24. ...process.env,
  25. // pnpm 11 会在 apps/zcode-cli 子 workspace 执行 run 前触发 install;
  26. // 子 workspace 不能解析根 workspace 的 @zcode/shared,Docker/web app 打包会因此卡在插件 runtime 构建。
  27. PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN: "false",
  28. };
  29. const BROWSER_USE_PLUGIN_PACKAGE_NAME = "@zcode/browser-use-plugin";
  30. // 平台目录命名:darwin/win32/linux + x64/arm64,
  31. // 支持 ZCODE_TARGET_OS / ZCODE_TARGET_ARCH 覆盖(交叉打包时由 CI 注入)。
  32. function normalizePlatform(raw) {
  33. switch (raw) {
  34. case "mac":
  35. case "macos":
  36. case "darwin":
  37. case "osx":
  38. return "darwin";
  39. case "win":
  40. case "windows":
  41. case "win32":
  42. return "win32";
  43. case "linux":
  44. return "linux";
  45. default:
  46. return raw;
  47. }
  48. }
  49. function normalizeArch(raw) {
  50. switch (raw) {
  51. case "x86_64":
  52. case "x64":
  53. case "amd64":
  54. return "x64";
  55. case "aarch64":
  56. case "arm64":
  57. return "arm64";
  58. default:
  59. return raw;
  60. }
  61. }
  62. const platform = normalizePlatform(process.env.ZCODE_TARGET_OS || "") || process.platform;
  63. const arch = normalizeArch(process.env.ZCODE_TARGET_ARCH || "") || process.arch;
  64. const platformKey = `${platform}-${arch}`;
  65. const glmDir = resolve(desktopRoot, "bundled-agents", platformKey, "glm");
  66. // zcode.cjs / .node-bundle-meta.json 的落点由 stage-agent-bundle.mjs 自己解析(同源)。
  67. // node_repl 宿主抽成独立包
  68. // @zcode/node-repl-host 之后,browser-use 不再产出 dist/mcp/server.js,CUA 资产
  69. // (docs/computer-use.md、scripts/computer-use-client.mjs)也已归 @zcode/zcode-cua-plugin。
  70. // 这份清单当时漏改,打包准备阶段照旧去 browser-use 要那三个文件,直接 missing runtime 挂掉。
  71. // dev 链路走的是 scripts/build-desktop-agent-cli.mjs 的 requiredDevPluginRuntimeBuilds(那份改对了),
  72. // 两份平行清单各自维护,所以 dev 测不出来 —— 权威归属见 bootstrap/official-plugin-definitions.ts。
  73. const browserUseRequiredRuntimePaths = [
  74. "scripts/browser-client.mjs",
  75. "docs/api.json",
  76. "docs/documents.json",
  77. "docs/overview.md",
  78. // documents.json 已暴露 recording lookup,桌面安装包不能复用缺少正文的 runtime。
  79. "docs/recording.md",
  80. "docs/workflow.md",
  81. "skills/control-browser/SKILL.md",
  82. "skills/web-gui-tester/SKILL.md",
  83. ];
  84. const officialPluginPackages = [
  85. {
  86. // browser-use 只携带自己的 client script 与 skill/docs;node_repl MCP runtime 归
  87. // @zcode/node-repl-host(见上方常量注释)。
  88. packageName: "@zcode/browser-use-plugin",
  89. relativePath: "apps/zcode-cli/packages/browser-use-plugin",
  90. requiresRuntime: true,
  91. requiredRuntimePaths: browserUseRequiredRuntimePaths,
  92. runtimeBuildScript: "scripts/build.mjs",
  93. stagedPath: "packages/browser-use-plugin",
  94. },
  95. {
  96. // node_repl 宿主:Browser Use 与 Computer Use 共用的 MCP runtime,本轮抽成独立包。
  97. // 它没有 listing(不进插件市场展示面),但生产包首启 seed 必须拿到它的 dist runtime,
  98. // 否则 bua/cua 任一开启时都会连不上 node_repl。
  99. packageName: "@zcode/node-repl-host",
  100. relativePath: "apps/zcode-cli/packages/node-repl-host",
  101. requiresRuntime: true,
  102. requiredRuntimePaths: ["dist/mcp/server.js"],
  103. runtimeBuildScript: "scripts/build.mjs",
  104. stagedPath: "packages/node-repl-host",
  105. },
  106. ];
  107. const includedOfficialPluginTopLevelPaths = new Set([
  108. ".mcp.json",
  109. ".zcode-plugin",
  110. "README.md",
  111. // Electron 生产资源复制有独立白名单,遗漏 agents 会让首启 filesystem seed 永久缺少子代理。
  112. "agents",
  113. "commands",
  114. "dist",
  115. "docs",
  116. "hooks",
  117. "output-styles",
  118. "package.json",
  119. "scripts",
  120. "skills",
  121. "templates",
  122. ]);
  123. const excludedOfficialPluginAssetNames = new Set([
  124. ".DS_Store",
  125. ".venv",
  126. "__pycache__",
  127. "node_modules",
  128. ]);
  129. function shouldCopyOfficialPluginAsset(sourcePath) {
  130. const name = basename(sourcePath);
  131. return !excludedOfficialPluginAssetNames.has(name) && !name.endsWith(".pyc");
  132. }
  133. const isBootstrapWithRemote = process.env.ZCODE_BOOTSTRAP_WITH_REMOTE === "1";
  134. function buildCliBundle() {
  135. console.log("[prepare:agent-bundle] building zcode-cli app-server bundle ...");
  136. // 复用仓库根脚本(turbo build:desktop-agent --filter=@zcode/cli),命中缓存时几乎瞬时。
  137. runCommand(process.execPath, [resolve(repoRoot, "scripts/build-desktop-agent-cli.mjs")], {
  138. cwd: repoRoot,
  139. env: pnpmRunEnv,
  140. });
  141. if (!existsSync(cliBundlePath)) {
  142. throw new Error(
  143. `[prepare:agent-bundle] expected cli bundle missing after build: ${cliBundlePath}`,
  144. );
  145. }
  146. }
  147. function buildOfficialPluginRuntimes() {
  148. for (const plugin of officialPluginPackages) {
  149. if (!plugin.requiresRuntime) continue;
  150. console.log(`[prepare:agent-bundle] building ${plugin.packageName} runtime ...`);
  151. if (isBootstrapWithRemote) {
  152. buildOfficialPluginRuntimeForBootstrap(plugin);
  153. assertOfficialPluginRuntime(plugin);
  154. continue;
  155. }
  156. runCommand(
  157. "pnpm",
  158. ["--dir", resolve(repoRoot, "apps/zcode-cli"), "--filter", plugin.packageName, "build"],
  159. {
  160. cwd: repoRoot,
  161. env: pnpmRunEnv,
  162. },
  163. );
  164. assertOfficialPluginRuntime(plugin);
  165. }
  166. }
  167. function buildOfficialPluginRuntimeForBootstrap(plugin) {
  168. const pluginRoot = resolve(repoRoot, plugin.relativePath);
  169. const hasCompleteRuntime = plugin.requiredRuntimePaths.every((relativePath) =>
  170. existsSync(resolve(pluginRoot, ...relativePath.split("/"))),
  171. );
  172. if (plugin.packageName !== BROWSER_USE_PLUGIN_PACKAGE_NAME && hasCompleteRuntime) {
  173. console.log(
  174. `[prepare:agent-bundle] reuse existing official plugin runtime: ${plugin.packageName}`,
  175. );
  176. return;
  177. }
  178. // bootstrap:with-remote 会连续构建 remote assets 和桌面 agent bundle。
  179. // 通过 pnpm/filter 进入插件 build 时,tsc shim 在本地低内存环境中容易被 SIGKILL;
  180. // 这里仅在 bootstrap 开关下用当前 Node 直接执行等价 tsc + build-mcp,不改变插件自身 build 脚本。
  181. // browser-use 的 server 与 browser-client 是同一发布对;即使旧 server.js 存在也必须重建,
  182. // 否则会把旧 server 与当前 client(或缺失 client)一起 stage 到桌面安装包。
  183. runCommand(process.execPath, ["../../node_modules/typescript/bin/tsc"], {
  184. cwd: pluginRoot,
  185. env: process.env,
  186. });
  187. runCommand(process.execPath, [plugin.runtimeBuildScript], {
  188. cwd: pluginRoot,
  189. env: process.env,
  190. });
  191. }
  192. function assertOfficialPluginRuntime(plugin) {
  193. const pluginRoot = resolve(repoRoot, plugin.relativePath);
  194. for (const relativePath of plugin.requiredRuntimePaths) {
  195. const runtimePath = resolve(pluginRoot, ...relativePath.split("/"));
  196. if (!existsSync(runtimePath)) {
  197. throw new Error(`[prepare:agent-bundle] missing official plugin runtime: ${runtimePath}`);
  198. }
  199. }
  200. }
  201. function stageBundle() {
  202. // 实现已抽到 stage-agent-bundle.mjs:dev 链(scripts/build-desktop-agent-cli.mjs)
  203. // 必须用同一份,否则 dev 会继续跑上一次打包留下的陈旧 agent。
  204. stageAgentBundle({ repoRoot, platformKey });
  205. }
  206. function stageOfficialPlugins() {
  207. for (const plugin of officialPluginPackages) {
  208. const sourceRoot = resolve(repoRoot, plugin.relativePath);
  209. const manifestPath = resolve(sourceRoot, ".zcode-plugin", "plugin.json");
  210. if (!existsSync(manifestPath)) {
  211. throw new Error(`[prepare:agent-bundle] missing official plugin manifest: ${manifestPath}`);
  212. }
  213. const targetRoot = resolve(glmDir, plugin.stagedPath);
  214. mkdirSync(targetRoot, { recursive: true });
  215. for (const entryName of includedOfficialPluginTopLevelPaths) {
  216. const sourcePath = resolve(sourceRoot, entryName);
  217. if (!existsSync(sourcePath)) continue;
  218. cpSync(sourcePath, resolve(targetRoot, entryName), {
  219. recursive: true,
  220. filter: shouldCopyOfficialPluginAsset,
  221. });
  222. }
  223. for (const relativePath of plugin.requiredSeedPaths ?? []) {
  224. const stagedAssetPath = resolve(targetRoot, ...relativePath.split("/"));
  225. if (!existsSync(stagedAssetPath)) {
  226. throw new Error(
  227. `[prepare:agent-bundle] missing staged official plugin seed asset: ${stagedAssetPath}`,
  228. );
  229. }
  230. }
  231. console.log(`[prepare:agent-bundle] staged official plugin ${plugin.stagedPath}`);
  232. }
  233. }
  234. // Electron 生产包只带 resources/glm/zcode.cjs 时,app-server 进程的
  235. // __dirname 附近没有官方插件目录,启动时 seed 找不到 source,用户侧不会自动得到内置插件。
  236. // 这里把官方插件按 bootstrap 的 rootCandidates 期望放到 glm/packages/*-plugin,
  237. // 让 Electron Node 运行 zcode.cjs 时复用同一套 filesystem seed 逻辑。
  238. // browser-use runtime 的声明生成依赖 @zcode/core/dist。CI 干净检出没有该产物,
  239. // 必须先构建 CLI 依赖,再构建官方插件;开发机残留的 dist 曾掩盖这个顺序问题。
  240. buildCliBundle();
  241. buildOfficialPluginRuntimes();
  242. stageBundle();
  243. stageOfficialPlugins();