task-stop-tool.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. TASK_STOP_TOOL_NAME,
  4. createRootTraceContext,
  5. createSessionId,
  6. createToolCallId,
  7. createTurnId,
  8. } from "@zcode/contracts";
  9. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  10. import {
  11. isErrorForToolResult,
  12. modelContentForToolResult,
  13. } from "../src/runtime/helpers/tool-result.js";
  14. import { createToolExecutor } from "../src/tool/executor.js";
  15. import { taskStopToolEntry } from "../src/tool/handlers/task-stop.js";
  16. import { createToolRegistry } from "../src/tool/registry.js";
  17. describe("TaskStop tool", () => {
  18. it("projects the complete TaskStop guidance to the provider", () => {
  19. const registry = createToolRegistry();
  20. registry.register(taskStopToolEntry);
  21. const contract = registry.toContracts().find((tool) => tool.name === TASK_STOP_TOOL_NAME);
  22. expect(contract?.description).toBe(
  23. "\n- Stops a running background task by its ID\n- Takes a task_id parameter identifying the task to stop\n- Returns a success or failure status\n- Use this tool when you need to terminate a long-running task\n",
  24. );
  25. });
  26. it("stops a running task through the runtime background task control port", async () => {
  27. const stopped: string[] = [];
  28. const output = await taskStopToolEntry.handler(
  29. { task_id: "task_123" },
  30. {
  31. abortSignal: new AbortController().signal,
  32. backgroundTaskControlPort: {
  33. async stopBackgroundTask(taskId, options) {
  34. stopped.push(`${taskId}:strict:${options.strict}:${options.initiator}`);
  35. return {
  36. command: "sleep 30",
  37. ok: true,
  38. status: "killed",
  39. taskId,
  40. type: "local_bash",
  41. };
  42. },
  43. },
  44. sessionId: "sess_task_stop" as never,
  45. toolCallId: "tool_task_stop",
  46. traceId: "trace_task_stop" as never,
  47. workingDirectory: "/tmp",
  48. workspaceRoot: "/tmp",
  49. },
  50. );
  51. // 模型自己停的:initiator 是 model,终态通知据此不会写成用户的决定。
  52. expect(stopped).toEqual(["task_123:strict:true:model"]);
  53. expect(output).toEqual({
  54. message: "Successfully stopped task: task_123 (sleep 30)",
  55. task_id: "task_123",
  56. task_type: "local_bash",
  57. command: "sleep 30",
  58. });
  59. expect(taskStopToolEntry.formatModelContent?.(output)).toBe(JSON.stringify(output));
  60. });
  61. it("passes the runtime background task control port through executor context", async () => {
  62. const sessionId = createSessionId("task-stop-executor");
  63. const turnId = createTurnId("task-stop-executor");
  64. const traceContext = createRootTraceContext({ sessionId, turnId });
  65. const toolCallId = createToolCallId("task-stop-executor");
  66. const stopped: string[] = [];
  67. const registry = createToolRegistry();
  68. registry.register(taskStopToolEntry);
  69. const executor = createToolExecutor({
  70. backgroundTaskControlPort: {
  71. async stopBackgroundTask(taskId, options) {
  72. stopped.push(`${taskId}:strict:${options.strict}:${options.initiator}`);
  73. return {
  74. command: "Research the current odds",
  75. ok: true,
  76. status: "killed",
  77. taskId,
  78. type: "local_agent",
  79. };
  80. },
  81. },
  82. emitEvent: async () => undefined,
  83. permissionService: new PermissionService(defaultPermissionConfig),
  84. registry,
  85. sessionId,
  86. turnId,
  87. traceContext,
  88. });
  89. const result = await executor.execute(
  90. {
  91. id: toolCallId,
  92. input: { task_id: "agent_bg" },
  93. name: TASK_STOP_TOOL_NAME,
  94. },
  95. { traceContext },
  96. );
  97. expect(stopped).toEqual(["agent_bg:strict:true:model"]);
  98. expect(result.success).toBe(true);
  99. expect(result.output).toMatchObject({
  100. message: "Successfully stopped task: agent_bg (Research the current odds)",
  101. task_id: "agent_bg",
  102. task_type: "local_agent",
  103. command: "Research the current odds",
  104. });
  105. });
  106. it("applies TaskStop permission rules when called through a legacy alias", async () => {
  107. const sessionId = createSessionId("task-stop-alias-permission");
  108. const turnId = createTurnId("task-stop-alias-permission");
  109. const traceContext = createRootTraceContext({ sessionId, turnId });
  110. const toolCallId = createToolCallId("task-stop-alias-permission");
  111. const stopped: string[] = [];
  112. const registry = createToolRegistry();
  113. registry.register(taskStopToolEntry);
  114. const executor = createToolExecutor({
  115. backgroundTaskControlPort: {
  116. async stopBackgroundTask(taskId) {
  117. stopped.push(taskId);
  118. return {
  119. ok: true,
  120. status: "killed",
  121. taskId,
  122. type: "local_bash",
  123. };
  124. },
  125. },
  126. emitEvent: async () => undefined,
  127. permissionService: new PermissionService({
  128. ...defaultPermissionConfig,
  129. disallowedTools: new Set([TASK_STOP_TOOL_NAME]),
  130. }),
  131. registry,
  132. sessionId,
  133. turnId,
  134. traceContext,
  135. });
  136. const result = await executor.execute(
  137. {
  138. id: toolCallId,
  139. input: { task_id: "bash_bg" },
  140. name: "KillShell",
  141. },
  142. { traceContext },
  143. );
  144. expect(result.success).toBe(false);
  145. expect(result.error?.message).toContain("explicitly disallowed");
  146. expect(stopped).toEqual([]);
  147. });
  148. it.each(["exec_12345678", "exec_12345678-1234-4234-8234-123456789abc"])(
  149. "keeps lookup failure for %s visible to the model as an error with full ID guidance",
  150. async (taskId) => {
  151. const sessionId = createSessionId("task-stop-lookup-failure");
  152. const turnId = createTurnId("task-stop-lookup-failure");
  153. const traceContext = createRootTraceContext({ sessionId, turnId });
  154. const registry = createToolRegistry();
  155. registry.register(taskStopToolEntry);
  156. const lookedUp: string[] = [];
  157. const executor = createToolExecutor({
  158. backgroundTaskControlPort: {
  159. async stopBackgroundTask(id) {
  160. lookedUp.push(id);
  161. return { ok: false, reason: "background_task_not_found", taskId: id };
  162. },
  163. },
  164. emitEvent: async () => undefined,
  165. permissionService: new PermissionService(defaultPermissionConfig),
  166. registry,
  167. sessionId,
  168. turnId,
  169. traceContext,
  170. });
  171. const result = await executor.execute(
  172. {
  173. id: createToolCallId("task-stop-lookup-failure"),
  174. input: { task_id: taskId },
  175. name: TASK_STOP_TOOL_NAME,
  176. },
  177. { traceContext },
  178. );
  179. expect(lookedUp).toEqual([taskId]);
  180. expect(result.success).toBe(false);
  181. expect(isErrorForToolResult(result)).toBe(true);
  182. expect(modelContentForToolResult(result)).toBe(
  183. `Invalid task ID "${taskId}". This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.`,
  184. );
  185. },
  186. );
  187. it("registers invisible stop aliases", async () => {
  188. const registry = createToolRegistry();
  189. registry.register(taskStopToolEntry);
  190. expect(registry.get("KillShell")?.handler).toBe(taskStopToolEntry.handler);
  191. expect(registry.get("KillBash")?.handler).toBe(taskStopToolEntry.handler);
  192. expect(registry.toContracts().map((tool) => tool.name)).toEqual([TASK_STOP_TOOL_NAME]);
  193. registry.unregister("KillShell");
  194. expect(registry.get(TASK_STOP_TOOL_NAME)).toBe(taskStopToolEntry);
  195. expect(registry.get("KillShell")).toBeUndefined();
  196. expect(registry.get("KillBash")?.handler).toBe(taskStopToolEntry.handler);
  197. registry.unregister(TASK_STOP_TOOL_NAME);
  198. expect(registry.get(TASK_STOP_TOOL_NAME)).toBeUndefined();
  199. expect(registry.get("KillBash")).toBeUndefined();
  200. });
  201. it("drops stale aliases when a tool is registered again with a smaller alias set", async () => {
  202. const registry = createToolRegistry();
  203. registry.register(taskStopToolEntry);
  204. registry.register(
  205. {
  206. ...taskStopToolEntry,
  207. aliases: ["KillShell"],
  208. },
  209. { silentDuplicateWarning: true },
  210. );
  211. expect(registry.get("KillShell")?.handler).toBe(taskStopToolEntry.handler);
  212. expect(registry.get("KillBash")).toBeUndefined();
  213. });
  214. it("accepts deprecated shell_id as task id", async () => {
  215. const output = await taskStopToolEntry.handler(
  216. { shell_id: "shell_123" },
  217. {
  218. abortSignal: new AbortController().signal,
  219. backgroundTaskControlPort: {
  220. async stopBackgroundTask(taskId) {
  221. return {
  222. command: "npm run dev",
  223. ok: true,
  224. status: "cancelled",
  225. taskId,
  226. type: "local_bash",
  227. };
  228. },
  229. },
  230. sessionId: "sess_task_stop_shell" as never,
  231. toolCallId: "tool_task_stop_shell",
  232. traceId: "trace_task_stop_shell" as never,
  233. workingDirectory: "/tmp",
  234. workspaceRoot: "/tmp",
  235. },
  236. );
  237. expect(output).toMatchObject({
  238. task_id: "shell_123",
  239. task_type: "local_bash",
  240. command: "npm run dev",
  241. });
  242. });
  243. it("returns stable error codes for invalid task ids", async () => {
  244. await expect(
  245. taskStopToolEntry.handler(
  246. {},
  247. {
  248. abortSignal: new AbortController().signal,
  249. sessionId: "sess_task_stop_missing" as never,
  250. toolCallId: "tool_task_stop_missing",
  251. traceId: "trace_task_stop_missing" as never,
  252. workingDirectory: "/tmp",
  253. workspaceRoot: "/tmp",
  254. },
  255. ),
  256. ).rejects.toMatchObject({
  257. context: {
  258. code: 1,
  259. },
  260. });
  261. await expect(
  262. taskStopToolEntry.handler(
  263. { task_id: "" },
  264. {
  265. abortSignal: new AbortController().signal,
  266. sessionId: "sess_task_stop_empty" as never,
  267. toolCallId: "tool_task_stop_empty",
  268. traceId: "trace_task_stop_empty" as never,
  269. workingDirectory: "/tmp",
  270. workspaceRoot: "/tmp",
  271. },
  272. ),
  273. ).rejects.toMatchObject({
  274. context: {
  275. code: 1,
  276. },
  277. message: "Missing required parameter: task_id",
  278. });
  279. await expect(
  280. taskStopToolEntry.handler(
  281. { task_id: "done_task" },
  282. {
  283. abortSignal: new AbortController().signal,
  284. backgroundTaskControlPort: {
  285. async stopBackgroundTask(taskId) {
  286. return {
  287. ok: false,
  288. reason: "background_task_not_running",
  289. status: "completed",
  290. taskId,
  291. type: "local_agent",
  292. };
  293. },
  294. },
  295. sessionId: "sess_task_stop_done" as never,
  296. toolCallId: "tool_task_stop_done",
  297. traceId: "trace_task_stop_done" as never,
  298. workingDirectory: "/tmp",
  299. workspaceRoot: "/tmp",
  300. },
  301. ),
  302. ).rejects.toMatchObject({
  303. context: {
  304. code: 3,
  305. },
  306. });
  307. await expect(
  308. taskStopToolEntry.handler(
  309. { task_id: "missing_task" },
  310. {
  311. abortSignal: new AbortController().signal,
  312. backgroundTaskControlPort: {
  313. async stopBackgroundTask(taskId) {
  314. return {
  315. ok: false,
  316. reason: "background_task_not_found",
  317. taskId,
  318. };
  319. },
  320. },
  321. sessionId: "sess_task_stop_not_found" as never,
  322. toolCallId: "tool_task_stop_not_found",
  323. traceId: "trace_task_stop_not_found" as never,
  324. workingDirectory: "/tmp",
  325. workspaceRoot: "/tmp",
  326. },
  327. ),
  328. ).rejects.toMatchObject({
  329. context: {
  330. code: 1,
  331. reason: "background_task_not_found",
  332. },
  333. message:
  334. 'Invalid task ID "missing_task". This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.',
  335. });
  336. });
  337. it("reports unsupported stop targets separately from missing tasks", async () => {
  338. await expect(
  339. taskStopToolEntry.handler(
  340. { task_id: "workflow_bg" },
  341. {
  342. abortSignal: new AbortController().signal,
  343. backgroundTaskControlPort: {
  344. async stopBackgroundTask(taskId) {
  345. return {
  346. ok: false,
  347. reason: "background_task_cancel_not_supported",
  348. status: "running",
  349. taskId,
  350. type: "local_workflow",
  351. };
  352. },
  353. },
  354. sessionId: "sess_task_stop_unsupported" as never,
  355. toolCallId: "tool_task_stop_unsupported",
  356. traceId: "trace_task_stop_unsupported" as never,
  357. workingDirectory: "/tmp",
  358. workspaceRoot: "/tmp",
  359. },
  360. ),
  361. ).rejects.toMatchObject({
  362. context: {
  363. code: 1,
  364. reason: "background_task_cancel_not_supported",
  365. taskType: "local_workflow",
  366. },
  367. message: "Task workflow_bg cannot be stopped",
  368. });
  369. });
  370. });