bash-handler.test.ts 83 KB

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