toolsearch-feedback.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { copyFile, mkdir, readdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import type { createToolSearchCliFixture } from "./toolsearch-cli-process.js";
  4. import { toolSearchBlocks, type ToolSearchRequest } from "./toolsearch-provider.js";
  5. export type SearchFixture = Awaited<ReturnType<typeof createToolSearchCliFixture>>;
  6. export type SearchMode = "native" | "local";
  7. export const feedbackCase = "conversation-session-toolsearch-feedback";
  8. export const recordingCase = "conversation-session-toolsearch-recording";
  9. export function resultFor(body: ToolSearchRequest, id: string) {
  10. const result = toolSearchBlocks(body).find(
  11. (block) => block.type === "tool_result" && block.tool_use_id === id,
  12. );
  13. expect(result).toBeDefined();
  14. return result!;
  15. }
  16. export function contentText(content: unknown): string {
  17. if (typeof content === "string") return content;
  18. if (Array.isArray(content)) return content.map(contentText).join("\n");
  19. if (content && typeof content === "object" && "text" in content) return String(content.text);
  20. return "";
  21. }
  22. export function loadedCount(body: ToolSearchRequest): number {
  23. return body.messages.reduce(
  24. (total, message) => total + (contentText(message.content).match(/Tool loaded\./g)?.length ?? 0),
  25. 0,
  26. );
  27. }
  28. export function definitionsFor(body: ToolSearchRequest, id: string): string[] {
  29. const result = resultFor(body, id);
  30. if (
  31. Array.isArray(result.content) &&
  32. result.content.some((block) => block.type === "tool_reference")
  33. )
  34. return result.content
  35. .filter((block) => block.type === "tool_reference")
  36. .map((block) => block.tool_name!);
  37. return [...contentText(result.content).matchAll(/<function>(.*?)<\/function>/g)].map(
  38. (match) => (JSON.parse(match[1]!) as { name: string }).name,
  39. );
  40. }
  41. export function replyStage(
  42. fixture: SearchFixture,
  43. body: ToolSearchRequest,
  44. response: Parameters<SearchFixture["reply"]>[1],
  45. stage: string,
  46. ) {
  47. fixture.reply(body, response, `${stage}-${body.stream ? "stream" : "json"}`);
  48. }
  49. export async function runFeedback(
  50. fixture: SearchFixture,
  51. mode: SearchMode,
  52. marker: string,
  53. extra: string[] = [],
  54. ) {
  55. const run = await fixture.start(["--toolsearch-mode", mode, ...extra, "-p", marker]).done;
  56. expect({ code: run.code, stderr: run.code === 0 ? "" : run.stderr }).toEqual({
  57. code: 0,
  58. stderr: "",
  59. });
  60. return (JSON.parse(run.stdout) as { sessionId: string }).sessionId;
  61. }
  62. export async function saveSearchEvidence(
  63. label: string,
  64. fixture: SearchFixture,
  65. extra: Record<string, unknown> = {},
  66. ) {
  67. const root = process.env.ZCODE_E2E_ARTIFACT_DIR;
  68. if (!root) throw new Error("Missing E2E artifact directory");
  69. const directory = join(root, "toolsearch-wire");
  70. await mkdir(directory, { recursive: true });
  71. const modelIoDirectory = join(directory, label, "model-io");
  72. await mkdir(modelIoDirectory, { recursive: true });
  73. const debugDirectory = join(fixture.root, "storage", "cli", "debug");
  74. const logs = (await readdir(debugDirectory)).filter(
  75. (name) => name.startsWith("model-io-") && name.endsWith(".jsonl"),
  76. );
  77. expect(logs.length).toBeGreaterThan(0);
  78. // 直接归档 adapter 产出的原始日志;不从受控响应或 HTTP 抓包反向拼造 model-io。
  79. await Promise.all(
  80. logs.map((name) => copyFile(join(debugDirectory, name), join(modelIoDirectory, name))),
  81. );
  82. // 保留真实 HTTP body 和选中的响应 fixture,不写隔离进程的认证头。
  83. await writeFile(
  84. join(directory, `${label}.json`),
  85. JSON.stringify(
  86. {
  87. kind: "controlled-provider-http",
  88. requests: fixture.requests.map(({ body, fixtureId }) => ({ body, fixtureId })),
  89. ...extra,
  90. },
  91. null,
  92. 2,
  93. ),
  94. );
  95. }