bash-model-result-wire.e2e.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Bash 结果的模型可见文本走真实 runtime、真实 Bash adapter 与 `anthropic-messages` wire:
  2. // 硬超时(04-bash.md「模型 result 映射规则」)、后台命令改目录的 cwd 说明、前台长 sleep 拦截与 Bash 描述
  3. // (04-bash.md「前台 sleep 拦截」「Prompt 约束」)、token 预算提醒默认关闭与静默提醒计时
  4. // (loop/meta-user-context.md「Total-tokens reminder」「Silent-turn reminder」),以及错误结果跑的 Hook 事件
  5. // (hooks.md「失败的定义」)。每个场景都在新 app 里冷恢复,检查已发出的消息逐字节回放。
  6. import { access, mkdir, writeFile } from "node:fs/promises";
  7. import { join } from "node:path";
  8. import { describe, expect, it, vi } from "vitest";
  9. import {
  10. setupBashWireTest,
  11. escapeRegExp,
  12. assertSubagentBashText,
  13. createFixture,
  14. bashCall,
  15. toolResult,
  16. expectColdReplay,
  17. expectNoTotalTokens,
  18. systemTexts,
  19. type WireBody,
  20. SLEEP_ADVICE,
  21. } from "./bash-model-result-wire-fixture.js";
  22. setupBashWireTest();
  23. describe.skipIf(process.platform === "win32")("Bash model result wire and cold resume", () => {
  24. it(
  25. "sends a hard timeout as Exit code 143 and replays it after a cold resume",
  26. { timeout: 30_000 },
  27. async () => {
  28. const f = await createFixture();
  29. f.script.set(1, bashCall("toolu_timeout", { command: "sleep 3", timeout: 1000 }));
  30. await f.run("run the timeout command");
  31. const live = f.bodies[1]!;
  32. expect(toolResult(live, "toolu_timeout")).toEqual({
  33. is_error: true,
  34. text: "Exit code 143\nCommand timed out after 1s",
  35. });
  36. await f.run("after resume", { resume: true });
  37. expectColdReplay(live, f.bodies[2]!);
  38. expectNoTotalTokens(f.bodies);
  39. },
  40. );
  41. it(
  42. "notes that a background command does not move the session cwd",
  43. { timeout: 30_000 },
  44. async () => {
  45. const f = await createFixture();
  46. await mkdir(join(f.workspace, "nested"));
  47. f.script.set(
  48. 1,
  49. bashCall("toolu_bg_cd", { command: "cd nested && sleep 0.2", run_in_background: true }),
  50. );
  51. f.script.set(
  52. 2,
  53. bashCall("toolu_bg_plain", { command: "sleep 0.2", run_in_background: true }),
  54. );
  55. // 两个后台任务完成后开启通知轮;等到第二个任务的通知送达再关闭 app、冷恢复。
  56. await f.run("run the background commands", {
  57. until: (body) => JSON.stringify(body).includes("toolu_bg_plain</tool-use-id>"),
  58. });
  59. const live = f.bodies.at(-1)!;
  60. const cdResult = toolResult(live, "toolu_bg_cd");
  61. expect(cdResult.is_error).toBe(false);
  62. expect(cdResult.text).toMatch(
  63. new RegExp(
  64. `^Command running in background with ID: \\S+\\. Output is being written to: \\S+\\. You will be notified when it completes\\. To check interim output, use Read on that file path\\.\\nSession cwd remains ${escapeRegExp(f.workspace)}; directory changes made by the backgrounded command do not apply to subsequent commands\\.$`,
  65. ),
  66. );
  67. // 没有改目录的后台命令不带这句。
  68. expect(toolResult(live, "toolu_bg_plain").text).not.toContain("Session cwd remains");
  69. const liveCount = f.bodies.length;
  70. await f.run("after resume", { resume: true });
  71. expectColdReplay(live, f.bodies[liveCount]!);
  72. expectNoTotalTokens(f.bodies);
  73. },
  74. );
  75. // hooks.md「失败的定义」:错误结果只跑 PostToolUseFailure,error 是模型看到的正文;
  76. // grep 退出 1 表示没有匹配,仍跑 PostToolUse。
  77. it(
  78. "runs PostToolUseFailure for a failed command and PostToolUse for grep without matches",
  79. { timeout: 30_000 },
  80. async () => {
  81. const f = await createFixture({ recordHooks: true });
  82. await writeFile(join(f.workspace, "sample.txt"), "AUDIT_SAMPLE first line\n");
  83. const missing = join(f.workspace, "deliberately-nonexistent");
  84. f.script.set(1, bashCall("toolu_hook_fail", { command: `ls ${missing}` }));
  85. f.script.set(
  86. 2,
  87. bashCall("toolu_hook_grep", { command: "grep AUDIT_NO_SUCH_TEXT sample.txt" }),
  88. );
  89. await f.run("run the audit commands");
  90. const live = f.bodies[2]!;
  91. const failed = toolResult(live, "toolu_hook_fail");
  92. expect(failed.is_error).toBe(true);
  93. // ls 的退出码与错误文字随系统不同(macOS 1,Linux 2)。
  94. expect(failed.text).toMatch(/^Exit code \d+\nls: .*deliberately-nonexistent/u);
  95. expect(toolResult(live, "toolu_hook_grep")).toEqual({
  96. is_error: false,
  97. text: "(Bash completed with no output)",
  98. });
  99. expect(systemTexts(live).filter((text) => text.includes("hook additional context"))).toEqual([
  100. "PostToolUseFailure:Bash hook additional context: AUDIT_PostToolUseFailure",
  101. "PostToolUse:Bash hook additional context: AUDIT_PostToolUse",
  102. ]);
  103. const inputs = await f.hookInputs();
  104. expect(inputs.map((input) => [input.hook_event_name, input.tool_use_id])).toEqual([
  105. ["PostToolUseFailure", "toolu_hook_fail"],
  106. ["PostToolUse", "toolu_hook_grep"],
  107. ]);
  108. expect(inputs[0]).toMatchObject({ error: failed.text, is_interrupt: false });
  109. expect(inputs[0]).not.toHaveProperty("tool_response");
  110. await f.run("after resume", { resume: true });
  111. expectColdReplay(live, f.bodies[3]!);
  112. },
  113. );
  114. it(
  115. "blocks a long foreground sleep before it runs and replays the block after a cold resume",
  116. { timeout: 30_000 },
  117. async () => {
  118. const f = await createFixture();
  119. f.script.set(
  120. 1,
  121. bashCall("toolu_sleep_block", { command: "sleep 30 && echo AUDIT_RAN > ran.txt" }),
  122. );
  123. // 后台与 25 秒以下的前台 sleep 照常运行。
  124. f.script.set(2, bashCall("toolu_sleep_bg", { command: "sleep 30", run_in_background: true }));
  125. f.script.set(3, bashCall("toolu_sleep_short", { command: "sleep 0.2 && echo AUDIT_SHORT" }));
  126. await f.run("wait for the build");
  127. const live = f.bodies[3]!;
  128. expect(toolResult(live, "toolu_sleep_block")).toEqual({
  129. is_error: true,
  130. text: `<tool_use_error>Blocked: sleep 30 followed by: echo AUDIT_RAN. ${SLEEP_ADVICE}</tool_use_error>`,
  131. });
  132. await expect(access(join(f.workspace, "ran.txt"))).rejects.toThrow();
  133. const background = toolResult(live, "toolu_sleep_bg");
  134. expect(background.is_error).toBe(false);
  135. expect(background.text).toMatch(/^Command running in background with ID: /u);
  136. expect(toolResult(live, "toolu_sleep_short")).toEqual({
  137. is_error: false,
  138. text: "AUDIT_SHORT",
  139. });
  140. const description = f.bodies[0]!.tools?.find((tool) => tool.name === "Bash")?.description;
  141. expect(description).toContain(
  142. "\n- `cd` carries to the next call only in the main session, if the command succeeds and ends inside the working directories.",
  143. );
  144. expect(description).toContain(
  145. "No `&` needed. Foreground `sleep` of 25 seconds or more is blocked; to wait on a condition, run an until-loop with `run_in_background`.\n",
  146. );
  147. expect(description).toContain(
  148. "\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- GitHub notifies the owner of any `@name` written in a PR, issue, or comment.",
  149. );
  150. expect(description).not.toContain("Working directory persists between calls");
  151. await f.run("after resume", { resume: true });
  152. expectColdReplay(live, f.bodies[4]!);
  153. },
  154. );
  155. // 静默提醒按时间判定:每次模型响应耗时 responseMs(伪造 Date)。25 秒一次时第 3 次响应后满 60 秒,
  156. // 第 4 个请求带提醒;很快的连续静默响应不带。冷恢复按原位置原字节回放。
  157. it.each([
  158. [25_000, [false, false, false, true]],
  159. [10, [false, false, false, false, false, false, false]],
  160. ])(
  161. "times the silent reminder with responses of %sms and replays it after a cold resume",
  162. { timeout: 30_000 },
  163. async (responseMs, expected) => {
  164. vi.useFakeTimers({ toFake: ["Date"] });
  165. try {
  166. const f = await createFixture();
  167. f.responseMs = responseMs;
  168. for (let request = 1; request < expected.length; request++) {
  169. f.script.set(request, bashCall(`toolu_quiet_${request}`, { command: "true" }));
  170. }
  171. await f.run("inspect quietly");
  172. const marker = "The user hasn't heard from you in a while.";
  173. expect(
  174. f.bodies.map((body) => systemTexts(body).some((text) => text.includes(marker))),
  175. ).toEqual(expected);
  176. const live = f.bodies.at(-1)!;
  177. const liveCount = f.bodies.length;
  178. await f.run("after resume", { resume: true });
  179. expectColdReplay(live, f.bodies[liveCount]!);
  180. } finally {
  181. vi.useRealTimers();
  182. }
  183. },
  184. );
  185. });
  186. describe.skipIf(process.platform === "win32")(
  187. "Bash background text in subagents over the wire",
  188. () => {
  189. it(
  190. "an Agent with run_in_background=true gets the matching child Bash text",
  191. { timeout: 30_000 },
  192. () => assertSubagentBashText(true, "You will be notified when it completes."),
  193. );
  194. it("blocks a long foreground sleep in a subagent", { timeout: 30_000 }, async () => {
  195. const f = await createFixture();
  196. const isChild = (body: WireBody) => !(body.tools ?? []).some((tool) => tool.name === "Agent");
  197. let parentCalls = 0;
  198. let childCalls = 0;
  199. f.respond = (body) => {
  200. if (isChild(body)) {
  201. childCalls += 1;
  202. return childCalls === 1
  203. ? bashCall("toolu_child_sleep", { command: "sleep 120" })
  204. : undefined;
  205. }
  206. parentCalls += 1;
  207. if (parentCalls !== 1) return undefined;
  208. return {
  209. content: [
  210. {
  211. type: "tool_use",
  212. id: "toolu_agent_sleep",
  213. name: "Agent",
  214. input: {
  215. description: "child task",
  216. prompt: "Wait for two minutes.",
  217. subagent_type: "general-purpose",
  218. run_in_background: false,
  219. },
  220. },
  221. ],
  222. stop: "tool_use",
  223. };
  224. };
  225. await f.run("launch the child");
  226. expect(toolResult(f.bodies.filter(isChild)[1]!, "toolu_child_sleep")).toEqual({
  227. is_error: true,
  228. text: `<tool_use_error>Blocked: standalone sleep 120. ${SLEEP_ADVICE}</tool_use_error>`,
  229. });
  230. });
  231. },
  232. );