memory-agent-loop.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. createModelId,
  4. createModelProviderId,
  5. type ExecutionShellSelection,
  6. type Model,
  7. type ModelInputMessage,
  8. type ModelRequest,
  9. type ModelResult,
  10. type ModelToolContract,
  11. } from "@zcode/contracts";
  12. import {
  13. evaluateMemoryAgentToolPolicy,
  14. runMemoryAgentLoop,
  15. type MemoryAgentModelRequest,
  16. } from "../src/memory/memory-agent-loop.js";
  17. import { setCmdReadonlyHostForTest } from "../src/tool/handlers/bash-cmd-readonly-policy.js";
  18. import {
  19. isRuntimeAttachmentEntry,
  20. type RuntimeMessageEntry,
  21. } from "../src/agent/message-history.js";
  22. import { DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES } from "../src/runtime/helpers/media-budget.js";
  23. import type { ExecutableToolCall, ToolExecutionResult } from "../src/tool/types.js";
  24. import { createTestInputFormat } from "./test-runtime-model.js";
  25. const modelSelection = {
  26. providerId: createModelProviderId("test"),
  27. modelId: createModelId("memory-agent"),
  28. };
  29. const memoryRoot = "/workspace/.memory";
  30. describe("runMemoryAgentLoop", () => {
  31. it("preserves the frozen provider context and real tool catalog on every model turn", async () => {
  32. const initialMessages = Object.freeze([
  33. Object.freeze({ role: "system", content: "full system" }),
  34. Object.freeze({ role: "user", content: "full conversation" }),
  35. Object.freeze({ role: "user", content: "extract now" }),
  36. ]) satisfies readonly ModelInputMessage[];
  37. const tools = Object.freeze([
  38. tool("Read", true, "none"),
  39. tool("Write", false, "workspace"),
  40. tool("Agent", false, "session"),
  41. ]) satisfies readonly ModelToolContract[];
  42. const requests: MemoryAgentModelRequest[] = [];
  43. const executeToolCalls = vi.fn(async (calls: ExecutableToolCall[]) =>
  44. calls.map((call) => executionResult(call.id, call.name, "written")),
  45. );
  46. const model = generateOnlyModel(async (request) => {
  47. requests.push(request as MemoryAgentModelRequest);
  48. if (requests.length < 5) {
  49. return modelResult({
  50. text: `turn ${requests.length}`,
  51. toolCalls: [{ id: `read-${requests.length}`, name: "Read", input: {} }],
  52. });
  53. }
  54. return modelResult({
  55. text: "last turn",
  56. toolCalls: [
  57. {
  58. id: "write-last",
  59. name: "Write",
  60. input: { file_path: `${memoryRoot}/fact.md`, content: "fact" },
  61. },
  62. ],
  63. });
  64. });
  65. const result = await runMemoryAgentLoop({
  66. abortSignal: new AbortController().signal,
  67. bashShellSelection: undefined,
  68. entries: messageEntries(initialMessages),
  69. executeToolCalls,
  70. maxTurns: 5,
  71. registry: noBatchNoticeRegistry,
  72. renderRequest: passthroughRender(tools),
  73. model,
  74. rootDir: memoryRoot,
  75. workingDirectory: "/workspace",
  76. workspaceRoot: "/workspace",
  77. });
  78. expect(requests).toHaveLength(5);
  79. expect(executeToolCalls).toHaveBeenCalledTimes(5);
  80. expect(executeToolCalls).toHaveBeenLastCalledWith(
  81. [expect.objectContaining({ id: "write-last", name: "Write" })],
  82. expect.objectContaining({ abortSignal: expect.any(AbortSignal) }),
  83. );
  84. expect(requests[0]?.messages).toEqual(initialMessages);
  85. expect(requests.every((request) => request.tools === tools)).toBe(true);
  86. expect(requests.every((request) => request.toolSearchEnabled === false)).toBe(true);
  87. expect(requests.every((request) => request.options?.reasoningLevel === "low")).toBe(true);
  88. expect(requests.every((request) => request.options?.maxOutputTokens === 5_000)).toBe(true);
  89. expect(requests[1]?.messages.slice(-2)).toEqual([
  90. expect.objectContaining({
  91. role: "assistant",
  92. content: "turn 1",
  93. toolCalls: [{ id: "read-1", name: "Read", input: {} }],
  94. }),
  95. expect.objectContaining({
  96. role: "tool",
  97. content: "written",
  98. toolCallId: "read-1",
  99. toolName: "Read",
  100. isError: false,
  101. }),
  102. ]);
  103. expect(result.turns).toBe(5);
  104. expect(messagesOf(result.entries).slice(-2)).toEqual([
  105. expect.objectContaining({ role: "assistant", content: "last turn" }),
  106. expect.objectContaining({ role: "tool", toolCallId: "write-last", isError: false }),
  107. ]);
  108. });
  109. it("applies media capability and budget projection on every model turn", async () => {
  110. const unsupportedVideo = {
  111. type: "video" as const,
  112. mediaType: "video/mp4",
  113. dataUrl: "data:video/mp4;base64,dmlkZW8=",
  114. };
  115. const sharedImageDataUrl = `data:image/png;base64,${"A".repeat(5 * 1024 * 1024)}`;
  116. const retainedImageCount = Math.floor(
  117. DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES / Buffer.byteLength(sharedImageDataUrl, "utf8"),
  118. );
  119. const historicalImage = {
  120. type: "image" as const,
  121. mediaType: "image/png",
  122. dataUrl: sharedImageDataUrl,
  123. };
  124. const requests: ModelRequest[] = [];
  125. const executeToolCalls = vi.fn(async (calls: ExecutableToolCall[]) =>
  126. calls.map((call) => ({
  127. ...executionResult(call.id, call.name, "read media"),
  128. modelContent: [unsupportedVideo, historicalImage],
  129. })),
  130. );
  131. const model = generateOnlyModel(
  132. async (request) => {
  133. requests.push(request);
  134. return requests.length === 1
  135. ? modelResult({
  136. toolCalls: [
  137. { id: "read-media-1", name: "Read", input: {} },
  138. { id: "read-media-2", name: "Read", input: {} },
  139. ],
  140. })
  141. : modelResult({ text: "done" });
  142. },
  143. { inputFormat: createTestInputFormat({ supportsVideo: false }) },
  144. );
  145. await runMemoryAgentLoop({
  146. bashShellSelection: undefined,
  147. entries: messageEntries([
  148. {
  149. role: "user",
  150. content: [
  151. { type: "text", text: "historical media" },
  152. unsupportedVideo,
  153. ...Array.from({ length: retainedImageCount + 2 }, () => historicalImage),
  154. ],
  155. },
  156. { role: "user", content: "extract memory" },
  157. ]),
  158. executeToolCalls,
  159. maxTurns: 2,
  160. registry: noBatchNoticeRegistry,
  161. renderRequest: passthroughRender([tool("Read", true, "none")]),
  162. model,
  163. rootDir: memoryRoot,
  164. workingDirectory: "/workspace",
  165. workspaceRoot: "/workspace",
  166. });
  167. expect(requests).toHaveLength(2);
  168. for (const request of requests) {
  169. const blocks = request.messages.flatMap((message) =>
  170. Array.isArray(message.content) ? message.content : [],
  171. );
  172. const text = blocks
  173. .filter((block) => block.type === "text")
  174. .map((block) => block.text)
  175. .join("\n");
  176. expect(blocks.filter((block) => block.type === "video")).toHaveLength(0);
  177. expect(blocks.filter((block) => block.type === "image")).toHaveLength(retainedImageCount);
  178. expect(text).toContain("does not support video input");
  179. expect(text).toContain("Media omitted from provider request");
  180. }
  181. });
  182. it("returns the exact provider-visible denial text without invoking the executor", async () => {
  183. const executeToolCalls = vi.fn();
  184. const requests: ModelRequest[] = [];
  185. const model = generateOnlyModel(async (request) => {
  186. requests.push(request);
  187. if (requests.length === 1) {
  188. return modelResult({
  189. toolCalls: [
  190. { id: "network", name: "WebFetch", input: { url: "https://example.com" } },
  191. { id: "bash-write", name: "Bash", input: { command: "touch /workspace/file" } },
  192. ],
  193. });
  194. }
  195. return modelResult({ text: "done" });
  196. });
  197. const result = await runMemoryAgentLoop({
  198. bashShellSelection: undefined,
  199. entries: messageEntries([{ role: "user", content: "extract" }]),
  200. executeToolCalls,
  201. maxTurns: 2,
  202. registry: noBatchNoticeRegistry,
  203. renderRequest: passthroughRender([
  204. tool("WebFetch", true, "network"),
  205. tool("Bash", false, "workspace"),
  206. ]),
  207. model,
  208. rootDir: memoryRoot,
  209. workingDirectory: "/workspace",
  210. workspaceRoot: "/workspace",
  211. });
  212. expect(executeToolCalls).not.toHaveBeenCalled();
  213. const deniedToolMessages = [
  214. {
  215. content:
  216. "only Read, Grep, Glob, read-only Bash, and Edit/Write within /workspace/.memory are allowed",
  217. role: "tool",
  218. toolCallId: "network",
  219. toolName: "WebFetch",
  220. isError: true,
  221. },
  222. {
  223. content:
  224. "Only read-only shell commands and rm with all paths inside /workspace/.memory are permitted in this context (ls, find, grep, cat, stat, wc, head, tail, and similar)",
  225. role: "tool",
  226. toolCallId: "bash-write",
  227. toolName: "Bash",
  228. isError: true,
  229. },
  230. ];
  231. expect(requests).toHaveLength(2);
  232. expect(requests[1]?.messages.slice(-2)).toEqual(deniedToolMessages);
  233. expect(messagesOf(result.entries).slice(-3, -1)).toEqual(deniedToolMessages);
  234. });
  235. it("returns the catalog-miss result before applying the Memory tool policy", async () => {
  236. const executeToolCalls = vi.fn();
  237. const requests: ModelRequest[] = [];
  238. const model = generateOnlyModel(async (request) => {
  239. requests.push(request);
  240. if (requests.length === 1) {
  241. return modelResult({
  242. toolCalls: [
  243. { id: "empty-name", name: "", input: {} },
  244. { id: "unknown-name", name: "Unknown", input: {} },
  245. ],
  246. });
  247. }
  248. return modelResult({ text: "done" });
  249. });
  250. await runMemoryAgentLoop({
  251. bashShellSelection: undefined,
  252. entries: messageEntries([{ role: "user", content: "extract" }]),
  253. executeToolCalls,
  254. maxTurns: 2,
  255. registry: noBatchNoticeRegistry,
  256. renderRequest: passthroughRender([tool("Read", true, "none")]),
  257. model,
  258. rootDir: memoryRoot,
  259. workingDirectory: "/workspace",
  260. workspaceRoot: "/workspace",
  261. });
  262. expect(executeToolCalls).not.toHaveBeenCalled();
  263. expect(requests).toHaveLength(2);
  264. expect(requests[1]?.messages.slice(-2)).toEqual([
  265. {
  266. content: "<tool_use_error>Error: No such tool available: </tool_use_error>",
  267. role: "tool",
  268. toolCallId: "empty-name",
  269. toolName: "",
  270. isError: true,
  271. },
  272. {
  273. content: "<tool_use_error>Error: No such tool available: Unknown</tool_use_error>",
  274. role: "tool",
  275. toolCallId: "unknown-name",
  276. toolName: "Unknown",
  277. isError: true,
  278. },
  279. ]);
  280. });
  281. it("executes tool calls returned by the fiftieth Dream turn", async () => {
  282. let requestCount = 0;
  283. const executeToolCalls = vi.fn(async (calls: ExecutableToolCall[]) =>
  284. calls.map((call) => executionResult(call.id, call.name, "done")),
  285. );
  286. const model = generateOnlyModel(async () => {
  287. requestCount += 1;
  288. return modelResult({
  289. toolCalls: [
  290. requestCount === 50
  291. ? {
  292. id: "write-fiftieth",
  293. name: "Write",
  294. input: { file_path: `${memoryRoot}/fact.md`, content: "fact" },
  295. }
  296. : { id: `read-${requestCount}`, name: "Read", input: {} },
  297. ],
  298. });
  299. });
  300. const result = await runMemoryAgentLoop({
  301. bashShellSelection: undefined,
  302. entries: messageEntries([{ role: "user", content: "dream" }]),
  303. executeToolCalls,
  304. maxTurns: 50,
  305. registry: noBatchNoticeRegistry,
  306. renderRequest: passthroughRender([
  307. tool("Read", true, "none"),
  308. tool("Write", false, "workspace"),
  309. ]),
  310. model,
  311. rootDir: memoryRoot,
  312. workingDirectory: "/workspace",
  313. workspaceRoot: "/workspace",
  314. });
  315. expect(result.turns).toBe(50);
  316. expect(executeToolCalls).toHaveBeenCalledTimes(50);
  317. expect(executeToolCalls).toHaveBeenLastCalledWith(
  318. [expect.objectContaining({ id: "write-fiftieth", name: "Write" })],
  319. expect.any(Object),
  320. );
  321. });
  322. it("gives every allowed call a tool result even when the executor returns none for it", async () => {
  323. const requests: ModelRequest[] = [];
  324. const executeToolCalls = vi.fn(async (calls: ExecutableToolCall[]) => [
  325. executionResult(calls[0]!.id, calls[0]!.name, "read"),
  326. ]);
  327. const model = generateOnlyModel(async (request) => {
  328. requests.push(request);
  329. return requests.length === 1
  330. ? modelResult({
  331. toolCalls: [
  332. { id: "read-1", name: "Read", input: {} },
  333. { id: "read-2", name: "Read", input: {} },
  334. ],
  335. })
  336. : modelResult({ text: "done" });
  337. });
  338. await runMemoryAgentLoop({
  339. bashShellSelection: undefined,
  340. entries: messageEntries([{ role: "user", content: "extract" }]),
  341. executeToolCalls,
  342. maxTurns: 2,
  343. registry: noBatchNoticeRegistry,
  344. renderRequest: passthroughRender([tool("Read", true, "none")]),
  345. model,
  346. rootDir: memoryRoot,
  347. workingDirectory: "/workspace",
  348. workspaceRoot: "/workspace",
  349. });
  350. // 每个 tool_use 都要有 tool_result,否则下一次请求会被 provider 拒绝。
  351. expect(requests[1]?.messages.slice(-2)).toEqual([
  352. expect.objectContaining({ role: "tool", toolCallId: "read-1", isError: false }),
  353. expect.objectContaining({ role: "tool", toolCallId: "read-2", isError: true }),
  354. ]);
  355. });
  356. it("keeps tool results in call order and appends the batch notices after them", async () => {
  357. const tools = [tool("Read", true, "none"), tool("WebFetch", true, "network")];
  358. const executeToolCalls = vi.fn(async (calls: ExecutableToolCall[]) =>
  359. calls.map((call) => executionResult(call.id, call.name, { notice: `${call.id} notice` })),
  360. );
  361. const model = generateOnlyModel(async (request) =>
  362. request.messages.length === 1
  363. ? modelResult({
  364. toolCalls: [
  365. { id: "read-1", name: "Read", input: {} },
  366. { id: "network", name: "WebFetch", input: {} },
  367. { id: "read-2", name: "Read", input: {} },
  368. ],
  369. })
  370. : modelResult({ text: "done" }),
  371. );
  372. const result = await runMemoryAgentLoop({
  373. bashShellSelection: undefined,
  374. entries: messageEntries([{ role: "user", content: "extract" }]),
  375. executeToolCalls,
  376. maxTurns: 2,
  377. registry: {
  378. get: (name: string) =>
  379. name === "Read"
  380. ? ({
  381. formatBatchNotice: (output: unknown) => ({
  382. source: "read_truncation_notice",
  383. content: (output as { notice: string }).notice,
  384. }),
  385. } as never)
  386. : undefined,
  387. },
  388. renderRequest: passthroughRender(tools),
  389. model,
  390. rootDir: memoryRoot,
  391. workingDirectory: "/workspace",
  392. workspaceRoot: "/workspace",
  393. });
  394. // 被拒绝的 call 不进入调度;结果按声明顺序,批次附件排在这批 tool result 之后。
  395. expect(executeToolCalls).toHaveBeenCalledWith(
  396. [expect.objectContaining({ id: "read-1" }), expect.objectContaining({ id: "read-2" })],
  397. expect.any(Object),
  398. );
  399. const batch = result.entries.slice(2, 7);
  400. expect(
  401. batch.map((entry) =>
  402. isRuntimeAttachmentEntry(entry) ? entry.content : entry.message.toolCallId,
  403. ),
  404. ).toEqual(["read-1", "network", "read-2", "read-1 notice", "read-2 notice"]);
  405. });
  406. });
  407. describe("evaluateMemoryAgentToolPolicy", () => {
  408. const registeredTools = [
  409. tool("Read", true, "none"),
  410. tool("Grep", true, "none"),
  411. tool("Bash", false, "workspace"),
  412. tool("Write", false, "workspace"),
  413. tool("Edit", false, "workspace"),
  414. tool("Agent", false, "session"),
  415. tool("WebFetch", true, "network"),
  416. tool("mcp__server__lookup", true, "network"),
  417. tool("OtherReadOnly", true, "none"),
  418. ] as const;
  419. it.each([
  420. ["registered read-only", "Read", {}],
  421. ["read-only Bash", "Bash", { command: "head -n 5 /workspace/notes.txt" }],
  422. ["read-only Bash with safe environment", "Bash", { command: "LANG=C head /workspace/file" }],
  423. ["read-only Bash with input redirect", "Bash", { command: "head < /workspace/file" }],
  424. [
  425. "read-only Bash redirected to /dev/null",
  426. "Bash",
  427. {
  428. command: "head /workspace/file > /dev/null",
  429. },
  430. ],
  431. [
  432. "read-only background Bash",
  433. "Bash",
  434. {
  435. command: "head /workspace/file",
  436. run_in_background: true,
  437. },
  438. ],
  439. ["Memory Write", "Write", { file_path: `${memoryRoot}/fact.md`, content: "fact" }],
  440. [
  441. "Memory Edit",
  442. "Edit",
  443. { file_path: `${memoryRoot}/nested/fact.md`, old_string: "a", new_string: "b" },
  444. ],
  445. ["narrow Bash removal", "Bash", { command: `rm -f ${memoryRoot}/old.md` }],
  446. ])("allows %s", (_label, name, input) => {
  447. expect(decide(name, input, registeredTools)).toMatchObject({ allowed: true });
  448. });
  449. it("does not let static metadata bypass the explicit shell, Agent, or MCP boundaries", () => {
  450. expect(
  451. decide("Bash", { command: "touch /workspace/file" }, [tool("Bash", true, "none")]),
  452. ).toMatchObject({ allowed: false });
  453. expect(decide("Agent", {}, [tool("Agent", true, "none")])).toMatchObject({ allowed: false });
  454. expect(
  455. decide("mcp__server__lookup", {}, [tool("mcp__server__lookup", true, "none")]),
  456. ).toMatchObject({ allowed: false });
  457. });
  458. it.each([
  459. ".git",
  460. "hooks",
  461. ".husky",
  462. ".githooks",
  463. "node_modules",
  464. ".vscode",
  465. ".idea",
  466. "head",
  467. "config",
  468. "objects",
  469. "refs",
  470. ".claude",
  471. "skills",
  472. "commands",
  473. "agents",
  474. ".cargo",
  475. ".devcontainer",
  476. ".yarn",
  477. ".mvn",
  478. ])("denies Memory Write/Edit in the sensitive %s path segment", (segment) => {
  479. const filePath = `${memoryRoot}/${segment}/fact.md`;
  480. expect(decide("Write", { file_path: filePath }, registeredTools)).toMatchObject({
  481. allowed: false,
  482. });
  483. expect(decide("Edit", { file_path: filePath }, registeredTools)).toMatchObject({
  484. allowed: false,
  485. });
  486. });
  487. it("uses the foreground sensitive-segment normalization without broadening it", () => {
  488. for (const segment of [".GIT", ".git.", ".git ", ".g\u200cit", ".git:stream"]) {
  489. expect(
  490. decide("Write", { file_path: `${memoryRoot}/${segment}/fact.md` }, registeredTools),
  491. ).toMatchObject({ allowed: false });
  492. }
  493. expect(
  494. decide("Write", { file_path: `${memoryRoot}/.git-notes/fact.md` }, registeredTools),
  495. ).toMatchObject({ allowed: true });
  496. });
  497. it("keeps the narrow Markdown rm policy unchanged for sensitive path segments", () => {
  498. expect(
  499. decide("Bash", { command: `rm -f ${memoryRoot}/.git/fact.md` }, registeredTools),
  500. ).toMatchObject({ allowed: true });
  501. });
  502. it.each([
  503. ["unregistered", "Unknown", {}],
  504. ["Agent", "Agent", {}],
  505. ["network tool", "WebFetch", { url: "https://example.com" }],
  506. ["MCP tool", "mcp__server__lookup", {}],
  507. ["unlisted read-only tool", "OtherReadOnly", {}],
  508. ["outside Write", "Write", { file_path: "/workspace/outside.md", content: "x" }],
  509. ["uppercase extension", "Write", { file_path: `${memoryRoot}/fact.MD`, content: "x" }],
  510. ["write-capable Bash", "Bash", { command: "touch /workspace/file" }],
  511. ["recursive removal", "Bash", { command: `rm -rf ${memoryRoot}/old.md` }],
  512. ["glob removal", "Bash", { command: `rm ${memoryRoot}/*.md` }],
  513. ["write redirect", "Bash", { command: "head /workspace/file > /workspace/copy" }],
  514. ["unsafe environment prefix", "Bash", { command: "PATH=/tmp head /workspace/file" }],
  515. ])("denies %s", (_label, name, input) => {
  516. expect(decide(name, input, registeredTools)).toMatchObject({ allowed: false });
  517. });
  518. describe("by session shell", () => {
  519. afterEach(() => setCmdReadonlyHostForTest(undefined));
  520. it.each([
  521. ["posix", POSIX_SELECTION],
  522. ["git-bash", GIT_BASH_SELECTION],
  523. ])("keeps read-only Bash and Memory rm allowed in a %s session", (_label, selection) => {
  524. for (const command of ["head -n 5 /workspace/notes.txt", `rm -f ${memoryRoot}/old.md`]) {
  525. expect(decide("Bash", { command }, registeredTools, selection)).toMatchObject({
  526. allowed: true,
  527. });
  528. }
  529. });
  530. // Bash AST 把 # 后面当注释,cmd.exe 却会执行 & 后面的命令。
  531. it.each([
  532. ["a command chained after #", String.raw`type # & python G:\temp\hello.py`],
  533. ["Memory rm with a command chained after #", `rm -f ${memoryRoot}/old.md # & python x.py`],
  534. ["Memory rm that only Bash AST can prove", `rm -f ${memoryRoot}/old.md`],
  535. ])("denies %s when Bash runs through cmd.exe", (_label, command) => {
  536. setCmdReadonlyHostForTest(WINDOWS_CMD_HOST);
  537. for (const selection of [CMD_SELECTION, LEGACY_SHELL_SELECTION]) {
  538. expect(decide("Bash", { command }, registeredTools, selection)).toMatchObject({
  539. allowed: false,
  540. });
  541. }
  542. });
  543. // `DIR /b` 只有 CMD 规则放行(Bash AST 区分大小写,不认 DIR),能证明两种会经 cmd.exe 的
  544. // shell 走的是 CMD 规则,而不是全部拒绝或退回 Bash AST。
  545. it("allows what the foreground CMD read-only policy allows", () => {
  546. setCmdReadonlyHostForTest(WINDOWS_CMD_HOST);
  547. for (const selection of [CMD_SELECTION, LEGACY_SHELL_SELECTION]) {
  548. for (const command of ["dir /b", "DIR /b"]) {
  549. expect(decide("Bash", { command }, registeredTools, selection)).toMatchObject({
  550. allowed: true,
  551. });
  552. }
  553. }
  554. });
  555. // POSIX 上的 legacy-shell 回落到 /bin/sh,# 同样是注释,CMD 绕过不成立;保持修复前的 Bash AST 判定。
  556. it.each(["darwin", "linux"])(
  557. "keeps read-only Bash and Memory rm allowed in a %s legacy-shell session",
  558. (platform) => {
  559. setCmdReadonlyHostForTest({ platform, env: {} });
  560. for (const command of ["head -n 5 /workspace/notes.txt", `rm -f ${memoryRoot}/old.md`]) {
  561. expect(
  562. decide("Bash", { command }, registeredTools, LEGACY_SHELL_SELECTION),
  563. ).toMatchObject({ allowed: true });
  564. }
  565. },
  566. );
  567. });
  568. });
  569. const POSIX_SELECTION: ExecutionShellSelection = {
  570. dialect: "posix",
  571. display: { name: "bash" },
  572. path: "/bin/bash",
  573. source: "auto-detected",
  574. };
  575. const GIT_BASH_SELECTION: ExecutionShellSelection = {
  576. dialect: "git-bash",
  577. display: { name: "Git Bash" },
  578. path: "C:/Program Files/Git/bin/bash.exe",
  579. source: "auto-detected",
  580. };
  581. const WINDOWS_CMD_PATH = String.raw`C:\Windows\System32\cmd.exe`;
  582. const WINDOWS_CMD_HOST = {
  583. platform: "win32",
  584. env: { ComSpec: WINDOWS_CMD_PATH, SystemRoot: String.raw`C:\Windows`, PATH: "" },
  585. realpath: (path: string) => path,
  586. };
  587. const CMD_SELECTION: ExecutionShellSelection = {
  588. dialect: "cmd",
  589. display: { name: "CMD" },
  590. id: "cmd",
  591. path: WINDOWS_CMD_PATH,
  592. source: "user-config",
  593. };
  594. const LEGACY_SHELL_SELECTION: ExecutionShellSelection = {
  595. dialect: "legacy-shell",
  596. display: { name: "system shell" },
  597. source: "legacy-fallback",
  598. };
  599. const noBatchNoticeRegistry = { get: () => undefined };
  600. function messageEntries(messages: readonly ModelInputMessage[]): RuntimeMessageEntry[] {
  601. return messages.map((message) => ({ message }));
  602. }
  603. function messagesOf(entries: readonly RuntimeMessageEntry[]): ModelInputMessage[] {
  604. return entries.flatMap((entry) => (isRuntimeAttachmentEntry(entry) ? [] : [entry.message]));
  605. }
  606. /** 循环机制测试用:entries 原样作为请求消息;与 Main 渲染器的一致性在 runtime 测试里覆盖。 */
  607. function passthroughRender(tools: readonly ModelToolContract[]) {
  608. return (entries: readonly RuntimeMessageEntry[]) => ({
  609. messages: entries.map((entry) =>
  610. isRuntimeAttachmentEntry(entry)
  611. ? { role: "user" as const, content: entry.content }
  612. : entry.message,
  613. ),
  614. tools: tools as ModelToolContract[],
  615. toolSearchEnabled: false,
  616. });
  617. }
  618. function decide(
  619. name: string,
  620. input: unknown,
  621. tools: readonly ModelToolContract[],
  622. bashShellSelection?: ExecutionShellSelection,
  623. ) {
  624. return evaluateMemoryAgentToolPolicy({
  625. bashShellSelection,
  626. rootDir: memoryRoot,
  627. toolCall: { id: "call", name, input },
  628. tools,
  629. workingDirectory: "/workspace",
  630. workspaceRoot: "/workspace",
  631. });
  632. }
  633. function tool(
  634. name: string,
  635. readOnly: boolean,
  636. sideEffectScope: ModelToolContract["sideEffectScope"],
  637. ): ModelToolContract {
  638. return {
  639. name,
  640. inputSchema: { type: "object" },
  641. readOnly,
  642. sideEffectScope,
  643. };
  644. }
  645. function generateOnlyModel(
  646. generateText: (request: ModelRequest) => Promise<ModelResult>,
  647. properties: Partial<Model["properties"]> = {},
  648. ): Model {
  649. return {
  650. ...modelSelection,
  651. properties: {
  652. requiresMfjsToolSchema: false,
  653. contextWindow: 200_000,
  654. inputFormat: createTestInputFormat(),
  655. outputFormat: { supportsText: true },
  656. supportsToolCall: true,
  657. supportsJsonSchemaOutput: true,
  658. supportsNativeWebSearch: false,
  659. supportsMidConversationSystem: true,
  660. ...properties,
  661. },
  662. optionSpecs: {
  663. reasoningLevel: { values: ["low", "high"] },
  664. maxOutputTokens: { max: 32_000 },
  665. },
  666. options: { maxOutputTokens: 32_000, reasoningLevel: "high" },
  667. bind() {
  668. return this;
  669. },
  670. generateText,
  671. streamText() {
  672. throw new Error("memory agent loop must not stream");
  673. },
  674. };
  675. }
  676. function modelResult(
  677. input: Pick<Partial<ModelResult>, "reasoning" | "text" | "toolCalls">,
  678. ): ModelResult {
  679. return {
  680. finishReason: input.toolCalls?.length ? "tool_calls" : "stop",
  681. model: modelSelection,
  682. text: input.text ?? "",
  683. toolCalls: input.toolCalls,
  684. reasoning: input.reasoning,
  685. usage: {},
  686. };
  687. }
  688. function executionResult(
  689. toolCallId: string,
  690. toolName: string,
  691. output: unknown,
  692. ): ToolExecutionResult {
  693. const now = new Date();
  694. return {
  695. completedAt: now,
  696. durationMs: 0,
  697. output,
  698. startedAt: now,
  699. success: true,
  700. toolCallId,
  701. toolName,
  702. };
  703. }