case-utils.mjs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { pathToFileURL } from "node:url";
  4. import {
  5. DEFAULT_PROVIDER,
  6. FAKE_PROVIDER,
  7. FULL_COMPACT_BUFFER_TOKENS,
  8. FULL_COMPACT_CONTEXT_WINDOW,
  9. MAX_TURNS,
  10. } from "./constants.mjs";
  11. const MICROCOMPACT_PLACEHOLDER = "[Old tool result content cleared]";
  12. const DEFAULT_MAX_OUTPUT_TOKENS = 32_000;
  13. const OUTPUT_TOKEN_FIELDS = {
  14. "anthropic-messages": "max_tokens",
  15. "openai-chat-completions": "max_tokens",
  16. "openai-responses": "max_output_tokens",
  17. };
  18. export async function loadZCodeModules(repoRoot) {
  19. try {
  20. const [bootstrap, contracts, providerConfig, providerRegistry] = await Promise.all([
  21. import(pathToFileURL(join(repoRoot, "packages", "bootstrap", "dist", "index.js")).href),
  22. import(pathToFileURL(join(repoRoot, "packages", "contracts", "dist", "index.js")).href),
  23. import(
  24. pathToFileURL(
  25. join(repoRoot, "..", "..", "packages", "provider", "dist", "config", "index.js"),
  26. ).href
  27. ),
  28. import(
  29. pathToFileURL(join(repoRoot, "..", "..", "packages", "provider", "dist", "registry.js"))
  30. .href
  31. ),
  32. ]);
  33. return {
  34. CompactPhase: contracts.CompactPhase,
  35. CompactReason: contracts.CompactReason,
  36. CompactTrigger: contracts.CompactTrigger,
  37. SessionEventType: contracts.SessionEventType,
  38. createZCodeApp: bootstrap.createZCodeApp,
  39. provider: { ...providerConfig, ...providerRegistry },
  40. };
  41. } catch (error) {
  42. throw new Error("Unable to load built ZCode packages. Run `pnpm build` before this E2E.", {
  43. cause: error,
  44. });
  45. }
  46. }
  47. export function buildRuntimeConfig(input) {
  48. return {
  49. compact: {
  50. bufferTokens: input.compact?.bufferTokens ?? FULL_COMPACT_BUFFER_TOKENS,
  51. contextWindow: input.compact?.contextWindow ?? FULL_COMPACT_CONTEXT_WINDOW,
  52. enabled: input.compact?.enabled,
  53. maxConsecutiveFailures: input.compact?.maxConsecutiveFailures,
  54. microcompact: input.compact?.microcompact,
  55. summaryReserveTokens: input.compact?.summaryReserveTokens ?? 0,
  56. thresholdPercentOverride: input.compact?.thresholdPercentOverride,
  57. },
  58. maxTurns: input.maxTurns ?? MAX_TURNS,
  59. ...(input.modelContextBudgetStrategy
  60. ? { modelContextBudgetStrategy: input.modelContextBudgetStrategy }
  61. : {}),
  62. mcp: { enabled: false, servers: {} },
  63. memory: {
  64. enabled: false,
  65. use: false,
  66. },
  67. mode: "yolo",
  68. streamingToolExecution: "off",
  69. workingDirectory: input.workspace,
  70. };
  71. }
  72. export async function writeProviderConfig(configPath, input) {
  73. const providerId = input.providerId ?? DEFAULT_PROVIDER;
  74. const config = {
  75. permission: {
  76. allowedTools: ["Bash", "Read", "Write", "Edit", "ApplyPatch"],
  77. mode: "yolo",
  78. },
  79. storage: {
  80. dir: input.storageDir,
  81. },
  82. features: {
  83. mcp: false,
  84. memory: false,
  85. skill: false,
  86. },
  87. logging: {
  88. level: "warn",
  89. },
  90. };
  91. const providerFixture = {
  92. apiFormat:
  93. input.kind === "anthropic"
  94. ? "anthropic-messages"
  95. : input.kind === "openai"
  96. ? "openai-responses"
  97. : "openai-chat-completions",
  98. apiKey: input.apiKey ?? "compact-e2e-key",
  99. baseURL: input.baseURL,
  100. contextWindow: input.contextWindow ?? FULL_COMPACT_CONTEXT_WINDOW,
  101. maxOutputTokens: input.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
  102. modelId: input.model,
  103. providerId,
  104. };
  105. await Promise.all([
  106. writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`),
  107. writeFile(`${configPath}.provider.json`, `${JSON.stringify(providerFixture, null, 2)}\n`),
  108. ]);
  109. }
  110. export async function createApp(input) {
  111. const providerConfig = JSON.parse(await readFile(`${input.configPath}.provider.json`, "utf8"));
  112. return input.modules.createZCodeApp({
  113. env: {
  114. ...process.env,
  115. ZCODE_STORAGE_DIR: input.storageDir,
  116. // 会话库默认在用户目录;需要检查或改写库内容的 case 用它指到本 case 的临时目录。
  117. ...(input.sessionDbPath ? { ZCODE_SESSION_DB_PATH: input.sessionDbPath } : {}),
  118. },
  119. runtimeConfig: input.runtimeConfig,
  120. // 重构后旧字符串解析入口已删除;新 session 使用完整选择,冷恢复仍由持久选择接管。
  121. configuredDefaultModelSelection: {
  122. providerId: providerConfig.providerId,
  123. modelId: providerConfig.modelId,
  124. options: { reasoningLevel: "disabled" },
  125. },
  126. userConfigPath: input.configPath,
  127. providerRegistry: createProviderRegistry(input.modules.provider, providerConfig),
  128. // Bug 根因:迁移 Registry 时漏传恢复参数,原本的 cold case 会误建新 session。
  129. ...(input.resume ? { resume: true } : {}),
  130. ...(input.sessionId ? { sessionId: input.sessionId } : {}),
  131. });
  132. }
  133. function createProviderRegistry(providerModule, input) {
  134. if (!input.baseURL) {
  135. throw new Error(`Compact E2E Provider ${input.providerId} is missing baseURL`);
  136. }
  137. const config = new providerModule.ProviderConfig({
  138. group: "standard-personal",
  139. access: new providerModule.ApiKeyAccessConfig({ apiKey: input.apiKey }),
  140. api: new providerModule.ProviderApiConfig({
  141. type: input.apiFormat,
  142. baseUrl: input.baseURL,
  143. }),
  144. personalModelIds: [input.modelId],
  145. visibility: "visible",
  146. });
  147. const model = new providerModule.ModelConfig({
  148. enabled: true,
  149. properties: new providerModule.ModelPropertiesConfig({
  150. requiresMfjsToolSchema: false,
  151. contextWindow: input.contextWindow,
  152. inputFormat: {
  153. supportsText: true,
  154. supportsImage: true,
  155. supportsVideo: true,
  156. supportsAudio: false,
  157. supportsPdf: true,
  158. },
  159. outputFormat: { supportsText: true },
  160. supportsToolCall: true,
  161. supportsJsonSchemaOutput: true,
  162. supportsNativeWebSearch: false,
  163. supportsMidConversationSystem: true,
  164. }),
  165. optionSpecs: new providerModule.ModelOptionSpecsConfig({
  166. reasoningLevel: { values: ["disabled"], map: "{}" },
  167. // Bug 根因:helper 丢掉 case 的预算并漏配 Option Map,旧 wire 断言因此失去真实输入。
  168. maxOutputTokens: {
  169. max: input.maxOutputTokens,
  170. map: `{"${OUTPUT_TOKEN_FIELDS[input.apiFormat]}":maxOutputTokens}`,
  171. },
  172. }),
  173. });
  174. return new providerModule.ProviderRegistry([
  175. {
  176. providerId: input.providerId,
  177. config,
  178. models: [{ modelId: input.modelId, config: model }],
  179. },
  180. ]);
  181. }
  182. export async function makeCaseDirs(input) {
  183. const paths = {
  184. artifactsDir: join(input.artifactsRoot, "cases", input.caseName),
  185. capturePath: join(input.artifactsRoot, "cases", input.caseName, "capture.json"),
  186. configPath: join(input.caseRoot, "config.json"),
  187. eventsPath: join(input.artifactsRoot, "cases", input.caseName, "events.json"),
  188. resultPath: join(input.artifactsRoot, "cases", input.caseName, "result.json"),
  189. storageDir: join(input.caseRoot, "storage"),
  190. workspace: join(input.caseRoot, "workspace"),
  191. };
  192. await mkdir(paths.storageDir, { recursive: true });
  193. await mkdir(paths.artifactsDir, { recursive: true });
  194. return paths;
  195. }
  196. export function assertCondition(condition, message, details) {
  197. if (condition) return;
  198. const suffix = details ? `\n${JSON.stringify(details, null, 2)}` : "";
  199. throw new Error(`${message}${suffix}`);
  200. }
  201. export function countEvents(events, type) {
  202. return events.filter((event) => event.type === type).length;
  203. }
  204. export function countEventTypes(events) {
  205. const counts = {};
  206. for (const event of events) {
  207. counts[event.type] = (counts[event.type] ?? 0) + 1;
  208. }
  209. return counts;
  210. }
  211. export function modelRequests(events, SessionEventType) {
  212. return events.filter((event) => event.type === SessionEventType.ModelRequest);
  213. }
  214. export function compactBoundaries(events, SessionEventType) {
  215. return events.filter((event) => event.type === SessionEventType.CompactBoundary);
  216. }
  217. export function stringifyModelRequest(event) {
  218. const payload = event?.payload;
  219. const messages = Array.isArray(payload?.messages) ? payload.messages : [];
  220. return messages.map((message) => modelContentToText(message.content)).join("\n");
  221. }
  222. export function modelContentToText(content) {
  223. if (typeof content === "string") return content;
  224. if (Array.isArray(content)) {
  225. return content.map((block) => modelContentToText(blockText(block))).join("\n");
  226. }
  227. if (content === undefined || content === null) return "";
  228. return JSON.stringify(content);
  229. }
  230. export function buildCaseResult(input) {
  231. return {
  232. capturePath: input.capturePath,
  233. capturedProviderRequestCount: input.capturedProviderRequestCount,
  234. case: input.caseName,
  235. eventCounts: countEventTypes(input.events),
  236. eventsPath: input.eventsPath,
  237. finalResponsePreview: input.response?.slice(0, 1000),
  238. model: input.model,
  239. resultPath: input.resultPath,
  240. status: "passed",
  241. traceId: input.traceId,
  242. };
  243. }
  244. export function assertProviderCapture(records) {
  245. assertCondition(records.length >= 1, "expected provider traffic to be captured");
  246. assertCondition(
  247. records.some((record) => record.upstreamURL.includes("/chat/completions")),
  248. "expected capture to include a chat completions request",
  249. { capturedURLs: records.map((record) => record.upstreamURL) },
  250. );
  251. }
  252. export function hasMicrocompactPlaceholder(text) {
  253. return text.includes(MICROCOMPACT_PLACEHOLDER);
  254. }
  255. export function fakeProviderConfig(input) {
  256. return {
  257. apiKeyRequired: false,
  258. baseURL: input.baseURL,
  259. model: input.model,
  260. providerId: FAKE_PROVIDER,
  261. providerName: "Compact E2E Fake Provider",
  262. storageDir: input.storageDir,
  263. };
  264. }
  265. function blockText(block) {
  266. if (!block || typeof block !== "object") return block;
  267. if (typeof block.text === "string") return block.text;
  268. if (typeof block.placeholder === "string") return block.placeholder;
  269. return block;
  270. }