prepare-agent-node-bundle.mjs 12 KB

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