toolsearch-cli-process.ts 7.2 KB

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