toolsearch-cli-process.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import { spawn } from "node:child_process";
  2. import { once } from "node:events";
  3. import { createServer, type ServerResponse } from "node:http";
  4. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join, resolve } from "node:path";
  7. import {
  8. seedPersonalDefaultModelSelection,
  9. seedPersonalProviderConfig,
  10. } from "./model-provider-restart-config.js";
  11. import {
  12. loadToolSearchResponses,
  13. toolSearchResponseStage,
  14. type ToolSearchRequest,
  15. } from "./toolsearch-provider.js";
  16. export interface CliWireRequest {
  17. body: ToolSearchRequest;
  18. headers: Record<string, string | string[] | undefined>;
  19. fixtureId?: string;
  20. }
  21. export async function createToolSearchCliFixture(
  22. caseName: string,
  23. options: { modelIo?: boolean } = {},
  24. ) {
  25. const responses = await loadToolSearchResponses(caseName);
  26. const repoRoot = resolve(process.cwd(), "../..");
  27. const root = await mkdtemp(join(tmpdir(), "zcode-toolsearch-process-"));
  28. const workspace = join(root, "workspace");
  29. const configPath = join(root, ".zcode", "cli", "config.json");
  30. const personalPath = join(root, "provider.json");
  31. const requests: CliWireRequest[] = [];
  32. const active = new Set<ReturnType<typeof spawn>>();
  33. const runs: { args: string[]; code: number | null; stdout: string; stderr: string }[] = [];
  34. function reply(
  35. body: ToolSearchRequest,
  36. response: ServerResponse,
  37. stage = toolSearchResponseStage(body),
  38. end = true,
  39. ) {
  40. const fixture = responses.get(stage);
  41. const record = requests.find((item) => item.body === body);
  42. if (record) record.fixtureId = fixture.id;
  43. response.writeHead(fixture.response.statusCode, fixture.response.headers);
  44. if (end) response.end(fixture.response.body);
  45. else response.write(fixture.response.body);
  46. }
  47. let respond: (body: ToolSearchRequest, response: ServerResponse) => void = reply;
  48. const server = createServer(async (request, response) => {
  49. const chunks: Buffer[] = [];
  50. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  51. const body = JSON.parse(Buffer.concat(chunks).toString()) as ToolSearchRequest;
  52. requests.push({ body, headers: request.headers });
  53. respond(body, response);
  54. });
  55. server.listen(0, "127.0.0.1");
  56. await once(server, "listening");
  57. const address = server.address();
  58. if (!address || typeof address === "string") throw new Error("CLI fixture failed to listen");
  59. const port = address.port;
  60. await mkdir(workspace, { recursive: true });
  61. await mkdir(join(root, ".zcode", "cli"), { recursive: true });
  62. let config = {
  63. features: { memory: false, skill: false, mcp: false, subagent: false },
  64. permission: { mode: "yolo", allowedTools: [] as string[], disallowedTools: [] as string[] },
  65. storage: { dir: join(root, "storage"), sessionDbPath: join(root, "session.sqlite") },
  66. };
  67. await writeFile(configPath, JSON.stringify(config));
  68. async function select(
  69. apiFormat: "anthropic-messages" | "openai-chat-completions",
  70. properties: { supportsMidConversationSystem?: boolean } = {},
  71. ) {
  72. await seedPersonalProviderConfig(personalPath, {
  73. id: "toolsearch-process",
  74. label: "ToolSearch Process",
  75. apiFormat,
  76. apiKey: "test-only",
  77. baseURL: `http://127.0.0.1:${port}/v1`,
  78. models: [{ id: "test-toolsearch", ...properties }],
  79. });
  80. await seedPersonalDefaultModelSelection(personalPath, {
  81. providerId: "toolsearch-process",
  82. modelId: "test-toolsearch",
  83. });
  84. }
  85. await select("anthropic-messages");
  86. const env = {
  87. PATH: process.env.PATH,
  88. SystemRoot: process.env.SystemRoot,
  89. COMSPEC: process.env.COMSPEC,
  90. TEMP: process.env.TEMP,
  91. TMP: process.env.TMP,
  92. HOME: root,
  93. USERPROFILE: root,
  94. TMPDIR: process.env.TMPDIR,
  95. NODE_ENV: "test",
  96. ...(options.modelIo ? { ZCODE_RUNTIME_ENV: "development" } : {}),
  97. ZCODE_DATA_BASE_DIR: root,
  98. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: personalPath,
  99. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: join(repoRoot, "config/provider/zcode-builtin.json"),
  100. };
  101. return {
  102. root,
  103. workspace,
  104. env,
  105. cliPath: join(repoRoot, "apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  106. requests,
  107. select,
  108. reply,
  109. setResponse(handler: typeof respond) {
  110. respond = handler;
  111. },
  112. async configure(patch: Record<string, unknown>) {
  113. config = { ...config, ...patch };
  114. await writeFile(configPath, JSON.stringify(config));
  115. },
  116. start(args: string[], outputFormat = "json") {
  117. // 全部用户路径指向隔离目录;仅继承执行工具所需 PATH,不复用用户 provider/凭据/代理。
  118. const child = spawn(
  119. process.execPath,
  120. [
  121. join(repoRoot, "apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  122. ...args,
  123. "--no-browser",
  124. "--output-format",
  125. outputFormat,
  126. ],
  127. {
  128. cwd: workspace,
  129. env,
  130. stdio: ["ignore", "pipe", "pipe"],
  131. timeout: 60_000,
  132. killSignal: "SIGKILL",
  133. },
  134. );
  135. active.add(child);
  136. let stdout = "";
  137. let stderr = "";
  138. child.stdout.on("data", (chunk: Buffer) => {
  139. stdout += chunk.toString();
  140. });
  141. child.stderr.on("data", (chunk: Buffer) => {
  142. stderr += chunk.toString();
  143. });
  144. const done = (async () => {
  145. // close 在 stdout/stderr 排空后触发,避免 exit 先到导致 JSON 尾部丢失。
  146. const [code] = (await once(child, "close")) as [number | null];
  147. active.delete(child);
  148. const result = { args, code, stdout, stderr };
  149. runs.push(result);
  150. return result;
  151. })();
  152. return { child, done, output: () => stdout };
  153. },
  154. async close() {
  155. await Promise.all(
  156. [...active].map(async (child) => {
  157. const exited = once(child, "close");
  158. child.kill("SIGKILL");
  159. await exited;
  160. }),
  161. );
  162. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH;
  163. if (capturePath)
  164. await writeFile(
  165. `${capturePath}.${root.split("-").at(-1)}.cli.json`,
  166. JSON.stringify({ requests, runs }, null, 2),
  167. );
  168. server.closeAllConnections();
  169. await new Promise<void>((resolveClose, reject) =>
  170. server.close((error) => (error ? reject(error) : resolveClose())),
  171. );
  172. await rm(root, { recursive: true, force: true });
  173. },
  174. };
  175. }