workflow-script-models.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import {
  6. AmendWorkflowInputSchema,
  7. CreateWorkflowInputSchema,
  8. type CreateWorkflowOutput,
  9. type DynamicWorkflowRunAmendRequest,
  10. type DynamicWorkflowRunPort,
  11. type DynamicWorkflowRunSnapshot,
  12. type DynamicWorkflowRunSubmitRequest,
  13. type ModelCatalogEntry,
  14. type ModelCatalogPort,
  15. parseWorkflowSettingsAdjustment,
  16. } from "@zcode/contracts";
  17. import { MODEL_UNRESOLVED_CODE } from "@zcode/dynamic-workflow";
  18. import { amendWorkflowToolEntry } from "../src/tool/handlers/amend-workflow.js";
  19. import { createWorkflowToolEntry } from "../src/tool/handlers/create-workflow.js";
  20. import { analyzeScript } from "../src/tool/handlers/workflow-script-analysis.js";
  21. import { applyWorkflowSettingsAdjustments } from "../src/tool/handlers/workflow-settings-adjustment.js";
  22. import {
  23. SCRIPT_MODELS_UNAVAILABLE,
  24. describeScriptModelBindings,
  25. distinctModelNames,
  26. resolveScriptModelBindings,
  27. unresolvedScriptModelDiagnostics,
  28. } from "../src/tool/handlers/workflow-script-models.js";
  29. import type { ToolExecutionContext, ToolInputResolutionContext } from "../src/tool/types.js";
  30. // docs/dynamic-workflow/launch.md「Models the script names」:脚本点名的模型在确认窗之前对着本机的
  31. // 模型目录解析;解得出来的进 `model_bindings`,解不出来的不开窗、报 9011,改的是脚本文件。
  32. function entry(
  33. providerId: string,
  34. modelId: string,
  35. extra: Partial<ModelCatalogEntry> = {},
  36. ): ModelCatalogEntry {
  37. return { providerId, modelId, reasoningLevels: [], current: false, ...extra };
  38. }
  39. const CATALOG: ModelCatalogPort = {
  40. listModels: () => [
  41. entry("zhipu", "GLM-5.3", {
  42. reasoningLevels: ["low", "high"],
  43. defaultReasoningLevel: "high",
  44. current: true,
  45. }),
  46. entry("zhipu", "GLM-5.3-Flash"),
  47. entry("team", "GLM-5.3-Flash"),
  48. entry("acme", "gpt-5"),
  49. ],
  50. };
  51. const ROUTING_SCRIPT = [
  52. `const MODELS = { light: model("gpt-5"), strong: model("GLM-5.3") };`,
  53. `interface Route { tier: "light" | "strong" }`,
  54. `const route = await agent("分诊", { model: MODELS.light }).ask<Route>("pick");`,
  55. `const answer = await agent("答复者", { model: MODELS[route.tier] }).ask("go");`,
  56. `return answer;`,
  57. ].join("\n");
  58. const UNKNOWN_MODEL_SCRIPT = [
  59. `const judge = agent("评审员", { model: "gemini-3" });`,
  60. `const again = agent("复核员", { model: "gemini-3" });`,
  61. `await judge.ask("x");`,
  62. `await again.ask("y");`,
  63. `return 1;`,
  64. ].join("\n");
  65. const cwds: string[] = [];
  66. function makeCwd(): string {
  67. const dir = mkdtempSync(join(tmpdir(), "dwf-script-models-"));
  68. cwds.push(dir);
  69. return dir;
  70. }
  71. afterEach(() => {
  72. while (cwds.length > 0) rmSync(cwds.pop()!, { force: true, recursive: true });
  73. });
  74. interface FakePort {
  75. port: DynamicWorkflowRunPort;
  76. submits: DynamicWorkflowRunSubmitRequest[];
  77. amends: DynamicWorkflowRunAmendRequest[];
  78. }
  79. function fakePort(snapshot: Partial<DynamicWorkflowRunSnapshot> = {}): FakePort {
  80. const submits: DynamicWorkflowRunSubmitRequest[] = [];
  81. const amends: DynamicWorkflowRunAmendRequest[] = [];
  82. const port = {
  83. async submit(request: DynamicWorkflowRunSubmitRequest) {
  84. submits.push(request);
  85. return { ok: true, runId: "dwfrun-new" };
  86. },
  87. async amend(request: DynamicWorkflowRunAmendRequest) {
  88. amends.push(request);
  89. return { ok: true, runId: "dwfrun-amended" };
  90. },
  91. async getTask(taskId: string) {
  92. return {
  93. runId: taskId,
  94. taskId,
  95. startedAt: new Date(0),
  96. status: "completed",
  97. runStatus: "errored",
  98. ...snapshot,
  99. } as DynamicWorkflowRunSnapshot;
  100. },
  101. async getScript() {
  102. return ROUTING_SCRIPT;
  103. },
  104. defaultConcurrency: () => 6,
  105. } as unknown as DynamicWorkflowRunPort;
  106. return { port, submits, amends };
  107. }
  108. function resolutionContext(
  109. port: DynamicWorkflowRunPort | undefined,
  110. catalog: ModelCatalogPort | undefined = CATALOG,
  111. cwd = "/workspace/never-read",
  112. ): ToolInputResolutionContext {
  113. return {
  114. workingDirectory: cwd,
  115. ...(port === undefined ? {} : { dynamicWorkflowRunPort: port }),
  116. ...(catalog === undefined ? {} : { modelCatalogPort: catalog }),
  117. // 技能门:视为已加载 dynamic-workflows(门本身有自己的测试)。
  118. dynamicWorkflowSkillLoaded: () => true,
  119. } as unknown as ToolInputResolutionContext;
  120. }
  121. function executionContext(
  122. cwd: string,
  123. port: DynamicWorkflowRunPort,
  124. catalog: ModelCatalogPort | undefined = CATALOG,
  125. ): ToolExecutionContext {
  126. return {
  127. workingDirectory: cwd,
  128. sessionId: "sess-1",
  129. toolCallId: "tool-1",
  130. dynamicWorkflowRunPort: port,
  131. ...(catalog === undefined ? {} : { modelCatalogPort: catalog }),
  132. readFileState: new Map(),
  133. } as unknown as ToolExecutionContext;
  134. }
  135. async function resolveCreate(
  136. input: Record<string, unknown>,
  137. context: ToolInputResolutionContext,
  138. ): Promise<Record<string, unknown>> {
  139. const resolution = await createWorkflowToolEntry.resolveInput!(input, context);
  140. expect(resolution.result).toBe(true);
  141. return (resolution as { input: Record<string, unknown> }).input;
  142. }
  143. describe("resolving the names a script uses", () => {
  144. it("resolves each distinct name once, in first-occurrence order", () => {
  145. const analysis = analyzeScript(ROUTING_SCRIPT);
  146. expect(distinctModelNames(analysis.modelReferences)).toEqual(["gpt-5", "GLM-5.3"]);
  147. expect(resolveScriptModelBindings(["gpt-5", "GLM-5.3"], CATALOG)).toEqual({
  148. "gpt-5": "acme/gpt-5",
  149. // 默认档位写进规范串:窗与 journal 读到的是将要生效的整条选择。
  150. "GLM-5.3": "zhipu/GLM-5.3$high",
  151. });
  152. });
  153. it("keeps an inherited binding (the model the predecessor ran the name on)", () => {
  154. expect(
  155. resolveScriptModelBindings(["gpt-5"], CATALOG, { "gpt-5": "zhipu/GLM-5.3$low" }),
  156. ).toEqual({ "gpt-5": "zhipu/GLM-5.3$low" });
  157. });
  158. it("reports one 9011 per unbound name, at its first occurrence, with the resolver's candidates", () => {
  159. const analysis = analyzeScript(UNKNOWN_MODEL_SCRIPT);
  160. const diagnostics = unresolvedScriptModelDiagnostics(analysis, {}, CATALOG);
  161. expect(diagnostics).toHaveLength(1);
  162. expect(diagnostics[0]).toMatchObject({ code: MODEL_UNRESOLVED_CODE, line: 1 });
  163. expect(diagnostics[0]!.message).toContain('The model "gemini-3" named in the script');
  164. expect(diagnostics[0]!.message).toContain("zhipu/GLM-5.3 [current]");
  165. });
  166. it("names the ambiguity when a bare id is configured under several providers and the session's is not among them", () => {
  167. const analysis = analyzeScript(`agent("a", { model: "GLM-5.3-Flash" });\nreturn 1;`);
  168. const [diagnostic] = unresolvedScriptModelDiagnostics(analysis, {}, CATALOG);
  169. expect(diagnostic!.message).toContain("more than one provider");
  170. expect(diagnostic!.message).toContain("zhipu/GLM-5.3-Flash");
  171. expect(diagnostic!.message).toContain("team/GLM-5.3-Flash");
  172. });
  173. it("says the inherited model is gone rather than blaming the name", () => {
  174. const analysis = analyzeScript(`agent("a", { model: "gpt-5" });\nreturn 1;`);
  175. const [diagnostic] = unresolvedScriptModelDiagnostics(analysis, {}, CATALOG, {
  176. "gpt-5": "retired/old-model",
  177. });
  178. expect(diagnostic!.message).toContain("keeps the model the amended run bound it to");
  179. expect(diagnostic!.message).toContain("retired/old-model");
  180. });
  181. it("a host with no model catalog fails every name with a script-side fix", () => {
  182. const analysis = analyzeScript(`agent("a", { model: "gpt-5" });\nreturn 1;`);
  183. const [diagnostic] = unresolvedScriptModelDiagnostics(analysis, {}, undefined);
  184. expect(diagnostic!.message).toBe(SCRIPT_MODELS_UNAVAILABLE);
  185. });
  186. it("describes the table in the canonical spelling the model can paste back", () => {
  187. expect(describeScriptModelBindings({})).toBe("");
  188. expect(describeScriptModelBindings({ "gpt-5": "acme/gpt-5", x: "zhipu/GLM-5.3$high" })).toBe(
  189. ' Models named in the script: "gpt-5" = acme/gpt-5; "x" = zhipu/GLM-5.3$high.',
  190. );
  191. });
  192. });
  193. describe("CreateWorkflow — models the script names", () => {
  194. it("resolveInput writes the bindings, and a forged table is overwritten", async () => {
  195. const { port } = fakePort();
  196. const input = await resolveCreate(
  197. { script: ROUTING_SCRIPT, model_bindings: { forged: "evil/model" } },
  198. resolutionContext(port),
  199. );
  200. expect(input.model_bindings).toEqual({
  201. "gpt-5": "acme/gpt-5",
  202. "GLM-5.3": "zhipu/GLM-5.3$high",
  203. });
  204. expect(CreateWorkflowInputSchema.safeParse(input).success).toBe(true);
  205. });
  206. it("writes no key for a script that names no model, and strips a forged one", async () => {
  207. const input = await resolveCreate(
  208. { script: "return 1;", model_bindings: { x: "evil/model" } },
  209. resolutionContext(fakePort().port),
  210. );
  211. expect(Object.hasOwn(input, "model_bindings")).toBe(false);
  212. });
  213. it("the window opens only when every name is bound", async () => {
  214. const context = resolutionContext(fakePort().port);
  215. const bound = await resolveCreate({ script: ROUTING_SCRIPT }, context);
  216. expect(createWorkflowToolEntry.prepareApproval!(bound).gate).toBe("ask");
  217. const unbound = await resolveCreate({ script: UNKNOWN_MODEL_SCRIPT }, context);
  218. expect(Object.hasOwn(unbound, "model_bindings")).toBe(false);
  219. expect(createWorkflowToolEntry.prepareApproval!(unbound).gate).toBe("proceed");
  220. });
  221. it("an unresolved name is a 9011 diagnostic in file lines, nothing is submitted, the draft is named", async () => {
  222. const cwd = makeCwd();
  223. const { port, submits } = fakePort();
  224. const input = await resolveCreate({ script: UNKNOWN_MODEL_SCRIPT }, resolutionContext(port));
  225. const output = (await createWorkflowToolEntry.handler(
  226. input,
  227. executionContext(cwd, port),
  228. )) as CreateWorkflowOutput;
  229. expect(output.ok).toBe(false);
  230. expect(submits).toHaveLength(0);
  231. expect(output.diagnostics.map((d) => d.code)).toEqual([MODEL_UNRESOLVED_CODE]);
  232. expect(output.response).toContain(":L1:C");
  233. expect(output.response).toContain("gemini-3");
  234. expect(output.response).toContain("NOTE: The workflow was NOT executed.");
  235. });
  236. it("a bound script submits the table as structured selections and names it in the response", async () => {
  237. const cwd = makeCwd();
  238. const { port, submits } = fakePort();
  239. const input = await resolveCreate({ script: ROUTING_SCRIPT }, resolutionContext(port));
  240. const output = (await createWorkflowToolEntry.handler(
  241. input,
  242. executionContext(cwd, port),
  243. )) as CreateWorkflowOutput;
  244. expect(output.ok).toBe(true);
  245. expect(submits).toHaveLength(1);
  246. expect(submits[0]!.modelBindings).toEqual({
  247. "gpt-5": { providerId: "acme", modelId: "gpt-5" },
  248. "GLM-5.3": { providerId: "zhipu", modelId: "GLM-5.3", options: { reasoningLevel: "high" } },
  249. });
  250. expect(output.response).toContain(
  251. 'Models named in the script: "gpt-5" = acme/gpt-5; "GLM-5.3" = zhipu/GLM-5.3$high.',
  252. );
  253. });
  254. it("a script without models submits no modelBindings key", async () => {
  255. const cwd = makeCwd();
  256. const { port, submits } = fakePort();
  257. const input = await resolveCreate({ script: "return 1;" }, resolutionContext(port));
  258. await createWorkflowToolEntry.handler(input, executionContext(cwd, port));
  259. expect(Object.hasOwn(submits[0]!, "modelBindings")).toBe(false);
  260. });
  261. });
  262. describe("the window's settings adjustment", () => {
  263. const OPTIONS = { errorCode: 400, schema: CreateWorkflowInputSchema };
  264. const context = resolutionContext(undefined);
  265. const input = {
  266. script: ROUTING_SCRIPT,
  267. model_bindings: { "gpt-5": "acme/gpt-5", "GLM-5.3": "zhipu/GLM-5.3$high" },
  268. };
  269. // 确认窗不逐名列出脚本点名的模型(docs/dynamic-workflow/launch.md「The window」):应答里没有改它们的
  270. // 字段,调整只动两项 run 设置,绑定表原样留在入参里。
  271. it("leaves the bindings as resolved; the answer has no field for them", () => {
  272. const outcome = applyWorkflowSettingsAdjustments(
  273. input,
  274. parseWorkflowSettingsAdjustment({
  275. max_concurrency: 3,
  276. model_bindings: { "gpt-5": "zhipu/GLM-5.3$low" },
  277. }),
  278. context,
  279. OPTIONS,
  280. );
  281. expect(outcome).toMatchObject({
  282. result: true,
  283. input: { ...input, max_concurrency: 3 },
  284. applied: { max_concurrency: 3 },
  285. });
  286. });
  287. });
  288. describe("AmendWorkflow — models the script names", () => {
  289. async function resolveAmend(
  290. input: Record<string, unknown>,
  291. context: ToolInputResolutionContext,
  292. ): Promise<Record<string, unknown>> {
  293. const resolution = await amendWorkflowToolEntry.resolveInput!(input, context);
  294. expect(resolution).toMatchObject({ result: true });
  295. return (resolution as { input: Record<string, unknown> }).input;
  296. }
  297. it("keeps the predecessor's binding for a name it already used and resolves new names", async () => {
  298. const { port } = fakePort({ modelBindings: { "gpt-5": "zhipu/GLM-5.3$low" } });
  299. const script = ROUTING_SCRIPT.replace(`model("GLM-5.3")`, `model("GLM-5.3-Flash$x")`).replace(
  300. `model("GLM-5.3-Flash$x")`,
  301. `model("zhipu/GLM-5.3-Flash")`,
  302. );
  303. const input = await resolveAmend({ run_id: "dwfrun-prev", script }, resolutionContext(port));
  304. expect(input.model_bindings).toEqual({
  305. "gpt-5": "zhipu/GLM-5.3$low",
  306. "zhipu/GLM-5.3-Flash": "zhipu/GLM-5.3-Flash",
  307. });
  308. expect(AmendWorkflowInputSchema.safeParse(input).success).toBe(true);
  309. });
  310. it("an inherited model that is gone is 9011 saying so; nothing is amended", async () => {
  311. const cwd = makeCwd();
  312. const { port, amends } = fakePort({ modelBindings: { "gpt-5": "retired/old" } });
  313. const input = await resolveAmend(
  314. {
  315. run_id: "dwfrun-prev",
  316. script: `await agent("a", { model: "gpt-5" }).ask("x");\nreturn 1;`,
  317. },
  318. resolutionContext(port),
  319. );
  320. expect(Object.hasOwn(input, "model_bindings")).toBe(false);
  321. expect(amendWorkflowToolEntry.prepareApproval!(input).gate).toBe("proceed");
  322. const output = (await amendWorkflowToolEntry.handler(
  323. input,
  324. executionContext(cwd, port),
  325. )) as CreateWorkflowOutput;
  326. expect(output.ok).toBe(false);
  327. expect(amends).toHaveLength(0);
  328. expect(output.response).toContain("keeps the model the amended run bound it to, retired/old");
  329. });
  330. it("hands the resolved table to port.amend", async () => {
  331. const cwd = makeCwd();
  332. const { port, amends } = fakePort({ modelBindings: { "gpt-5": "zhipu/GLM-5.3$low" } });
  333. const input = await resolveAmend(
  334. { run_id: "dwfrun-prev", script: ROUTING_SCRIPT },
  335. resolutionContext(port),
  336. );
  337. await amendWorkflowToolEntry.handler(input, executionContext(cwd, port));
  338. expect(amends).toHaveLength(1);
  339. expect(amends[0]!.modelBindings).toEqual({
  340. "gpt-5": { providerId: "zhipu", modelId: "GLM-5.3", options: { reasoningLevel: "low" } },
  341. "GLM-5.3": { providerId: "zhipu", modelId: "GLM-5.3", options: { reasoningLevel: "high" } },
  342. });
  343. });
  344. });