case-utils.mjs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. },
  117. runtimeConfig: input.runtimeConfig,
  118. // 重构后旧字符串解析入口已删除;新 session 使用完整选择,冷恢复仍由持久选择接管。
  119. configuredDefaultModelSelection: {
  120. providerId: providerConfig.providerId,
  121. modelId: providerConfig.modelId,
  122. options: { reasoningLevel: "disabled" },
  123. },
  124. userConfigPath: input.configPath,
  125. providerRegistry: createProviderRegistry(input.modules.provider, providerConfig),
  126. // Bug 根因:迁移 Registry 时漏传恢复参数,原本的 cold case 会误建新 session。
  127. ...(input.resume ? { resume: true } : {}),
  128. ...(input.sessionId ? { sessionId: input.sessionId } : {}),
  129. });
  130. }
  131. function createProviderRegistry(providerModule, input) {
  132. if (!input.baseURL) {
  133. throw new Error(`Compact E2E Provider ${input.providerId} is missing baseURL`);
  134. }
  135. const config = new providerModule.ProviderConfig({
  136. group: "standard-personal",
  137. access: new providerModule.ApiKeyAccessConfig({ apiKey: input.apiKey }),
  138. api: new providerModule.ProviderApiConfig({
  139. type: input.apiFormat,
  140. baseUrl: input.baseURL,
  141. }),
  142. personalModelIds: [input.modelId],
  143. visibility: "visible",
  144. });
  145. const model = new providerModule.ModelConfig({
  146. enabled: true,
  147. properties: new providerModule.ModelPropertiesConfig({
  148. requiresMfjsToolSchema: false,
  149. contextWindow: input.contextWindow,
  150. inputFormat: {
  151. supportsText: true,
  152. supportsImage: true,
  153. supportsVideo: true,
  154. supportsAudio: false,
  155. supportsPdf: true,
  156. },
  157. outputFormat: { supportsText: true },
  158. supportsToolCall: true,
  159. supportsJsonSchemaOutput: true,
  160. supportsNativeWebSearch: false,
  161. supportsMidConversationSystem: true,
  162. }),
  163. optionSpecs: new providerModule.ModelOptionSpecsConfig({
  164. reasoningLevel: { values: ["disabled"], map: "{}" },
  165. // Bug 根因:helper 丢掉 case 的预算并漏配 Option Map,旧 wire 断言因此失去真实输入。
  166. maxOutputTokens: {
  167. max: input.maxOutputTokens,
  168. map: `{"${OUTPUT_TOKEN_FIELDS[input.apiFormat]}":maxOutputTokens}`,
  169. },
  170. }),
  171. });
  172. return new providerModule.ProviderRegistry([
  173. {
  174. providerId: input.providerId,
  175. config,
  176. models: [{ modelId: input.modelId, config: model }],
  177. },
  178. ]);
  179. }
  180. export async function makeCaseDirs(input) {
  181. const paths = {
  182. artifactsDir: join(input.artifactsRoot, "cases", input.caseName),
  183. capturePath: join(input.artifactsRoot, "cases", input.caseName, "capture.json"),
  184. configPath: join(input.caseRoot, "config.json"),
  185. eventsPath: join(input.artifactsRoot, "cases", input.caseName, "events.json"),
  186. resultPath: join(input.artifactsRoot, "cases", input.caseName, "result.json"),
  187. storageDir: join(input.caseRoot, "storage"),
  188. workspace: join(input.caseRoot, "workspace"),
  189. };
  190. await mkdir(paths.storageDir, { recursive: true });
  191. await mkdir(paths.artifactsDir, { recursive: true });
  192. return paths;
  193. }
  194. export function assertCondition(condition, message, details) {
  195. if (condition) return;
  196. const suffix = details ? `\n${JSON.stringify(details, null, 2)}` : "";
  197. throw new Error(`${message}${suffix}`);
  198. }
  199. export function countEvents(events, type) {
  200. return events.filter((event) => event.type === type).length;
  201. }
  202. export function countEventTypes(events) {
  203. const counts = {};
  204. for (const event of events) {
  205. counts[event.type] = (counts[event.type] ?? 0) + 1;
  206. }
  207. return counts;
  208. }
  209. export function modelRequests(events, SessionEventType) {
  210. return events.filter((event) => event.type === SessionEventType.ModelRequest);
  211. }
  212. export function compactBoundaries(events, SessionEventType) {
  213. return events.filter((event) => event.type === SessionEventType.CompactBoundary);
  214. }
  215. export function stringifyModelRequest(event) {
  216. const payload = event?.payload;
  217. const messages = Array.isArray(payload?.messages) ? payload.messages : [];
  218. return messages.map((message) => modelContentToText(message.content)).join("\n");
  219. }
  220. export function modelContentToText(content) {
  221. if (typeof content === "string") return content;
  222. if (Array.isArray(content)) {
  223. return content.map((block) => modelContentToText(blockText(block))).join("\n");
  224. }
  225. if (content === undefined || content === null) return "";
  226. return JSON.stringify(content);
  227. }
  228. export function buildCaseResult(input) {
  229. return {
  230. capturePath: input.capturePath,
  231. capturedProviderRequestCount: input.capturedProviderRequestCount,
  232. case: input.caseName,
  233. eventCounts: countEventTypes(input.events),
  234. eventsPath: input.eventsPath,
  235. finalResponsePreview: input.response?.slice(0, 1000),
  236. model: input.model,
  237. resultPath: input.resultPath,
  238. status: "passed",
  239. traceId: input.traceId,
  240. };
  241. }
  242. export function assertProviderCapture(records) {
  243. assertCondition(records.length >= 1, "expected provider traffic to be captured");
  244. assertCondition(
  245. records.some((record) => record.upstreamURL.includes("/chat/completions")),
  246. "expected capture to include a chat completions request",
  247. { capturedURLs: records.map((record) => record.upstreamURL) },
  248. );
  249. }
  250. export function hasMicrocompactPlaceholder(text) {
  251. return text.includes(MICROCOMPACT_PLACEHOLDER);
  252. }
  253. export function fakeProviderConfig(input) {
  254. return {
  255. apiKeyRequired: false,
  256. baseURL: input.baseURL,
  257. model: input.model,
  258. providerId: FAKE_PROVIDER,
  259. providerName: "Compact E2E Fake Provider",
  260. storageDir: input.storageDir,
  261. };
  262. }
  263. function blockText(block) {
  264. if (!block || typeof block !== "object") return block;
  265. if (typeof block.text === "string") return block.text;
  266. if (typeof block.placeholder === "string") return block.placeholder;
  267. return block;
  268. }