bash-foreground-sleep.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // 前台长 sleep 拦截(04-bash.md「前台 sleep 拦截」):只看第一个顶层元素,`sleep N`(N ≥ 25)在 validateInput
  2. // 拒绝;后台、后台不可用、CMD shell 放行;主会话和子代理都拦截,被拒时不跑 hook、不请求权限、不启动进程。
  3. import { describe, expect, it, onTestFinished, vi } from "vitest";
  4. import {
  5. HookEventName,
  6. createSessionId,
  7. createToolCallId,
  8. createTurnId,
  9. modelMessageContentToText,
  10. type ExecutionPort,
  11. type ExecutionShellSelection,
  12. } from "@zcode/contracts";
  13. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  14. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  15. import { createToolExecutor } from "../src/tool/executor.js";
  16. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  17. import type { BashBackgroundLifecycleExecutionPort } from "../src/tool/handlers/bash-background-lifecycle.js";
  18. import { describeBlockedForegroundSleep } from "../src/tool/handlers/bash-semantics.js";
  19. import { createToolRegistry } from "../src/tool/registry.js";
  20. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  21. import { createTestSessionEventStore } from "./test-event-store.js";
  22. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  23. import { createTestModelFactory } from "./test-runtime-model.js";
  24. const ADVICE =
  25. "To wait for a condition, run an until-loop with run_in_background: true (e.g. `until <check>; do sleep 2; done`); you are notified when it exits. To wait for a command you started, use run_in_background: true. Do not chain shorter sleeps to work around this block.";
  26. const USAGE = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  27. describe("foreground sleep detection", () => {
  28. it.each([
  29. ["sleep 25", "standalone sleep 25"],
  30. ["sleep 25.", "standalone sleep 25"],
  31. ["sleep 0025", "standalone sleep 25"],
  32. ["sleep 25.0", "standalone sleep 25"],
  33. ["sleep 25.50", "standalone sleep 25.5"],
  34. [" sleep 30 ", "standalone sleep 30"],
  35. ["sleep 30 > /dev/null 2>&1", "standalone sleep 30"],
  36. ["sleep 30 &", "standalone sleep 30"],
  37. ["# wait for the server\nsleep 30", "standalone sleep 30"],
  38. ["sleep 30 && make", "sleep 30 followed by: make"],
  39. ["sleep 30; make", "sleep 30 followed by: make"],
  40. ["sleep 30\nmake", "sleep 30 followed by: make"],
  41. ["sleep 30 | cat", "sleep 30 followed by: cat"],
  42. ["sleep 30 |& cat", "sleep 30 followed by: cat"],
  43. ["sleep 30 & wait", "sleep 30 followed by: wait"],
  44. ["sleep 30 && npm test > log.txt || echo failed", "sleep 30 followed by: npm test echo failed"],
  45. ["sleep 30 | cat && (make)", "sleep 30 followed by: cat (make)"],
  46. // 超过解析上限时按整条命令判断。
  47. [`sleep 30${" ".repeat(10_001)}`, "standalone sleep 30"],
  48. ])("blocks %j as %j", (command, reason) => {
  49. expect(describeBlockedForegroundSleep(command)).toBe(reason);
  50. });
  51. it.each([
  52. "sleep 24",
  53. "sleep 24.9",
  54. "sleep 0",
  55. "sleep 25s",
  56. "sleep 1m",
  57. "sleep .5",
  58. "sleep 1e2",
  59. 'sleep "30"',
  60. "FOO=1 sleep 30",
  61. "/bin/sleep 30",
  62. "timeout 40 sleep 30",
  63. "time sleep 30",
  64. "! sleep 30",
  65. "(sleep 30)",
  66. "{ sleep 30; }",
  67. "sh -c 'sleep 60'",
  68. "echo a; sleep 30",
  69. "until curl -s localhost:3000; do sleep 30; done",
  70. // 解析有错误时按整条命令判断,整条命令不匹配。
  71. "sleep 30 && (",
  72. `sleep 30;${" echo x".repeat(2_000)}`,
  73. "",
  74. ])("allows %j", (command) => {
  75. expect(describeBlockedForegroundSleep(command)).toBeUndefined();
  76. });
  77. });
  78. describe("Bash validateInput for foreground sleep", () => {
  79. const lifecyclePort = {
  80. run: vi.fn(),
  81. runBashWithBackgroundLifecycle: vi.fn(),
  82. } as unknown as ExecutionPort;
  83. const posix: ExecutionShellSelection = {
  84. dialect: "posix",
  85. source: "auto-detected",
  86. display: { name: "bash" },
  87. };
  88. it("rejects with error code 10 and the fixed advice", () => {
  89. expect(
  90. bashToolEntry.validateInput?.(
  91. { command: "sleep 30 && make" },
  92. { executionPort: lifecyclePort, bashShellSelection: posix },
  93. ),
  94. ).toEqual({
  95. result: false,
  96. errorCode: 10,
  97. message: `Blocked: sleep 30 followed by: make. ${ADVICE}`,
  98. });
  99. // shell 选择还没初始化时按 posix 处理。
  100. expect(
  101. bashToolEntry.validateInput?.({ command: "sleep 30" }, { executionPort: lifecyclePort }),
  102. ).toMatchObject({ result: false, errorCode: 10 });
  103. });
  104. it.each([
  105. ["run_in_background: true", { command: "sleep 30", run_in_background: true }, {}],
  106. [
  107. "an execution port without the Bash background lifecycle",
  108. { command: "sleep 30" },
  109. { executionPort: { run: vi.fn() } as unknown as ExecutionPort },
  110. ],
  111. ["no execution port", { command: "sleep 30" }, { executionPort: undefined }],
  112. [
  113. "the cmd shell",
  114. { command: "sleep 30" },
  115. { bashShellSelection: { ...posix, dialect: "cmd" as const } },
  116. ],
  117. [
  118. "the legacy shell",
  119. { command: "sleep 30" },
  120. { bashShellSelection: { ...posix, dialect: "legacy-shell" as const } },
  121. ],
  122. ["a short sleep", { command: "sleep 24" }, {}],
  123. ])("allows %s", (_name, input, context) => {
  124. expect(
  125. bashToolEntry.validateInput?.(input, {
  126. executionPort: lifecyclePort,
  127. bashShellSelection: posix,
  128. ...context,
  129. }),
  130. ).toEqual({ result: true });
  131. });
  132. });
  133. it("rejects a long foreground sleep before hooks, permission and execution", async () => {
  134. const hookEvents: string[] = [];
  135. const requestPermission = vi.fn(async () => ({ decision: "allow" as const }));
  136. const port: BashBackgroundLifecycleExecutionPort = {
  137. run: vi.fn(async () => {
  138. throw new Error("execution reached");
  139. }),
  140. runBashWithBackgroundLifecycle: vi.fn(async () => {
  141. throw new Error("execution reached");
  142. }),
  143. };
  144. const registry = createToolRegistry();
  145. registry.register(bashToolEntry);
  146. const executor = createToolExecutor({
  147. emitEvent: async () => {},
  148. executionPort: port,
  149. hookRunner: createInMemoryHookRunner({
  150. hooks: [
  151. HookEventName.PreToolUse,
  152. HookEventName.PostToolUse,
  153. HookEventName.PostToolUseFailure,
  154. ].map((event) => ({
  155. event,
  156. matcher: "Bash",
  157. callback: async (input) => {
  158. hookEvents.push(input.hookEventName);
  159. return {};
  160. },
  161. })),
  162. }),
  163. mode: "build",
  164. permissionBroker: { requestPermission },
  165. permissionService: new PermissionService(defaultPermissionConfig),
  166. registry,
  167. sessionId: createSessionId("bash-sleep-block"),
  168. turnId: createTurnId("turn"),
  169. workingDirectory: process.cwd(),
  170. });
  171. const result = await executor.execute({
  172. id: createToolCallId("bash-sleep"),
  173. input: { command: "sleep 25" },
  174. name: "Bash",
  175. });
  176. expect(result.success).toBe(false);
  177. expect(result.modelContent).toBe(
  178. `<tool_use_error>Blocked: standalone sleep 25. ${ADVICE}</tool_use_error>`,
  179. );
  180. // App 工具卡显示不带标签的原文。
  181. expect(result.error?.message).toBe(`Blocked: standalone sleep 25. ${ADVICE}`);
  182. expect(hookEvents).toEqual([]);
  183. expect(requestPermission).not.toHaveBeenCalled();
  184. expect(port.run).not.toHaveBeenCalled();
  185. expect(port.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  186. });
  187. describe("foreground sleep in a session", () => {
  188. it.each(["main session", "subagent"] as const)(
  189. "the %s gets the blocked result with is_error",
  190. async (actor) => {
  191. const { result, port } = await runSleepCall(actor);
  192. expect(result.isError).toBe(true);
  193. expect(modelMessageContentToText(result.content)).toBe(
  194. `<tool_use_error>Blocked: standalone sleep 30. ${ADVICE}</tool_use_error>`,
  195. );
  196. expect(port.run).not.toHaveBeenCalled();
  197. expect(port.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  198. },
  199. );
  200. });
  201. async function runSleepCall(actor: "main session" | "subagent") {
  202. const requests: any[] = [];
  203. const port: BashBackgroundLifecycleExecutionPort = {
  204. run: vi.fn(async () => {
  205. throw new Error("execution reached");
  206. }),
  207. runBashWithBackgroundLifecycle: vi.fn(async () => {
  208. throw new Error("execution reached");
  209. }),
  210. };
  211. const sleepCall = {
  212. finishReason: "tool-calls",
  213. text: "",
  214. toolCalls: [{ id: "call_sleep", name: "Bash", input: { command: "sleep 30" } }],
  215. usage: USAGE,
  216. };
  217. let childCalls = 0;
  218. const runtime = createTestAgentRuntime(
  219. createSessionId(`bash-sleep-${actor === "subagent" ? "child" : "main"}`),
  220. {
  221. mode: "yolo",
  222. workingDirectory: "/workspace/project",
  223. subagents: {
  224. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  225. alwaysBackground: false,
  226. profiles: [
  227. {
  228. name: "sleep-child",
  229. description: "Waits.",
  230. source: "project",
  231. systemPrompt: "Wait as asked.",
  232. tools: ["Bash"],
  233. },
  234. ],
  235. },
  236. },
  237. {
  238. eventStore: createTestSessionEventStore(),
  239. executionPort: port,
  240. sessionStore: createRecordingSubagentSessionStore(),
  241. modelFactory: createTestModelFactory({
  242. async generateText(request: any) {
  243. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  244. const isParent = toolNames.includes("Agent");
  245. if (actor === "main session" || !isParent) {
  246. if (actor === "subagent") childCalls += 1;
  247. requests.push(request);
  248. if (requests.length === 1) return sleepCall;
  249. return { finishReason: "stop", text: "done", usage: USAGE };
  250. }
  251. if (childCalls === 0) {
  252. return {
  253. finishReason: "tool-calls",
  254. text: "",
  255. toolCalls: [
  256. {
  257. id: "call_child",
  258. name: "Agent",
  259. input: {
  260. description: "Wait",
  261. prompt: "Wait for 30 seconds.",
  262. subagent_type: "sleep-child",
  263. run_in_background: false,
  264. },
  265. },
  266. ],
  267. usage: USAGE,
  268. };
  269. }
  270. return { finishReason: "stop", text: "parent done", usage: USAGE };
  271. },
  272. } as never),
  273. },
  274. );
  275. onTestFinished(async () => {
  276. await runtime.closeBrowserSession();
  277. });
  278. await runtime.executeTurn("wait a bit");
  279. const result = requests[1]?.messages.find(
  280. (item: any) => item.role === "tool" && item.toolCallId === "call_sleep",
  281. );
  282. if (!result) throw new Error("the sleep call has no tool result");
  283. return { result, port };
  284. }