actor-models.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import { describe, expect, it } from "vitest";
  2. import { analyzeWorkflowScript } from "../src/index.js";
  3. import { MODEL_REFERENCE_CODE } from "../src/analysis/actor-models.js";
  4. import { lowerWorkflowScript } from "../src/lowering/index.js";
  5. // 子代理模型名集合的封闭性(9010,docs/dynamic-workflow/authoring.md「Choosing a model per
  6. // subagent」)。规则判的是 persona `model` 属性的**类型**:ModelRef、字符串字面量类型或它们的
  7. // 联合才收;收下的每个字面量都进 `modelReferences`,launch 工具据此在确认窗之前解析全部名字。
  8. function analyze(scriptText: string) {
  9. const result = analyzeWorkflowScript(scriptText);
  10. const hits = result.diagnostics.filter((d) => d.code === MODEL_REFERENCE_CODE);
  11. return { hits, result };
  12. }
  13. /** 干净脚本:没有任何诊断,返回收集到的名字(按出现顺序,含重复)。 */
  14. function namesOf(scriptText: string): string[] {
  15. const { result } = analyze(scriptText);
  16. expect(result.diagnostics).toEqual([]);
  17. expect(result.ok).toBe(true);
  18. return result.modelReferences.map((ref) => ref.name);
  19. }
  20. describe("persona model: accepted forms", () => {
  21. it("an inline string literal", () => {
  22. expect(
  23. namesOf(`const a = agent("评审员", { system: "s", model: "GLM-5.3-Flash" });\nreturn 1;`),
  24. ).toEqual(["GLM-5.3-Flash"]);
  25. });
  26. it("keeps the name verbatim, reasoning level and provider included", () => {
  27. expect(
  28. namesOf(
  29. `agent("a", { model: "zhipu/GLM-5.3$high" });\nagent("b", { model: " GLM-5.3 " });\nreturn 1;`,
  30. ),
  31. ).toEqual(["zhipu/GLM-5.3$high", " GLM-5.3 "]);
  32. });
  33. it("a const bound to a literal, and a ternary between two literals", () => {
  34. const names = namesOf(
  35. `const FLASH = "GLM-5.3-Flash";\n` +
  36. `const hard = args.hard === true;\n` +
  37. `agent("a", { model: FLASH });\n` +
  38. `agent("b", { model: hard ? "GLM-5.3$high" : FLASH });\n` +
  39. `return 1;`,
  40. );
  41. // 联合成员的顺序是 checker 的(类型 id 序),不是源码序:只断言集合与次数。
  42. expect([...names].sort()).toEqual(["GLM-5.3$high", "GLM-5.3-Flash", "GLM-5.3-Flash"]);
  43. });
  44. it("a shorthand property bound to a literal const", () => {
  45. expect(namesOf(`const model = "GLM-5.3-Flash";\nagent("a", { model });\nreturn 1;`)).toEqual([
  46. "GLM-5.3-Flash",
  47. ]);
  48. });
  49. it("a persona object declared as const", () => {
  50. expect(
  51. namesOf(
  52. `const persona = { system: "s", model: "GLM-5.3-Flash" } as const;\nagent("a", persona);\nreturn 1;`,
  53. ),
  54. ).toEqual(["GLM-5.3-Flash"]);
  55. });
  56. it("routing through a model() table: every declared name is collected once per call", () => {
  57. const script =
  58. `const MODELS = { light: model("GLM-5.3-Flash"), strong: model("GLM-5.3$high") };\n` +
  59. `interface Route { tier: "light" | "strong" }\n` +
  60. `const route = await agent("分诊", { model: MODELS.light }).ask<Route>("pick");\n` +
  61. `const answer = await agent("答复者", { model: MODELS[route.tier] }).ask("go");\n` +
  62. `return answer;`;
  63. const { result } = analyze(script);
  64. expect(result.diagnostics).toEqual([]);
  65. expect(result.ok).toBe(true);
  66. expect(result.modelReferences).toEqual([
  67. { name: "GLM-5.3-Flash", line: 1, column: 31 },
  68. { name: "GLM-5.3$high", line: 1, column: 63 },
  69. ]);
  70. // 分析照常产出图:模型不是图的一部分。
  71. expect(result.graph).toBeDefined();
  72. });
  73. it("a ModelRef passed through a helper function parameter", () => {
  74. const names = namesOf(
  75. `const LIGHT = model("GLM-5.3-Flash");\n` +
  76. `function judge(name: string, m: ModelRef) { return agent(name, { model: m }); }\n` +
  77. `await judge("a", LIGHT).ask("x");\n` +
  78. `return 1;`,
  79. );
  80. expect(names).toEqual(["GLM-5.3-Flash"]);
  81. });
  82. it("a literal union answered by a router (the schema pins the enum)", () => {
  83. const names = namesOf(
  84. `interface Route { model: "GLM-5.3" | "GLM-5.3-Flash" }\n` +
  85. `const r = await agent("分诊").ask<Route>("pick");\n` +
  86. `await agent("答复者", { model: r.model }).ask("go");\n` +
  87. `return 1;`,
  88. );
  89. expect([...names].sort()).toEqual(["GLM-5.3", "GLM-5.3-Flash"]);
  90. });
  91. it("no model anywhere: nothing collected, string personas skipped", () => {
  92. expect(
  93. namesOf(`agent("a");\nagent("b", "You review.");\nagent("c", { system: "s" });\nreturn 1;`),
  94. ).toEqual([]);
  95. });
  96. it("a spread persona whose model is a literal type", () => {
  97. expect(
  98. namesOf(
  99. `const base = { model: "GLM-5.3-Flash" } as const;\nagent("a", { ...base, system: "s" });\nreturn 1;`,
  100. ),
  101. ).toEqual(["GLM-5.3-Flash"]);
  102. });
  103. });
  104. describe("persona model: rejected forms (9010)", () => {
  105. const expectRejected = (script: string, line: number) => {
  106. const { hits, result } = analyze(script);
  107. expect(hits).toHaveLength(1);
  108. expect(hits[0]?.line).toBe(line);
  109. expect(result.ok).toBe(false);
  110. // 与 world.run / phase 同席:图不产出。
  111. expect(result.graph).toBeUndefined();
  112. return hits[0]!;
  113. };
  114. it("a let binding widens to string", () => {
  115. const hit = expectRejected(`let m = "GLM-5.3-Flash";\nagent("a", { model: m });\nreturn 1;`, 2);
  116. expect(hit.message).toContain("'string'");
  117. expect(hit.message).toContain("model(");
  118. });
  119. it("a persona object built into a variable (its model widens)", () => {
  120. const hit = expectRejected(
  121. `const persona = { system: "s", model: "GLM-5.3-Flash" };\nagent("a", persona);\nreturn 1;`,
  122. 2,
  123. );
  124. expect(hit.message).toContain("as const");
  125. });
  126. it("a template with a hole", () => {
  127. expectRejected(
  128. `const v = args.v as string;\nagent("a", { model: \`GLM-\${v}\` });\nreturn 1;`,
  129. 2,
  130. );
  131. });
  132. it("a parameter typed AgentPersona (its model could be any string)", () => {
  133. expectRejected(
  134. `function make(p: AgentPersona) { return agent("a", p); }\nawait make({ system: "s" }).ask("x");\nreturn 1;`,
  135. 1,
  136. );
  137. });
  138. it("a model name computed from a subagent's answer", () => {
  139. expectRejected(
  140. `const name = await agent("分诊").ask("which model?");\nagent("b", { model: name });\nreturn 1;`,
  141. 2,
  142. );
  143. });
  144. it("one bad branch of a conditional persona is enough", () => {
  145. expectRejected(
  146. `const s = args.s as string;\nagent("a", args.x ? { model: "GLM-5.3" } : { model: s });\nreturn 1;`,
  147. 2,
  148. );
  149. });
  150. it("model() with a non-literal, an empty literal, or no argument", () => {
  151. const { hits, result } = analyze(
  152. `const v = args.v as string;\nconst a = model(v);\nconst b = model(" ");\nreturn 1;`,
  153. );
  154. expect(hits.map((h) => h.line)).toEqual([2, 3]);
  155. expect(hits[0]?.message).toContain("string literal");
  156. expect(result.modelReferences).toEqual([]);
  157. });
  158. it("an empty string literal as the model", () => {
  159. expectRejected(`agent("a", { model: "" });\nreturn 1;`, 1);
  160. });
  161. it("ModelRef used as a value (it does not exist at run time)", () => {
  162. const { hits } = analyze(
  163. `const m = model("GLM-5.3");\nconst isRef = (m as unknown) instanceof ModelRef;\nreturn isRef;`,
  164. );
  165. expect(hits).toHaveLength(1);
  166. expect(hits[0]?.line).toBe(2);
  167. expect(hits[0]?.message).toContain("only as a type");
  168. });
  169. it("a ModelRef cannot be forged by an object literal or new (TypeScript errors, not 9010)", () => {
  170. const literal = analyzeWorkflowScript(
  171. `agent("a", { model: { modelRef: undefined as never } });\nreturn 1;`,
  172. );
  173. expect(literal.ok).toBe(false);
  174. expect(literal.diagnostics.some((d) => d.code !== MODEL_REFERENCE_CODE)).toBe(true);
  175. const constructed = analyzeWorkflowScript(`const m = new ModelRef();\nreturn 1;`);
  176. expect(constructed.ok).toBe(false);
  177. });
  178. it("aliasing model() is facade misuse (9001), not a way around 9010", () => {
  179. const result = analyzeWorkflowScript(
  180. `const m = model;\nagent("a", { model: m("x") });\nreturn 1;`,
  181. );
  182. expect(result.ok).toBe(false);
  183. expect(result.diagnostics[0]?.code).toBe(9001);
  184. });
  185. it("names are still collected next to other authoring diagnostics", () => {
  186. const { result } = analyze(
  187. `let m = "x" as string;\nagent("a", { model: m });\nagent("b", { model: "GLM-5.3" });\nreturn 1;`,
  188. );
  189. expect(result.ok).toBe(false);
  190. expect(result.modelReferences.map((r) => r.name)).toEqual(["GLM-5.3"]);
  191. });
  192. });
  193. describe("lowering model()", () => {
  194. it('erases model("x") to the string itself and leaves the persona object alone', () => {
  195. const result = lowerWorkflowScript(
  196. `const MODELS = { light: model("GLM-5.3-Flash") };\n` +
  197. `const a = agent("评审员", { system: "s", model: MODELS.light });\n` +
  198. `const b = agent("写手", { model: "GLM-5.3$high" });\n` +
  199. `return 1;`,
  200. );
  201. expect(result.ok).toBe(true);
  202. const code = result.lowered!.code;
  203. expect(code).toContain(`light: "GLM-5.3-Flash"`);
  204. expect(code).not.toMatch(/\bmodel\(/);
  205. expect(code).toContain(`model: MODELS.light`);
  206. expect(code).toContain(`model: "GLM-5.3$high"`);
  207. expect(code).not.toContain("ModelRef");
  208. });
  209. it("the lowered code runs: a ModelRef is its name at run time", async () => {
  210. const result = lowerWorkflowScript(
  211. `const MODELS = { light: model("GLM-5.3-Flash"), strong: model("GLM-5.3") };\n` +
  212. `const pick: "light" | "strong" = args.hard === true ? "strong" : "light";\n` +
  213. `agent("答复者", { model: MODELS[pick] });\n` +
  214. `return 1;`,
  215. );
  216. expect(result.ok).toBe(true);
  217. const personas: unknown[] = [];
  218. const host = {
  219. args: { hard: true },
  220. createActor: (_site: string, _name: string, persona: unknown) => {
  221. personas.push(persona);
  222. return "local#1";
  223. },
  224. };
  225. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor as new (
  226. ...params: string[]
  227. ) => (host: unknown) => Promise<unknown>;
  228. await new AsyncFunction("__host", result.lowered!.code)(host);
  229. expect(personas).toEqual([{ model: "GLM-5.3" }]);
  230. });
  231. });