bash-handler.test.ts 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788
  1. import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { CoreErrorType, SessionEventType, createImageProcessorError } from "@zcode/contracts";
  6. import { isErrorForToolResult } from "../src/runtime/helpers/tool-result.js";
  7. import { decideBashCwdPolicy } from "../src/tool/handlers/bash-cwd-policy.js";
  8. import { bashHandler, bashToolEntry, createBashToolEntry } from "../src/tool/handlers/bash.js";
  9. import type { BashBackgroundLifecycleExecutionPort } from "../src/tool/handlers/bash-background-lifecycle.js";
  10. import { resolveTimeoutMs } from "../src/tool/executor/timeout.js";
  11. import type {
  12. BashInput,
  13. BashOutput,
  14. CommandExecutionSpanWriter,
  15. ExecutionPort,
  16. ExecutionRequest,
  17. ExecutionResult,
  18. FileSystemPort,
  19. FileSystemReadTextResult,
  20. FileSystemStatResult,
  21. ImageProcessorPort,
  22. ExecutionShellSelection,
  23. SessionEvent,
  24. ToolExecutionSpanWriter,
  25. } from "@zcode/contracts";
  26. import { createReadFileStateKey } from "../src/tool/read-file-state.js";
  27. import type { ReadFileStateMap, ToolExecutionContext } from "../src/tool/types.js";
  28. const workspaceRoot = resolve("/work");
  29. const projectRoot = resolve(workspaceRoot, "project");
  30. const defaultCommandRoot = resolve("/tmp");
  31. describe("Bash cwd policy", () => {
  32. it("keeps cwd when resolved cwd stays inside workspace", () => {
  33. expect(
  34. decideBashCwdPolicy({
  35. status: "completed",
  36. exitCode: 0,
  37. resolvedCwd: "/repo/subdir",
  38. workspaceRoot: "/repo",
  39. runtimeScope: "main",
  40. }),
  41. ).toEqual({ nextWorkingDirectory: "/repo/subdir" });
  42. });
  43. it("resets cwd and returns provider-visible stderr suffix when resolved cwd leaves workspace", () => {
  44. expect(
  45. decideBashCwdPolicy({
  46. status: "completed",
  47. exitCode: 0,
  48. resolvedCwd: "/tmp/outside",
  49. workspaceRoot: "/repo",
  50. runtimeScope: "main",
  51. }),
  52. ).toEqual({
  53. nextWorkingDirectory: "/repo",
  54. stderrSuffix: "Shell cwd was reset to /repo",
  55. });
  56. });
  57. it("does not update cwd for subagent scope", () => {
  58. expect(
  59. decideBashCwdPolicy({
  60. status: "completed",
  61. exitCode: 0,
  62. resolvedCwd: "/tmp/outside",
  63. workspaceRoot: "/repo",
  64. runtimeScope: "subagent",
  65. }),
  66. ).toEqual({});
  67. });
  68. it("treats macOS /private/tmp aliases as the same cwd boundary", () => {
  69. expect(
  70. decideBashCwdPolicy({
  71. status: "completed",
  72. exitCode: 0,
  73. resolvedCwd: "/private/tmp/repo/subdir",
  74. workspaceRoot: "/tmp/repo",
  75. runtimeScope: "main",
  76. }),
  77. ).toEqual({ nextWorkingDirectory: "/tmp/repo/subdir" });
  78. });
  79. it.skipIf(process.platform === "win32")(
  80. "keeps cwd when a symlink workspace resolves to a physical child path",
  81. async () => {
  82. const root = await mkdtemp(join(tmpdir(), "zcode-bash-cwd-policy-"));
  83. const realRoot = join(root, "real-project");
  84. const linkRoot = join(root, "project-link");
  85. const realChild = join(realRoot, "child");
  86. await mkdir(realChild, { recursive: true });
  87. await symlink(realRoot, linkRoot, "dir");
  88. try {
  89. const physicalChild = await realpath(realChild);
  90. // 测试基建修复:Turbo 的严格环境可能让 tmpdir() 回落到 /tmp,而 macOS realpath
  91. // 会返回 /private/tmp;断言必须与生产 cwd policy 使用同一组系统路径别名。
  92. const normalizedPhysicalChild = physicalChild
  93. .replace(/^\/private\/var\//, "/var/")
  94. .replace(/^\/private\/tmp(\/|$)/, "/tmp$1");
  95. expect(
  96. decideBashCwdPolicy({
  97. status: "completed",
  98. exitCode: 0,
  99. resolvedCwd: physicalChild,
  100. workspaceRoot: linkRoot,
  101. runtimeScope: "main",
  102. }),
  103. ).toEqual({ nextWorkingDirectory: normalizedPhysicalChild });
  104. } finally {
  105. await rm(root, { recursive: true, force: true });
  106. }
  107. },
  108. );
  109. it("handles Windows path containment case-insensitively", () => {
  110. expect(
  111. decideBashCwdPolicy({
  112. status: "completed",
  113. exitCode: 0,
  114. resolvedCwd: "C:\\Repo\\Subdir",
  115. workspaceRoot: "c:\\repo",
  116. platform: "win32",
  117. runtimeScope: "main",
  118. }),
  119. ).toEqual({ nextWorkingDirectory: "C:\\Repo\\Subdir" });
  120. });
  121. it("reuses shared Windows tool path normalization for Git Bash cwd aliases", () => {
  122. expect(
  123. decideBashCwdPolicy({
  124. status: "completed",
  125. exitCode: 0,
  126. resolvedCwd: "/c/Repo/Subdir",
  127. workspaceRoot: "C:\\Repo",
  128. platform: "win32",
  129. runtimeScope: "main",
  130. }),
  131. ).toEqual({ nextWorkingDirectory: "C:\\Repo\\Subdir" });
  132. });
  133. it("reuses shared Windows tool path normalization for extended drive paths", () => {
  134. expect(
  135. decideBashCwdPolicy({
  136. status: "completed",
  137. exitCode: 0,
  138. resolvedCwd: "\\\\?\\c:\\Repo\\Subdir",
  139. workspaceRoot: "C:\\Repo",
  140. platform: "win32",
  141. runtimeScope: "main",
  142. }),
  143. ).toEqual({ nextWorkingDirectory: "C:\\Repo\\Subdir" });
  144. });
  145. it.skipIf(process.platform === "win32")(
  146. "does not infer Windows cwd semantics from POSIX /c paths",
  147. () => {
  148. expect(
  149. decideBashCwdPolicy({
  150. status: "completed",
  151. exitCode: 0,
  152. resolvedCwd: "/c/repo/subdir",
  153. workspaceRoot: "/c/repo",
  154. platform: "linux",
  155. runtimeScope: "main",
  156. }),
  157. ).toEqual({ nextWorkingDirectory: "/c/repo/subdir" });
  158. },
  159. );
  160. it.skipIf(process.platform === "win32")(
  161. "honors explicit POSIX cwd semantics for Windows-looking path strings",
  162. () => {
  163. expect(
  164. decideBashCwdPolicy({
  165. status: "completed",
  166. exitCode: 0,
  167. resolvedCwd: "C:\\Repo\\Subdir",
  168. workspaceRoot: "c:\\repo",
  169. platform: "linux",
  170. runtimeScope: "main",
  171. }),
  172. ).toEqual({
  173. nextWorkingDirectory: "c:\\repo",
  174. stderrSuffix: "Shell cwd was reset to c:\\repo",
  175. });
  176. },
  177. );
  178. it("keeps cwd for workspace child directories whose names start with dot-dot", () => {
  179. expect(
  180. decideBashCwdPolicy({
  181. status: "completed",
  182. exitCode: 0,
  183. resolvedCwd: "/repo/..cache",
  184. workspaceRoot: "/repo",
  185. runtimeScope: "main",
  186. }),
  187. ).toEqual({ nextWorkingDirectory: "/repo/..cache" });
  188. expect(
  189. decideBashCwdPolicy({
  190. status: "completed",
  191. exitCode: 0,
  192. resolvedCwd: "C:\\Repo\\..cache",
  193. workspaceRoot: "c:\\repo",
  194. platform: "win32",
  195. runtimeScope: "main",
  196. }),
  197. ).toEqual({ nextWorkingDirectory: "C:\\Repo\\..cache" });
  198. });
  199. });
  200. describe("bashHandler", () => {
  201. it("把非零退出码保留为事实,只有结构化执行错误才标记 Command 失败", async () => {
  202. const outcomes: string[] = [];
  203. const telemetry = recordingBashTelemetry(outcomes);
  204. const nonZeroPort: ExecutionPort = {
  205. async run() {
  206. return executionResult({ status: "failed", exitCode: 1 });
  207. },
  208. };
  209. await bashHandler(
  210. { command: "grep missing file.txt" },
  211. contextWith(nonZeroPort, { telemetry }),
  212. );
  213. expect(outcomes).toEqual(["exit:1", "completed"]);
  214. outcomes.length = 0;
  215. const spawnErrorPort: ExecutionPort = {
  216. async run() {
  217. return executionResult({
  218. status: "spawn_error",
  219. error: { message: "spawn failed", type: "spawn_error" },
  220. });
  221. },
  222. };
  223. await bashHandler({ command: "missing-command" }, contextWith(spawnErrorPort, { telemetry }));
  224. expect(outcomes).toEqual(["failed:spawn"]);
  225. });
  226. it.each([
  227. "sqlite3 /Users/test/.zcode/v2/tasks-index.sqlite .tables",
  228. "cd ~/.zcode/v2 && sqlite3 tasks-index.sqlite .tables",
  229. 'db=~/.zcode/v2/tasks-index.sqlite; sqlite3 "$db" .tables',
  230. ])(
  231. "does not present shell text matching as a task database security boundary: %s",
  232. async (command) => {
  233. let capturedRequest: ExecutionRequest | undefined;
  234. const executionPort: ExecutionPort = {
  235. async run(request) {
  236. capturedRequest = request;
  237. return executionResult({
  238. status: "completed",
  239. exitCode: 0,
  240. });
  241. },
  242. };
  243. await bashHandler({ command }, contextWith(executionPort));
  244. expect(capturedRequest?.command).toEqual({
  245. mode: "shell",
  246. command,
  247. shellProfile: "posix-bash",
  248. });
  249. expect(capturedRequest?.sandbox).not.toHaveProperty("protectedResources");
  250. },
  251. );
  252. it("delegates shell command, timeout, session cwd, and sandbox fields to ExecutionPort", async () => {
  253. let capturedRequest: ExecutionRequest | undefined;
  254. const executionPort: ExecutionPort = {
  255. async run(request) {
  256. capturedRequest = request;
  257. return executionResult({
  258. status: "failed",
  259. exitCode: 2,
  260. stderr: "nope",
  261. });
  262. },
  263. };
  264. const output = (await bashHandler(
  265. {
  266. command: "npm test",
  267. timeout: 123,
  268. dangerouslyDisableSandbox: true,
  269. } satisfies BashInput,
  270. contextWith(executionPort, {
  271. workingDirectory: projectRoot,
  272. workspaceRoot: projectRoot,
  273. }),
  274. )) as BashOutput;
  275. expect(output).toMatchObject({
  276. exitCode: 2,
  277. status: "failed",
  278. stderr: "nope",
  279. });
  280. expect(bashToolEntry.formatModelContent?.(output)).toBe("Exit code 2\nnope");
  281. expect(
  282. isErrorForToolResult({
  283. completedAt: new Date(),
  284. durationMs: 1,
  285. output,
  286. startedAt: new Date(),
  287. success: true,
  288. toolCallId: "toolu_bash",
  289. toolName: "Bash",
  290. }),
  291. ).toBe(true);
  292. expect(capturedRequest?.command).toEqual({
  293. mode: "shell",
  294. command: "npm test",
  295. shellProfile: "posix-bash",
  296. });
  297. expect(capturedRequest?.cwd).toBe(projectRoot);
  298. expect(capturedRequest?.env).toBeUndefined();
  299. expect(capturedRequest?.timeoutMs).toBe(123);
  300. expect(capturedRequest?.outputLimit).toEqual({
  301. maxInlineBytes: 30_000,
  302. maxBufferBytes: 30_000,
  303. maxPersistedBytes: 5 * 1024 * 1024 * 1024,
  304. persistOutput: "on_truncate",
  305. });
  306. expect(capturedRequest?.sandbox).toMatchObject({
  307. enabled: false,
  308. dangerouslyDisableSandbox: true,
  309. });
  310. expect(capturedRequest?.sandbox).not.toHaveProperty("protectedResources");
  311. });
  312. it("keeps the filesystem output-loss diagnostic in provider-visible stdout", async () => {
  313. const diagnostic =
  314. "Command output was lost: the temp filesystem at /tmp/tasks is full (9MB free). The child process's stdout/stderr writes failed with ENOSPC. Free up space on this filesystem.";
  315. const executionPort: ExecutionPort = {
  316. async run() {
  317. return executionResult({
  318. status: "failed",
  319. exitCode: 7,
  320. stdout: diagnostic,
  321. });
  322. },
  323. };
  324. const output = (await bashHandler(
  325. {
  326. command: "failing-command",
  327. } satisfies BashInput,
  328. contextWith(executionPort),
  329. )) as BashOutput;
  330. expect(output.stdout).toBe(diagnostic);
  331. expect(output.stderr).toBe("");
  332. expect(bashToolEntry.formatModelContent?.(output)).toBe(`Exit code 7\n${diagnostic}`);
  333. });
  334. it("does not attach a no-op Bash startup script by default", async () => {
  335. const executionRequests: ExecutionRequest[] = [];
  336. const executionPort: ExecutionPort = {
  337. async run(request) {
  338. executionRequests.push(request);
  339. return executionResult({
  340. status: "completed",
  341. exitCode: 0,
  342. stdout: "ok\n",
  343. });
  344. },
  345. };
  346. await bashHandler({ command: "echo ok" }, contextWith(executionPort));
  347. expect(executionRequests).toHaveLength(1);
  348. expect(
  349. (executionRequests[0] as Record<string, unknown> | undefined)?.bashStartup,
  350. ).toBeUndefined();
  351. expect(executionRequests[0]?.bashPrelude).toBeUndefined();
  352. });
  353. it("adds sanitized Bash performance attribution to structured output", async () => {
  354. const executionPort: ExecutionPort = {
  355. async run(_request, options) {
  356. await options?.onEvent?.({
  357. type: "progress",
  358. timestamp: new Date(),
  359. elapsedMs: 42,
  360. stdoutBytes: 5,
  361. stderrBytes: 0,
  362. stdoutTail: "hello",
  363. stderrTail: "",
  364. });
  365. return {
  366. ...executionResult({
  367. status: "completed",
  368. exitCode: 0,
  369. stdout: "hello",
  370. }),
  371. durationMs: 1234,
  372. };
  373. },
  374. };
  375. const output = (await bashHandler(
  376. { command: "npm test -- --runInBand" },
  377. contextWith(executionPort),
  378. )) as BashOutput;
  379. expect(output).toMatchObject({
  380. stdout: "hello",
  381. perf: {
  382. detail: {
  383. kind: "command",
  384. command: {
  385. runMs: 1234,
  386. firstOutputMs: 42,
  387. noOutputMs: 42,
  388. exitCode: 0,
  389. timedOut: false,
  390. outputBytes: 5,
  391. category: "test",
  392. count: 1,
  393. name: "npm",
  394. status: "completed",
  395. },
  396. },
  397. },
  398. });
  399. expect((output as any).perf.detail.command.hash).toMatch(/^[a-f0-9]{16}$/u);
  400. expect(JSON.stringify((output as any).perf)).not.toContain("npm test");
  401. });
  402. it("accepts semantic timeout and boolean values from model input", async () => {
  403. let capturedRequest: ExecutionRequest | undefined;
  404. const executionPort: ExecutionPort = {
  405. async run(request) {
  406. capturedRequest = request;
  407. return executionResult({ status: "completed" });
  408. },
  409. };
  410. await bashHandler(
  411. {
  412. command: "npm test",
  413. timeout: "123",
  414. run_in_background: "false",
  415. dangerouslyDisableSandbox: "1",
  416. },
  417. contextWith(executionPort),
  418. );
  419. expect(capturedRequest?.timeoutMs).toBe(123);
  420. expect(capturedRequest?.sandbox).toMatchObject({
  421. enabled: false,
  422. dangerouslyDisableSandbox: true,
  423. });
  424. });
  425. it("updates session cwd from successful foreground Bash execution", async () => {
  426. const nextCwd = resolve(projectRoot, "nested");
  427. let observedCwd: string | undefined;
  428. let capturedRequest: ExecutionRequest | undefined;
  429. const executionPort: ExecutionPort = {
  430. async run(request) {
  431. capturedRequest = request;
  432. return executionResult({
  433. status: "completed",
  434. exitCode: 0,
  435. resolvedCwd: nextCwd,
  436. stdout: "ok\n",
  437. });
  438. },
  439. };
  440. const output = (await bashHandler(
  441. { command: `cd ${nextCwd} && echo ok` } satisfies BashInput,
  442. contextWith(executionPort, {
  443. workingDirectory: projectRoot,
  444. workspaceRoot: projectRoot,
  445. setWorkingDirectory: (cwd) => {
  446. observedCwd = cwd;
  447. },
  448. }),
  449. )) as BashOutput;
  450. expect(capturedRequest?.captureCwdAfterSuccess).toBe(true);
  451. expect(capturedRequest?.command).toMatchObject({
  452. mode: "shell",
  453. shellProfile: "posix-bash",
  454. });
  455. expect(observedCwd).toBe(nextCwd);
  456. expect(bashToolEntry.formatModelContent?.(output)).toBe("ok");
  457. });
  458. it("keeps cwd persistence independent from read-only Bash inspection classification", async () => {
  459. const nextCwd = resolve(projectRoot, "nested");
  460. let observedCwd: string | undefined;
  461. const executionPort: ExecutionPort = {
  462. async run() {
  463. return executionResult({
  464. status: "completed",
  465. exitCode: 0,
  466. resolvedCwd: nextCwd,
  467. stdout: "src/index.ts:1:foo\n",
  468. });
  469. },
  470. };
  471. const output = (await bashHandler(
  472. { command: `cd ${nextCwd} && grep -R -n foo src` } satisfies BashInput,
  473. contextWith(executionPort, {
  474. workingDirectory: projectRoot,
  475. workspaceRoot: projectRoot,
  476. setWorkingDirectory: (cwd) => {
  477. observedCwd = cwd;
  478. },
  479. }),
  480. )) as BashOutput;
  481. expect(observedCwd).toBe(nextCwd);
  482. expect(output.stderr).toBe("");
  483. expect(bashToolEntry.formatModelContent?.(output)).toBe("src/index.ts:1:foo");
  484. });
  485. it("resets main Bash cwd to workspace root and exposes the cwd reset stderr when final cwd leaves workspace", async () => {
  486. const outsideCwd = resolve("/tmp/zcode-outside");
  487. let observedCwd: string | undefined;
  488. const executionPort: ExecutionPort = {
  489. async run() {
  490. return executionResult({
  491. status: "completed",
  492. exitCode: 0,
  493. resolvedCwd: outsideCwd,
  494. stdout: "done\n",
  495. });
  496. },
  497. };
  498. const output = (await bashHandler(
  499. { command: "cd /tmp/zcode-outside && echo done" } satisfies BashInput,
  500. contextWith(executionPort, {
  501. workingDirectory: projectRoot,
  502. workspaceRoot: projectRoot,
  503. setWorkingDirectory: (cwd) => {
  504. observedCwd = cwd;
  505. },
  506. }),
  507. )) as BashOutput;
  508. expect(observedCwd).toBe(projectRoot);
  509. expect(output.stderr).toBe(`Shell cwd was reset to ${projectRoot}`);
  510. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  511. `done\nShell cwd was reset to ${projectRoot}`,
  512. );
  513. expect(JSON.stringify(output)).not.toContain("resolvedCwd");
  514. expect(JSON.stringify(output)).not.toContain(outsideCwd);
  515. });
  516. it("preserves existing stderr content when appending cwd reset stderr", async () => {
  517. const outsideCwd = resolve("/tmp/zcode-stderr-outside");
  518. const executionPort: ExecutionPort = {
  519. async run() {
  520. return executionResult({
  521. status: "completed",
  522. exitCode: 0,
  523. resolvedCwd: outsideCwd,
  524. stdout: "done\n",
  525. stderr: " warning detail \n\n",
  526. });
  527. },
  528. };
  529. const output = (await bashHandler(
  530. {
  531. command: "cd /tmp/zcode-stderr-outside && echo done",
  532. } satisfies BashInput,
  533. contextWith(executionPort, {
  534. workingDirectory: projectRoot,
  535. workspaceRoot: projectRoot,
  536. }),
  537. )) as BashOutput;
  538. expect(output.stderr).toBe(` warning detail \nShell cwd was reset to ${projectRoot}`);
  539. });
  540. it("does not leave stray carriage returns when appending cwd reset stderr", async () => {
  541. const outsideCwd = resolve("/tmp/zcode-crlf-stderr-outside");
  542. const executionPort: ExecutionPort = {
  543. async run() {
  544. return executionResult({
  545. status: "completed",
  546. exitCode: 0,
  547. resolvedCwd: outsideCwd,
  548. stdout: "done\n",
  549. stderr: "warning detail\r\n\r\n",
  550. });
  551. },
  552. };
  553. const output = (await bashHandler(
  554. {
  555. command: "cd /tmp/zcode-crlf-stderr-outside && echo done",
  556. } satisfies BashInput,
  557. contextWith(executionPort, {
  558. workingDirectory: projectRoot,
  559. workspaceRoot: projectRoot,
  560. }),
  561. )) as BashOutput;
  562. expect(output.stderr).toBe(`warning detail\nShell cwd was reset to ${projectRoot}`);
  563. });
  564. it("keeps cwd reset stderr even when project cwd env is present", async () => {
  565. const previousEnv = process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR;
  566. process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
  567. const outsideCwd = resolve("/tmp/zcode-env-outside");
  568. let observedCwd: string | undefined;
  569. const executionPort: ExecutionPort = {
  570. async run() {
  571. return executionResult({
  572. status: "completed",
  573. exitCode: 0,
  574. resolvedCwd: outsideCwd,
  575. stdout: "done\n",
  576. });
  577. },
  578. };
  579. try {
  580. const output = (await bashHandler(
  581. {
  582. command: "cd /tmp/zcode-env-outside && echo done",
  583. } satisfies BashInput,
  584. contextWith(executionPort, {
  585. workingDirectory: projectRoot,
  586. workspaceRoot: projectRoot,
  587. setWorkingDirectory: (cwd) => {
  588. observedCwd = cwd;
  589. },
  590. }),
  591. )) as BashOutput;
  592. expect(observedCwd).toBe(projectRoot);
  593. expect(output.stderr).toBe(`Shell cwd was reset to ${projectRoot}`);
  594. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  595. `done\nShell cwd was reset to ${projectRoot}`,
  596. );
  597. } finally {
  598. if (previousEnv === undefined) {
  599. delete process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR;
  600. } else {
  601. process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = previousEnv;
  602. }
  603. }
  604. });
  605. it("does not reset or expose cwd reminder for subagent Bash scope", async () => {
  606. let observedCwd: string | undefined;
  607. const executionPort: ExecutionPort = {
  608. async run() {
  609. return executionResult({
  610. status: "completed",
  611. exitCode: 0,
  612. resolvedCwd: "/tmp/subagent-outside",
  613. stdout: "child\n",
  614. });
  615. },
  616. };
  617. const output = (await bashHandler(
  618. { command: "cd /tmp/subagent-outside && echo child" } satisfies BashInput,
  619. contextWith(executionPort, {
  620. runtimeScope: "subagent",
  621. setWorkingDirectory: (cwd) => {
  622. observedCwd = cwd;
  623. },
  624. }),
  625. )) as BashOutput;
  626. expect(observedCwd).toBeUndefined();
  627. expect(output.stderr).toBe("");
  628. expect(bashToolEntry.formatModelContent?.(output)).toBe("child");
  629. });
  630. it("does not capture or update cwd for background Bash execution", async () => {
  631. let observedCwd: string | undefined;
  632. let capturedRequest: ExecutionRequest | undefined;
  633. const executionPort: BashBackgroundLifecycleExecutionPort = {
  634. async run() {
  635. throw new Error("run should not be used for background execution");
  636. },
  637. async runBashWithBackgroundLifecycle(request) {
  638. capturedRequest = request;
  639. return {
  640. kind: "backgrounded",
  641. task: {
  642. taskId: "exec_bg",
  643. status: "running",
  644. startedAt: new Date(),
  645. },
  646. };
  647. },
  648. };
  649. await bashHandler(
  650. { command: "cd /tmp", run_in_background: true } satisfies BashInput,
  651. contextWith(executionPort, {
  652. setWorkingDirectory: (cwd) => {
  653. observedCwd = cwd;
  654. },
  655. }),
  656. );
  657. expect(capturedRequest?.captureCwdAfterSuccess).toBeUndefined();
  658. expect(capturedRequest?.command).toMatchObject({
  659. mode: "shell",
  660. shellProfile: "posix-bash",
  661. });
  662. expect(observedCwd).toBeUndefined();
  663. });
  664. it.each([
  665. [
  666. "failed",
  667. executionResult({
  668. status: "failed",
  669. exitCode: 1,
  670. resolvedCwd: "/tmp/ignored",
  671. }),
  672. ],
  673. [
  674. "timed_out",
  675. executionResult({
  676. status: "timed_out",
  677. timedOut: true,
  678. resolvedCwd: "/tmp/ignored",
  679. }),
  680. ],
  681. ])("does not update cwd for %s Bash results", async (_name, result) => {
  682. let observedCwd: string | undefined;
  683. const executionPort: ExecutionPort = {
  684. async run() {
  685. return result;
  686. },
  687. };
  688. const output = (await bashHandler(
  689. { command: "cd /tmp && false" } satisfies BashInput,
  690. contextWith(executionPort, {
  691. setWorkingDirectory: (cwd) => {
  692. observedCwd = cwd;
  693. },
  694. }),
  695. )) as BashOutput;
  696. expect(observedCwd).toBeUndefined();
  697. expect(bashToolEntry.formatModelContent?.(output)).not.toContain("Shell cwd was reset");
  698. });
  699. it.each([
  700. ["rg missing .", "No matches found", false],
  701. ["find . -name missing", "Some directories were inaccessible", false],
  702. ["printf x | grep y", "No matches found", false],
  703. ["rg missing .; test -f missing", "Condition is false", false],
  704. ["rg missing . || test -f missing", "Condition is false", false],
  705. ["rg missing . && test -f missing", "Condition is false", false],
  706. ["true && rg missing .", "No matches found", false],
  707. ["git grep missing", "No matches found", false],
  708. ["git -C . diff --exit-code", "Files differ", false],
  709. ["rg missing .; exit 1", "Command exited with code 1", true],
  710. ])(
  711. "interprets %s exit 1 from status-bearing command",
  712. async (command, interpretation, expectedIsError) => {
  713. const executionPort: ExecutionPort = {
  714. async run() {
  715. return executionResult({
  716. status: "failed",
  717. exitCode: 1,
  718. });
  719. },
  720. };
  721. const output = (await bashHandler(
  722. { command } satisfies BashInput,
  723. contextWith(executionPort),
  724. )) as BashOutput;
  725. expect(output.returnCodeInterpretation).toBe(interpretation);
  726. expect(
  727. isErrorForToolResult({
  728. completedAt: new Date(),
  729. durationMs: 1,
  730. output,
  731. startedAt: new Date(),
  732. success: true,
  733. toolCallId: "call_bash",
  734. toolName: "Bash",
  735. }),
  736. ).toBe(expectedIsError);
  737. },
  738. );
  739. it("keeps raw command output on BashOutput and trims only provider-visible content", async () => {
  740. const executionPort: ExecutionPort = {
  741. async run() {
  742. return executionResult({
  743. status: "completed",
  744. stderr: "\nwarn\n",
  745. stdout: "\nalpha\n\n",
  746. });
  747. },
  748. };
  749. const output = (await bashHandler(
  750. {
  751. command: "printf '\\nalpha\\n\\n'",
  752. } satisfies BashInput,
  753. contextWith(executionPort),
  754. )) as BashOutput;
  755. expect(output.stdout).toBe("\nalpha\n\n");
  756. expect(output.stderr).toBe("\nwarn\n");
  757. expect(bashToolEntry.formatModelContent?.(output)).toBe("alpha\nwarn");
  758. });
  759. it("does not add cwd reset text without observing an actual shell cwd change", async () => {
  760. const executionPort: ExecutionPort = {
  761. async run() {
  762. return executionResult({
  763. exitCode: 1,
  764. status: "failed",
  765. stderr: "cd: no such file or directory",
  766. });
  767. },
  768. };
  769. const output = (await bashHandler(
  770. {
  771. command: "cd /missing-zcode-path && pwd",
  772. } satisfies BashInput,
  773. contextWith(executionPort, {
  774. workingDirectory: projectRoot,
  775. workspaceRoot: projectRoot,
  776. }),
  777. )) as BashOutput;
  778. expect(output.stderr).toBe("cd: no such file or directory");
  779. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  780. "Exit code 1\ncd: no such file or directory",
  781. );
  782. });
  783. it("marks valid image data URI stdout as image output for provider-visible content", async () => {
  784. const tinyPng =
  785. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  786. const executionPort: ExecutionPort = {
  787. async run() {
  788. return executionResult({
  789. status: "completed",
  790. stdout: tinyPng,
  791. });
  792. },
  793. };
  794. const output = (await bashHandler(
  795. {
  796. command: "printf image",
  797. } satisfies BashInput,
  798. contextWith(executionPort),
  799. )) as BashOutput;
  800. expect(output.isImage).toBe(true);
  801. expect(output.stdout).toBe(tinyPng);
  802. expect(bashToolEntry.formatModelContent?.(output)).toEqual([
  803. {
  804. type: "image",
  805. mediaType: "image/png",
  806. dataUrl: tinyPng,
  807. },
  808. ]);
  809. });
  810. it("resizes image data URI stdout through ImageProcessorPort when configured", async () => {
  811. const tinyPng =
  812. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  813. let capturedResizeRequest: Parameters<ImageProcessorPort["resizeToFit"]>[0] | undefined;
  814. const imageProcessorPort: ImageProcessorPort = {
  815. async resizeToFit(request) {
  816. capturedResizeRequest = request;
  817. return {
  818. data: Buffer.from("resized-image"),
  819. mediaType: "image/jpeg",
  820. resized: true,
  821. };
  822. },
  823. async prepareForModel() {
  824. throw new Error("prepareForModel should not be called");
  825. },
  826. };
  827. const executionPort: ExecutionPort = {
  828. async run() {
  829. return executionResult({
  830. status: "completed",
  831. stdout: tinyPng,
  832. });
  833. },
  834. };
  835. const output = (await bashHandler(
  836. {
  837. command: "printf image",
  838. } satisfies BashInput,
  839. contextWith(executionPort, { imageProcessorPort }),
  840. )) as BashOutput;
  841. expect(output.isImage).toBe(true);
  842. expect(output.stdout).toBe("data:image/jpeg;base64,cmVzaXplZC1pbWFnZQ==");
  843. expect(capturedResizeRequest?.maxDimension).toBe(2000);
  844. expect(capturedResizeRequest?.mediaType).toBe("image/png");
  845. expect(Buffer.from(capturedResizeRequest?.data ?? []).byteLength).toBeGreaterThan(0);
  846. });
  847. it("keeps valid image stdout as image output when optional resize fails", async () => {
  848. const grayAlphaPng =
  849. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
  850. const imageProcessorPort: ImageProcessorPort = {
  851. async resizeToFit() {
  852. throw new Error("decoder did not handle this valid png");
  853. },
  854. async prepareForModel() {
  855. throw new Error("prepareForModel should not be called");
  856. },
  857. };
  858. const executionPort: ExecutionPort = {
  859. async run() {
  860. return executionResult({
  861. status: "completed",
  862. stdout: grayAlphaPng,
  863. });
  864. },
  865. };
  866. const output = (await bashHandler(
  867. {
  868. command: "printf image",
  869. } satisfies BashInput,
  870. contextWith(executionPort, { imageProcessorPort }),
  871. )) as BashOutput;
  872. expect(output.isImage).toBe(true);
  873. expect(output.stdout).toBe(grayAlphaPng);
  874. expect(bashToolEntry.formatModelContent?.(output)).toEqual([
  875. {
  876. type: "image",
  877. mediaType: "image/png",
  878. dataUrl: grayAlphaPng,
  879. },
  880. ]);
  881. });
  882. it("falls back to text when image resize fails because the image is too large", async () => {
  883. const grayAlphaPng =
  884. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
  885. const imageProcessorPort: ImageProcessorPort = {
  886. async resizeToFit() {
  887. throw createImageProcessorError({
  888. code: "too_large",
  889. message: "Unable to fit image in provider budget",
  890. });
  891. },
  892. async prepareForModel() {
  893. throw new Error("prepareForModel should not be called");
  894. },
  895. };
  896. const executionPort: ExecutionPort = {
  897. async run() {
  898. return executionResult({
  899. status: "completed",
  900. stdout: grayAlphaPng,
  901. });
  902. },
  903. };
  904. const output = (await bashHandler(
  905. {
  906. command: "printf image",
  907. } satisfies BashInput,
  908. contextWith(executionPort, { imageProcessorPort }),
  909. )) as BashOutput;
  910. expect(output.isImage).toBe(false);
  911. expect(output.stdout).toBe(grayAlphaPng);
  912. expect(bashToolEntry.formatModelContent?.(output)).toBe(grayAlphaPng);
  913. });
  914. it("short-circuits successful image stdout without appending stderr text", async () => {
  915. const tinyPng =
  916. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  917. const executionPort: ExecutionPort = {
  918. async run() {
  919. return executionResult({
  920. status: "completed",
  921. stderr: "warn\n",
  922. stdout: tinyPng,
  923. });
  924. },
  925. };
  926. const output = (await bashHandler(
  927. {
  928. command: "printf image && echo warn >&2",
  929. } satisfies BashInput,
  930. contextWith(executionPort),
  931. )) as BashOutput;
  932. expect(bashToolEntry.formatModelContent?.(output)).toEqual([
  933. {
  934. type: "image",
  935. mediaType: "image/png",
  936. dataUrl: tinyPng,
  937. },
  938. ]);
  939. });
  940. it("projects failed image Bash results as text-only provider errors", async () => {
  941. const tinyPng =
  942. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  943. const executionPort: ExecutionPort = {
  944. async run() {
  945. return executionResult({
  946. exitCode: 7,
  947. status: "failed",
  948. stderr: "bad image command\n",
  949. stdout: tinyPng,
  950. });
  951. },
  952. };
  953. const output = (await bashHandler(
  954. {
  955. command: "printf image; exit 7",
  956. } satisfies BashInput,
  957. contextWith(executionPort),
  958. )) as BashOutput;
  959. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  960. `Exit code 7\n${tinyPng}\nbad image command`,
  961. );
  962. });
  963. it("keeps claude-code hint lines in failed provider-error stdout", async () => {
  964. const stdout =
  965. 'visible\n<claude-code-hint v="1" type="plugin" value="demo@example" />\nafter\n';
  966. const executionPort: ExecutionPort = {
  967. async run() {
  968. return executionResult({
  969. exitCode: 2,
  970. status: "failed",
  971. stderr: "bad command\n",
  972. stdout,
  973. });
  974. },
  975. };
  976. const output = (await bashHandler(
  977. {
  978. command: "printf hints; exit 2",
  979. } satisfies BashInput,
  980. contextWith(executionPort),
  981. )) as BashOutput;
  982. expect(output.stdout).toBe(stdout);
  983. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  984. `Exit code 2\n${stdout.trimEnd()}\nbad command`,
  985. );
  986. });
  987. it("does not resize failed image-looking stdout before provider error projection", async () => {
  988. const tinyPng =
  989. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  990. const resizeToFit = vi.fn<ImageProcessorPort["resizeToFit"]>(async () => {
  991. throw new Error("failed Bash output should not be resized");
  992. });
  993. const imageProcessorPort: ImageProcessorPort = {
  994. resizeToFit,
  995. async prepareForModel() {
  996. throw new Error("prepareForModel should not be called");
  997. },
  998. };
  999. const executionPort: ExecutionPort = {
  1000. async run() {
  1001. return executionResult({
  1002. exitCode: 7,
  1003. status: "failed",
  1004. stderr: "bad image command\n",
  1005. stdout: tinyPng,
  1006. });
  1007. },
  1008. };
  1009. const output = (await bashHandler(
  1010. {
  1011. command: "printf image; exit 7",
  1012. } satisfies BashInput,
  1013. contextWith(executionPort, { imageProcessorPort }),
  1014. )) as BashOutput;
  1015. expect(output.isImage).toBe(false);
  1016. expect(output.stdout).toBe(tinyPng);
  1017. expect(resizeToFit).not.toHaveBeenCalled();
  1018. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  1019. `Exit code 7\n${tinyPng}\nbad image command`,
  1020. );
  1021. });
  1022. it("reads artifact-backed image stdout before resizing provider-visible image output", async () => {
  1023. const testRoot = await mkdtemp(join(tmpdir(), "zcode-bash-image-"));
  1024. const tinyPng =
  1025. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  1026. const outputPath = join(testRoot, "stdout.txt");
  1027. await writeFile(outputPath, tinyPng, "utf8");
  1028. let capturedResizeRequest: Parameters<ImageProcessorPort["resizeToFit"]>[0] | undefined;
  1029. const imageProcessorPort: ImageProcessorPort = {
  1030. async resizeToFit(request) {
  1031. capturedResizeRequest = request;
  1032. return {
  1033. data: Buffer.from("resized-from-artifact"),
  1034. mediaType: "image/webp",
  1035. resized: true,
  1036. };
  1037. },
  1038. async prepareForModel() {
  1039. throw new Error("prepareForModel should not be called");
  1040. },
  1041. };
  1042. const executionPort: ExecutionPort = {
  1043. async run() {
  1044. return executionResult({
  1045. status: "completed",
  1046. stdout: tinyPng.slice(0, 24),
  1047. stdoutArtifactPath: outputPath,
  1048. stdoutArtifactBytes: Buffer.byteLength(tinyPng, "utf8"),
  1049. });
  1050. },
  1051. };
  1052. try {
  1053. const output = (await bashHandler(
  1054. {
  1055. command: "printf image",
  1056. } satisfies BashInput,
  1057. contextWith(executionPort, { imageProcessorPort }),
  1058. )) as BashOutput;
  1059. expect(output.isImage).toBe(true);
  1060. expect(output.stdout).toBe("data:image/webp;base64,cmVzaXplZC1mcm9tLWFydGlmYWN0");
  1061. expect(capturedResizeRequest?.mediaType).toBe("image/png");
  1062. expect(Buffer.from(capturedResizeRequest?.data ?? [])).toEqual(
  1063. Buffer.from(tinyPng.split(",")[1]!, "base64"),
  1064. );
  1065. expect(bashToolEntry.formatModelContent?.(output)).toEqual([
  1066. {
  1067. type: "image",
  1068. mediaType: "image/webp",
  1069. dataUrl: "data:image/webp;base64,cmVzaXplZC1mcm9tLWFydGlmYWN0",
  1070. },
  1071. ]);
  1072. } finally {
  1073. await rm(testRoot, { force: true, recursive: true });
  1074. }
  1075. });
  1076. it("does not swallow cancellation while resizing Bash image stdout", async () => {
  1077. const tinyPng =
  1078. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l2tzWQAAAABJRU5ErkJggg==";
  1079. const abortController = new AbortController();
  1080. abortController.abort();
  1081. const imageProcessorPort: ImageProcessorPort = {
  1082. async resizeToFit() {
  1083. throw new Error("resize aborted");
  1084. },
  1085. async prepareForModel() {
  1086. throw new Error("prepareForModel should not be called");
  1087. },
  1088. };
  1089. const executionPort: ExecutionPort = {
  1090. async run() {
  1091. return executionResult({
  1092. status: "completed",
  1093. stdout: tinyPng,
  1094. });
  1095. },
  1096. };
  1097. await expect(
  1098. bashHandler(
  1099. {
  1100. command: "printf image",
  1101. } satisfies BashInput,
  1102. contextWith(executionPort, {
  1103. abortSignal: abortController.signal,
  1104. imageProcessorPort,
  1105. }),
  1106. ),
  1107. ).rejects.toThrow("resize aborted");
  1108. });
  1109. it("闲时轮复用显式后台及超时自动后台的 Bash 生命周期", async () => {
  1110. const runBashWithBackgroundLifecycle = vi.fn(async () => ({
  1111. kind: "completed" as const,
  1112. result: executionResult({ status: "completed", exitCode: 0 }),
  1113. }));
  1114. const run = vi.fn(async () => executionResult({ status: "completed", exitCode: 0 }));
  1115. const executionPort: BashBackgroundLifecycleExecutionPort = {
  1116. run,
  1117. runBashWithBackgroundLifecycle,
  1118. };
  1119. await expect(
  1120. bashHandler(
  1121. { command: "long-running command", run_in_background: true } satisfies BashInput,
  1122. contextWith(executionPort, { offPeakTurn: true }),
  1123. ),
  1124. ).resolves.toBeDefined();
  1125. expect(runBashWithBackgroundLifecycle).toHaveBeenCalledTimes(1);
  1126. const output = (await bashHandler(
  1127. { command: "long-running command" } satisfies BashInput,
  1128. contextWith(executionPort, { offPeakTurn: true }),
  1129. )) as BashOutput;
  1130. expect(runBashWithBackgroundLifecycle).toHaveBeenCalledTimes(2);
  1131. expect(run).not.toHaveBeenCalled();
  1132. expect(output.status).toBe("completed");
  1133. });
  1134. it("starts background execution when requested", async () => {
  1135. let capturedRequest: ExecutionRequest | undefined;
  1136. let capturedMode: string | undefined;
  1137. const runBashWithBackgroundLifecycle = vi.fn(
  1138. async (request: ExecutionRequest, lifecycle: { mode: "explicit" | "auto_on_timeout" }) => {
  1139. capturedRequest = request;
  1140. capturedMode = lifecycle.mode;
  1141. return {
  1142. kind: "backgrounded" as const,
  1143. task: {
  1144. taskId: "exec_bg",
  1145. status: "running" as const,
  1146. startedAt: new Date(),
  1147. outputPath: "/tmp/exec_bg-stdout.log",
  1148. stdoutPersistedOutputPath: "/tmp/exec_bg-stdout.log",
  1149. stderrPersistedOutputPath: "/tmp/exec_bg-stderr.log",
  1150. },
  1151. };
  1152. },
  1153. );
  1154. const executionPort: BashBackgroundLifecycleExecutionPort = {
  1155. async run() {
  1156. throw new Error("run should not be called");
  1157. },
  1158. runBashWithBackgroundLifecycle,
  1159. };
  1160. const output = (await bashHandler(
  1161. {
  1162. command: "long-running command",
  1163. run_in_background: true,
  1164. } satisfies BashInput,
  1165. contextWith(executionPort),
  1166. )) as BashOutput;
  1167. expect(runBashWithBackgroundLifecycle).toHaveBeenCalledTimes(1);
  1168. expect(capturedMode).toBe("explicit");
  1169. expect(capturedRequest?.timeoutMs).toBe(120_000);
  1170. expect(capturedRequest?.outputLimit).toEqual({
  1171. maxInlineBytes: 30_000,
  1172. maxBufferBytes: 30_000,
  1173. maxPersistedBytes: 5 * 1024 * 1024 * 1024,
  1174. persistOutput: "always",
  1175. });
  1176. expect(output.status).toBe("backgrounded");
  1177. expect(output.backgroundTaskId).toBe("exec_bg");
  1178. expect(output.persistedOutputPath).toBe("/tmp/exec_bg-stdout.log");
  1179. expect(output.stdoutPersistedOutputPath).toBe("/tmp/exec_bg-stdout.log");
  1180. expect(output.stderrPersistedOutputPath).toBe("/tmp/exec_bg-stderr.log");
  1181. expect(output.interrupted).toBe(false);
  1182. });
  1183. it.each([
  1184. { inputTimeout: undefined, expected: 250 },
  1185. { inputTimeout: 0, expected: 250 },
  1186. { inputTimeout: "0", expected: 250 },
  1187. { inputTimeout: 500, expected: 500 },
  1188. { inputTimeout: "500", expected: 500 },
  1189. { inputTimeout: 5_000, expected: 900 },
  1190. ])(
  1191. "uses one injected timeout policy for handler requests ($inputTimeout -> $expected)",
  1192. async ({ inputTimeout, expected }) => {
  1193. let capturedRequest: ExecutionRequest | undefined;
  1194. const entry = createBashToolEntry({
  1195. bashTimeoutPolicy: {
  1196. defaultTimeoutMs: 250,
  1197. maxTimeoutMs: 900,
  1198. },
  1199. });
  1200. const executionPort: ExecutionPort = {
  1201. async run(request) {
  1202. capturedRequest = request;
  1203. return executionResult({ status: "completed", exitCode: 0 });
  1204. },
  1205. };
  1206. const toolInput = {
  1207. command: "sleep 0",
  1208. ...(inputTimeout === undefined ? {} : { timeout: inputTimeout }),
  1209. };
  1210. await entry.handler(toolInput, contextWith(executionPort));
  1211. expect(capturedRequest?.timeoutMs).toBe(expected);
  1212. expect(resolveTimeoutMs(entry, toolInput, 300_000)).toBe(expected + 6_000);
  1213. expect(entry.metadata.timeoutMs).toBe(250);
  1214. expect(entry.timeout).toMatchObject({ defaultMs: 250, maxMs: 900 });
  1215. expect(
  1216. (
  1217. (entry.inputSchema.properties as Record<string, unknown>).timeout as Record<
  1218. string,
  1219. unknown
  1220. >
  1221. ).description,
  1222. ).toBe("Optional timeout in milliseconds (max 900)");
  1223. expect(entry.metadata.description).toContain("default 250");
  1224. expect(entry.metadata.description).toContain("max 900");
  1225. },
  1226. );
  1227. it("returns separate stdout and stderr artifact paths", async () => {
  1228. const executionPort: ExecutionPort = {
  1229. async run() {
  1230. return executionResult({
  1231. status: "failed",
  1232. stdout: "abc",
  1233. stderr: "def",
  1234. stdoutArtifactPath: "/tmp/stdout.log",
  1235. stdoutArtifactBytes: 3,
  1236. stderrArtifactPath: "/tmp/stderr.log",
  1237. stderrArtifactBytes: 3,
  1238. });
  1239. },
  1240. };
  1241. const output = (await bashHandler(
  1242. {
  1243. command: "noisy command",
  1244. } satisfies BashInput,
  1245. contextWith(executionPort),
  1246. )) as BashOutput;
  1247. expect(output.persistedOutputPath).toBe("/tmp/stdout.log");
  1248. expect(output.stdoutPersistedOutputPath).toBe("/tmp/stdout.log");
  1249. expect(output.stderrPersistedOutputPath).toBe("/tmp/stderr.log");
  1250. expect(output.persistedOutputSize).toBe(6);
  1251. expect(output.stdoutPersistedOutputSize).toBe(3);
  1252. expect(output.stderrPersistedOutputSize).toBe(3);
  1253. });
  1254. it("uses observed Bash bytes instead of capped artifact bytes for persisted output", async () => {
  1255. const executionPort: ExecutionPort = {
  1256. async run() {
  1257. return executionResult({
  1258. status: "completed",
  1259. stdout: "preview",
  1260. stdoutBytes: 80 * 1024 * 1024,
  1261. stdoutArtifactPath: "/tmp/stdout.log",
  1262. stdoutArtifactBytes: 64 * 1024 * 1024,
  1263. stdoutTruncated: true,
  1264. });
  1265. },
  1266. };
  1267. const output = (await bashHandler(
  1268. { command: "large command" } satisfies BashInput,
  1269. contextWith(executionPort),
  1270. )) as BashOutput;
  1271. expect(output.persistedOutputSize).toBe(80 * 1024 * 1024);
  1272. expect(output.stdoutPersistedOutputSize).toBe(64 * 1024 * 1024);
  1273. });
  1274. it("surfaces output limit failures as a Bash interpretation", async () => {
  1275. const executionPort: ExecutionPort = {
  1276. async run() {
  1277. return executionResult({
  1278. status: "failed",
  1279. error: {
  1280. type: "output_limit",
  1281. message: "Execution output exceeded the persisted output limit",
  1282. },
  1283. });
  1284. },
  1285. };
  1286. const output = (await bashHandler(
  1287. {
  1288. command: "yes",
  1289. } satisfies BashInput,
  1290. contextWith(executionPort),
  1291. )) as BashOutput;
  1292. expect(output.stderr).toBe("Execution output exceeded the persisted output limit");
  1293. expect(output.returnCodeInterpretation).toBe(
  1294. "Command stopped because output exceeded the configured limit",
  1295. );
  1296. });
  1297. it("maps execution progress events to session events", async () => {
  1298. const events: SessionEvent[] = [];
  1299. const executionPort: ExecutionPort = {
  1300. async run(_request, options) {
  1301. await options?.onEvent?.({
  1302. type: "progress",
  1303. elapsedMs: 2100,
  1304. pid: 123,
  1305. stdoutBytes: 5,
  1306. stderrBytes: 4,
  1307. outputPreview: {
  1308. text: "hello",
  1309. fullText: "hello",
  1310. totalBytes: 5,
  1311. totalLines: 1,
  1312. linesEstimated: false,
  1313. },
  1314. stdoutTail: "hello",
  1315. stderrTail: "warn",
  1316. timestamp: new Date("2026-05-06T00:00:00.000Z"),
  1317. });
  1318. return executionResult({ status: "completed", stdout: "done" });
  1319. },
  1320. };
  1321. await bashHandler(
  1322. {
  1323. command: "long command",
  1324. } satisfies BashInput,
  1325. contextWith(executionPort, {
  1326. emitEvent: async (event) => {
  1327. events.push(event);
  1328. },
  1329. }),
  1330. );
  1331. expect(events).toHaveLength(1);
  1332. expect(events[0]?.type).toBe(SessionEventType.ToolCallProgress);
  1333. expect(events[0]?.payload).toMatchObject({
  1334. elapsedMs: 2100,
  1335. outputBytes: 9,
  1336. pid: 123,
  1337. stderrBytes: 4,
  1338. stderrTail: "warn",
  1339. stdoutBytes: 5,
  1340. outputPreview: {
  1341. text: "hello",
  1342. fullText: "hello",
  1343. totalBytes: 5,
  1344. totalLines: 1,
  1345. linesEstimated: false,
  1346. },
  1347. stdoutTail: "hello",
  1348. toolCallId: "tool_test",
  1349. toolName: "Bash",
  1350. });
  1351. });
  1352. it("uses the posix-bash profile without an explicit session shell selection", async () => {
  1353. let capturedRequest: ExecutionRequest | undefined;
  1354. const executionPort: ExecutionPort = {
  1355. async run(request) {
  1356. capturedRequest = request;
  1357. return executionResult({ status: "completed" });
  1358. },
  1359. };
  1360. await bashHandler(
  1361. {
  1362. command: "dir",
  1363. } satisfies BashInput,
  1364. contextWith(executionPort),
  1365. );
  1366. expect(capturedRequest?.command).toEqual({
  1367. mode: "shell",
  1368. command: "dir",
  1369. shellProfile: "posix-bash",
  1370. });
  1371. });
  1372. it("passes the session Bash shell selection to the execution adapter", async () => {
  1373. let capturedRequest: ExecutionRequest | undefined;
  1374. const shellSelection: ExecutionShellSelection = {
  1375. dialect: "git-bash",
  1376. display: { name: "Git Bash" },
  1377. id: "git-bash:C:\\Program Files\\Git\\bin\\bash.exe",
  1378. label: "Git Bash",
  1379. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  1380. source: "user-config",
  1381. };
  1382. const executionPort: ExecutionPort = {
  1383. async run(request) {
  1384. capturedRequest = request;
  1385. return executionResult({ status: "completed" });
  1386. },
  1387. };
  1388. await bashHandler(
  1389. {
  1390. command: "printf '%s\\n' \"$BASH_VERSION\"",
  1391. } satisfies BashInput,
  1392. contextWith(executionPort, { bashShellSelection: shellSelection }),
  1393. );
  1394. expect(capturedRequest?.command).toEqual({
  1395. mode: "shell",
  1396. command: "printf '%s\\n' \"$BASH_VERSION\"",
  1397. shellProfile: "posix-bash",
  1398. shellOverride: shellSelection,
  1399. });
  1400. });
  1401. it("keeps embedded search provider-visible state without injecting the Bash prelude", async () => {
  1402. let capturedRequest: ExecutionRequest | undefined;
  1403. const backend = {
  1404. kind: "internal-cli" as const,
  1405. command: "zcode",
  1406. args: ["__internal-search"],
  1407. };
  1408. const executionPort: ExecutionPort = {
  1409. async run(request) {
  1410. capturedRequest = request;
  1411. return executionResult({ status: "completed" });
  1412. },
  1413. };
  1414. await bashHandler(
  1415. {
  1416. command: "grep needle file.txt",
  1417. } satisfies BashInput,
  1418. contextWith(executionPort, {
  1419. embeddedSearch: { enabled: true, backend },
  1420. }),
  1421. );
  1422. expect(capturedRequest?.bashPrelude).toBeUndefined();
  1423. });
  1424. it("passes embedded search prelude for a POSIX shell selection", async () => {
  1425. let capturedRequest: ExecutionRequest | undefined;
  1426. const backend = {
  1427. kind: "internal-cli" as const,
  1428. command: "zcode",
  1429. args: ["__internal-search"],
  1430. };
  1431. const shellSelection: ExecutionShellSelection = {
  1432. dialect: "posix",
  1433. display: { name: "bash" },
  1434. id: "posix:/bin/bash",
  1435. label: "bash",
  1436. path: "/bin/bash",
  1437. source: "auto-detected",
  1438. };
  1439. const executionPort: ExecutionPort = {
  1440. async run(request) {
  1441. capturedRequest = request;
  1442. return executionResult({ status: "completed" });
  1443. },
  1444. };
  1445. await bashHandler(
  1446. {
  1447. command: "grep needle file.txt",
  1448. } satisfies BashInput,
  1449. contextWith(executionPort, {
  1450. bashShellSelection: shellSelection,
  1451. embeddedSearch: { enabled: true, backend },
  1452. }),
  1453. );
  1454. expect(capturedRequest?.bashPrelude).toEqual({
  1455. kind: "embedded-search",
  1456. backend,
  1457. });
  1458. });
  1459. it("marks find and grep disabled without removing the rg prelude", async () => {
  1460. let capturedRequest: ExecutionRequest | undefined;
  1461. const backend = {
  1462. kind: "native-binaries" as const,
  1463. findCommand: "/tools/bfs",
  1464. grepCommand: "/tools/ugrep",
  1465. rgCommand: "/tools/rg",
  1466. };
  1467. const executionPort: ExecutionPort = {
  1468. async run(request) {
  1469. capturedRequest = request;
  1470. return executionResult({ status: "completed" });
  1471. },
  1472. };
  1473. await bashHandler(
  1474. { command: "find . && grep needle file.txt && rg needle" } satisfies BashInput,
  1475. contextWith(executionPort, {
  1476. bashShellSelection: {
  1477. dialect: "posix",
  1478. display: { name: "bash" },
  1479. id: "posix:/bin/bash",
  1480. label: "bash",
  1481. path: "/bin/bash",
  1482. source: "auto-detected",
  1483. },
  1484. embeddedSearch: { enabled: true, backend, findAndGrepEnabled: false },
  1485. }),
  1486. );
  1487. expect(capturedRequest?.bashPrelude).toEqual({
  1488. kind: "embedded-search",
  1489. backend,
  1490. findAndGrepEnabled: false,
  1491. });
  1492. });
  1493. it("does not pass embedded search prelude without a backend", async () => {
  1494. let capturedRequest: ExecutionRequest | undefined;
  1495. const executionPort: ExecutionPort = {
  1496. async run(request) {
  1497. capturedRequest = request;
  1498. return executionResult({ status: "completed" });
  1499. },
  1500. };
  1501. await bashHandler(
  1502. {
  1503. command: "grep needle file.txt",
  1504. } satisfies BashInput,
  1505. contextWith(executionPort, {
  1506. embeddedSearch: { enabled: true },
  1507. }),
  1508. );
  1509. expect(capturedRequest?.bashPrelude).toBeUndefined();
  1510. });
  1511. it("does not pass embedded search prelude for a CMD shell selection", async () => {
  1512. let capturedRequest: ExecutionRequest | undefined;
  1513. const backend = {
  1514. kind: "internal-cli" as const,
  1515. command: "zcode",
  1516. args: ["__internal-search"],
  1517. };
  1518. const shellSelection: ExecutionShellSelection = {
  1519. dialect: "cmd",
  1520. display: { name: "CMD" },
  1521. id: "cmd",
  1522. label: "CMD",
  1523. path: "cmd.exe",
  1524. source: "user-config",
  1525. };
  1526. const executionPort: ExecutionPort = {
  1527. async run(request) {
  1528. capturedRequest = request;
  1529. return executionResult({ status: "completed" });
  1530. },
  1531. };
  1532. await bashHandler(
  1533. {
  1534. command: "grep needle file.txt",
  1535. } satisfies BashInput,
  1536. contextWith(executionPort, {
  1537. bashShellSelection: shellSelection,
  1538. embeddedSearch: { enabled: true, backend },
  1539. }),
  1540. );
  1541. expect(capturedRequest?.bashPrelude).toBeUndefined();
  1542. });
  1543. it("passes embedded search prelude for a Windows Git Bash shell selection", async () => {
  1544. let capturedRequest: ExecutionRequest | undefined;
  1545. const backend = {
  1546. kind: "internal-cli" as const,
  1547. command: "zcode",
  1548. args: ["__internal-search"],
  1549. };
  1550. const shellSelection: ExecutionShellSelection = {
  1551. dialect: "git-bash",
  1552. display: { name: "Git Bash" },
  1553. id: "git-bash:C:\\Program Files\\Git\\bin\\bash.exe",
  1554. label: "Git Bash",
  1555. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  1556. source: "user-config",
  1557. };
  1558. const executionPort: ExecutionPort = {
  1559. async run(request) {
  1560. capturedRequest = request;
  1561. return executionResult({ status: "completed" });
  1562. },
  1563. };
  1564. await bashHandler(
  1565. {
  1566. command: "grep needle file.txt",
  1567. } satisfies BashInput,
  1568. contextWith(executionPort, {
  1569. bashShellSelection: shellSelection,
  1570. embeddedSearch: { enabled: true, backend },
  1571. }),
  1572. );
  1573. expect(capturedRequest?.command).toMatchObject({
  1574. shellOverride: shellSelection,
  1575. shellProfile: "posix-bash",
  1576. });
  1577. expect(capturedRequest?.bashPrelude).toEqual({
  1578. kind: "embedded-search",
  1579. backend,
  1580. });
  1581. });
  1582. it("passes a CMD session shell selection to the execution adapter request", async () => {
  1583. let capturedRequest: ExecutionRequest | undefined;
  1584. const shellSelection: ExecutionShellSelection = {
  1585. dialect: "cmd",
  1586. display: { name: "CMD" },
  1587. id: "cmd",
  1588. label: "CMD",
  1589. path: "cmd.exe",
  1590. source: "user-config",
  1591. };
  1592. const executionPort: ExecutionPort = {
  1593. async run(request) {
  1594. capturedRequest = request;
  1595. return executionResult({ status: "completed" });
  1596. },
  1597. };
  1598. await bashHandler(
  1599. {
  1600. command: "dir",
  1601. } satisfies BashInput,
  1602. contextWith(executionPort, {
  1603. bashShellSelection: shellSelection,
  1604. }),
  1605. );
  1606. expect(capturedRequest?.command).toEqual({
  1607. mode: "shell",
  1608. command: "dir",
  1609. shellProfile: "posix-bash",
  1610. shellOverride: shellSelection,
  1611. });
  1612. });
  1613. it("defaults command cwd to the session cwd", async () => {
  1614. let capturedRequest: ExecutionRequest | undefined;
  1615. const executionPort: ExecutionPort = {
  1616. async run(request) {
  1617. capturedRequest = request;
  1618. return executionResult({ status: "completed" });
  1619. },
  1620. };
  1621. await bashHandler(
  1622. {
  1623. command: "pwd",
  1624. } satisfies BashInput,
  1625. contextWith(executionPort, {
  1626. workingDirectory: projectRoot,
  1627. workspaceRoot: projectRoot,
  1628. }),
  1629. );
  1630. expect(capturedRequest?.cwd).toBe(projectRoot);
  1631. });
  1632. it("does not expose resolved cwd in provider-visible Bash content", async () => {
  1633. const secretCwd = resolve(projectRoot, "secret-cwd");
  1634. const executionPort: ExecutionPort = {
  1635. async run() {
  1636. return executionResult({
  1637. status: "completed",
  1638. exitCode: 0,
  1639. resolvedCwd: secretCwd,
  1640. stdout: "ok\n",
  1641. });
  1642. },
  1643. };
  1644. const output = (await bashHandler(
  1645. { command: `cd ${secretCwd} && echo ok` } satisfies BashInput,
  1646. contextWith(executionPort, {
  1647. workingDirectory: projectRoot,
  1648. workspaceRoot: projectRoot,
  1649. }),
  1650. )) as BashOutput;
  1651. const content = bashToolEntry.formatModelContent?.(output);
  1652. expect(content).toBe("ok");
  1653. expect(JSON.stringify(output)).not.toContain("resolvedCwd");
  1654. });
  1655. it("formats Bash results as stdout and stderr text for the model", () => {
  1656. const modelContent = bashToolEntry.formatModelContent?.({
  1657. stdout: "input.tex\nmain.tex\nsynonyms.txt\n",
  1658. stderr: "",
  1659. interrupted: false,
  1660. status: "completed",
  1661. exitCode: 0,
  1662. stdoutBytes: 31,
  1663. stderrBytes: 0,
  1664. } satisfies BashOutput);
  1665. expect(modelContent).toBe("input.tex\nmain.tex\nsynonyms.txt");
  1666. });
  1667. it("formats Bash interrupted and persisted results with hints", () => {
  1668. const interrupted = bashToolEntry.formatModelContent?.({
  1669. stdout: "",
  1670. stderr: "partial failure",
  1671. interrupted: true,
  1672. status: "cancelled",
  1673. } satisfies BashOutput);
  1674. expect(interrupted).toBe(
  1675. "partial failure\n<error>Command was aborted before completion</error>",
  1676. );
  1677. const persisted = bashToolEntry.formatModelContent?.({
  1678. stdout: "x".repeat(20_000),
  1679. stderr: "",
  1680. interrupted: false,
  1681. status: "completed",
  1682. persistedOutputPath: "/tmp/stdout.log",
  1683. stdoutBytes: 20_000,
  1684. stderrBytes: 0,
  1685. } satisfies BashOutput);
  1686. expect(persisted).toContain("<persisted-output>");
  1687. expect(persisted).toContain("Full output saved to: /tmp/stdout.log");
  1688. expect(persisted).toContain("Preview (first 2KB):");
  1689. expect(persisted).toContain("</persisted-output>");
  1690. });
  1691. it("keeps Bash stale read hints visible without JSON serialization", () => {
  1692. const modelContent = bashToolEntry.formatModelContent?.({
  1693. stdout: "updated\n",
  1694. stderr: "",
  1695. interrupted: false,
  1696. status: "completed",
  1697. staleReadFileStateHint: "Previously read files changed; re-read before editing.",
  1698. } satisfies BashOutput);
  1699. expect(modelContent).toBe("updated\nPreviously read files changed; re-read before editing.");
  1700. });
  1701. it("backfills readFileState from successful cat before Edit", async () => {
  1702. const filePath = resolve(defaultCommandRoot, ".env.example");
  1703. const readFileState: ReadFileStateMap = new Map();
  1704. const fileSystemPort = memoryFileSystemPort({
  1705. [filePath]: {
  1706. content: "FOO=bar\n",
  1707. mtimeMs: 1000,
  1708. },
  1709. });
  1710. const executionPort: ExecutionPort = {
  1711. async run() {
  1712. return executionResult({
  1713. status: "completed",
  1714. exitCode: 0,
  1715. stdout: "FOO=bar\n",
  1716. });
  1717. },
  1718. };
  1719. await bashHandler(
  1720. { command: "cat .env.example" },
  1721. contextWith(executionPort, { fileSystemPort, readFileState }),
  1722. );
  1723. const entry = readFileState.get(createReadFileStateKey(filePath, 1, undefined));
  1724. expect(entry).toMatchObject({
  1725. path: filePath,
  1726. content: "FOO=bar\n",
  1727. offset: undefined,
  1728. limit: undefined,
  1729. isPartialView: false,
  1730. mtimeMs: 1000,
  1731. sizeBytes: Buffer.byteLength("FOO=bar\n"),
  1732. });
  1733. });
  1734. it("backfills ranged readFileState for head tail and sed print commands", async () => {
  1735. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  1736. const fileSystemPort = memoryFileSystemPort({
  1737. [filePath]: {
  1738. content: "a\nb\nc\nd\ne\n",
  1739. mtimeMs: 1000,
  1740. },
  1741. });
  1742. const cases = [
  1743. {
  1744. command: "head -n 2 fixture.txt",
  1745. expectedContent: "a\nb",
  1746. expectedOffset: 1,
  1747. expectedLimit: 2,
  1748. },
  1749. {
  1750. command: "tail -n 2 fixture.txt",
  1751. expectedContent: "d\ne",
  1752. expectedOffset: 4,
  1753. expectedLimit: 2,
  1754. },
  1755. {
  1756. command: "sed -n '2,3p' fixture.txt",
  1757. expectedContent: "b\nc",
  1758. expectedOffset: 2,
  1759. expectedLimit: 2,
  1760. },
  1761. ];
  1762. for (const testCase of cases) {
  1763. const readFileState: ReadFileStateMap = new Map();
  1764. const executionPort: ExecutionPort = {
  1765. async run() {
  1766. return executionResult({
  1767. status: "completed",
  1768. exitCode: 0,
  1769. stdout: testCase.expectedContent,
  1770. });
  1771. },
  1772. };
  1773. await bashHandler(
  1774. { command: testCase.command },
  1775. contextWith(executionPort, { fileSystemPort, readFileState }),
  1776. );
  1777. const entry = readFileState.get(
  1778. createReadFileStateKey(filePath, testCase.expectedOffset, testCase.expectedLimit),
  1779. );
  1780. expect(entry).toMatchObject({
  1781. path: filePath,
  1782. content: testCase.expectedContent,
  1783. offset: testCase.expectedOffset,
  1784. limit: testCase.expectedLimit,
  1785. isPartialView: false,
  1786. });
  1787. }
  1788. });
  1789. it("backfills full readFileState for grep only when grep exits zero", async () => {
  1790. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  1791. const fileSystemPort = memoryFileSystemPort({
  1792. [filePath]: {
  1793. content: "needle\nhaystack\n",
  1794. mtimeMs: 1000,
  1795. },
  1796. });
  1797. const successState: ReadFileStateMap = new Map();
  1798. const successPort: ExecutionPort = {
  1799. async run() {
  1800. return executionResult({
  1801. status: "completed",
  1802. exitCode: 0,
  1803. stdout: "needle\n",
  1804. });
  1805. },
  1806. };
  1807. await bashHandler(
  1808. { command: "grep needle fixture.txt" },
  1809. contextWith(successPort, { fileSystemPort, readFileState: successState }),
  1810. );
  1811. expect(successState.get(createReadFileStateKey(filePath, 1, undefined))).toMatchObject({
  1812. path: filePath,
  1813. content: "needle\nhaystack\n",
  1814. offset: undefined,
  1815. limit: undefined,
  1816. });
  1817. const missState: ReadFileStateMap = new Map();
  1818. const missPort: ExecutionPort = {
  1819. async run() {
  1820. return executionResult({
  1821. status: "failed",
  1822. exitCode: 1,
  1823. stdout: "",
  1824. });
  1825. },
  1826. };
  1827. await bashHandler(
  1828. { command: "grep missing fixture.txt" },
  1829. contextWith(missPort, { fileSystemPort, readFileState: missState }),
  1830. );
  1831. expect(missState.size).toBe(0);
  1832. });
  1833. it("does not backfill readFileState when Bash exits with provider error", async () => {
  1834. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  1835. const readFileState: ReadFileStateMap = new Map();
  1836. const fileSystemPort = memoryFileSystemPort({
  1837. [filePath]: {
  1838. content: "visible before failure\n",
  1839. mtimeMs: 1000,
  1840. },
  1841. });
  1842. const executionPort: ExecutionPort = {
  1843. async run() {
  1844. return executionResult({
  1845. status: "failed",
  1846. exitCode: 2,
  1847. stdout: "visible before failure\n",
  1848. stderr: "later command failed\n",
  1849. });
  1850. },
  1851. };
  1852. await bashHandler(
  1853. { command: "cat fixture.txt" },
  1854. contextWith(executionPort, { fileSystemPort, readFileState }),
  1855. );
  1856. expect(readFileState.get(createReadFileStateKey(filePath, 1, undefined))).toBeUndefined();
  1857. });
  1858. it("does not backfill readFileState for complex or unsafe Bash read commands", async () => {
  1859. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  1860. const fileSystemPort = memoryFileSystemPort({
  1861. [filePath]: {
  1862. content: "a\nb\n",
  1863. mtimeMs: 1000,
  1864. },
  1865. [resolve(defaultCommandRoot, "other.txt")]: {
  1866. content: "c\n",
  1867. mtimeMs: 1000,
  1868. },
  1869. });
  1870. const unsafeCommands = [
  1871. "cat fixture.txt | head",
  1872. "cat fixture.txt > out.txt",
  1873. 'cat "$TARGET"',
  1874. "cat fixture.txt other.txt",
  1875. "sed -i 's/a/b/' fixture.txt",
  1876. "head -n 0 fixture.txt",
  1877. ];
  1878. for (const command of unsafeCommands) {
  1879. const readFileState: ReadFileStateMap = new Map();
  1880. const executionPort: ExecutionPort = {
  1881. async run() {
  1882. return executionResult({
  1883. status: "completed",
  1884. exitCode: 0,
  1885. stdout: "ignored\n",
  1886. });
  1887. },
  1888. };
  1889. await bashHandler({ command }, contextWith(executionPort, { fileSystemPort, readFileState }));
  1890. expect(readFileState.size).toBe(0);
  1891. }
  1892. });
  1893. it("emits stale read hint when a write-like Bash command modifies a previously read file", async () => {
  1894. const filePath = resolve(defaultCommandRoot, "fixture.ts");
  1895. const readFileState: ReadFileStateMap = new Map();
  1896. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  1897. path: filePath,
  1898. content: "old\n",
  1899. isPartialView: false,
  1900. readAt: new Date(500),
  1901. sourceTool: "Read",
  1902. mtimeMs: 1000,
  1903. sizeBytes: 4,
  1904. });
  1905. const fileSystemPort = memoryFileSystemPort({
  1906. [filePath]: {
  1907. content: "new\n",
  1908. mtimeMs: 2000,
  1909. },
  1910. });
  1911. const executionPort: ExecutionPort = {
  1912. async run() {
  1913. return executionResult({
  1914. status: "completed",
  1915. exitCode: 0,
  1916. stdout: "formatted\n",
  1917. startedAt: new Date(1500),
  1918. });
  1919. },
  1920. };
  1921. const output = (await bashHandler(
  1922. { command: "pnpm format" },
  1923. contextWith(executionPort, { fileSystemPort, readFileState }),
  1924. )) as BashOutput;
  1925. const expectedHint = `[This command modified 1 file you've previously read: fixture.ts. Call Read before editing.]`;
  1926. expect(output.staleReadFileStateHint).toBe(expectedHint);
  1927. expect(bashToolEntry.formatModelContent?.(output)).toContain(expectedHint);
  1928. });
  1929. it("does not emit stale hint when write-like Bash exits with provider error", async () => {
  1930. const filePath = resolve(defaultCommandRoot, "fixture.ts");
  1931. const readFileState: ReadFileStateMap = new Map();
  1932. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  1933. path: filePath,
  1934. content: "old\n",
  1935. isPartialView: false,
  1936. readAt: new Date(500),
  1937. sourceTool: "Read",
  1938. mtimeMs: 1000,
  1939. sizeBytes: 4,
  1940. });
  1941. const fileSystemPort = memoryFileSystemPort({
  1942. [filePath]: {
  1943. content: "new\n",
  1944. mtimeMs: 2000,
  1945. },
  1946. });
  1947. const executionPort: ExecutionPort = {
  1948. async run() {
  1949. return executionResult({
  1950. status: "failed",
  1951. exitCode: 2,
  1952. stderr: "format failed",
  1953. startedAt: new Date(1500),
  1954. });
  1955. },
  1956. };
  1957. const output = (await bashHandler(
  1958. { command: "pnpm format" },
  1959. contextWith(executionPort, { fileSystemPort, readFileState }),
  1960. )) as BashOutput;
  1961. expect(output.staleReadFileStateHint).toBeUndefined();
  1962. expect(bashToolEntry.formatModelContent?.(output)).not.toContain("Call Read before editing");
  1963. });
  1964. it("formats stale hint paths when many read files changed", async () => {
  1965. const changedFilePaths = Array.from({ length: 6 }, (_, index) =>
  1966. resolve(defaultCommandRoot, `fixture-${index + 1}.ts`),
  1967. );
  1968. const readFileState: ReadFileStateMap = new Map();
  1969. for (const filePath of changedFilePaths) {
  1970. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  1971. path: filePath,
  1972. content: "old\n",
  1973. isPartialView: false,
  1974. readAt: new Date(500),
  1975. sourceTool: "Read",
  1976. mtimeMs: 1000,
  1977. sizeBytes: 4,
  1978. });
  1979. }
  1980. const fileSystemPort = memoryFileSystemPort(
  1981. Object.fromEntries(
  1982. changedFilePaths.map((filePath) => [
  1983. filePath,
  1984. {
  1985. content: "new\n",
  1986. mtimeMs: 2000,
  1987. },
  1988. ]),
  1989. ),
  1990. );
  1991. const executionPort: ExecutionPort = {
  1992. async run() {
  1993. return executionResult({
  1994. status: "completed",
  1995. exitCode: 0,
  1996. stdout: "formatted\n",
  1997. startedAt: new Date(1500),
  1998. });
  1999. },
  2000. };
  2001. const output = (await bashHandler(
  2002. { command: "pnpm format" },
  2003. contextWith(executionPort, { fileSystemPort, readFileState }),
  2004. )) as BashOutput;
  2005. const expectedHint =
  2006. "[This command modified 6 files you've previously read: fixture-1.ts, fixture-2.ts, fixture-3.ts, fixture-4.ts, fixture-5.ts and 1 more. Call Read before editing.]";
  2007. expect(output.staleReadFileStateHint).toBe(expectedHint);
  2008. expect(bashToolEntry.formatModelContent?.(output)).toContain(expectedHint);
  2009. });
  2010. it("stats stale hint candidates concurrently", async () => {
  2011. const changedFilePaths = Array.from({ length: 3 }, (_, index) =>
  2012. resolve(defaultCommandRoot, `fixture-${index + 1}.ts`),
  2013. );
  2014. const readFileState: ReadFileStateMap = new Map();
  2015. for (const filePath of changedFilePaths) {
  2016. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  2017. path: filePath,
  2018. content: "old\n",
  2019. isPartialView: false,
  2020. readAt: new Date(500),
  2021. sourceTool: "Read",
  2022. mtimeMs: 1000,
  2023. sizeBytes: 4,
  2024. });
  2025. }
  2026. const baseFileSystemPort = memoryFileSystemPort(
  2027. Object.fromEntries(
  2028. changedFilePaths.map((filePath) => [
  2029. filePath,
  2030. {
  2031. content: "new\n",
  2032. mtimeMs: 2000,
  2033. },
  2034. ]),
  2035. ),
  2036. );
  2037. let statsInFlight = 0;
  2038. let maxStatsInFlight = 0;
  2039. const fileSystemPort: FileSystemPort = {
  2040. ...baseFileSystemPort,
  2041. async stat(request, options) {
  2042. statsInFlight += 1;
  2043. maxStatsInFlight = Math.max(maxStatsInFlight, statsInFlight);
  2044. try {
  2045. await Promise.resolve();
  2046. return await baseFileSystemPort.stat(request, options);
  2047. } finally {
  2048. statsInFlight -= 1;
  2049. }
  2050. },
  2051. };
  2052. const executionPort: ExecutionPort = {
  2053. async run() {
  2054. return executionResult({
  2055. status: "completed",
  2056. exitCode: 0,
  2057. stdout: "formatted\n",
  2058. startedAt: new Date(1500),
  2059. });
  2060. },
  2061. };
  2062. await bashHandler(
  2063. { command: "pnpm format" },
  2064. contextWith(executionPort, { fileSystemPort, readFileState }),
  2065. );
  2066. expect(maxStatsInFlight).toBeGreaterThan(1);
  2067. });
  2068. it("accepts supported cat head tail sed and grep flag variants for read-state backfill", async () => {
  2069. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  2070. const fileSystemPort = memoryFileSystemPort({
  2071. [filePath]: {
  2072. content: "a\nb\nc\nd\ne\n",
  2073. mtimeMs: 1000,
  2074. },
  2075. });
  2076. const cases = [
  2077. {
  2078. command: "cat -n fixture.txt",
  2079. keyOffset: 1,
  2080. keyLimit: undefined,
  2081. expectedContent: "a\nb\nc\nd\ne\n",
  2082. expectedOffset: undefined,
  2083. expectedLimit: undefined,
  2084. },
  2085. {
  2086. command: "cat --number fixture.txt",
  2087. keyOffset: 1,
  2088. keyLimit: undefined,
  2089. expectedContent: "a\nb\nc\nd\ne\n",
  2090. expectedOffset: undefined,
  2091. expectedLimit: undefined,
  2092. },
  2093. {
  2094. command: "head --lines=2 fixture.txt",
  2095. keyOffset: 1,
  2096. keyLimit: 2,
  2097. expectedContent: "a\nb",
  2098. expectedOffset: 1,
  2099. expectedLimit: 2,
  2100. },
  2101. {
  2102. command: "head -2 fixture.txt",
  2103. keyOffset: 1,
  2104. keyLimit: 2,
  2105. expectedContent: "a\nb",
  2106. expectedOffset: 1,
  2107. expectedLimit: 2,
  2108. },
  2109. {
  2110. command: "tail --lines 2 fixture.txt",
  2111. keyOffset: 4,
  2112. keyLimit: 2,
  2113. expectedContent: "d\ne",
  2114. expectedOffset: 4,
  2115. expectedLimit: 2,
  2116. },
  2117. {
  2118. command: "sed --quiet '3p' fixture.txt",
  2119. keyOffset: 3,
  2120. keyLimit: 1,
  2121. expectedContent: "c",
  2122. expectedOffset: 3,
  2123. expectedLimit: 1,
  2124. },
  2125. {
  2126. command: "grep -n --color=never c fixture.txt",
  2127. keyOffset: 1,
  2128. keyLimit: undefined,
  2129. expectedContent: "a\nb\nc\nd\ne\n",
  2130. expectedOffset: undefined,
  2131. expectedLimit: undefined,
  2132. },
  2133. ];
  2134. for (const testCase of cases) {
  2135. const readFileState: ReadFileStateMap = new Map();
  2136. const executionPort: ExecutionPort = {
  2137. async run() {
  2138. return executionResult({
  2139. status: "completed",
  2140. exitCode: 0,
  2141. stdout: testCase.expectedContent,
  2142. });
  2143. },
  2144. };
  2145. await bashHandler(
  2146. { command: testCase.command },
  2147. contextWith(executionPort, { fileSystemPort, readFileState }),
  2148. );
  2149. expect(
  2150. readFileState.get(createReadFileStateKey(filePath, testCase.keyOffset, testCase.keyLimit)),
  2151. ).toMatchObject({
  2152. content: testCase.expectedContent,
  2153. offset: testCase.expectedOffset,
  2154. limit: testCase.expectedLimit,
  2155. });
  2156. }
  2157. });
  2158. it("rejects unsupported read-state backfill variants", async () => {
  2159. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  2160. const fileSystemPort = memoryFileSystemPort({
  2161. [filePath]: {
  2162. content: "a\nb\nc\n",
  2163. mtimeMs: 1000,
  2164. },
  2165. });
  2166. const rejectedCommands = ["sed --expression '3p' fixture.txt", 'grep needle "*.txt"'];
  2167. for (const command of rejectedCommands) {
  2168. const readFileState: ReadFileStateMap = new Map();
  2169. const executionPort: ExecutionPort = {
  2170. async run() {
  2171. return executionResult({
  2172. status: "completed",
  2173. exitCode: 0,
  2174. stdout: "ignored\n",
  2175. });
  2176. },
  2177. };
  2178. await bashHandler({ command }, contextWith(executionPort, { fileSystemPort, readFileState }));
  2179. expect(readFileState.size).toBe(0);
  2180. }
  2181. });
  2182. it("does not backfill readFileState for files over 10MB or existing read state paths", async () => {
  2183. const largePath = resolve(defaultCommandRoot, "large.txt");
  2184. const existingPath = resolve(defaultCommandRoot, "existing.txt");
  2185. const existingKey = createReadFileStateKey(existingPath, 1, undefined);
  2186. const readFileState: ReadFileStateMap = new Map([
  2187. [
  2188. existingKey,
  2189. {
  2190. path: existingPath,
  2191. content: "old\n",
  2192. isPartialView: false,
  2193. readAt: new Date(500),
  2194. sourceTool: "Read",
  2195. mtimeMs: 1000,
  2196. sizeBytes: 4,
  2197. },
  2198. ],
  2199. ]);
  2200. const fileSystemPort = memoryFileSystemPort({
  2201. [largePath]: {
  2202. content: "x".repeat(10 * 1024 * 1024 + 1),
  2203. mtimeMs: 1000,
  2204. },
  2205. [existingPath]: {
  2206. content: "new\n",
  2207. mtimeMs: 2000,
  2208. },
  2209. });
  2210. const executionPort: ExecutionPort = {
  2211. async run(request) {
  2212. return executionResult({
  2213. status: "completed",
  2214. exitCode: 0,
  2215. stdout: request.command.command.includes("large") ? "" : "new\n",
  2216. });
  2217. },
  2218. };
  2219. await bashHandler(
  2220. { command: "cat large.txt" },
  2221. contextWith(executionPort, { fileSystemPort, readFileState }),
  2222. );
  2223. await bashHandler(
  2224. { command: "cat existing.txt" },
  2225. contextWith(executionPort, { fileSystemPort, readFileState }),
  2226. );
  2227. expect(readFileState.get(createReadFileStateKey(largePath, 1, undefined))).toBeUndefined();
  2228. expect(readFileState.get(existingKey)?.content).toBe("old\n");
  2229. });
  2230. it("does not backfill readFileState when Bash file read is truncated", async () => {
  2231. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  2232. const readFileState: ReadFileStateMap = new Map();
  2233. const fileSystemPort = memoryFileSystemPort({
  2234. [filePath]: {
  2235. content: "partial\n",
  2236. mtimeMs: 1000,
  2237. truncated: true,
  2238. },
  2239. });
  2240. const executionPort: ExecutionPort = {
  2241. async run() {
  2242. return executionResult({
  2243. status: "completed",
  2244. exitCode: 0,
  2245. stdout: "partial\n",
  2246. });
  2247. },
  2248. };
  2249. await bashHandler(
  2250. { command: "cat fixture.txt" },
  2251. contextWith(executionPort, { fileSystemPort, readFileState }),
  2252. );
  2253. expect(readFileState.get(createReadFileStateKey(filePath, 1, undefined))).toBeUndefined();
  2254. });
  2255. it("does not backfill readFileState when Bash stdout is truncated", async () => {
  2256. const filePath = resolve(defaultCommandRoot, "fixture.txt");
  2257. const readFileState: ReadFileStateMap = new Map();
  2258. const fileSystemPort = memoryFileSystemPort({
  2259. [filePath]: {
  2260. content: "full content hidden from model\n",
  2261. mtimeMs: 1000,
  2262. },
  2263. });
  2264. const executionPort: ExecutionPort = {
  2265. async run() {
  2266. return executionResult({
  2267. status: "completed",
  2268. exitCode: 0,
  2269. stdout: "full",
  2270. stdoutTruncated: true,
  2271. });
  2272. },
  2273. };
  2274. await bashHandler(
  2275. { command: "cat fixture.txt" },
  2276. contextWith(executionPort, { fileSystemPort, readFileState }),
  2277. );
  2278. expect(readFileState.get(createReadFileStateKey(filePath, 1, undefined))).toBeUndefined();
  2279. });
  2280. it("does not reject completed Bash output when read-state parsing sees an empty path", async () => {
  2281. const readFileState: ReadFileStateMap = new Map();
  2282. const executionPort: ExecutionPort = {
  2283. async run() {
  2284. return executionResult({
  2285. status: "completed",
  2286. exitCode: 0,
  2287. stdout: "",
  2288. });
  2289. },
  2290. };
  2291. await expect(
  2292. bashHandler(
  2293. { command: "cat ''" },
  2294. contextWith(executionPort, {
  2295. fileSystemPort: memoryFileSystemPort({}),
  2296. readFileState,
  2297. }),
  2298. ),
  2299. ).resolves.toMatchObject({ status: "completed" });
  2300. expect(readFileState.size).toBe(0);
  2301. });
  2302. it("ignores stale hint candidates unless mtime is newer than both Bash start and read state", async () => {
  2303. const filePath = resolve(defaultCommandRoot, "fixture.ts");
  2304. const readFileState: ReadFileStateMap = new Map();
  2305. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  2306. path: filePath,
  2307. content: "old\n",
  2308. isPartialView: false,
  2309. readAt: new Date(500),
  2310. sourceTool: "Read",
  2311. mtimeMs: 1000,
  2312. sizeBytes: 4,
  2313. });
  2314. const fileSystemPort = memoryFileSystemPort({
  2315. [filePath]: {
  2316. content: "new\n",
  2317. mtimeMs: 1400,
  2318. },
  2319. });
  2320. const executionPort: ExecutionPort = {
  2321. async run() {
  2322. return executionResult({
  2323. status: "completed",
  2324. exitCode: 0,
  2325. stdout: "formatted\n",
  2326. startedAt: new Date(1500),
  2327. });
  2328. },
  2329. };
  2330. const output = (await bashHandler(
  2331. { command: "pnpm format" },
  2332. contextWith(executionPort, { fileSystemPort, readFileState }),
  2333. )) as BashOutput;
  2334. expect(output.staleReadFileStateHint).toBeUndefined();
  2335. });
  2336. it("ignores stale hint candidates that cannot be stat'ed", async () => {
  2337. const filePath = resolve(defaultCommandRoot, "missing.ts");
  2338. const readFileState: ReadFileStateMap = new Map();
  2339. readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
  2340. path: filePath,
  2341. content: "old\n",
  2342. isPartialView: false,
  2343. readAt: new Date(500),
  2344. sourceTool: "Read",
  2345. mtimeMs: 1000,
  2346. sizeBytes: 4,
  2347. });
  2348. const executionPort: ExecutionPort = {
  2349. async run() {
  2350. return executionResult({
  2351. status: "completed",
  2352. exitCode: 0,
  2353. stdout: "formatted\n",
  2354. startedAt: new Date(1500),
  2355. });
  2356. },
  2357. };
  2358. const output = (await bashHandler(
  2359. { command: "pnpm format" },
  2360. contextWith(executionPort, {
  2361. fileSystemPort: memoryFileSystemPort({}),
  2362. readFileState,
  2363. }),
  2364. )) as BashOutput;
  2365. expect(output.staleReadFileStateHint).toBeUndefined();
  2366. });
  2367. it("formats background Bash output paths for the model", () => {
  2368. const modelContent = bashToolEntry.formatModelContent?.({
  2369. stdout: "",
  2370. stderr: "",
  2371. interrupted: false,
  2372. status: "backgrounded",
  2373. backgroundTaskId: "exec_bg",
  2374. persistedOutputPath: "/tmp/exec_bg-stdout.log",
  2375. stdoutPersistedOutputPath: "/tmp/exec_bg-stdout.log",
  2376. stderrPersistedOutputPath: "/tmp/exec_bg-stderr.log",
  2377. } satisfies BashOutput);
  2378. expect(modelContent).toBe(
  2379. "Command running in background with ID: exec_bg. Output is being written to: /tmp/exec_bg-stdout.log. You will be notified when it completes. To check interim output, use Read on that file path.",
  2380. );
  2381. });
  2382. });
  2383. function contextWith(
  2384. executionPort: ExecutionPort,
  2385. options: {
  2386. abortSignal?: AbortSignal;
  2387. bashShellSelection?: ToolExecutionContext["bashShellSelection"];
  2388. embeddedSearch?: ToolExecutionContext["embeddedSearch"];
  2389. emitEvent?: ToolExecutionContext["emitEvent"];
  2390. fileSystemPort?: FileSystemPort;
  2391. imageProcessorPort?: ImageProcessorPort;
  2392. offPeakTurn?: boolean;
  2393. readFileState?: ReadFileStateMap;
  2394. runtimeScope?: ToolExecutionContext["runtimeScope"];
  2395. setWorkingDirectory?: ToolExecutionContext["setWorkingDirectory"];
  2396. telemetry?: ToolExecutionSpanWriter;
  2397. workingDirectory?: string;
  2398. workspaceRoot?: string;
  2399. } = {},
  2400. ): ToolExecutionContext {
  2401. return {
  2402. toolCallId: "tool_test",
  2403. traceId: "trace_test",
  2404. spanId: "span_test",
  2405. abortSignal: options.abortSignal ?? new AbortController().signal,
  2406. bashShellSelection: options.bashShellSelection,
  2407. embeddedSearch: options.embeddedSearch,
  2408. emitEvent: options.emitEvent,
  2409. executionPort,
  2410. fileSystemPort: options.fileSystemPort,
  2411. imageProcessorPort: options.imageProcessorPort,
  2412. offPeakTurn: options.offPeakTurn,
  2413. readFileState: options.readFileState,
  2414. runtimeScope: options.runtimeScope,
  2415. setWorkingDirectory: options.setWorkingDirectory,
  2416. telemetry: options.telemetry,
  2417. workingDirectory: options.workingDirectory ?? defaultCommandRoot,
  2418. workspaceRoot: options.workspaceRoot ?? defaultCommandRoot,
  2419. sessionId: "sess_test",
  2420. turnId: "turn_test",
  2421. };
  2422. }
  2423. function recordingBashTelemetry(outcomes: string[]): ToolExecutionSpanWriter {
  2424. const command: CommandExecutionSpanWriter = {
  2425. captureCausation: () => undefined,
  2426. finishBackgrounded() {
  2427. outcomes.push("backgrounded");
  2428. },
  2429. finishCancelled() {
  2430. outcomes.push("cancelled");
  2431. },
  2432. finishCompleted() {
  2433. outcomes.push("completed");
  2434. },
  2435. finishFailed(stage) {
  2436. outcomes.push(`failed:${stage}`);
  2437. },
  2438. markFirstOutput() {},
  2439. markTerminationRequested() {},
  2440. run: (execute) => execute(),
  2441. setExitCode(exitCode) {
  2442. outcomes.push(`exit:${exitCode}`);
  2443. },
  2444. setOutputBytes() {},
  2445. setSignal() {},
  2446. setTimedOut() {},
  2447. };
  2448. return {
  2449. captureCausation: () => undefined,
  2450. finishCancelled() {},
  2451. finishCompleted() {},
  2452. finishDenied() {},
  2453. finishFailed() {},
  2454. markPermissionRequested() {},
  2455. run: (execute) => execute(),
  2456. setOutputBytes() {},
  2457. setOutputTruncated() {},
  2458. setPermissionDecision() {},
  2459. startCommand: () => command,
  2460. };
  2461. }
  2462. function executionResult(options: {
  2463. status: ExecutionResult["status"];
  2464. exitCode?: number;
  2465. stdout?: string;
  2466. stdoutBytes?: number;
  2467. stderr?: string;
  2468. stderrBytes?: number;
  2469. stdoutArtifactPath?: string;
  2470. stdoutArtifactBytes?: number;
  2471. stdoutTruncated?: boolean;
  2472. stderrArtifactPath?: string;
  2473. stderrArtifactBytes?: number;
  2474. stderrTruncated?: boolean;
  2475. error?: ExecutionResult["error"];
  2476. resolvedCwd?: string;
  2477. startedAt?: Date;
  2478. completedAt?: Date;
  2479. timedOut?: boolean;
  2480. }): ExecutionResult {
  2481. const now = new Date();
  2482. const startedAt = options.startedAt ?? now;
  2483. const completedAt = options.completedAt ?? startedAt;
  2484. return {
  2485. status: options.status,
  2486. exitCode: options.exitCode,
  2487. stdout: {
  2488. text: options.stdout ?? "",
  2489. bytes: options.stdoutBytes ?? Buffer.byteLength(options.stdout ?? ""),
  2490. truncated: options.stdoutTruncated ?? false,
  2491. artifactPath: options.stdoutArtifactPath,
  2492. artifactBytes: options.stdoutArtifactBytes,
  2493. },
  2494. stderr: {
  2495. text: options.stderr ?? "",
  2496. bytes: options.stderrBytes ?? Buffer.byteLength(options.stderr ?? ""),
  2497. truncated: options.stderrTruncated ?? false,
  2498. artifactPath: options.stderrArtifactPath,
  2499. artifactBytes: options.stderrArtifactBytes,
  2500. },
  2501. durationMs: 1,
  2502. timedOut: options.timedOut ?? false,
  2503. cancelled: false,
  2504. startedAt,
  2505. completedAt,
  2506. error: options.error,
  2507. resolvedCwd: options.resolvedCwd,
  2508. };
  2509. }
  2510. function memoryFileSystemPort(
  2511. files: Record<
  2512. string,
  2513. {
  2514. content: string;
  2515. mtimeMs?: number;
  2516. revisionId?: string;
  2517. truncated?: boolean;
  2518. }
  2519. >,
  2520. ): FileSystemPort {
  2521. const port: Partial<FileSystemPort> = {
  2522. async stat(request) {
  2523. const file = files[request.path];
  2524. if (!file) {
  2525. throw new Error(`missing fixture file: ${request.path}`);
  2526. }
  2527. const sizeBytes = Buffer.byteLength(file.content);
  2528. return {
  2529. path: request.path,
  2530. kind: "file",
  2531. sizeBytes,
  2532. mtimeMs: file.mtimeMs,
  2533. revision: {
  2534. id: file.revisionId ?? `${request.path}:${file.mtimeMs ?? 0}`,
  2535. mtimeMs: file.mtimeMs,
  2536. sizeBytes,
  2537. },
  2538. } satisfies FileSystemStatResult;
  2539. },
  2540. async readTextFile(request) {
  2541. const file = files[request.path];
  2542. if (!file) {
  2543. throw new Error(`missing fixture file: ${request.path}`);
  2544. }
  2545. const sizeBytes = Buffer.byteLength(file.content);
  2546. return {
  2547. path: request.path,
  2548. content: file.content,
  2549. encoding: "utf8",
  2550. bytesRead: sizeBytes,
  2551. sizeBytes,
  2552. truncated: file.truncated === true,
  2553. revision: {
  2554. id: file.revisionId ?? `${request.path}:${file.mtimeMs ?? 0}`,
  2555. mtimeMs: file.mtimeMs,
  2556. sizeBytes,
  2557. },
  2558. } satisfies FileSystemReadTextResult;
  2559. },
  2560. };
  2561. return port as FileSystemPort;
  2562. }