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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. // Continue 写入历史:下一轮第一个请求仍带着本轮的三条。
  124. expect(requests.map((request) => countContinuePrompts(request.messages))).toEqual([
  125. 0, 0, 1, 2, 3, 3,
  126. ]);
  127. const records = await recordedRequests();
  128. expect(records).toHaveLength(requests.length);
  129. for (const [index, request] of requests.entries()) {
  130. // 记录与实际请求是同一份消息。
  131. const expected = withoutCacheControl(request.messages);
  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 进入待总结历史;压缩记录与实际压缩请求是同一份消息。
  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.map((record) => countContinuePrompts(record.messages))).toEqual(
  196. requests.map((request) => countContinuePrompts(request.messages)),
  197. );
  198. const compactRecords = records.filter((record) => record.querySource === "compact");
  199. expect(compactRecords).toHaveLength(1);
  200. expect(withoutCacheControl(compactRecords[0]!.messages)).toEqual(
  201. withoutCacheControl(actual.messages),
  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(request.messages);
  240. expect(withoutCacheControl(records[index]!.messages)).toEqual(expected);
  241. expect(
  242. withoutCacheControl(snapshots.mock.results[index]!.value.modelRequest.messages),
  243. ).toEqual(expected);
  244. }
  245. } finally {
  246. await runtime.closeBrowserSession();
  247. }
  248. },
  249. );
  250. it.each([CompactTrigger.Manual, CompactTrigger.Reactive])(
  251. "promotes discovery at successful %s compact and keeps it across the next compact",
  252. async (trigger) => {
  253. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) =>
  254. isCompact(request)
  255. ? { ...done(), text: "<summary>Continue.</summary>" }
  256. : index === 1
  257. ? search()
  258. : done(),
  259. );
  260. try {
  261. await runtime.executeTurn("Load lookup.");
  262. await runtime.executeTurn("Keep working.");
  263. const internal = runtime as unknown as AgentRuntimeInternal;
  264. for (let pass = 0; pass < 2; pass++) {
  265. const result = await internal.compactActiveConversation(
  266. undefined,
  267. createRootTraceContext(),
  268. [],
  269. { trigger },
  270. );
  271. expect(result.outcome).toBe("compacted");
  272. // 返回时公告就应使用提升后的分类,而不是等待下一次正常收集纠正。
  273. expect(
  274. result.entries
  275. .filter((e) => e.metadata?.toolSearchAnnouncement)
  276. .flatMap((e) => e.metadata!.toolSearchAnnouncement!.addedNames),
  277. ).not.toContain(TARGET);
  278. await runtime.executeTurn("Continue after compact.");
  279. const request = requests.at(-1)!;
  280. expect(request.tools?.find((t) => t.name === TARGET)).toMatchObject({ name: TARGET });
  281. expect(request.tools?.find((t) => t.name === TARGET)?.deferLoading).toBeUndefined();
  282. expect(request.tools?.map((t) => t.name)).toContain("DeferredToolCall");
  283. }
  284. } finally {
  285. await runtime.closeBrowserSession();
  286. }
  287. },
  288. );
  289. it.each(["cancel", "persist failure"])(
  290. "does not promote Local tools on compact %s",
  291. async (failure) => {
  292. const controller = new AbortController();
  293. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) => {
  294. if (isCompact(request)) {
  295. if (failure === "cancel") controller.abort();
  296. return { ...done(), text: "<summary>Candidate.</summary>" };
  297. }
  298. return index === 1 ? search() : done();
  299. });
  300. try {
  301. await runtime.executeTurn("Load lookup.");
  302. await runtime.executeTurn("Keep working.");
  303. const internal = runtime as unknown as AgentRuntimeInternal;
  304. const before = internal.messageHistory.toRuntimeEntries();
  305. if (failure === "persist failure")
  306. vi.spyOn(internal, "persistCompactSummary").mockRejectedValue(new Error("persist failed"));
  307. await expect(
  308. internal.compactActiveConversation(undefined, createRootTraceContext(), [], {
  309. abortSignal: controller.signal,
  310. }),
  311. ).rejects.toThrow();
  312. expect(internal.messageHistory.toRuntimeEntries()).toEqual(before);
  313. await runtime.executeTurn("Still use the search result.");
  314. expect(requests.at(-1)!.tools?.some((t) => t.name === TARGET)).toBe(false);
  315. } finally {
  316. await runtime.closeBrowserSession();
  317. }
  318. },
  319. );