bash-result-mapping.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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("keeps the head and tail of large failed Bash output inline", async () => {
  193. const stdout = `${"H".repeat(6_000)}${"M".repeat(18_000)}${"T".repeat(6_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. // 失败命令不落盘:完整文本超过 1 万 + 1024 字符时,保留头尾各 5000 字符,中间写明截掉的字符数。
  214. const full = `Exit code 2\n${stdout}\nbad command`;
  215. expect(artifactStore.requests).toHaveLength(0);
  216. expect(result.content).toBe(
  217. `${full.slice(0, 5_000)}\n\n... [${full.length - 10_000} characters truncated] ...\n\n${full.slice(-5_000)}`,
  218. );
  219. expect(result.modelContent).toBe(result.content);
  220. });
  221. it.each([10_500, 20_000])(
  222. "keeps a failed Bash output of %i CJK characters inline instead of persisting it",
  223. async (length) => {
  224. const stdout = "错".repeat(length);
  225. const artifactStore = new RecordingArtifactStore();
  226. const result = await serializeOutput(
  227. { ...minimalToolExecutorDeps(), artifactStore },
  228. bashOutput({ exitCode: 1, status: "failed", stdout }),
  229. bashToolEntry,
  230. {},
  231. "tool_bash",
  232. new AbortController().signal,
  233. );
  234. // 失败正文已按字符保留头尾;多字节文本超过 30000 字节也不能再被落盘成 2KB 开头预览。
  235. const full = `Exit code 1\n${stdout}`;
  236. const expected =
  237. full.length <= 11_024
  238. ? full
  239. : `${full.slice(0, 5_000)}\n\n... [${full.length - 10_000} characters truncated] ...\n\n${full.slice(-5_000)}`;
  240. expect(Buffer.byteLength(expected, "utf8")).toBeGreaterThan(30_000);
  241. expect(artifactStore.requests).toHaveLength(0);
  242. expect(result.content).toBe(expected);
  243. expect(result.content).not.toContain("<persisted-output>");
  244. expect(result.truncated).toBe(false);
  245. expect(result.modelContent).toBe(result.content);
  246. },
  247. );
  248. it("still persists a successful CJK Bash output over the byte budget", async () => {
  249. const stdout = "错".repeat(10_500);
  250. const artifactStore = new RecordingArtifactStore();
  251. const result = await serializeOutput(
  252. { ...minimalToolExecutorDeps(), artifactStore },
  253. bashOutput({ stdout }),
  254. bashToolEntry,
  255. {},
  256. "tool_bash",
  257. new AbortController().signal,
  258. );
  259. expect(artifactStore.requests).toHaveLength(1);
  260. expect(result.content).toContain("<persisted-output>");
  261. });
  262. it("keeps the byte budget for a failed Bash result that returns structuredContent", async () => {
  263. const artifactStore = new RecordingArtifactStore();
  264. const result = await serializeOutput(
  265. { ...minimalToolExecutorDeps(), artifactStore },
  266. bashOutput({
  267. exitCode: 1,
  268. status: "failed",
  269. structuredContent: [{ type: "text", text: "structured".repeat(10_000) }],
  270. }),
  271. bashToolEntry,
  272. {},
  273. "tool_bash",
  274. new AbortController().signal,
  275. );
  276. // structuredContent 不经过失败正文的头尾截断,没有字符上限,仍按字节预算落盘。
  277. expect(artifactStore.requests).toHaveLength(1);
  278. expect(result.truncated).toBe(true);
  279. });
  280. it("shows failed Bash output in full up to the truncation slack", () => {
  281. const stdout = "x".repeat(11_000);
  282. expect(formatText(bashOutput({ exitCode: 1, status: "failed", stdout }))).toBe(
  283. `Exit code 1\n${stdout}`,
  284. );
  285. });
  286. it("uses the inline output of an adapter-persisted failure instead of the saved-file preview", () => {
  287. const stdout = "y".repeat(30_000);
  288. const text = formatText(
  289. bashOutput({
  290. exitCode: 1,
  291. status: "failed",
  292. stdout,
  293. persistedOutputPath: "/tmp/exec_fail.output",
  294. persistedOutputSize: 90_000,
  295. }),
  296. );
  297. expect(text).not.toContain("<persisted-output>");
  298. expect(text).toBe(
  299. `Exit code 1\n${"y".repeat(4_988)}\n\n... [20012 characters truncated] ...\n\n${"y".repeat(5_000)}`,
  300. );
  301. });
  302. it("names the timeout when a foreground command is moved to the background", () => {
  303. expect(
  304. formatText(
  305. bashOutput({
  306. status: "backgrounded",
  307. backgroundTaskId: "exec_bg",
  308. persistedOutputPath: "/tmp/exec_bg.output",
  309. timedOutAfterMs: 120_000,
  310. }),
  311. ),
  312. ).toBe(
  313. "Command did not complete within its 120s timeout and was moved to the background (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.",
  314. );
  315. });
  316. it("does not rehydrate structuredContent after serializer persists a large Bash result", async () => {
  317. const largeStructuredText = "structured".repeat(10_000);
  318. const artifactStore = new RecordingArtifactStore();
  319. const result = await serializeOutput(
  320. {
  321. ...minimalToolExecutorDeps(),
  322. artifactStore,
  323. },
  324. bashOutput({
  325. structuredContent: [{ type: "text", text: largeStructuredText }],
  326. }),
  327. bashToolEntry,
  328. {},
  329. "tool_bash",
  330. new AbortController().signal,
  331. );
  332. expect(artifactStore.requests).toHaveLength(1);
  333. expect(result.content).toContain("<persisted-output>");
  334. expect(result.content).not.toContain(largeStructuredText);
  335. expect(result.modelContent).toBe(result.content);
  336. });
  337. it("formats background results with background wording and without persisted-output envelopes", () => {
  338. expect(
  339. formatText(
  340. bashOutput({
  341. status: "backgrounded",
  342. backgroundTaskId: "exec_bg",
  343. persistedOutputPath: "/tmp/exec_bg.output",
  344. }),
  345. ),
  346. ).toBe(
  347. "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.",
  348. );
  349. expect(
  350. formatText(
  351. bashOutput({
  352. status: "backgrounded",
  353. backgroundTaskId: "exec_bg",
  354. backgroundedByUser: true,
  355. persistedOutputPath: "/tmp/exec_bg.output",
  356. }),
  357. ),
  358. ).toBe(
  359. "Command was manually backgrounded by user with ID: exec_bg. Output is being written to: /tmp/exec_bg.output",
  360. );
  361. expect(
  362. formatText(
  363. bashOutput({
  364. status: "backgrounded",
  365. backgroundTaskId: "exec_bg",
  366. assistantAutoBackgrounded: true,
  367. persistedOutputPath: "/tmp/exec_bg.output",
  368. }),
  369. ),
  370. ).toBe(
  371. "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.",
  372. );
  373. });
  374. it("returns image content only for recognized data image output and falls back otherwise", () => {
  375. const dataUrl = `data:image/png;base64,${PNG_1X1_BASE64}`;
  376. expect(
  377. formatModelContent(
  378. bashOutput({
  379. stdout: dataUrl,
  380. isImage: true,
  381. }),
  382. ),
  383. ).toEqual([
  384. {
  385. type: "image",
  386. mediaType: "image/png",
  387. dataUrl,
  388. },
  389. ]);
  390. expect(
  391. formatText(
  392. bashOutput({
  393. stdout: "data:image/png;base64,not-base64-image",
  394. isImage: true,
  395. }),
  396. ),
  397. ).toBe("data:image/png;base64,not-base64-image");
  398. });
  399. it("does not add gh rate-limit hints to failed provider-error Bash output", async () => {
  400. const executionPort: ExecutionPort = {
  401. async run() {
  402. return executionResult({
  403. status: "failed",
  404. stderr: "API rate limit exceeded for user",
  405. });
  406. },
  407. };
  408. const output = (await bashHandler(
  409. { command: "gh pr view 123" } satisfies BashInput,
  410. contextWith(executionPort),
  411. )) as BashOutput;
  412. expect(output.ghRateLimitHint).toBeUndefined();
  413. expect(formatText(output)).not.toContain(GH_RATE_LIMIT_HINT);
  414. });
  415. it("adds the gh rate-limit hint from successful stdout", async () => {
  416. const executionPort: ExecutionPort = {
  417. async run() {
  418. return executionResult({
  419. status: "completed",
  420. stdout: "API rate limit exceeded for user",
  421. });
  422. },
  423. };
  424. const output = (await bashHandler(
  425. { command: "gh pr view 123" } satisfies BashInput,
  426. contextWith(executionPort),
  427. )) as BashOutput;
  428. expect(output.ghRateLimitHint).toBe(GH_RATE_LIMIT_HINT);
  429. expect(formatText(output)).toContain(GH_RATE_LIMIT_HINT);
  430. });
  431. });
  432. function formatModelContent(output: BashOutput): ModelMessageContent {
  433. const content = bashToolEntry.formatModelContent?.(output);
  434. expect(content).toBeDefined();
  435. return content as ModelMessageContent;
  436. }
  437. function formatText(output: BashOutput): string {
  438. const content = formatModelContent(output);
  439. expect(typeof content).toBe("string");
  440. return content as string;
  441. }
  442. function bashOutput(output: Partial<BashOutput> = {}): BashOutput {
  443. return {
  444. stdout: "",
  445. stderr: "",
  446. interrupted: false,
  447. status: "completed",
  448. ...output,
  449. };
  450. }
  451. function contextWith(executionPort: ExecutionPort): ToolExecutionContext {
  452. return {
  453. toolCallId: "tool_bash",
  454. traceId: "trace_bash",
  455. spanId: "span_bash",
  456. abortSignal: new AbortController().signal,
  457. executionPort,
  458. workingDirectory: "/tmp",
  459. workspaceRoot: "/tmp",
  460. sessionId: "sess_bash",
  461. turnId: "turn_bash",
  462. };
  463. }
  464. function executionResult(options: {
  465. status: ExecutionResult["status"];
  466. stdout?: string;
  467. stderr?: string;
  468. }): ExecutionResult {
  469. const now = new Date();
  470. return {
  471. status: options.status,
  472. stdout: {
  473. text: options.stdout ?? "",
  474. bytes: Buffer.byteLength(options.stdout ?? "", "utf8"),
  475. truncated: false,
  476. },
  477. stderr: {
  478. text: options.stderr ?? "",
  479. bytes: Buffer.byteLength(options.stderr ?? "", "utf8"),
  480. truncated: false,
  481. },
  482. durationMs: 1,
  483. timedOut: false,
  484. cancelled: false,
  485. startedAt: now,
  486. completedAt: now,
  487. };
  488. }
  489. function minimalToolExecutorDeps(): ToolExecutorDeps {
  490. return {
  491. defaultTimeoutMs: 300_000,
  492. emitEvent: async () => {},
  493. getMode: () => "build",
  494. getWorkingDirectory: () => "/tmp",
  495. getWorkspaceRoot: () => "/tmp",
  496. maxConcurrency: 1,
  497. permissionBroker: {} as ToolExecutorDeps["permissionBroker"],
  498. permissionService: {} as ToolExecutorDeps["permissionService"],
  499. readFileState: new Map(),
  500. registry: {} as ToolExecutorDeps["registry"],
  501. sessionId: "sess_bash" as ToolExecutorDeps["sessionId"],
  502. };
  503. }
  504. class RecordingArtifactStore implements ToolArtifactStorePort {
  505. readonly requests: ToolArtifactWriteRequest[] = [];
  506. async writeToolResultArtifact(request: ToolArtifactWriteRequest) {
  507. this.requests.push(request);
  508. return {
  509. id: "artifact-1",
  510. uri: "zcode-artifact://test/artifact-1",
  511. path: "/artifacts/artifact-1.json",
  512. bytes: Buffer.byteLength(request.content, "utf8"),
  513. contentType: request.contentType ?? "text/plain",
  514. createdAt: new Date(),
  515. };
  516. }
  517. async readToolResultArtifact(_request: ToolArtifactReadRequest): Promise<never> {
  518. throw new Error("readToolResultArtifact should not be called");
  519. }
  520. }