task-stop-tool.test.ts 11 KB

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