tool-search-turn.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. LOCAL_TOOL_SEARCH_NAME,
  4. ModelRequestSessionFeature,
  5. SESSION_ENTRY_SESSION_FEATURES,
  6. TOOL_SEARCH_NAME,
  7. createRootTraceContext,
  8. createSessionId,
  9. type Model,
  10. type ModelInvocationContext,
  11. type ModelRequest,
  12. type ModelResult,
  13. type SessionEntryInfo,
  14. type SessionStorePort,
  15. type ToolSearchMode,
  16. } from "@zcode/contracts";
  17. import type { AgentRuntimeInternal } from "../../src/runtime/internal.js";
  18. import { readSessionFeatures } from "../../src/runtime/session-features/contract.js";
  19. import { createToolRegistry } from "../../src/tool/registry.js";
  20. import { createRecordingMessageStore } from "../runtime-output-token-continuation-test-helpers.js";
  21. import { createTestAgentRuntime } from "../test-agent-runtime.js";
  22. import { createTestSessionEventStore } from "../test-event-store.js";
  23. import { createTestModelFactory } from "../test-runtime-model.js";
  24. // 规格:docs/design/v2/model/session-features-header.md 的 ToolSearch 标签:主循环打点与旁路请求。
  25. const { ToolSearchCalled, ToolSearchLocal, ToolSearchNative } = ModelRequestSessionFeature;
  26. describe("主循环打点(端到端)", () => {
  27. /** 一轮:模型先搜索一次再结束;返回每次模型请求带的标签和最终写入的 entry。 */
  28. async function runSearchTurn(mode: ToolSearchMode, searchName = TOOL_SEARCH_NAME) {
  29. const entries = new Map<string, SessionEntryInfo>();
  30. const seen: ModelInvocationContext[] = [];
  31. const runtime = createTestAgentRuntime(
  32. createSessionId(`session-features-tool-search-${Math.random().toString(36).slice(2)}`),
  33. {
  34. mode: "yolo",
  35. modelStreaming: "off",
  36. titleGeneration: { enabled: false },
  37. toolSearch: { mode },
  38. // TaskOutput 是内置的 deferred 工具;local 还需要 DeferredToolCall 作为控制工具。
  39. toolAllowlist: [TOOL_SEARCH_NAME, "DeferredToolCall", "Read", "TaskOutput"],
  40. },
  41. {
  42. eventStore: createTestSessionEventStore(),
  43. sessionStore: recordingSessionStore(entries),
  44. modelFactory: withToolSearchCapability(
  45. createTestModelFactory({
  46. async generateText(_request, observation) {
  47. seen.push(observation.invocationContext!);
  48. if (seen.length === 1)
  49. return {
  50. text: "",
  51. finishReason: "tool-calls",
  52. usage: {},
  53. toolCalls: [
  54. { id: "call_search", name: searchName, input: { query: "select:TaskOutput" } },
  55. ],
  56. };
  57. return { text: "done", finishReason: "stop", usage: {} };
  58. },
  59. }),
  60. ),
  61. },
  62. );
  63. await runtime.executeTurn("load the task output tool");
  64. await (runtime as unknown as AgentRuntimeInternal).sessionFeaturesWrite;
  65. return {
  66. features: seen.map((context) => context.modelRequestSessionFeatures),
  67. entries: [...entries.values()]
  68. .filter((entry) => entry.type === SESSION_ENTRY_SESSION_FEATURES)
  69. .map((entry) => entry.data),
  70. };
  71. }
  72. it("native:首个请求就带模式标签,搜索之后的请求再带 tool_search_called,并写入 entry", async () => {
  73. const { features, entries } = await runSearchTurn("native");
  74. expect(features).toEqual([[ToolSearchNative], [ToolSearchCalled, ToolSearchNative]]);
  75. expect(entries).toEqual([{ features: [ToolSearchCalled, ToolSearchNative] }]);
  76. });
  77. it("local:模型调用 LocalToolSearch,标签与 native 对称", async () => {
  78. const { features, entries } = await runSearchTurn("local", LOCAL_TOOL_SEARCH_NAME);
  79. expect(features).toEqual([[ToolSearchLocal], [ToolSearchCalled, ToolSearchLocal]]);
  80. expect(entries).toEqual([{ features: [ToolSearchCalled, ToolSearchLocal] }]);
  81. });
  82. it("off:不打模式标签;搜索调用执行失败也不打 tool_search_called", async () => {
  83. const { features, entries } = await runSearchTurn("off");
  84. expect(features).toEqual([undefined, undefined]);
  85. expect(entries).toEqual([]);
  86. });
  87. });
  88. describe("旁路请求不打模式标签", () => {
  89. it("compact 请求即使启用了 ToolSearch 也不打标签", async () => {
  90. const registry = createToolRegistry();
  91. // compact 只保留 Read、ToolSearch 与 MCP 工具;一个 deferred 的 MCP 工具即可让 ToolSearch 生效。
  92. registry.register({
  93. inputSchema: { type: "object", properties: {} },
  94. metadata: {
  95. name: "mcp__demo__lookup",
  96. mcpPresentation: { serverName: "demo", toolName: "lookup" },
  97. readOnly: true,
  98. concurrentSafe: true,
  99. destructive: false,
  100. needsApproval: false,
  101. riskLevel: "low",
  102. sideEffectScope: "none",
  103. },
  104. handler: async () => "done",
  105. });
  106. const compactRequests: Array<{ request: ModelRequest; context: ModelInvocationContext }> = [];
  107. const runtime = createTestAgentRuntime(
  108. createSessionId("session-features-tool-search-compact"),
  109. {
  110. modelStreaming: "off",
  111. titleGeneration: { enabled: false },
  112. toolAllowlist: ["Read", TOOL_SEARCH_NAME],
  113. toolSearch: { mode: "native" },
  114. },
  115. {
  116. toolRegistry: registry,
  117. eventStore: createTestSessionEventStore(),
  118. modelFactory: withToolSearchCapability(
  119. createTestModelFactory({
  120. async generateText(request, observation): Promise<ModelResult> {
  121. compactRequests.push({ request, context: observation.invocationContext! });
  122. return {
  123. text: "<summary>Continue the task.</summary>",
  124. finishReason: "stop",
  125. usage: {},
  126. };
  127. },
  128. }),
  129. ),
  130. },
  131. );
  132. const internal = runtime as unknown as AgentRuntimeInternal;
  133. // 直接灌历史再压缩:不经过主循环,会话里没有任何标签。
  134. internal.messageHistory.addUser("first setup turn");
  135. internal.messageHistory.addAssistant("first response");
  136. internal.messageHistory.addUser("second setup turn");
  137. internal.messageHistory.addAssistant("second response");
  138. await internal.compactActiveConversation(undefined, createRootTraceContext(), [], {});
  139. expect(compactRequests).toHaveLength(1);
  140. expect(compactRequests[0]!.request.toolSearchEnabled).toBe(true);
  141. expect(compactRequests[0]!.context.modelRequestSessionFeatures).toBeUndefined();
  142. expect(readSessionFeatures(internal)).toEqual([]);
  143. });
  144. });
  145. /** 让测试模型声明支持 Anthropic 协议的工具搜索,native 才能生效(resolveToolSearchMode)。 */
  146. function withToolSearchCapability(
  147. factory: ReturnType<typeof createTestModelFactory>,
  148. ): ReturnType<typeof createTestModelFactory> {
  149. const wrap = (model: Model): Model => ({
  150. ...model,
  151. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  152. bind: (options) => wrap(model.bind(options)),
  153. });
  154. return (input) => wrap(factory(input));
  155. }
  156. function recordingSessionStore(entries: Map<string, SessionEntryInfo>): SessionStorePort {
  157. return {
  158. ...createRecordingMessageStore(),
  159. async getProjectPermission() {
  160. return null;
  161. },
  162. async saveSessionEntry(entry: SessionEntryInfo) {
  163. entries.set(entry.id, entry);
  164. },
  165. } as unknown as SessionStorePort;
  166. }