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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // 摘要指令紧跟 Continue 时,按相邻 user 规则在 Continue 末尾补换行;比较时忽略这个分隔。
  199. expect(withoutCacheControl(compactRecords[0]!.messages)).toEqual(
  200. withoutCacheControl(
  201. actual.messages.filter(
  202. (message) =>
  203. typeof message.content !== "string" ||
  204. message.content.replace(/\n$/u, "") !== OUTPUT_TOKEN_CONTINUE_PROMPT,
  205. ),
  206. ),
  207. );
  208. } finally {
  209. await runtime.closeBrowserSession();
  210. }
  211. },
  212. );
  213. it.each(cases)(
  214. "keeps repeated-search feedback stable in Continue, records and snapshots ($mode/$modelStreaming)",
  215. async ({ mode, modelStreaming }) => {
  216. const snapshots = vi.spyOn(TurnMachineImpl.prototype, "startModelRequest");
  217. const { runtime, requests, recordedRequests } = fixture(
  218. { toolSearch: { mode }, modelStreaming },
  219. (_request, index) => {
  220. if (index === 1) return search();
  221. if (index === 3)
  222. return {
  223. ...search(),
  224. toolCalls: [{ id: "repeat", name: "ToolSearch", input: { query: "select:lookup" } }],
  225. };
  226. if (index === 4) return { text: "partial", finishReason: "length", usage: {} };
  227. return done();
  228. },
  229. );
  230. try {
  231. await runtime.executeTurn("Load the lookup tool.");
  232. await runtime.executeTurn("Find lookup again using its short name.");
  233. expect(requests.map((r) => successCount(r.messages))).toEqual(
  234. mode === "local" ? [0, 0, 0, 0, 0] : [0, 1, 1, 2, 2],
  235. );
  236. const latest = requests.at(-1)!;
  237. const repeat = latest.messages.find((m) => m.role === "tool" && m.toolCallId === "repeat");
  238. expect(JSON.stringify(repeat)).toContain(
  239. mode === "local" ? "already available" : "tool_reference",
  240. );
  241. if (mode === "local") expect(JSON.stringify(repeat)).not.toContain("<functions>");
  242. const records = await recordedRequests();
  243. for (const [index, request] of requests.entries()) {
  244. const expected = withoutCacheControl(
  245. request.messages.filter((m) => m.content !== OUTPUT_TOKEN_CONTINUE_PROMPT),
  246. );
  247. expect(withoutCacheControl(records[index]!.messages)).toEqual(expected);
  248. expect(
  249. withoutCacheControl(snapshots.mock.results[index]!.value.modelRequest.messages),
  250. ).toEqual(expected);
  251. }
  252. } finally {
  253. await runtime.closeBrowserSession();
  254. }
  255. },
  256. );
  257. it.each([CompactTrigger.Manual, CompactTrigger.Reactive])(
  258. "promotes discovery at successful %s compact and keeps it across the next compact",
  259. async (trigger) => {
  260. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) =>
  261. isCompact(request)
  262. ? { ...done(), text: "<summary>Continue.</summary>" }
  263. : index === 1
  264. ? search()
  265. : done(),
  266. );
  267. try {
  268. await runtime.executeTurn("Load lookup.");
  269. await runtime.executeTurn("Keep working.");
  270. const internal = runtime as unknown as AgentRuntimeInternal;
  271. for (let pass = 0; pass < 2; pass++) {
  272. const result = await internal.compactActiveConversation(
  273. undefined,
  274. createRootTraceContext(),
  275. [],
  276. { trigger },
  277. );
  278. expect(result.outcome).toBe("compacted");
  279. // 返回时公告就应使用提升后的分类,而不是等待下一次正常收集纠正。
  280. expect(
  281. result.entries
  282. .filter((e) => e.metadata?.toolSearchAnnouncement)
  283. .flatMap((e) => e.metadata!.toolSearchAnnouncement!.addedNames),
  284. ).not.toContain(TARGET);
  285. await runtime.executeTurn("Continue after compact.");
  286. const request = requests.at(-1)!;
  287. expect(request.tools?.find((t) => t.name === TARGET)).toMatchObject({ name: TARGET });
  288. expect(request.tools?.find((t) => t.name === TARGET)?.deferLoading).toBeUndefined();
  289. expect(request.tools?.map((t) => t.name)).toContain("DeferredToolCall");
  290. }
  291. } finally {
  292. await runtime.closeBrowserSession();
  293. }
  294. },
  295. );
  296. it.each(["cancel", "persist failure"])(
  297. "does not promote Local tools on compact %s",
  298. async (failure) => {
  299. const controller = new AbortController();
  300. const { runtime, requests } = fixture({ toolSearch: { mode: "local" } }, (request, index) => {
  301. if (isCompact(request)) {
  302. if (failure === "cancel") controller.abort();
  303. return { ...done(), text: "<summary>Candidate.</summary>" };
  304. }
  305. return index === 1 ? search() : done();
  306. });
  307. try {
  308. await runtime.executeTurn("Load lookup.");
  309. await runtime.executeTurn("Keep working.");
  310. const internal = runtime as unknown as AgentRuntimeInternal;
  311. const before = internal.messageHistory.toRuntimeEntries();
  312. if (failure === "persist failure")
  313. vi.spyOn(internal, "persistCompactSummary").mockRejectedValue(new Error("persist failed"));
  314. await expect(
  315. internal.compactActiveConversation(undefined, createRootTraceContext(), [], {
  316. abortSignal: controller.signal,
  317. }),
  318. ).rejects.toThrow();
  319. expect(internal.messageHistory.toRuntimeEntries()).toEqual(before);
  320. await runtime.executeTurn("Still use the search result.");
  321. expect(requests.at(-1)!.tools?.some((t) => t.name === TARGET)).toBe(false);
  322. } finally {
  323. await runtime.closeBrowserSession();
  324. }
  325. },
  326. );