cron-tool.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createToolRegistry, registerBuiltInTools } from "../src/tool/index.js";
  3. import {
  4. cronCreateHandler,
  5. cronCreateToolEntry,
  6. cronDeleteHandler,
  7. cronListHandler,
  8. cronPauseSelfHandler,
  9. cronPauseSelfToolEntry,
  10. cronUpdateHandler,
  11. cronUpdateToolEntry,
  12. } from "../src/tool/handlers/cron.js";
  13. import { CoreErrorType, type AutomationPort, type TraceId } from "@zcode/contracts";
  14. import type { ToolExecutionContext } from "../src/tool/types.js";
  15. import { createTestRuntimeModel } from "./test-runtime-model.js";
  16. function createContext(port?: AutomationPort): ToolExecutionContext {
  17. return {
  18. toolCallId: "tool-cron",
  19. traceId: "trace-cron" as TraceId,
  20. abortSignal: new AbortController().signal,
  21. automationPort: port,
  22. model: createTestRuntimeModel({
  23. generateText: async () => ({ finishReason: "stop", text: "" }),
  24. providerId: "zai-api",
  25. modelId: "GLM-5",
  26. }),
  27. workingDirectory: "/workspace",
  28. workspaceRoot: "/workspace",
  29. sessionId: "sess-cron" as never,
  30. };
  31. }
  32. const automation = {
  33. automationId: "automation-1",
  34. title: "daily report",
  35. cronExpr: "0 9 * * *",
  36. prompt: "write daily report",
  37. enabled: true,
  38. lifecycleStatus: "active" as const,
  39. nextRunAt: 1_700_000_000_000,
  40. runCount: 0,
  41. recurring: true,
  42. };
  43. describe("cron tools", () => {
  44. it("CronCreate 提醒模型在标题中保留用户的时间规则", () => {
  45. expect(cronCreateToolEntry.metadata.modelInstructions).toEqual(
  46. expect.arrayContaining([
  47. expect.stringContaining("preserve the user's natural-language schedule phrase"),
  48. ]),
  49. );
  50. });
  51. it("CronCreate 向模型说明本地时间、一次性和持久化语义", () => {
  52. expect(cronCreateToolEntry.metadata.description).toContain("persistent");
  53. expect(cronCreateToolEntry.metadata.description).toContain("must never ask the run to create");
  54. expect(cronCreateToolEntry.metadata.modelInstructions).toEqual(
  55. expect.arrayContaining([
  56. expect.stringContaining("Do not convert to UTC"),
  57. expect.stringContaining("delayMinutes=3"),
  58. // 相对延迟必须覆盖小时/中文表述并换算成分钟,避免模型只认“in N minutes”。
  59. expect.stringContaining("delayMinutes=120"),
  60. // 根因守卫:pin 绝对 cron 的指令必须显式声明相对一次性改走 delayMinutes,
  61. // 否则“一次性提醒就 pin 月日时分”会覆盖相对延迟规则,模型自算出会滚到下一年的固定日历 cron。
  62. expect.stringContaining("must use delayMinutes"),
  63. expect.stringContaining("recurring=false"),
  64. expect.stringContaining("maxRuns=N"),
  65. expect.stringContaining("not session-only or auto-deleted"),
  66. expect.stringContaining("without adding jitter"),
  67. expect.stringContaining("Never ask the scheduled run to create"),
  68. // 停止条件必须写进 prompt,执行轮才能在条件满足时调用 CronPauseSelf 自暂停。
  69. expect.stringContaining("CronPauseSelf"),
  70. ]),
  71. );
  72. });
  73. it("registerBuiltInTools:只有注入 automation port 时才暴露 Cron 工具", () => {
  74. const withoutPort = createToolRegistry();
  75. registerBuiltInTools(withoutPort);
  76. expect(withoutPort.has("CronCreate")).toBe(false);
  77. expect(withoutPort.has("CronList")).toBe(false);
  78. expect(withoutPort.has("CronUpdate")).toBe(false);
  79. expect(withoutPort.has("CronDelete")).toBe(false);
  80. expect(withoutPort.has("CronPauseSelf")).toBe(false);
  81. const withPort = createToolRegistry();
  82. registerBuiltInTools(withPort, { includeAutomation: true });
  83. expect(withPort.has("CronCreate")).toBe(true);
  84. expect(withPort.has("CronList")).toBe(true);
  85. expect(withPort.has("CronUpdate")).toBe(true);
  86. expect(withPort.has("CronDelete")).toBe(true);
  87. expect(withPort.has("CronPauseSelf")).toBe(true);
  88. });
  89. it("CronCreate:通过 automationPort 创建当前 workspace 的定时任务", async () => {
  90. const port: AutomationPort = {
  91. create: vi.fn(async () => automation),
  92. list: vi.fn(),
  93. update: vi.fn(),
  94. delete: vi.fn(),
  95. pause: vi.fn(),
  96. };
  97. const result = await cronCreateHandler(
  98. {
  99. cron: "0 9 * * *",
  100. delayMinutes: null,
  101. prompt: "write daily report",
  102. title: "daily report",
  103. },
  104. createContext(port),
  105. );
  106. expect(port.create).toHaveBeenCalledWith(
  107. {
  108. cron: "0 9 * * *",
  109. delayMinutes: null,
  110. prompt: "write daily report",
  111. title: "daily report",
  112. },
  113. {
  114. model: "zai-api/GLM-5",
  115. sessionId: "sess-cron",
  116. },
  117. );
  118. expect(result).toMatchObject({
  119. automation: {
  120. automationId: "automation-1",
  121. cronExpr: "0 9 * * *",
  122. },
  123. });
  124. });
  125. it("CronCreate 透传 interval carrier,并在结果中保留权威 scheduleRule", async () => {
  126. const intervalAutomation = {
  127. ...automation,
  128. cronExpr: "49 * * * *",
  129. title: "每31小时的第49分提醒",
  130. scheduleRule: {
  131. unit: "hourly" as const,
  132. interval: 31,
  133. hour: 0,
  134. minute: 49,
  135. anchorAt: 1_700_000_000_000,
  136. },
  137. };
  138. const port: AutomationPort = {
  139. create: vi.fn(async () => intervalAutomation),
  140. list: vi.fn(async () => [intervalAutomation]),
  141. update: vi.fn(async () => intervalAutomation),
  142. delete: vi.fn(),
  143. pause: vi.fn(),
  144. };
  145. const created = await cronCreateHandler(
  146. {
  147. cron: "49 * * * *",
  148. prompt: "提醒我",
  149. title: "每31小时的第49分提醒",
  150. intervalUnit: "hourly",
  151. interval: 31,
  152. },
  153. createContext(port),
  154. );
  155. const updated = await cronUpdateHandler(
  156. {
  157. id: "automation-1",
  158. title: "每200年提醒",
  159. cron: "0 9 15 6 *",
  160. intervalUnit: "yearly",
  161. interval: 200,
  162. },
  163. createContext(port),
  164. );
  165. const listed = await cronListHandler({}, createContext(port));
  166. expect(port.create).toHaveBeenCalledWith(
  167. expect.objectContaining({ intervalUnit: "hourly", interval: 31 }),
  168. expect.anything(),
  169. );
  170. expect(port.update).toHaveBeenCalledWith(
  171. expect.objectContaining({ intervalUnit: "yearly", interval: 200 }),
  172. );
  173. for (const result of [created.automation, updated.automation, listed.automations[0]]) {
  174. expect(result).toMatchObject({
  175. scheduleRule: { unit: "hourly", interval: 31, minute: 49 },
  176. });
  177. }
  178. });
  179. it("CronUpdate:原地更新当前 workspace 的同一个定时任务", async () => {
  180. const updatedAutomation = {
  181. ...automation,
  182. title: "updated report",
  183. maxRuns: undefined,
  184. };
  185. const port: AutomationPort = {
  186. create: vi.fn(),
  187. list: vi.fn(),
  188. update: vi.fn(async () => updatedAutomation),
  189. delete: vi.fn(),
  190. pause: vi.fn(),
  191. };
  192. const result = await cronUpdateHandler(
  193. {
  194. id: "automation-1",
  195. title: "updated report",
  196. recurring: true,
  197. maxRuns: null,
  198. },
  199. createContext(port),
  200. );
  201. expect(port.update).toHaveBeenCalledWith({
  202. id: "automation-1",
  203. title: "updated report",
  204. recurring: true,
  205. maxRuns: null,
  206. });
  207. expect(result).toMatchObject({
  208. automation: {
  209. automationId: "automation-1",
  210. title: "updated report",
  211. },
  212. });
  213. expect(cronUpdateToolEntry.metadata.modelInstructions).toEqual(
  214. expect.arrayContaining([
  215. expect.stringContaining("CronList first"),
  216. expect.stringContaining("Always pass title"),
  217. expect.stringContaining("every 5 minutes to every 6 minutes"),
  218. expect.stringContaining("Do not simulate an update"),
  219. expect.stringContaining("brief confirmation"),
  220. expect.stringContaining("fenced code block"),
  221. expect.stringContaining("updated automation card"),
  222. ]),
  223. );
  224. });
  225. it("CronList / CronDelete:通过 automationPort 管理当前 workspace 定时任务", async () => {
  226. const port: AutomationPort = {
  227. create: vi.fn(),
  228. list: vi.fn(async () => [automation]),
  229. update: vi.fn(),
  230. delete: vi.fn(async () => true),
  231. pause: vi.fn(),
  232. };
  233. await expect(cronListHandler({}, createContext(port))).resolves.toEqual({
  234. automations: [automation],
  235. });
  236. await expect(
  237. cronDeleteHandler({ id: "automation-1" }, createContext(port)),
  238. ).resolves.toMatchObject({ deleted: true, id: "automation-1" });
  239. expect(port.delete).toHaveBeenCalledWith({ id: "automation-1" });
  240. });
  241. it("CronDelete:删除不到任务时返回失败结果,避免模型误判为已删除", async () => {
  242. const port: AutomationPort = {
  243. create: vi.fn(),
  244. list: vi.fn(),
  245. update: vi.fn(),
  246. delete: vi.fn(async () => false),
  247. pause: vi.fn(),
  248. };
  249. await expect(cronDeleteHandler({ id: "stale-id" }, createContext(port))).resolves.toEqual({
  250. deleted: false,
  251. id: "stale-id",
  252. message: "Automation stale-id was not found in the current workspace.",
  253. });
  254. });
  255. it("automation turn 即使绕过 provider denylist 也拒绝三个写工具", async () => {
  256. const port: AutomationPort = {
  257. create: vi.fn(async () => automation),
  258. list: vi.fn(async () => [automation]),
  259. update: vi.fn(async () => automation),
  260. delete: vi.fn(async () => true),
  261. pause: vi.fn(),
  262. };
  263. const context = { ...createContext(port), automationTurn: true };
  264. const mutations = [
  265. () =>
  266. cronCreateHandler(
  267. {
  268. cron: "0 9 * * *",
  269. delayMinutes: null,
  270. prompt: "write daily report",
  271. title: "daily report",
  272. },
  273. context,
  274. ),
  275. () => cronUpdateHandler({ id: "automation-1", title: "updated", prompt: "updated" }, context),
  276. () => cronDeleteHandler({ id: "automation-1" }, context),
  277. ];
  278. for (const mutation of mutations) {
  279. await expect(mutation()).rejects.toMatchObject({ type: CoreErrorType.PermissionDenied });
  280. }
  281. expect(port.create).not.toHaveBeenCalled();
  282. expect(port.update).not.toHaveBeenCalled();
  283. expect(port.delete).not.toHaveBeenCalled();
  284. await expect(cronListHandler({}, context)).resolves.toEqual({ automations: [automation] });
  285. });
  286. it("CronPauseSelf:只暂停执行器注入的本轮 automationId,不接受模型输入", async () => {
  287. const port: AutomationPort = {
  288. create: vi.fn(),
  289. list: vi.fn(),
  290. update: vi.fn(),
  291. delete: vi.fn(),
  292. pause: vi.fn(async () => true),
  293. };
  294. const context = { ...createContext(port), automationTurn: true, automationId: "automation-1" };
  295. await expect(cronPauseSelfHandler({}, context)).resolves.toEqual({
  296. paused: true,
  297. id: "automation-1",
  298. message:
  299. "Paused automation automation-1. It will not run on schedule until the user resumes it.",
  300. });
  301. expect(port.pause).toHaveBeenCalledWith({ id: "automation-1" });
  302. // 输入 schema 严格为空对象:模型不能通过 id 指定别的任务。
  303. await expect(cronPauseSelfHandler({ id: "automation-2" }, context)).rejects.toThrow();
  304. expect(port.pause).toHaveBeenCalledTimes(1);
  305. });
  306. it("CronPauseSelf:任务已不是 active 时返回 paused=false 的明确结果", async () => {
  307. const port: AutomationPort = {
  308. create: vi.fn(),
  309. list: vi.fn(),
  310. update: vi.fn(),
  311. delete: vi.fn(),
  312. pause: vi.fn(async () => false),
  313. };
  314. const context = { ...createContext(port), automationTurn: true, automationId: "automation-1" };
  315. await expect(cronPauseSelfHandler({}, context)).resolves.toEqual({
  316. paused: false,
  317. id: "automation-1",
  318. message:
  319. "Automation automation-1 is not active (already paused, completed, failed, or deleted), so nothing changed.",
  320. });
  321. });
  322. it("CronPauseSelf:缺少本轮 automationId 时 PermissionDenied 且不调用端口", async () => {
  323. const port: AutomationPort = {
  324. create: vi.fn(),
  325. list: vi.fn(),
  326. update: vi.fn(),
  327. delete: vi.fn(),
  328. pause: vi.fn(async () => true),
  329. };
  330. // 普通用户轮、只有 denylist/queryId 兜底信号的轮都没有可暂停目标。
  331. for (const context of [
  332. createContext(port),
  333. { ...createContext(port), automationTurn: true },
  334. { ...createContext(port), automationTurn: true, automationId: " " },
  335. ]) {
  336. await expect(cronPauseSelfHandler({}, context)).rejects.toMatchObject({
  337. type: CoreErrorType.PermissionDenied,
  338. });
  339. }
  340. expect(port.pause).not.toHaveBeenCalled();
  341. });
  342. it("CronPauseSelf:工具契约为低风险、无需审批的 deferred 工作区副作用", () => {
  343. expect(cronPauseSelfToolEntry.metadata).toMatchObject({
  344. name: "CronPauseSelf",
  345. shouldDefer: true,
  346. readOnly: false,
  347. destructive: false,
  348. concurrentSafe: false,
  349. sideEffectScope: "workspace",
  350. riskLevel: "low",
  351. needsApproval: false,
  352. });
  353. expect(cronPauseSelfToolEntry.metadata.searchHint).toBeTruthy();
  354. expect(cronPauseSelfToolEntry.permission).toMatchObject({
  355. permission: "automation.pause",
  356. needsApproval: false,
  357. });
  358. });
  359. });