case-usage-anchor.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import { mkdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { writeJsonFile } from "./artifacts.mjs";
  4. import {
  5. assertCondition,
  6. assertProviderCapture,
  7. buildCaseResult,
  8. buildRuntimeConfig,
  9. createApp,
  10. makeCaseDirs,
  11. modelContentToText,
  12. writeProviderConfig,
  13. } from "./case-utils.mjs";
  14. import { FAKE_MODEL } from "./constants.mjs";
  15. import { assertUsageAnchorScenario } from "./case-usage-anchor-assertions.mjs";
  16. import { createScenarioHandler, promptsForScenario } from "./case-usage-anchor-provider.mjs";
  17. import { prepareWorkspace } from "./workspace.mjs";
  18. import { startScriptedProvider, stopScriptedProvider } from "./scripted-provider.mjs";
  19. const CASE_NAME = "usage-anchor";
  20. const CONTEXT_WINDOW = 20_000;
  21. const MAX_OUTPUT_TOKENS = 16_000;
  22. const SCENARIOS = ["full", "reactive", "input-only", "hydration", "rewind"];
  23. const RESTART_AFTER_SCENARIOS = new Set(["full", "reactive", "hydration", "rewind"]);
  24. export const usageAnchorCase = {
  25. name: CASE_NAME,
  26. requiresApiKey: false,
  27. async run(input) {
  28. const scenarioResults = [];
  29. const scenarioFailures = [];
  30. const caseRoot = input.caseRoot;
  31. for (const scenario of SCENARIOS) {
  32. try {
  33. scenarioResults.push(await runScenario({ ...input, caseRoot, scenario }));
  34. } catch (error) {
  35. scenarioFailures.push({ error, scenario });
  36. }
  37. }
  38. if (scenarioFailures.length > 0) {
  39. const details = scenarioFailures
  40. .map(
  41. ({ error, scenario }) => `${scenario}: ${error instanceof Error ? error.message : error}`,
  42. )
  43. .join("\n");
  44. throw new Error(`usage-anchor scenario failures:\n${details}`, {
  45. cause: scenarioFailures[0].error,
  46. });
  47. }
  48. const resultPath = `${input.artifactsRoot}/cases/${CASE_NAME}/result.json`;
  49. const capturePath = `${input.artifactsRoot}/cases/${CASE_NAME}/capture.json`;
  50. const eventsPath = `${input.artifactsRoot}/cases/${CASE_NAME}/events.json`;
  51. await mkdir(`${input.artifactsRoot}/cases/${CASE_NAME}`, { recursive: true });
  52. const resultPayload = buildCaseResult({
  53. capturedProviderRequestCount: scenarioResults.reduce(
  54. (total, result) => total + result.capturedProviderRequestCount,
  55. 0,
  56. ),
  57. caseName: CASE_NAME,
  58. capturePath,
  59. events: scenarioResults.flatMap((result) => result.events),
  60. eventsPath,
  61. response: scenarioResults.map((result) => result.response).join("\n"),
  62. resultPath,
  63. traceId: scenarioResults.at(-1)?.traceId,
  64. });
  65. await writeJsonFile(capturePath, {
  66. case: CASE_NAME,
  67. scenarios: scenarioResults.map((result) => ({
  68. name: result.scenario,
  69. records: result.records,
  70. })),
  71. });
  72. await writeJsonFile(eventsPath, {
  73. case: CASE_NAME,
  74. scenarios: scenarioResults.map((result) => ({
  75. events: result.events,
  76. name: result.scenario,
  77. })),
  78. });
  79. await writeJsonFile(resultPath, {
  80. ...resultPayload,
  81. scenarios: scenarioResults.map(({ events: _events, records: _records, ...result }) => result),
  82. });
  83. return resultPayload;
  84. },
  85. };
  86. async function runScenario(input) {
  87. const scenarioName = `${CASE_NAME}-${input.scenario}`;
  88. const paths = await makeCaseDirs({
  89. ...input,
  90. caseName: scenarioName,
  91. caseRoot: join(input.caseRoot, input.scenario),
  92. });
  93. const events = [];
  94. let app;
  95. let provider;
  96. let rewindFollowUpRecordIndex;
  97. const historySnapshots = {};
  98. const durableSnapshots = {};
  99. try {
  100. await prepareWorkspace({
  101. fixtureDir: input.fixtureDir,
  102. workspace: paths.workspace,
  103. });
  104. provider = await startScriptedProvider({
  105. handler: createScenarioHandler(input.scenario),
  106. name: scenarioName,
  107. });
  108. await writeProviderConfig(paths.configPath, {
  109. apiKeyRequired: false,
  110. baseURL: provider.baseURL,
  111. contextWindow: CONTEXT_WINDOW,
  112. maxOutputTokens: MAX_OUTPUT_TOKENS,
  113. model: FAKE_MODEL,
  114. providerId: "compact-e2e-fake",
  115. providerName: "Usage Anchor E2E Provider",
  116. storageDir: paths.storageDir,
  117. });
  118. app = createApp({
  119. configPath: paths.configPath,
  120. modules: input.modules,
  121. runtimeConfig: buildRuntimeConfig({
  122. compact: {
  123. bufferTokens: 1,
  124. contextWindow: CONTEXT_WINDOW,
  125. // Reactive 场景只关闭 auto compact,保留 overflow 后的 reactive compact。
  126. maxConsecutiveFailures: input.scenario === "reactive" ? 0 : 1,
  127. microcompact: { enabled: false },
  128. },
  129. modelContextBudgetStrategy: "preflight-v1",
  130. maxTurns: 8,
  131. workspace: paths.workspace,
  132. }),
  133. storageDir: paths.storageDir,
  134. });
  135. const prompts = promptsForScenario(input.scenario);
  136. let result;
  137. for (const prompt of prompts) {
  138. result = await app.submitPrompt(prompt, { onEvent: async (event) => events.push(event) });
  139. }
  140. historySnapshots.beforeRestart = captureRuntimeHistory(app);
  141. durableSnapshots.beforeRestart = await captureDurableAssistantHistory(app);
  142. if (RESTART_AFTER_SCENARIOS.has(input.scenario) && input.scenario !== "rewind") {
  143. const sessionId = app.sessionId;
  144. await app.close?.();
  145. app = createApp({
  146. configPath: paths.configPath,
  147. modules: input.modules,
  148. resume: true,
  149. runtimeConfig: buildRuntimeConfig({
  150. compact: {
  151. bufferTokens: 1,
  152. contextWindow: CONTEXT_WINDOW,
  153. microcompact: { enabled: false },
  154. },
  155. modelContextBudgetStrategy: "preflight-v1",
  156. maxTurns: 8,
  157. workspace: paths.workspace,
  158. }),
  159. sessionId,
  160. storageDir: paths.storageDir,
  161. });
  162. await app.resume?.();
  163. historySnapshots.afterRestartBeforeFollowUp = captureRuntimeHistory(app);
  164. durableSnapshots.afterRestartBeforeFollowUp = await captureDurableAssistantHistory(app);
  165. result = await app.submitPrompt("Hydration follow-up after restart.", {
  166. onEvent: async (event) => events.push(event),
  167. });
  168. historySnapshots.afterRestart = captureRuntimeHistory(app);
  169. durableSnapshots.afterRestart = await captureDurableAssistantHistory(app);
  170. }
  171. if (input.scenario === "rewind") {
  172. historySnapshots.beforeRewind = historySnapshots.beforeRestart;
  173. durableSnapshots.beforeRewind = durableSnapshots.beforeRestart;
  174. const targetMessageId = app.runtime.latestAssistantMessageId;
  175. assertCondition(
  176. typeof targetMessageId === "string" && targetMessageId.length > 0,
  177. "expected a persisted assistant id before rewind",
  178. );
  179. await app.submitPrompt(`/rewind conversation ${targetMessageId}`, {
  180. onEvent: async (event) => events.push(event),
  181. });
  182. rewindFollowUpRecordIndex = provider.records.length;
  183. result = await app.submitPrompt("Rewind follow-up.", {
  184. onEvent: async (event) => events.push(event),
  185. });
  186. historySnapshots.afterRewind = captureRuntimeHistory(app);
  187. durableSnapshots.afterRewind = await captureDurableAssistantHistory(app);
  188. const sessionId = app.sessionId;
  189. await app.close?.();
  190. app = createApp({
  191. configPath: paths.configPath,
  192. modules: input.modules,
  193. resume: true,
  194. runtimeConfig: buildRuntimeConfig({
  195. compact: {
  196. bufferTokens: 1,
  197. contextWindow: CONTEXT_WINDOW,
  198. microcompact: { enabled: false },
  199. },
  200. modelContextBudgetStrategy: "preflight-v1",
  201. maxTurns: 8,
  202. workspace: paths.workspace,
  203. }),
  204. sessionId,
  205. storageDir: paths.storageDir,
  206. });
  207. await app.resume?.();
  208. historySnapshots.afterRestartBeforeFollowUp = captureRuntimeHistory(app);
  209. durableSnapshots.afterRestartBeforeFollowUp = await captureDurableAssistantHistory(app);
  210. result = await app.submitPrompt("Rewind follow-up after restart.", {
  211. onEvent: async (event) => events.push(event),
  212. });
  213. historySnapshots.afterRestart = captureRuntimeHistory(app);
  214. durableSnapshots.afterRestart = await captureDurableAssistantHistory(app);
  215. }
  216. assertUsageAnchorScenario({
  217. records: provider.records,
  218. response: result?.response ?? "",
  219. rewindFollowUpRecordIndex,
  220. scenario: input.scenario,
  221. durableSnapshots,
  222. historySnapshots,
  223. });
  224. assertProviderCapture(provider.records);
  225. await writeJsonFile(paths.capturePath, {
  226. records: provider.records,
  227. scenario: input.scenario,
  228. });
  229. await writeJsonFile(paths.eventsPath, events);
  230. return {
  231. capturedProviderRequestCount: provider.records.length,
  232. events,
  233. records: provider.records,
  234. response: result?.response ?? "",
  235. resultPath: paths.resultPath,
  236. scenario: input.scenario,
  237. traceId: result?.traceId,
  238. durableSnapshots,
  239. historySnapshots,
  240. };
  241. } catch (error) {
  242. await writeJsonFile(paths.capturePath, {
  243. error: error instanceof Error ? error.message : String(error),
  244. records: provider?.records ?? [],
  245. scenario: input.scenario,
  246. });
  247. await writeJsonFile(paths.eventsPath, events);
  248. throw error;
  249. } finally {
  250. await app?.close?.();
  251. await stopScriptedProvider(provider);
  252. }
  253. }
  254. function captureRuntimeHistory(app) {
  255. const entries = app?.runtime?.messageHistory?.borrowReadOnlyRuntimeEntries?.() ?? [];
  256. return entries.map((entry) => ({
  257. content:
  258. entry.kind === "attachment" ? entry.content : modelContentToText(entry.message?.content),
  259. kind: entry.kind ?? "message",
  260. role: entry.kind === "attachment" ? undefined : entry.message?.role,
  261. source: entry.metadata?.source,
  262. tokens: entry.tokens ? structuredClone(entry.tokens) : undefined,
  263. }));
  264. }
  265. async function captureDurableAssistantHistory(app) {
  266. const runtime = app?.runtime;
  267. const sessionStore = runtime?.sessionStore;
  268. if (!sessionStore?.messages) {
  269. throw new Error(
  270. `E2E runtime session store is unavailable; runtime keys: ${Object.getOwnPropertyNames(runtime ?? {}).join(",")}`,
  271. );
  272. }
  273. const messages = (await sessionStore.messages({ sessionID: app.sessionId })) ?? [];
  274. return messages
  275. .filter((message) => message.info?.role === "assistant")
  276. .map((message) => ({
  277. content: message.parts
  278. .filter((part) => part.type === "text")
  279. .map((part) => part.text)
  280. .join(""),
  281. id: message.info.id,
  282. tokens: message.info.tokens ? structuredClone(message.info.tokens) : undefined,
  283. }));
  284. }