subagents.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import {
  6. loadPluginAgentTemplates,
  7. resolvePluginAgentProfiles,
  8. loadZCodeAgentProfiles,
  9. } from "../src/subagents.js";
  10. import { loadPluginAgentProfiles } from "./helpers/subagents.js";
  11. function pluginMetadata(input: { enabled?: boolean; id: string; name: string; rootPath: string }) {
  12. return {
  13. commandRootCount: 0,
  14. components: [{ kind: "agent" as const, items: [{ name: "code-architect" }] }],
  15. dataPath: join(input.rootPath, ".data"),
  16. declaredMcpServerNames: [],
  17. enabled: input.enabled ?? true,
  18. id: input.id,
  19. manifestPath: join(input.rootPath, ".claude-plugin", "plugin.json"),
  20. marketplace: "claude-plugins-official",
  21. mcpServerNames: [],
  22. name: input.name,
  23. hookDetails: [],
  24. rootPath: input.rootPath,
  25. skillCount: 0,
  26. skillRootCount: 0,
  27. source: "cache" as const,
  28. version: "0.0.0",
  29. };
  30. }
  31. describe("loadZCodeAgentProfiles", () => {
  32. it("一次读取迁移后的插件覆盖注入规范名和别名,不修改插件文件或串用另一插件覆盖", async () => {
  33. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-selection-"));
  34. try {
  35. const storageRoot = join(root, "state");
  36. const pluginRoot = join(root, "plugin");
  37. const agentId = "plugin:fixture@personal:code-architect";
  38. await mkdir(join(storageRoot, "v2"), { recursive: true });
  39. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  40. const path = join(pluginRoot, "agents", "code-architect.md");
  41. const markdown =
  42. "---\nname: code-architect\ndescription: Architect\nmodel: custom:p:old\nthoughtLevel: low\n---\nPrompt";
  43. await writeFile(path, markdown);
  44. await writeFile(
  45. join(storageRoot, "v2", "agents-state.json"),
  46. JSON.stringify({
  47. pluginAgentModelOverrides: { [agentId]: "custom:builtin%3Azai-coding-plan:GLM" },
  48. pluginAgentThoughtLevelOverrides: { [agentId]: "high" },
  49. }),
  50. );
  51. const state = await loadZCodeAgentProfiles({ storageRoot, workingDirectory: root });
  52. const selection = {
  53. providerId: "account:zai-individual-coding-plan",
  54. modelId: "GLM",
  55. options: { reasoningLevel: "high" },
  56. };
  57. expect(state.pluginAgentModelSelectionOverrides).toEqual({ [agentId]: selection });
  58. const plugins = [
  59. pluginMetadata({ id: "fixture@personal", name: "fixture", rootPath: pluginRoot }),
  60. ];
  61. const templates = loadPluginAgentTemplates({ plugins });
  62. const result = resolvePluginAgentProfiles(
  63. { plugins, modelSelectionOverrides: state.pluginAgentModelSelectionOverrides },
  64. templates,
  65. );
  66. // 保存后只组合已读取模板;清除覆盖恢复插件原值,新增自定义同名定义移除裸名别名。
  67. await rm(path);
  68. const restored = resolvePluginAgentProfiles(
  69. { plugins, reservedProfileNames: ["code-architect"] },
  70. templates,
  71. );
  72. expect(restored.profiles).toHaveLength(1);
  73. expect(restored.profiles[0]?.modelSelection).toEqual({
  74. providerId: "p",
  75. modelId: "old",
  76. options: { reasoningLevel: "low" },
  77. });
  78. await writeFile(path, markdown);
  79. expect(result.profiles.map((p) => [p.name, p.modelSelection])).toEqual([
  80. ["fixture:code-architect", selection],
  81. ["code-architect", selection],
  82. ]);
  83. const modelOnly = { providerId: "p", modelId: "new" };
  84. expect(
  85. loadPluginAgentProfiles({ plugins, modelSelectionOverrides: { [agentId]: modelOnly } })
  86. .profiles[0]?.modelSelection,
  87. ).toEqual(modelOnly);
  88. expect(
  89. loadPluginAgentProfiles({
  90. plugins,
  91. modelSelectionOverrides: { "plugin:other@personal:code-architect": selection },
  92. }).profiles[0]?.modelSelection,
  93. ).toEqual({
  94. providerId: "p",
  95. modelId: "old",
  96. options: { reasoningLevel: "low" },
  97. });
  98. expect(await readFile(path, "utf8")).toBe(markdown);
  99. } finally {
  100. await rm(root, { recursive: true, force: true });
  101. }
  102. });
  103. it("loads only direct user and project Markdown files from beta-compatible roots", async () => {
  104. const root = await mkdtemp(join(tmpdir(), "zcode-subagents-"));
  105. const storageRoot = join(root, "home");
  106. const workingDirectory = join(root, "workspace");
  107. try {
  108. await mkdir(join(storageRoot, "agents"), { recursive: true });
  109. await mkdir(join(workingDirectory, ".zcode", "agents"), { recursive: true });
  110. for (const agentsRoot of [
  111. join(storageRoot, "agents"),
  112. join(workingDirectory, ".zcode", "agents"),
  113. ]) {
  114. await mkdir(join(agentsRoot, "nested"));
  115. await writeFile(
  116. join(agentsRoot, "nested", "ignored.markdown"),
  117. "---\nname: nested-reviewer\ndescription: Nested\n---\nNested prompt",
  118. );
  119. }
  120. await writeFile(
  121. join(storageRoot, "agents", "reviewer.md"),
  122. `---
  123. name: zcode-reviewer
  124. description: 用户级中文审查 agent
  125. ---
  126. 用户级 prompt`,
  127. "utf8",
  128. );
  129. await writeFile(
  130. join(workingDirectory, ".zcode", "agents", "reviewer.md"),
  131. `---
  132. name: zcode-reviewer
  133. description: 项目级中文审查 agent
  134. ---
  135. 项目级 prompt`,
  136. "utf8",
  137. );
  138. const result = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  139. expect(result.diagnostics).toEqual([]);
  140. expect(result.profiles.map((profile) => profile.source)).toEqual(["user", "project"]);
  141. expect(result.profiles.map((profile) => profile.description)).toEqual([
  142. "用户级中文审查 agent",
  143. "项目级中文审查 agent",
  144. ]);
  145. } finally {
  146. await rm(root, { force: true, recursive: true });
  147. }
  148. });
  149. it("ignores project Markdown permissionMode because project profiles are untrusted", async () => {
  150. const root = await mkdtemp(join(tmpdir(), "zcode-subagents-project-permission-"));
  151. const storageRoot = join(root, "home");
  152. const workingDirectory = join(root, "workspace");
  153. try {
  154. await mkdir(join(storageRoot, "agents"), { recursive: true });
  155. await mkdir(join(workingDirectory, ".zcode", "agents"), { recursive: true });
  156. await writeFile(
  157. join(storageRoot, "agents", "trusted.md"),
  158. `---
  159. name: trusted-runner
  160. description: 用户级运行 agent
  161. permissionMode: bypassPermissions
  162. ---
  163. 用户级 prompt`,
  164. "utf8",
  165. );
  166. await writeFile(
  167. join(workingDirectory, ".zcode", "agents", "attacker.md"),
  168. `---
  169. name: attacker-runner
  170. description: 项目级运行 agent
  171. permissionMode: bypassPermissions
  172. ---
  173. 项目级 prompt`,
  174. "utf8",
  175. );
  176. const result = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  177. const userProfile = result.profiles.find((profile) => profile.name === "trusted-runner");
  178. const projectProfile = result.profiles.find((profile) => profile.name === "attacker-runner");
  179. expect(userProfile?.permissionMode).toBe("bypassPermissions");
  180. expect(projectProfile?.permissionMode).toBeUndefined();
  181. } finally {
  182. await rm(root, { force: true, recursive: true });
  183. }
  184. });
  185. it("reports diagnostics for invalid agent Markdown without failing the load", async () => {
  186. const root = await mkdtemp(join(tmpdir(), "zcode-subagents-invalid-"));
  187. const storageRoot = join(root, "home");
  188. const workingDirectory = join(root, "workspace");
  189. try {
  190. await mkdir(join(storageRoot, "agents"), { recursive: true });
  191. await writeFile(
  192. join(storageRoot, "agents", "invalid.md"),
  193. `---
  194. name: missing-description
  195. ---
  196. prompt`,
  197. "utf8",
  198. );
  199. const result = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  200. expect(result.profiles).toEqual([]);
  201. expect(result.diagnostics).toHaveLength(1);
  202. expect(result.diagnostics[0]?.code).toBe("agent_missing_required_frontmatter");
  203. } finally {
  204. await rm(root, { force: true, recursive: true });
  205. }
  206. });
  207. it("skips disabled user Markdown profiles from shared subagent state", async () => {
  208. const root = await mkdtemp(join(tmpdir(), "zcode-subagents-disabled-"));
  209. const storageRoot = join(root, "home");
  210. const workingDirectory = join(root, "workspace");
  211. try {
  212. await mkdir(join(storageRoot, "agents"), { recursive: true });
  213. await mkdir(join(storageRoot, "v2"), { recursive: true });
  214. await writeFile(
  215. join(storageRoot, "agents", "reviewer.md"),
  216. `---
  217. name: zcode-reviewer
  218. description: 用户级中文审查 agent
  219. ---
  220. 用户级 prompt`,
  221. "utf8",
  222. );
  223. await writeFile(
  224. join(storageRoot, "agents", "runner.md"),
  225. `---
  226. name: zcode-runner
  227. description: 用户级运行 agent
  228. ---
  229. 用户级 prompt`,
  230. "utf8",
  231. );
  232. await writeFile(
  233. join(storageRoot, "v2", "agents-state.json"),
  234. JSON.stringify({ disabledAgentIds: ["user:user:zcode-reviewer"] }),
  235. "utf8",
  236. );
  237. const result = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  238. expect(result.diagnostics).toEqual([]);
  239. expect(result.profiles.map((profile) => profile.name)).toEqual(["zcode-runner"]);
  240. } finally {
  241. await rm(root, { force: true, recursive: true });
  242. }
  243. });
  244. it("loads structured built-in model selections from shared subagent state", async () => {
  245. const root = await mkdtemp(join(tmpdir(), "zcode-subagents-built-in-models-"));
  246. const storageRoot = join(root, "home");
  247. const workingDirectory = join(root, "workspace");
  248. try {
  249. await mkdir(join(storageRoot, "v2"), { recursive: true });
  250. await writeFile(
  251. join(storageRoot, "v2", "agents-state.json"),
  252. JSON.stringify({
  253. builtInModelSelectionOverrides: {
  254. Explore: {
  255. providerId: "custom-openai",
  256. modelId: "glm-5.2",
  257. options: { reasoningLevel: "max" },
  258. },
  259. "general-purpose": {
  260. providerId: "custom-openai",
  261. modelId: "gpt-5.4",
  262. options: { reasoningLevel: "high" },
  263. },
  264. ignored: {
  265. providerId: "custom-openai",
  266. modelId: "ignored",
  267. },
  268. },
  269. disabledAgentIds: [],
  270. }),
  271. "utf8",
  272. );
  273. const result = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  274. expect(result.diagnostics).toEqual([]);
  275. expect(result.profiles).toEqual([]);
  276. expect(result.builtInModelSelectionOverrides).toEqual({
  277. Explore: {
  278. providerId: "custom-openai",
  279. modelId: "glm-5.2",
  280. options: { reasoningLevel: "max" },
  281. },
  282. "general-purpose": {
  283. providerId: "custom-openai",
  284. modelId: "gpt-5.4",
  285. options: { reasoningLevel: "high" },
  286. },
  287. });
  288. } finally {
  289. await rm(root, { force: true, recursive: true });
  290. }
  291. });
  292. });
  293. describe("loadPluginAgentProfiles", () => {
  294. it("SA97-09:用户迁移和重新加载不改项目/插件文件或其显式旧身份", async () => {
  295. const root = await mkdtemp(join(tmpdir(), "zcode-subagent-scope-migration-"));
  296. const storageRoot = join(root, "storage");
  297. const workingDirectory = join(root, "workspace");
  298. const pluginRoot = join(root, "plugin");
  299. const paths = [
  300. join(storageRoot, "agents", "code-architect.md"),
  301. join(workingDirectory, ".zcode", "agents", "code-architect.md"),
  302. join(pluginRoot, "agents", "code-architect.md"),
  303. ];
  304. const markdown =
  305. "---\r\nname: code-architect\r\ndescription: review\r\n# 保留备注\r\nmodel: builtin:zai-coding-plan/GLM\r\nthoughtLevel: high\r\n---\r\n正文 builtin:zai-coding-plan/GLM\r\n";
  306. try {
  307. for (const directory of [
  308. join(storageRoot, "agents"),
  309. join(workingDirectory, ".zcode", "agents"),
  310. join(pluginRoot, "agents"),
  311. ]) {
  312. await mkdir(directory, { recursive: true });
  313. }
  314. for (const path of paths) await writeFile(path, markdown);
  315. for (let load = 0; load < 2; load++) {
  316. const local = await loadZCodeAgentProfiles({ storageRoot, workingDirectory });
  317. const plugins = loadPluginAgentProfiles({
  318. plugins: [pluginMetadata({ id: "scope-test", name: "scope-test", rootPath: pluginRoot })],
  319. });
  320. expect(local.diagnostics).toEqual([]);
  321. expect(plugins.diagnostics).toEqual([]);
  322. expect(
  323. local.profiles.find((profile) => profile.source === "user")?.modelSelection?.providerId,
  324. ).toBe("account:zai-individual-coding-plan");
  325. expect(
  326. local.profiles.find((profile) => profile.source === "project")?.modelSelection
  327. ?.providerId,
  328. ).toBe("builtin:zai-coding-plan");
  329. for (const profile of plugins.profiles)
  330. expect(profile.modelSelection).toEqual({
  331. providerId: "builtin:zai-coding-plan",
  332. modelId: "GLM",
  333. options: { reasoningLevel: "high" },
  334. });
  335. expect(plugins.profiles.length).toBeGreaterThan(0);
  336. expect(await readFile(paths[0]!, "utf8")).toBe(
  337. markdown.replace(
  338. "model: builtin:zai-coding-plan",
  339. "model: account:zai-individual-coding-plan",
  340. ),
  341. );
  342. for (const path of paths.slice(1)) expect(await readFile(path, "utf8")).toBe(markdown);
  343. }
  344. } finally {
  345. await rm(root, { force: true, recursive: true });
  346. }
  347. });
  348. it("loads enabled plugin agents as runtime profiles", async () => {
  349. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-subagents-"));
  350. const pluginRoot = join(root, "feature-dev");
  351. try {
  352. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  353. await writeFile(
  354. join(pluginRoot, "agents", "code-architect.md"),
  355. `---
  356. name: code-architect
  357. description: 设计功能架构
  358. tools:
  359. - Read
  360. ---
  361. 架构 prompt`,
  362. "utf8",
  363. );
  364. const result = loadPluginAgentProfiles({
  365. plugins: [
  366. pluginMetadata({
  367. id: "feature-dev@claude-plugins-official",
  368. name: "feature-dev",
  369. rootPath: pluginRoot,
  370. }),
  371. ],
  372. });
  373. expect(result.diagnostics).toEqual([]);
  374. expect(result.profiles.map((profile) => profile.name)).toEqual([
  375. "feature-dev:code-architect",
  376. "code-architect",
  377. ]);
  378. expect(result.profiles[0]).toMatchObject({
  379. source: "user",
  380. tools: ["Read"],
  381. systemPrompt: "架构 prompt",
  382. });
  383. } finally {
  384. await rm(root, { force: true, recursive: true });
  385. }
  386. });
  387. it("applies plugin agent model overrides from shared subagent state to canonical and alias profiles", async () => {
  388. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-subagents-overrides-"));
  389. const storageRoot = join(root, "home");
  390. const pluginRoot = join(root, "document-skills");
  391. try {
  392. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  393. await mkdir(join(storageRoot, "v2"), { recursive: true });
  394. await writeFile(
  395. join(pluginRoot, "agents", "code-architect.md"),
  396. `---
  397. name: code-architect
  398. description: 插件默认模型
  399. model: custom:custom-openai:gpt-5.4
  400. thoughtLevel: low
  401. ---
  402. 架构 prompt`,
  403. "utf8",
  404. );
  405. await writeFile(
  406. join(storageRoot, "v2", "agents-state.json"),
  407. JSON.stringify({
  408. pluginAgentModelOverrides: {
  409. "plugin:document-skills@zcode-plugins-official:code-architect":
  410. "custom:custom-openai:glm-5.2",
  411. "plugin:other@zcode-plugins-official:code-architect": "custom:custom-openai:ignored",
  412. },
  413. pluginAgentThoughtLevelOverrides: {
  414. "plugin:document-skills@zcode-plugins-official:code-architect": "high",
  415. },
  416. }),
  417. "utf8",
  418. );
  419. const plugins = [
  420. pluginMetadata({
  421. id: "document-skills@zcode-plugins-official",
  422. name: "document-skills",
  423. rootPath: pluginRoot,
  424. }),
  425. ];
  426. const state = await loadZCodeAgentProfiles({ storageRoot, workingDirectory: root });
  427. const overridden = loadPluginAgentProfiles({
  428. plugins,
  429. modelSelectionOverrides: state.pluginAgentModelSelectionOverrides,
  430. });
  431. const selection = {
  432. providerId: "custom-openai",
  433. modelId: "glm-5.2",
  434. options: { reasoningLevel: "high" },
  435. };
  436. // 规范名与裸名别名是同一文件的两个调用入口,必须共享同一覆盖。
  437. expect(overridden.profiles.map((profile) => [profile.name, profile.modelSelection])).toEqual([
  438. ["document-skills:code-architect", selection],
  439. ["code-architect", selection],
  440. ]);
  441. // 未传入覆盖时保留 md 声明;插件 loader 不单独读取 state 文件。
  442. const untouched = loadPluginAgentProfiles({ plugins });
  443. expect(untouched.profiles[0]).toMatchObject({
  444. modelSelection: {
  445. providerId: "custom-openai",
  446. modelId: "gpt-5.4",
  447. options: { reasoningLevel: "low" },
  448. },
  449. });
  450. // 覆盖 model 但未指定 thoughtLevel 时,不能沿用 md 里另一模型的档位。
  451. await writeFile(
  452. join(storageRoot, "v2", "agents-state.json"),
  453. JSON.stringify({
  454. pluginAgentModelOverrides: {
  455. "plugin:document-skills@zcode-plugins-official:code-architect":
  456. "custom:custom-openai:glm-5.2",
  457. },
  458. }),
  459. "utf8",
  460. );
  461. const modelOnlyState = await loadZCodeAgentProfiles({ storageRoot, workingDirectory: root });
  462. const modelOnly = loadPluginAgentProfiles({
  463. plugins,
  464. modelSelectionOverrides: modelOnlyState.pluginAgentModelSelectionOverrides,
  465. });
  466. expect(modelOnly.profiles[0]?.modelSelection).toEqual({
  467. providerId: "custom-openai",
  468. modelId: "glm-5.2",
  469. });
  470. } finally {
  471. await rm(root, { force: true, recursive: true });
  472. }
  473. });
  474. it("skips disabled plugin agents and ambiguous bare aliases", async () => {
  475. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-subagents-ambiguous-"));
  476. const firstRoot = join(root, "feature-dev");
  477. const secondRoot = join(root, "pr-review-toolkit");
  478. try {
  479. for (const pluginRoot of [firstRoot, secondRoot]) {
  480. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  481. await writeFile(
  482. join(pluginRoot, "agents", "code-architect.md"),
  483. `---
  484. name: code-architect
  485. description: 设计功能架构
  486. ---
  487. architect prompt`,
  488. "utf8",
  489. );
  490. }
  491. const result = loadPluginAgentProfiles({
  492. plugins: [
  493. pluginMetadata({
  494. id: "feature-dev@claude-plugins-official",
  495. name: "feature-dev",
  496. rootPath: firstRoot,
  497. }),
  498. pluginMetadata({
  499. id: "pr-review-toolkit@claude-plugins-official",
  500. name: "pr-review-toolkit",
  501. rootPath: secondRoot,
  502. }),
  503. pluginMetadata({
  504. enabled: false,
  505. id: "disabled@claude-plugins-official",
  506. name: "disabled",
  507. rootPath: join(root, "disabled"),
  508. }),
  509. ],
  510. });
  511. expect(result.profiles.map((profile) => profile.name)).toEqual([
  512. "feature-dev:code-architect",
  513. "pr-review-toolkit:code-architect",
  514. ]);
  515. expect(result.diagnostics.map((diagnostic) => diagnostic.code)).toEqual([
  516. "agent_ambiguous_name",
  517. "agent_ambiguous_name",
  518. ]);
  519. } finally {
  520. await rm(root, { force: true, recursive: true });
  521. }
  522. });
  523. });