sea-cua-runtime-assets.mjs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import { spawn } from "node:child_process";
  2. import { cp, readdir, rm } from "node:fs/promises";
  3. import { existsSync } from "node:fs";
  4. import { createRequire } from "node:module";
  5. import { dirname, join, relative, resolve, sep } from "node:path";
  6. import { readMachOArchs, readPeArchs } from "../../../../../scripts/native-binary-archs.mjs";
  7. import { isRealComputerUseProducerInstalled } from "../../../../../packages/desktop/scripts/computer-use-producer.mjs";
  8. import { stageSharpIntoBundledAgents } from "../../../../../packages/desktop/scripts/sharp-package-assets.mjs";
  9. import { targetParts } from "./sea-targets.mjs";
  10. export const CUA_SEA_TARGETS = Object.freeze(["darwin-arm64", "darwin-x64", "win-arm64", "win-x64"]);
  11. export const CUA_SEA_ADDON_SEED_PATH = "native/ax_native.node";
  12. const resolveRepositoryRoot = (root) => resolve(root, "..", "..");
  13. /**
  14. * 规则见 apps/zcode-cli/docs/design/v2/cua-standalone-in-process-broker.md「发布物(SEA)」。
  15. * 返回 null 表示该 target 不内置 computer-use(开源占位 producer)。
  16. */
  17. export async function collectCuaRuntimeFiles({
  18. root,
  19. stagingDirectory,
  20. target,
  21. addonPath,
  22. hostPlatform = process.platform,
  23. producerIsReal,
  24. readArchs,
  25. runNodeGyp,
  26. stageSharp,
  27. }) {
  28. const repositoryRoot = resolveRepositoryRoot(root);
  29. const desktopPackageRoot = join(repositoryRoot, "packages", "desktop");
  30. const isReal = producerIsReal ?? (() => isRealComputerUseProducerInstalled({ desktopPackageRoot }));
  31. if (!isReal()) return null;
  32. const { arch, releasePlatform } = targetParts(target);
  33. const os = releasePlatform === "win" ? "win32" : releasePlatform;
  34. const cuaRoot = join(repositoryRoot, "packages", "zcode-cua");
  35. // 只有一份 build/Release 时,`--all` 的 darwin-x64 在 arm64 Mac 上必然架构不符;macOS 主机按 target 现编。
  36. const addon =
  37. addonPath ??
  38. (os === "darwin" && hostPlatform === "darwin"
  39. ? await buildAddon({
  40. arch,
  41. cuaRoot,
  42. runNodeGyp: runNodeGyp ?? defaultRunNodeGyp,
  43. workDirectory: join(stagingDirectory, "ax-native-build"),
  44. })
  45. : join(cuaRoot, "build", "Release", "ax_native.node"));
  46. const hint =
  47. os === hostPlatform
  48. ? `Run \`node-gyp rebuild --arch=${arch}\` in packages/zcode-cua.`
  49. : `It can only be built on ${os}; build the platforms this host supports, e.g. \`pnpm build:sea --darwin --linux\` on macOS.`;
  50. if (!existsSync(addon)) {
  51. throw new Error(`Missing ax_native.node for ${target} at ${addon}. ${hint}`);
  52. }
  53. const archs = (readArchs ?? (os === "win32" ? readPeArchs : readMachOArchs))(addon);
  54. if (!archs.includes(arch)) {
  55. throw new Error(
  56. `ax_native.node at ${addon} is ${archs.join(",") || "<unknown>"}, but SEA target ${target} needs ${arch}. ${hint}`,
  57. );
  58. }
  59. const sharpStaging = join(stagingDirectory, "sharp");
  60. await (stageSharp ?? defaultStageSharp)({ desktopPackageRoot, stagingDirectory: sharpStaging, os, arch });
  61. const files = [{ path: CUA_SEA_ADDON_SEED_PATH, sourcePath: addon }];
  62. for await (const sourcePath of walkFiles(join(sharpStaging, "node_modules"))) {
  63. files.push({
  64. path: ["node_modules", ...relative(join(sharpStaging, "node_modules"), sourcePath).split(sep)].join("/"),
  65. sourcePath,
  66. });
  67. }
  68. return files;
  69. }
  70. /**
  71. * 把 binding.gyp 与 src/native 复制到暂存目录再编译。不在 packages/zcode-cua 原地 rebuild:那份
  72. * build/Release 是桌面开发与 E2E 加载的主机架构 addon,`--all` 中途换成 x64 会让它们加载失败。
  73. */
  74. async function buildAddon({ arch, cuaRoot, runNodeGyp, workDirectory }) {
  75. await rm(workDirectory, { force: true, recursive: true });
  76. await cp(join(cuaRoot, "binding.gyp"), join(workDirectory, "binding.gyp"));
  77. await cp(join(cuaRoot, "src", "native"), join(workDirectory, "src", "native"), { recursive: true });
  78. console.log(`[sea] building ax_native.node for ${arch} in ${workDirectory}`);
  79. await runNodeGyp({ args: ["rebuild", `--arch=${arch}`], cuaRoot, cwd: workDirectory });
  80. return join(workDirectory, "build", "Release", "ax_native.node");
  81. }
  82. function defaultRunNodeGyp({ args, cuaRoot, cwd }) {
  83. const requireFromCua = createRequire(join(cuaRoot, "package.json"));
  84. // binding.gyp 用 `node -p "require('node-addon-api').include"` 取头文件;暂存目录不在 zcode-cua 包内,
  85. // 用 NODE_PATH 指向 zcode-cua 解析到的 node_modules。
  86. const nodeModules = dirname(dirname(requireFromCua.resolve("node-addon-api")));
  87. return new Promise((resolveRun, reject) => {
  88. const child = spawn(process.execPath, [requireFromCua.resolve("node-gyp/bin/node-gyp.js"), ...args], {
  89. cwd,
  90. env: { ...process.env, NODE_PATH: nodeModules },
  91. stdio: "inherit",
  92. });
  93. child.once("error", reject);
  94. child.once("exit", (code, signal) => {
  95. if (code === 0) resolveRun();
  96. else reject(new Error(`node-gyp ${args.join(" ")} failed (${signal ?? code}) in ${cwd}`));
  97. });
  98. });
  99. }
  100. function defaultStageSharp({ desktopPackageRoot, stagingDirectory, os, arch }) {
  101. stageSharpIntoBundledAgents({
  102. desktopPackageRoot,
  103. glmDir: stagingDirectory,
  104. targetPlatform: { os, arch, key: `${os}-${arch}` },
  105. });
  106. }
  107. async function* walkFiles(directory) {
  108. for (const entry of await readdir(directory, { withFileTypes: true })) {
  109. const fullPath = join(directory, entry.name);
  110. if (entry.isDirectory()) yield* walkFiles(fullPath);
  111. else if (entry.isFile()) yield fullPath;
  112. }
  113. }