child-spawn-args.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /**
  2. * 沙箱子进程的 **spawn 策略**契约(`RunWorkflowOptions.childSpawn`)。
  3. *
  4. * 2026-09-09 追记(docs/dynamic-workflow/launch.md)之后,payload 不再过命令行:harness 先把
  5. * 入口文件写到 `<cwd>/.zcode/workflow-runs/<runId>.mjs`,argv 只剩路径。
  6. * - 缺省策略:`node --max-old-space-size=… <entry>`(没有 `--input-type` / `--eval`);
  7. * - SEA(bug 根因见同一 spec 的「SEA 子命令」):SEA 单文件二进制**不解释 Node CLI 旗标**,
  8. * 故 harness 允许调用方(bootstrap,只在 SEA 下)改用 `childSpawn.argsPrefix`:
  9. * `execPath [...argsPrefix, <entry>]`,零旗标。
  10. *
  11. * 两条断言方向缺一不可:
  12. * - 缺省分支的 argv 形状(旗标、入口路径、`ELECTRON_RUN_AS_NODE`)必须钉住,否则 SEA 修法会
  13. * 顺手回归掉桌面 Electron helper 的既有修复;
  14. * - argsPrefix 分支必须**真的能跑完一个 run**,光断言 argv 形状只能证明我们拼对了字符串,
  15. * 证明不了子进程侧「import 入口文件、调 start」的形态也成立。这里用一个 SEA CLI 的替身脚本
  16. * (正是 dwf-child-command.ts 做的事)跑真链路。
  17. */
  18. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  19. import { tmpdir } from "node:os";
  20. import { join } from "node:path";
  21. import { afterEach, describe, expect, it, vi } from "vitest";
  22. import type { spawn as spawnType } from "node:child_process";
  23. import { InMemoryJournalStore } from "@zcode/dynamic-workflow";
  24. import { runWorkflowScript } from "../src/index.js";
  25. import { AutoDriver } from "./auto-driver.js";
  26. import { askSpecsFor } from "./helpers.js";
  27. // 包一层真 spawn:只截获 args/options,子进程照常启动——桥接、结算全走真实路径。
  28. const spawnCalls: Array<{ args: readonly string[]; options: Record<string, unknown> }> = [];
  29. vi.mock("node:child_process", async (importOriginal) => {
  30. const actual = await importOriginal<typeof import("node:child_process")>();
  31. const wrapped: typeof spawnType = ((...args: Parameters<typeof spawnType>) => {
  32. spawnCalls.push({
  33. args: (args[1] ?? []) as readonly string[],
  34. options: (args[2] ?? {}) as Record<string, unknown>,
  35. });
  36. return actual.spawn(...args);
  37. }) as typeof spawnType;
  38. return { ...actual, spawn: wrapped };
  39. });
  40. const SCRIPT = ['const a = agent("a");', 'const r = await a.ask("hello");', "return r;"].join("\n");
  41. const roots: string[] = [];
  42. afterEach(async () => {
  43. spawnCalls.length = 0;
  44. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  45. });
  46. async function tempRoot(prefix: string): Promise<string> {
  47. const root = await mkdtemp(join(tmpdir(), prefix));
  48. roots.push(root);
  49. return root;
  50. }
  51. /** 跑一个真实 run(一次 ask,AutoDriver 回 "hi"),返回结算与 run cwd。 */
  52. async function runOnce(extra: Partial<Parameters<typeof runWorkflowScript>[0]> = {}) {
  53. const cwd = await tempRoot("dwf-spawn-args-cwd-");
  54. const journal = new InMemoryJournalStore();
  55. const driver = new AutoDriver(journal, { asks: { "ask#1": () => ({ type: "text", finalText: "hi" }) } });
  56. const settlement = await runWorkflowScript({
  57. scriptText: SCRIPT,
  58. runId: "run",
  59. cwd,
  60. caps: { maxConcurrency: 16 },
  61. askSpecs: askSpecsFor(SCRIPT),
  62. validate: () => [],
  63. makeDriver: (sink) => {
  64. driver.attach(sink);
  65. return driver;
  66. },
  67. timeoutMs: 20000,
  68. ...extra,
  69. });
  70. return { settlement, cwd };
  71. }
  72. /** 从入口文件文本里取出内嵌的 payload(不 import 它:import 会在测试进程里跑它的顶层逻辑)。 */
  73. async function readEntryPayload(entryPath: string): Promise<Record<string, unknown>> {
  74. const text = await readFile(entryPath, "utf8");
  75. const match = /^export const payload = (.*);$/m.exec(text);
  76. expect(match).not.toBeNull();
  77. return JSON.parse(match![1]!) as Record<string, unknown>;
  78. }
  79. /**
  80. * 写一个 SEA CLI 的替身:它就是 `dwf-child-command.ts` 的最小形态——import 入口文件、注入真实
  81. * deps 调 `start`。关键是它**不接受任何 Node 旗标**,只认 argv 末位的路径——正是 SEA 二进制的行为。
  82. */
  83. async function writeSeaCliStandIn(): Promise<string> {
  84. const root = await tempRoot("dwf-sea-standin-");
  85. const scriptPath = join(root, "sea-cli-stand-in.mjs");
  86. await writeFile(
  87. scriptPath,
  88. `import { createInterface } from "node:readline";
  89. import { pathToFileURL } from "node:url";
  90. import { createContext, runInContext } from "node:vm";
  91. // 严格模拟 SEA 主程序:除了 argv 末位的入口路径,任何多余 token 都是错误。
  92. if (process.argv.length !== 3) {
  93. process.stderr.write("sea-cli-stand-in: unexpected argv " + JSON.stringify(process.argv.slice(2)) + "\\n");
  94. process.exit(1);
  95. }
  96. const entry = await import(pathToFileURL(process.argv[2]).href);
  97. await entry.start({
  98. vm: { createContext, runInContext },
  99. createInterface,
  100. stdin: process.stdin,
  101. stdout: process.stdout,
  102. });
  103. `,
  104. "utf8",
  105. );
  106. return scriptPath;
  107. }
  108. describe("sandbox child spawn strategy", () => {
  109. it("spawns only the heap flag and the entry path when childSpawn is absent", async () => {
  110. const { settlement, cwd } = await runOnce();
  111. expect(settlement).toEqual({ status: "completed", artifact: "hi" });
  112. expect(spawnCalls).toHaveLength(1);
  113. const args = spawnCalls[0]!.args;
  114. // 命令行上只有旗标与路径——payload 与子进程源码都不在这里(Windows 32,767 字符上限)。
  115. expect(args).toEqual(["--max-old-space-size=256", join(cwd, ".zcode", "workflow-runs", "run.mjs")]);
  116. await expect(readEntryPayload(args[1]!)).resolves.toMatchObject({ lowered: expect.any(String) });
  117. expect(spawnCalls[0]!.options.env).toMatchObject({ ELECTRON_RUN_AS_NODE: "1" });
  118. expect(spawnCalls[0]!.options.cwd).toBe(cwd);
  119. });
  120. it("keeps host-only run metadata out of the child payload (launch stays host-side)", async () => {
  121. // 只有 `args` 过界——沙箱脚本要读它。其余 run 元数据(lineage 指针、工具调用 id、父会话、
  122. // 展示名、以及 launch 那一整块:发起锚点与子代理模型)全是宿主事实。把它们写进入口文件
  123. // 只会让一份 run 级事实多出一个永远不会被读的副本,而那个副本还会随入口文件留在项目的
  124. // .zcode 目录里。launch 里的 `subagentModel` 尤其如此:模型面整个在宿主侧(子进程只把
  125. // ask 经桥递回来),子进程知道跑在哪个模型上既无用处,也没有任何代码路径会去读。
  126. //
  127. // 五个都真的传下去,否则「不在 payload 里」是一句废话。
  128. const { settlement, cwd } = await runOnce({
  129. launch: { inputId: "input-origin", subagentModel: "zhipu/glm-5.3-flash$high" },
  130. resumedFrom: "run-predecessor",
  131. toolCallId: "call-origin",
  132. parentSessionId: "sess_parent",
  133. name: "nightly triage",
  134. args: { topic: "release" },
  135. });
  136. expect(settlement).toEqual({ status: "completed", artifact: "hi" });
  137. const payload = await readEntryPayload(join(cwd, ".zcode", "workflow-runs", "run.mjs"));
  138. // 过界的那一个还在:这条断言让「全都没过界」不能靠一个空 payload 蒙混过去。
  139. expect(payload.args).toEqual({ topic: "release" });
  140. for (const field of ["launch", "resumedFrom", "toolCallId", "parentSessionId", "name"]) {
  141. expect(field in payload).toBe(false);
  142. }
  143. });
  144. it("maps maxOldSpaceSizeMb onto the node flag on the default path", async () => {
  145. await runOnce({ maxOldSpaceSizeMb: 512 });
  146. expect(spawnCalls[0]!.args[0]).toBe("--max-old-space-size=512");
  147. });
  148. it("spawns argsPrefix + entry path with zero node flags, and the run still settles", async () => {
  149. const standIn = await writeSeaCliStandIn();
  150. const { settlement, cwd } = await runOnce({ childSpawn: { argsPrefix: [standIn] } });
  151. // 真链路跑完是这条分支的主张:argv 拼对了,子进程侧「import 入口、调 start」的形态也成立。
  152. expect(settlement).toEqual({ status: "completed", artifact: "hi" });
  153. expect(spawnCalls).toHaveLength(1);
  154. const args = spawnCalls[0]!.args;
  155. expect(args).toEqual([standIn, join(cwd, ".zcode", "workflow-runs", "run.mjs")]);
  156. // 一个旗标都不许漏出去——SEA 主程序会把它们当未知参数而报错退出。
  157. expect(args.some((arg) => arg.startsWith("--"))).toBe(false);
  158. // 堆上限只能随 payload 走(argsPrefix 路上没有旗标可传),由入口文件 best-effort 施加。
  159. await expect(readEntryPayload(args[1]!)).resolves.toMatchObject({ maxOldSpaceSizeMb: 256 });
  160. // Electron helper 的既有修复对两条分支都成立。
  161. expect(spawnCalls[0]!.options.env).toMatchObject({ ELECTRON_RUN_AS_NODE: "1" });
  162. });
  163. it("forwards every argsPrefix token in order, entry path last", async () => {
  164. const standIn = await writeSeaCliStandIn();
  165. // 替身脚本只接受 argv.length === 3,所以多一个 token 必然让它自述失败——这正好证明
  166. // 「prefix 原样透传、入口路径在末位」不是靠巧合成立的。
  167. const { settlement } = await runOnce({
  168. childSpawn: { argsPrefix: [standIn, "__zcode-dwf-child"] },
  169. timeoutMs: 20000,
  170. });
  171. // 子进程非零退出而无 complete:宿主侧故障,stopped(interrupted)。
  172. expect(settlement).toMatchObject({ status: "stopped", reason: "interrupted" });
  173. expect(spawnCalls[0]!.args).toEqual([
  174. standIn,
  175. "__zcode-dwf-child",
  176. expect.stringMatching(/run\.mjs$/),
  177. ]);
  178. });
  179. });