runtime.mjs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import assert from "node:assert/strict";
  2. import { createHash } from "node:crypto";
  3. import { execFile } from "node:child_process";
  4. import { readFile, writeFile, readdir, lstat, readlink } from "node:fs/promises";
  5. import { dirname, join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { promisify } from "node:util";
  8. export const directory = dirname(fileURLToPath(import.meta.url));
  9. export const config = JSON.parse(await readFile(join(directory, "config.json"), "utf8"));
  10. export const isWindows = process.platform === "win32";
  11. // Windows 上 Agent 的 Bash 是 Git Bash;裸 bash 可能解析到 WSL,必须用测试传入的绝对路径。
  12. export const bash = config.bash ?? "/bin/bash";
  13. export const agentCommand = /(?:zcode-cli|agent-cli|zcode-agent|[\\/]cli[\\/]dist[\\/])/;
  14. export const docs = join(directory, "中文 空格");
  15. export const tools = ["python", "qpdf", "pandoc", "poppler", "libreoffice"];
  16. export const entries = {
  17. python: ["zcode-python"],
  18. qpdf: ["qpdf"],
  19. pandoc: ["pandoc"],
  20. poppler: ["pdftoppm", "pdftotext", "pdfimages", "pdfinfo"],
  21. libreoffice: ["zcode-soffice"],
  22. };
  23. export const hash = async (path) =>
  24. createHash("sha256")
  25. .update(await readFile(path))
  26. .digest("hex");
  27. export const record = async (id) =>
  28. JSON.parse(await readFile(join(config.root, "tools", id, "installation.json"), "utf8"));
  29. export const put = (name, value) =>
  30. writeFile(join(directory, `${name}.json`), JSON.stringify(value, null, 2));
  31. export const get = async (name) =>
  32. JSON.parse(await readFile(join(directory, `${name}.json`), "utf8"));
  33. const run = promisify(execFile);
  34. const commands = [];
  35. let logWrite = Promise.resolve();
  36. /** 公开入口的可执行文件:Windows 上是 shim 副本 <name>.exe,其他平台是 sh 脚本。与 E2E 辅助函数同规则。 */
  37. export const entryPath = (name) => join(config.root, "bin", isWindows ? `${name}.exe` : name);
  38. /** 入口指向的目标、参数和环境值;Windows 上解码 shim 配置,避免 JSON 转义的反斜杠让断言落空。 */
  39. export async function entryDefinition(name) {
  40. if (!isWindows) return readFile(join(config.root, "bin", name), "utf8");
  41. const shim = JSON.parse(await readFile(join(config.root, "bin", `${name}.shim`), "utf8"));
  42. return [shim.target, ...shim.args, ...shim.env.map((item) => item.value ?? "")].join("\n");
  43. }
  44. // Windows 入口是 shim 可执行文件,Node 不经 shell 即可按名字从 PATH 找到 <name>.exe。
  45. export async function execute(file, args, expectedCode = 0, options = {}) {
  46. let result;
  47. try {
  48. result = {
  49. ...(await run(file, args, {
  50. timeout: 180000,
  51. maxBuffer: 4 * 1024 * 1024,
  52. windowsHide: true,
  53. ...options,
  54. })),
  55. code: 0,
  56. };
  57. } catch (error) {
  58. result = {
  59. stdout: error.stdout ?? "",
  60. stderr: error.stderr ?? "",
  61. code: error.code,
  62. signal: error.signal,
  63. };
  64. }
  65. commands.push({ file, args, ...result });
  66. const receipt = [...commands];
  67. logWrite = logWrite.then(() => put(`commands-${process.argv[2]}`, receipt));
  68. await logWrite;
  69. if (expectedCode !== null)
  70. assert.equal(result.code, expectedCode, JSON.stringify(commands.at(-1)));
  71. return result;
  72. }
  73. export async function selected(name) {
  74. const found = (
  75. await execute(bash, ["-c", 'command -v "$1" || true', "probe", name])
  76. ).stdout.trim();
  77. // Git Bash 给出 /c/... 形式;转回 Windows 路径后再与入口目录比较。
  78. if (!isWindows || !found) return found;
  79. return (await execute(bash, ["-c", 'cygpath -w "$1"', "probe", found])).stdout.trim();
  80. }
  81. export async function plugin(name) {
  82. const cache = join(config.storageRoot, "cli/plugins/cache/zcode-plugins-official", name);
  83. const versions = await readdir(cache);
  84. assert.equal(versions.length, 1);
  85. const root = join(cache, versions[0]);
  86. const metadata = JSON.parse(await readFile(join(root, ".zcode-plugin/plugin.json"), "utf8"));
  87. assert.equal(metadata.version, versions[0]);
  88. assert.equal(await hash(join(root, "scripts/zcode_libreoffice.py")), config.helperSha256);
  89. return root;
  90. }
  91. export async function tree(root) {
  92. const result = {};
  93. async function walk(relative) {
  94. let items;
  95. try {
  96. items = await readdir(join(root, relative), { withFileTypes: true });
  97. } catch (error) {
  98. if (error.code === "ENOENT" && !relative) return;
  99. throw error;
  100. }
  101. for (const item of items.sort((a, b) => a.name.localeCompare(b.name))) {
  102. const name = join(relative, item.name);
  103. const path = join(root, name);
  104. if (item.isSymbolicLink()) result[name] = `link:${await readlink(path)}`;
  105. else if (item.isDirectory()) {
  106. result[name] = "directory";
  107. await walk(name);
  108. } else {
  109. assert.ok((await lstat(path)).isFile());
  110. result[name] = await hash(path);
  111. }
  112. }
  113. }
  114. await walk("");
  115. return result;
  116. }
  117. export async function snapshots() {
  118. const root = join(config.storageRoot, "cli/exec/shell-snapshots");
  119. return Promise.all(
  120. (await readdir(root))
  121. .sort()
  122. .map(async (name) => ({ name, sha256: await hash(join(root, name)) })),
  123. );
  124. }
  125. async function processTable() {
  126. if (!isWindows) {
  127. const result = await run("/bin/ps", ["-axo", "pid=,ppid=,command="]);
  128. return result.stdout
  129. .split("\n")
  130. .map((line) => line.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/))
  131. .filter(Boolean)
  132. .map((match) => ({ pid: Number(match[1]), parent: Number(match[2]), command: match[3] }));
  133. }
  134. const script =
  135. "[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress";
  136. const result = await run(
  137. "powershell.exe",
  138. ["-NoProfile", "-NonInteractive", "-Command", script],
  139. {
  140. maxBuffer: 16 * 1024 * 1024,
  141. windowsHide: true,
  142. },
  143. );
  144. return JSON.parse(result.stdout).map((row) => ({
  145. pid: row.ProcessId,
  146. parent: row.ParentProcessId,
  147. command: row.CommandLine ?? "",
  148. }));
  149. }
  150. export async function ancestors() {
  151. const rows = new Map((await processTable()).map((row) => [row.pid, row]));
  152. const chain = [];
  153. let pid = process.ppid;
  154. while (rows.has(pid) && pid > 1 && !chain.some((row) => row.pid === pid)) {
  155. const row = rows.get(pid);
  156. chain.push(row);
  157. pid = row.parent;
  158. }
  159. return chain;
  160. }
  161. export async function assertSameAgent() {
  162. const before = await get("before");
  163. assert.deepEqual(await snapshots(), before.snapshots);
  164. const current = await ancestors();
  165. const original = before.ancestors.find((item) => agentCommand.test(item.command));
  166. assert.ok(original, JSON.stringify(before.ancestors));
  167. assert.ok(
  168. current.some((item) => item.pid === original.pid && item.command === original.command),
  169. "original Agent process exited",
  170. );
  171. return { agentPid: original.pid, ancestors: current };
  172. }