bash-handler.test.ts 87 KB

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