bash-direct-probe.cjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // 实际 adapter 的跨平台验证:node bash-direct-probe.cjs <bundled-adapter.cjs> [report.json]
  2. const assert = require("node:assert/strict");
  3. const fs = require("node:fs/promises");
  4. const { join, resolve } = require("node:path");
  5. const { tmpdir } = require("node:os");
  6. const { setTimeout: sleep } = require("node:timers/promises");
  7. const { createHash } = require("node:crypto");
  8. const { NodeExecutionAdapter } = require(resolve(process.argv[2]));
  9. const report = { node: process.version, platform: process.platform, arch: process.arch, cases: [] };
  10. const shells =
  11. process.platform === "win32"
  12. ? [
  13. { name: "Git Bash", path: "C:\\Program Files\\Git\\bin\\bash.exe", dialect: "git-bash" },
  14. {
  15. name: "CMD",
  16. path: process.env.ComSpec || "C:\\Windows\\System32\\cmd.exe",
  17. dialect: "cmd",
  18. },
  19. ]
  20. : [{ name: "bash", path: "/bin/bash", dialect: "posix" }];
  21. const hash = (data) => createHash("sha256").update(data).digest("hex");
  22. async function waitFor(check) {
  23. const deadline = Date.now() + 15_000;
  24. let error;
  25. do {
  26. try {
  27. await check();
  28. return;
  29. } catch (failure) {
  30. error = failure;
  31. }
  32. await sleep(20);
  33. } while (Date.now() < deadline);
  34. throw error;
  35. }
  36. async function probe(shell, name, execute) {
  37. const root = await fs.mkdtemp(join(tmpdir(), "zcode-adapter-probe-"));
  38. const cwd = join(root, "输出 with spaces");
  39. await fs.mkdir(cwd);
  40. const writer = join(cwd, "writer.cjs");
  41. const release = join(cwd, "release");
  42. const path = join(root, "probe", "output-stdout.log");
  43. const adapter = new NodeExecutionAdapter({
  44. outputRootDir: root,
  45. progressThresholdMs: 0,
  46. progressIntervalMs: 25,
  47. });
  48. const request = {
  49. command: {
  50. mode: "shell",
  51. shellProfile: "posix-bash",
  52. shellOverride: {
  53. path: shell.path,
  54. dialect: shell.dialect,
  55. display: { name: shell.name },
  56. source: "user-config",
  57. },
  58. command:
  59. shell.dialect === "cmd"
  60. ? '"%PROBE_NODE%" "%PROBE_WRITER%"'
  61. : '"$PROBE_NODE" "$PROBE_WRITER"',
  62. },
  63. cwd,
  64. timeoutMs: 15_000,
  65. env: { set: { PROBE_NODE: process.execPath, PROBE_WRITER: writer, PROBE_RELEASE: release } },
  66. outputLimit: {
  67. maxInlineBytes: 30_000,
  68. maxArtifactBytes: 64 * 1024 ** 2,
  69. persistOutput: "always",
  70. },
  71. trace: { sessionId: "probe", attributes: { toolCallId: "output" } },
  72. };
  73. const started = Date.now();
  74. try {
  75. const details = await execute({ adapter, request, writer, release, path, cwd });
  76. report.cases.push({
  77. shell: shell.name,
  78. name,
  79. pass: true,
  80. elapsedMs: Date.now() - started,
  81. ...details,
  82. });
  83. console.log(JSON.stringify(report.cases.at(-1)));
  84. } finally {
  85. await fs.writeFile(release, "go").catch(() => undefined);
  86. await adapter.close();
  87. await fs.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
  88. }
  89. }
  90. const gate = `const fs=require('node:fs');fs.writeSync(1,'regular:'+fs.fstatSync(1).isFile()+':'+fs.fstatSync(2).isFile()+'\\n');
  91. fs.writeSync(2,'stderr-first\\n');const t=setInterval(()=>{if(fs.existsSync(process.env.PROBE_RELEASE)){clearInterval(t);fs.writeSync(1,'last-no-newline');}},10);`;
  92. async function main() {
  93. for (const shell of shells) {
  94. await probe(
  95. shell,
  96. "complete-foreground-file-over-64MiB",
  97. async ({ adapter, request, writer, path }) => {
  98. await fs.writeFile(
  99. writer,
  100. `const fs=require('node:fs');fs.writeSync(1,'HEAD');const chunk=Buffer.alloc(1024*1024,120);for(let i=0;i<65;i++)fs.writeSync(1,chunk);fs.writeSync(2,'TAIL');`,
  101. );
  102. const outcome = await adapter.runBashWithBackgroundLifecycle(request, {
  103. mode: "auto_on_timeout",
  104. });
  105. assert.equal(outcome.kind, "foreground");
  106. const output = outcome.result.stdout;
  107. const expected = 65 * 1024 ** 2 + 8;
  108. assert.equal(output.bytes, expected);
  109. assert.equal(output.artifactBytes, expected);
  110. assert.equal(output.artifactTruncated, false);
  111. assert.equal(output.text.length, 30_000);
  112. assert(output.text.startsWith("HEAD"));
  113. const file = await fs.open(path, "r");
  114. try {
  115. assert.equal((await file.stat()).size, expected);
  116. const tail = Buffer.alloc(4);
  117. await file.read(tail, 0, 4, expected - 4);
  118. assert.equal(tail.toString(), "TAIL");
  119. } finally {
  120. await file.close();
  121. }
  122. return { fileBytes: expected, summaryBytes: output.text.length, tail: "TAIL" };
  123. },
  124. );
  125. await probe(
  126. shell,
  127. "two-preview-sizes-before-exit",
  128. async ({ adapter, request, writer, path, release }) => {
  129. await fs.writeFile(
  130. writer,
  131. `const fs=require('node:fs');for(let i=1;i<=120;i++)fs.writeSync(1,'progress-line-'+i+'\\n');const timer=setInterval(()=>{if(fs.existsSync(process.env.PROBE_RELEASE)){clearInterval(timer);fs.writeSync(1,'DONE');}},10);`,
  132. );
  133. const events = [];
  134. const running = adapter.run(request, { onEvent: (event) => events.push(event) });
  135. await waitFor(() => {
  136. const preview = events.findLast((event) => event.outputPreview)?.outputPreview;
  137. assert(preview);
  138. assert(preview.text.includes("progress-line-120"));
  139. assert(!preview.text.includes("progress-line-30"));
  140. assert(preview.fullText.includes("progress-line-30"));
  141. assert.equal(preview.totalLines, 121);
  142. assert.equal(preview.linesEstimated, false);
  143. });
  144. assert(!events.some((event) => event.type === "completed"));
  145. assert((await fs.stat(path)).size > 0);
  146. await fs.writeFile(release, "go");
  147. const result = await running;
  148. assert.equal(result.status, "completed");
  149. assert(result.stdout.text.endsWith("DONE"));
  150. return { preview: events.findLast((event) => event.outputPreview).outputPreview };
  151. },
  152. );
  153. await probe(
  154. shell,
  155. "foreground-real-time",
  156. async ({ adapter, request, writer, release, path }) => {
  157. await fs.writeFile(writer, gate);
  158. const prefix =
  159. shell.dialect === "cmd"
  160. ? "echo builtin-out&echo builtin-err 1>&2&"
  161. : "printf builtin-out; printf builtin-err >&2; /usr/bin/printf external-out; ";
  162. request.command.command = prefix + request.command.command;
  163. const events = [];
  164. const running = adapter.run(request, { onEvent: (event) => events.push(event) });
  165. await waitFor(async () =>
  166. assert.match(await fs.readFile(path, "utf8"), /regular:true:true\nstderr-first\n$/),
  167. );
  168. await waitFor(() =>
  169. assert(
  170. events.some(
  171. (event) => event.type === "progress" && event.stdoutTail.includes("stderr-first"),
  172. ),
  173. ),
  174. );
  175. assert(!events.some((event) => ["completed", "stdout", "stderr"].includes(event.type)));
  176. const before = await fs.readFile(path);
  177. await fs.writeFile(release, "go");
  178. const result = await running;
  179. assert.equal(result.status, "completed");
  180. assert.equal(result.stdout.text, before.toString() + "last-no-newline");
  181. return { bytesBeforeExit: before.length, finalBytes: result.stdout.bytes };
  182. },
  183. );
  184. for (const mode of ["explicit", "auto_on_timeout"]) {
  185. await probe(shell, mode, async ({ adapter, request, writer, release, path }) => {
  186. await fs.writeFile(writer, gate);
  187. request.timeoutMs = 30;
  188. const abort = new AbortController();
  189. const launch = await adapter.runBashWithBackgroundLifecycle(
  190. request,
  191. { mode },
  192. { signal: abort.signal },
  193. );
  194. assert.equal(launch.kind, "backgrounded");
  195. assert.equal(launch.task.outputPath, path);
  196. await waitFor(async () => assert.match(await fs.readFile(path, "utf8"), /stderr-first/));
  197. abort.abort();
  198. await sleep(60);
  199. assert.equal((await adapter.getBackgroundTask(launch.task.taskId)).status, "running");
  200. await fs.writeFile(release, "go");
  201. const done = await adapter.waitForBackgroundTask(launch.task.taskId);
  202. assert.equal(done.status, "completed");
  203. assert.equal(done.result.stdout.text, "regular:true:true\nstderr-first\nlast-no-newline");
  204. });
  205. }
  206. await probe(shell, "late-descendant", async ({ adapter, request, writer, release, path }) => {
  207. const descendant = `const fs=require('node:fs');const t=setInterval(()=>{if(fs.existsSync(process.env.PROBE_RELEASE)){clearInterval(t);fs.writeSync(1,'late-out\\n');fs.writeSync(2,'late-err\\n');}},10);`;
  208. await fs.writeFile(
  209. writer,
  210. `const fs=require('node:fs');fs.writeSync(1,'root\\n');require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify(descendant)}],{stdio:['ignore',1,2],detached:true}).unref();`,
  211. );
  212. const launch = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  213. assert.equal(launch.kind, "backgrounded");
  214. const done = await adapter.waitForBackgroundTask(launch.task.taskId);
  215. assert.equal(done.result.stdout.text, "root\n");
  216. await fs.writeFile(release, "go");
  217. await waitFor(async () =>
  218. assert.equal(await fs.readFile(path, "utf8"), "root\nlate-out\nlate-err\n"),
  219. );
  220. assert.deepEqual((await adapter.getBackgroundTask(launch.task.taskId)).result, done.result);
  221. await sleep(100);
  222. return { bytesAtExit: 5, bytesAfterDescendant: 23 };
  223. });
  224. await probe(shell, "binary-integrity", async ({ adapter, request, writer, path }) => {
  225. await fs.writeFile(
  226. writer,
  227. `const fs=require('node:fs');const b=Buffer.alloc(65549);for(let i=0;i<64;i++){for(let j=0;j<b.length;j++)b[j]=(i+j)%256;let p=0;while(p<b.length)p+=fs.writeSync(i%2+1,b,p,b.length-p);}`,
  228. );
  229. const result = await adapter.run(request);
  230. assert.equal(result.status, "completed");
  231. const actual = await fs.readFile(path);
  232. const expected = Buffer.alloc(64 * 65549);
  233. for (let i = 0; i < 64; i++)
  234. for (let j = 0; j < 65549; j++) expected[i * 65549 + j] = (i + j) % 256;
  235. assert.deepEqual(actual, expected);
  236. return { bytes: actual.length, sha256: hash(actual) };
  237. });
  238. await probe(shell, "concurrent-writers", async ({ adapter, request, writer, path }) => {
  239. const child = `const fs=require('node:fs'),id=process.argv[1];for(let i=0;i<256;i++){const b=Buffer.from((id+':'+i).padEnd(1023,'.')+'\\n');let p=0;while(p<b.length)p+=fs.writeSync(i%2+1,b,p,b.length-p);}`;
  240. await fs.writeFile(
  241. writer,
  242. `const {spawn}=require('node:child_process');for(let i=0;i<4;i++)spawn(process.execPath,['-e',${JSON.stringify(child)},String(i)],{stdio:['ignore',1,2]});`,
  243. );
  244. assert.equal((await adapter.run(request)).status, "completed");
  245. const actual = await fs.readFile(path);
  246. assert.equal(actual.length, 4 * 256 * 1024);
  247. const records = actual.toString().trimEnd().split("\n");
  248. assert.equal(new Set(records).size, 1024);
  249. for (const line of records) assert.match(line, /^[0-3]:\d+\.+$/);
  250. return { bytes: actual.length, records: records.length };
  251. });
  252. await probe(shell, "existing-file-flags", async ({ adapter, request, writer, path }) => {
  253. await fs.mkdir(join(path, ".."), { recursive: true });
  254. await fs.writeFile(path, "existing:");
  255. await fs.writeFile(writer, "require('node:fs').writeSync(1,'new')");
  256. const result = await adapter.run(request);
  257. assert.equal(result.stdout.text, process.platform === "win32" ? "new" : "existing:new");
  258. });
  259. await probe(shell, "background-stop", async ({ adapter, request, writer, path }) => {
  260. await fs.writeFile(writer, gate);
  261. const launch = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  262. assert.equal(launch.kind, "backgrounded");
  263. await waitFor(async () => assert.match(await fs.readFile(path, "utf8"), /stderr-first/));
  264. await adapter.cancelBackgroundTask(launch.task.taskId);
  265. await waitFor(async () =>
  266. assert.equal((await adapter.getBackgroundTask(launch.task.taskId)).result?.exitCode, 137),
  267. );
  268. const result = await adapter.waitForBackgroundTask(launch.task.taskId);
  269. assert.equal(result.status, "cancelled");
  270. assert.equal(result.result.exitCode, 137);
  271. });
  272. }
  273. if (process.argv[3]) await fs.writeFile(process.argv[3], JSON.stringify(report, null, 2));
  274. console.log(JSON.stringify({ complete: true, node: report.node, passed: report.cases.length }));
  275. }
  276. // adapter 的后台 watchdog/杀树计时器不会保活应用;独立验证脚本需要等待完整报告写出。
  277. const keepAlive = setInterval(() => {}, 1_000);
  278. main()
  279. .catch((error) => {
  280. console.error(error);
  281. process.exitCode = 1;
  282. })
  283. .finally(() => clearInterval(keepAlive));