memory-agent-loop.test.ts 22 KB

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