bash-handler.test.ts 96 KB

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