standalone-process.e2e.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { once } from "node:events";
  4. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. import { it } from "vitest";
  9. import { z } from "zod";
  10. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  11. import { isTranscriptVisibleMessage } from "../../src/active-transcript/index.js";
  12. import {
  13. LOCAL_TOOL_SEARCH_NAME,
  14. createMessageId,
  15. createPartId,
  16. createProjectId,
  17. type SessionId,
  18. } from "@zcode/contracts";
  19. import {
  20. createSessionResultSchema,
  21. forkSessionResultSchema,
  22. listSessionsResultSchema,
  23. mutationResultSchema,
  24. readSessionResultSchema,
  25. sendToSessionResultSchema,
  26. waitSessionsResultSchema,
  27. } from "@zcode/session-control/contracts";
  28. const providerModule = new URL(
  29. "../../../../e2e/compact-microcompact/scripted-provider.mjs",
  30. import.meta.url,
  31. );
  32. const { startScriptedProvider, stopScriptedProvider, writeScriptedCaptureFile } = await import(
  33. providerModule.href
  34. );
  35. const cliEntry = fileURLToPath(new URL("../../../cli/src/main.ts", import.meta.url));
  36. const tsxLoader = fileURLToPath(import.meta.resolve("tsx"));
  37. const MODEL = "session-control-fixture";
  38. const ACTOR = "SCT_ACTOR: exercise the standalone session tools";
  39. const FIRST = "SCT_FIRST: preserve this stable boundary";
  40. const SECOND = "SCT_SECOND: exactly one queued input";
  41. const LONG = "SCT_LONG: remain active until interrupted";
  42. const TITLE = "SCT 独立会话";
  43. const DONE = "SCT_ALL_TOOLS_VERIFIED";
  44. // 预置在另一个 workspace 的历史会话:验证独立 CLI 读本机会话库、但不能写。
  45. const HISTORY_ID = "sess_00000000-0000-4000-8000-00000000a11c";
  46. const HISTORY_TITLE = "SCT 其他目录历史";
  47. const HISTORY_TEXT = "SCT_HISTORY: written by another process";
  48. const OUTPUTS = {
  49. ListSessions: listSessionsResultSchema,
  50. ReadSession: readSessionResultSchema,
  51. CreateSession: createSessionResultSchema,
  52. ForkSession: forkSessionResultSchema,
  53. SendToSession: sendToSessionResultSchema,
  54. WaitSessions: waitSessionsResultSchema,
  55. InterruptSession: mutationResultSchema,
  56. RenameSession: mutationResultSchema,
  57. };
  58. const TOOLS = Object.keys(OUTPUTS);
  59. type Step = { name: string; input: Record<string, unknown> };
  60. type Output<K extends keyof typeof OUTPUTS> = z.output<(typeof OUTPUTS)[K]>;
  61. const requestSchema = z.object({
  62. stream: z.boolean().optional(),
  63. messages: z.array(
  64. z.object({ role: z.string(), content: z.unknown(), tool_call_id: z.string().optional() }),
  65. ),
  66. tools: z.array(z.object({ function: z.object({ name: z.string() }) })).optional(),
  67. });
  68. type Request = z.infer<typeof requestSchema>;
  69. function* invokeRaw(name: string, input: Step["input"]): Generator<Step, string, string> {
  70. return yield { name, input };
  71. }
  72. function* invoke<K extends keyof typeof OUTPUTS>(
  73. name: K,
  74. input: Step["input"],
  75. ): Generator<Step, Output<K>, string> {
  76. const raw = yield { name, input };
  77. return OUTPUTS[name].parse(JSON.parse(raw)) as Output<K>;
  78. }
  79. // SCT01/02/04/05/06:真实 CLI main → LocalToolSearch/DeferredToolCall → executor → owner → SQLite。
  80. // 模型只编排请求;引用、分页边界、operation 和 executionId 必须取自真实 tool_result。
  81. it("runs all eight session tools in a standalone CLI process and reopens its SQLite history", async () => {
  82. const directory = await mkdtemp(join(tmpdir(), "zcode-session-control-e2e-"));
  83. const workspace = join(directory, "workspace");
  84. const database = join(directory, "sessions.sqlite");
  85. const configDirectory = join(directory, ".zcode", "cli");
  86. await Promise.all([mkdir(workspace), mkdir(configDirectory, { recursive: true })]);
  87. const firstStarted = Promise.withResolvers<void>();
  88. const releaseFirst = Promise.withResolvers<void>();
  89. const longStarted = Promise.withResolvers<void>();
  90. const releaseLong = Promise.withResolvers<void>();
  91. const received = new Map<string, string>();
  92. const targetRequests: string[] = [];
  93. let created: Output<"CreateSession"> | undefined;
  94. let forked: Output<"ForkSession"> | undefined;
  95. let completed = false;
  96. let passed = false;
  97. let providerError: unknown;
  98. async function* scenario(): AsyncGenerator<Step, void, string> {
  99. const discovery = yield {
  100. name: LOCAL_TOOL_SEARCH_NAME,
  101. input: { query: `select:${TOOLS.join(",")}` },
  102. };
  103. for (const name of TOOLS) assert.ok(discovery.includes(name), `missing schema: ${name}`);
  104. // 独立 CLI 只注册共有 8 个;App 独有工具不出现。
  105. for (const appOnly of ["ListProjects", "OpenSession", "SetSessionPinned"])
  106. assert.ok(!discovery.includes(`"${appOnly}"`), `unexpected App tool: ${appOnly}`);
  107. const roots = yield* invoke("ListSessions", {});
  108. // 读本机会话库:调用者根与预置的其他 workspace 历史都列出;历史只宣称可读。
  109. assert.equal(roots.sessions.length, 2);
  110. const history = roots.sessions.find((item) => item.session.sessionId === HISTORY_ID)!;
  111. assert.equal(history.title, HISTORY_TITLE);
  112. assert.deepEqual(history.availableActions, ["readSession"]);
  113. const historyRead = yield* invoke("ReadSession", { sessionId: HISTORY_ID, view: "messages" });
  114. assert.ok(historyRead.view === "messages");
  115. assert.deepEqual(
  116. historyRead.messages.map((item) => [item.role, item.text]),
  117. [["user", HISTORY_TEXT]],
  118. );
  119. const caller = roots.sessions.find((item) => item.session.sessionId !== HISTORY_ID)!.session;
  120. assert.equal(caller.kind, "cli");
  121. assert.ok(caller.kind === "cli");
  122. // macOS /var 临时目录会被 cwd 解析成 /private/var;使用 owner 返回的真实 workspace 身份。
  123. const createInput = { prompt: FIRST };
  124. created = yield* invoke("CreateSession", createInput);
  125. assert.equal(created.creation, "created");
  126. assert.equal(created.firstInput, "accepted");
  127. assert.equal(created.delivery, "start_now");
  128. assert.ok(created.session && created.operation);
  129. assert.equal(created.session.kind, "cli");
  130. // 规格 0.14:requestId 不再由模型给出,重试要回放回执里的那个 id。
  131. assert.deepEqual(
  132. yield* invoke("CreateSession", { ...createInput, retryOf: created.requestId }),
  133. created,
  134. );
  135. await firstStarted.promise;
  136. const first = yield* invoke("ReadSession", {
  137. sessionId: created.session.sessionId,
  138. view: "summary",
  139. });
  140. assert.ok(first.view === "summary");
  141. assert.equal(first.summary.status, "running");
  142. const firstExecutionId = first.summary.executionId;
  143. assert.ok(firstExecutionId);
  144. const observing = yield* invoke("WaitSessions", {
  145. operations: [
  146. { sessionId: created.operation.session.sessionId, commandId: created.operation.commandId },
  147. ],
  148. mode: "all",
  149. timeoutMs: 0,
  150. });
  151. assert.equal(observing.status, "timed_out");
  152. assert.equal(observing.operations[0]!.status, "running");
  153. assert.deepEqual(observing.operations[0]!.operation, created.operation);
  154. const sendInput = { sessionId: created.session.sessionId, prompt: SECOND };
  155. const sent = yield* invoke("SendToSession", sendInput);
  156. assert.equal(sent.admission, "accepted");
  157. assert.equal(sent.delivery, "queued");
  158. assert.deepEqual(
  159. yield* invoke("SendToSession", { ...sendInput, retryOf: sent.requestId }),
  160. sent,
  161. );
  162. // 超时只释放观察;原 owner 继续运行目标并排队接纳下一条输入。
  163. assert.deepEqual(targetRequests, [FIRST]);
  164. releaseFirst.resolve();
  165. const waited = yield* invoke("WaitSessions", {
  166. operations: [
  167. { sessionId: created.operation.session.sessionId, commandId: created.operation.commandId },
  168. { sessionId: sent.operation.session.sessionId, commandId: sent.operation.commandId },
  169. ],
  170. mode: "all",
  171. });
  172. assert.equal(waited.status, "completed");
  173. assert.deepEqual(
  174. waited.operations.map((item) => item.operation),
  175. [created.operation, sent.operation],
  176. );
  177. assert.deepEqual(
  178. waited.operations.map((item) => item.status),
  179. ["completed", "completed"],
  180. );
  181. const page = yield* invoke("ReadSession", {
  182. sessionId: created.session.sessionId,
  183. view: "messages",
  184. limit: 1,
  185. });
  186. assert.ok(page.view === "messages");
  187. assert.deepEqual(
  188. page.messages.map((item) => [item.role, item.text]),
  189. [["user", FIRST]],
  190. );
  191. assert.ok(page.nextCursor);
  192. const rest = yield* invoke("ReadSession", {
  193. sessionId: created.session.sessionId,
  194. view: "messages",
  195. cursor: page.nextCursor,
  196. });
  197. assert.ok(rest.view === "messages");
  198. assert.deepEqual(
  199. rest.messages.map((item) => [item.role, item.text]),
  200. [
  201. ["assistant", "SCT_FIRST_DONE"],
  202. ["user", SECOND],
  203. ["assistant", "SCT_SECOND_DONE"],
  204. ],
  205. );
  206. forked = yield* invoke("ForkSession", {
  207. sessionId: created.session.sessionId,
  208. atMessage: rest.messages[0]!.id,
  209. });
  210. assert.equal(forked.status, "created");
  211. assert.ok(forked.session);
  212. assert.notEqual(forked.session.sessionId, created.session.sessionId);
  213. const forkHistory = yield* invoke("ReadSession", {
  214. sessionId: forked.session.sessionId,
  215. view: "messages",
  216. });
  217. assert.ok(forkHistory.view === "messages");
  218. assert.deepEqual(
  219. forkHistory.messages.map((item) => [item.role, item.text]),
  220. [
  221. ["user", FIRST],
  222. ["assistant", "SCT_FIRST_DONE"],
  223. // stable fork 另存 assistant timeline 标记,它没有正文;不能把它算作模型执行。
  224. ["assistant", ""],
  225. ],
  226. );
  227. assert.equal(
  228. (yield* invoke("RenameSession", {
  229. sessionId: created.session.sessionId,
  230. title: TITLE,
  231. })).status,
  232. "applied",
  233. );
  234. // 规格 0.14:workspace 过滤器已删除(发现链循环);标题子串匹配仍只返回这一条。
  235. const listed = yield* invoke("ListSessions", { query: TITLE });
  236. assert.equal(listed.sessions.length, 1);
  237. assert.deepEqual(listed.sessions[0]!.session, created.session);
  238. assert.equal(listed.sessions[0]!.title, TITLE);
  239. const historyWrite = yield* invokeRaw("SendToSession", {
  240. sessionId: HISTORY_ID,
  241. prompt: "must not restore history",
  242. });
  243. // 读范围不扩大写权限:其他 workspace 的历史在写授权前就被拒绝,不会恢复它。
  244. assert.match(historyWrite, /outside the trusted scope/);
  245. const long = yield* invoke("SendToSession", {
  246. sessionId: created.session.sessionId,
  247. prompt: LONG,
  248. });
  249. assert.equal(long.admission, "accepted");
  250. assert.equal(long.delivery, "start_now");
  251. await longStarted.promise;
  252. const active = yield* invoke("ReadSession", {
  253. sessionId: created.session.sessionId,
  254. view: "summary",
  255. });
  256. assert.ok(active.view === "summary");
  257. assert.equal(active.summary.status, "running");
  258. assert.ok(active.summary.executionId);
  259. assert.notEqual(active.summary.executionId, firstExecutionId);
  260. assert.equal(
  261. (yield* invoke("InterruptSession", {
  262. sessionId: created.session.sessionId,
  263. expectedExecutionId: firstExecutionId,
  264. })).status,
  265. "rejected",
  266. );
  267. const stillRunning = yield* invoke("WaitSessions", {
  268. operations: [
  269. { sessionId: long.operation.session.sessionId, commandId: long.operation.commandId },
  270. ],
  271. mode: "any",
  272. timeoutMs: 0,
  273. });
  274. assert.equal(stillRunning.status, "timed_out");
  275. assert.equal(stillRunning.operations[0]!.status, "running");
  276. assert.equal(stillRunning.operations[0]!.executionId, active.summary.executionId);
  277. assert.equal(
  278. (yield* invoke("InterruptSession", {
  279. sessionId: created.session.sessionId,
  280. expectedExecutionId: active.summary.executionId,
  281. })).status,
  282. "applied",
  283. );
  284. const interrupted = yield* invoke("WaitSessions", {
  285. operations: [
  286. { sessionId: long.operation.session.sessionId, commandId: long.operation.commandId },
  287. ],
  288. mode: "all",
  289. });
  290. assert.equal(interrupted.status, "completed");
  291. assert.equal(interrupted.operations[0]!.status, "interrupted");
  292. assert.deepEqual(interrupted.operations[0]!.operation, long.operation);
  293. completed = true;
  294. }
  295. const plan = scenario();
  296. let step = 0;
  297. const provider = await startScriptedProvider({
  298. name: "session-control-e2e",
  299. handler: async ({ body }: { body: unknown }) => {
  300. try {
  301. const request = requestSchema.parse(body);
  302. const text = request.messages
  303. .filter((message) => message.role === "user")
  304. .map((message) => JSON.stringify(message.content))
  305. .join("\n");
  306. // 标题 sidecar 也只访问本地 provider,不推进业务场景。
  307. if (!request.tools?.length) return response(request, "SCT fixture title");
  308. if (text.includes(ACTOR)) {
  309. const names = request.tools.map((tool) => tool.function.name);
  310. assert.ok(names.includes(LOCAL_TOOL_SEARCH_NAME) && names.includes("DeferredToolCall"));
  311. // 会话工具 deferred:只经 ToolSearch / DeferredToolCall 调用,不进入首屏工具表。
  312. assert.equal(
  313. names.some((name) => TOOLS.includes(name)),
  314. false,
  315. );
  316. let result = "";
  317. if (step > 0) {
  318. const toolResult = request.messages.find(
  319. (message) => message.role === "tool" && message.tool_call_id === `sct-${step}`,
  320. );
  321. assert.ok(toolResult, `missing tool_result for step ${step}`);
  322. result = z.string().parse(toolResult.content);
  323. received.set(`sct-${step}`, result);
  324. }
  325. const current = await plan.next(result);
  326. if (current.done) return response(request, DONE);
  327. step += 1;
  328. const call =
  329. current.value.name === LOCAL_TOOL_SEARCH_NAME
  330. ? current.value
  331. : { name: "DeferredToolCall", input: current.value };
  332. return response(request, call, `sct-${step}`);
  333. }
  334. if (text.includes(LONG)) {
  335. targetRequests.push(LONG);
  336. longStarted.resolve();
  337. await releaseLong.promise;
  338. return response(request, "must be interrupted");
  339. }
  340. if (text.includes(SECOND)) {
  341. targetRequests.push(SECOND);
  342. return response(request, "SCT_SECOND_DONE");
  343. }
  344. assert.ok(text.includes(FIRST), `unexpected provider request: ${text}`);
  345. targetRequests.push(FIRST);
  346. firstStarted.resolve();
  347. await releaseFirst.promise;
  348. return response(request, "SCT_FIRST_DONE");
  349. } catch (error) {
  350. providerError ??= error;
  351. // fixture 断言失败属于本轮失败,返回不可重试响应以保留首个证据。
  352. return { status: 400, body: { error: { message: String(error) } } };
  353. }
  354. },
  355. });
  356. let stdout = "";
  357. let stderr = "";
  358. let child: ReturnType<typeof spawn> | undefined;
  359. let exited: Promise<[number | null, NodeJS.Signals | null]> | undefined;
  360. const errors: unknown[] = [];
  361. try {
  362. await writeConfig(directory, provider.baseURL);
  363. // 另一个进程在另一个 workspace 留下的历史:只写持久层,不由本次 CLI 托管。
  364. const seeded = await createSqliteSessionStore({ dbPath: database });
  365. try {
  366. const historyId = HISTORY_ID as SessionId;
  367. const messageId = createMessageId("sct-history-user");
  368. await seeded.createSession({
  369. id: historyId,
  370. projectID: createProjectId("sct-history"),
  371. directory: join(directory, "other-workspace"),
  372. slug: "sct-history",
  373. title: HISTORY_TITLE,
  374. version: "test",
  375. });
  376. await seeded.saveMessage({
  377. id: messageId,
  378. sessionID: historyId,
  379. role: "user",
  380. agent: "zcode-agent",
  381. time: { created: 1 },
  382. } as never);
  383. await seeded.savePart({
  384. id: createPartId("sct-history-text"),
  385. messageID: messageId,
  386. sessionID: historyId,
  387. type: "text",
  388. text: HISTORY_TEXT,
  389. } as never);
  390. } finally {
  391. seeded.close();
  392. }
  393. // 直接启动生产 main;合法 --mode 参数只授权 actor,目标独立 build 权限由 owner 维护。
  394. child = spawn(
  395. process.execPath,
  396. [
  397. "--disable-warning=DEP0205",
  398. "--import",
  399. tsxLoader,
  400. cliEntry,
  401. "-p",
  402. ACTOR,
  403. "--mode",
  404. "yolo",
  405. "--toolsearch-mode",
  406. "local",
  407. "--output-format",
  408. "stream-json",
  409. ],
  410. {
  411. cwd: workspace,
  412. env: {
  413. PATH: process.env.PATH,
  414. SystemRoot: process.env.SystemRoot,
  415. HOME: directory,
  416. USERPROFILE: directory,
  417. APPDATA: directory,
  418. LOCALAPPDATA: directory,
  419. ZCODE_ENV: "test",
  420. ZCODE_DATA_BASE_DIR: directory,
  421. ZCODE_STORAGE_DIR: join(directory, "storage"),
  422. ZCODE_SESSION_DB_PATH: database,
  423. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: join(directory, "builtin.json"),
  424. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: join(directory, "personal.json"),
  425. ZCODE_MODEL_TELEMETRY_ENABLED: "false",
  426. },
  427. stdio: ["ignore", "pipe", "pipe"],
  428. timeout: 75_000,
  429. killSignal: "SIGKILL",
  430. },
  431. );
  432. child.stdout!.on("data", (chunk) => {
  433. stdout += chunk;
  434. });
  435. child.stderr!.on("data", (chunk) => {
  436. stderr += chunk;
  437. });
  438. exited = once(child, "close") as Promise<[number | null, NodeJS.Signals | null]>;
  439. const [code, signal] = await exited;
  440. if (providerError) throw providerError;
  441. assert.deepEqual({ code, signal }, { code: 0, signal: null }, stderr);
  442. assert.ok(completed, `scenario stopped at ${step}`);
  443. assert.match(stdout, new RegExp(DONE));
  444. assert.deepEqual(targetRequests, [FIRST, SECOND, LONG]);
  445. assert.equal(received.size, step);
  446. assert.equal((await readFile(database)).subarray(0, 16).toString(), "SQLite format 3\0");
  447. assert.ok(created?.session && forked?.session);
  448. const store = await createSqliteSessionStore({ dbPath: database });
  449. try {
  450. const roots = await store.listSessions();
  451. assert.equal(roots.length, 4, "create retry must not add a root");
  452. const history = await store.messages({ sessionID: HISTORY_ID as SessionId });
  453. assert.equal(history.length, 1, "reading history must not restore or write it");
  454. const target = await store.getSession(created.session.sessionId as SessionId);
  455. assert.equal(target?.title, TITLE);
  456. assert.equal(target?.lastOutcome, "interrupted");
  457. assert.equal(target?.parentID, undefined);
  458. const messages = await store.messages({
  459. sessionID: created.session.sessionId as SessionId,
  460. });
  461. // staging 起运行时提醒与中断标记也以隐藏 user 消息落库;只比较界面可见的真实输入。
  462. assert.deepEqual(
  463. messages
  464. .filter((message) => message.info.role === "user" && isTranscriptVisibleMessage(message))
  465. .map((message) =>
  466. message.parts
  467. .filter((part) => part.type === "text")
  468. .map((part) => part.text)
  469. .join("\n"),
  470. ),
  471. [FIRST, SECOND, LONG],
  472. );
  473. assert.ok(
  474. messages
  475. .filter((message) => message.info.role === "assistant")
  476. .every((message) => message.info.role === "assistant" && message.info.mode === "build"),
  477. );
  478. const fork = await store.messages({ sessionID: forked.session.sessionId as SessionId });
  479. assert.deepEqual(
  480. fork
  481. .filter(
  482. (message) =>
  483. !(message.info.role === "user" && message.info.visibility === "model-only"),
  484. )
  485. .flatMap((message) =>
  486. message.parts.filter((part) => part.type === "text").map((part) => part.text),
  487. ),
  488. [FIRST, "SCT_FIRST_DONE"],
  489. );
  490. const actor = roots.find(
  491. (root) =>
  492. root.id !== created!.session!.sessionId &&
  493. root.id !== forked!.session!.sessionId &&
  494. root.id !== HISTORY_ID,
  495. )!;
  496. const executed = (await store.messages({ sessionID: actor.id }))
  497. .flatMap((message) => message.parts)
  498. .filter((part) => part.type === "tool" && TOOLS.includes(part.tool));
  499. assert.equal(executed.length, step - 1);
  500. assert.deepEqual(
  501. [...new Set(executed.map((part) => part.type === "tool" && part.tool))].sort(),
  502. [...TOOLS].sort(),
  503. );
  504. // 唯一预期失败的调用是写入未托管的历史会话;其余调用都必须成功完成。
  505. const failed = executed.filter(
  506. (part) => part.type === "tool" && part.state.status !== "completed",
  507. );
  508. assert.equal(failed.length, 1);
  509. assert.ok(failed[0]?.type === "tool" && failed[0].tool === "SendToSession");
  510. } finally {
  511. try {
  512. store.close();
  513. } catch (error) {
  514. errors.push(error);
  515. }
  516. }
  517. passed = errors.length === 0;
  518. } catch (error) {
  519. // 清理和证据写入失败不能覆盖最先发生的场景断言,原错误始终排在第一位。
  520. errors.unshift(error);
  521. } finally {
  522. releaseFirst.resolve();
  523. releaseLong.resolve();
  524. for (const cleanup of [
  525. async () => {
  526. if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
  527. await exited;
  528. },
  529. async () => {
  530. provider.server.closeAllConnections();
  531. await stopScriptedProvider(provider);
  532. },
  533. async () => {
  534. if (passed && errors.length === 0) {
  535. await rm(directory, { recursive: true, force: true, maxRetries: 3 });
  536. } else {
  537. process.stderr.write(`CLI session-control evidence: ${directory}\n`);
  538. const writes = await Promise.allSettled([
  539. writeFile(join(directory, "stdout.jsonl"), stdout),
  540. writeFile(join(directory, "stderr.txt"), stderr),
  541. writeScriptedCaptureFile(provider, join(directory, "provider-capture.json")),
  542. ]);
  543. for (const write of writes) if (write.status === "rejected") errors.push(write.reason);
  544. }
  545. },
  546. ]) {
  547. try {
  548. await cleanup();
  549. } catch (error) {
  550. if (!errors.includes(error)) errors.push(error);
  551. }
  552. }
  553. }
  554. if (errors.length === 1) throw errors[0];
  555. if (errors.length > 1) {
  556. throw new AggregateError(errors, `CLI session-control E2E failed: ${String(errors[0])}`, {
  557. cause: errors[0],
  558. });
  559. }
  560. }, 90_000);
  561. async function writeConfig(directory: string, baseUrl: string) {
  562. await Promise.all([
  563. writeFile(
  564. join(directory, "builtin.json"),
  565. JSON.stringify({
  566. schemaVersion: 1,
  567. revision: 1,
  568. config: {
  569. providerConfigRules: { templateRules: [], providerRules: [] },
  570. modelConfigRules: {
  571. modelRules: [
  572. {
  573. modelMatch: ".*",
  574. config: {
  575. enabled: true,
  576. properties: {
  577. contextWindow: 1_000_000,
  578. requiresMfjsToolSchema: false,
  579. inputFormat: {
  580. supportsText: true,
  581. supportsImage: false,
  582. supportsVideo: false,
  583. supportsAudio: false,
  584. supportsPdf: false,
  585. },
  586. outputFormat: { supportsText: true },
  587. supportsToolCall: true,
  588. supportsJsonSchemaOutput: false,
  589. supportsNativeWebSearch: false,
  590. supportsMidConversationSystem: false,
  591. },
  592. optionSpecs: {
  593. reasoningLevel: { values: ["disabled"], map: "{}" },
  594. maxOutputTokens: { max: 8192, map: "{'max_tokens': maxOutputTokens}" },
  595. },
  596. },
  597. },
  598. ],
  599. modelApiRules: [],
  600. providerSiteRules: [],
  601. templateModelRules: [],
  602. builtinProviderModelRules: [],
  603. },
  604. },
  605. }),
  606. ),
  607. writeFile(
  608. join(directory, "personal.json"),
  609. JSON.stringify({
  610. schemaVersion: 1,
  611. config: {
  612. providerConfigRules: {
  613. providerRules: [
  614. {
  615. providerId: "fixture",
  616. config: {
  617. group: "standard-personal",
  618. personalModelIds: [MODEL],
  619. access: { type: "api-key", apiKey: "local-fixture-key" },
  620. api: { type: "openai-chat-completions", baseUrl },
  621. },
  622. },
  623. ],
  624. },
  625. modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
  626. defaultModelSelection: { providerId: "fixture", modelId: MODEL },
  627. },
  628. }),
  629. ),
  630. writeFile(
  631. join(directory, ".zcode", "cli", "config.json"),
  632. JSON.stringify({
  633. features: { memory: false, mcp: false, subagent: false, skill: false },
  634. plugins: { enabled: false },
  635. skills: { enabled: false },
  636. }),
  637. ),
  638. ]);
  639. }
  640. function response(request: Request, value: string | Step, id = "fixture") {
  641. const tool = typeof value !== "string";
  642. const message = tool
  643. ? {
  644. role: "assistant",
  645. content: "",
  646. tool_calls: [
  647. {
  648. id,
  649. type: "function",
  650. function: { name: value.name, arguments: JSON.stringify(value.input) },
  651. },
  652. ],
  653. }
  654. : { role: "assistant", content: value };
  655. const usage = { prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 };
  656. if (!request.stream)
  657. return {
  658. body: {
  659. id,
  660. object: "chat.completion",
  661. model: MODEL,
  662. created: 1,
  663. choices: [{ index: 0, message, finish_reason: tool ? "tool_calls" : "stop" }],
  664. usage,
  665. },
  666. };
  667. const delta = tool ? { tool_calls: [{ index: 0, ...message.tool_calls![0] }] } : message;
  668. const frame = (choices: unknown[], extra = {}) =>
  669. `data: ${JSON.stringify({ id, object: "chat.completion.chunk", model: MODEL, created: 1, choices, ...extra })}\n\n`;
  670. return {
  671. headers: { "content-type": "text/event-stream" },
  672. bodyText:
  673. frame([{ index: 0, delta, finish_reason: null }]) +
  674. frame([{ index: 0, delta: {}, finish_reason: tool ? "tool_calls" : "stop" }]) +
  675. frame([], { usage }) +
  676. "data: [DONE]\n\n",
  677. };
  678. }