subagent-config-proxy.mjs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { execFile, spawn } from "node:child_process";
  2. import { appendFile, readFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { createInterface } from "node:readline";
  5. // 非 CLI 进程(Electron/Host、存储准备 Worker)只加载模块,不拦截原始入口。
  6. if (process.argv.includes("app-server") && process.argv.includes("--stdio")) {
  7. // 仅由本组 WDIO 预加载的透明 stdio 代理。真实 Host/CLI 完成保存、解析和执行;
  8. // 故障位于传输边界,不修改业务对象,也不记录其他 RPC 的鉴权或模型凭据。
  9. // WDIO 以 file:// URL 注入预加载(Windows 不接受裸绝对路径),这里按同一形式剥离。
  10. const preload = `--import=${JSON.stringify(import.meta.url)}`;
  11. const child = spawn(process.execPath, process.argv.slice(1), {
  12. stdio: ["pipe", "pipe", "inherit"],
  13. // 只移除当前代理预加载,保留覆盖采集等其他 Node 参数,防止递归启动代理。
  14. env: {
  15. ...process.env,
  16. NODE_OPTIONS: (process.env.NODE_OPTIONS ?? "").replace(preload, "").trim(),
  17. },
  18. });
  19. const root = process.env.ZCODE_E2E_ARTIFACT_DIR;
  20. const control = join(root, "subagent-config-control.json");
  21. const log = join(root, `subagent-config-rpc-${child.pid}.jsonl`);
  22. // 修复原因:Windows 上 CLI 由每个 CLI 独占的原生 helper(zcode-runtime-host.exe)在 Job 中创建,
  23. // process.ppid 是 helper 而不是 Host,"两个 CLI 属于同一 Host" 的断言会误报。父进程是该 helper 时
  24. // 再上取一级(helper 由 Host 直接启动);其他平台与非 helper 父进程保持 process.ppid。
  25. const hostPid =
  26. process.platform === "win32"
  27. ? new Promise((resolveHostPid) =>
  28. execFile(
  29. "powershell.exe",
  30. [
  31. "-NoProfile",
  32. "-Command",
  33. `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${process.ppid}"; "$($p.Name)|$($p.ParentProcessId)"`,
  34. ],
  35. { windowsHide: true },
  36. (error, stdout) => {
  37. const [name, parentPid] = String(stdout).trim().split("|");
  38. resolveHostPid(
  39. !error && name?.toLowerCase() === "zcode-runtime-host.exe" && Number(parentPid) > 0
  40. ? Number(parentPid)
  41. : process.ppid,
  42. );
  43. },
  44. ),
  45. )
  46. : Promise.resolve(process.ppid);
  47. const pending = new Map();
  48. let outbound = Promise.resolve(),
  49. inbound = Promise.resolve();
  50. const writeLog = async (event) =>
  51. appendFile(
  52. log,
  53. JSON.stringify({
  54. time: Date.now(),
  55. pid: child.pid,
  56. hostPid: await hostPid,
  57. cwd: process.cwd(),
  58. ...event,
  59. }) + "\n",
  60. );
  61. createInterface({ input: child.stdout }).on("line", (line) => {
  62. outbound = outbound
  63. .then(async () => {
  64. let frame;
  65. try {
  66. frame = JSON.parse(line);
  67. } catch {
  68. process.stdout.write(line + "\n");
  69. return;
  70. }
  71. if (frame.method === "subagents/readRuntimeConfig") {
  72. const state = JSON.parse(await readFile(control, "utf8").catch(() => "{}"));
  73. const sessionId = frame.params.sessionId;
  74. const failed = state.failedSessionIds?.includes(sessionId) === true;
  75. await writeLog({ kind: "read", sessionId, failed });
  76. // 重载不再阻塞 RPC;关闭用例在测试传输边界保持请求待决,独立验证真实断连取消。
  77. if (state.heldSessionIds?.includes(sessionId)) {
  78. await writeLog({ kind: "held", sessionId });
  79. return;
  80. }
  81. if (failed) {
  82. child.stdin.write(
  83. JSON.stringify({
  84. id: frame.id,
  85. error: { code: -32603, message: "E2E_CONFIG_UNAVAILABLE" },
  86. }) + "\n",
  87. );
  88. return;
  89. }
  90. pending.set(frame.id, sessionId);
  91. }
  92. process.stdout.write(line + "\n");
  93. })
  94. .catch((error) => {
  95. process.stderr.write(String(error));
  96. process.exitCode = 1;
  97. child.kill();
  98. });
  99. });
  100. createInterface({ input: process.stdin })
  101. .on("line", (line) => {
  102. inbound = inbound
  103. .then(async () => {
  104. const frame = JSON.parse(line);
  105. if (pending.has(frame.id)) {
  106. await writeLog({
  107. kind: "snapshot",
  108. sessionId: pending.get(frame.id),
  109. snapshot: frame.result,
  110. error: frame.error,
  111. });
  112. pending.delete(frame.id);
  113. }
  114. child.stdin.write(line + "\n");
  115. })
  116. .catch((error) => {
  117. process.stderr.write(String(error));
  118. process.exitCode = 1;
  119. child.kill();
  120. });
  121. })
  122. .on("close", () => {
  123. void inbound.then(() => child.stdin.end());
  124. });
  125. for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => child.kill(signal));
  126. child.on("exit", (code) => {
  127. void Promise.all([inbound, outbound]).finally(() => process.exit(code ?? 1));
  128. });
  129. // 预加载阶段等待代理子进程退出,不能再次执行当前进程原定的 CLI 入口。
  130. await new Promise(() => {});
  131. }