compact-restore-wire.e2e.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // compaction 之后补回的内容走真实 runtime、真实 Read / Bash / Agent 与 `anthropic-messages` wire:
  2. // 摘要文本的选取与摘要回复里的工具调用(compact/README.md「摘要文本的选取」)、文件补回在 user 侧、
  3. // 后台任务状态(rewind-compact.md「Compact 之后的上下文布局」的文件恢复与后台任务状态)。每个场景都在新 app 里冷恢复,
  4. // 检查已发出的消息逐字节回放。
  5. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  6. import { createServer, type ServerResponse } from "node:http";
  7. import { tmpdir } from "node:os";
  8. import { join } from "node:path";
  9. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  10. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  11. import { createSessionId } from "@zcode/contracts";
  12. import {
  13. ApiKeyAccessConfig,
  14. ModelConfig,
  15. ModelOptionSpecsConfig,
  16. ModelPropertiesConfig,
  17. ProviderApiConfig,
  18. ProviderConfig,
  19. ProviderRegistry,
  20. } from "@zcode/provider";
  21. import { createZCodeApp } from "../src/app/create-app.js";
  22. import { createRuntimeAiSdkModelExecutionConfig } from "../src/model-config.js";
  23. import { createModelAdapter } from "../src/model-factory.js";
  24. const PROVIDER_ID = "compact-wire";
  25. const MODEL_ID = "compact-wire-model";
  26. const SUMMARY_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  27. type Block = Record<string, unknown> & { type?: string };
  28. type WireMessage = { role: string; content: string | Block[] };
  29. type WireBody = {
  30. system?: Block[];
  31. messages: WireMessage[];
  32. tools?: Array<{ name: string }>;
  33. stream?: boolean;
  34. };
  35. type Reply = { content: Block[]; stop: "tool_use" | "end_turn" };
  36. type App = Awaited<ReturnType<typeof createZCodeApp>>;
  37. interface Fixture {
  38. root: string;
  39. workspace: string;
  40. bodies: WireBody[];
  41. /** 按请求内容给出回复;返回 undefined 时回复一段文字。可以返回 Promise,用来扣住子代理。 */
  42. respond: (body: WireBody) => Reply | undefined | Promise<Reply | undefined>;
  43. /** 打开一个 app,执行 action 后关闭;resume 时从同一个存档冷恢复。 */
  44. withApp(action: (app: App) => Promise<void>, options?: { resume?: boolean }): Promise<void>;
  45. waitForRequest(predicate: (body: WireBody) => boolean): Promise<WireBody>;
  46. close(): Promise<void>;
  47. }
  48. let fixture: Fixture | undefined;
  49. let previousStorageDir: string | undefined;
  50. beforeEach(() => {
  51. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  52. });
  53. afterEach(async () => {
  54. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  55. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  56. if (fixture) {
  57. await fixture.close();
  58. await rm(fixture.root, { recursive: true, force: true });
  59. }
  60. fixture = undefined;
  61. });
  62. describe.skipIf(process.platform === "win32")("compaction restore over the wire", () => {
  63. it.each([true, false])(
  64. "keeps the chosen summary block, restores the read file on the user side and restates the running shell (MCS %s)",
  65. { timeout: 60_000 },
  66. async (mcs) => {
  67. const f = await createFixture({ mcs });
  68. const notes = join(f.workspace, "notes.txt");
  69. await writeFile(notes, "WIRE_FILE_LINE\n");
  70. let mainCalls = 0;
  71. f.respond = (body) => {
  72. // 摘要回复:多个文本块,最后还调用了工具。只留最后一个带 <summary> 的块,工具不执行。
  73. if (isSummaryRequest(body)) {
  74. return {
  75. content: [
  76. { type: "text", text: "<summary>WIRE_SUMMARY_DROPPED</summary>" },
  77. { type: "text", text: "<analysis>a</analysis><summary>WIRE_SUMMARY_KEPT</summary>" },
  78. { type: "text", text: "WIRE_SUMMARY_TRAILING" },
  79. {
  80. type: "tool_use",
  81. id: "toolu_summary_read",
  82. name: "Read",
  83. input: { file_path: notes },
  84. },
  85. ],
  86. stop: "tool_use",
  87. };
  88. }
  89. mainCalls += 1;
  90. if (mainCalls === 1) return toolCall("toolu_read", "Read", { file_path: notes });
  91. if (mainCalls === 2) {
  92. return toolCall("toolu_bg", "Bash", {
  93. command: "sleep 30",
  94. description: "wire sleep",
  95. run_in_background: true,
  96. });
  97. }
  98. return undefined;
  99. };
  100. await f.withApp(async (app) => {
  101. await app.submitPrompt("read the notes");
  102. await app.submitPrompt("/compact");
  103. await app.submitPrompt("after compact");
  104. });
  105. expect(f.bodies.filter(isSummaryRequest)).toHaveLength(1);
  106. expect(JSON.stringify(f.bodies)).not.toContain('"tool_use_id":"toolu_summary_read"');
  107. const live = f.bodies.find((body) => lastUserText(body) === "after compact")!;
  108. const liveText = JSON.stringify(live.messages);
  109. expect(liveText).toContain("Summary:\\nWIRE_SUMMARY_KEPT");
  110. expect(liveText).not.toContain("WIRE_SUMMARY_DROPPED");
  111. expect(liveText).not.toContain("WIRE_SUMMARY_TRAILING");
  112. // 文件补回是两条 user 侧提醒,紧挨着;MCS 开时也不进 system。
  113. const userTexts = textBlocks(live, "user");
  114. const called = userTexts.indexOf(
  115. `<system-reminder>\nCalled the Read tool with the following input: ${JSON.stringify({ file_path: notes })}\n</system-reminder>\n`,
  116. );
  117. expect(called).toBeGreaterThan(-1);
  118. expect(userTexts[called + 1]).toBe(
  119. `<system-reminder>\nResult of calling the Read tool:\n1\tWIRE_FILE_LINE\n2\t\n</system-reminder>${mcs ? "\n" : ""}`,
  120. );
  121. expect(JSON.stringify([live.system, textBlocks(live, "system")])).not.toContain(
  122. "Result of calling the Read tool",
  123. );
  124. // 后台命令的 ID 与输出路径取自压缩前的启动结果;命令原文来自登记时的输入。
  125. const launched = toolResultText(
  126. f.bodies.find((body) => hasToolResult(body, "toolu_bg"))!,
  127. "toolu_bg",
  128. ).match(
  129. /^Command running in background with ID: (\S+)\. Output is being written to: (\S+)\./,
  130. )!;
  131. const shellText = `Background shell ${launched[1]} ("wire sleep") is still running (command, shown on one line: \`sleep 30\`). Do not start it again; to restart it, stop it with TaskStop first. You can read its output at ${launched[2]}.`;
  132. if (mcs) {
  133. expect(textBlocks(live, "system").filter((text) => text.includes(shellText))).toHaveLength(
  134. 1,
  135. );
  136. } else {
  137. // MCS 关时是 user 侧提醒,排在文件补回之后。
  138. expect(userTexts.indexOf(`<system-reminder>\n${shellText}\n</system-reminder>`)).toBe(
  139. called + 2,
  140. );
  141. }
  142. await f.withApp(
  143. async (app) => {
  144. await app.submitPrompt("after resume");
  145. },
  146. { resume: true },
  147. );
  148. expectColdReplay(live, f.bodies.at(-1)!);
  149. },
  150. );
  151. it(
  152. "restates a running agent, delivers its result once, then restates it as ended within 30 seconds",
  153. { timeout: 60_000 },
  154. async () => {
  155. const f = await createFixture({ mcs: true });
  156. const isChild = (body: WireBody) => !(body.tools ?? []).some((tool) => tool.name === "Agent");
  157. const isParent = (body: WireBody) => !isChild(body) && !isSummaryRequest(body);
  158. let releaseChild = () => {};
  159. const childGate = new Promise<void>((resolve) => {
  160. releaseChild = resolve;
  161. });
  162. let parentCalls = 0;
  163. f.respond = async (body) => {
  164. if (isSummaryRequest(body)) {
  165. return {
  166. content: [{ type: "text", text: "<summary>WIRE_AGENT_SUMMARY</summary>" }],
  167. stop: "end_turn",
  168. };
  169. }
  170. // 子代理一直扣住,直到第一次压缩之后。
  171. if (isChild(body)) {
  172. await childGate;
  173. return { content: [{ type: "text", text: "WIRE_CHILD_RESULT" }], stop: "end_turn" };
  174. }
  175. parentCalls += 1;
  176. if (parentCalls !== 1) return undefined;
  177. return toolCall("toolu_agent", "Agent", {
  178. description: "wire child",
  179. prompt: "Report WIRE_CHILD_RESULT.",
  180. subagent_type: "general-purpose",
  181. run_in_background: true,
  182. });
  183. };
  184. const isNotification = (body: WireBody) =>
  185. isParent(body) && JSON.stringify(body.messages.at(-1)).includes("<task-notification>");
  186. await f.withApp(async (app) => {
  187. await app.submitPrompt("launch the child");
  188. await app.submitPrompt("/compact");
  189. await app.submitPrompt("after compact");
  190. releaseChild();
  191. await f.waitForRequest(isNotification);
  192. await waitFor(() => app.runtime.getActiveTurnInfo() === undefined);
  193. await app.submitPrompt("/compact");
  194. await app.submitPrompt("after second compact");
  195. });
  196. const agentId = toolResultText(
  197. f.bodies.find((body) => isParent(body) && hasToolResult(body, "toolu_agent"))!,
  198. "toolu_agent",
  199. ).match(/agentId: (\S+)/)![1]!;
  200. const running = f.bodies.find((body) => lastUserText(body) === "after compact")!;
  201. expect(textBlocks(running, "system").join("\n")).toContain(
  202. `Background agent "wire child" (${agentId}) is still running. Do NOT spawn a duplicate. You will be notified when it completes. Send it a message with SendMessage if you need a progress report before then.`,
  203. );
  204. // 运行中的状态不代替终态通知:结果在压缩之后照常送达,而且只送一次。
  205. const notified = f.bodies.find(isNotification)!;
  206. expect(JSON.stringify(notified.messages).split("<task-notification>")).toHaveLength(2);
  207. expect(JSON.stringify(notified.messages)).toContain("WIRE_CHILD_RESULT");
  208. const ended = f.bodies.find((body) => lastUserText(body) === "after second compact")!;
  209. const endedText = textBlocks(ended, "system").join("\n");
  210. expect(endedText).toContain(
  211. `Task ${agentId} (type: local_agent) (status: completed) (description: wire child) Send it a message with SendMessage to retrieve its result.`,
  212. );
  213. expect(endedText).not.toContain("is still running");
  214. await f.withApp(
  215. async (app) => {
  216. await app.submitPrompt("after resume");
  217. },
  218. { resume: true },
  219. );
  220. expectColdReplay(ended, f.bodies.at(-1)!);
  221. },
  222. );
  223. });
  224. async function createFixture(options: { mcs: boolean }): Promise<Fixture> {
  225. const root = await mkdtemp(join(tmpdir(), "zcode-compact-wire-"));
  226. const workspace = join(root, "workspace");
  227. const storageDir = join(root, "storage");
  228. await mkdir(workspace, { recursive: true });
  229. process.env.ZCODE_STORAGE_DIR = storageDir;
  230. const bodies: WireBody[] = [];
  231. const waiters: Array<() => void> = [];
  232. const server = createServer(async (req, res) => {
  233. let raw = "";
  234. for await (const chunk of req) raw += chunk;
  235. if (!req.url?.includes("/messages")) {
  236. res.writeHead(404).end("{}");
  237. return;
  238. }
  239. const body = JSON.parse(raw) as WireBody & { model: string };
  240. bodies.push(body);
  241. const index = bodies.length;
  242. for (const wake of waiters.splice(0)) wake();
  243. const reply = (await fixture?.respond(body)) ?? {
  244. content: [{ type: "text", text: "done" }],
  245. stop: "end_turn",
  246. };
  247. writeReply(res, body, index, reply);
  248. });
  249. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  250. const address = server.address();
  251. if (!address || typeof address === "string") throw new Error("mock server has no port");
  252. const registry = providerRegistry(`http://127.0.0.1:${address.port}/v1`, options.mcs);
  253. const sessionId = createSessionId("compact-wire");
  254. // shell 用隔离的 HOME,不读本机 shell 配置;PATH 等其余环境沿用测试进程。
  255. const home = join(root, "home");
  256. await mkdir(home, { recursive: true });
  257. const env = { ...process.env, HOME: home, ZCODE_STORAGE_DIR: storageDir };
  258. const waitForRequest = async (predicate: (body: WireBody) => boolean) => {
  259. await waitFor(() => bodies.some(predicate), waiters);
  260. return bodies.find(predicate)!;
  261. };
  262. const withApp = async (
  263. action: (app: App) => Promise<void>,
  264. appOptions: { resume?: boolean } = {},
  265. ) => {
  266. const sessionStore = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  267. const app = await createZCodeApp({
  268. env,
  269. modelAdapter: createModelAdapter({
  270. env,
  271. executionConfig: createRuntimeAiSdkModelExecutionConfig(env),
  272. }),
  273. providerRegistry: registry,
  274. pluginStorageRoot: join(root, "plugins"),
  275. readSubagentRuntimeConfig: async () => ({ kind: "built-in-fallback" }),
  276. runtimeConfig: {
  277. mcp: { enabled: false },
  278. memory: { enabled: false },
  279. mode: "yolo",
  280. modelSelection: {
  281. providerId: PROVIDER_ID,
  282. modelId: MODEL_ID,
  283. options: { reasoningLevel: "disabled" },
  284. },
  285. modelStreaming: "off",
  286. storage: { dir: storageDir },
  287. subagents: { enabled: true },
  288. titleGeneration: { enabled: false },
  289. workingDirectory: workspace,
  290. },
  291. ...(appOptions.resume ? { resume: true } : {}),
  292. sessionId,
  293. sessionStore,
  294. skipUserConfig: true,
  295. });
  296. try {
  297. await action(app);
  298. // 等当前轮次结束再关闭;轮次中途关闭会留下中断标记,改变下一次请求。
  299. await waitFor(() => app.runtime.getActiveTurnInfo() === undefined);
  300. } finally {
  301. await app.close?.();
  302. sessionStore.close();
  303. }
  304. };
  305. const close = async () => {
  306. server.closeAllConnections();
  307. await new Promise<void>((resolve) => server.close(() => resolve()));
  308. };
  309. fixture = { root, workspace, bodies, respond: () => undefined, withApp, waitForRequest, close };
  310. return fixture;
  311. }
  312. /** 压缩摘要固定走流式请求,按 SSE 回复;其余请求回复 JSON。 */
  313. function writeReply(
  314. res: ServerResponse,
  315. body: WireBody & { model: string },
  316. index: number,
  317. reply: Reply,
  318. ) {
  319. const message = {
  320. id: `msg_${index}`,
  321. type: "message",
  322. role: "assistant",
  323. model: body.model,
  324. content: reply.content,
  325. stop_reason: reply.stop,
  326. stop_sequence: null,
  327. usage: { input_tokens: 100, output_tokens: 5 },
  328. };
  329. if (!body.stream) {
  330. res.writeHead(200, { "content-type": "application/json" });
  331. res.end(JSON.stringify(message));
  332. return;
  333. }
  334. res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
  335. const events: Array<Record<string, unknown>> = [
  336. {
  337. type: "message_start",
  338. message: {
  339. ...message,
  340. content: [],
  341. stop_reason: null,
  342. usage: { input_tokens: 100, output_tokens: 1 },
  343. },
  344. },
  345. ];
  346. for (const [blockIndex, block] of reply.content.entries()) {
  347. const toolUse = block.type === "tool_use";
  348. events.push(
  349. {
  350. type: "content_block_start",
  351. index: blockIndex,
  352. content_block: toolUse ? { ...block, input: {} } : { type: "text", text: "" },
  353. },
  354. {
  355. type: "content_block_delta",
  356. index: blockIndex,
  357. delta: toolUse
  358. ? { type: "input_json_delta", partial_json: JSON.stringify(block.input) }
  359. : { type: "text_delta", text: block.text },
  360. },
  361. { type: "content_block_stop", index: blockIndex },
  362. );
  363. }
  364. events.push(
  365. {
  366. type: "message_delta",
  367. delta: { stop_reason: reply.stop, stop_sequence: null },
  368. usage: { output_tokens: 5 },
  369. },
  370. { type: "message_stop" },
  371. );
  372. for (const event of events) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
  373. res.end();
  374. }
  375. /** 轮询条件;收到新请求时立即再查一次。 */
  376. async function waitFor(check: () => boolean, waiters: Array<() => void> = []): Promise<void> {
  377. const deadline = Date.now() + 15_000;
  378. while (!check()) {
  379. if (Date.now() > deadline) throw new Error("condition was not reached");
  380. await new Promise<void>((resolve) => {
  381. waiters.push(resolve);
  382. setTimeout(resolve, 50);
  383. });
  384. }
  385. }
  386. function providerRegistry(baseUrl: string, mcs: boolean): ProviderRegistry {
  387. return new ProviderRegistry([
  388. {
  389. providerId: PROVIDER_ID,
  390. config: new ProviderConfig({
  391. access: new ApiKeyAccessConfig({ apiKey: "wire-local-fake" }),
  392. api: new ProviderApiConfig({ type: "anthropic-messages", baseUrl }),
  393. models: [MODEL_ID],
  394. enabled: true,
  395. }),
  396. models: [
  397. {
  398. modelId: MODEL_ID,
  399. config: new ModelConfig({
  400. properties: new ModelPropertiesConfig({
  401. contextWindow: 1_000_000,
  402. inputFormat: { supportsText: true },
  403. outputFormat: { supportsText: true },
  404. supportsToolCall: true,
  405. supportsJsonSchemaOutput: true,
  406. supportsNativeWebSearch: false,
  407. supportsMidConversationSystem: mcs,
  408. }),
  409. optionSpecs: new ModelOptionSpecsConfig({
  410. reasoningLevel: { values: ["disabled"], map: "{}" },
  411. maxOutputTokens: { max: 10_000, map: '{"max_tokens": maxOutputTokens}' },
  412. }),
  413. }),
  414. },
  415. ],
  416. },
  417. ]);
  418. }
  419. function isSummaryRequest(body: WireBody): boolean {
  420. return JSON.stringify(body.messages.at(-1)).includes(SUMMARY_SENTINEL);
  421. }
  422. function toolCall(id: string, name: string, input: Record<string, unknown>): Reply {
  423. return { content: [{ type: "tool_use", id, name, input }], stop: "tool_use" };
  424. }
  425. /** 该角色所有消息里的文本,按出现顺序;字符串内容算一条。 */
  426. function textBlocks(body: WireBody, role: string): string[] {
  427. return body.messages
  428. .filter((message) => message.role === role)
  429. .flatMap((message) =>
  430. typeof message.content === "string"
  431. ? [message.content]
  432. : message.content.flatMap((block) => (block.type === "text" ? [String(block.text)] : [])),
  433. );
  434. }
  435. /** 最后一条 user 消息的最后一个文本块,即本次请求的用户输入。 */
  436. function lastUserText(body: WireBody): string | undefined {
  437. return textBlocks({ messages: body.messages.filter((m) => m.role === "user") }, "user").at(-1);
  438. }
  439. function hasToolResult(body: WireBody, toolUseId: string): boolean {
  440. return body.messages.some(
  441. (message) =>
  442. Array.isArray(message.content) &&
  443. message.content.some(
  444. (block) => block.type === "tool_result" && block.tool_use_id === toolUseId,
  445. ),
  446. );
  447. }
  448. function toolResultText(body: WireBody, toolUseId: string): string {
  449. for (const message of body.messages) {
  450. if (!Array.isArray(message.content)) continue;
  451. for (const block of message.content) {
  452. if (block.type !== "tool_result" || block.tool_use_id !== toolUseId) continue;
  453. const content = block.content;
  454. return Array.isArray(content)
  455. ? (content as Block[]).map((item) => String(item.text ?? "")).join("")
  456. : String(content ?? "");
  457. }
  458. }
  459. throw new Error(`${toolUseId} has no tool_result`);
  460. }
  461. /**
  462. * 冷恢复后的首个请求:重启前最后一个请求的 system 与 messages 原样在前,只在后面追加。
  463. * 缓存断点会移到最新的消息上,不算内容。
  464. */
  465. function expectColdReplay(live: WireBody, resumed: WireBody) {
  466. expect(withoutCacheControl(resumed.system)).toEqual(withoutCacheControl(live.system));
  467. expect(withoutCacheControl(resumed.messages.slice(0, live.messages.length))).toEqual(
  468. withoutCacheControl(live.messages),
  469. );
  470. }
  471. function withoutCacheControl(value: unknown): unknown {
  472. if (Array.isArray(value)) return value.map(withoutCacheControl);
  473. if (!value || typeof value !== "object") return value;
  474. return Object.fromEntries(
  475. Object.entries(value)
  476. .filter(([key]) => key !== "cache_control")
  477. .map(([key, item]) => [key, withoutCacheControl(item)]),
  478. );
  479. }