off-peak-tool.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { describe, expect, it, vi } from "vitest";
  2. import { getTurnTools } from "../src/runtime/methods/turn-tool-visibility.js";
  3. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  4. import { createToolRegistry, registerBuiltInTools } from "../src/tool/index.js";
  5. import {
  6. offPeakCreateHandler,
  7. offPeakCreateToolEntry,
  8. offPeakListHandler,
  9. } from "../src/tool/handlers/off-peak.js";
  10. import {
  11. OFF_PEAK_MUTATION_TOOL_NAMES,
  12. isOffPeakCreateRestrictedTurn,
  13. type RegularTurnLoopState,
  14. } from "../src/runtime/methods/turn-loop-state.js";
  15. import { sendMessageToolEntry } from "../src/tool/handlers/send-message.js";
  16. import { workflowToolEntry } from "../src/tool/handlers/workflow.js";
  17. import { CoreErrorType, type OffPeakPort, type TraceId } from "@zcode/contracts";
  18. import type { ToolExecutionContext } from "../src/tool/types.js";
  19. function createContext(port?: OffPeakPort): ToolExecutionContext {
  20. return {
  21. toolCallId: "tool-offpeak",
  22. traceId: "trace-offpeak" as TraceId,
  23. abortSignal: new AbortController().signal,
  24. offPeakPort: port,
  25. workingDirectory: "/workspace",
  26. workspaceRoot: "/workspace",
  27. sessionId: "sess-offpeak" as never,
  28. };
  29. }
  30. const task = {
  31. offPeakTaskId: "offpeak-1",
  32. title: "重构 utils",
  33. status: "queued" as const,
  34. queuePosition: 3,
  35. createdAt: 1_700_000_000_000,
  36. };
  37. function createPort(overrides?: Partial<OffPeakPort>): OffPeakPort {
  38. return {
  39. create: vi.fn(async () => ({ ok: true as const, task })),
  40. list: vi.fn(async () => [task]),
  41. ...overrides,
  42. };
  43. }
  44. describe("off-peak tools", () => {
  45. it("OffPeakCreate 向模型说明闲时语义、与 CronCreate 的分工和禁止递归", () => {
  46. expect(offPeakCreateToolEntry.metadata.description).toContain("unattended");
  47. expect(offPeakCreateToolEntry.metadata.description).toContain("THIS session");
  48. expect(offPeakCreateToolEntry.metadata.description).not.toContain("fresh session");
  49. expect(offPeakCreateToolEntry.metadata.modelInstructions.join("\n")).not.toMatch(
  50. /NEW session|self-contained/,
  51. );
  52. expect(offPeakCreateToolEntry.metadata.description).toContain("no guaranteed start time");
  53. expect(offPeakCreateToolEntry.metadata.description).toContain(
  54. "must never ask the run to create",
  55. );
  56. expect(offPeakCreateToolEntry.metadata.modelInstructions).toEqual(
  57. expect.arrayContaining([
  58. expect.stringContaining("Choose CronCreate instead"),
  59. // D50:绑定会话执行,文案不得再宣称新会话/自包含(机审 CR-01)。
  60. expect.stringContaining("continues THIS conversation"),
  61. expect.stringContaining("full-automatic mode"),
  62. expect.stringContaining("Never call OffPeakCreate from within an idle-time task run"),
  63. ]),
  64. );
  65. // D49-7:创建消耗取号额度,必须走审批门(cron 同款)。
  66. expect(offPeakCreateToolEntry.metadata.needsApproval).toBe(true);
  67. });
  68. it("registerBuiltInTools:只有 includeOffPeak 时才暴露 OffPeak 工具(与 automation 门独立)", () => {
  69. const withoutFlag = createToolRegistry();
  70. registerBuiltInTools(withoutFlag, { includeAutomation: true });
  71. expect(withoutFlag.has("OffPeakCreate")).toBe(false);
  72. expect(withoutFlag.has("OffPeakList")).toBe(false);
  73. const withFlag = createToolRegistry();
  74. registerBuiltInTools(withFlag, { includeOffPeak: true });
  75. expect(withFlag.has("OffPeakCreate")).toBe(true);
  76. expect(withFlag.has("OffPeakList")).toBe(true);
  77. expect(withFlag.has("CronCreate")).toBe(false);
  78. });
  79. it("OffPeakCreate:透传可选参数并只携带 sessionId 归因上下文", async () => {
  80. const port = createPort();
  81. const result = await offPeakCreateHandler(
  82. {
  83. title: "重构 utils",
  84. prompt: "Refactor the utils directory and keep tests green.",
  85. permissionMode: "build",
  86. model: "GLM-5.2",
  87. thoughtLevel: "high",
  88. },
  89. createContext(port),
  90. );
  91. expect(port.create).toHaveBeenCalledWith(
  92. {
  93. title: "重构 utils",
  94. prompt: "Refactor the utils directory and keep tests green.",
  95. permissionMode: "build",
  96. model: "GLM-5.2",
  97. thoughtLevel: "high",
  98. },
  99. { sessionId: "sess-offpeak" },
  100. );
  101. expect(result).toMatchObject({
  102. task: { offPeakTaskId: "offpeak-1", queuePosition: 3 },
  103. message: expect.stringContaining("#3 in queue"),
  104. });
  105. });
  106. it("闲时派发轮拒绝 OffPeakCreate,但 OffPeakList 只读保留(D49-2)", async () => {
  107. const port = createPort();
  108. const context = { ...createContext(port), offPeakTurn: true };
  109. await expect(offPeakCreateHandler({ title: "t", prompt: "p" }, context)).rejects.toMatchObject({
  110. type: CoreErrorType.PermissionDenied,
  111. });
  112. expect(port.create).not.toHaveBeenCalled();
  113. await expect(offPeakListHandler({}, context)).resolves.toEqual({ tasks: [task] });
  114. });
  115. it("automation 派发轮放行 OffPeakCreate(D49-3 组合玩法,勿照抄 cron 的防御方向)", async () => {
  116. const port = createPort();
  117. const context = { ...createContext(port), automationTurn: true };
  118. await expect(
  119. offPeakCreateHandler({ title: "定时派生", prompt: "run nightly digest" }, context),
  120. ).resolves.toMatchObject({ task: { offPeakTaskId: "offpeak-1" } });
  121. expect(port.create).toHaveBeenCalledTimes(1);
  122. });
  123. it("ok:false 判别联合按分类翻译为稳定错误,分类进入错误上下文", async () => {
  124. const port = createPort({
  125. create: vi.fn(async () => ({
  126. ok: false as const,
  127. failureStage: "ticket_request" as const,
  128. errorCategory: "quota_3103" as const,
  129. errorCode: "3103",
  130. })),
  131. });
  132. await expect(
  133. offPeakCreateHandler({ title: "t", prompt: "p" }, createContext(port)),
  134. ).rejects.toMatchObject({
  135. type: CoreErrorType.ToolExecutionFailed,
  136. recoverable: false,
  137. context: expect.objectContaining({ errorCategory: "quota_3103", errorCode: "3103" }),
  138. });
  139. });
  140. it("缺少 offPeakPort 时报 ConfigurationError", async () => {
  141. await expect(
  142. offPeakCreateHandler({ title: "t", prompt: "p" }, createContext()),
  143. ).rejects.toMatchObject({ type: CoreErrorType.ConfigurationError });
  144. await expect(offPeakListHandler({}, createContext())).rejects.toMatchObject({
  145. type: CoreErrorType.ConfigurationError,
  146. });
  147. });
  148. });
  149. describe("闲时轮拒绝 SendMessage / Workflow(D52,ZCT-2099408932463325184)", () => {
  150. const sendMessageInput = { to: "agent_1", summary: "s", message: "continue" };
  151. const workflowInput = { scriptPath: "review.workflow.js" };
  152. it("denylist 常量同时覆盖 OffPeakCreate、SendMessage、Workflow,且哨兵仍是 OffPeakCreate", () => {
  153. expect([...OFF_PEAK_MUTATION_TOOL_NAMES]).toEqual(["OffPeakCreate", "SendMessage", "Workflow"]);
  154. expect(OFF_PEAK_MUTATION_TOOL_NAMES[0]).toBe("OffPeakCreate");
  155. });
  156. it("SendMessage 在闲时轮抛 PermissionDenied(recoverable,提示改用前台 Agent),不触达端口", async () => {
  157. const sendMessage = vi.fn();
  158. const context = {
  159. ...createContext(),
  160. offPeakTurn: true,
  161. subagentPort: { sendMessage } as never,
  162. };
  163. await expect(sendMessageToolEntry.handler(sendMessageInput, context)).rejects.toMatchObject({
  164. type: CoreErrorType.PermissionDenied,
  165. recoverable: true,
  166. message: expect.stringContaining("Spawn a new foreground Agent"),
  167. });
  168. expect(sendMessage).not.toHaveBeenCalled();
  169. });
  170. it("Workflow 在闲时轮抛 PermissionDenied,不触达 WorkflowPort", async () => {
  171. const start = vi.fn();
  172. const context = {
  173. ...createContext(),
  174. offPeakTurn: true,
  175. workflowPort: { start } as never,
  176. };
  177. await expect(workflowToolEntry.handler(workflowInput, context)).rejects.toMatchObject({
  178. type: CoreErrorType.PermissionDenied,
  179. recoverable: true,
  180. });
  181. expect(start).not.toHaveBeenCalled();
  182. });
  183. it("普通轮与 automation 轮不受影响(D49-3 方向:cron 轮照旧放行)", async () => {
  184. const sendMessage = vi.fn(async () => ({ status: "success", messageId: "m1" }));
  185. const start = vi.fn(async () => ({ status: "backgrounded", runId: "wf_1", response: "ok" }));
  186. for (const extra of [{}, { automationTurn: true }]) {
  187. const context = {
  188. ...createContext(),
  189. ...extra,
  190. subagentPort: { sendMessage } as never,
  191. workflowPort: { start } as never,
  192. };
  193. await expect(sendMessageToolEntry.handler(sendMessageInput, context)).resolves.toBeDefined();
  194. await expect(workflowToolEntry.handler(workflowInput, context)).resolves.toBeDefined();
  195. }
  196. expect(sendMessage).toHaveBeenCalledTimes(2);
  197. expect(start).toHaveBeenCalledTimes(2);
  198. });
  199. });
  200. describe("isOffPeakCreateRestrictedTurn", () => {
  201. function stateOf(partial: {
  202. offPeakTaskId?: string;
  203. automationId?: string;
  204. queryId?: string;
  205. toolDisallowlist?: readonly string[];
  206. }): RegularTurnLoopState {
  207. return {
  208. ...(partial.offPeakTaskId ? { offPeakTaskId: partial.offPeakTaskId } : {}),
  209. ...(partial.automationId ? { automationId: partial.automationId } : {}),
  210. toolDisallowlist: partial.toolDisallowlist,
  211. turnTraceContext: { queryId: partial.queryId },
  212. } as unknown as RegularTurnLoopState;
  213. }
  214. it("显式 offPeakTaskId 是主信号", () => {
  215. const state = stateOf({ offPeakTaskId: "offpeak-1" });
  216. expect(isOffPeakCreateRestrictedTurn(state)).toBe(true);
  217. const tools = ["OffPeakCreate", "OffPeakList", "Agent"].map((name) => ({ name }));
  218. const runtime = { getTools: () => tools } as unknown as AgentRuntimeInternal;
  219. expect(getTurnTools(runtime, state).map((tool) => tool.name)).toEqual(["OffPeakList", "Agent"]);
  220. });
  221. it("resume 段 queryId 前缀是兜底信号(首段 traceId 无固定前缀)", () => {
  222. expect(isOffPeakCreateRestrictedTurn(stateOf({ queryId: "offpeak-1:resume:abc" }))).toBe(true);
  223. });
  224. it("turn denylist 含 OffPeakCreate 时同样限制(busy 合并路径)", () => {
  225. expect(isOffPeakCreateRestrictedTurn(stateOf({ toolDisallowlist: ["OffPeakCreate"] }))).toBe(
  226. true,
  227. );
  228. });
  229. it("automation 轮不触发闲时限制(D49-3 反向断言)", () => {
  230. expect(
  231. isOffPeakCreateRestrictedTurn(
  232. stateOf({
  233. automationId: "automation-1",
  234. queryId: "automation-1:run:abc",
  235. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  236. }),
  237. ),
  238. ).toBe(false);
  239. });
  240. it("普通用户轮不受限", () => {
  241. expect(isOffPeakCreateRestrictedTurn(stateOf({ queryId: "user-input-1" }))).toBe(false);
  242. });
  243. });