case-output-token-continuation.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. writeProviderConfig,
  12. } from "./case-utils.mjs";
  13. import { FAKE_MODEL } from "./constants.mjs";
  14. import {
  15. chatCompletion,
  16. startScriptedProvider,
  17. stopScriptedProvider,
  18. } from "./scripted-provider.mjs";
  19. import { prepareWorkspace } from "./workspace.mjs";
  20. import {
  21. assistantContents,
  22. captureDurableAssistantHistory,
  23. captureRuntimeHistory,
  24. } from "./output-token-continuation-history.mjs";
  25. const CASE_NAME = "output-token-continuation";
  26. const OUTPUT_TOKEN_CONTINUE_PROMPT =
  27. "Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.";
  28. const OUTPUT_TOKEN_LIMIT_ERROR = "The model's response exceeded the output token maximum.";
  29. const SUCCESS_PARTIAL = "OUTPUT_CONTINUE_E2E_PARTIAL";
  30. const SUCCESS_DONE = "OUTPUT_CONTINUE_E2E_DONE";
  31. const COLD_DONE = "OUTPUT_CONTINUE_E2E_COLD_DONE";
  32. const AFTER_ERROR_DONE = "OUTPUT_CONTINUE_E2E_AFTER_ERROR_DONE";
  33. const SCENARIOS = ["success", "exhausted"];
  34. const CONTEXT_WINDOW = 100_000;
  35. const MAX_OUTPUT_TOKENS = 16_000;
  36. export const outputTokenContinuationCase = {
  37. name: CASE_NAME,
  38. requiresApiKey: false,
  39. async run(input) {
  40. const scenarioResults = [];
  41. for (const scenario of SCENARIOS) {
  42. scenarioResults.push(
  43. await runScenario({
  44. ...input,
  45. caseRoot: join(input.caseRoot, scenario),
  46. scenario,
  47. }),
  48. );
  49. }
  50. const artifactsDir = `${input.artifactsRoot}/cases/${CASE_NAME}`;
  51. const capturePath = `${artifactsDir}/capture.json`;
  52. const eventsPath = `${artifactsDir}/events.json`;
  53. const resultPath = `${artifactsDir}/result.json`;
  54. await mkdir(artifactsDir, { recursive: true });
  55. await writeJsonFile(capturePath, {
  56. case: CASE_NAME,
  57. scenarios: scenarioResults.map((result) => ({
  58. name: result.scenario,
  59. records: result.records,
  60. })),
  61. });
  62. await writeJsonFile(eventsPath, {
  63. case: CASE_NAME,
  64. scenarios: scenarioResults.map((result) => ({
  65. events: result.events,
  66. name: result.scenario,
  67. })),
  68. });
  69. const result = buildCaseResult({
  70. capturedProviderRequestCount: scenarioResults.reduce(
  71. (total, scenario) => total + scenario.records.length,
  72. 0,
  73. ),
  74. caseName: CASE_NAME,
  75. capturePath,
  76. events: scenarioResults.flatMap((scenario) => scenario.events),
  77. eventsPath,
  78. response: scenarioResults.map((scenario) => scenario.response).join("\n"),
  79. resultPath,
  80. traceId: scenarioResults.at(-1)?.traceId,
  81. });
  82. await writeJsonFile(resultPath, {
  83. ...result,
  84. scenarios: scenarioResults.map(
  85. ({ events: _events, records: _records, ...scenario }) => scenario,
  86. ),
  87. });
  88. return result;
  89. },
  90. };
  91. async function runScenario(input) {
  92. const scenarioName = `${CASE_NAME}-${input.scenario}`;
  93. const paths = await makeCaseDirs({ ...input, caseName: scenarioName });
  94. const events = [];
  95. let app;
  96. let provider;
  97. try {
  98. await prepareWorkspace({ fixtureDir: input.fixtureDir, workspace: paths.workspace });
  99. provider = await startScriptedProvider({
  100. handler: createScenarioHandler(input.scenario),
  101. name: scenarioName,
  102. });
  103. await writeProviderConfig(paths.configPath, {
  104. apiKeyRequired: false,
  105. baseURL: provider.baseURL,
  106. contextWindow: CONTEXT_WINDOW,
  107. maxOutputTokens: MAX_OUTPUT_TOKENS,
  108. model: FAKE_MODEL,
  109. providerId: "output-continuation-e2e-fake",
  110. providerName: "Output Continuation E2E Provider",
  111. storageDir: paths.storageDir,
  112. });
  113. const runtimeConfig = {
  114. ...buildRuntimeConfig({
  115. compact: { enabled: false, microcompact: { enabled: false } },
  116. maxTurns: 12,
  117. workspace: paths.workspace,
  118. }),
  119. titleGeneration: { enabled: false },
  120. };
  121. // Bug 根因:createApp 已异步化,漏 await 会在第一条 provider 请求前直接失败。
  122. app = await createApp({
  123. configPath: paths.configPath,
  124. modules: input.modules,
  125. runtimeConfig,
  126. storageDir: paths.storageDir,
  127. });
  128. const scenarioResult =
  129. input.scenario === "success"
  130. ? await runSuccessScenario({
  131. app,
  132. events,
  133. input,
  134. paths,
  135. provider,
  136. runtimeConfig,
  137. })
  138. : await runExhaustedScenario({
  139. app,
  140. events,
  141. input,
  142. paths,
  143. provider,
  144. runtimeConfig,
  145. });
  146. assertProviderCapture(provider.records);
  147. await writeJsonFile(paths.capturePath, { records: provider.records, scenario: input.scenario });
  148. await writeJsonFile(paths.eventsPath, events);
  149. return {
  150. ...scenarioResult,
  151. events,
  152. records: provider.records,
  153. scenario: input.scenario,
  154. };
  155. } catch (error) {
  156. await writeJsonFile(paths.capturePath, {
  157. error: error instanceof Error ? error.message : String(error),
  158. records: provider?.records ?? [],
  159. scenario: input.scenario,
  160. });
  161. await writeJsonFile(paths.eventsPath, events);
  162. throw error;
  163. } finally {
  164. await app?.close?.();
  165. await stopScriptedProvider(provider);
  166. }
  167. }
  168. async function runSuccessScenario({ app, events, input, paths, provider, runtimeConfig }) {
  169. const result = await app.submitPrompt("Run successful output continuation.", {
  170. onEvent: async (event) => events.push(event),
  171. });
  172. const firstTurnRecords = [...provider.records];
  173. const runtimeHistory = captureRuntimeHistory(app);
  174. const durableHistory = await captureDurableAssistantHistory(app);
  175. assertCondition(
  176. result.response === SUCCESS_DONE,
  177. "successful chain must return only final text",
  178. {
  179. response: result.response,
  180. },
  181. );
  182. assertContinueRequestSequence(firstTurnRecords);
  183. assertNoRecordedContinue(events, input.modules.SessionEventType);
  184. assertCondition(
  185. assistantContents(runtimeHistory).join("|") === `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  186. "only real partial and final assistants may enter runtime history",
  187. { runtimeHistory },
  188. );
  189. assertCondition(
  190. durableHistory.map((message) => message.content).join("|") ===
  191. `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  192. "only real partial and final assistants may enter durable history",
  193. { durableHistory },
  194. );
  195. const sessionId = app.sessionId;
  196. await app.close?.();
  197. let resumedApp;
  198. try {
  199. resumedApp = await createApp({
  200. configPath: paths.configPath,
  201. modules: input.modules,
  202. resume: true,
  203. runtimeConfig,
  204. sessionId,
  205. storageDir: paths.storageDir,
  206. });
  207. await resumedApp.resume?.();
  208. // 恢复成功必须同时证明身份和历史,避免新建空 session 也满足“不含 Continue”。
  209. assertCondition(
  210. resumedApp.sessionId === sessionId,
  211. "cold App must retain the original session",
  212. );
  213. assertCondition(
  214. assistantContents(captureRuntimeHistory(resumedApp)).join("|") ===
  215. `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
  216. "cold App must restore the original partial and final assistants before the next prompt",
  217. );
  218. const coldResult = await resumedApp.submitPrompt("Cold follow-up after output continuation.", {
  219. onEvent: async (event) => events.push(event),
  220. });
  221. const coldRequest = parseRecordBody(provider.records.at(-1));
  222. assertCondition(coldResult.response === COLD_DONE, "cold follow-up must complete normally");
  223. assertCondition(
  224. countContinuePrompts(coldRequest) === 0,
  225. "Continue must not leak into the cold follow-up provider request",
  226. { messages: coldRequest.messages },
  227. );
  228. assertCondition(
  229. JSON.stringify(coldRequest.messages ?? []).includes(
  230. "Cold follow-up after output continuation.",
  231. ),
  232. "cold follow-up request must include the new real user input",
  233. );
  234. return { response: coldResult.response, traceId: coldResult.traceId };
  235. } finally {
  236. await resumedApp?.close?.();
  237. }
  238. }
  239. async function runExhaustedScenario({ app, events, input, paths, provider, runtimeConfig }) {
  240. const { SessionEventType } = input.modules;
  241. let terminalError;
  242. try {
  243. await app.submitPrompt("Exhaust output continuation.", {
  244. onEvent: async (event) => events.push(event),
  245. });
  246. } catch (error) {
  247. terminalError = error;
  248. }
  249. const exhaustedHistory = captureRuntimeHistory(app);
  250. const exhaustedDurableHistory = await captureDurableAssistantHistory(app);
  251. assertCondition(
  252. terminalError instanceof Error && terminalError.message === OUTPUT_TOKEN_LIMIT_ERROR,
  253. "fourth output limit must reject the current Turn with the stable error",
  254. { error: terminalError instanceof Error ? terminalError.message : terminalError },
  255. );
  256. assertCondition(provider.records.length === 4, "exhaustion must not send a fifth request");
  257. assertContinueRequestSequence(provider.records);
  258. const exhaustedRuntimeAssistants = exhaustedHistory.filter((entry) => entry.role === "assistant");
  259. assertCondition(
  260. exhaustedRuntimeAssistants.length === 0 &&
  261. exhaustedDurableHistory.length === 1 &&
  262. exhaustedDurableHistory[0]?.content === "" &&
  263. exhaustedDurableHistory[0]?.error?.data?.message === OUTPUT_TOKEN_LIMIT_ERROR &&
  264. exhaustedDurableHistory[0]?.tokens?.input === 0 &&
  265. exhaustedDurableHistory[0]?.tokens?.output === 0,
  266. "fully empty exhaustion must persist only the durable assistant error",
  267. { exhaustedDurableHistory, exhaustedHistory },
  268. );
  269. assertNoRecordedContinue(events, SessionEventType);
  270. assertCondition(
  271. events.some((event) => event.type === SessionEventType.TurnError) &&
  272. !events.some((event) => event.type === SessionEventType.TurnComplete),
  273. "exhausted Turn must end in TurnError without TurnComplete(success)",
  274. { eventTypes: events.map((event) => event.type) },
  275. );
  276. const sessionId = app.sessionId;
  277. await app.close?.();
  278. const resumedApp = await createApp({
  279. configPath: paths.configPath,
  280. modules: input.modules,
  281. resume: true,
  282. runtimeConfig,
  283. sessionId,
  284. storageDir: paths.storageDir,
  285. });
  286. try {
  287. await resumedApp.resume?.({ onEvent: async (event) => events.push(event) });
  288. assertCondition(
  289. resumedApp.sessionId === sessionId,
  290. "exhausted App must resume the original session",
  291. );
  292. assertCondition(
  293. captureRuntimeHistory(resumedApp).some(
  294. (entry) => entry.role === "user" && entry.content.includes("Exhaust output continuation."),
  295. ),
  296. "exhausted cold App must restore the original user history",
  297. );
  298. const nextResult = await resumedApp.submitPrompt("Continue after the output-limit error.", {
  299. onEvent: async (event) => events.push(event),
  300. });
  301. const nextRequest = parseRecordBody(provider.records.at(-1));
  302. assertCondition(
  303. nextResult.response === AFTER_ERROR_DONE,
  304. "cold runtime must accept the next Turn",
  305. );
  306. assertCondition(provider.records.length === 5, "next Turn must issue exactly one new request");
  307. assertCondition(
  308. countContinuePrompts(nextRequest) === 0 &&
  309. !nextRequest.messages?.some((message) => message.role === "assistant"),
  310. "cold provider history must exclude Continue and the error-only assistant",
  311. );
  312. return { response: nextResult.response, traceId: nextResult.traceId };
  313. } finally {
  314. await resumedApp.close?.();
  315. }
  316. }
  317. function createScenarioHandler(scenario) {
  318. let requestCount = 0;
  319. return async ({ body }) => {
  320. assertCondition(
  321. body?.max_tokens === MAX_OUTPUT_TOKENS,
  322. "every request must retain the case output budget",
  323. {
  324. max_tokens: body?.max_tokens,
  325. },
  326. );
  327. requestCount += 1;
  328. if (scenario === "success") {
  329. const responses = [
  330. { content: "", finishReason: "length" },
  331. { content: SUCCESS_PARTIAL, finishReason: "length" },
  332. { content: "", finishReason: "length" },
  333. { content: SUCCESS_DONE, finishReason: "stop" },
  334. { content: COLD_DONE, finishReason: "stop" },
  335. ];
  336. const response = responses[requestCount - 1];
  337. if (!response) throw new Error(`Unexpected success request ${requestCount}`);
  338. return { body: chatCompletion({ ...response, model: body?.model }) };
  339. }
  340. if (requestCount <= 4) {
  341. return {
  342. body: chatCompletion({
  343. completionTokens: 0,
  344. content: "",
  345. finishReason: "length",
  346. model: body?.model,
  347. }),
  348. };
  349. }
  350. if (requestCount === 5) {
  351. return { body: chatCompletion({ content: AFTER_ERROR_DONE, model: body?.model }) };
  352. }
  353. throw new Error(`Unexpected exhausted request ${requestCount}`);
  354. };
  355. }
  356. function assertContinueRequestSequence(records) {
  357. assertCondition(records.length === 4, "recovery chain must contain exactly four requests", {
  358. requestCount: records.length,
  359. });
  360. const counts = records.map((record) => countContinuePrompts(parseRecordBody(record)));
  361. assertCondition(
  362. JSON.stringify(counts) === JSON.stringify([0, 1, 2, 3]),
  363. "requests 1-4 must contain 0/1/2/3 exact Continue messages",
  364. { counts },
  365. );
  366. }
  367. function assertNoRecordedContinue(events, SessionEventType) {
  368. const modelRequests = events.filter((event) => event.type === SessionEventType.ModelRequest);
  369. assertCondition(
  370. !JSON.stringify(modelRequests).includes(OUTPUT_TOKEN_CONTINUE_PROMPT),
  371. "ModelRequest events must not record query-local Continue",
  372. );
  373. }
  374. function countContinuePrompts(body) {
  375. return JSON.stringify(body?.messages ?? []).split(OUTPUT_TOKEN_CONTINUE_PROMPT).length - 1;
  376. }
  377. function parseRecordBody(record) {
  378. try {
  379. return JSON.parse(record?.requestBody ?? "{}");
  380. } catch {
  381. return {};
  382. }
  383. }