tool-search-request-recording.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import { afterEach, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. createRootTraceContext,
  5. CompactTrigger,
  6. ModelErrorCode,
  7. SessionEventType,
  8. type Model,
  9. type ModelRequest,
  10. type ModelRequestPayload,
  11. type ModelResult,
  12. } from "@zcode/contracts";
  13. import { TurnMachineImpl } from "../src/agent/turn-machine.js";
  14. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  15. import type { AgentRuntimeConfig } from "../src/runtime/types.js";
  16. import { createToolRegistry } from "../src/tool/registry.js";
  17. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  18. import { createTestModelFactory } from "./test-runtime-model.js";
  19. import { createTestSessionEventStore } from "./test-event-store.js";
  20. import {
  21. countContinuePrompts,
  22. OUTPUT_TOKEN_CONTINUE_PROMPT,
  23. registerReadOnlyTool,
  24. requestText,
  25. } from "./runtime-output-token-continuation-test-helpers.js";
  26. const TARGET = "mcp__test__lookup";
  27. const SUCCESS_MESSAGE = "Tool loaded.";
  28. const cases = (["native", "local"] as const).flatMap((mode) =>
  29. (["off", "on"] as const).map((modelStreaming) => ({ mode, modelStreaming })),
  30. );
  31. const done = (): ModelResult => ({ text: "done", finishReason: "stop", usage: {} });
  32. const search = (): ModelResult => ({
  33. text: "",
  34. finishReason: "tool-calls",
  35. usage: {},
  36. toolCalls: [{ id: "search", name: "ToolSearch", input: { query: `select:${TARGET}` } }],
  37. });
  38. const isCompact = (request: ModelRequest) =>
  39. requestText(request.messages).includes("create a detailed summary");
  40. const successCount = (messages: ModelRequest["messages"]) =>
  41. messages.filter((message) => message.content === SUCCESS_MESSAGE).length;
  42. const withoutCacheControl = (messages: ModelRequest["messages"]) =>
  43. messages.map(({ cacheControl: _cacheControl, ...message }) => message);
  44. afterEach(() => vi.restoreAllMocks());
  45. function fixture(
  46. config: Partial<AgentRuntimeConfig>,
  47. respond: (request: ModelRequest, index: number) => ModelResult,
  48. ) {
  49. const sessionId = createSessionId("toolsearch-request-recording");
  50. const eventStore = createTestSessionEventStore();
  51. const requests: ModelRequest[] = [];
  52. const generateText = async (request: ModelRequest) => {
  53. requests.push(structuredClone(request));
  54. return respond(request, requests.length);
  55. };
  56. const baseFactory = createTestModelFactory({
  57. generateText,
  58. async *streamText(request) {
  59. const result = await generateText(request);
  60. for (const toolCall of result.toolCalls ?? []) yield { type: "tool_call", toolCall };
  61. if (result.text) {
  62. yield { type: "text_start", id: "text" };
  63. yield { type: "text_delta", id: "text", text: result.text };
  64. yield { type: "text_end", id: "text" };
  65. }
  66. yield { type: "finish", finishReason: result.finishReason, usage: result.usage };
  67. },
  68. });
  69. const wrap = (model: Model): Model => ({
  70. ...model,
  71. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  72. bind: (options) => wrap(model.bind(options)),
  73. });
  74. const registry = createToolRegistry();
  75. registerReadOnlyTool(registry, TARGET, "unused");
  76. const entry = registry.get(TARGET)!;
  77. registry.register(
  78. {
  79. ...entry,
  80. metadata: {
  81. ...entry.metadata,
  82. shouldDefer: true,
  83. mcpPresentation: { serverName: "test", toolName: "lookup" },
  84. },
  85. },
  86. { silentDuplicateWarning: true },
  87. );
  88. const runtime = createTestAgentRuntime(
  89. sessionId,
  90. {
  91. titleGeneration: { enabled: false },
  92. systemPrompt: "Test request recording.",
  93. toolAllowlist: ["ToolSearch", "DeferredToolCall", TARGET],
  94. ...config,
  95. },
  96. { eventStore, toolRegistry: registry, modelFactory: (input) => wrap(baseFactory(input)) },
  97. );
  98. const recordedRequests = async () =>
  99. (await eventStore.getEvents(sessionId))
  100. .filter((event) => event.type === SessionEventType.ModelRequest)
  101. .map((event) => event.payload as ModelRequestPayload);
  102. return { runtime, requests, recordedRequests };
  103. }
  104. it.each(cases)(
  105. "retains success hints in continuation records and turn snapshots ($mode, streaming=$modelStreaming)",
  106. async ({ mode, modelStreaming }) => {
  107. const snapshots = vi.spyOn(TurnMachineImpl.prototype, "startModelRequest");
  108. const { runtime, requests, recordedRequests } = fixture(
  109. { toolSearch: { mode }, modelStreaming },
  110. (_request, index) =>
  111. index === 1
  112. ? search()
  113. : index <= 4
  114. ? { text: `partial ${index}`, finishReason: "length", usage: {} }
  115. : done(),
  116. );
  117. try {
  118. await runtime.executeTurn("Search for the lookup tool.");
  119. await runtime.executeTurn("Continue the task.");
  120. expect(requests.map((request) => successCount(request.messages))).toEqual(
  121. mode === "native" ? [0, 1, 1, 1, 1, 1] : [0, 0, 0, 0, 0, 0],
  122. );
  123. expect(requests.map((request) => countContinuePrompts(request.messages))).toEqual([
  124. 0, 0, 1, 2, 3, 0,
  125. ]);
  126. const records = await recordedRequests();
  127. expect(records).toHaveLength(requests.length);
  128. for (const [index, request] of requests.entries()) {
  129. const expected = withoutCacheControl(
  130. request.messages.filter((message) => message.content !== OUTPUT_TOKEN_CONTINUE_PROMPT),
  131. );
  132. expect(withoutCacheControl(records[index]!.messages)).toEqual(expected);
  133. expect(
  134. withoutCacheControl(snapshots.mock.results[index]!.value.modelRequest.messages),
  135. ).toEqual(expected);
  136. }
  137. const internal = runtime as unknown as AgentRuntimeInternal;
  138. expect(JSON.stringify(internal.messageHistory.toRuntimeEntries())).not.toContain(
  139. SUCCESS_MESSAGE,
  140. );
  141. expect(JSON.stringify(records)).not.toContain("loadedToolCallIds");
  142. } finally {
  143. await runtime.closeBrowserSession();
  144. }
  145. },
  146. );
  147. it.each(
  148. cases.flatMap((testCase) =>
  149. (["auto", "reactive"] as const).map((trigger) => ({ ...testCase, trigger })),
  150. ),
  151. )(
  152. "retains success hints in $trigger compact records during continuation ($mode, streaming=$modelStreaming)",
  153. async ({ mode, modelStreaming, trigger }) => {
  154. let mainCalls = 0;
  155. const { runtime, requests, recordedRequests } = fixture(
  156. {
  157. toolSearch: { mode },
  158. modelStreaming,
  159. ...(trigger === "auto"
  160. ? { compact: { contextWindow: 40000, bufferTokens: 10, summaryReserveTokens: 0 } }
  161. : {}),
  162. },
  163. (request) => {
  164. if (isCompact(request)) return { ...done(), text: "<summary>Continue the task.</summary>" };
  165. mainCalls++;
  166. if (mainCalls === 1) return search();
  167. if (mainCalls === 4 || mainCalls === 5)
  168. return {
  169. text: `partial ${mainCalls}`,
  170. finishReason: "length",
  171. usage: {
  172. inputTokens: trigger === "auto" && mainCalls === 5 ? 39995 : 1,
  173. outputTokens: 1,
  174. },
  175. };
  176. if (mainCalls === 6 && trigger === "reactive")
  177. throw Object.assign(new Error("provider context window exceeded"), {
  178. code: ModelErrorCode.ModelContextExceeded,
  179. });
  180. return done();
  181. },
  182. );
  183. try {
  184. await runtime.executeTurn("Search for the lookup tool.");
  185. await runtime.executeTurn("Prepare the next step.");
  186. const result = await runtime.executeTurn("Continue the task.");
  187. expect(result.response).toBe("done");
  188. const compactRequests = requests.filter(isCompact);
  189. expect(compactRequests).toHaveLength(1);
  190. const actual = compactRequests[0]!;
  191. // 两次续写让 Continue 进入待总结历史,真正覆盖 compact 的记录重建分支。
  192. expect(countContinuePrompts(actual.messages)).toBeGreaterThan(0);
  193. expect(successCount(actual.messages)).toBe(mode === "native" ? 1 : 0);
  194. const records = await recordedRequests();
  195. expect(records.every((record) => countContinuePrompts(record.messages) === 0)).toBe(true);
  196. const compactRecords = records.filter((record) => record.querySource === "compact");
  197. expect(compactRecords).toHaveLength(1);
  198. expect(withoutCacheControl(compactRecords[0]!.messages)).toEqual(
  199. withoutCacheControl(
  200. actual.messages.filter((message) => message.content !== OUTPUT_TOKEN_CONTINUE_PROMPT),
  201. ),
  202. );
  203. } finally {
  204. await runtime.closeBrowserSession();
  205. }
  206. },
  207. );
  208. it.each(cases)(
  209. "keeps repeated-search feedback stable in Continue, records and snapshots ($mode/$modelStreaming)",
  210. async ({ mode, modelStreaming }) => {
  211. const snapshots = vi.spyOn(TurnMachineImpl.prototype, "startModelRequest");
  212. const { runtime, requests, recordedRequests } = fixture(
  213. { toolSearch: { mode }, modelStreaming },
  214. (_request, index) => {
  215. if (index === 1) return search();
  216. if (index === 3)
  217. return {
  218. ...search(),
  219. toolCalls: [{ id: "repeat", name: "ToolSearch", input: { query: "select:lookup" } }],
  220. };
  221. if (index === 4) return { text: "partial", finishReason: "length", usage: {} };
  222. return done();
  223. },
  224. );
  225. try {
  226. await runtime.executeTurn("Load the lookup tool.");
  227. await runtime.executeTurn("Find lookup again using its short name.");
  228. expect(requests.map((r) => successCount(r.messages))).toEqual(
  229. mode === "local" ? [0, 0, 0, 0, 0] : [0, 1, 1, 2, 2],
  230. );
  231. const latest = requests.at(-1)!;
  232. const repeat = latest.messages.find((m) => m.role === "tool" && m.toolCallId === "repeat");
  233. expect(JSON.stringify(repeat)).toContain(
  234. mode === "local" ? "already available" : "tool_reference",
  235. );
  236. if (mode === "local") expect(JSON.stringify(repeat)).not.toContain("<functions>");
  237. const records = await recordedRequests();
  238. for (const [index, request] of requests.entries()) {
  239. const expected = withoutCacheControl(
  240. request.messages.filter((m) => m.content !== OUTPUT_TOKEN_CONTINUE_PROMPT),
  241. );
  242. expect(withoutCacheControl(records[index]!.messages)).toEqual(expected);
  243. expect(
  244. withoutCacheControl(snapshots.mock.results[index]!.value.modelRequest.messages),
  245. ).toEqual(expected);
  246. }
  247. } finally {
  248. await runtime.closeBrowserSession();
  249. }
  250. },
  251. );
  252. it.each([CompactTrigger.Manual, CompactTrigger.Reactive])(
  253. "promotes discovery at successful %s compact and keeps it across the next compact",
  254. async (trigger) => {
  255. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) =>
  256. isCompact(request)
  257. ? { ...done(), text: "<summary>Continue.</summary>" }
  258. : index === 1
  259. ? search()
  260. : done(),
  261. );
  262. try {
  263. await runtime.executeTurn("Load lookup.");
  264. await runtime.executeTurn("Keep working.");
  265. const internal = runtime as unknown as AgentRuntimeInternal;
  266. for (let pass = 0; pass < 2; pass++) {
  267. const result = await internal.compactActiveConversation(
  268. undefined,
  269. createRootTraceContext(),
  270. [],
  271. { trigger },
  272. );
  273. expect(result.outcome).toBe("compacted");
  274. // 返回时公告就应使用提升后的分类,而不是等待下一次正常收集纠正。
  275. expect(
  276. result.entries
  277. .filter((e) => e.metadata?.toolSearchAnnouncement)
  278. .flatMap((e) => e.metadata!.toolSearchAnnouncement!.addedNames),
  279. ).not.toContain(TARGET);
  280. await runtime.executeTurn("Continue after compact.");
  281. const request = requests.at(-1)!;
  282. expect(request.tools?.find((t) => t.name === TARGET)).toMatchObject({ name: TARGET });
  283. expect(request.tools?.find((t) => t.name === TARGET)?.deferLoading).toBeUndefined();
  284. expect(request.tools?.map((t) => t.name)).toContain("DeferredToolCall");
  285. }
  286. } finally {
  287. await runtime.closeBrowserSession();
  288. }
  289. },
  290. );
  291. it.each(["cancel", "persist failure"])(
  292. "does not promote Local tools on compact %s",
  293. async (failure) => {
  294. const controller = new AbortController();
  295. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) => {
  296. if (isCompact(request)) {
  297. if (failure === "cancel") controller.abort();
  298. return { ...done(), text: "<summary>Candidate.</summary>" };
  299. }
  300. return index === 1 ? search() : done();
  301. });
  302. try {
  303. await runtime.executeTurn("Load lookup.");
  304. await runtime.executeTurn("Keep working.");
  305. const internal = runtime as unknown as AgentRuntimeInternal;
  306. const before = internal.messageHistory.toRuntimeEntries();
  307. if (failure === "persist failure")
  308. vi.spyOn(internal, "persistCompactSummary").mockRejectedValue(new Error("persist failed"));
  309. await expect(
  310. internal.compactActiveConversation(undefined, createRootTraceContext(), [], {
  311. abortSignal: controller.signal,
  312. }),
  313. ).rejects.toThrow();
  314. expect(internal.messageHistory.toRuntimeEntries()).toEqual(before);
  315. await runtime.executeTurn("Still use the search result.");
  316. expect(requests.at(-1)!.tools?.some((t) => t.name === TARGET)).toBe(false);
  317. } finally {
  318. await runtime.closeBrowserSession();
  319. }
  320. },
  321. );