workflow-script-models.test.ts 16 KB

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