toolsearch-provider.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import { readFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import type {
  4. E2ENetworkCaptureArtifact,
  5. E2ENetworkCaptureRecord,
  6. } from "./network-capture-proxy.js";
  7. export const TOOLSEARCH_CALL_ID = "toolu_e2e_toolsearch";
  8. export const TOOLSEARCH_TODO_CALL_ID = "toolu_e2e_toolsearch_todo";
  9. export const TOOLSEARCH_DONE = "E2E_TOOLSEARCH_DONE";
  10. export const TOOLSEARCH_NOTICE = "The following deferred tools are now available via ToolSearch.";
  11. // 搜索样例用的 deferred 内置工具。TodoWrite 已转为常驻,改用始终注册、执行无副作用、
  12. // 输入为空对象的 TodoRead;新会话读到的是空清单。
  13. export const TOOLSEARCH_DEFERRED_TOOL = "TodoRead";
  14. export interface ToolSearchBlock {
  15. type: string;
  16. id?: string;
  17. name?: string;
  18. text?: string;
  19. tool_use_id?: string;
  20. tool_name?: string;
  21. is_error?: boolean;
  22. content?: string | ToolSearchBlock[];
  23. }
  24. export interface ToolSearchRequest {
  25. model: string;
  26. stream?: boolean;
  27. tools?: Array<{ name: string; defer_loading?: boolean; input_schema?: unknown }>;
  28. messages: Array<{ role: string; content: string | ToolSearchBlock[] }>;
  29. system?: unknown;
  30. }
  31. export type ToolSearchRecord = E2ENetworkCaptureRecord & { requestJson: ToolSearchRequest };
  32. export function toolSearchBlocks(body: ToolSearchRequest): ToolSearchBlock[] {
  33. return body.messages.flatMap((message) =>
  34. Array.isArray(message.content) ? message.content : [],
  35. );
  36. }
  37. export function isToolSearchCompact(body: ToolSearchRequest): boolean {
  38. return JSON.stringify(body).includes("Your task is to create a detailed summary");
  39. }
  40. interface ToolSearchFixtureResponse {
  41. id: string;
  42. stage: string;
  43. response: { statusCode: number; headers: Record<string, string>; body: string };
  44. }
  45. /** 只读取 case-local 响应;不存在的阶段直接失败,避免转正 fixture 沦为未使用的登记。 */
  46. export async function loadToolSearchResponses(caseName: string) {
  47. const path = resolve("test/e2e/fixtures/upstream/conversation-session", `${caseName}.json`);
  48. const file = JSON.parse(await readFile(path, "utf8")) as {
  49. version: number;
  50. caseName: string;
  51. fixtures: ToolSearchFixtureResponse[];
  52. };
  53. if (file.version !== 1 || file.caseName !== caseName)
  54. throw new Error(`Invalid ToolSearch fixture: ${path}`);
  55. const stages = new Map<string, ToolSearchFixtureResponse>();
  56. for (const fixture of file.fixtures) {
  57. if (!fixture.stage || stages.has(fixture.stage) || typeof fixture.response.body !== "string")
  58. throw new Error(`Invalid or duplicate ToolSearch fixture stage: ${fixture.stage}`);
  59. stages.set(fixture.stage, fixture);
  60. }
  61. return {
  62. get(stage: string) {
  63. const fixture = stages.get(stage);
  64. if (!fixture) throw new Error(`Missing ToolSearch fixture: ${caseName}/${stage}`);
  65. return fixture;
  66. },
  67. };
  68. }
  69. /** 保留原请求阶段编排;正文和工具参数均由静态 fixture 提供。 */
  70. export function toolSearchResponseStage(body: ToolSearchRequest): string {
  71. const text = JSON.stringify(body.messages);
  72. if (isToolSearchCompact(body)) return "summary";
  73. if (!text.includes("E2E_TOOLSEARCH_") || !body.tools?.length) return "auxiliary";
  74. if (text.includes("E2E_TOOLSEARCH_SETTINGS")) {
  75. const latestInput = body.messages.findLastIndex(
  76. (message) =>
  77. message.role === "user" &&
  78. JSON.stringify(message.content).includes("E2E_TOOLSEARCH_SETTINGS"),
  79. );
  80. if (
  81. !JSON.stringify(body.messages[latestInput]?.content).includes(
  82. "E2E_TOOLSEARCH_SETTINGS_SEARCH",
  83. )
  84. )
  85. return "done";
  86. const results = toolSearchBlocks({ ...body, messages: body.messages.slice(latestInput) });
  87. if (results.some((block) => block.tool_use_id === "toolu_settings_todo")) return "done";
  88. if (!results.some((block) => block.tool_use_id === "toolu_settings_search"))
  89. return "settings-search";
  90. return body.tools?.some((tool) => tool.name === "DeferredToolCall")
  91. ? "settings-local-todo"
  92. : "settings-todo";
  93. }
  94. if (/E2E_TOOLSEARCH_(COLD|OFF|ON|AFTER|FORK|EDITED)/u.test(text)) return "done";
  95. if (text.includes("E2E_TOOLSEARCH_CONTINUE")) {
  96. const partials = [...text.matchAll(/E2E_TOOLSEARCH_PARTIAL_(\d)/gu)];
  97. const step = Math.max(0, ...partials.map((match) => Number(match[1]))) + 1;
  98. return step <= 3 ? `partial-${step}` : "done";
  99. }
  100. const results = toolSearchBlocks(body).filter((block) => block.type === "tool_result");
  101. if (text.includes("E2E_TOOLSEARCH_INITIAL")) {
  102. if (
  103. body.tools?.some((tool) => tool.name === "ToolSearch") &&
  104. !results.some((block) => block.tool_use_id === TOOLSEARCH_CALL_ID)
  105. )
  106. return "search";
  107. if (!results.some((block) => block.tool_use_id === TOOLSEARCH_TODO_CALL_ID)) return "todo";
  108. }
  109. return "done";
  110. }
  111. export async function readToolSearchRequests(
  112. marker = "E2E_TOOLSEARCH_",
  113. ): Promise<ToolSearchRecord[]> {
  114. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH;
  115. if (!capturePath) throw new Error("ToolSearch capture path is not configured");
  116. const artifact = JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  117. // 关闭请求没有 ToolSearch schema;按功能 marker 和主请求识别,避免漏掉整个降级分支。
  118. return artifact.records.filter((record) => {
  119. const body = record.requestJson as ToolSearchRequest | undefined;
  120. return (
  121. body?.messages &&
  122. (body.tools?.length ?? 0) > 0 &&
  123. JSON.stringify(body.messages).includes(marker) &&
  124. !isToolSearchCompact(body)
  125. );
  126. }) as ToolSearchRecord[];
  127. }