download-glm.mjs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // 下载并整理 GLM 平台二进制。
  2. //
  3. // 开发态优先走 ZCODE_AGENT_WORKDIR / 同级仓库源码启动;只有打包态、生产态和无源码的开发环境
  4. // 才需要依赖这个脚本提前准备平台二进制。目录布局统一服务本机打包与远程部署:
  5. // - 当前目标平台输出到 bundled-agents,供本机运行 / 打包直接内置
  6. // - 远程专用平台输出到 mock-cdn,供 remote deploy 按平台拉取
  7. import { execSync } from "child_process";
  8. import fs from "fs";
  9. import path from "path";
  10. import https from "https";
  11. import http from "http";
  12. import { createRequire } from "module";
  13. import { fileURLToPath, pathToFileURL } from "url";
  14. import { resolveIntranetDepsBaseUrl } from "./intranetDefaults.mjs";
  15. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  16. const require = createRequire(import.meta.url);
  17. const REPO_ROOT = path.resolve(__dirname, "..");
  18. function readZCodeAgentRuntimeVersion() {
  19. const runtimeSourcePath = path.join(REPO_ROOT, "packages/shared/src/zcode-agent-runtime.ts");
  20. const runtimeSource = fs.readFileSync(runtimeSourcePath, "utf8");
  21. const match = runtimeSource.match(/version:\s*["']([^"']+)["']/);
  22. if (!match?.[1]) {
  23. throw new Error("Unable to parse ZCode Agent runtime version");
  24. }
  25. return match[1];
  26. }
  27. export const GLM_RUNTIME_VERSION = readZCodeAgentRuntimeVersion();
  28. // Bugfix: GLM 二进制按 zcode-cli 版本发布,旧的 deps/zcode-cli 会在版本升级后复用旧目录。
  29. // 这里读取 shared runtime 里的 glm.version,让下载目录与远程 manifest/cache 版本来源一致。
  30. function resolveDefaultGlmBinaryDownloadBaseUrl(env = process.env) {
  31. return `${resolveIntranetDepsBaseUrl(env)}/zcode-cli-${GLM_RUNTIME_VERSION}`;
  32. }
  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. function detectPlatform() {
  64. const s =
  65. process.platform === "win32" ? "win32" : execSync("uname -s").toString().trim().toLowerCase();
  66. return normalizePlatform(s);
  67. }
  68. function detectArch() {
  69. const m =
  70. process.arch === "x64"
  71. ? "x64"
  72. : process.arch === "arm64"
  73. ? "arm64"
  74. : execSync("uname -m").toString().trim();
  75. return normalizeArch(m);
  76. }
  77. export function resolveGlmDownloadName(platform, arch) {
  78. // Bugfix:Windows 产物命名恢复为 zcode-windows-*.exe,避免继续请求到错误文件名。
  79. if (platform === "win32") {
  80. return `zcode-windows-${arch}.exe`;
  81. }
  82. return `zcode-${platform}-${arch}`;
  83. }
  84. export function resolveGlmDownloadBaseUrl(env = process.env) {
  85. return env.GLM_BINARY_DOWNLOAD_BASE_URL || resolveDefaultGlmBinaryDownloadBaseUrl(env);
  86. }
  87. function isPlainObject(value) {
  88. return typeof value === "object" && value !== null;
  89. }
  90. export function isGlmBundleMetaMatch(meta, expected) {
  91. if (!isPlainObject(meta)) {
  92. return false;
  93. }
  94. const provider = typeof meta.provider === "string" ? meta.provider : null;
  95. const version = typeof meta.version === "string" ? meta.version : null;
  96. const platform = typeof meta.platform === "string" ? meta.platform : null;
  97. const source = typeof meta.source === "string" ? meta.source : null;
  98. return (
  99. provider === "glm" &&
  100. version === expected.version &&
  101. platform === expected.platform &&
  102. source === expected.source
  103. );
  104. }
  105. function readJsonFile(filePath) {
  106. try {
  107. return JSON.parse(fs.readFileSync(filePath, "utf8"));
  108. } catch {
  109. // Bugfix: 历史下载中断或手工改动可能留下损坏 meta。
  110. // 解析失败时不命中缓存,后续按当前 GLM 版本重新下载并重写 meta。
  111. return null;
  112. }
  113. }
  114. function writeGlmBundleMeta(outputDir, expectedMeta) {
  115. const metadata = JSON.stringify(
  116. {
  117. provider: "glm",
  118. version: expectedMeta.version,
  119. platform: expectedMeta.platform,
  120. source: expectedMeta.source,
  121. },
  122. null,
  123. 2,
  124. );
  125. fs.writeFileSync(path.join(outputDir, ".bundle-meta.json"), `${metadata}\n`, "utf8");
  126. }
  127. function download(url, dest) {
  128. return new Promise((resolve, reject) => {
  129. const mod = url.startsWith("https") ? https : http;
  130. const file = fs.createWriteStream(dest);
  131. mod
  132. .get(url, (res) => {
  133. if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
  134. file.close();
  135. fs.unlinkSync(dest);
  136. return download(res.headers.location, dest).then(resolve, reject);
  137. }
  138. if (res.statusCode !== 200) {
  139. file.close();
  140. fs.unlinkSync(dest);
  141. return reject(new Error(`Download failed: HTTP ${res.statusCode}`));
  142. }
  143. res.pipe(file);
  144. file.on("finish", () => file.close(resolve));
  145. file.on("error", reject);
  146. })
  147. .on("error", (err) => {
  148. file.close();
  149. fs.unlink(dest, () => {});
  150. reject(err);
  151. });
  152. });
  153. }
  154. export async function main() {
  155. const platform =
  156. normalizePlatform(process.argv[2] || process.env.ZCODE_TARGET_OS || "") || detectPlatform();
  157. const arch =
  158. normalizeArch(process.argv[3] || process.env.ZCODE_TARGET_ARCH || "") || detectArch();
  159. const forceRemoteOutput = process.env.ZCODE_FORCE_REMOTE_MOCK_CDN === "1";
  160. const localPlatform = normalizePlatform(process.env.ZCODE_TARGET_OS || "") || detectPlatform();
  161. const localArch = normalizeArch(process.env.ZCODE_TARGET_ARCH || "") || detectArch();
  162. const platformKey = `${platform}-${arch}`;
  163. const localKey = `${localPlatform}-${localArch}`;
  164. const repoRoot = REPO_ROOT;
  165. const localOutputDir = path.join(repoRoot, "packages/desktop/bundled-agents", platformKey, "glm");
  166. const version = require(path.join(repoRoot, "package.json")).version;
  167. const remoteOutputDir = path.join(
  168. repoRoot,
  169. "packages/desktop/mock-cdn/releases",
  170. version,
  171. "glm",
  172. platformKey,
  173. );
  174. const outputDir = forceRemoteOutput
  175. ? remoteOutputDir
  176. : platformKey === localKey
  177. ? localOutputDir
  178. : remoteOutputDir;
  179. const binaryName = platform === "win32" ? "zcode-agent.exe" : "zcode-agent";
  180. const binaryPath = path.join(outputDir, binaryName);
  181. const baseUrl = resolveGlmDownloadBaseUrl();
  182. const downloadUrl = `${baseUrl}/${resolveGlmDownloadName(platform, arch)}`;
  183. const expectedMeta = {
  184. version: GLM_RUNTIME_VERSION,
  185. platform: platformKey,
  186. source: downloadUrl,
  187. };
  188. const metadataPath = path.join(outputDir, ".bundle-meta.json");
  189. console.log("==> glm binary download");
  190. console.log(` version: v${expectedMeta.version}`);
  191. console.log(` platform: ${platformKey}`);
  192. console.log(` target: ${binaryPath}`);
  193. if (fs.existsSync(binaryPath)) {
  194. const existingMeta = readJsonFile(metadataPath);
  195. if (isGlmBundleMetaMatch(existingMeta, expectedMeta)) {
  196. console.log(` [skip] 已存在 glm v${expectedMeta.version},跳过`);
  197. process.exit(0);
  198. }
  199. }
  200. fs.mkdirSync(outputDir, { recursive: true });
  201. if (forceRemoteOutput) {
  202. const bundledBinaryPath = path.join(localOutputDir, binaryName);
  203. const bundledMetadataPath = path.join(localOutputDir, ".bundle-meta.json");
  204. const bundledMeta = readJsonFile(bundledMetadataPath);
  205. if (fs.existsSync(bundledBinaryPath) && isGlmBundleMetaMatch(bundledMeta, expectedMeta)) {
  206. // Bugfix: 本机平台与远端平台一致时,旧逻辑会只写 bundled-agents,
  207. // 导致 remote deploy 在 mock-cdn 查不到对应平台资源。
  208. // 这里只回填版本匹配的 bundled 产物,避免把旧 GLM 二进制复制进 mock-cdn。
  209. fs.copyFileSync(bundledBinaryPath, binaryPath);
  210. writeGlmBundleMeta(outputDir, expectedMeta);
  211. if (platform !== "win32") {
  212. try {
  213. fs.chmodSync(binaryPath, 0o755);
  214. } catch {}
  215. }
  216. console.log(` [copy] bundled -> mock-cdn (${bundledBinaryPath})`);
  217. process.exit(0);
  218. }
  219. }
  220. // Bugfix: CI(如 GitLab Docker)里系统临时目录与仓库常在不同挂载点,`rename` 会报 EXDEV;
  221. // 下载临时文件与目标同目录,保证同卷原子替换。
  222. const tmpFile = path.join(outputDir, `.glm-dl-${Date.now()}.part`);
  223. try {
  224. console.log(` [download] ${downloadUrl}`);
  225. await download(downloadUrl, tmpFile);
  226. // Bugfix: 旧逻辑只按文件存在判断缓存,GLM 版本升级后会复用旧二进制。
  227. // 现在 GLM runtime version 已稳定可用,下载完成后重写二进制和 meta,后续按版本命中缓存。
  228. fs.rmSync(binaryPath, { force: true });
  229. fs.renameSync(tmpFile, binaryPath);
  230. if (platform !== "win32") {
  231. try {
  232. fs.chmodSync(binaryPath, 0o755);
  233. } catch {}
  234. }
  235. writeGlmBundleMeta(outputDir, expectedMeta);
  236. console.log(`==> Done! glm (${platformKey}) -> ${binaryPath}`);
  237. } catch (err) {
  238. try {
  239. fs.unlinkSync(tmpFile);
  240. } catch {}
  241. console.error(` [error] ${err.message}`);
  242. process.exit(1);
  243. }
  244. }
  245. const entryHref = process.argv[1] ? pathToFileURL(process.argv[1]).href : null;
  246. if (entryHref === import.meta.url) {
  247. await main();
  248. }