tool-search-result-budget.test.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import { expect, it } from "vitest";
  2. import {
  3. createSessionId,
  4. createTurnId,
  5. modelMessageContentToText,
  6. type ModelMessageContentBlock,
  7. } from "@zcode/contracts";
  8. import { createToolExecutor } from "../src/tool/executor.js";
  9. import { createToolRegistry } from "../src/tool/registry.js";
  10. import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
  11. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  12. import { collectDiscoveredTools } from "../src/tool/search/history.js";
  13. import { completedToolPartMetadata } from "../src/runtime/methods/tool-part-metadata.js";
  14. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  15. const catalog = Array.from({ length: 2_000 }, (_, i) => ({
  16. name: `mcp__demo__lookup_${String(i).padStart(4, "0")}_`.padEnd(64, "x"),
  17. description: "lookup information",
  18. deferred: true,
  19. }));
  20. it.each([
  21. { query: "lookup", max_results: 5, count: 5 },
  22. { query: "lookup", max_results: -1, count: 1_999 },
  23. { query: "lookup", max_results: 0, count: 0 },
  24. { query: "lookup", max_results: 1.5, count: 1 },
  25. { query: "lookup", max_results: 1_000_000, count: 2_000 },
  26. { query: `select:${catalog.map((tool) => tool.name).join(",")}`, max_results: 1, count: 2_000 },
  27. ])(
  28. "preserves $count references with max_results=$max_results",
  29. async ({ query, max_results, count }) => {
  30. const result = await execute({ query, max_results });
  31. expect(result.success).toBe(true);
  32. const names = catalog.slice(0, count).map((tool) => tool.name);
  33. const expected = names.map((toolName) => ({ type: "tool_reference", toolName }));
  34. expect(result.modelContent).toEqual(
  35. count
  36. ? expected
  37. : "No matching deferred tools found. Loaded tools are not searchable here and need no loading. Check your loaded tool list and query; try corrected spelling, alternative names, or broader keywords before concluding a tool is missing.",
  38. );
  39. expect(result.serialization?.truncated).toBe(false);
  40. expect(completedToolPartMetadata(result).modelContent).toEqual(count ? expected : undefined);
  41. expect([
  42. ...collectDiscoveredTools([
  43. {
  44. message: {
  45. role: "tool",
  46. toolCallId: result.toolCallId,
  47. toolName: "ToolSearch",
  48. content: result.modelContent!,
  49. },
  50. },
  51. ]),
  52. ]).toEqual(names);
  53. },
  54. );
  55. it("keeps all references unchanged when a Hook returns a large context", async () => {
  56. const hookText = "说明".repeat(60_000);
  57. const result = await execute({ query: "lookup", max_results: -1 }, hookText);
  58. expect(result.success).toBe(true);
  59. // Hook 文本是工具批次后的附件,不占 tool result 预算,也不改变引用块。
  60. expect(result.modelContent).toEqual(
  61. catalog.slice(0, -1).map((tool) => ({ type: "tool_reference", toolName: tool.name })),
  62. );
  63. expect(result.serialization?.truncated).toBe(false);
  64. expect(completedToolPartMetadata(result).modelContent).toEqual(result.modelContent);
  65. // 单条 Hook 文本有自己的 10000 字符上限;这里没有 artifact store,按截断兜底。
  66. expect(result.hookAdditionalContexts).toEqual([
  67. `PostToolUse:ToolSearch hook additional context: ${hookText.slice(0, 10_000)}\n\n` +
  68. "[Hook additionalContext truncated at 10000 chars — persist-to-disk failed: no artifact store]",
  69. ]);
  70. });
  71. it.each(["head", "tail"] as const)(
  72. "preserves interleaved block order when clipping %s text",
  73. async (direction) => {
  74. const blocks: ModelMessageContentBlock[] = [
  75. { type: "text", text: "first" },
  76. { type: "tool_reference", toolName: "WebFetch" },
  77. { type: "text", text: "中".repeat(100) },
  78. { type: "tool_reference", toolName: "TodoWrite" },
  79. { type: "text", text: "last" },
  80. ];
  81. const original = structuredClone(blocks);
  82. const result = await execute({ query: "lookup", max_results: 1 }, undefined, blocks, direction);
  83. expect(Array.isArray(result.modelContent)).toBe(true);
  84. const projected = result.modelContent as ModelMessageContentBlock[];
  85. expect(projected.filter((b) => b.type === "tool_reference")).toEqual([blocks[1], blocks[3]]);
  86. if (direction === "head") expect(projected[0]).toEqual(blocks[0]);
  87. else expect(projected.slice(0, -1).at(-1)).toEqual(blocks[4]);
  88. const text = modelMessageContentToText(projected.filter((b) => b.type === "text"));
  89. expect(Buffer.byteLength(text)).toBeLessThanOrEqual(80);
  90. expect(text).toContain("truncated");
  91. expect(blocks).toEqual(original);
  92. },
  93. );
  94. async function execute(
  95. input: { query: string; max_results: number },
  96. hookText?: string,
  97. content?: ModelMessageContentBlock[],
  98. direction: "head" | "tail" = "head",
  99. ) {
  100. const registry = createToolRegistry();
  101. registry.register(
  102. content
  103. ? {
  104. ...toolSearchToolEntry,
  105. formatModelContent: () => content,
  106. resultBudget: {
  107. maxInlineBytes: 80,
  108. maxModelBytes: 80,
  109. strategy: "truncate",
  110. preview: { direction },
  111. },
  112. }
  113. : toolSearchToolEntry,
  114. );
  115. const executor = createToolExecutor({
  116. registry,
  117. emitEvent: async () => {},
  118. permissionService: new PermissionService(defaultPermissionConfig),
  119. sessionId: createSessionId("search-budget"),
  120. turnId: createTurnId("turn"),
  121. ...(hookText
  122. ? {
  123. hookRunner: createInMemoryHookRunner({
  124. hooks: [
  125. {
  126. event: "PostToolUse",
  127. matcher: "ToolSearch",
  128. callback: async (hook) => ({
  129. hookSpecificOutput: {
  130. hookEventName: hook.hookEventName,
  131. additionalContext: hookText,
  132. },
  133. }),
  134. },
  135. ],
  136. }),
  137. }
  138. : {}),
  139. });
  140. return executor.execute(
  141. { id: "search", name: "ToolSearch", input },
  142. {
  143. toolSearch: { enabled: true, mode: "native", catalog, discovered: new Set() },
  144. },
  145. );
  146. }