subagent-runtime-config.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { tmpdir } from "node:os";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { createAgentStateId, type SubagentRuntimeConfig } from "@zcode/shared";
  6. import type { ModelRequest } from "@zcode/contracts";
  7. import { createNodeLoggerFactory } from "@zcode/adapters/logging";
  8. import { parseRuntimeSubagentConfig } from "../src/runtime-subagents/index.js";
  9. import * as subagents from "../src/subagents.js";
  10. import { createRegistryBackedTestApp } from "./helpers/registry-backed-test-app.js";
  11. describe("runtime subagent source parsing", () => {
  12. it("preserves complete profiles, strips project permission and applies disabled user ids", () => {
  13. const parsed = parseRuntimeSubagentConfig({
  14. documents: [
  15. {
  16. path: "/project/.zcode/agents/reviewer.md",
  17. source: "project",
  18. content:
  19. "---\nname: reviewer\ndescription: Review\npermissionMode: bypassPermissions\nmodel: custom:provider:model\nthoughtLevel: high\ntools: Read, Grep\n---\nNEW_PROMPT",
  20. },
  21. ],
  22. state: {
  23. disabledAgentIds: [],
  24. builtInModelSelectionOverrides: {},
  25. pluginAgentModelSelectionOverrides: {},
  26. },
  27. });
  28. expect(parsed.profiles[0]).toMatchObject({
  29. name: "reviewer",
  30. systemPrompt: "NEW_PROMPT",
  31. tools: ["Read", "Grep"],
  32. modelSelection: {
  33. providerId: "provider",
  34. modelId: "model",
  35. options: { reasoningLevel: "high" },
  36. },
  37. });
  38. expect(parsed.profiles[0]?.permissionMode).toBeUndefined();
  39. const disabled = createAgentStateId({ name: "reviewer", scope: "user", source: "user" });
  40. const deleted = parseRuntimeSubagentConfig({
  41. documents: [
  42. {
  43. path: "/user/reviewer.md",
  44. source: "user",
  45. content: "---\nname: reviewer\ndescription: Review\n---\nPrompt",
  46. },
  47. ],
  48. state: {
  49. disabledAgentIds: [disabled],
  50. builtInModelSelectionOverrides: {},
  51. pluginAgentModelSelectionOverrides: {},
  52. },
  53. });
  54. expect(deleted.profiles).toEqual([]);
  55. });
  56. });
  57. describe("subagent initialization source", () => {
  58. it.each(["host", "files"] as const)(
  59. "initializes from %s and preserves other storage settings",
  60. async (source) => {
  61. const root = await mkdtemp(join(tmpdir(), "subagent-initial-source-"));
  62. const workspace = join(root, "workspace"),
  63. storage = join(root, "cli-storage");
  64. const configPath = join(root, "config.json");
  65. const logDir = join(root, "logs");
  66. const invalidDocument = {
  67. path: join(workspace, ".zcode", "agents", "invalid.md"),
  68. source: "project" as const,
  69. content: "This document intentionally lacks frontmatter",
  70. };
  71. const readDiagnostics = async () =>
  72. (
  73. await Promise.all(
  74. (await readdir(logDir)).map((name) => readFile(join(logDir, name), "utf8")),
  75. )
  76. )
  77. .flatMap((text) =>
  78. text
  79. .trim()
  80. .split("\n")
  81. .map((line) => JSON.parse(line)),
  82. )
  83. .filter((entry) => entry.message === "Agent profile diagnostic");
  84. const expectedDiagnostic = {
  85. level: "warn",
  86. module: "bootstrap.subagents",
  87. context: {
  88. code: "agent_missing_frontmatter",
  89. path: invalidDocument.path,
  90. message: `Agent Markdown must include frontmatter: ${invalidDocument.path}`,
  91. },
  92. };
  93. const markdown = (prompt: string) =>
  94. `---\nname: reviewer\ndescription: Review\ntools: Read\n---\n${prompt}`;
  95. const hostConfig = (prompt: string): SubagentRuntimeConfig => ({
  96. kind: "ready",
  97. profiles: [
  98. {
  99. path: join(root, "host-agents", "reviewer.md"),
  100. source: "user",
  101. name: "reviewer",
  102. description: "Review",
  103. tools: ["Read"],
  104. systemPrompt: prompt,
  105. },
  106. ],
  107. builtInModelSelectionOverrides: {},
  108. pluginAgentModelSelectionOverrides: {},
  109. });
  110. const initial = Promise.withResolvers<SubagentRuntimeConfig>();
  111. const readHost = vi.fn(async () => initial.promise);
  112. const fileLoader = vi.spyOn(subagents, "loadZCodeAgentProfiles");
  113. const pluginLoader = vi.spyOn(subagents, "loadPluginAgentTemplates");
  114. const requests: ModelRequest[] = [];
  115. let parentCalls = 0;
  116. let app: Awaited<ReturnType<typeof createRegistryBackedTestApp>> | undefined;
  117. let creating: ReturnType<typeof createRegistryBackedTestApp> | undefined;
  118. try {
  119. await mkdir(join(storage, "agents"), { recursive: true });
  120. await mkdir(join(workspace, ".zcode", "agents"), { recursive: true });
  121. if (source === "files") await writeFile(invalidDocument.path, invalidDocument.content);
  122. await writeFile(
  123. configPath,
  124. JSON.stringify({ storage: { dir: join(root, "unused-storage") } }),
  125. );
  126. await writeFile(join(storage, "agents", "reviewer.md"), markdown("DISK_PROFILE"));
  127. creating = createRegistryBackedTestApp({
  128. loggerFactory: createNodeLoggerFactory({ logDir }),
  129. env: {
  130. ZCODE_STORAGE_DIR: storage,
  131. ZCODE_SESSION_DB_PATH: join(storage, "cli", "db", "db.sqlite"),
  132. },
  133. userConfigPath: configPath,
  134. runtimeConfig: {
  135. workingDirectory: workspace,
  136. mode: "yolo",
  137. mcp: { enabled: false, servers: {} },
  138. modelSelection: {
  139. providerId: "zai",
  140. modelId: "glm-4.6",
  141. options: { reasoningLevel: "low" },
  142. },
  143. },
  144. ...(source === "host" ? { readSubagentRuntimeConfig: readHost } : {}),
  145. modelExecutor: {
  146. async generateText(request) {
  147. const isChild = JSON.stringify(request.messages).includes("_PROFILE");
  148. if (isChild) requests.push(request);
  149. return !isChild && ++parentCalls === 1
  150. ? {
  151. finishReason: "tool-calls",
  152. text: "",
  153. usage: {},
  154. toolCalls: [
  155. {
  156. id: "source_agent",
  157. name: "Agent",
  158. input: {
  159. description: "Review",
  160. prompt: "Review",
  161. subagent_type: "reviewer",
  162. },
  163. },
  164. ],
  165. }
  166. : { finishReason: "stop", text: "done", usage: {} };
  167. },
  168. },
  169. });
  170. if (source === "host") {
  171. let created = false;
  172. void creating.then(
  173. () => {
  174. created = true;
  175. },
  176. () => {},
  177. );
  178. await vi.waitFor(() => expect(readHost).toHaveBeenCalledTimes(1));
  179. expect(created).toBe(false);
  180. expect(fileLoader).not.toHaveBeenCalled();
  181. initial.resolve(hostConfig("INITIAL_PROFILE"));
  182. }
  183. app = await creating;
  184. // Host 已记录解析诊断;CLI 不再重复解析/记录,独立 loader 保持诊断。
  185. expect(await readDiagnostics()).toMatchObject(
  186. source === "files" ? [expectedDiagnostic] : [],
  187. );
  188. expect(fileLoader).toHaveBeenCalledTimes(source === "host" ? 0 : 1);
  189. expect(pluginLoader).toHaveBeenCalledTimes(1);
  190. readHost.mockResolvedValue(hostConfig("NEXT_PROFILE"));
  191. await app.submitPrompt("Please delegate the review");
  192. expect(readHost).toHaveBeenCalledTimes(source === "host" ? 2 : 0);
  193. expect(requests).toHaveLength(1);
  194. expect(JSON.stringify(requests[0])).toContain(
  195. source === "host" ? "NEXT_PROFILE" : "DISK_PROFILE",
  196. );
  197. expect(pluginLoader).toHaveBeenCalledTimes(1);
  198. expect((await readdir(join(storage, "cli", "agents"))).length).toBeGreaterThan(0);
  199. const diagnostics = await readDiagnostics();
  200. expect(diagnostics).toMatchObject(
  201. Array.from({ length: source === "host" ? 0 : 1 }, () => expectedDiagnostic),
  202. );
  203. expect(JSON.stringify(diagnostics)).not.toContain(invalidDocument.content);
  204. // 只替换 subagent 来源;实际 session 数据库仍在环境变量指定的位置。
  205. expect((await readFile(join(storage, "cli", "db", "db.sqlite"))).length).toBeGreaterThan(0);
  206. } finally {
  207. initial.resolve(hostConfig("INITIAL_PROFILE"));
  208. await (app ?? (await creating?.catch(() => undefined)))?.close?.();
  209. vi.restoreAllMocks();
  210. await rm(root, { recursive: true, force: true });
  211. }
  212. },
  213. );
  214. it("keeps builtins and inline definitions through fallback and restores cached plugin templates", async () => {
  215. const root = await mkdtemp(join(tmpdir(), "subagent-fallback-"));
  216. const profile = (name: string) => ({
  217. name,
  218. description: `${name} description`,
  219. systemPrompt: name,
  220. source: "user" as const,
  221. });
  222. const readHost = vi.fn(
  223. async (): Promise<SubagentRuntimeConfig> => ({ kind: "built-in-fallback" }),
  224. );
  225. const loadTemplates = vi.spyOn(subagents, "loadPluginAgentTemplates");
  226. const resolvePlugins = vi.spyOn(subagents, "resolvePluginAgentProfiles").mockReturnValue({
  227. profiles: [profile("fixture:worker")],
  228. diagnostics: [],
  229. builtInModelSelectionOverrides: {},
  230. pluginAgentModelSelectionOverrides: {},
  231. });
  232. const requests: ModelRequest[] = [];
  233. let app: Awaited<ReturnType<typeof createRegistryBackedTestApp>> | undefined;
  234. try {
  235. app = await createRegistryBackedTestApp({
  236. env: { ZCODE_STORAGE_DIR: root, ZCODE_SESSION_DB_PATH: join(root, "db.sqlite") },
  237. skipUserConfig: true,
  238. runtimeConfig: {
  239. workingDirectory: root,
  240. mcp: { enabled: false, servers: {} },
  241. subagents: { profiles: [profile("inline-reviewer")] },
  242. },
  243. readSubagentRuntimeConfig: readHost,
  244. modelExecutor: {
  245. async generateText(request) {
  246. requests.push(request);
  247. return { finishReason: "stop", text: "done", usage: {} };
  248. },
  249. },
  250. });
  251. await app.submitPrompt("Fallback turn");
  252. const first = JSON.stringify(requests[0]);
  253. for (const name of ["Explore", "general-purpose", "inline-reviewer"])
  254. expect(first).toContain(name);
  255. expect(first).not.toContain("fixture:worker");
  256. expect(resolvePlugins).not.toHaveBeenCalled();
  257. readHost.mockResolvedValue({
  258. kind: "ready",
  259. profiles: [profile("file-reviewer")],
  260. builtInModelSelectionOverrides: {},
  261. pluginAgentModelSelectionOverrides: {},
  262. });
  263. await app.submitPrompt("Recovered turn");
  264. expect(JSON.stringify(requests[1])).toContain("fixture:worker");
  265. expect(JSON.stringify(requests[1])).toContain("file-reviewer");
  266. readHost.mockResolvedValue({ kind: "built-in-fallback" });
  267. await app.submitPrompt("Fallback again");
  268. const last = JSON.stringify(requests[2]);
  269. expect(last).toMatch(/no longer available/);
  270. expect(last).toContain("inline-reviewer");
  271. expect(resolvePlugins).toHaveBeenCalledTimes(1);
  272. expect(loadTemplates).toHaveBeenCalledTimes(1);
  273. expect(readHost).toHaveBeenCalledTimes(4);
  274. } finally {
  275. await app?.close?.();
  276. vi.restoreAllMocks();
  277. await rm(root, { recursive: true, force: true });
  278. }
  279. });
  280. it("propagates an initialization read failure without using the file loader", async () => {
  281. const root = await mkdtemp(join(tmpdir(), "subagent-initial-failure-"));
  282. const fileLoader = vi.spyOn(subagents, "loadZCodeAgentProfiles");
  283. const error = new Error("Host configuration unavailable");
  284. let app: Awaited<ReturnType<typeof createRegistryBackedTestApp>> | undefined;
  285. try {
  286. await expect(
  287. createRegistryBackedTestApp({
  288. env: { ZCODE_STORAGE_DIR: root, ZCODE_SESSION_DB_PATH: join(root, "db.sqlite") },
  289. skipUserConfig: true,
  290. runtimeConfig: { workingDirectory: root, mcp: { enabled: false, servers: {} } },
  291. readSubagentRuntimeConfig: async () => {
  292. throw error;
  293. },
  294. }).then((created) => {
  295. app = created;
  296. return "created";
  297. }),
  298. ).rejects.toBe(error);
  299. expect(fileLoader).not.toHaveBeenCalled();
  300. } finally {
  301. await app?.close?.();
  302. vi.restoreAllMocks();
  303. await rm(root, { recursive: true, force: true });
  304. }
  305. });
  306. });