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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 {
  6. EVAL_WORKFLOW_SNIPPET_SOURCE_CONFLICT_ERROR,
  7. EVAL_WORKFLOW_SNIPPET_SOURCE_MISSING_ERROR,
  8. WORKFLOW_SOURCE_MISSING_HINT,
  9. EvalWorkflowSnippetInputJsonSchema,
  10. EvalWorkflowSnippetInputSchema,
  11. HookEventName,
  12. createRootTraceContext,
  13. createSessionId,
  14. createToolCallId,
  15. createTurnId,
  16. type DynamicWorkflowSnippetEvalRequest,
  17. type DynamicWorkflowSnippetEvalResult,
  18. type DynamicWorkflowSnippetPort,
  19. type EvalWorkflowSnippetOutput,
  20. } from "@zcode/contracts";
  21. import type { HookRunner } from "../src/hooks/index.js";
  22. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  23. import { createToolExecutor } from "../src/tool/executor.js";
  24. import { evalWorkflowSnippetToolEntry } from "../src/tool/handlers/eval-workflow-snippet.js";
  25. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  26. import { createToolRegistry } from "../src/tool/registry.js";
  27. import type { ToolExecutionContext } from "../src/tool/types.js";
  28. /** 端口 fake:记录请求、按脚本回结果。编译与执行的真实链路在 bootstrap 的 service 测试里。 */
  29. function stubPort(result: DynamicWorkflowSnippetEvalResult): {
  30. port: DynamicWorkflowSnippetPort;
  31. requests: DynamicWorkflowSnippetEvalRequest[];
  32. } {
  33. const requests: DynamicWorkflowSnippetEvalRequest[] = [];
  34. return {
  35. requests,
  36. port: {
  37. async evalSnippet(request) {
  38. requests.push(request);
  39. return result;
  40. },
  41. },
  42. };
  43. }
  44. function makeContext(port?: DynamicWorkflowSnippetPort): ToolExecutionContext {
  45. return {
  46. ...(port === undefined ? {} : { dynamicWorkflowSnippetPort: port }),
  47. workingDirectory: "/tmp/snippet-test",
  48. traceId: "trace-1",
  49. sessionId: "sess_test",
  50. } as unknown as ToolExecutionContext;
  51. }
  52. async function run(input: unknown, context: ToolExecutionContext): Promise<EvalWorkflowSnippetOutput> {
  53. return (await evalWorkflowSnippetToolEntry.handler(input, context)) as EvalWorkflowSnippetOutput;
  54. }
  55. describe("EvalWorkflowSnippet tool", () => {
  56. it("is registered by default via registerBuiltInTools", () => {
  57. const registry = createToolRegistry();
  58. registerBuiltInTools(registry);
  59. expect(registry.has("EvalWorkflowSnippet")).toBe(true);
  60. });
  61. it("fails honestly when the port is absent (nothing pretends to execute)", async () => {
  62. const output = await run({ code: "return 1;" }, makeContext());
  63. expect(output.ok).toBe(false);
  64. expect(output.response).toContain("NOT executed");
  65. expect(output.response).toContain("not available");
  66. });
  67. it("passes code, session cwd and the default 60s timeout to the port", async () => {
  68. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  69. await run({ code: "return 1;" }, makeContext(port));
  70. expect(requests).toHaveLength(1);
  71. expect(requests[0]?.code).toBe("return 1;");
  72. expect(requests[0]?.cwd).toBe("/tmp/snippet-test");
  73. expect(requests[0]?.timeoutMs).toBe(60_000);
  74. });
  75. it("honours an explicit timeoutMs within schema bounds", async () => {
  76. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  77. await run({ code: "return 1;", timeoutMs: 600_000 }, makeContext(port));
  78. expect(requests[0]?.timeoutMs).toBe(600_000);
  79. });
  80. it("rejects timeoutMs beyond the 600s schema ceiling", async () => {
  81. const { port } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  82. await expect(run({ code: "return 1;", timeoutMs: 900_000 }, makeContext(port))).rejects.toThrow();
  83. });
  84. it("renders diagnostics with the NOT-executed note", async () => {
  85. const { port } = stubPort({
  86. kind: "diagnostics",
  87. diagnostics: [{ code: 2304, column: 14, line: 1, message: "Cannot find name 'agent'." }],
  88. });
  89. const output = await run({ code: `await agent("x")` }, makeContext(port));
  90. expect(output.ok).toBe(false);
  91. expect(output.diagnostics).toHaveLength(1);
  92. expect(output.response).toContain("L1:C14 Cannot find name 'agent'.");
  93. expect(output.response).toContain("NOT executed");
  94. });
  95. it("renders the artifact and logs on success", async () => {
  96. const { port } = stubPort({
  97. kind: "completed",
  98. artifact: { files: ["a.ts"], count: 1 },
  99. logs: ["saw 1"],
  100. logsTruncated: false,
  101. });
  102. const output = await run({ code: "return x;" }, makeContext(port));
  103. expect(output.ok).toBe(true);
  104. expect(output.response).toContain("Return value:");
  105. expect(output.response).toContain('"a.ts"');
  106. expect(output.response).toContain("- saw 1");
  107. expect(output.logs).toEqual(["saw 1"]);
  108. });
  109. it("says so when the snippet returned no value", async () => {
  110. const { port } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  111. const output = await run({ code: 'log("hi");' }, makeContext(port));
  112. expect(output.ok).toBe(true);
  113. expect(output.response).toContain("returned no value");
  114. });
  115. it("renders structured failures with the stable code, keeping logs", async () => {
  116. const { port } = stubPort({
  117. kind: "failed",
  118. error: { code: "WorldReadCapExceeded", message: "files.grep over cap" },
  119. logs: ["before the failure"],
  120. logsTruncated: true,
  121. });
  122. const output = await run({ code: "…" }, makeContext(port));
  123. expect(output.ok).toBe(false);
  124. expect(output.response).toContain("(WorldReadCapExceeded)");
  125. expect(output.response).toContain("- before the failure");
  126. expect(output.response).toContain("logs truncated");
  127. });
  128. });
  129. // docs/dynamic-workflow/launch.md「Script files」→「The `path` source」:片段的第二条来源。
  130. // 整个文件就是代码(不解析元数据块),诊断按文件行报。
  131. describe("EvalWorkflowSnippet — the `path` source", () => {
  132. const validate = (input: unknown) => evalWorkflowSnippetToolEntry.validateInput!(input, {});
  133. const resolve = async (input: unknown, cwd: string) =>
  134. await evalWorkflowSnippetToolEntry.resolveInput!(input, { workingDirectory: cwd });
  135. it("refuses a call giving both sources, and one giving neither", () => {
  136. expect(validate({ code: "return 1;", path: "a.ts" })).toMatchObject({ result: false });
  137. expect(validate({})).toMatchObject({ result: false });
  138. expect(validate({ code: "return 1;" })).toEqual({ result: true });
  139. expect(validate({ path: "a.ts" })).toEqual({ result: true });
  140. });
  141. // 两种违规原因不同,文案也必须不同:「没给」多半是参数 JSON 没解析出来、被 adapter 恢复成 `{}`,
  142. // 写了 `code` 的模型读到「两个都给或都没给」只会原样重发同一个坏调用。
  143. it("tells both sources apart from none", () => {
  144. expect(validate({ code: "return 1;", path: "a.ts" })).toMatchObject({
  145. message: EVAL_WORKFLOW_SNIPPET_SOURCE_CONFLICT_ERROR,
  146. });
  147. for (const input of [{}, { timeoutMs: 5_000 }]) {
  148. expect(validate(input)).toMatchObject({
  149. message: EVAL_WORKFLOW_SNIPPET_SOURCE_MISSING_ERROR,
  150. });
  151. }
  152. });
  153. it("explains on a missing source that a call which does not parse arrives empty", () => {
  154. expect(EVAL_WORKFLOW_SNIPPET_SOURCE_MISSING_ERROR).toContain(WORKFLOW_SOURCE_MISSING_HINT);
  155. expect(WORKFLOW_SOURCE_MISSING_HINT).toContain("not valid JSON");
  156. expect(WORKFLOW_SOURCE_MISSING_HINT).toContain("`path`");
  157. expect(EVAL_WORKFLOW_SNIPPET_SOURCE_CONFLICT_ERROR).not.toContain("JSON");
  158. });
  159. it("reads the file whole as `code`, metadata block included", async () => {
  160. const cwd = mkdtempSync(join(tmpdir(), "dwf-snippet-path-"));
  161. try {
  162. // 恰好以起始标记开头的文件也整个是代码:片段没有保存定义那套语义。
  163. const source = '/* zcode-workflow\ndescription: not a workflow\n*/\nreturn 1;';
  164. writeFileSync(join(cwd, "snippet.ts"), source, "utf8");
  165. const resolution = await resolve({ path: "snippet.ts" }, cwd);
  166. expect(resolution).toMatchObject({ result: true });
  167. const input = (resolution as { input: Record<string, unknown> }).input;
  168. expect(input.code).toBe(source);
  169. expect(input.path).toBe(join(cwd, "snippet.ts"));
  170. } finally {
  171. rmSync(cwd, { force: true, recursive: true });
  172. }
  173. });
  174. it("names the file when it cannot be read", async () => {
  175. const cwd = mkdtempSync(join(tmpdir(), "dwf-snippet-path-"));
  176. try {
  177. const resolution = await resolve({ path: "missing.ts" }, cwd);
  178. expect(resolution).toMatchObject({ result: false });
  179. expect((resolution as { message: string }).message).toContain("missing.ts could not be read");
  180. } finally {
  181. rmSync(cwd, { force: true, recursive: true });
  182. }
  183. });
  184. it("prefixes diagnostics with the file when the snippet came from one", async () => {
  185. const { port } = stubPort({
  186. kind: "diagnostics",
  187. diagnostics: [{ code: 2304, column: 14, line: 1, message: "Cannot find name 'agent'." }],
  188. });
  189. const context = makeContext(port);
  190. const output = await run(
  191. { code: `await agent("x")`, path: join(context.workingDirectory, "snippet.ts") },
  192. context,
  193. );
  194. expect(output.response).toContain("snippet.ts:L1:C14 Cannot find name 'agent'.");
  195. });
  196. });
  197. describe("EvalWorkflowSnippet approval gate (world.run)", () => {
  198. const gate = (input: unknown) => evalWorkflowSnippetToolEntry.prepareApproval!(input);
  199. it("proceeds silently for a pure read snippet", () => {
  200. expect(gate({ code: `return await files.glob("*.ts");` })).toEqual({ gate: "proceed" });
  201. });
  202. it("asks when the snippet carries world.run commands", () => {
  203. expect(gate({ code: `const r = await world.run("lean", ["a.lean"]); return r.exitCode;` })).toEqual({
  204. gate: "ask",
  205. });
  206. });
  207. it("proceeds for invalid input and for snippets that do not compile", () => {
  208. // handler / 端口负责把这两种失败变成可读的诊断;打断用户批准一段编不过的代码没有意义。
  209. expect(gate({ notCode: true })).toEqual({ gate: "proceed" });
  210. expect(gate({ code: `await agent("x").ask("y");` })).toEqual({ gate: "proceed" });
  211. expect(gate({ code: `const c = "node"; await world.run(c, []);` })).toEqual({ gate: "proceed" });
  212. });
  213. it("stays a standard-permission tool: no alwaysAsk, no always-allow suppression", () => {
  214. // 2026-08-26 复议(docs/dynamic-workflow/authoring.md「EvalWorkflowSnippet」):alwaysAsk 只属于
  215. // CreateWorkflow——load-bearing 且昂贵。snippet 按标准模式 / 规则流程裁决。
  216. expect(evalWorkflowSnippetToolEntry.permission.alwaysAsk).toBeUndefined();
  217. expect(evalWorkflowSnippetToolEntry.permission.askOptions).toBeUndefined();
  218. });
  219. });
  220. // 归一化后 `script` 恒等于 `code`(docs/dynamic-workflow/authoring.md「EvalWorkflowSnippet」):
  221. // 另外三个提交脚本的工具字段都叫 `script`,一条只读 `tool_input.script` 的 PreToolUse hook
  222. // 原先在这里读不到任何东西,片段就绕开了它。
  223. describe("EvalWorkflowSnippet — `script` mirrors `code` after resolution", () => {
  224. const resolve = async (input: unknown, cwd: string) =>
  225. await evalWorkflowSnippetToolEntry.resolveInput!(input, { workingDirectory: cwd });
  226. const resolvedInput = (resolution: unknown) =>
  227. (resolution as { input: Record<string, unknown> }).input;
  228. it("adds `script` for an inline snippet", async () => {
  229. const resolution = await resolve({ code: "return 1;" }, "/tmp/snippet-test");
  230. expect(resolution).toMatchObject({ result: true });
  231. expect(resolvedInput(resolution)).toEqual({ code: "return 1;", script: "return 1;" });
  232. });
  233. it("adds `script` for a snippet read from a file", async () => {
  234. const cwd = mkdtempSync(join(tmpdir(), "dwf-snippet-script-"));
  235. try {
  236. writeFileSync(join(cwd, "snippet.ts"), "return 2;", "utf8");
  237. const input = resolvedInput(await resolve({ path: "snippet.ts" }, cwd));
  238. expect(input.code).toBe("return 2;");
  239. expect(input.script).toBe("return 2;");
  240. } finally {
  241. rmSync(cwd, { force: true, recursive: true });
  242. }
  243. });
  244. it("overwrites a `script` the model supplied: it is a resolution result, not a parameter", async () => {
  245. const input = resolvedInput(
  246. await resolve({ code: "return 1;", script: "return 2;" }, "/tmp/x"),
  247. );
  248. expect(input.script).toBe("return 1;");
  249. });
  250. it("keeps `script` off the model-facing schema, and the runtime schema accepts it", () => {
  251. const properties = (EvalWorkflowSnippetInputJsonSchema as { properties?: object }).properties;
  252. expect(Object.keys(properties ?? {}).sort()).toEqual(["code", "path", "timeoutMs"]);
  253. expect(
  254. EvalWorkflowSnippetInputSchema.safeParse({ code: "return 1;", script: "return 1;" }).success,
  255. ).toBe(true);
  256. });
  257. it("gives PreToolUse hooks the snippet as `script`, as for the other workflow tools", async () => {
  258. const seen: unknown[] = [];
  259. const hookRunner: HookRunner = {
  260. async run(input) {
  261. if (input.hookEventName === HookEventName.PreToolUse) {
  262. seen.push((input as unknown as { toolInput?: unknown }).toolInput);
  263. }
  264. return { additionalContexts: [] };
  265. },
  266. };
  267. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  268. const sessionId = createSessionId("eval-snippet-hook");
  269. const turnId = createTurnId("eval-snippet-hook");
  270. const traceContext = createRootTraceContext({ sessionId, turnId });
  271. const registry = createToolRegistry();
  272. registry.register(evalWorkflowSnippetToolEntry);
  273. const executor = createToolExecutor({
  274. dynamicWorkflowSnippetPort: port,
  275. emitEvent: async () => {},
  276. hookRunner,
  277. mode: "yolo",
  278. permissionBroker: {
  279. async requestPermission() {
  280. return { decision: "allow" as const };
  281. },
  282. },
  283. permissionService: new PermissionService(defaultPermissionConfig),
  284. registry,
  285. sessionId,
  286. turnId,
  287. traceContext,
  288. workingDirectory: "/tmp/snippet-test",
  289. });
  290. const result = await executor.execute(
  291. {
  292. id: createToolCallId("eval-snippet-hook"),
  293. input: { code: "return 1;" },
  294. name: "EvalWorkflowSnippet",
  295. },
  296. { traceContext },
  297. );
  298. expect(result.success).toBe(true);
  299. expect(seen).toHaveLength(1);
  300. expect((seen[0] as { script?: string }).script).toBe("return 1;");
  301. expect(requests[0]?.code).toBe("return 1;");
  302. });
  303. });
  304. // 参数不是合法 JSON 时,adapter 记 `model.tool_input.normalize_failed` 并把调用恢复成 `{}`
  305. // (adapters/src/model/tool-input-normalization.ts);本工具字段全可选,`{}` 能过 schema。
  306. // 这条从 executor 走一遍:拿到的必须是「没给来源」那句带解析提示的话,且什么都没执行。
  307. describe("EvalWorkflowSnippet — a call whose arguments did not parse", () => {
  308. it("answers the recovered empty input with the missing-source hint, before hooks and the port", async () => {
  309. const hookEvents: string[] = [];
  310. const hookRunner: HookRunner = {
  311. async run(input) {
  312. hookEvents.push(input.hookEventName);
  313. return { additionalContexts: [] };
  314. },
  315. };
  316. const { port, requests } = stubPort({ kind: "completed", logs: [], logsTruncated: false });
  317. const sessionId = createSessionId("eval-snippet-empty");
  318. const turnId = createTurnId("eval-snippet-empty");
  319. const traceContext = createRootTraceContext({ sessionId, turnId });
  320. const registry = createToolRegistry();
  321. registry.register(evalWorkflowSnippetToolEntry);
  322. const executor = createToolExecutor({
  323. dynamicWorkflowSnippetPort: port,
  324. emitEvent: async () => {},
  325. hookRunner,
  326. mode: "yolo",
  327. permissionBroker: {
  328. async requestPermission() {
  329. return { decision: "allow" as const };
  330. },
  331. },
  332. permissionService: new PermissionService(defaultPermissionConfig),
  333. registry,
  334. sessionId,
  335. turnId,
  336. traceContext,
  337. workingDirectory: "/tmp/snippet-test",
  338. });
  339. const result = await executor.execute(
  340. { id: createToolCallId("eval-snippet-empty"), input: {}, name: "EvalWorkflowSnippet" },
  341. { traceContext },
  342. );
  343. expect(result.success).toBe(false);
  344. expect(result.error?.message).toContain(EVAL_WORKFLOW_SNIPPET_SOURCE_MISSING_ERROR);
  345. expect(hookEvents).not.toContain(HookEventName.PreToolUse);
  346. expect(requests).toHaveLength(0);
  347. });
  348. });