memory-provider-body.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { readFileSync } from "node:fs";
  2. import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
  3. import {
  4. createModelId,
  5. createModelProviderId,
  6. type ModelInputMessage,
  7. type ModelToolContract,
  8. } from "@zcode/contracts";
  9. import { afterEach, describe, expect, it } from "vitest";
  10. import {
  11. TestAiSdkModelAdapter as AiSdkModelAdapter,
  12. TestProviderConfigFixture,
  13. } from "./test-provider-config.js";
  14. import { executeAdapterGenerateText, executeAdapterStreamText } from "./test-adapter-model.js";
  15. const MEMORY_ROOT = "/storage/memories/project/memory";
  16. const MODEL = {
  17. modelId: createModelId("claude-opus-4-8-cc"),
  18. providerId: createModelProviderId("anthropic"),
  19. };
  20. const MAIN_MEMORY = memoryFixture("main-memory-default-index.md").replaceAll(
  21. "<MEMORY_ROOT>",
  22. MEMORY_ROOT,
  23. );
  24. const SEMANTIC_RECALL_MAIN_MEMORY = memoryFixture("main-memory-semantic-recall.md").replaceAll(
  25. "<MEMORY_ROOT>",
  26. MEMORY_ROOT,
  27. );
  28. const MAIN_MEMORY_INDEX = memoryFixture("main-memory-index.md").replaceAll(
  29. "<MEMORY_INDEX_PATH>",
  30. `${MEMORY_ROOT}/MEMORY.md`,
  31. );
  32. const RECALLED_MEMORY = memoryFixture("recalled-memory.md", true).replaceAll(
  33. "<MEMORY_ROOT>",
  34. MEMORY_ROOT,
  35. );
  36. const EXTRACTION_PROMPT = memoryFixture("extraction-prompt.md").replaceAll(
  37. "<TIMESTAMP>",
  38. "2026-07-16T00:00:00.000Z",
  39. );
  40. const DREAM_PROMPT = memoryFixture("dream-prompt.md")
  41. .replaceAll("<MEMORY_ROOT>", MEMORY_ROOT)
  42. .replaceAll("<SESSION_TRANSCRIPT_ROOT>", "/storage/rollout")
  43. .replaceAll("<SESSION_ID>", "sess-history");
  44. const MEMORY_UPDATE = memoryFixture("memory-update.md").replaceAll("<MEMORY_ROOT>", MEMORY_ROOT);
  45. const CUSTOM_AGENT_MEMORY = memoryFixture("custom-agent-memory.md");
  46. const CUSTOM_AGENT_SCOPE_GUIDANCE = JSON.parse(
  47. memoryFixture("custom-agent-scope-guidance.json", true),
  48. ) as Record<"local" | "project" | "user", string>;
  49. const MEMORY_TOOLS: ModelToolContract[] = [
  50. {
  51. description: "Write a file",
  52. inputSchema: {
  53. additionalProperties: false,
  54. properties: {
  55. content: { type: "string" },
  56. file_path: { type: "string" },
  57. },
  58. required: ["file_path", "content"],
  59. type: "object",
  60. },
  61. name: "Write",
  62. },
  63. {
  64. description: "Edit a file",
  65. inputSchema: {
  66. additionalProperties: false,
  67. properties: {
  68. file_path: { type: "string" },
  69. new_string: { type: "string" },
  70. old_string: { type: "string" },
  71. },
  72. required: ["file_path", "old_string", "new_string"],
  73. type: "object",
  74. },
  75. name: "Edit",
  76. },
  77. ];
  78. const openServers: Server[] = [];
  79. afterEach(async () => {
  80. await Promise.all(openServers.splice(0).map(closeServer));
  81. });
  82. describe("Memory provider-visible request body", () => {
  83. it("keeps default-index and semantic-recall provider bodies mutually exclusive", async () => {
  84. const capture = await startProviderBodyCapture();
  85. const adapter = createAdapter(capture.baseURL);
  86. await sendStreamingRequest(adapter, [
  87. systemMessage(MAIN_MEMORY, true),
  88. userMessage(MAIN_MEMORY_INDEX),
  89. userMessage("default branch", true),
  90. ]);
  91. await sendStreamingRequest(adapter, [
  92. systemMessage(SEMANTIC_RECALL_MAIN_MEMORY, true),
  93. userMessage("semantic branch tool batch", true),
  94. systemMessage(RECALLED_MEMORY),
  95. ]);
  96. expect(capture.bodies).toHaveLength(2);
  97. const defaultText = requestBodyText(capture.bodies[0]!);
  98. const semanticText = requestBodyText(capture.bodies[1]!);
  99. expect(defaultText).toContain(MAIN_MEMORY);
  100. expect(defaultText).toContain(MAIN_MEMORY_INDEX);
  101. expect(defaultText).not.toContain(RECALLED_MEMORY);
  102. expect(semanticText).toContain(SEMANTIC_RECALL_MAIN_MEMORY);
  103. expect(semanticText).toContain(RECALLED_MEMORY);
  104. expect(semanticText).not.toContain(MAIN_MEMORY_INDEX);
  105. expect(semanticText).not.toContain(
  106. "After writing the file, add a one-line pointer in `MEMORY.md`",
  107. );
  108. });
  109. it("projects Main Memory and both Memory MCS surfaces into final streaming bodies", async () => {
  110. const capture = await startProviderBodyCapture();
  111. const adapter = createAdapter(capture.baseURL);
  112. await sendStreamingRequest(adapter, [
  113. systemMessage(MAIN_MEMORY, true),
  114. userMessage(MAIN_MEMORY_INDEX),
  115. userMessage("first request", true),
  116. ]);
  117. await sendStreamingRequest(adapter, [
  118. systemMessage(MAIN_MEMORY, true),
  119. userMessage("tool batch completed", true),
  120. systemMessage(RECALLED_MEMORY),
  121. ]);
  122. await sendStreamingRequest(adapter, [
  123. systemMessage(MAIN_MEMORY, true),
  124. userMessage("next request", true),
  125. systemMessage(MEMORY_UPDATE),
  126. ]);
  127. expect(capture.bodies).toHaveLength(3);
  128. expect(capture.bodies.map((body) => body.model)).toEqual([
  129. "claude-opus-4-8-cc",
  130. "claude-opus-4-8-cc",
  131. "claude-opus-4-8-cc",
  132. ]);
  133. expect(capture.bodies[0]!.system).toEqual([
  134. {
  135. cache_control: { type: "ephemeral" },
  136. text: MAIN_MEMORY,
  137. type: "text",
  138. },
  139. ]);
  140. expect(bodyMessages(capture.bodies[0]!)[0]).toEqual({
  141. content: [
  142. { text: MAIN_MEMORY_INDEX, type: "text" },
  143. {
  144. cache_control: { type: "ephemeral" },
  145. text: "first request",
  146. type: "text",
  147. },
  148. ],
  149. role: "user",
  150. });
  151. expect(bodyMessages(capture.bodies[1]!).at(-1)).toEqual({
  152. content: RECALLED_MEMORY,
  153. role: "system",
  154. });
  155. expect(bodyMessages(capture.bodies[2]!).at(-1)).toEqual({
  156. content: MEMORY_UPDATE,
  157. role: "system",
  158. });
  159. expect(bodyMessages(capture.bodies[1]!)[0]).toEqual({
  160. content: [
  161. {
  162. cache_control: { type: "ephemeral" },
  163. text: "tool batch completed",
  164. type: "text",
  165. },
  166. ],
  167. role: "user",
  168. });
  169. expect(capture.headers.map((headers) => headers["anthropic-beta"])).toEqual([
  170. "mid-conversation-system-2026-04-07",
  171. "mid-conversation-system-2026-04-07",
  172. "mid-conversation-system-2026-04-07",
  173. ]);
  174. });
  175. it("projects exact Extraction and Dream prompts with the permitted tool catalog", async () => {
  176. const capture = await startProviderBodyCapture();
  177. const adapter = createAdapter(capture.baseURL);
  178. await sendGenerateRequest(
  179. adapter,
  180. [
  181. systemMessage(MAIN_MEMORY, true),
  182. { content: "remember this durable preference", role: "user" },
  183. { content: "main answer", role: "assistant" },
  184. userMessage(EXTRACTION_PROMPT, true),
  185. ],
  186. MEMORY_TOOLS,
  187. );
  188. await sendGenerateRequest(
  189. adapter,
  190. [
  191. systemMessage(MAIN_MEMORY, true),
  192. { content: "completed session", role: "user" },
  193. userMessage(DREAM_PROMPT, true),
  194. ],
  195. MEMORY_TOOLS,
  196. );
  197. expect(capture.bodies).toHaveLength(2);
  198. expect(bodyMessages(capture.bodies[0]!).at(-1)).toEqual({
  199. content: [
  200. {
  201. cache_control: { type: "ephemeral" },
  202. text: EXTRACTION_PROMPT,
  203. type: "text",
  204. },
  205. ],
  206. role: "user",
  207. });
  208. expect(bodyMessages(capture.bodies[1]!).at(-1)).toEqual({
  209. content: [
  210. {
  211. text: "completed session",
  212. type: "text",
  213. },
  214. {
  215. cache_control: { type: "ephemeral" },
  216. text: DREAM_PROMPT,
  217. type: "text",
  218. },
  219. ],
  220. role: "user",
  221. });
  222. expect(capture.bodies.map(toolNames)).toEqual([
  223. ["Write", "Edit"],
  224. ["Write", "Edit"],
  225. ]);
  226. });
  227. it.each(["user", "project", "local"] as const)(
  228. "projects exact %s custom-agent Memory prompt and write tools into the final body",
  229. async (scope) => {
  230. const capture = await startProviderBodyCapture();
  231. const adapter = createAdapter(capture.baseURL);
  232. const rootDir = `/storage/agent-memory/${scope}`;
  233. const prompt = CUSTOM_AGENT_MEMORY.replaceAll("<MEMORY_ROOT>", rootDir).replaceAll(
  234. "<SCOPE_GUIDANCE>",
  235. CUSTOM_AGENT_SCOPE_GUIDANCE[scope],
  236. );
  237. await sendGenerateRequest(
  238. adapter,
  239. [
  240. systemMessage("You are a focused code reviewer.", true),
  241. systemMessage(`\n\n${prompt}`, true),
  242. { content: "review the change", role: "user" },
  243. ],
  244. MEMORY_TOOLS,
  245. );
  246. expect(capture.bodies).toHaveLength(1);
  247. expect(capture.bodies[0]!.system).toEqual([
  248. {
  249. cache_control: { type: "ephemeral" },
  250. text: "You are a focused code reviewer.",
  251. type: "text",
  252. },
  253. {
  254. cache_control: { type: "ephemeral" },
  255. text: `\n\n${prompt}`,
  256. type: "text",
  257. },
  258. ]);
  259. expect(systemTexts(capture.bodies[0]!)).not.toContain(MAIN_MEMORY);
  260. expect(toolNames(capture.bodies[0]!)).toEqual(["Write", "Edit"]);
  261. },
  262. );
  263. });
  264. function createAdapter(baseURL: string): AiSdkModelAdapter {
  265. return new AiSdkModelAdapter({
  266. registry: new TestProviderConfigFixture({
  267. env: {},
  268. providers: {
  269. anthropic: {
  270. apiKey: "provider-body-test-key",
  271. baseURL,
  272. headers: { "anthropic-beta": "mid-conversation-system-2026-04-07" },
  273. kind: "anthropic",
  274. },
  275. },
  276. }),
  277. retry: { maxAttempts: 1 },
  278. });
  279. }
  280. async function sendGenerateRequest(
  281. adapter: AiSdkModelAdapter,
  282. messages: ModelInputMessage[],
  283. tools?: ModelToolContract[],
  284. ): Promise<void> {
  285. try {
  286. await executeAdapterGenerateText(adapter, {
  287. providerId: "anthropic" as never,
  288. modelId: MODEL.modelId,
  289. messages,
  290. tools,
  291. });
  292. } catch {
  293. // 本地 capture endpoint 在记录最终 body 后固定返回 400;请求是否真正到达由调用方断言。
  294. }
  295. }
  296. async function sendStreamingRequest(
  297. adapter: AiSdkModelAdapter,
  298. messages: ModelInputMessage[],
  299. ): Promise<void> {
  300. try {
  301. for await (const _event of executeAdapterStreamText(adapter, {
  302. providerId: "anthropic" as never,
  303. modelId: MODEL.modelId,
  304. messages,
  305. })) {
  306. // Capture endpoint 不产生流事件。
  307. }
  308. } catch {
  309. // 本地 capture endpoint 在记录最终 body 后固定返回 400;请求是否真正到达由调用方断言。
  310. }
  311. }
  312. function systemMessage(content: string, cached = false): ModelInputMessage {
  313. return {
  314. ...(cached ? { cacheControl: { type: "ephemeral" as const } } : {}),
  315. content,
  316. role: "system",
  317. };
  318. }
  319. function userMessage(content: string, cached = false): ModelInputMessage {
  320. return {
  321. ...(cached ? { cacheControl: { type: "ephemeral" as const } } : {}),
  322. content,
  323. role: "user",
  324. };
  325. }
  326. function memoryFixture(filename: string, preserveFinalLf = false): string {
  327. const content = readFileSync(
  328. new URL(`../../core/tests/fixtures/memory/${filename}`, import.meta.url),
  329. "utf8",
  330. );
  331. return !preserveFinalLf && content.endsWith("\n") ? content.slice(0, -1) : content;
  332. }
  333. async function startProviderBodyCapture(): Promise<{
  334. baseURL: string;
  335. bodies: Record<string, unknown>[];
  336. headers: IncomingHttpHeaders[];
  337. }> {
  338. const bodies: Record<string, unknown>[] = [];
  339. const headers: IncomingHttpHeaders[] = [];
  340. const server = createServer(async (request, response) => {
  341. let body = "";
  342. for await (const chunk of request) body += chunk.toString();
  343. bodies.push(JSON.parse(body) as Record<string, unknown>);
  344. headers.push(request.headers);
  345. response.writeHead(400, { "content-type": "application/json" });
  346. response.end(
  347. JSON.stringify({
  348. error: { message: "request captured", type: "invalid_request_error" },
  349. type: "error",
  350. }),
  351. );
  352. });
  353. openServers.push(server);
  354. const baseURL = await listenServer(server);
  355. return { baseURL, bodies, headers };
  356. }
  357. function systemTexts(body: Record<string, unknown>): string[] {
  358. return contentTexts(body.system);
  359. }
  360. function bodyMessages(body: Record<string, unknown>): Record<string, unknown>[] {
  361. if (!Array.isArray(body.messages)) return [];
  362. return body.messages.flatMap((message) =>
  363. message && typeof message === "object" ? [message as Record<string, unknown>] : [],
  364. );
  365. }
  366. function requestBodyText(body: Record<string, unknown>): string {
  367. return [
  368. ...systemTexts(body),
  369. ...bodyMessages(body).flatMap((message) => contentTexts(message.content)),
  370. ].join("\n");
  371. }
  372. function contentTexts(content: unknown): string[] {
  373. if (typeof content === "string") return [content];
  374. if (!Array.isArray(content)) return [];
  375. return content.flatMap((block) => {
  376. if (!block || typeof block !== "object") return [];
  377. const text = (block as Record<string, unknown>).text;
  378. return typeof text === "string" ? [text] : [];
  379. });
  380. }
  381. function toolNames(body: Record<string, unknown>): string[] {
  382. if (!Array.isArray(body.tools)) return [];
  383. return body.tools.flatMap((tool) => {
  384. if (!tool || typeof tool !== "object") return [];
  385. const name = (tool as Record<string, unknown>).name;
  386. return typeof name === "string" ? [name] : [];
  387. });
  388. }
  389. async function listenServer(server: Server): Promise<string> {
  390. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  391. const address = server.address();
  392. if (!address || typeof address === "string") throw new Error("capture server has no port");
  393. return `http://127.0.0.1:${address.port}`;
  394. }
  395. async function closeServer(server: Server): Promise<void> {
  396. if (!server.listening) return;
  397. await new Promise<void>((resolve, reject) =>
  398. server.close((error) => (error ? reject(error) : resolve())),
  399. );
  400. }