case-background-bash.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { FAKE_MODEL } from "./constants.mjs";
  4. import {
  5. assertCondition,
  6. assertProviderCapture,
  7. buildCaseResult,
  8. buildRuntimeConfig,
  9. createApp,
  10. fakeProviderConfig,
  11. makeCaseDirs,
  12. modelRequests,
  13. stringifyModelRequest,
  14. writeProviderConfig,
  15. } from "./case-utils.mjs";
  16. import { writeJsonFile } from "./artifacts.mjs";
  17. import { prepareWorkspace } from "./workspace.mjs";
  18. import {
  19. chatCompletion,
  20. startScriptedProvider,
  21. stopScriptedProvider,
  22. writeScriptedCaptureFile,
  23. } from "./scripted-provider.mjs";
  24. const CASE_NAME = "background-bash";
  25. const COMPLETION_MARKER = "BACKGROUND_BASH_E2E_DONE";
  26. const BACKGROUND_STDOUT_FIRST = "BACKGROUND_BASH_E2E_STDOUT_FIRST";
  27. const BACKGROUND_STDERR = "BACKGROUND_BASH_E2E_STDERR";
  28. const BACKGROUND_STDOUT_LAST = "BACKGROUND_BASH_E2E_STDOUT_LAST";
  29. const FOREGROUND_STDOUT_FIRST = "FOREGROUND_BASH_E2E_STDOUT_FIRST";
  30. const FOREGROUND_STDERR = "FOREGROUND_BASH_E2E_STDERR";
  31. const FOREGROUND_STDOUT_LAST = "FOREGROUND_BASH_E2E_STDOUT_LAST";
  32. const BACKGROUND_TOOL_CALL_ID = "call_background_bash_e2e";
  33. const WAIT_TOOL_CALL_ID = "call_background_bash_wait";
  34. const PIPE_FLUSH_MS = 50;
  35. const WAIT_FOR_BACKGROUND_POLL_MS = 1_500;
  36. export const backgroundBashCase = {
  37. name: CASE_NAME,
  38. requiresApiKey: false,
  39. async run(input) {
  40. const events = [];
  41. const paths = await makeCaseDirs({ ...input, caseName: CASE_NAME });
  42. let app;
  43. let provider;
  44. try {
  45. await prepareWorkspace({
  46. fixtureDir: input.fixtureDir,
  47. workspace: paths.workspace,
  48. });
  49. await writeBashScripts(paths.workspace);
  50. provider = await startScriptedProvider({
  51. handler: createBackgroundBashHandler(),
  52. name: CASE_NAME,
  53. });
  54. await writeProviderConfig(
  55. paths.configPath,
  56. fakeProviderConfig({
  57. baseURL: provider.baseURL,
  58. model: FAKE_MODEL,
  59. storageDir: paths.storageDir,
  60. }),
  61. );
  62. app = await createApp({
  63. configPath: paths.configPath,
  64. modules: input.modules,
  65. runtimeConfig: buildRuntimeConfig({
  66. compact: {
  67. contextWindow: 1_000_000,
  68. microcompact: { enabled: false },
  69. },
  70. maxTurns: 6,
  71. workspace: paths.workspace,
  72. }),
  73. storageDir: paths.storageDir,
  74. });
  75. const result = await app.submitPrompt(buildPrompt(), {
  76. onEvent: async (event) => events.push(event),
  77. });
  78. await assertBackgroundBashOutcome({
  79. events,
  80. records: provider.records,
  81. response: result.response,
  82. SessionEventType: input.modules.SessionEventType,
  83. });
  84. assertProviderCapture(provider.records);
  85. await writeScriptedCaptureFile(provider, paths.capturePath);
  86. await writeJsonFile(paths.eventsPath, events);
  87. const resultPayload = buildCaseResult({
  88. capturedProviderRequestCount: provider.records.length,
  89. caseName: CASE_NAME,
  90. capturePath: paths.capturePath,
  91. events,
  92. eventsPath: paths.eventsPath,
  93. response: result.response,
  94. resultPath: paths.resultPath,
  95. traceId: result.traceId,
  96. });
  97. await writeJsonFile(paths.resultPath, resultPayload);
  98. return resultPayload;
  99. } catch (error) {
  100. await writeScriptedCaptureFile(provider, paths.capturePath);
  101. await writeJsonFile(paths.eventsPath, events);
  102. throw error;
  103. } finally {
  104. await app?.close?.();
  105. await stopScriptedProvider(provider);
  106. }
  107. },
  108. };
  109. function buildPrompt() {
  110. return [
  111. "Run the background Bash E2E.",
  112. "Use Bash with run_in_background=true to run node scripts/background-bash.mjs.",
  113. "When the runtime reports the background task notification, read no files and answer with the completion marker only.",
  114. `Completion marker: ${COMPLETION_MARKER}`,
  115. ].join("\n");
  116. }
  117. function createBackgroundBashHandler() {
  118. let requestCount = 0;
  119. let waitIssued = false;
  120. return async ({ body }) => {
  121. requestCount += 1;
  122. const requestText = JSON.stringify(body?.messages ?? []);
  123. if (requestCount === 1) {
  124. return {
  125. body: chatCompletion({
  126. model: body?.model,
  127. toolCalls: [
  128. openAiToolCall(BACKGROUND_TOOL_CALL_ID, "Bash", {
  129. command: "node scripts/background-bash.mjs",
  130. description: "Run background Bash E2E script",
  131. run_in_background: true,
  132. }),
  133. ],
  134. }),
  135. };
  136. }
  137. if (!waitIssued) {
  138. waitIssued = true;
  139. return {
  140. body: chatCompletion({
  141. model: body?.model,
  142. toolCalls: [
  143. openAiToolCall(WAIT_TOOL_CALL_ID, "Bash", {
  144. command: "node scripts/foreground-bash.mjs",
  145. description: "Wait for background Bash E2E completion",
  146. }),
  147. ],
  148. }),
  149. };
  150. }
  151. if (requestText.includes("<task-notification>")) {
  152. return {
  153. body: chatCompletion({
  154. content: COMPLETION_MARKER,
  155. model: body?.model,
  156. }),
  157. };
  158. }
  159. return {
  160. body: chatCompletion({
  161. content: "BACKGROUND_BASH_E2E_MISSING_NOTIFICATION",
  162. model: body?.model,
  163. }),
  164. };
  165. };
  166. }
  167. async function assertBackgroundBashOutcome(input) {
  168. const { events, response, records, SessionEventType } = input;
  169. const startedEvents = events.filter(
  170. (event) => event.type === SessionEventType.BackgroundTaskStarted,
  171. );
  172. const completedEvents = events.filter(
  173. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  174. );
  175. const completedPayload = completedEvents.at(-1)?.payload;
  176. const requestContexts = modelRequests(events, SessionEventType).map(stringifyModelRequest);
  177. const notifiedContext = requestContexts.find((context) =>
  178. context.includes("<task-notification>"),
  179. );
  180. const messages = providerMessages(records);
  181. assertCondition(response.includes(COMPLETION_MARKER), `expected ${COMPLETION_MARKER}`, {
  182. response,
  183. });
  184. assertCondition(startedEvents.length >= 1, "expected a background task started event");
  185. assertCondition(completedEvents.length >= 1, "expected a background task completed event");
  186. assertCondition(completedPayload?.status === "completed", "expected background task completion", {
  187. completedPayload,
  188. });
  189. assertCondition(
  190. typeof completedPayload?.outputPath === "string" &&
  191. completedPayload.outputPath.endsWith("-stdout.log"),
  192. "expected stdout output path on background completion",
  193. { completedPayload },
  194. );
  195. assertCondition(
  196. completedPayload?.stderrPersistedOutputPath === undefined,
  197. "expected no split stderr output path on background completion",
  198. { completedPayload },
  199. );
  200. const expectedBackgroundResult =
  201. `Command running in background with ID: ${completedPayload.taskId}. ` +
  202. `Output is being written to: ${completedPayload.outputPath}. ` +
  203. "You will be notified when it completes. " +
  204. "To check interim output, use Read on that file path.";
  205. const backgroundResult = messages.find(
  206. (message) => message?.role === "tool" && message?.tool_call_id === BACKGROUND_TOOL_CALL_ID,
  207. )?.content;
  208. assertCondition(
  209. backgroundResult === expectedBackgroundResult,
  210. "expected exact single-path background Bash provider result",
  211. { backgroundResult, expectedBackgroundResult },
  212. );
  213. const expectedForegroundResult = [
  214. FOREGROUND_STDOUT_FIRST,
  215. FOREGROUND_STDERR,
  216. FOREGROUND_STDOUT_LAST,
  217. ].join("\n");
  218. const foregroundResult = messages.find(
  219. (message) => message?.role === "tool" && message?.tool_call_id === WAIT_TOOL_CALL_ID,
  220. )?.content;
  221. assertCondition(
  222. foregroundResult === expectedForegroundResult,
  223. "expected foreground Bash provider result to preserve synchronized stdout/stderr order",
  224. { foregroundResult, expectedForegroundResult },
  225. );
  226. const expectedNotification = [
  227. "<task-notification>",
  228. `<task-id>${completedPayload.taskId}</task-id>`,
  229. `<tool-use-id>${BACKGROUND_TOOL_CALL_ID}</tool-use-id>`,
  230. `<output-file>${completedPayload.outputPath}</output-file>`,
  231. "<status>completed</status>",
  232. '<summary>Background command "Run background Bash E2E script" completed (exit code 0)</summary>',
  233. "</task-notification>",
  234. ].join("\n");
  235. const providerNotification = messages.find(
  236. (message) =>
  237. typeof message?.content === "string" && message.content.includes("<task-notification>"),
  238. )?.content;
  239. assertCondition(Boolean(notifiedContext), "expected task notification in model context");
  240. assertCondition(
  241. providerNotification === expectedNotification,
  242. "expected exact single-path background Bash completion notification",
  243. { expectedNotification, providerNotification },
  244. );
  245. const output = await readFile(completedPayload.outputPath, "utf8");
  246. const expectedOutput = [
  247. BACKGROUND_STDOUT_FIRST,
  248. BACKGROUND_STDERR,
  249. BACKGROUND_STDOUT_LAST,
  250. "",
  251. ].join("\n");
  252. assertCondition(
  253. output === expectedOutput,
  254. "expected canonical output file to preserve synchronized stdout/stderr order",
  255. { expectedOutput, output, outputPath: completedPayload.outputPath },
  256. );
  257. assertCondition(
  258. completedPayload.stdoutPersistedOutputPath === completedPayload.outputPath,
  259. "expected stdout compatibility path to reuse the canonical output file",
  260. {
  261. completedPayload,
  262. },
  263. );
  264. }
  265. function providerMessages(records) {
  266. return records.flatMap((record) => {
  267. const body = JSON.parse(record.requestBody);
  268. return Array.isArray(body?.messages) ? body.messages : [];
  269. });
  270. }
  271. async function writeBashScripts(workspace) {
  272. const backgroundScript = [
  273. 'import { writeSync } from "node:fs";',
  274. `writeSync(1, ${JSON.stringify(`${BACKGROUND_STDOUT_FIRST}\n`)});`,
  275. `await new Promise((resolve) => setTimeout(resolve, ${PIPE_FLUSH_MS}));`,
  276. `writeSync(2, ${JSON.stringify(`${BACKGROUND_STDERR}\n`)});`,
  277. `await new Promise((resolve) => setTimeout(resolve, ${PIPE_FLUSH_MS}));`,
  278. `writeSync(1, ${JSON.stringify(`${BACKGROUND_STDOUT_LAST}\n`)});`,
  279. "",
  280. ].join("\n");
  281. const foregroundScript = [
  282. 'import { writeSync } from "node:fs";',
  283. `writeSync(1, ${JSON.stringify(`${FOREGROUND_STDOUT_FIRST}\n`)});`,
  284. `await new Promise((resolve) => setTimeout(resolve, ${PIPE_FLUSH_MS}));`,
  285. `writeSync(2, ${JSON.stringify(`${FOREGROUND_STDERR}\n`)});`,
  286. `await new Promise((resolve) => setTimeout(resolve, ${PIPE_FLUSH_MS}));`,
  287. `writeSync(1, ${JSON.stringify(`${FOREGROUND_STDOUT_LAST}\n`)});`,
  288. `await new Promise((resolve) => setTimeout(resolve, ${WAIT_FOR_BACKGROUND_POLL_MS}));`,
  289. "",
  290. ].join("\n");
  291. await Promise.all([
  292. writeFile(join(workspace, "scripts", "background-bash.mjs"), backgroundScript),
  293. writeFile(join(workspace, "scripts", "foreground-bash.mjs"), foregroundScript),
  294. ]);
  295. }
  296. function openAiToolCall(id, name, input) {
  297. return {
  298. id,
  299. type: "function",
  300. function: {
  301. name,
  302. arguments: JSON.stringify(input),
  303. },
  304. };
  305. }