toolsearch-provider.ts 5.2 KB

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