submit-result-tool.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import {
  2. CoreErrorType,
  3. SUBMIT_RESULT_TOOL_NAME,
  4. createRootTraceContext,
  5. createSessionId,
  6. createToolCallId,
  7. createTurnId,
  8. isCoreError,
  9. type SubmitResultRequest,
  10. type WorkflowSubmitPort,
  11. } from "@zcode/contracts";
  12. import { describe, expect, it } from "vitest";
  13. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  14. import { createToolExecutor } from "../src/tool/executor.js";
  15. import { withTerminalToolTurnStop } from "../src/tool/executor/turn-control.js";
  16. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  17. import {
  18. createSubmitResultToolEntry,
  19. submitResultToolEntry,
  20. } from "../src/tool/handlers/submit-result.js";
  21. import { createToolRegistry } from "../src/tool/registry.js";
  22. import type { ToolEntry, ToolExecutionContext, ToolExecutionResult } from "../src/tool/types.js";
  23. function acceptPort(): WorkflowSubmitPort {
  24. return { respond: async () => ({ accept: true }) };
  25. }
  26. function toolContext(overrides: Partial<ToolExecutionContext> = {}): ToolExecutionContext {
  27. return {
  28. abortSignal: new AbortController().signal,
  29. sessionId: "sess_submit_result" as never,
  30. toolCallId: "tool_submit_result",
  31. traceId: "trace_submit_result" as never,
  32. workingDirectory: "/tmp",
  33. workspaceRoot: "/tmp",
  34. ...overrides,
  35. };
  36. }
  37. function submitExecutor(port: WorkflowSubmitPort | undefined) {
  38. const sessionId = createSessionId("submit-result-exec");
  39. const turnId = createTurnId("submit-result-exec");
  40. const traceContext = createRootTraceContext({ sessionId, turnId });
  41. const registry = createToolRegistry();
  42. registry.register(submitResultToolEntry);
  43. const executor = createToolExecutor({
  44. emitEvent: async () => undefined,
  45. permissionService: new PermissionService(defaultPermissionConfig),
  46. registry,
  47. workflowSubmitPort: port,
  48. sessionId,
  49. turnId,
  50. traceContext,
  51. });
  52. return { executor, traceContext };
  53. }
  54. describe("submit_result handler", () => {
  55. it("throws a non-recoverable ConfigurationError when no submit port is configured", async () => {
  56. let caught: unknown;
  57. try {
  58. await submitResultToolEntry.handler({ result: { ok: true } }, toolContext());
  59. } catch (error) {
  60. caught = error;
  61. }
  62. expect(isCoreError(caught)).toBe(true);
  63. if (!isCoreError(caught)) throw new Error("expected a core error");
  64. expect(caught.type).toBe(CoreErrorType.ConfigurationError);
  65. expect(caught.recoverable).toBe(false);
  66. });
  67. it("forwards toolCallId, result and trace to the port and returns accepted on accept", async () => {
  68. const seen: SubmitResultRequest[] = [];
  69. const port: WorkflowSubmitPort = {
  70. respond: async (request) => {
  71. seen.push(request);
  72. return { accept: true };
  73. },
  74. };
  75. const result = { title: "done", items: [1, 2] };
  76. const output = await submitResultToolEntry.handler(
  77. { result },
  78. toolContext({ workflowSubmitPort: port, toolCallId: "call_42" }),
  79. );
  80. expect(output).toEqual({ status: "accepted" });
  81. expect(seen).toHaveLength(1);
  82. expect(seen[0]?.toolCallId).toBe("call_42");
  83. expect(seen[0]?.result).toEqual(result);
  84. expect(seen[0]?.trace.traceId).toBe("trace_submit_result");
  85. });
  86. it("returns a tool-handler failure carrying the violation list on reject", async () => {
  87. const port: WorkflowSubmitPort = {
  88. respond: async () => ({
  89. accept: false,
  90. violations: [
  91. { path: "$.title", expected: "string", got: "number" },
  92. { path: "$.items", expected: "array", got: "undefined" },
  93. ],
  94. }),
  95. };
  96. const output = await submitResultToolEntry.handler(
  97. { result: { title: 1 } },
  98. toolContext({ workflowSubmitPort: port }),
  99. );
  100. expect(output).toMatchObject({ result: false, errorCode: 1 });
  101. const message = (output as { message: string }).message;
  102. expect(message).toContain("$.title: expected string, got number");
  103. expect(message).toContain("$.items: expected array, got undefined");
  104. });
  105. });
  106. describe("submit_result executor surface", () => {
  107. it("stops the turn after an accepted submit via subagent_terminal turn control", async () => {
  108. const { executor, traceContext } = submitExecutor(acceptPort());
  109. const result = await executor.execute(
  110. {
  111. id: createToolCallId("submit-accept"),
  112. input: { result: { ok: true } },
  113. name: SUBMIT_RESULT_TOOL_NAME,
  114. },
  115. { traceContext },
  116. );
  117. expect(result.success).toBe(true);
  118. expect(result.turnControl).toEqual({
  119. reason: "subagent_terminal",
  120. stopTurnAfterResult: true,
  121. });
  122. // subagent_terminal 走 turn-tools 的默认 stop(break)分支,而不是 automation_create_limit
  123. // 的纯文本续写分支——它只对 automation_create_limit 特判。
  124. expect(result.turnControl?.reason).not.toBe("automation_create_limit");
  125. });
  126. it("does not stop the turn on reject and surfaces violations as the error tool_result", async () => {
  127. const port: WorkflowSubmitPort = {
  128. respond: async () => ({
  129. accept: false,
  130. violations: [{ path: "$.title", expected: "string", got: "number" }],
  131. }),
  132. };
  133. const { executor, traceContext } = submitExecutor(port);
  134. const result = await executor.execute(
  135. {
  136. id: createToolCallId("submit-reject"),
  137. input: { result: { title: 1 } },
  138. name: SUBMIT_RESULT_TOOL_NAME,
  139. },
  140. { traceContext },
  141. );
  142. expect(result.success).toBe(false);
  143. expect(result.turnControl).toBeUndefined();
  144. expect(result.modelContent).toBe(
  145. "<tool_use_error>The submitted result does not match the required schema:\n" +
  146. "$.title: expected string, got number</tool_use_error>",
  147. );
  148. });
  149. it("fails with ConfigurationError through the executor when the port is absent", async () => {
  150. const { executor, traceContext } = submitExecutor(undefined);
  151. const result = await executor.execute(
  152. {
  153. id: createToolCallId("submit-no-port"),
  154. input: { result: {} },
  155. name: SUBMIT_RESULT_TOOL_NAME,
  156. },
  157. { traceContext },
  158. );
  159. expect(result.success).toBe(false);
  160. expect(result.turnControl).toBeUndefined();
  161. expect(result.error?.type).toBe(CoreErrorType.ConfigurationError);
  162. });
  163. });
  164. describe("submit_result registration gate", () => {
  165. it("registers submit_result only when includeSubmitResult is set", () => {
  166. const withPort = createToolRegistry();
  167. registerBuiltInTools(withPort, { includeSubmitResult: true });
  168. expect(withPort.has(SUBMIT_RESULT_TOOL_NAME)).toBe(true);
  169. const withoutPort = createToolRegistry();
  170. registerBuiltInTools(withoutPort, {});
  171. expect(withoutPort.has(SUBMIT_RESULT_TOOL_NAME)).toBe(false);
  172. });
  173. it("declares submit_result as a terminal-on-success tool via metadata", () => {
  174. expect(submitResultToolEntry.metadata.stopTurnOnSuccess).toBe(true);
  175. });
  176. });
  177. describe("withTerminalToolTurnStop", () => {
  178. const success = {
  179. toolCallId: "t",
  180. toolName: "any",
  181. success: true,
  182. output: null,
  183. } as ToolExecutionResult;
  184. function entryWith(stopTurnOnSuccess?: boolean): ToolEntry {
  185. return { metadata: { stopTurnOnSuccess } } as unknown as ToolEntry;
  186. }
  187. it("stops the turn on success only when the entry declares stopTurnOnSuccess", () => {
  188. expect(withTerminalToolTurnStop(success, { entry: entryWith(true) }).turnControl).toEqual({
  189. reason: "subagent_terminal",
  190. stopTurnAfterResult: true,
  191. });
  192. // 键入 metadata 声明而非工具名:未声明的工具永不因成功而终止 turn。
  193. expect(withTerminalToolTurnStop(success, { entry: entryWith(false) }).turnControl).toBeUndefined();
  194. expect(
  195. withTerminalToolTurnStop(success, { entry: entryWith(undefined) }).turnControl,
  196. ).toBeUndefined();
  197. });
  198. it("never stops a failed result even for a terminal tool", () => {
  199. const failed = { ...success, success: false } as ToolExecutionResult;
  200. expect(withTerminalToolTurnStop(failed, { entry: entryWith(true) }).turnControl).toBeUndefined();
  201. });
  202. });
  203. // typed 声明(docs/execution-engine.md「Typed asks and `submit_result`」):
  204. // 只有 provider 可见的声明与 strict 资格不同,其余逐字节相同。
  205. describe("submit_result typed entry", () => {
  206. const REVIEW = {
  207. type: "object",
  208. properties: { ok: { type: "boolean" }, notes: { type: "string" } },
  209. required: ["ok"],
  210. additionalProperties: false,
  211. };
  212. it("declares { result: schema } and strict eligibility, sharing everything else with the generic entry", () => {
  213. const typed = createSubmitResultToolEntry(REVIEW);
  214. expect(typed.metadata.name).toBe(SUBMIT_RESULT_TOOL_NAME);
  215. expect(typed.strict).toBe(true);
  216. expect(typed.inputSchema.required).toEqual(["result"]);
  217. expect(typed.inputSchema.additionalProperties).toBe(false);
  218. expect((typed.inputSchema.properties as Record<string, unknown>).result).toMatchObject(REVIEW);
  219. // 运行时 zod 校验、handler、权限、终止语义与通用条目相同。
  220. expect(typed.runtimeInputSchema).toBe(submitResultToolEntry.runtimeInputSchema);
  221. expect(typed.handler).toBe(submitResultToolEntry.handler);
  222. expect(typed.permission).toEqual(submitResultToolEntry.permission);
  223. expect(typed.metadata.stopTurnOnSuccess).toBe(true);
  224. expect(typed.metadata.concurrentSafe).toBe(false);
  225. // 通用条目不声明 strict:任意 JSON 的 result 在严格子集里表达不了,也不该被约束。
  226. expect(submitResultToolEntry.strict).toBeUndefined();
  227. expect(
  228. (submitResultToolEntry.inputSchema.properties as Record<string, Record<string, unknown>>)
  229. .result.type,
  230. ).toBeUndefined();
  231. });
  232. it("registers the typed entry when registerBuiltInTools is given a submitResultSchema", () => {
  233. const registry = createToolRegistry();
  234. registerBuiltInTools(registry, { includeSubmitResult: true, submitResultSchema: REVIEW });
  235. const contract = registry.toContracts().find((tool) => tool.name === SUBMIT_RESULT_TOOL_NAME);
  236. expect(contract?.strict).toBe(true);
  237. expect((contract?.inputSchema.properties as Record<string, unknown>).result).toMatchObject(
  238. REVIEW,
  239. );
  240. });
  241. it("registers the generic entry (no strict) without a schema, and nothing without the gate", () => {
  242. const generic = createToolRegistry();
  243. registerBuiltInTools(generic, { includeSubmitResult: true });
  244. const contract = generic.toContracts().find((tool) => tool.name === SUBMIT_RESULT_TOOL_NAME);
  245. expect(contract).toBeDefined();
  246. expect(contract?.strict).toBeUndefined();
  247. // schema 在场但门没开:仍然不注册——端口才是门。
  248. const gated = createToolRegistry();
  249. registerBuiltInTools(gated, { submitResultSchema: REVIEW });
  250. expect(gated.has(SUBMIT_RESULT_TOOL_NAME)).toBe(false);
  251. });
  252. it("the typed entry still accepts any JSON at the executor boundary (per-ask shape is the engine's job)", async () => {
  253. const typed = createSubmitResultToolEntry(REVIEW);
  254. // 与 schema 不符的 payload 也照常交给端口:形状违规由引擎裁决并作为可修复的 tool_result 回来。
  255. const seen: unknown[] = [];
  256. const port: WorkflowSubmitPort = {
  257. respond: async (request) => {
  258. seen.push(request.result);
  259. return { accept: true };
  260. },
  261. };
  262. const output = await typed.handler(
  263. { result: { unrelated: 1 } },
  264. toolContext({ workflowSubmitPort: port }),
  265. );
  266. expect(output).toEqual({ status: "accepted" });
  267. expect(seen).toEqual([{ unrelated: 1 }]);
  268. });
  269. });