canonical-agent-config.test.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. import {
  2. mkdtemp,
  3. mkdir,
  4. readFile,
  5. readdir,
  6. realpath,
  7. rm,
  8. symlink,
  9. writeFile,
  10. } from "node:fs/promises";
  11. import { tmpdir } from "node:os";
  12. import { join } from "node:path";
  13. import { afterEach, describe, expect, it, vi } from "vitest";
  14. import {
  15. configureLocalRuntimeLogging,
  16. flushLocalRuntimeLogging,
  17. logger,
  18. shutdownLocalRuntimeLogging,
  19. } from "../../../../src/infra/logging/index.js";
  20. import {
  21. AgentConfigError,
  22. assertSafeAgentAvatarDirectory,
  23. decodeAgentAvatarDataUrl,
  24. parseBuiltinCanonicalAgentMarkdown,
  25. parseCanonicalAgentMarkdown,
  26. readCanonicalAgentConfig,
  27. readSafeAgentAvatar,
  28. readStableAgentMarkdown,
  29. serializeBuiltinCanonicalAgentConfig,
  30. serializeCanonicalAgentConfig,
  31. } from "../../../../src/service/agent/storage/canonical-agent-config.js";
  32. import {
  33. hasCanonicalPatch,
  34. patchCanonicalMarkdown,
  35. } from "../../../../src/service/agent/storage/canonical-agent-patch.js";
  36. const cleanup: Array<() => Promise<void>> = [];
  37. const DATA_DIR_SOURCE_ENV = "__MAVIS_RUNTIME_DATA_DIR_SOURCE";
  38. const ORIGINAL_DATA_DIR_SOURCE = process.env[DATA_DIR_SOURCE_ENV];
  39. afterEach(async () => {
  40. vi.restoreAllMocks();
  41. for (const dispose of cleanup.splice(0).reverse()) await dispose();
  42. if (ORIGINAL_DATA_DIR_SOURCE === undefined)
  43. delete process.env[DATA_DIR_SOURCE_ENV];
  44. else process.env[DATA_DIR_SOURCE_ENV] = ORIGINAL_DATA_DIR_SOURCE;
  45. });
  46. describe("canonical Custom Agent config", () => {
  47. registerCanonicalConfigParsingTests();
  48. registerCanonicalConfigCapabilityTests();
  49. });
  50. function registerCanonicalConfigParsingTests(): void {
  51. it("accepts the minimal frontmatter and preserves a body as the Agent-owned prompt", () => {
  52. expect(
  53. parseCanonicalAgentMarkdown(
  54. "---\nname: researcher\ndescription: Evidence first.\n---\n\nUse primary sources.\n",
  55. "researcher",
  56. ),
  57. ).toMatchObject({
  58. name: "researcher",
  59. description: "Evidence first.",
  60. systemPrompt: "Use primary sources.\n",
  61. diagnostics: [],
  62. });
  63. });
  64. it("preserves CRLF prompt bytes and whitespace after the canonical delimiter", () => {
  65. const systemPrompt =
  66. "\r\n Keep leading spaces \r\n\r\nKeep trailing spaces \r\n";
  67. const raw = `\uFEFF---\r\nname: researcher\r\ndescription: Evidence first.\r\n---\r\n\r\n${systemPrompt}`;
  68. expect(parseCanonicalAgentMarkdown(raw, "researcher").systemPrompt).toBe(
  69. systemPrompt,
  70. );
  71. });
  72. it("accepts only the legacy unquoted description colon spelling", () => {
  73. const legacy =
  74. "---\nname: psd-localizer\ndescription: PSD localizer: preserve layers\n---\n\nKeep layers.\n";
  75. expect(parseCanonicalAgentMarkdown(legacy, "psd-localizer")).toMatchObject({
  76. description: "PSD localizer: preserve layers",
  77. systemPrompt: "Keep layers.\n",
  78. });
  79. expect(
  80. parseCanonicalAgentMarkdown(
  81. legacy.replaceAll("\n", "\r\n"),
  82. "psd-localizer",
  83. ),
  84. ).toMatchObject({
  85. description: "PSD localizer: preserve layers",
  86. });
  87. let invalid: unknown;
  88. try {
  89. parseCanonicalAgentMarkdown(
  90. "---\nname: psd-localizer\ndescription: PSD localizer: preserve layers\ntools: Read\n---\n",
  91. "psd-localizer",
  92. );
  93. } catch (error) {
  94. invalid = error;
  95. }
  96. expect(invalid).toMatchObject({
  97. code: "AGENT_CONFIG_INVALID",
  98. field: "tools",
  99. });
  100. let malformed: unknown;
  101. try {
  102. parseCanonicalAgentMarkdown(
  103. "---\nname: psd-localizer: invalid\ndescription: PSD localizer: preserve layers\n---\n",
  104. "psd-localizer",
  105. );
  106. } catch (error) {
  107. malformed = error;
  108. }
  109. expect(malformed).toMatchObject({
  110. code: "AGENT_CONFIG_INVALID",
  111. field: "frontmatter",
  112. });
  113. let duplicate: unknown;
  114. try {
  115. parseCanonicalAgentMarkdown(
  116. "---\nname: psd-localizer\ndescription: PSD localizer: preserve layers\nname: duplicate\n---\n",
  117. "psd-localizer",
  118. );
  119. } catch (error) {
  120. duplicate = error;
  121. }
  122. expect(duplicate).toMatchObject({
  123. code: "AGENT_CONFIG_INVALID",
  124. field: "frontmatter",
  125. });
  126. });
  127. it("keeps route ownership with the directory name, normalizes blank workspace, and diagnoses unknown fields", () => {
  128. const parsed = parseCanonicalAgentMarkdown(
  129. '---\nname: portable-name\ndescription: Evidence first.\nunknownCompatibilityKey: keep-me\nx-mavis:\n displayName: Portable display\n avatar: ./avatar.png\n defaultWorkspaceDir: " "\n unknownMavisKey: keep-me\n---\n',
  130. "researcher",
  131. );
  132. expect(parsed).toMatchObject({
  133. name: "portable-name",
  134. description: "Evidence first.",
  135. xMavis: { displayName: "Portable display", avatar: "./avatar.png" },
  136. });
  137. expect(parsed.xMavis).not.toHaveProperty("defaultWorkspaceDir");
  138. expect(parsed.diagnostics).toEqual([
  139. { code: "agent_name_mismatch", field: "name" },
  140. { code: "unsupported_agent_field", field: "unknownCompatibilityKey" },
  141. { code: "unsupported_agent_field", field: "x-mavis.unknownMavisKey" },
  142. ]);
  143. });
  144. it.each(["on", "off"] as const)(
  145. "reads an unquoted MiniMax M3 thinking mode %s as a string and preserves it through serialization",
  146. (effort) => {
  147. const parsed = parseCanonicalAgentMarkdown(
  148. `---\nname: researcher\ndescription: Evidence first.\nmodel: minimax/MiniMax-M3\neffort: ${effort}\n---\n`,
  149. "researcher",
  150. );
  151. expect(parsed.model).toBe("minimax/MiniMax-M3");
  152. expect(parsed.effort).toBe(effort);
  153. expect(typeof parsed.effort).toBe("string");
  154. const serialized = serializeCanonicalAgentConfig({
  155. config: {
  156. name: parsed.name,
  157. description: parsed.description,
  158. model: parsed.model,
  159. effort: parsed.effort,
  160. systemPrompt: parsed.systemPrompt,
  161. },
  162. });
  163. expect(
  164. parseCanonicalAgentMarkdown(serialized, "researcher"),
  165. ).toMatchObject({
  166. model: "minimax/MiniMax-M3",
  167. effort,
  168. });
  169. },
  170. );
  171. it.each([
  172. ["missing description", "---\nname: researcher\n---\n", "description"],
  173. [
  174. "invalid name",
  175. "---\nname: [researcher]\ndescription: desc\n---\n",
  176. "name",
  177. ],
  178. [
  179. "invalid description",
  180. "---\nname: researcher\ndescription: [desc]\n---\n",
  181. "description",
  182. ],
  183. [
  184. "invalid known array",
  185. "---\nname: researcher\ndescription: desc\ntools: Read\n---\n",
  186. "tools",
  187. ],
  188. [
  189. "invalid model shape",
  190. "---\nname: researcher\ndescription: desc\nmodel: MiniMax-M3\n---\n",
  191. "model",
  192. ],
  193. [
  194. "invalid effort",
  195. "---\nname: researcher\ndescription: desc\neffort: [high]\n---\n",
  196. "effort",
  197. ],
  198. [
  199. "invalid disallowed tools",
  200. "---\nname: researcher\ndescription: desc\ndisallowedTools: Write\n---\n",
  201. "disallowedTools",
  202. ],
  203. [
  204. "invalid MCP servers",
  205. "---\nname: researcher\ndescription: desc\nmcpServers: local\n---\n",
  206. "mcpServers",
  207. ],
  208. [
  209. "invalid skills",
  210. "---\nname: researcher\ndescription: desc\nskills: research\n---\n",
  211. "skills",
  212. ],
  213. [
  214. "invalid x-mavis display name",
  215. "---\nname: researcher\ndescription: desc\nx-mavis:\n displayName: [display]\n---\n",
  216. "displayName",
  217. ],
  218. [
  219. "invalid x-mavis avatar",
  220. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: 42\n---\n",
  221. "avatar",
  222. ],
  223. [
  224. "invalid x-mavis limit",
  225. "---\nname: researcher\ndescription: desc\nx-mavis:\n contextWindow: -1\n---\n",
  226. "contextWindow",
  227. ],
  228. [
  229. "invalid x-mavis output limit",
  230. "---\nname: researcher\ndescription: desc\nx-mavis:\n maxOutputTokens: zero\n---\n",
  231. "maxOutputTokens",
  232. ],
  233. [
  234. "invalid x-mavis extension skills",
  235. "---\nname: researcher\ndescription: desc\nx-mavis:\n extensionSkills: research\n---\n",
  236. "extensionSkills",
  237. ],
  238. [
  239. "relative workspace",
  240. "---\nname: researcher\ndescription: desc\nx-mavis:\n defaultWorkspaceDir: relative/workspace\n---\n",
  241. "x-mavis.defaultWorkspaceDir",
  242. ],
  243. ])(
  244. "fails closed for %s with a field-level diagnostic",
  245. (_label, markdown, field) => {
  246. let thrown: unknown;
  247. try {
  248. parseCanonicalAgentMarkdown(markdown, "researcher");
  249. } catch (error) {
  250. thrown = error;
  251. }
  252. expect(thrown).toBeInstanceOf(AgentConfigError);
  253. expect(thrown).toMatchObject({ code: "AGENT_CONFIG_INVALID", field });
  254. },
  255. );
  256. }
  257. function registerCanonicalConfigCapabilityTests(): void {
  258. it("fails closed for a frontmatter tree deeper than the bounded parser limit", () => {
  259. const nested = Array.from(
  260. { length: 18 },
  261. (_, index) => `${" ".repeat(index)}next:`,
  262. ).join("\n");
  263. let thrown: unknown;
  264. try {
  265. parseCanonicalAgentMarkdown(
  266. `---\nname: researcher\ndescription: desc\nextra:\n${nested}\n${" ".repeat(18)}value: true\n---\n`,
  267. "researcher",
  268. );
  269. } catch (error) {
  270. thrown = error;
  271. }
  272. expect(thrown).toMatchObject({
  273. code: "AGENT_CONFIG_INVALID",
  274. field: "frontmatter",
  275. });
  276. });
  277. it("normalizes YAML alias expansion failures into the stable config diagnostic", () => {
  278. const aliases = Array.from(
  279. { length: 33 },
  280. (_, index) => `copy${index}: *base`,
  281. ).join("\n");
  282. let thrown: unknown;
  283. try {
  284. parseCanonicalAgentMarkdown(
  285. `---\nname: researcher\ndescription: desc\nbase: &base [one, two]\n${aliases}\n---\n`,
  286. "researcher",
  287. );
  288. } catch (error) {
  289. thrown = error;
  290. }
  291. expect(thrown).toMatchObject({
  292. code: "AGENT_CONFIG_INVALID",
  293. field: "frontmatter",
  294. });
  295. });
  296. it.each([
  297. ["a scalar frontmatter document", "---\nplain text\n---\n", "frontmatter"],
  298. [
  299. "a non-mapping x-mavis section",
  300. "---\nname: researcher\ndescription: desc\nx-mavis: []\n---\n",
  301. "x-mavis",
  302. ],
  303. [
  304. "a blank required value",
  305. '---\nname: " "\ndescription: desc\n---\n',
  306. "name",
  307. ],
  308. ])("rejects %s", (_label, markdown, field) => {
  309. expect(() => parseCanonicalAgentMarkdown(markdown, "researcher")).toThrow(
  310. expect.objectContaining({ code: "AGENT_CONFIG_INVALID", field }),
  311. );
  312. });
  313. it("distinguishes omitted capability selectors from explicit empty and nonempty arrays", () => {
  314. const inherited = parseCanonicalAgentMarkdown(
  315. "---\nname: researcher\ndescription: desc\n---\n",
  316. "researcher",
  317. );
  318. const disabled = parseCanonicalAgentMarkdown(
  319. "---\nname: researcher\ndescription: desc\ntools: []\ndisallowedTools: []\nmcpServers: []\nskills: []\nx-mavis:\n extensionSkills: []\n---\n",
  320. "researcher",
  321. );
  322. const selected = parseCanonicalAgentMarkdown(
  323. "---\nname: researcher\ndescription: desc\ntools: [Read]\ndisallowedTools: [Write]\nmcpServers: [local-mcp]\nskills: [research]\nx-mavis:\n extensionSkills: [extension-research]\n---\n",
  324. "researcher",
  325. );
  326. expect(inherited).not.toHaveProperty("tools");
  327. expect(inherited).not.toHaveProperty("disallowedTools");
  328. expect(inherited).not.toHaveProperty("mcpServers");
  329. expect(inherited).not.toHaveProperty("skills");
  330. expect(inherited.xMavis).toBeUndefined();
  331. expect(disabled.tools).toEqual([]);
  332. expect(disabled.disallowedTools).toEqual([]);
  333. expect(disabled.mcpServers).toEqual([]);
  334. expect(disabled.skills).toEqual([]);
  335. expect(disabled.xMavis?.extensionSkills).toEqual([]);
  336. expect(selected).toMatchObject({
  337. tools: ["Read"],
  338. disallowedTools: ["Write"],
  339. mcpServers: ["local-mcp"],
  340. skills: ["research"],
  341. xMavis: { extensionSkills: ["extension-research"] },
  342. });
  343. });
  344. }
  345. describe("managed Builtin Agent config", () => {
  346. it("serializes feature policy without adding it to the Custom Agent contract", () => {
  347. const serialized = serializeBuiltinCanonicalAgentConfig({
  348. config: {
  349. name: "explore",
  350. description: "Explore",
  351. features: { mavis: false, delegation: false, webSearch: true },
  352. systemPrompt: "Builtin prompt",
  353. },
  354. });
  355. expect(serialized).toContain(
  356. "features:\n mavis: false\n delegation: false\n webSearch: true",
  357. );
  358. expect(
  359. parseBuiltinCanonicalAgentMarkdown(serialized, "explore"),
  360. ).toMatchObject({
  361. features: { mavis: false, delegation: false, webSearch: true },
  362. });
  363. const custom = parseCanonicalAgentMarkdown(serialized, "explore");
  364. expect(custom).not.toHaveProperty("features");
  365. expect(custom.diagnostics).toContainEqual({
  366. code: "unsupported_agent_field",
  367. field: "features",
  368. });
  369. });
  370. it("keeps a partial legacy policy readable but rejects it for a managed write", () => {
  371. const legacy =
  372. "---\nname: explore\ndescription: Explore\nmodel: provider/model\nfeatures:\n webSearch: true\n---\n";
  373. expect(parseBuiltinCanonicalAgentMarkdown(legacy, "explore")).toMatchObject(
  374. {
  375. config: { model: "provider/model" },
  376. },
  377. );
  378. expect(() =>
  379. parseBuiltinCanonicalAgentMarkdown(legacy, "explore", {
  380. requireFeaturePolicy: true,
  381. }),
  382. ).toThrow(
  383. expect.objectContaining({
  384. code: "AGENT_CONFIG_INVALID",
  385. field: "features.mavis",
  386. }),
  387. );
  388. });
  389. });
  390. describe("canonical Custom Agent profile patching", () => {
  391. it("preserves CRLF framing and a terminal closing marker while applying profile fields", () => {
  392. const source = [
  393. "---",
  394. "name: researcher",
  395. "description: Before",
  396. "x-mavis:",
  397. " displayName: Before Name",
  398. " avatar: ./before.png",
  399. "---",
  400. ].join("\r\n");
  401. const rendered = patchCanonicalMarkdown(
  402. source,
  403. "researcher",
  404. {
  405. description: " After ",
  406. displayName: null,
  407. avatar: undefined,
  408. },
  409. undefined,
  410. );
  411. expect(rendered.startsWith("---\r\n")).toBe(true);
  412. expect(rendered.endsWith("\r\n---")).toBe(true);
  413. expect(parseCanonicalAgentMarkdown(rendered, "researcher")).toMatchObject({
  414. description: "After",
  415. });
  416. expect(
  417. parseCanonicalAgentMarkdown(rendered, "researcher").xMavis,
  418. ).toBeUndefined();
  419. });
  420. it("keeps the raw prompt suffix when patching profile fields", () => {
  421. const systemPrompt =
  422. "\r\n Keep leading spaces \r\n\r\nKeep trailing spaces \r\n";
  423. const source = `---\r\nname: researcher\r\ndescription: Before\r\n---\r\n\r\n${systemPrompt}`;
  424. const rendered = patchCanonicalMarkdown(
  425. source,
  426. "researcher",
  427. { description: "After" },
  428. undefined,
  429. );
  430. expect(rendered.endsWith(`---\r\n\r\n${systemPrompt}`)).toBe(true);
  431. expect(
  432. parseCanonicalAgentMarkdown(rendered, "researcher").systemPrompt,
  433. ).toBe(systemPrompt);
  434. });
  435. it("keeps the existing avatar until a staged local reference is available", () => {
  436. const source =
  437. "---\nname: researcher\ndescription: Before\nx-mavis:\n avatar: ./before.png\n---\nBody\n";
  438. const rendered = patchCanonicalMarkdown(
  439. source,
  440. "researcher",
  441. { avatar: "data:image/png;base64,staged-elsewhere" },
  442. undefined,
  443. );
  444. expect(
  445. parseCanonicalAgentMarkdown(rendered, "researcher").xMavis?.avatar,
  446. ).toBe("./before.png");
  447. expect(rendered.endsWith("Body\n")).toBe(true);
  448. });
  449. it.each([
  450. ["missing opening marker", "name: researcher\ndescription: Before\n---\n"],
  451. ["missing closing marker", "---\nname: researcher\ndescription: Before\n"],
  452. [
  453. "duplicate YAML key",
  454. "---\nname: researcher\nname: duplicate\ndescription: Before\n---\n",
  455. ],
  456. ])("rejects %s before replacing the canonical bytes", (_label, source) => {
  457. expect(() =>
  458. patchCanonicalMarkdown(
  459. source,
  460. "researcher",
  461. { description: "After" },
  462. undefined,
  463. ),
  464. ).toThrow(
  465. expect.objectContaining({
  466. code: "AGENT_CONFIG_INVALID",
  467. field: "frontmatter",
  468. }),
  469. );
  470. });
  471. it.each([
  472. [{ description: null }, "description"],
  473. [{ displayName: undefined }, "x-mavis.displayName"],
  474. ] as const)("rejects an explicitly blank profile field", (patch, field) => {
  475. const source = "---\nname: researcher\ndescription: Before\n---\n";
  476. expect(() =>
  477. patchCanonicalMarkdown(source, "researcher", patch, undefined),
  478. ).toThrow(expect.objectContaining({ code: "AGENT_CONFIG_INVALID", field }));
  479. });
  480. it("distinguishes an omitted profile patch from an explicitly supplied field", () => {
  481. expect(hasCanonicalPatch({})).toBe(false);
  482. expect(hasCanonicalPatch({ avatar: undefined })).toBe(true);
  483. });
  484. });
  485. describe("canonical Custom Agent file safety", () => {
  486. it("rejects a requested canonical filename that escapes the Agent directory", async () => {
  487. const agentDir = await createAgentDir();
  488. await expect(
  489. readStableAgentMarkdown({
  490. agentDir,
  491. routeName: "researcher",
  492. fileName: "../agent.md",
  493. }),
  494. ).rejects.toMatchObject({ code: "AGENT_CONFIG_INVALID", field: "file" });
  495. });
  496. it("fails closed for invalid UTF-8 instead of returning a replacement-character source", async () => {
  497. const dataDir = await mkdtemp(
  498. join(tmpdir(), "canonical-agent-invalid-utf8-"),
  499. );
  500. cleanup.push(() => rm(dataDir, { recursive: true, force: true }));
  501. const agentDir = join(dataDir, "agents", "researcher");
  502. await mkdir(agentDir, { recursive: true });
  503. await writeFile(
  504. join(agentDir, "agent.md"),
  505. Buffer.from([0x2d, 0x2d, 0x2d, 0x0a, 0xff, 0x0a, 0x2d, 0x2d, 0x2d, 0x0a]),
  506. );
  507. await expect(
  508. readStableAgentMarkdown({
  509. agentDir,
  510. routeName: "researcher",
  511. trustedRoot: dataDir,
  512. }),
  513. ).rejects.toMatchObject({
  514. code: "AGENT_CONFIG_INVALID",
  515. field: "agent.md",
  516. });
  517. });
  518. it("strictly decodes bounded Desktop image data URLs without accepting a MIME mismatch", () => {
  519. const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
  520. const dataUrl = `data:image/png;base64,${png.toString("base64")}`;
  521. const oversized = Buffer.alloc(10 * 1024 * 1024 + 1);
  522. png.copy(oversized);
  523. expect(decodeAgentAvatarDataUrl(dataUrl)).toEqual({
  524. bytes: png,
  525. extension: ".png",
  526. });
  527. expect(() =>
  528. decodeAgentAvatarDataUrl("data:image/png;base64,not-base64"),
  529. ).toThrow(AgentConfigError);
  530. expect(() =>
  531. decodeAgentAvatarDataUrl(
  532. `data:image/jpeg;base64,${png.toString("base64")}`,
  533. ),
  534. ).toThrow(AgentConfigError);
  535. expect(() =>
  536. decodeAgentAvatarDataUrl("https://example.invalid/avatar.png"),
  537. ).toThrow(AgentConfigError);
  538. expect(() =>
  539. decodeAgentAvatarDataUrl(
  540. `data:image/png;base64,${oversized.toString("base64")}`,
  541. ),
  542. ).toThrow(AgentConfigError);
  543. expect(() => decodeAgentAvatarDataUrl("data:image/png;base64,AAA")).toThrow(
  544. AgentConfigError,
  545. );
  546. const jpeg = Buffer.from([0xff, 0xd8, 0xff]);
  547. const gif = Buffer.from("GIF89a", "ascii");
  548. const webp = Buffer.from("RIFF0000WEBP", "ascii");
  549. expect(
  550. decodeAgentAvatarDataUrl(
  551. `data:image/jpeg;base64,${jpeg.toString("base64")}`,
  552. ),
  553. ).toEqual({
  554. bytes: jpeg,
  555. extension: ".jpg",
  556. });
  557. expect(
  558. decodeAgentAvatarDataUrl(
  559. `data:image/gif;base64,${gif.toString("base64")}`,
  560. ),
  561. ).toEqual({
  562. bytes: gif,
  563. extension: ".gif",
  564. });
  565. expect(
  566. decodeAgentAvatarDataUrl(
  567. `data:image/webp;base64,${webp.toString("base64")}`,
  568. ),
  569. ).toEqual({
  570. bytes: webp,
  571. extension: ".webp",
  572. });
  573. });
  574. it("rejects missing, escaping, non-file, and malformed local avatar targets", async () => {
  575. const dataDir = await mkdtemp(
  576. join(tmpdir(), "canonical-agent-avatar-guards-"),
  577. );
  578. cleanup.push(() => rm(dataDir, { recursive: true, force: true }));
  579. const agentDir = join(dataDir, "agents", "researcher");
  580. await mkdir(agentDir, { recursive: true });
  581. await expect(
  582. assertSafeAgentAvatarDirectory(
  583. join(dataDir, "agents", "missing"),
  584. dataDir,
  585. ),
  586. ).rejects.toMatchObject({ code: "AGENT_CONFIG_AVATAR_INVALID" });
  587. await expect(
  588. assertSafeAgentAvatarDirectory(join(dataDir, "..", "outside"), dataDir),
  589. ).rejects.toMatchObject({ code: "AGENT_CONFIG_AVATAR_INVALID" });
  590. await mkdir(join(agentDir, "folder.png"));
  591. await expect(
  592. readSafeAgentAvatar(agentDir, "./folder.png", dataDir),
  593. ).rejects.toMatchObject({
  594. code: "AGENT_CONFIG_AVATAR_INVALID",
  595. });
  596. await writeFile(join(agentDir, "nested"), "not a directory");
  597. await expect(
  598. readSafeAgentAvatar(agentDir, "./nested/avatar.png", dataDir),
  599. ).rejects.toMatchObject({
  600. code: "AGENT_CONFIG_AVATAR_INVALID",
  601. });
  602. await writeFile(join(agentDir, "invalid.jpg"), Buffer.from("not an image"));
  603. await expect(
  604. readSafeAgentAvatar(agentDir, "./invalid.jpg", dataDir),
  605. ).rejects.toMatchObject({
  606. code: "AGENT_CONFIG_AVATAR_INVALID",
  607. });
  608. });
  609. it("reads an avatar below a linked Desktop agents root", async () => {
  610. const dataDir = await mkdtemp(
  611. join(tmpdir(), "canonical-agent-linked-root-"),
  612. );
  613. const outsideDir = await mkdtemp(
  614. join(tmpdir(), "canonical-agent-linked-root-outside-"),
  615. );
  616. cleanup.push(
  617. () => rm(outsideDir, { recursive: true, force: true }),
  618. () => rm(dataDir, { recursive: true, force: true }),
  619. );
  620. const externalAgentDir = join(outsideDir, "agents", "researcher");
  621. await mkdir(externalAgentDir, { recursive: true });
  622. await writeFile(
  623. join(externalAgentDir, "avatar.png"),
  624. Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
  625. );
  626. await writeFile(
  627. join(externalAgentDir, "agent.md"),
  628. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./avatar.png\n---\n",
  629. );
  630. await symlink(join(outsideDir, "agents"), join(dataDir, "agents"));
  631. await expect(
  632. readCanonicalAgentConfig({
  633. agentDir: join(dataDir, "agents", "researcher"),
  634. routeName: "researcher",
  635. trustedRoot: dataDir,
  636. }),
  637. ).resolves.toMatchObject({
  638. name: "researcher",
  639. xMavis: { avatar: "./avatar.png" },
  640. });
  641. });
  642. });
  643. describe("canonical Custom Agent avatar safety", () => {
  644. it("reads a supported regular avatar but rejects path escapes and symlinks", async () => {
  645. const agentDir = await createAgentDir();
  646. await writeFile(
  647. join(agentDir, "avatar.png"),
  648. Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
  649. );
  650. await writeFile(
  651. join(agentDir, "agent.md"),
  652. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./avatar.png\n---\n",
  653. );
  654. await expect(
  655. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  656. ).resolves.toMatchObject({
  657. xMavis: { avatar: "./avatar.png" },
  658. });
  659. await writeFile(
  660. join(agentDir, "agent.md"),
  661. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: https://example.invalid/avatar.png\n---\n",
  662. );
  663. await expect(
  664. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  665. ).rejects.toMatchObject({
  666. code: "AGENT_CONFIG_AVATAR_INVALID",
  667. field: "x-mavis.avatar",
  668. });
  669. await writeFile(
  670. join(agentDir, "agent.md"),
  671. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ../avatar.png\n---\n",
  672. );
  673. await expect(
  674. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  675. ).rejects.toMatchObject({
  676. code: "AGENT_CONFIG_AVATAR_INVALID",
  677. });
  678. await symlink(join(agentDir, "avatar.png"), join(agentDir, "linked.png"));
  679. await writeFile(
  680. join(agentDir, "agent.md"),
  681. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./linked.png\n---\n",
  682. );
  683. await expect(
  684. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  685. ).rejects.toMatchObject({
  686. code: "AGENT_CONFIG_AVATAR_INVALID",
  687. });
  688. await writeFile(
  689. join(agentDir, "agent.md"),
  690. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./avatar.png\n---\n",
  691. );
  692. const linkedAgentDir = join(agentDir, "..", "linked-researcher");
  693. await symlink(agentDir, linkedAgentDir);
  694. await expect(
  695. readCanonicalAgentConfig({
  696. agentDir: linkedAgentDir,
  697. routeName: "researcher",
  698. }),
  699. ).resolves.toMatchObject({ name: "researcher" });
  700. const outsideDir = await mkdtemp(
  701. join(tmpdir(), "canonical-agent-avatar-outside-"),
  702. );
  703. cleanup.push(() => rm(outsideDir, { recursive: true, force: true }));
  704. await writeFile(
  705. join(outsideDir, "avatar.png"),
  706. Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
  707. );
  708. await symlink(outsideDir, join(agentDir, "nested"));
  709. await writeFile(
  710. join(agentDir, "agent.md"),
  711. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./nested/avatar.png\n---\n",
  712. );
  713. await expect(
  714. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  715. ).rejects.toMatchObject({
  716. code: "AGENT_CONFIG_AVATAR_INVALID",
  717. });
  718. });
  719. it("accepts a 10 MiB GIF data URL and reads the same bytes from the avatar file", async () => {
  720. const bytes = Buffer.alloc(10 * 1024 * 1024);
  721. bytes.write("GIF89a");
  722. const decoded = decodeAgentAvatarDataUrl(
  723. `data:image/gif;base64,${bytes.toString("base64")}`,
  724. );
  725. expect(decoded.bytes.equals(bytes)).toBe(true);
  726. const agentDir = await createAgentDir();
  727. await writeFile(join(agentDir, "avatar.gif"), decoded.bytes);
  728. const read = await readSafeAgentAvatar(agentDir, "./avatar.gif");
  729. expect(read.bytes.equals(bytes)).toBe(true);
  730. });
  731. it("bounds avatar reads before loading an arbitrarily large local image", async () => {
  732. const agentDir = await createAgentDir();
  733. await writeFile(
  734. join(agentDir, "avatar.png"),
  735. Buffer.concat([
  736. Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
  737. Buffer.alloc(10 * 1024 * 1024),
  738. ]),
  739. );
  740. await writeFile(
  741. join(agentDir, "agent.md"),
  742. "---\nname: researcher\ndescription: desc\nx-mavis:\n avatar: ./avatar.png\n---\n",
  743. );
  744. await expect(
  745. readCanonicalAgentConfig({ agentDir, routeName: "researcher" }),
  746. ).rejects.toMatchObject({
  747. code: "AGENT_CONFIG_AVATAR_INVALID",
  748. field: "x-mavis.avatar",
  749. });
  750. });
  751. it("serializes a complete canonical file without introducing legacy assets", () => {
  752. expect(
  753. serializeCanonicalAgentConfig({
  754. config: {
  755. name: "researcher",
  756. description: "Evidence first.",
  757. tools: [],
  758. xMavis: { defaultWorkspaceDir: "/workspace/researcher" },
  759. systemPrompt: "Use primary sources.",
  760. },
  761. }),
  762. ).toBe(
  763. "---\nname: researcher\ndescription: Evidence first.\ntools: []\nx-mavis:\n defaultWorkspaceDir: /workspace/researcher\n---\n\nUse primary sources.",
  764. );
  765. });
  766. it("serializes prompt whitespace without normalizing line endings or appending a newline", () => {
  767. const systemPrompt =
  768. "\n\n Keep leading spaces \r\n\r\nKeep trailing spaces \n\n";
  769. const serialized = serializeCanonicalAgentConfig({
  770. config: {
  771. name: "researcher",
  772. description: "Evidence first.",
  773. systemPrompt,
  774. },
  775. });
  776. expect(serialized.endsWith(`---\n\n${systemPrompt}`)).toBe(true);
  777. const parsed = parseCanonicalAgentMarkdown(serialized, "researcher");
  778. expect(parsed.systemPrompt).toBe(systemPrompt);
  779. const serializedAgain = serializeCanonicalAgentConfig({
  780. config: {
  781. name: parsed.name,
  782. description: parsed.description,
  783. systemPrompt: parsed.systemPrompt,
  784. },
  785. });
  786. expect(serializedAgain).toBe(serialized);
  787. const whitespaceOnly = "\t \r\n ";
  788. const whitespaceOnlySerialized = serializeCanonicalAgentConfig({
  789. config: {
  790. name: "whitespace-only",
  791. description: "Whitespace only",
  792. systemPrompt: whitespaceOnly,
  793. },
  794. });
  795. expect(
  796. parseCanonicalAgentMarkdown(whitespaceOnlySerialized, "whitespace-only")
  797. .systemPrompt,
  798. ).toBe(whitespaceOnly);
  799. });
  800. it("serializes every x-mavis field while omitting an explicitly empty extension object", () => {
  801. const complete = serializeCanonicalAgentConfig({
  802. config: {
  803. name: "researcher",
  804. description: "Evidence first.",
  805. xMavis: {
  806. displayName: "Researcher",
  807. avatar: "./avatar.png",
  808. contextWindow: 64_000,
  809. maxOutputTokens: 4_096,
  810. extensionSkills: [],
  811. },
  812. systemPrompt: "",
  813. },
  814. });
  815. expect(complete).toContain("extensionSkills: []");
  816. expect(
  817. serializeCanonicalAgentConfig({
  818. config: {
  819. name: "minimal",
  820. description: "Minimal",
  821. xMavis: {},
  822. systemPrompt: "",
  823. },
  824. }),
  825. ).not.toContain("x-mavis");
  826. });
  827. });
  828. describe("canonical Agent directory safety", () => {
  829. it("follows linked Agent-directory segments and records their targets", async () => {
  830. process.env[DATA_DIR_SOURCE_ENV] = "mavis_env";
  831. const parentDir = await mkdtemp(
  832. join(tmpdir(), "canonical-agent-linked-config-"),
  833. );
  834. const outsideDir = await mkdtemp(
  835. join(tmpdir(), "canonical-agent-linked-config-outside-"),
  836. );
  837. cleanup.push(
  838. () => rm(outsideDir, { recursive: true, force: true }),
  839. () => rm(parentDir, { recursive: true, force: true }),
  840. );
  841. const markdown = "---\nname: researcher\ndescription: desc\n---\nPrompt\n";
  842. const warnSpy = vi.spyOn(logger, "warn");
  843. const minimaxRoot = join(parentDir, ".minimax-profile");
  844. const mavisRoot = join(parentDir, ".mavis-profile");
  845. await mkdir(join(minimaxRoot, "agents", "researcher"), { recursive: true });
  846. await writeFile(
  847. join(minimaxRoot, "agents", "researcher", "agent.md"),
  848. markdown,
  849. );
  850. await symlink(minimaxRoot, mavisRoot);
  851. await expect(
  852. readCanonicalAgentConfig({
  853. agentDir: join(mavisRoot, "agents", "researcher"),
  854. routeName: "researcher",
  855. trustedRoot: mavisRoot,
  856. }),
  857. ).resolves.toMatchObject({ name: "researcher" });
  858. const agentsRoot = join(parentDir, ".minimax-agents");
  859. const agentsTarget = join(outsideDir, "agents-target");
  860. await mkdir(agentsRoot, { recursive: true });
  861. await mkdir(join(agentsTarget, "researcher"), { recursive: true });
  862. await writeFile(join(agentsTarget, "researcher", "agent.md"), markdown);
  863. await symlink(agentsTarget, join(agentsRoot, "agents"));
  864. await expect(
  865. readCanonicalAgentConfig({
  866. agentDir: join(agentsRoot, "agents", "researcher"),
  867. routeName: "researcher",
  868. trustedRoot: agentsRoot,
  869. }),
  870. ).resolves.toMatchObject({ name: "researcher" });
  871. const builtinRoot = join(parentDir, ".minimax-builtin");
  872. const builtinTarget = join(outsideDir, "builtin-target");
  873. await mkdir(join(builtinRoot, "agents"), { recursive: true });
  874. await mkdir(join(builtinTarget, "explore"), { recursive: true });
  875. await writeFile(join(builtinTarget, "explore", "agent.md"), markdown);
  876. await symlink(builtinTarget, join(builtinRoot, "agents", ".builtin"));
  877. await expect(
  878. readCanonicalAgentConfig({
  879. agentDir: join(builtinRoot, "agents", ".builtin", "explore"),
  880. routeName: "researcher",
  881. trustedRoot: builtinRoot,
  882. }),
  883. ).resolves.toMatchObject({ name: "researcher" });
  884. const agentRoot = join(parentDir, ".minimax-agent");
  885. const agentTarget = join(outsideDir, "agent-target");
  886. await mkdir(join(agentRoot, "agents"), { recursive: true });
  887. await mkdir(agentTarget, { recursive: true });
  888. await writeFile(join(agentTarget, "agent.md"), markdown);
  889. await symlink(agentTarget, join(agentRoot, "agents", "researcher"));
  890. await expect(
  891. readCanonicalAgentConfig({
  892. agentDir: join(agentRoot, "agents", "researcher"),
  893. routeName: "researcher",
  894. trustedRoot: agentRoot,
  895. }),
  896. ).resolves.toMatchObject({ name: "researcher" });
  897. const insideRoot = join(parentDir, ".minimax-inside");
  898. const insideTarget = join(insideRoot, "managed-agent");
  899. await mkdir(join(insideRoot, "agents"), { recursive: true });
  900. await mkdir(insideTarget, { recursive: true });
  901. await writeFile(join(insideTarget, "agent.md"), markdown);
  902. await symlink(insideTarget, join(insideRoot, "agents", "researcher"));
  903. await expect(
  904. readCanonicalAgentConfig({
  905. agentDir: join(insideRoot, "agents", "researcher"),
  906. routeName: "researcher",
  907. trustedRoot: insideRoot,
  908. }),
  909. ).resolves.toMatchObject({ name: "researcher" });
  910. const nestedRoot = join(parentDir, ".minimax-nested");
  911. const nestedTarget = join(outsideDir, "nested-target");
  912. const nestedLink = join(
  913. nestedRoot,
  914. "agents",
  915. "researcher",
  916. "linked-directory",
  917. );
  918. await mkdir(join(nestedRoot, "agents", "researcher"), { recursive: true });
  919. await mkdir(nestedTarget, { recursive: true });
  920. await writeFile(join(nestedTarget, "agent.md"), markdown);
  921. await symlink(nestedTarget, nestedLink);
  922. await expect(
  923. readCanonicalAgentConfig({
  924. agentDir: nestedLink,
  925. routeName: "researcher",
  926. trustedRoot: nestedRoot,
  927. }),
  928. ).resolves.toMatchObject({ name: "researcher" });
  929. expect(warnSpy).toHaveBeenCalledWith(
  930. {
  931. event: "agent_directory_link_followed",
  932. data_dir_source: "mavis_env",
  933. segment: "data_dir",
  934. logical_link_path: mavisRoot,
  935. readlink_raw_target: minimaxRoot,
  936. realpath_resolved_target: await realpath(minimaxRoot),
  937. resolved_target_kind: "directory",
  938. target_scope: "expected_default_target",
  939. root_kind: ".mavis",
  940. },
  941. "Following linked Agent directory",
  942. );
  943. expect(warnSpy).toHaveBeenCalledWith(
  944. {
  945. event: "agent_directory_link_followed",
  946. data_dir_source: "mavis_env",
  947. segment: "agents",
  948. logical_link_path: join(agentsRoot, "agents"),
  949. readlink_raw_target: agentsTarget,
  950. realpath_resolved_target: await realpath(agentsTarget),
  951. resolved_target_kind: "directory",
  952. target_scope: "data_dir_outside",
  953. root_kind: ".minimax",
  954. },
  955. "Following linked Agent directory",
  956. );
  957. expect(warnSpy).toHaveBeenCalledWith(
  958. {
  959. event: "agent_directory_link_followed",
  960. data_dir_source: "mavis_env",
  961. segment: "builtin",
  962. logical_link_path: join(builtinRoot, "agents", ".builtin"),
  963. readlink_raw_target: builtinTarget,
  964. realpath_resolved_target: await realpath(builtinTarget),
  965. resolved_target_kind: "directory",
  966. target_scope: "data_dir_outside",
  967. root_kind: ".minimax",
  968. },
  969. "Following linked Agent directory",
  970. );
  971. expect(warnSpy).toHaveBeenCalledWith(
  972. {
  973. event: "agent_directory_link_followed",
  974. data_dir_source: "mavis_env",
  975. segment: "agent",
  976. logical_link_path: join(agentRoot, "agents", "researcher"),
  977. readlink_raw_target: agentTarget,
  978. realpath_resolved_target: await realpath(agentTarget),
  979. resolved_target_kind: "directory",
  980. target_scope: "data_dir_outside",
  981. root_kind: ".minimax",
  982. },
  983. "Following linked Agent directory",
  984. );
  985. expect(warnSpy).toHaveBeenCalledWith(
  986. {
  987. event: "agent_directory_link_followed",
  988. data_dir_source: "mavis_env",
  989. segment: "agent",
  990. logical_link_path: join(insideRoot, "agents", "researcher"),
  991. readlink_raw_target: insideTarget,
  992. realpath_resolved_target: await realpath(insideTarget),
  993. resolved_target_kind: "directory",
  994. target_scope: "data_dir_inside",
  995. root_kind: ".minimax",
  996. },
  997. "Following linked Agent directory",
  998. );
  999. expect(warnSpy).toHaveBeenCalledWith(
  1000. {
  1001. event: "agent_directory_link_followed",
  1002. data_dir_source: "mavis_env",
  1003. segment: "nested",
  1004. logical_link_path: nestedLink,
  1005. readlink_raw_target: nestedTarget,
  1006. realpath_resolved_target: await realpath(nestedTarget),
  1007. resolved_target_kind: "directory",
  1008. target_scope: "data_dir_outside",
  1009. root_kind: ".minimax",
  1010. },
  1011. "Following linked Agent directory",
  1012. );
  1013. });
  1014. });
  1015. describe("canonical Agent directory safety", () => {
  1016. it("logs each logical link target once across stable reads", async () => {
  1017. const dataDir = await mkdtemp(
  1018. join(tmpdir(), "canonical-agent-link-dedup-"),
  1019. );
  1020. const targetDir = await mkdtemp(
  1021. join(tmpdir(), "canonical-agent-link-dedup-target-"),
  1022. );
  1023. cleanup.push(
  1024. () => rm(targetDir, { recursive: true, force: true }),
  1025. () => rm(dataDir, { recursive: true, force: true }),
  1026. );
  1027. await mkdir(join(targetDir, "researcher"), { recursive: true });
  1028. await writeFile(
  1029. join(targetDir, "researcher", "agent.md"),
  1030. "---\nname: researcher\ndescription: desc\n---\nPrompt\n",
  1031. );
  1032. await symlink(targetDir, join(dataDir, "agents"));
  1033. const warnSpy = vi.spyOn(logger, "warn");
  1034. const input = {
  1035. agentDir: join(dataDir, "agents", "researcher"),
  1036. routeName: "researcher",
  1037. trustedRoot: dataDir,
  1038. };
  1039. await expect(readCanonicalAgentConfig(input)).resolves.toMatchObject({
  1040. name: "researcher",
  1041. });
  1042. await expect(readCanonicalAgentConfig(input)).resolves.toMatchObject({
  1043. name: "researcher",
  1044. });
  1045. expect(warnSpy).toHaveBeenCalledTimes(1);
  1046. expect(warnSpy).toHaveBeenCalledWith(
  1047. expect.objectContaining({
  1048. event: "agent_directory_link_followed",
  1049. logical_link_path: join(dataDir, "agents"),
  1050. realpath_resolved_target: await realpath(targetDir),
  1051. resolved_target_kind: "directory",
  1052. }),
  1053. "Following linked Agent directory",
  1054. );
  1055. });
  1056. it("persists a directory-link warning in the local-runtime disk log", async () => {
  1057. process.env[DATA_DIR_SOURCE_ENV] = "mavis_env";
  1058. const dataDir = await mkdtemp(
  1059. join(tmpdir(), "canonical-agent-persistent-link-"),
  1060. );
  1061. const targetDir = await mkdtemp(
  1062. join(tmpdir(), "canonical-agent-persistent-target-"),
  1063. );
  1064. const logsDir = await mkdtemp(
  1065. join(tmpdir(), "canonical-agent-persistent-logs-"),
  1066. );
  1067. cleanup.push(
  1068. () => rm(logsDir, { recursive: true, force: true }),
  1069. () => rm(targetDir, { recursive: true, force: true }),
  1070. () => rm(dataDir, { recursive: true, force: true }),
  1071. );
  1072. const logicalLink = join(dataDir, "agents");
  1073. await mkdir(join(targetDir, "researcher"), { recursive: true });
  1074. await writeFile(
  1075. join(targetDir, "researcher", "agent.md"),
  1076. "---\nname: researcher\ndescription: desc\n---\nPrompt\n",
  1077. );
  1078. await symlink(targetDir, logicalLink);
  1079. try {
  1080. configureLocalRuntimeLogging({
  1081. dir: logsDir,
  1082. now: () => new Date(2026, 7, 31, 10, 0, 0, 0).getTime(),
  1083. loggerOptions: { env: { NODE_ENV: "production" }, level: "info" },
  1084. });
  1085. await expect(
  1086. readCanonicalAgentConfig({
  1087. agentDir: join(logicalLink, "researcher"),
  1088. routeName: "researcher",
  1089. trustedRoot: dataDir,
  1090. }),
  1091. ).resolves.toMatchObject({ name: "researcher" });
  1092. await flushLocalRuntimeLogging();
  1093. const logFiles = (await readdir(logsDir)).filter((file) =>
  1094. /^runtime-.*\.log$/u.test(file),
  1095. );
  1096. expect(logFiles).toEqual(["runtime-2026083110.log"]);
  1097. const contents = await readFile(join(logsDir, logFiles[0]!), "utf8");
  1098. const persistedLine = contents
  1099. .split("\n")
  1100. .find((line) =>
  1101. line.includes('"event":"agent_directory_link_followed"'),
  1102. );
  1103. expect(persistedLine).toBeDefined();
  1104. const fieldsIndex = persistedLine!.indexOf("{");
  1105. expect(fieldsIndex).toBeGreaterThanOrEqual(0);
  1106. expect(JSON.parse(persistedLine!.slice(fieldsIndex))).toMatchObject({
  1107. event: "agent_directory_link_followed",
  1108. data_dir_source: "mavis_env",
  1109. segment: "agents",
  1110. logical_link_path: logicalLink,
  1111. readlink_raw_target: targetDir,
  1112. realpath_resolved_target: await realpath(targetDir),
  1113. resolved_target_kind: "directory",
  1114. target_scope: "data_dir_outside",
  1115. root_kind: "other",
  1116. });
  1117. } finally {
  1118. await shutdownLocalRuntimeLogging();
  1119. }
  1120. });
  1121. it("reports dangling and non-directory links without a link-prohibition error", async () => {
  1122. process.env[DATA_DIR_SOURCE_ENV] = "mavis_env";
  1123. const dataDir = await mkdtemp(
  1124. join(tmpdir(), "canonical-agent-diagnostic-unresolved-"),
  1125. );
  1126. const nonDirectoryRoot = await mkdtemp(
  1127. join(tmpdir(), "canonical-agent-diagnostic-file-"),
  1128. );
  1129. cleanup.push(
  1130. () => rm(nonDirectoryRoot, { recursive: true, force: true }),
  1131. () => rm(dataDir, { recursive: true, force: true }),
  1132. );
  1133. const warnSpy = vi.spyOn(logger, "warn");
  1134. await mkdir(join(dataDir, "agents"), { recursive: true });
  1135. const missingTarget = join(dataDir, "missing-target");
  1136. const danglingLink = join(dataDir, "agents", "researcher");
  1137. await symlink(missingTarget, danglingLink);
  1138. const unresolvedFailure = await readAgentDirectoryFailure({
  1139. agentDir: danglingLink,
  1140. routeName: "researcher",
  1141. trustedRoot: dataDir,
  1142. });
  1143. expect(unresolvedFailure.message).toContain(
  1144. "Agent directory does not exist or cannot be read.",
  1145. );
  1146. expect(unresolvedFailure.message).not.toContain(
  1147. "must not contain symbolic links",
  1148. );
  1149. expect(warnSpy).toHaveBeenCalledWith(
  1150. {
  1151. event: "agent_directory_link_followed",
  1152. data_dir_source: "mavis_env",
  1153. segment: "agent",
  1154. logical_link_path: danglingLink,
  1155. readlink_raw_target: missingTarget,
  1156. realpath_resolved_target: null,
  1157. resolved_target_kind: "unresolvable",
  1158. target_scope: "unresolvable",
  1159. root_kind: "other",
  1160. },
  1161. "Following linked Agent directory",
  1162. );
  1163. const fileTarget = join(nonDirectoryRoot, "not-a-directory");
  1164. const nonDirectoryLink = join(nonDirectoryRoot, "agents");
  1165. await writeFile(fileTarget, "not a directory");
  1166. await symlink(fileTarget, nonDirectoryLink);
  1167. const nonDirectoryFailure = await readAgentDirectoryFailure({
  1168. agentDir: join(nonDirectoryLink, "researcher"),
  1169. routeName: "researcher",
  1170. trustedRoot: nonDirectoryRoot,
  1171. });
  1172. expect(nonDirectoryFailure.message).toContain(
  1173. "Agent directory is not a directory.",
  1174. );
  1175. expect(nonDirectoryFailure.message).not.toContain(
  1176. "must not contain symbolic links",
  1177. );
  1178. expect(warnSpy).toHaveBeenCalledWith(
  1179. {
  1180. event: "agent_directory_link_followed",
  1181. data_dir_source: "mavis_env",
  1182. segment: "agents",
  1183. logical_link_path: nonDirectoryLink,
  1184. readlink_raw_target: fileTarget,
  1185. realpath_resolved_target: await realpath(fileTarget),
  1186. resolved_target_kind: "not_directory",
  1187. target_scope: "data_dir_inside",
  1188. root_kind: "other",
  1189. },
  1190. "Following linked Agent directory",
  1191. );
  1192. });
  1193. });
  1194. describe("canonical Custom Agent legacy description fallback", () => {
  1195. it.each([
  1196. ["a malformed document without a top-level description", "broken: ["],
  1197. [
  1198. "an empty description with unrelated malformed YAML",
  1199. "description:\nbroken: [",
  1200. ],
  1201. [
  1202. "a plain description without a legacy colon and malformed YAML",
  1203. "description: Plain text\nbroken: [",
  1204. ],
  1205. [
  1206. "a YAML indicator prefix",
  1207. "description: ? PSD localizer: preserve layers",
  1208. ],
  1209. [
  1210. "an unclosed quote prefix",
  1211. 'description: "PSD localizer: preserve layers',
  1212. ],
  1213. [
  1214. "an inline YAML comment",
  1215. "description: PSD localizer: preserve layers # keep",
  1216. ],
  1217. [
  1218. "an indented continuation",
  1219. "description: PSD localizer: preserve layers\n continuation: no",
  1220. ],
  1221. ["a trailing space", "description: PSD localizer: preserve layers "],
  1222. ])(
  1223. "keeps the legacy description fallback closed for %s",
  1224. (_caseName, descriptionLine) => {
  1225. let thrown: unknown;
  1226. try {
  1227. parseCanonicalAgentMarkdown(
  1228. `---\nname: psd-localizer\n${descriptionLine}\n---\n`,
  1229. "psd-localizer",
  1230. );
  1231. } catch (error) {
  1232. thrown = error;
  1233. }
  1234. expect(thrown).toMatchObject({
  1235. code: "AGENT_CONFIG_INVALID",
  1236. field: "frontmatter",
  1237. });
  1238. },
  1239. );
  1240. });
  1241. async function readAgentDirectoryFailure(input: {
  1242. readonly agentDir: string;
  1243. readonly routeName: string;
  1244. readonly trustedRoot: string;
  1245. }): Promise<AgentConfigError> {
  1246. try {
  1247. await readCanonicalAgentConfig(input);
  1248. } catch (error) {
  1249. if (error instanceof AgentConfigError) return error;
  1250. throw error;
  1251. }
  1252. throw new Error("expected Agent directory validation to fail");
  1253. }
  1254. async function createAgentDir(): Promise<string> {
  1255. const dataDir = await mkdtemp(join(tmpdir(), "canonical-agent-config-"));
  1256. cleanup.push(() => rm(dataDir, { recursive: true, force: true }));
  1257. const agentDir = join(dataDir, "agents", "researcher");
  1258. await mkdir(agentDir, { recursive: true });
  1259. return agentDir;
  1260. }