submit-result-tool.test.ts 11 KB

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