catalog.test.ts 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { tmpdir } from "node:os";
  4. import { fileURLToPath } from "node:url";
  5. import { resolveAgentCapabilities } from "@mavis/config";
  6. import type {
  7. PromptReadSnapshot,
  8. PromptSnapshotSource,
  9. } from "@mavis/agent-runtime";
  10. import { afterEach, describe, expect, it, vi } from "vitest";
  11. import {
  12. BuiltinAgentCatalog,
  13. canonicalBuiltinName,
  14. legacyNamesFor,
  15. resolveCanonicalCapabilities,
  16. } from "../../../../src/service/agent/builtin/catalog.js";
  17. import type {
  18. PromptFileReader,
  19. PromptReadContext,
  20. } from "../../../../src/service/prompt-config/index.js";
  21. const fixtureDirectories: string[] = [];
  22. const markdownLinkPolicy =
  23. "- Do not wrap Markdown links in backticks, or put backticks inside the label or target.\n";
  24. function extractCitationSection(prompt: string): string {
  25. const start = prompt.indexOf("## Citations");
  26. if (start < 0) return "";
  27. const endMarker =
  28. "Do not cite unused calls or unsupported claims, invent metadata, output bare parenthesized links, or add trailing source/reference lists.";
  29. const end = prompt.indexOf(endMarker, start);
  30. if (end < 0) return "";
  31. return prompt.slice(start, end + endMarker.length).trim();
  32. }
  33. afterEach(async () => {
  34. vi.restoreAllMocks();
  35. await Promise.all(
  36. fixtureDirectories
  37. .splice(0)
  38. .map((directory) => rm(directory, { recursive: true, force: true })),
  39. );
  40. });
  41. function promptReadContext(directory: string): PromptReadContext {
  42. return {
  43. scopeId: "scope",
  44. subject: "anonymous",
  45. version: directory,
  46. cacheId: directory,
  47. directory,
  48. storageMode: "plaintext",
  49. keyVersion: "desktop-v1",
  50. };
  51. }
  52. function promptFiles(version: string): Readonly<Record<string, string>> {
  53. return {
  54. "worker/PERSONA.md": `${version} persona`,
  55. "worker/system-prompt.md.hbs": `${version} system`,
  56. "_default/prompt-base-all.md.hbs": `${version} base`,
  57. "_default/prompt-base-windows.md.hbs": "",
  58. "_default/prompt-base-worker.md.hbs": `${version} worker base`,
  59. "_default/prompt-session-root.md.hbs": `${version} root surface`,
  60. };
  61. }
  62. function promptReader(
  63. byDirectory: Readonly<Record<string, Readonly<Record<string, string>>>>,
  64. ): PromptFileReader & { readonly read: ReturnType<typeof vi.fn> } {
  65. return {
  66. read: vi.fn(
  67. async (context: PromptReadContext, relativePath: string) =>
  68. byDirectory[context.directory]?.[relativePath],
  69. ),
  70. };
  71. }
  72. describe("BuiltinAgentCatalog", () => {
  73. it("keeps managed Prompt keys POSIX-normalized on Windows", async () => {
  74. const root = await mkdtemp(
  75. join(tmpdir(), "local-runtime-v2-agent-windows-prompt-"),
  76. );
  77. fixtureDirectories.push(root);
  78. await mkdir(join(root, "worker"), { recursive: true });
  79. await writeFile(join(root, "builtin-agents.json"), '["worker"]');
  80. await writeFile(join(root, "worker", "PERSONA.md"), "Static identity only");
  81. const snapshot = {} as PromptReadSnapshot;
  82. const source: PromptSnapshotSource = {
  83. capture: vi.fn(async () => snapshot),
  84. captureBuiltin: vi.fn(async () => snapshot),
  85. read: vi.fn(async (_snapshot, key) => ({
  86. kind: "found" as const,
  87. content: key,
  88. })),
  89. };
  90. vi.spyOn(process, "platform", "get").mockReturnValue("win32");
  91. await new BuiltinAgentCatalog({ assetsDir: root }).render({
  92. agentName: "worker",
  93. surface: "interactive",
  94. appMode: "coding",
  95. locale: "en-US",
  96. promptChannel: "online",
  97. capabilities: resolveAgentCapabilities({ tools: ["bash"] }),
  98. promptReadContext: { source, snapshot },
  99. });
  100. const keys = vi.mocked(source.read).mock.calls.map(([, key]) => key);
  101. expect(keys).toContain("_default/prompt-base-windows.md.hbs");
  102. expect(keys).toContain("worker/features/delegation.md.hbs");
  103. expect(keys.every((key) => !key.includes("\\"))).toBe(true);
  104. });
  105. it("continues locale fallback on a missing optional candidate and rejects an invalid managed template", async () => {
  106. const root = await mkdtemp(
  107. join(tmpdir(), "local-runtime-v2-agent-locale-fallback-"),
  108. );
  109. fixtureDirectories.push(root);
  110. await mkdir(join(root, "worker"), { recursive: true });
  111. await writeFile(join(root, "builtin-agents.json"), '["worker"]');
  112. await writeFile(join(root, "worker", "PERSONA.md"), "static metadata");
  113. const snapshot = {} as PromptReadSnapshot;
  114. const source: PromptSnapshotSource = {
  115. capture: vi.fn(async () => snapshot),
  116. captureBuiltin: vi.fn(async () => snapshot),
  117. read: vi.fn(async (_snapshot, key) => {
  118. if (key === "worker/PERSONA-en.md") return { kind: "missing" as const };
  119. if (key === "worker/PERSONA.md")
  120. return { kind: "found" as const, content: "remote persona" };
  121. if (key === "worker/system-prompt.md.hbs")
  122. return { kind: "invalid" as const };
  123. return { kind: "missing" as const };
  124. }),
  125. };
  126. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  127. const input = {
  128. agentName: "worker",
  129. surface: "interactive" as const,
  130. appMode: "coding" as const,
  131. locale: "en-US",
  132. promptChannel: "online" as const,
  133. capabilities: resolveAgentCapabilities(),
  134. promptReadContext: { source, snapshot },
  135. };
  136. await expect(catalog.readCanonicalContent(input)).rejects.toThrow(
  137. "worker/system-prompt.md.hbs",
  138. );
  139. expect(source.read).toHaveBeenCalledWith(snapshot, "worker/PERSONA-en.md");
  140. expect(source.read).toHaveBeenCalledWith(snapshot, "worker/PERSONA.md");
  141. });
  142. it("reads every built-in template from the immutable context supplied for one render", async () => {
  143. const root = await mkdtemp(
  144. join(tmpdir(), "local-runtime-v2-agent-prompt-context-"),
  145. );
  146. fixtureDirectories.push(root);
  147. await mkdir(join(root, "worker"), { recursive: true });
  148. await writeFile(join(root, "builtin-agents.json"), '["worker"]');
  149. await writeFile(join(root, "worker", "PERSONA.md"), "Static identity only");
  150. const v1 = promptReadContext("version-1");
  151. const v2 = promptReadContext("version-2");
  152. const reader = promptReader({
  153. "version-1": promptFiles("v1"),
  154. "version-2": promptFiles("v2"),
  155. });
  156. const catalog = new BuiltinAgentCatalog({
  157. assetsDir: root,
  158. promptFileReader: reader,
  159. });
  160. const input = {
  161. agentName: "worker",
  162. surface: "interactive" as const,
  163. appMode: "coding" as const,
  164. locale: "en-US",
  165. promptChannel: "online" as const,
  166. capabilities: resolveAgentCapabilities(),
  167. };
  168. const first = await catalog.render({ ...input, promptReadContext: v1 });
  169. const second = await catalog.render({ ...input, promptReadContext: v2 });
  170. expect(first).toMatchObject({
  171. persona: "v1 persona",
  172. corePrompt: "v1 system\n\nv1 base\n\nv1 worker base",
  173. surfacePrompt: "v1 root surface",
  174. });
  175. expect(second).toMatchObject({
  176. persona: "v2 persona",
  177. corePrompt: "v2 system\n\nv2 base\n\nv2 worker base",
  178. surfacePrompt: "v2 root surface",
  179. });
  180. expect(
  181. reader.read.mock.calls.filter(([context]) => context === v1),
  182. ).not.toHaveLength(0);
  183. expect(
  184. reader.read.mock.calls.filter(([context]) => context === v2),
  185. ).not.toHaveLength(0);
  186. expect(
  187. reader.read.mock.calls
  188. .filter(([context]) => context === v1)
  189. .every(([context]) => context === v1),
  190. ).toBe(true);
  191. });
  192. });
  193. describe("BuiltinAgentCatalog recoverable deletion guidance", () => {
  194. it("teaches Mavis to use the runtime-owned recoverable deletion path", async () => {
  195. const assetsDir = resolve(
  196. dirname(fileURLToPath(import.meta.url)),
  197. "../../../../assets/agents",
  198. );
  199. const catalog = new BuiltinAgentCatalog({ assetsDir });
  200. const common = {
  201. agentName: "mavis",
  202. surface: "interactive" as const,
  203. locale: "en-US",
  204. promptChannel: "online" as const,
  205. };
  206. for (const appMode of ["coding", "work"] as const) {
  207. const rendered = await catalog.render({
  208. ...common,
  209. appMode,
  210. capabilities: resolveAgentCapabilities({ tools: ["bash"] }),
  211. });
  212. expect(rendered.corePrompt).toContain("## Recoverable Deletion");
  213. expect(rendered.corePrompt).toContain("activeDataDir");
  214. expect(rendered.corePrompt).toContain("/bin/mavis-trash");
  215. expect(rendered.corePrompt).toMatch(
  216. /never guess it or use\s+bare `mavis-trash`/u,
  217. );
  218. expect(rendered.corePrompt).toMatch(
  219. /never fall back to permanent\s+deletion/u,
  220. );
  221. }
  222. const withoutBash = await catalog.render({
  223. ...common,
  224. appMode: "coding",
  225. capabilities: resolveAgentCapabilities({ tools: [] }),
  226. });
  227. expect(withoutBash.corePrompt).not.toContain("## Recoverable Deletion");
  228. });
  229. });
  230. describe("BuiltinAgentCatalog Explore composition", () => {
  231. it("keeps Explore Bash boundaries in V1 and V2 assets and task reuse in V1 delegation", async () => {
  232. const assetsDir = resolve(
  233. dirname(fileURLToPath(import.meta.url)),
  234. "../../../../assets/agents",
  235. );
  236. const [v1ExplorePrompt, v2ExplorePrompt, delegation] = await Promise.all([
  237. readFile(join(assetsDir, "explore", "system-prompt.md.hbs"), "utf8"),
  238. readFile(join(assetsDir, "_v2", "explore.md.hbs"), "utf8"),
  239. readFile(
  240. join(assetsDir, "mavis", "features", "delegation.md.hbs"),
  241. "utf8",
  242. ),
  243. ]);
  244. for (const explorePrompt of [v1ExplorePrompt, v2ExplorePrompt]) {
  245. expect(explorePrompt).toContain("Read-only Bash");
  246. expect(explorePrompt).toContain(
  247. "Use `bash` only to inspect existing code or Git state.",
  248. );
  249. expect(explorePrompt).toContain(
  250. "Do not modify files, Git\nstate, or external systems",
  251. );
  252. expect(explorePrompt).toContain(
  253. "Explore does not have `task_output`, so do not use `run_in_background` with\n`bash`.",
  254. );
  255. }
  256. expect(delegation).toContain(
  257. "`bash` for read-only Git and code investigation.",
  258. );
  259. expect(delegation).toContain(
  260. "reuse the existing task with `task_append` instead of opening a\nnew task.",
  261. );
  262. });
  263. });
  264. describe("BuiltinAgentCatalog composition", () => {
  265. it("keeps local evidence rules and citations without a web-search system section", async () => {
  266. const assetsDir = resolve(
  267. dirname(fileURLToPath(import.meta.url)),
  268. "../../../../assets/agents",
  269. );
  270. const catalog = new BuiltinAgentCatalog({ assetsDir });
  271. const rendered = await catalog.render({
  272. agentName: "mavis",
  273. surface: "interactive",
  274. promptMode: "work",
  275. appMode: "work",
  276. locale: "zh-CN",
  277. promptChannel: "online",
  278. capabilities: resolveAgentCapabilities({ features: { webSearch: true } }),
  279. });
  280. const citationSection = extractCitationSection(rendered.corePrompt);
  281. expect(rendered.corePrompt).not.toContain("Factual Freshness And Search");
  282. expect(rendered.corePrompt).not.toContain(
  283. "Prefer primary or authoritative sources",
  284. );
  285. expect(rendered.corePrompt).toContain(
  286. "For unfamiliar project-specific concepts, search the workspace with `grep` or `glob` first.",
  287. );
  288. expect(rendered.corePrompt).toContain(
  289. "unfamiliarity alone does not prove non-existence",
  290. );
  291. expect(citationSection).toContain("Web: use the exact result/final URL.");
  292. expect(citationSection).toContain(
  293. "Do not cite unused calls or unsupported claims",
  294. );
  295. expect(citationSection).toContain(
  296. "Place citations at sentence granularity; do not group multiple citations at the end of a paragraph.",
  297. );
  298. expect(citationSection).toContain(
  299. "For tables, use a source column per row or a source line below the table.",
  300. );
  301. expect(rendered.corePrompt).not.toContain("contextual Markdown link");
  302. expect(rendered.corePrompt).not.toContain("Do not emit favicon");
  303. expect(rendered.corePrompt).not.toContain("## Tool source citations");
  304. });
  305. it("avoids duplicating the shared Mavis mode layer while retaining Windows and worker bases", async () => {
  306. const root = await mkdtemp(
  307. join(tmpdir(), "local-runtime-v2-agent-shared-base-"),
  308. );
  309. fixtureDirectories.push(root);
  310. await mkdir(join(root, "mavis", "modes", "coding", "online"), {
  311. recursive: true,
  312. });
  313. await mkdir(join(root, "worker"), { recursive: true });
  314. await mkdir(join(root, "_default"), { recursive: true });
  315. await writeFile(join(root, "builtin-agents.json"), '["mavis", "worker"]');
  316. await writeFile(
  317. join(root, "mavis", "modes", "coding", "online", "SYSTEM.md.hbs"),
  318. "## Harness\nMavis system",
  319. );
  320. await writeFile(
  321. join(root, "mavis", "modes", "coding", "online", "PERSONA.md"),
  322. "Mavis persona",
  323. );
  324. await writeFile(join(root, "worker", "PERSONA.md"), "Worker persona");
  325. await writeFile(join(root, "worker", "system-prompt.md"), "Worker system");
  326. await writeFile(
  327. join(root, "_default", "prompt-base-all.md"),
  328. "## Harness\nshared base",
  329. );
  330. await writeFile(
  331. join(root, "_default", "prompt-base-windows.md"),
  332. "windows base",
  333. );
  334. await writeFile(
  335. join(root, "_default", "prompt-base-worker.md"),
  336. "worker base",
  337. );
  338. await writeFile(
  339. join(root, "_default", "prompt-session-root.md"),
  340. "root session",
  341. );
  342. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  343. vi.spyOn(process, "platform", "get").mockReturnValue("win32");
  344. const common = {
  345. surface: "interactive" as const,
  346. appMode: "coding" as const,
  347. locale: "en-US",
  348. promptChannel: "online" as const,
  349. capabilities: resolveAgentCapabilities({
  350. tools: ["bash"],
  351. features: { mavis: false, delegation: false, webSearch: false },
  352. }),
  353. };
  354. const mavis = await catalog.render({ ...common, agentName: "mavis" });
  355. expect(mavis.corePrompt).toBe("## Harness\nMavis system\n\nwindows base");
  356. expect(mavis.corePrompt.match(/^## Harness$/gmu)).toHaveLength(1);
  357. await expect(
  358. catalog.render({ ...common, agentName: "worker" }),
  359. ).resolves.toMatchObject({
  360. corePrompt:
  361. "Worker system\n\n## Harness\nshared base\n\nwindows base\n\nworker base",
  362. });
  363. });
  364. it("honors an empty Windows template without reviving fallback content", async () => {
  365. const root = await mkdtemp(
  366. join(tmpdir(), "local-runtime-v2-agent-windows-base-"),
  367. );
  368. fixtureDirectories.push(root);
  369. await mkdir(join(root, "worker"), { recursive: true });
  370. await mkdir(join(root, "_default"), { recursive: true });
  371. await writeFile(join(root, "builtin-agents.json"), '["worker"]');
  372. await writeFile(join(root, "worker", "PERSONA.md"), "Worker persona");
  373. await writeFile(join(root, "worker", "system-prompt.md"), "Worker system");
  374. await writeFile(
  375. join(root, "_default", "prompt-base-all.md"),
  376. "shared base",
  377. );
  378. await writeFile(
  379. join(root, "_default", "prompt-base-worker.md"),
  380. "worker base",
  381. );
  382. await writeFile(
  383. join(root, "_default", "prompt-base-windows.md"),
  384. "windows base",
  385. );
  386. await writeFile(join(root, "_default", "prompt-base-windows.md.hbs"), "");
  387. vi.spyOn(process, "platform", "get").mockReturnValue("win32");
  388. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  389. const common = {
  390. agentName: "worker",
  391. surface: "interactive" as const,
  392. appMode: "coding" as const,
  393. locale: "en-US",
  394. promptChannel: "online" as const,
  395. };
  396. await expect(
  397. catalog.render({
  398. ...common,
  399. capabilities: resolveAgentCapabilities({ tools: ["bash"] }),
  400. }),
  401. ).resolves.toMatchObject({
  402. corePrompt: "Worker system\n\nshared base\n\nworker base",
  403. });
  404. await expect(
  405. catalog.render({
  406. ...common,
  407. capabilities: resolveAgentCapabilities({ tools: [] }),
  408. }),
  409. ).resolves.toMatchObject({
  410. corePrompt: "Worker system\n\nshared base\n\nworker base",
  411. });
  412. });
  413. });
  414. describe("BuiltinAgentCatalog localized assets", () => {
  415. it("uses English built-in personas while keeping greeting assets localized", async () => {
  416. const root = await mkdtemp(
  417. join(tmpdir(), "local-runtime-v2-agent-assets-"),
  418. );
  419. fixtureDirectories.push(root);
  420. await mkdir(join(root, "explore", "features"), { recursive: true });
  421. await mkdir(join(root, "_default"), { recursive: true });
  422. await writeFile(join(root, "builtin-agents.json"), '["explore"]');
  423. await writeFile(
  424. join(root, "explore", "PERSONA.md"),
  425. "---\ndisplay_name: Explore\ndescription: Explore agent\navatar: explore.png\n---\nExplore EN",
  426. );
  427. await writeFile(
  428. join(root, "explore", "PERSONA-zh.md"),
  429. "---\ndisplay_name: 探索\n---\n探索",
  430. );
  431. await writeFile(
  432. join(root, "explore", "system-prompt.md.hbs"),
  433. "System {{features.mavis}}",
  434. );
  435. await writeFile(
  436. join(root, "explore", "agent.md"),
  437. "---\nfeatures:\n mavis: true\n delegation: true\n webSearch: false\n---\n",
  438. );
  439. await writeFile(
  440. join(root, "explore", "features", "delegation.md.hbs"),
  441. "Delegation {{features.delegation}}",
  442. );
  443. await writeFile(
  444. join(root, "_default", "prompt-session-root.md.hbs"),
  445. "Root {{surface.interactive}}",
  446. );
  447. await writeFile(
  448. join(root, "_default", "prompt-session-branch.md.hbs"),
  449. "Branch {{surface.taskChild}}",
  450. );
  451. await writeFile(
  452. join(root, "_default", "prompt-base-all.md"),
  453. "shared base",
  454. );
  455. await writeFile(
  456. join(root, "_default", "prompt-base-worker.md"),
  457. "worker base",
  458. );
  459. // Include the required platform layer without changing this fixture's expected prose.
  460. await writeFile(join(root, "_default", "prompt-base-windows.md.hbs"), "");
  461. await writeFile(join(root, "greeting-zh.md"), "你好");
  462. await writeFile(join(root, "greeting.md"), "Hello");
  463. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  464. await expect(catalog.resolveAssetsDir()).resolves.toBe(root);
  465. expect(canonicalBuiltinName(" MAIN ")).toBe("mavis");
  466. expect(legacyNamesFor("explore")).toEqual([]);
  467. await expect(catalog.hasBuiltin("EXPLORE")).resolves.toBe(true);
  468. // A detached historic built-in is no longer an alias of a canonical role.
  469. await expect(catalog.hasBuiltin("general")).resolves.toBe(false);
  470. await expect(catalog.hasBuiltin("missing")).resolves.toBe(false);
  471. await expect(catalog.listDefinitions()).resolves.toEqual([
  472. expect.objectContaining({
  473. name: "explore",
  474. legacyNames: [],
  475. identity: {
  476. displayName: "Explore",
  477. description: "Explore agent",
  478. avatar: "explore.png",
  479. },
  480. capabilityOverride: expect.objectContaining({
  481. features: expect.any(Object),
  482. }),
  483. }),
  484. ]);
  485. await expect(catalog.readDefinition("missing")).rejects.toThrow(
  486. /not in the roster/u,
  487. );
  488. const rendered = await catalog.render({
  489. agentName: "EXPLORE",
  490. surface: "interactive",
  491. appMode: "coding",
  492. locale: "zh-CN",
  493. promptChannel: "online",
  494. capabilities: resolveAgentCapabilities(),
  495. memoryEnabled: false,
  496. dataDirToken: "/data/token",
  497. });
  498. expect(rendered).toMatchObject({
  499. persona: "Explore EN",
  500. corePrompt: "System true\n\nshared base\n\nworker base",
  501. surfacePrompt: "Root true",
  502. assetAgentName: "explore",
  503. identity: { displayName: "Explore" },
  504. });
  505. await expect(
  506. catalog.readCanonicalContent({
  507. agentName: "EXPLORE",
  508. surface: "interactive",
  509. appMode: "coding",
  510. locale: "zh-CN",
  511. promptChannel: "online",
  512. capabilities: resolveAgentCapabilities(),
  513. memoryEnabled: false,
  514. dataDirToken: "/data/token",
  515. }),
  516. ).resolves.toMatchObject({
  517. persona: "Explore EN",
  518. systemPrompt: "System true",
  519. });
  520. await expect(
  521. catalog.render({
  522. agentName: "explore",
  523. surface: "task-child",
  524. appMode: "coding",
  525. locale: "en-US",
  526. promptChannel: "online",
  527. capabilities: resolveAgentCapabilities(),
  528. }),
  529. ).resolves.toMatchObject({ surfacePrompt: "Branch true" });
  530. await expect(catalog.readGreetingTemplate("zh-CN")).resolves.toBe("你好");
  531. await expect(catalog.readGreetingTemplate("en-US")).resolves.toBe("Hello");
  532. });
  533. });
  534. describe("BuiltinAgentCatalog validation and fallback rendering", () => {
  535. it("uses Handlebars strict rendering to reject unknown variables", async () => {
  536. const root = await mkdtemp(
  537. join(tmpdir(), "local-runtime-v2-agent-template-"),
  538. );
  539. fixtureDirectories.push(root);
  540. await mkdir(join(root, "explore"), { recursive: true });
  541. await mkdir(join(root, "_default"), { recursive: true });
  542. await writeFile(join(root, "builtin-agents.json"), '["explore"]');
  543. await writeFile(
  544. join(root, "explore", "PERSONA.md"),
  545. "---\ndisplay_name: Explore\n---\nExplore",
  546. );
  547. await writeFile(
  548. join(root, "explore", "system-prompt.md.hbs"),
  549. "{{unknownVariable}}",
  550. );
  551. await writeFile(
  552. join(root, "_default", "prompt-session-root.md.hbs"),
  553. "{{surface.interactive}}",
  554. );
  555. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  556. await expect(
  557. catalog.render({
  558. agentName: "explore",
  559. surface: "interactive",
  560. appMode: "coding",
  561. locale: "en-US",
  562. promptChannel: "online",
  563. capabilities: resolveAgentCapabilities(),
  564. }),
  565. ).rejects.toThrow(/unknownVariable|not defined/u);
  566. });
  567. it("handles plain persona assets, missing optional templates, and fallback greetings", async () => {
  568. const root = await mkdtemp(
  569. join(tmpdir(), "local-runtime-v2-agent-assets-minimal-"),
  570. );
  571. fixtureDirectories.push(root);
  572. await mkdir(join(root, "explore"), { recursive: true });
  573. await mkdir(join(root, "_default"), { recursive: true });
  574. await writeFile(join(root, "builtin-agents.json"), '["explore"]');
  575. await writeFile(
  576. join(root, "explore", "PERSONA.md"),
  577. "Plain persona without frontmatter",
  578. );
  579. await writeFile(
  580. join(root, "_default", "prompt-base-all.md"),
  581. "shared base",
  582. );
  583. await writeFile(
  584. join(root, "_default", "prompt-base-worker.md"),
  585. "worker base",
  586. );
  587. // Include the required platform layer without changing this fixture's expected prose.
  588. await writeFile(join(root, "_default", "prompt-base-windows.md.hbs"), "");
  589. await writeFile(
  590. join(root, "_default", "prompt-session-root.md.hbs"),
  591. "fallback root",
  592. );
  593. await writeFile(join(root, "greeting.md"), "generic greeting");
  594. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  595. await expect(catalog.readDefinition("explore")).resolves.toMatchObject({
  596. name: "explore",
  597. identity: {},
  598. });
  599. await expect(
  600. catalog.render({
  601. agentName: "explore",
  602. surface: "interactive",
  603. appMode: "coding",
  604. locale: "fr-FR",
  605. promptChannel: "online",
  606. capabilities: resolveAgentCapabilities(),
  607. }),
  608. ).resolves.toMatchObject({
  609. persona: "Plain persona without frontmatter",
  610. corePrompt: "shared base\n\nworker base",
  611. surfacePrompt: "fallback root",
  612. });
  613. await expect(catalog.readGreetingTemplate("zh-CN")).resolves.toBe(
  614. "generic greeting",
  615. );
  616. await expect(catalog.readGreetingTemplate("en-US")).resolves.toBe(
  617. "generic greeting",
  618. );
  619. });
  620. it("renders primary internal-channel fallback and resolves capability intersections", async () => {
  621. const root = await mkdtemp(
  622. join(tmpdir(), "local-runtime-v2-agent-assets-primary-"),
  623. );
  624. fixtureDirectories.push(root);
  625. await mkdir(join(root, "mavis", "modes", "coding", "online"), {
  626. recursive: true,
  627. });
  628. await mkdir(join(root, "_default"), { recursive: true });
  629. await writeFile(join(root, "builtin-agents.json"), '["mavis"]');
  630. await writeFile(
  631. join(root, "mavis", "modes", "coding", "online", "SYSTEM.md.hbs"),
  632. "online",
  633. );
  634. await writeFile(
  635. join(root, "mavis", "modes", "coding", "online", "PERSONA.md"),
  636. "Mavis",
  637. );
  638. await writeFile(
  639. join(root, "mavis", "modes", "coding", "online", "PERSONA-zh.md"),
  640. "马维斯",
  641. );
  642. await writeFile(
  643. join(root, "_default", "prompt-base-all.md"),
  644. "shared base",
  645. );
  646. await writeFile(join(root, "_default", "prompt-session-root.md"), "root");
  647. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  648. await expect(
  649. catalog.render({
  650. agentName: "mavis",
  651. surface: "interactive",
  652. appMode: "coding",
  653. locale: "zh-CN",
  654. promptChannel: "internal",
  655. capabilities: resolveAgentCapabilities({
  656. tools: [],
  657. features: { mavis: false, delegation: false, webSearch: false },
  658. }),
  659. }),
  660. ).resolves.toMatchObject({ corePrompt: "online", persona: "Mavis" });
  661. const resolved = resolveCanonicalCapabilities(
  662. {
  663. persona: { enabled: true },
  664. tools: ["read", "write"] as never,
  665. features: { mavis: true, delegation: true, webSearch: true },
  666. },
  667. { persona: { enabled: false }, features: { delegation: false } },
  668. );
  669. expect(resolved).toMatchObject({
  670. persona: { enabled: false },
  671. tools: ["read", "write"],
  672. features: { mavis: true, delegation: false, webSearch: true },
  673. });
  674. expect(
  675. resolveCanonicalCapabilities(undefined, { tools: ["read"] as never })
  676. .tools,
  677. ).toEqual(["read"]);
  678. expect(
  679. resolveCanonicalCapabilities({ tools: ["read"] as never }, undefined)
  680. .tools,
  681. ).toEqual(["read"]);
  682. expect(canonicalBuiltinName("unknown")).toBe("unknown");
  683. expect(canonicalBuiltinName("general")).toBe("general");
  684. expect(legacyNamesFor("mavis")).toEqual(["main"]);
  685. expect(legacyNamesFor("unknown")).toEqual([]);
  686. });
  687. it("rejects malformed built-in rosters instead of silently accepting them", async () => {
  688. const root = await mkdtemp(
  689. join(tmpdir(), "local-runtime-v2-agent-assets-roster-"),
  690. );
  691. fixtureDirectories.push(root);
  692. await writeFile(join(root, "builtin-agents.json"), '{"explore":true}');
  693. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  694. await expect(catalog.listDefinitions()).rejects.toThrow(
  695. "roster must be an array",
  696. );
  697. });
  698. });
  699. describe("BuiltinAgentCatalog TodoWrite lifecycle guidance", () => {
  700. it("leaves TodoWrite lifecycle guidance to the tool description", async () => {
  701. const catalog = new BuiltinAgentCatalog();
  702. const common = {
  703. surface: "interactive" as const,
  704. promptMode: "coding" as const,
  705. appMode: "coding" as const,
  706. locale: "en",
  707. promptChannel: "online" as const,
  708. memoryEnabled: false,
  709. cronEnabled: false,
  710. };
  711. const [mavis, work, worker, withoutTodoWrite] = await Promise.all([
  712. catalog.render({
  713. ...common,
  714. agentName: "mavis",
  715. capabilities: resolveAgentCapabilities(),
  716. }),
  717. catalog.render({
  718. ...common,
  719. agentName: "mavis",
  720. appMode: "work",
  721. promptMode: "work",
  722. capabilities: resolveAgentCapabilities(),
  723. }),
  724. catalog.render({
  725. ...common,
  726. agentName: "worker",
  727. capabilities: resolveAgentCapabilities(),
  728. }),
  729. catalog.render({
  730. ...common,
  731. agentName: "mavis",
  732. capabilities: resolveAgentCapabilities({ tools: ["read"] }),
  733. }),
  734. ]);
  735. for (const rendered of [mavis, work, worker, withoutTodoWrite]) {
  736. expect(rendered.corePrompt).not.toContain("Task Management");
  737. expect(rendered.corePrompt).not.toContain(
  738. "When tracking work with TodoWrite",
  739. );
  740. expect(rendered.corePrompt).not.toContain("`in_progress`");
  741. }
  742. });
  743. });
  744. describe("BuiltinAgentCatalog session surfaces", () => {
  745. it("ships the response style contract in coding and work online prompts", async () => {
  746. const catalog = new BuiltinAgentCatalog();
  747. const common = {
  748. agentName: "mavis",
  749. surface: "interactive" as const,
  750. locale: "en-US",
  751. promptChannel: "online" as const,
  752. capabilities: resolveAgentCapabilities(),
  753. };
  754. const [coding, work] = await Promise.all([
  755. catalog.render({ ...common, appMode: "coding", promptMode: "coding" }),
  756. catalog.render({ ...common, appMode: "work", promptMode: "work" }),
  757. ]);
  758. for (const rendered of [coding, work]) {
  759. expect(rendered.corePrompt).toContain("## Response Style");
  760. expect(rendered.corePrompt).not.toContain("use 1 to 3 short paragraphs");
  761. expect(rendered.corePrompt).toContain(
  762. "For a one-point explanation, use compact prose without a heading, bullet recap, or code excerpt unless the user asks for one",
  763. );
  764. expect(rendered.corePrompt).toContain(
  765. "Indent supporting paragraphs or nested lists inside that numbered item",
  766. );
  767. expect(rendered.corePrompt).toContain(
  768. "File: source every code-file mention",
  769. );
  770. expect(rendered.corePrompt).not.toContain("<filepath>");
  771. expect(rendered.corePrompt).toContain(markdownLinkPolicy);
  772. }
  773. });
  774. it("uses the complete coding template for CLI while preserving capability gates", async () => {
  775. const catalog = new BuiltinAgentCatalog();
  776. const capabilities = resolveAgentCapabilities({
  777. features: { mavis: true, delegation: true, webSearch: true },
  778. });
  779. const common = {
  780. agentName: "mavis",
  781. appMode: "coding" as const,
  782. promptMode: "coding" as const,
  783. promptChannel: "online" as const,
  784. capabilities,
  785. memoryEnabled: false,
  786. cronEnabled: false,
  787. };
  788. const [coding, codingZh, cli, cliZh, cliWithoutDelegation] =
  789. await Promise.all([
  790. catalog.render({ ...common, surface: "interactive", locale: "en" }),
  791. catalog.render({ ...common, surface: "interactive", locale: "zh" }),
  792. catalog.render({ ...common, surface: "cli", locale: "en" }),
  793. catalog.render({ ...common, surface: "cli", locale: "zh" }),
  794. catalog.render({
  795. ...common,
  796. surface: "cli",
  797. locale: "en",
  798. capabilities: resolveAgentCapabilities({
  799. features: { mavis: true, delegation: false, webSearch: true },
  800. }),
  801. }),
  802. ]);
  803. expect(cli.persona).toBe(coding.persona);
  804. expect(cliZh.corePrompt).toBe(cli.corePrompt);
  805. expect(codingZh.persona).toBe(coding.persona);
  806. expect(codingZh.corePrompt).toBe(coding.corePrompt);
  807. expect(cli.corePrompt).toContain(
  808. "user's active MiniMax Code terminal conversation",
  809. );
  810. expect(coding.corePrompt).toContain("this agent's root session");
  811. expect(cli.corePrompt).toContain("# Core Judgment");
  812. expect(cli.persona).toBeUndefined();
  813. expect(cliZh.corePrompt).toContain(
  814. "You help users with software engineering tasks.",
  815. );
  816. expect(cliZh.corePrompt).not.toContain("You are Mavis");
  817. expect(cliZh.corePrompt).not.toContain("MiniMax As a Jarvis");
  818. expect(cli.corePrompt).not.toContain("# Work Rules");
  819. expect(cli.corePrompt).toContain("# Communication & Delivery");
  820. expect(cliWithoutDelegation.corePrompt).not.toContain("Task Routing");
  821. expect(cli.corePrompt).not.toContain("Task Routing");
  822. expect(cli.corePrompt).not.toContain("## Self-Reminder via Cron");
  823. expect(cli.corePrompt).not.toContain("# Memory");
  824. });
  825. it.each(["coding", "work"] as const)(
  826. "keeps task and Cron guidance outside the %s system prompt",
  827. async (appMode) => {
  828. const catalog = new BuiltinAgentCatalog();
  829. const rendered = await catalog.render({
  830. agentName: "mavis",
  831. surface: "interactive",
  832. appMode,
  833. promptMode: appMode,
  834. locale: "en",
  835. promptChannel: "online",
  836. capabilities: resolveAgentCapabilities({
  837. features: { mavis: true, delegation: true, webSearch: true },
  838. }),
  839. memoryEnabled: false,
  840. cronEnabled: true,
  841. });
  842. const corePrompt = rendered.corePrompt.replace(/\s+/gu, " ");
  843. expect(corePrompt).not.toContain("Scheduled Work and Async Follow-up");
  844. expect(corePrompt).not.toContain(
  845. "Use Cron only to schedule a future Agent turn",
  846. );
  847. expect(corePrompt).not.toContain("Use `cron once` for one future turn");
  848. expect(corePrompt).not.toContain("Use `cron self`");
  849. expect(corePrompt).not.toContain("Task Routing");
  850. expect(corePrompt).not.toContain(
  851. "The child does not inherit this conversation",
  852. );
  853. expect(corePrompt).not.toContain("## Task Management");
  854. },
  855. );
  856. it("renders the shared session surface for custom Agents and appends the child contract", async () => {
  857. const root = await mkdtemp(
  858. join(tmpdir(), "local-runtime-v2-agent-surface-"),
  859. );
  860. const customDir = await mkdtemp(
  861. join(tmpdir(), "local-runtime-v2-agent-custom-"),
  862. );
  863. fixtureDirectories.push(root, customDir);
  864. await mkdir(join(root, "_default"), { recursive: true });
  865. await writeFile(join(root, "builtin-agents.json"), "[]");
  866. await writeFile(
  867. join(root, "_default", "prompt-session-root.md.hbs"),
  868. "Default root",
  869. );
  870. await writeFile(
  871. join(root, "_default", "prompt-session-branch.md.hbs"),
  872. "{{#if surface.taskChild}}Default child contract{{/if}}",
  873. );
  874. await writeFile(
  875. join(customDir, "prompt-session-root.md"),
  876. "Custom root override",
  877. );
  878. await writeFile(
  879. join(customDir, "prompt-session-branch.md"),
  880. "Custom child override",
  881. );
  882. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  883. const common = {
  884. agentName: "custom",
  885. appMode: "coding" as const,
  886. locale: "en-US",
  887. promptChannel: "online" as const,
  888. capabilities: resolveAgentCapabilities(),
  889. };
  890. await expect(
  891. catalog.renderSurfacePrompt({
  892. ...common,
  893. surface: "interactive",
  894. agentConfigDir: customDir,
  895. }),
  896. ).resolves.toBe("Custom root override");
  897. await expect(
  898. catalog.renderSurfacePrompt({
  899. ...common,
  900. surface: "task-child",
  901. agentConfigDir: customDir,
  902. }),
  903. ).resolves.toBe("Custom child override\n\nDefault child contract");
  904. });
  905. it("keeps legacy role names out of model-visible Mavis onboarding assets", async () => {
  906. const catalog = new BuiltinAgentCatalog();
  907. const root = await catalog.resolveAssetsDir();
  908. expect(root).toBe(
  909. resolve(
  910. dirname(fileURLToPath(import.meta.url)),
  911. "../../../../assets/agents",
  912. ),
  913. );
  914. const systemPrompt = await readFile(
  915. join(root, "mavis", "system-prompt.md.hbs"),
  916. "utf8",
  917. );
  918. expect(systemPrompt).not.toMatch(
  919. /legacy\s+(?:general|coder)|(?:general|coder)\s*\/\s*(?:coder|general)|explicitly approves|go-ahead/,
  920. );
  921. });
  922. it("keeps product knowledge in the Mavis Skill catalog instead of duplicating it in mode prompts", async () => {
  923. const catalog = new BuiltinAgentCatalog();
  924. const root = await catalog.resolveAssetsDir();
  925. const common = {
  926. agentName: "mavis",
  927. surface: "interactive" as const,
  928. locale: "en-US",
  929. promptChannel: "online" as const,
  930. capabilities: resolveAgentCapabilities(),
  931. };
  932. const [coding, work, productSkill] = await Promise.all([
  933. catalog.render({ ...common, appMode: "coding", promptMode: "coding" }),
  934. catalog.render({ ...common, appMode: "work", promptMode: "work" }),
  935. readFile(
  936. join(root, "mavis", "skills", "minimax-code-product", "SKILL.md"),
  937. "utf8",
  938. ),
  939. ]);
  940. for (const rendered of [coding, work]) {
  941. expect(rendered.corePrompt).not.toContain("minimax-code-product");
  942. expect(rendered.corePrompt).not.toContain(
  943. "Do not guess dynamic product facts from model memory.",
  944. );
  945. }
  946. expect(productSkill).toMatch(/官方|authoritative/i);
  947. expect(productSkill).toMatch(
  948. /核实顺序|verification workflow|official source discovery/i,
  949. );
  950. expect(productSkill).toContain("https://agent.minimax.cn/docs/llms.txt");
  951. expect(productSkill).toContain(
  952. "https://platform.minimaxi.com/docs/llms.txt",
  953. );
  954. expect(productSkill).toContain("https://agent.minimax.io/docs/llms.txt");
  955. expect(productSkill).toContain("https://platform.minimax.io/docs/llms.txt");
  956. expect(productSkill).toContain(
  957. "https://agent.minimax.cn/docs/changelog.md",
  958. );
  959. expect(productSkill).toContain(
  960. "https://agent.minimax.io/docs/changelog.md",
  961. );
  962. expect(productSkill).toMatch(
  963. /current-region Desktop changelog[\s\S]*latest-version/i,
  964. );
  965. expect(productSkill).toMatch(/version\/date[\s\S]*download links/i);
  966. expect(productSkill).not.toMatch(/latest\.yml|latest-mac\.yml/i);
  967. expect(productSkill).not.toMatch(
  968. /filecdn\.minimax\.chat|file\.cdn\.minimax\.io/i,
  969. );
  970. expect(productSkill).not.toMatch(
  971. /https:\/\/agent\.minimaxi\.com|process\.platform/,
  972. );
  973. expect(productSkill).not.toContain("web_fetch");
  974. expect(productSkill).not.toMatch(
  975. /国内 Changelog[^\n]*https:\/\/agent\.minimax\.cn\/docs\/changelog(?!\.md)/i,
  976. );
  977. expect(productSkill).not.toMatch(
  978. /海外 Changelog[^\n]*https:\/\/agent\.minimax\.io\/docs\/changelog(?!\.md)/i,
  979. );
  980. expect(productSkill).not.toMatch(/\b(?:test|staging|inside)\b/i);
  981. expect(productSkill).not.toMatch(/最新版本\s*[::]\s*v?\d/i);
  982. expect(productSkill).not.toMatch(
  983. /https?:\/\/[^\s)]+\.(?:dmg|exe|zip|pkg)/i,
  984. );
  985. });
  986. });
  987. describe("BuiltinAgentCatalog Desktop V2 prompt profile", () => {
  988. it.each(["coding", "work"] as const)(
  989. "reads %s and child context from one remote version",
  990. async (appMode) => {
  991. const files = (version: string) => ({
  992. [`_v2/${appMode}/SYSTEM.md.hbs`]: `${version} ${appMode} {{#if memory.enabled}}memory{{/if}}`,
  993. "_v2/worker.md.hbs": `${version} worker`,
  994. "_v2/AGENT_CONTEXT.md.hbs": `${version} shared context`,
  995. });
  996. const reader = promptReader({ a: files("a"), b: files("b") });
  997. const catalog = new BuiltinAgentCatalog({ promptFileReader: reader });
  998. const input = {
  999. agentName: "mavis",
  1000. surface: "interactive" as const,
  1001. promptProfile: "desktop" as const,
  1002. appMode,
  1003. locale: "en",
  1004. promptChannel: "online" as const,
  1005. capabilities: resolveAgentCapabilities(),
  1006. memoryEnabled: true,
  1007. };
  1008. const a = promptReadContext("a");
  1009. const b = promptReadContext("b");
  1010. const first = await catalog.render({ ...input, promptReadContext: a });
  1011. expect(first.corePrompt).toBe(`a ${appMode} memory`);
  1012. expect(first.promptSnapshot?.template).toBe(
  1013. files("a")[`_v2/${appMode}/SYSTEM.md.hbs`],
  1014. );
  1015. expect(
  1016. (await catalog.render({ ...input, promptReadContext: b })).corePrompt,
  1017. ).toBe(`b ${appMode} memory`);
  1018. expect(
  1019. (await catalog.render({ ...input, promptReadContext: a })).corePrompt,
  1020. ).toBe(first.corePrompt);
  1021. const child = await catalog.render({
  1022. ...input,
  1023. agentName: "worker",
  1024. surface: "task-child",
  1025. promptReadContext: a,
  1026. });
  1027. expect(child.corePrompt).toContain("a worker");
  1028. expect(child.corePrompt).toContain("a shared context");
  1029. expect(child.surfacePrompt).toContain("a shared context");
  1030. expect(
  1031. reader.read.mock.calls.every(([, key]) => key.startsWith("_v2/")),
  1032. ).toBe(true);
  1033. },
  1034. );
  1035. });
  1036. describe("BuiltinAgentCatalog TUI prompt profile", () => {
  1037. it.each(["coding", "work"] as const)(
  1038. "uses the complete TUI template independently of the %s mode and Desktop snapshot",
  1039. async (appMode) => {
  1040. const reader = promptReader({ desktop: {} });
  1041. const catalog = new BuiltinAgentCatalog({ promptFileReader: reader });
  1042. const input = {
  1043. agentName: "mavis",
  1044. surface: "cli" as const,
  1045. promptProfile: "tui" as const,
  1046. appMode,
  1047. locale: "zh-CN",
  1048. promptChannel: "internal" as const,
  1049. capabilities: resolveAgentCapabilities(),
  1050. memoryEnabled: false,
  1051. cronEnabled: false,
  1052. promptReadContext: promptReadContext("desktop"),
  1053. };
  1054. const enabled = await catalog.render(input);
  1055. const child = await catalog.render({ ...input, surface: "task-child" });
  1056. expect(enabled.corePrompt).toContain(
  1057. "You are a coding agent running in the MiniMax Code terminal",
  1058. );
  1059. expect(enabled.corePrompt).toContain("markdown in a terminal");
  1060. expect(enabled.corePrompt).toContain("## Deliverable Files");
  1061. expect(enabled.corePrompt).not.toContain("## Media Output");
  1062. expect(enabled.surfacePrompt).toBe("");
  1063. expect(child.surfacePrompt).toContain("hidden TUI child Agent");
  1064. expect(reader.read).not.toHaveBeenCalled();
  1065. },
  1066. );
  1067. it("requires the selected complete template and child context without Desktop fallback", async () => {
  1068. const root = await mkdtemp(
  1069. join(tmpdir(), "local-runtime-v2-agent-tui-required-"),
  1070. );
  1071. fixtureDirectories.push(root);
  1072. await mkdir(join(root, "_v2", "tui"), { recursive: true });
  1073. await mkdir(join(root, "_default"), { recursive: true });
  1074. await writeFile(join(root, "builtin-agents.json"), '["mavis"]');
  1075. await writeFile(
  1076. join(root, "_default", "prompt-session-branch.md.hbs"),
  1077. "Desktop child",
  1078. );
  1079. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  1080. const input = {
  1081. agentName: "mavis",
  1082. surface: "cli" as const,
  1083. promptProfile: "tui" as const,
  1084. appMode: "coding" as const,
  1085. locale: "en",
  1086. promptChannel: "online" as const,
  1087. capabilities: resolveAgentCapabilities(),
  1088. };
  1089. await expect(catalog.render(input)).rejects.toThrow(
  1090. "_v2/tui/SYSTEM.md.hbs",
  1091. );
  1092. await writeFile(join(root, "_v2/tui/SYSTEM.md.hbs"), "Complete TUI prompt");
  1093. await expect(catalog.render(input)).resolves.toMatchObject({
  1094. corePrompt: "Complete TUI prompt",
  1095. });
  1096. await expect(
  1097. catalog.render({ ...input, surface: "task-child" }),
  1098. ).rejects.toThrow("Mandatory TUI surface");
  1099. });
  1100. it("preserves TUI worker context and custom child surface overrides on Windows", async () => {
  1101. const customDir = await mkdtemp(
  1102. join(tmpdir(), "local-runtime-v2-agent-tui-child-"),
  1103. );
  1104. fixtureDirectories.push(customDir);
  1105. await writeFile(
  1106. join(customDir, "prompt-session-branch.md"),
  1107. "Custom child briefing",
  1108. );
  1109. vi.spyOn(process, "platform", "get").mockReturnValue("win32");
  1110. const catalog = new BuiltinAgentCatalog();
  1111. const input = {
  1112. agentName: "worker",
  1113. surface: "task-child" as const,
  1114. promptProfile: "tui" as const,
  1115. appMode: "coding" as const,
  1116. locale: "en",
  1117. promptChannel: "online" as const,
  1118. capabilities: resolveAgentCapabilities({ tools: ["bash"] }),
  1119. };
  1120. const rendered = await catalog.render(input);
  1121. expect(rendered.corePrompt).toContain("Markdown in the terminal");
  1122. expect(rendered.corePrompt).toContain("Do the work first, report after.");
  1123. const surface = await catalog.renderSurfacePrompt({
  1124. ...input,
  1125. agentConfigDir: customDir,
  1126. });
  1127. expect(surface).toContain("Custom child briefing");
  1128. expect(surface).toContain("hidden TUI child Agent");
  1129. });
  1130. });
  1131. describe("BuiltinAgentCatalog persona assets", () => {
  1132. it("keeps identity and Core Judgment in the complete coding template", async () => {
  1133. const catalog = new BuiltinAgentCatalog();
  1134. const root = await catalog.resolveAssetsDir();
  1135. const persona = await readFile(join(root, "mavis", "PERSONA.md"), "utf8");
  1136. const { corePrompt } = await catalog.render({
  1137. agentName: "mavis",
  1138. surface: "interactive",
  1139. appMode: "coding",
  1140. promptMode: "coding",
  1141. locale: "en",
  1142. promptChannel: "online",
  1143. capabilities: resolveAgentCapabilities(),
  1144. });
  1145. expect(corePrompt).toContain(
  1146. "When the goal is clear, move forward directly without repeated confirmations.",
  1147. );
  1148. expect(corePrompt).toContain(
  1149. "When faced with ambiguity, first complete everything that does not depend on the answer.",
  1150. );
  1151. expect(corePrompt).toContain(
  1152. "Report results faithfully: say what succeeded, what failed, what was skipped, and what remains unverified.",
  1153. );
  1154. expect(persona).toContain("display_name: Mavis");
  1155. expect(persona).toContain("MiniMax Code");
  1156. expect(persona).not.toContain("You are Mavis");
  1157. expect(persona).not.toContain("Core Judgment");
  1158. expect(persona).not.toContain("customer service");
  1159. expect(persona).not.toContain("Warm But Not Soft");
  1160. expect(persona).not.toContain("## Communication Style");
  1161. expect(persona).not.toContain("sense of humor");
  1162. expect(persona).not.toContain("being robotic");
  1163. });
  1164. });
  1165. describe("BuiltinAgentCatalog citation surfaces", () => {
  1166. it.each([false, true])(
  1167. "shares citation and module structure with memory enabled: %s",
  1168. async (memoryEnabled) => {
  1169. const catalog = new BuiltinAgentCatalog();
  1170. const common = {
  1171. agentName: "mavis",
  1172. surface: "interactive" as const,
  1173. locale: "zh-CN",
  1174. promptChannel: "online" as const,
  1175. capabilities: resolveAgentCapabilities(),
  1176. memoryEnabled,
  1177. };
  1178. const [coding, work] = await Promise.all([
  1179. catalog.render({ ...common, appMode: "coding", promptMode: "coding" }),
  1180. catalog.render({ ...common, appMode: "work", promptMode: "work" }),
  1181. ]);
  1182. const workCitations = extractCitationSection(work.corePrompt);
  1183. const codingCitations = extractCitationSection(coding.corePrompt);
  1184. for (const prompt of [work.corePrompt, coding.corePrompt]) {
  1185. const headings = [...prompt.matchAll(/^# (.+)$/gmu)].map(
  1186. (match) => match[1],
  1187. );
  1188. expect(headings).toEqual([
  1189. "Harness",
  1190. "Core Judgment",
  1191. ...(memoryEnabled ? ["Memory"] : []),
  1192. "Communication & Delivery",
  1193. ]);
  1194. expect(prompt).not.toContain("Avoid Redundant Reads");
  1195. expect(prompt).not.toContain("memory(target=");
  1196. if (memoryEnabled)
  1197. expect(prompt).toContain(
  1198. "If memory writes are unavailable, leave durable memory unchanged.",
  1199. );
  1200. const harness = prompt.slice(
  1201. prompt.indexOf("# Harness"),
  1202. prompt.indexOf("# Core Judgment"),
  1203. );
  1204. expect(harness).not.toMatch(/^#{2,6} /gmu);
  1205. expect(harness).toContain(
  1206. "Independent tool calls can run in parallel in one response.",
  1207. );
  1208. expect(harness).toContain(
  1209. "Run dependent calls or conflicting writes sequentially",
  1210. );
  1211. expect(harness).toContain(
  1212. "Text you output outside of tool use is displayed to the user as GitHub-flavored Markdown.",
  1213. );
  1214. const media = prompt.slice(
  1215. prompt.indexOf("## Media Output"),
  1216. prompt.indexOf("## Citations"),
  1217. );
  1218. expect(prompt.indexOf("## Media Output")).toBeGreaterThan(
  1219. prompt.indexOf("# Communication & Delivery"),
  1220. );
  1221. expect(media).toContain("<deliver-assets>");
  1222. expect(media).toContain('<media type="file"');
  1223. expect(media).toContain("absolute local path");
  1224. expect(media).toContain("created or modified files must exist");
  1225. expect(media).toContain(
  1226. "file existed before this turn and is now absent",
  1227. );
  1228. expect(media).toContain(
  1229. "If creation or verification failed, report the failure",
  1230. );
  1231. const artifact = prompt.indexOf("## Artifact Completion Contract");
  1232. if (artifact >= 0)
  1233. expect(artifact).toBeGreaterThan(
  1234. prompt.indexOf("# Communication & Delivery"),
  1235. );
  1236. expect(prompt).not.toContain("MCP/App citation examples");
  1237. expect(prompt).not.toContain("Output Conventions");
  1238. const style = prompt.slice(
  1239. prompt.indexOf("## Response Style"),
  1240. prompt.indexOf("## Preamble messages"),
  1241. );
  1242. expect(style).not.toContain("GitHub-flavored Markdown");
  1243. expect(style).toContain("Use emoji sparingly");
  1244. expect(prompt).not.toContain("Task Routing");
  1245. }
  1246. expect(workCitations).toBe(codingCitations);
  1247. expect(workCitations).toContain(
  1248. "MCP/App: use the exact ToolResult `Citation candidate`",
  1249. );
  1250. expect(workCitations).toContain("File: source every code-file mention");
  1251. expect(workCitations).toContain("git diff paths auto-resolve");
  1252. expect(workCitations).toContain(
  1253. "Never leave sourceable code paths as inline/plain text",
  1254. );
  1255. expect(workCitations).toContain(
  1256. "Label code `filename(line N)` or `filename(lines N-M)`",
  1257. );
  1258. expect(workCitations).toContain(
  1259. "always label it with the App/MCP name. Client adds its icon",
  1260. );
  1261. expect(workCitations).not.toContain("localized `Source: [App](URL)`");
  1262. expect(workCitations).toContain("Keep standalone sources outside lists");
  1263. expect(workCitations).toContain(
  1264. "Place citations at sentence granularity; do not group multiple citations at the end of a paragraph.",
  1265. );
  1266. expect(workCitations).toContain(
  1267. "For tables, use a source column per row or a source line below the table.",
  1268. );
  1269. expect(workCitations).toContain(
  1270. "Do not cite unused calls or unsupported claims",
  1271. );
  1272. expect(workCitations).toContain("output bare parenthesized links");
  1273. expect(workCitations).toContain("add trailing source/reference lists");
  1274. expect(workCitations.length).toBeLessThan(900);
  1275. for (const prompt of [work.corePrompt, coding.corePrompt]) {
  1276. expect(prompt).not.toContain("file_path:line_number");
  1277. expect(prompt).not.toContain("<filepath>");
  1278. expect(prompt).not.toContain("### Web Citation Placement");
  1279. expect(prompt).not.toContain(
  1280. "one semantic citation link at that block's end is enough",
  1281. );
  1282. expect(prompt).not.toContain("## Tool source citations");
  1283. expect(prompt).not.toContain("Before finishing");
  1284. expect(prompt).not.toContain("Available fetched source");
  1285. expect(prompt.match(/File:/gu)).toHaveLength(1);
  1286. }
  1287. },
  1288. );
  1289. });
  1290. describe("shipped canonical SubAgent definitions", () => {
  1291. it.each(["explore", "worker", "verifier"])(
  1292. "declares WebSearch explicitly for shipped %s",
  1293. async (name) => {
  1294. const definition = await new BuiltinAgentCatalog().readDefinition(name);
  1295. expect(definition.capabilityOverride?.features?.webSearch).toBe(true);
  1296. },
  1297. );
  1298. });
  1299. describe("BuiltinAgentCatalog prompt modes", () => {
  1300. const common = {
  1301. agentName: "mavis",
  1302. surface: "cli" as const,
  1303. promptProfile: "tui" as const,
  1304. appMode: "coding" as const,
  1305. locale: "en",
  1306. promptChannel: "online" as const,
  1307. memoryEnabled: false,
  1308. cronEnabled: false,
  1309. };
  1310. it("selects one complete file per mode and evaluates inline Memory and Persona gates", async () => {
  1311. const catalog = new BuiltinAgentCatalog();
  1312. const rendered = [];
  1313. for (const promptMode of ["tui", "coding", "work"] as const) {
  1314. const enabled = await catalog.render({
  1315. ...common,
  1316. promptMode,
  1317. memoryEnabled: true,
  1318. capabilities: resolveAgentCapabilities(),
  1319. });
  1320. const disabled = await catalog.render({
  1321. ...common,
  1322. promptMode,
  1323. capabilities: resolveAgentCapabilities({ persona: { enabled: false } }),
  1324. });
  1325. expect(enabled.promptSnapshot?.mode).toBe(promptMode);
  1326. expect(enabled.promptSnapshot?.template).toContain(
  1327. "{{#if memory.enabled}}",
  1328. );
  1329. expect(enabled.corePrompt).toContain("# Memory");
  1330. expect(disabled.corePrompt).not.toContain("# Memory");
  1331. expect(disabled.corePrompt).not.toContain(
  1332. enabled.corePrompt.trim().split("\n")[0],
  1333. );
  1334. expect(enabled.corePrompt).not.toMatch(
  1335. /## (Task Routing|Task Management|Factual Freshness)/,
  1336. );
  1337. const resumed = catalog.renderPromptSnapshot(
  1338. { ...common, promptMode, capabilities: resolveAgentCapabilities() },
  1339. enabled.promptSnapshot!,
  1340. );
  1341. expect(resumed.systemPrompt).not.toContain("# Memory");
  1342. rendered.push(enabled);
  1343. }
  1344. expect(rendered[0]?.corePrompt).toContain(
  1345. "You are a coding agent running in the MiniMax Code terminal",
  1346. );
  1347. expect(rendered[1]?.corePrompt).toContain(
  1348. "You help users with software engineering tasks.",
  1349. );
  1350. expect(rendered[2]?.corePrompt).toContain(
  1351. "You help users research, analyze information, and create professional deliverables.",
  1352. );
  1353. expect(rendered[0]?.corePrompt).toContain("## Deliverable Files");
  1354. expect(rendered[1]?.corePrompt).toContain("## Media Output");
  1355. expect(
  1356. new Set(rendered.map((item) => item.promptSnapshot?.template)).size,
  1357. ).toBe(3);
  1358. });
  1359. it("freezes every mode before first render, including initially disabled Memory and Workflow text", async () => {
  1360. const root = await mkdtemp(join(tmpdir(), "prompt-mode-frozen-"));
  1361. fixtureDirectories.push(root);
  1362. await cp(await new BuiltinAgentCatalog().resolveAssetsDir(), root, {
  1363. recursive: true,
  1364. });
  1365. const catalog = new BuiltinAgentCatalog({
  1366. assetsDir: root,
  1367. freezeLocalPrompts: true,
  1368. });
  1369. await catalog.render({
  1370. ...common,
  1371. promptMode: "tui",
  1372. capabilities: resolveAgentCapabilities(),
  1373. });
  1374. const source = (await catalog.frozenPromptSource())!;
  1375. const snapshot = await source.capture();
  1376. const workflowKey = "workflow/plan-mode/agent-entry.md";
  1377. const workflow = await source.read(snapshot, workflowKey);
  1378. await writeFile(join(root, workflowKey), "changed workflow");
  1379. expect(await source.read(await source.capture(), workflowKey)).toEqual(
  1380. workflow,
  1381. );
  1382. await writeFile(
  1383. join(root, "_v2/work/SYSTEM.md.hbs"),
  1384. "Changed Work prompt",
  1385. );
  1386. const input = {
  1387. ...common,
  1388. promptMode: "work" as const,
  1389. memoryEnabled: true,
  1390. capabilities: resolveAgentCapabilities(),
  1391. };
  1392. const frozen = await catalog.render(input);
  1393. expect(frozen.corePrompt).toContain("# Memory");
  1394. expect(frozen.corePrompt).not.toContain("Changed Work prompt");
  1395. const fresh = await new BuiltinAgentCatalog({ assetsDir: root }).render(
  1396. input,
  1397. );
  1398. expect(fresh.corePrompt).toBe("Changed Work prompt");
  1399. });
  1400. it("reads V2 without V1 feature files and rejects a missing selected mode", async () => {
  1401. const root = await mkdtemp(join(tmpdir(), "prompt-mode-required-"));
  1402. fixtureDirectories.push(root);
  1403. await cp(await new BuiltinAgentCatalog().resolveAssetsDir(), root, {
  1404. recursive: true,
  1405. });
  1406. const catalog = new BuiltinAgentCatalog({ assetsDir: root });
  1407. await rm(join(root, "mavis/features"), { recursive: true });
  1408. const input = {
  1409. ...common,
  1410. promptMode: "work" as const,
  1411. capabilities: resolveAgentCapabilities(),
  1412. };
  1413. await expect(catalog.render(input)).resolves.toMatchObject({
  1414. promptSnapshot: { mode: "work" },
  1415. });
  1416. await rm(join(root, "_v2/work/SYSTEM.md.hbs"));
  1417. await expect(catalog.render(input)).rejects.toThrow(
  1418. "_v2/work/SYSTEM.md.hbs",
  1419. );
  1420. });
  1421. });