bash-result-mapping.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. parseImageDataUrl,
  4. type BashInput,
  5. type BashOutput,
  6. type ExecutionPort,
  7. type ExecutionResult,
  8. type ModelMessageContent,
  9. type ToolArtifactReadRequest,
  10. type ToolArtifactStorePort,
  11. type ToolArtifactWriteRequest,
  12. } from "@zcode/contracts";
  13. import { bashHandler, bashToolEntry } from "../src/tool/handlers/bash.js";
  14. import { formatPersistedOutputEnvelope } from "../src/tool/result-persistence-format.js";
  15. import { serializeOutput } from "../src/tool/executor/result-serialization.js";
  16. import type { ToolExecutorDeps } from "../src/tool/executor/types.js";
  17. import type { ToolExecutionContext } from "../src/tool/types.js";
  18. const GH_RATE_LIMIT_HINT =
  19. "<system-reminder>GitHub API rate limit exceeded (5,000/hr shared across all tools and agents). Run `gh api rate_limit --jq .resources` and sleep until reset before further gh calls. If polling in a loop, use ScheduleWakeup instead of retrying.</system-reminder>";
  20. const PNG_1X1_BASE64 =
  21. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
  22. describe("Bash result mapping", () => {
  23. it("parses image data URIs through the shared media helper", () => {
  24. const parsed = parseImageDataUrl(` data:image/PNG;base64,${PNG_1X1_BASE64} `);
  25. expect(parsed?.mediaType).toBe("image/png");
  26. expect(parsed?.base64).toBe(PNG_1X1_BASE64);
  27. expect(parsed?.dataUrl).toBe(`data:image/png;base64,${PNG_1X1_BASE64}`);
  28. expect(Buffer.from(parsed?.data ?? []).byteLength).toBeGreaterThan(0);
  29. expect(parseImageDataUrl("data:text/plain;base64,aaaa")).toBeUndefined();
  30. expect(parseImageDataUrl("data:image/png;base64,abcde")).toBeUndefined();
  31. });
  32. it("formats persisted-output envelopes with caller supplied byte style", () => {
  33. expect(
  34. formatPersistedOutputEnvelope({
  35. content: `${"a".repeat(1_200)}\n${"b".repeat(1_200)}`,
  36. formatBytes: (bytes) => `fmt:${bytes}`,
  37. originalBytes: 4_096,
  38. persistedPath: "/tmp/stdout.log",
  39. previewChars: 2_000,
  40. }),
  41. ).toBe(
  42. [
  43. "<persisted-output>",
  44. "Output too large (fmt:4096). Full output saved to: /tmp/stdout.log",
  45. "",
  46. "Preview (first fmt:2000):",
  47. "a".repeat(1_200),
  48. "...",
  49. "</persisted-output>",
  50. ].join("\n"),
  51. );
  52. });
  53. it("returns structuredContent before image, text, stderr, background, and hints", () => {
  54. const structuredContent = [{ type: "text", text: "structured result" }];
  55. expect(
  56. formatModelContent(
  57. bashOutput({
  58. stdout: `data:image/png;base64,${PNG_1X1_BASE64}`,
  59. stderr: "stderr should be ignored",
  60. isImage: true,
  61. backgroundTaskId: "exec_bg",
  62. structuredContent,
  63. staleReadFileStateHint: "stale hint should be ignored",
  64. ghRateLimitHint: GH_RATE_LIMIT_HINT,
  65. }),
  66. ),
  67. ).toEqual(structuredContent);
  68. });
  69. it("formats stdout, stderr, stale read hints, and gh rate-limit hints as ordered text", () => {
  70. expect(
  71. formatText(
  72. bashOutput({
  73. stdout: "\n\n hello\n\n",
  74. stderr: " warn\n",
  75. staleReadFileStateHint:
  76. "[This command modified 1 file you've previously read: a.ts. Call Read before editing.]",
  77. ghRateLimitHint: GH_RATE_LIMIT_HINT,
  78. }),
  79. ),
  80. ).toBe(
  81. [
  82. " hello",
  83. "warn",
  84. "[This command modified 1 file you've previously read: a.ts. Call Read before editing.]",
  85. GH_RATE_LIMIT_HINT,
  86. ].join("\n"),
  87. );
  88. });
  89. it("formats interrupted Bash results with the aborted error tag", () => {
  90. expect(
  91. formatText(
  92. bashOutput({
  93. stdout: "partial\n",
  94. stderr: "stderr\n",
  95. interrupted: true,
  96. status: "cancelled",
  97. }),
  98. ),
  99. ).toBe("partial\nstderr\n<error>Command was aborted before completion</error>");
  100. });
  101. it("keeps the zcode generic no-output placeholder for empty Bash output", async () => {
  102. const emptyBashContent = "(Bash completed with no output)";
  103. const result = await serializeOutput(
  104. minimalToolExecutorDeps(),
  105. bashOutput(),
  106. bashToolEntry,
  107. {},
  108. "tool_bash",
  109. new AbortController().signal,
  110. );
  111. expect(result.content).toBe(emptyBashContent);
  112. expect(result.modelContent).toBe(emptyBashContent);
  113. expect(result.originalBytes).toBe(0);
  114. expect(result.returnedBytes).toBe(Buffer.byteLength(emptyBashContent, "utf8"));
  115. });
  116. it("formats persisted foreground output with the 2KB preview envelope", () => {
  117. const preview = "a".repeat(1_200);
  118. const stdout = `${preview}\n${"b".repeat(1_200)}`;
  119. expect(
  120. formatText(
  121. bashOutput({
  122. stdout,
  123. persistedOutputPath: "/tmp/stdout.log",
  124. persistedOutputSize: 4_096,
  125. }),
  126. ),
  127. ).toBe(
  128. [
  129. "<persisted-output>",
  130. "Output too large (4KB). Full output saved to: /tmp/stdout.log",
  131. "",
  132. "Preview (first 2KB):",
  133. preview,
  134. "...",
  135. "</persisted-output>",
  136. ].join("\n"),
  137. );
  138. });
  139. it("uses Bash persisted-output projection when serializer persists a large Bash result", async () => {
  140. const stdout = "x".repeat(30_001);
  141. const artifactStore = new RecordingArtifactStore();
  142. const result = await serializeOutput(
  143. {
  144. ...minimalToolExecutorDeps(),
  145. artifactStore,
  146. },
  147. bashOutput({
  148. stdout,
  149. stdoutBytes: Buffer.byteLength(stdout, "utf8"),
  150. stderrBytes: 0,
  151. }),
  152. bashToolEntry,
  153. {},
  154. "tool_bash",
  155. new AbortController().signal,
  156. );
  157. expect(artifactStore.requests).toHaveLength(1);
  158. expect(result.content).toContain("<persisted-output>");
  159. expect(result.content).toContain(
  160. "Output too large (29.3KB). Full output saved to: /artifacts/artifact-1.json",
  161. );
  162. expect(result.content).toContain(`Preview (first 2KB):\n${"x".repeat(2_000)}`);
  163. expect(result.modelContent).toBe(result.content);
  164. });
  165. it("does not rehydrate oversized stderr after serializer persists a Bash result", async () => {
  166. const stderr = "E".repeat(30_001);
  167. const artifactStore = new RecordingArtifactStore();
  168. const result = await serializeOutput(
  169. {
  170. ...minimalToolExecutorDeps(),
  171. artifactStore,
  172. },
  173. bashOutput({
  174. stderr,
  175. stdoutBytes: 0,
  176. stderrBytes: Buffer.byteLength(stderr, "utf8"),
  177. }),
  178. bashToolEntry,
  179. {},
  180. "tool_bash",
  181. new AbortController().signal,
  182. );
  183. expect(artifactStore.requests).toHaveLength(1);
  184. expect(result.content).toContain(
  185. "Output too large (29.3KB). Full output saved to: /artifacts/artifact-1.json",
  186. );
  187. expect(result.content).toContain(`Preview (first 2KB):\n${"E".repeat(2_000)}`);
  188. expect(result.content.match(/E/g)).toHaveLength(2_000);
  189. expect(result.returnedBytes).toBeLessThan(2_200);
  190. expect(result.modelContent).toBe(result.content);
  191. });
  192. it("uses Bash persisted-output projection for failed oversized Bash results", async () => {
  193. const stdout = "O".repeat(30_001);
  194. const artifactStore = new RecordingArtifactStore();
  195. const result = await serializeOutput(
  196. {
  197. ...minimalToolExecutorDeps(),
  198. artifactStore,
  199. },
  200. bashOutput({
  201. exitCode: 2,
  202. status: "failed",
  203. stderr: "bad command",
  204. stdout,
  205. stdoutBytes: Buffer.byteLength(stdout, "utf8"),
  206. stderrBytes: Buffer.byteLength("bad command", "utf8"),
  207. }),
  208. bashToolEntry,
  209. {},
  210. "tool_bash",
  211. new AbortController().signal,
  212. );
  213. expect(artifactStore.requests).toHaveLength(1);
  214. expect(result.content).toContain(
  215. "Output too large (29.3KB). Full output saved to: /artifacts/artifact-1.json",
  216. );
  217. expect(result.content).toContain(`Preview (first 2KB):\nExit code 2\n${"O".repeat(1_988)}`);
  218. expect(result.modelContent).toBe(result.content);
  219. });
  220. it("does not rehydrate structuredContent after serializer persists a large Bash result", async () => {
  221. const largeStructuredText = "structured".repeat(10_000);
  222. const artifactStore = new RecordingArtifactStore();
  223. const result = await serializeOutput(
  224. {
  225. ...minimalToolExecutorDeps(),
  226. artifactStore,
  227. },
  228. bashOutput({
  229. structuredContent: [{ type: "text", text: largeStructuredText }],
  230. }),
  231. bashToolEntry,
  232. {},
  233. "tool_bash",
  234. new AbortController().signal,
  235. );
  236. expect(artifactStore.requests).toHaveLength(1);
  237. expect(result.content).toContain("<persisted-output>");
  238. expect(result.content).not.toContain(largeStructuredText);
  239. expect(result.modelContent).toBe(result.content);
  240. });
  241. it("formats background results with background wording and without persisted-output envelopes", () => {
  242. expect(
  243. formatText(
  244. bashOutput({
  245. status: "backgrounded",
  246. backgroundTaskId: "exec_bg",
  247. persistedOutputPath: "/tmp/exec_bg.output",
  248. }),
  249. ),
  250. ).toBe(
  251. "Command running in background with ID: exec_bg. Output is being written to: /tmp/exec_bg.output. You will be notified when it completes. To check interim output, use Read on that file path.",
  252. );
  253. expect(
  254. formatText(
  255. bashOutput({
  256. status: "backgrounded",
  257. backgroundTaskId: "exec_bg",
  258. backgroundedByUser: true,
  259. persistedOutputPath: "/tmp/exec_bg.output",
  260. }),
  261. ),
  262. ).toBe(
  263. "Command was manually backgrounded by user with ID: exec_bg. Output is being written to: /tmp/exec_bg.output",
  264. );
  265. expect(
  266. formatText(
  267. bashOutput({
  268. status: "backgrounded",
  269. backgroundTaskId: "exec_bg",
  270. assistantAutoBackgrounded: true,
  271. persistedOutputPath: "/tmp/exec_bg.output",
  272. }),
  273. ),
  274. ).toBe(
  275. "Command exceeded the assistant-mode blocking budget (15s) and was moved to the background with ID: exec_bg. It is still running \u2014 you will be notified when it completes. Output is being written to: /tmp/exec_bg.output. In assistant mode, delegate long-running work to a subagent or use run_in_background to keep this conversation responsive.",
  276. );
  277. });
  278. it("returns image content only for recognized data image output and falls back otherwise", () => {
  279. const dataUrl = `data:image/png;base64,${PNG_1X1_BASE64}`;
  280. expect(
  281. formatModelContent(
  282. bashOutput({
  283. stdout: dataUrl,
  284. isImage: true,
  285. }),
  286. ),
  287. ).toEqual([
  288. {
  289. type: "image",
  290. mediaType: "image/png",
  291. dataUrl,
  292. },
  293. ]);
  294. expect(
  295. formatText(
  296. bashOutput({
  297. stdout: "data:image/png;base64,not-base64-image",
  298. isImage: true,
  299. }),
  300. ),
  301. ).toBe("data:image/png;base64,not-base64-image");
  302. });
  303. it("does not add gh rate-limit hints to failed provider-error Bash output", async () => {
  304. const executionPort: ExecutionPort = {
  305. async run() {
  306. return executionResult({
  307. status: "failed",
  308. stderr: "API rate limit exceeded for user",
  309. });
  310. },
  311. };
  312. const output = (await bashHandler(
  313. { command: "gh pr view 123" } satisfies BashInput,
  314. contextWith(executionPort),
  315. )) as BashOutput;
  316. expect(output.ghRateLimitHint).toBeUndefined();
  317. expect(formatText(output)).not.toContain(GH_RATE_LIMIT_HINT);
  318. });
  319. it("adds the gh rate-limit hint from successful stdout", async () => {
  320. const executionPort: ExecutionPort = {
  321. async run() {
  322. return executionResult({
  323. status: "completed",
  324. stdout: "API rate limit exceeded for user",
  325. });
  326. },
  327. };
  328. const output = (await bashHandler(
  329. { command: "gh pr view 123" } satisfies BashInput,
  330. contextWith(executionPort),
  331. )) as BashOutput;
  332. expect(output.ghRateLimitHint).toBe(GH_RATE_LIMIT_HINT);
  333. expect(formatText(output)).toContain(GH_RATE_LIMIT_HINT);
  334. });
  335. });
  336. function formatModelContent(output: BashOutput): ModelMessageContent {
  337. const content = bashToolEntry.formatModelContent?.(output);
  338. expect(content).toBeDefined();
  339. return content as ModelMessageContent;
  340. }
  341. function formatText(output: BashOutput): string {
  342. const content = formatModelContent(output);
  343. expect(typeof content).toBe("string");
  344. return content as string;
  345. }
  346. function bashOutput(output: Partial<BashOutput> = {}): BashOutput {
  347. return {
  348. stdout: "",
  349. stderr: "",
  350. interrupted: false,
  351. status: "completed",
  352. ...output,
  353. };
  354. }
  355. function contextWith(executionPort: ExecutionPort): ToolExecutionContext {
  356. return {
  357. toolCallId: "tool_bash",
  358. traceId: "trace_bash",
  359. spanId: "span_bash",
  360. abortSignal: new AbortController().signal,
  361. executionPort,
  362. workingDirectory: "/tmp",
  363. workspaceRoot: "/tmp",
  364. sessionId: "sess_bash",
  365. turnId: "turn_bash",
  366. };
  367. }
  368. function executionResult(options: {
  369. status: ExecutionResult["status"];
  370. stdout?: string;
  371. stderr?: string;
  372. }): ExecutionResult {
  373. const now = new Date();
  374. return {
  375. status: options.status,
  376. stdout: {
  377. text: options.stdout ?? "",
  378. bytes: Buffer.byteLength(options.stdout ?? "", "utf8"),
  379. truncated: false,
  380. },
  381. stderr: {
  382. text: options.stderr ?? "",
  383. bytes: Buffer.byteLength(options.stderr ?? "", "utf8"),
  384. truncated: false,
  385. },
  386. durationMs: 1,
  387. timedOut: false,
  388. cancelled: false,
  389. startedAt: now,
  390. completedAt: now,
  391. };
  392. }
  393. function minimalToolExecutorDeps(): ToolExecutorDeps {
  394. return {
  395. defaultTimeoutMs: 300_000,
  396. emitEvent: async () => {},
  397. getMode: () => "build",
  398. getWorkingDirectory: () => "/tmp",
  399. getWorkspaceRoot: () => "/tmp",
  400. maxConcurrency: 1,
  401. permissionBroker: {} as ToolExecutorDeps["permissionBroker"],
  402. permissionService: {} as ToolExecutorDeps["permissionService"],
  403. readFileState: new Map(),
  404. registry: {} as ToolExecutorDeps["registry"],
  405. sessionId: "sess_bash" as ToolExecutorDeps["sessionId"],
  406. };
  407. }
  408. class RecordingArtifactStore implements ToolArtifactStorePort {
  409. readonly requests: ToolArtifactWriteRequest[] = [];
  410. async writeToolResultArtifact(request: ToolArtifactWriteRequest) {
  411. this.requests.push(request);
  412. return {
  413. id: "artifact-1",
  414. uri: "zcode-artifact://test/artifact-1",
  415. path: "/artifacts/artifact-1.json",
  416. bytes: Buffer.byteLength(request.content, "utf8"),
  417. contentType: request.contentType ?? "text/plain",
  418. createdAt: new Date(),
  419. };
  420. }
  421. async readToolResultArtifact(_request: ToolArtifactReadRequest): Promise<never> {
  422. throw new Error("readToolResultArtifact should not be called");
  423. }
  424. }