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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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(count ? expected : "No matching deferred tools found");
  35. expect(result.serialization?.truncated).toBe(false);
  36. expect(completedToolPartMetadata(result).modelContent).toEqual(count ? expected : undefined);
  37. expect([
  38. ...collectDiscoveredTools([
  39. {
  40. message: {
  41. role: "tool",
  42. toolCallId: result.toolCallId,
  43. toolName: "ToolSearch",
  44. content: result.modelContent!,
  45. },
  46. },
  47. ]),
  48. ]).toEqual(names);
  49. },
  50. );
  51. it("keeps all references and counts the final content after an oversized Hook", async () => {
  52. const result = await execute({ query: "lookup", max_results: -1 }, "说明".repeat(60_000));
  53. expect(result.success).toBe(true);
  54. expect(Array.isArray(result.modelContent)).toBe(true);
  55. const blocks = result.modelContent as ModelMessageContentBlock[];
  56. expect(blocks.filter((block) => block.type === "tool_reference")).toEqual(
  57. catalog.slice(0, -1).map((tool) => ({ type: "tool_reference", toolName: tool.name })),
  58. );
  59. const text = modelMessageContentToText(blocks.filter((block) => block.type === "text"));
  60. expect(text).toContain("[Hook additional context]");
  61. expect(text).toContain("truncated");
  62. expect(text).not.toContain("\uFFFD");
  63. expect(Buffer.byteLength(text)).toBeLessThanOrEqual(100_000);
  64. const content = modelMessageContentToText(blocks);
  65. expect(result.serialization).toMatchObject({
  66. content,
  67. returnedBytes: Buffer.byteLength(content),
  68. truncated: true,
  69. });
  70. expect(result.serialization!.returnedBytes).toBeGreaterThan(100_000);
  71. expect(completedToolPartMetadata(result).modelContent).toEqual(blocks);
  72. });
  73. it.each(["head", "tail"] as const)(
  74. "preserves interleaved block order when clipping %s text",
  75. async (direction) => {
  76. const blocks: ModelMessageContentBlock[] = [
  77. { type: "text", text: "first" },
  78. { type: "tool_reference", toolName: "WebFetch" },
  79. { type: "text", text: "中".repeat(100) },
  80. { type: "tool_reference", toolName: "TodoWrite" },
  81. { type: "text", text: "last" },
  82. ];
  83. const original = structuredClone(blocks);
  84. const result = await execute({ query: "lookup", max_results: 1 }, undefined, blocks, direction);
  85. expect(Array.isArray(result.modelContent)).toBe(true);
  86. const projected = result.modelContent as ModelMessageContentBlock[];
  87. expect(projected.filter((b) => b.type === "tool_reference")).toEqual([blocks[1], blocks[3]]);
  88. if (direction === "head") expect(projected[0]).toEqual(blocks[0]);
  89. else expect(projected.slice(0, -1).at(-1)).toEqual(blocks[4]);
  90. const text = modelMessageContentToText(projected.filter((b) => b.type === "text"));
  91. expect(Buffer.byteLength(text)).toBeLessThanOrEqual(80);
  92. expect(text).toContain("truncated");
  93. expect(blocks).toEqual(original);
  94. },
  95. );
  96. async function execute(
  97. input: { query: string; max_results: number },
  98. hookText?: string,
  99. content?: ModelMessageContentBlock[],
  100. direction: "head" | "tail" = "head",
  101. ) {
  102. const registry = createToolRegistry();
  103. registry.register(
  104. content
  105. ? {
  106. ...toolSearchToolEntry,
  107. formatModelContent: () => content,
  108. resultBudget: {
  109. maxInlineBytes: 80,
  110. maxModelBytes: 80,
  111. strategy: "truncate",
  112. preview: { direction },
  113. },
  114. }
  115. : toolSearchToolEntry,
  116. );
  117. const executor = createToolExecutor({
  118. registry,
  119. emitEvent: async () => {},
  120. permissionService: new PermissionService(defaultPermissionConfig),
  121. sessionId: createSessionId("search-budget"),
  122. turnId: createTurnId("turn"),
  123. ...(hookText
  124. ? {
  125. hookRunner: createInMemoryHookRunner({
  126. hooks: [
  127. {
  128. event: "PostToolUse",
  129. matcher: "ToolSearch",
  130. callback: async (hook) => ({
  131. hookSpecificOutput: {
  132. hookEventName: hook.hookEventName,
  133. additionalContext: hookText,
  134. },
  135. }),
  136. },
  137. ],
  138. }),
  139. }
  140. : {}),
  141. });
  142. return executor.execute(
  143. { id: "search", name: "ToolSearch", input },
  144. {
  145. toolSearch: { enabled: true, mode: "native", catalog, discovered: new Set() },
  146. },
  147. );
  148. }