eval-workflow-snippet-tool.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import type {
  6. DynamicWorkflowSnippetEvalRequest,
  7. DynamicWorkflowSnippetEvalResult,
  8. DynamicWorkflowSnippetPort,
  9. EvalWorkflowSnippetOutput,
  10. } from "@zcode/contracts";
  11. import { evalWorkflowSnippetToolEntry } from "../src/tool/handlers/eval-workflow-snippet.js";
  12. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  13. import { createToolRegistry } from "../src/tool/registry.js";
  14. import type { ToolExecutionContext } from "../src/tool/types.js";
  15. /** 端口 fake:记录请求、按脚本回结果。编译与执行的真实链路在 bootstrap 的 service 测试里。 */
  16. function stubPort(result: DynamicWorkflowSnippetEvalResult): {
  17. port: DynamicWorkflowSnippetPort;
  18. requests: DynamicWorkflowSnippetEvalRequest[];
  19. } {
  20. const requests: DynamicWorkflowSnippetEvalRequest[] = [];
  21. return {
  22. requests,
  23. port: {
  24. async evalSnippet(request) {
  25. requests.push(request);
  26. return result;
  27. },
  28. },
  29. };
  30. }
  31. function makeContext(port?: DynamicWorkflowSnippetPort): ToolExecutionContext {
  32. return {
  33. ...(port === undefined ? {} : { dynamicWorkflowSnippetPort: port }),
  34. workingDirectory: "/tmp/snippet-test",
  35. traceId: "trace-1",
  36. sessionId: "sess_test",
  37. } as unknown as ToolExecutionContext;
  38. }
  39. async function run(input: unknown, context: ToolExecutionContext): Promise<EvalWorkflowSnippetOutput> {
  40. return (await evalWorkflowSnippetToolEntry.handler(input, context)) as EvalWorkflowSnippetOutput;
  41. }
  42. describe("EvalWorkflowSnippet tool", () => {
  43. it("is registered by default via registerBuiltInTools", () => {
  44. const registry = createToolRegistry();
  45. registerBuiltInTools(registry);
  46. expect(registry.has("EvalWorkflowSnippet")).toBe(true);
  47. });
  48. it("fails honestly when the port is absent (nothing pretends to execute)", async () => {
  49. const output = await run({ code: "return 1;" }, makeContext());
  50. expect(output.ok).toBe(false);
  51. expect(output.response).toContain("NOT executed");
  52. expect(output.response).toContain("not available");
  53. });
  54. it("passes code, session cwd and the default 60s timeout to the port", async () => {
  55. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  56. await run({ code: "return 1;" }, makeContext(port));
  57. expect(requests).toHaveLength(1);
  58. expect(requests[0]?.code).toBe("return 1;");
  59. expect(requests[0]?.cwd).toBe("/tmp/snippet-test");
  60. expect(requests[0]?.timeoutMs).toBe(60_000);
  61. });
  62. it("honours an explicit timeoutMs within schema bounds", async () => {
  63. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  64. await run({ code: "return 1;", timeoutMs: 600_000 }, makeContext(port));
  65. expect(requests[0]?.timeoutMs).toBe(600_000);
  66. });
  67. it("rejects timeoutMs beyond the 600s schema ceiling", async () => {
  68. const { port } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  69. await expect(run({ code: "return 1;", timeoutMs: 900_000 }, makeContext(port))).rejects.toThrow();
  70. });
  71. it("renders diagnostics with the NOT-executed note", async () => {
  72. const { port } = stubPort({
  73. kind: "diagnostics",
  74. diagnostics: [{ code: 2304, column: 14, line: 1, message: "Cannot find name 'agent'." }],
  75. });
  76. const output = await run({ code: `await agent("x")` }, makeContext(port));
  77. expect(output.ok).toBe(false);
  78. expect(output.diagnostics).toHaveLength(1);
  79. expect(output.response).toContain("L1:C14 Cannot find name 'agent'.");
  80. expect(output.response).toContain("NOT executed");
  81. });
  82. it("renders the artifact and logs on success", async () => {
  83. const { port } = stubPort({
  84. kind: "completed",
  85. artifact: { files: ["a.ts"], count: 1 },
  86. logs: ["saw 1"],
  87. logsTruncated: false,
  88. });
  89. const output = await run({ code: "return x;" }, makeContext(port));
  90. expect(output.ok).toBe(true);
  91. expect(output.response).toContain("Return value:");
  92. expect(output.response).toContain('"a.ts"');
  93. expect(output.response).toContain("- saw 1");
  94. expect(output.logs).toEqual(["saw 1"]);
  95. });
  96. it("says so when the snippet returned no value", async () => {
  97. const { port } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  98. const output = await run({ code: 'log("hi");' }, makeContext(port));
  99. expect(output.ok).toBe(true);
  100. expect(output.response).toContain("returned no value");
  101. });
  102. it("renders structured failures with the stable code, keeping logs", async () => {
  103. const { port } = stubPort({
  104. kind: "failed",
  105. error: { code: "WorldReadCapExceeded", message: "files.grep over cap" },
  106. logs: ["before the failure"],
  107. logsTruncated: true,
  108. });
  109. const output = await run({ code: "…" }, makeContext(port));
  110. expect(output.ok).toBe(false);
  111. expect(output.response).toContain("(WorldReadCapExceeded)");
  112. expect(output.response).toContain("- before the failure");
  113. expect(output.response).toContain("logs truncated");
  114. });
  115. });
  116. // docs/dynamic-workflow/launch.md「Script files」→「The `path` source」:片段的第二条来源。
  117. // 整个文件就是代码(不解析元数据块),诊断按文件行报。
  118. describe("EvalWorkflowSnippet — the `path` source", () => {
  119. const validate = (input: unknown) => evalWorkflowSnippetToolEntry.validateInput!(input, {});
  120. const resolve = async (input: unknown, cwd: string) =>
  121. await evalWorkflowSnippetToolEntry.resolveInput!(input, { workingDirectory: cwd });
  122. it("refuses a call giving both sources, and one giving neither", () => {
  123. expect(validate({ code: "return 1;", path: "a.ts" })).toMatchObject({ result: false });
  124. expect(validate({})).toMatchObject({ result: false });
  125. expect(validate({ code: "return 1;" })).toEqual({ result: true });
  126. expect(validate({ path: "a.ts" })).toEqual({ result: true });
  127. });
  128. it("reads the file whole as `code`, metadata block included", async () => {
  129. const cwd = mkdtempSync(join(tmpdir(), "dwf-snippet-path-"));
  130. try {
  131. // 恰好以起始标记开头的文件也整个是代码:片段没有保存定义那套语义。
  132. const source = '/* zcode-workflow\ndescription: not a workflow\n*/\nreturn 1;';
  133. writeFileSync(join(cwd, "snippet.ts"), source, "utf8");
  134. const resolution = await resolve({ path: "snippet.ts" }, cwd);
  135. expect(resolution).toMatchObject({ result: true });
  136. const input = (resolution as { input: Record<string, unknown> }).input;
  137. expect(input.code).toBe(source);
  138. expect(input.path).toBe(join(cwd, "snippet.ts"));
  139. } finally {
  140. rmSync(cwd, { force: true, recursive: true });
  141. }
  142. });
  143. it("names the file when it cannot be read", async () => {
  144. const cwd = mkdtempSync(join(tmpdir(), "dwf-snippet-path-"));
  145. try {
  146. const resolution = await resolve({ path: "missing.ts" }, cwd);
  147. expect(resolution).toMatchObject({ result: false });
  148. expect((resolution as { message: string }).message).toContain("missing.ts could not be read");
  149. } finally {
  150. rmSync(cwd, { force: true, recursive: true });
  151. }
  152. });
  153. it("prefixes diagnostics with the file when the snippet came from one", async () => {
  154. const { port } = stubPort({
  155. kind: "diagnostics",
  156. diagnostics: [{ code: 2304, column: 14, line: 1, message: "Cannot find name 'agent'." }],
  157. });
  158. const context = makeContext(port);
  159. const output = await run(
  160. { code: `await agent("x")`, path: join(context.workingDirectory, "snippet.ts") },
  161. context,
  162. );
  163. expect(output.response).toContain("snippet.ts:L1:C14 Cannot find name 'agent'.");
  164. });
  165. });
  166. describe("EvalWorkflowSnippet approval gate (world.run)", () => {
  167. const gate = (input: unknown) => evalWorkflowSnippetToolEntry.prepareApproval!(input);
  168. it("proceeds silently for a pure read snippet", () => {
  169. expect(gate({ code: `return await files.glob("*.ts");` })).toEqual({ gate: "proceed" });
  170. });
  171. it("asks when the snippet carries world.run commands", () => {
  172. expect(gate({ code: `const r = await world.run("lean", ["a.lean"]); return r.exitCode;` })).toEqual({
  173. gate: "ask",
  174. });
  175. });
  176. it("proceeds for invalid input and for snippets that do not compile", () => {
  177. // handler / 端口负责把这两种失败变成可读的诊断;打断用户批准一段编不过的代码没有意义。
  178. expect(gate({ notCode: true })).toEqual({ gate: "proceed" });
  179. expect(gate({ code: `await agent("x").ask("y");` })).toEqual({ gate: "proceed" });
  180. expect(gate({ code: `const c = "node"; await world.run(c, []);` })).toEqual({ gate: "proceed" });
  181. });
  182. it("stays a standard-permission tool: no alwaysAsk, no always-allow suppression", () => {
  183. // 2026-08-26 复议(docs/dynamic-workflow/authoring.md「EvalWorkflowSnippet」):alwaysAsk 只属于
  184. // CreateWorkflow——load-bearing 且昂贵。snippet 按标准模式 / 规则流程裁决。
  185. expect(evalWorkflowSnippetToolEntry.permission.alwaysAsk).toBeUndefined();
  186. expect(evalWorkflowSnippetToolEntry.permission.askOptions).toBeUndefined();
  187. });
  188. });