exec.test.ts 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015
  1. import {
  2. mkdir,
  3. mkdtemp,
  4. open,
  5. readdir,
  6. readFile,
  7. realpath,
  8. rm,
  9. stat,
  10. symlink,
  11. unlink,
  12. writeFile,
  13. } from "node:fs/promises";
  14. import { tmpdir } from "node:os";
  15. import { join } from "node:path";
  16. import { execFileSync } from "node:child_process";
  17. import iconv from "iconv-lite";
  18. import { setTimeout as sleep } from "node:timers/promises";
  19. import { describe, expect, it, vi } from "vitest";
  20. const { statfsMock } = vi.hoisted(() => ({
  21. statfsMock: vi.fn(),
  22. }));
  23. vi.mock("node:fs/promises", async (importOriginal) => {
  24. const actual = await importOriginal<typeof import("node:fs/promises")>();
  25. statfsMock.mockImplementation(actual.statfs);
  26. return {
  27. ...actual,
  28. statfs: statfsMock,
  29. };
  30. });
  31. import {
  32. applyResolvedShellCommandForTest,
  33. buildExecutionEnv,
  34. decodeExecutionOutputBuffer,
  35. NodeExecutionAdapter,
  36. resolveExecutionCommand,
  37. setResolvedShellLoginMode,
  38. } from "../src/exec/index.js";
  39. import {
  40. resolveEffectiveBashShellSelection,
  41. resolveWindowsGitBashShell,
  42. } from "../src/exec/bash-shell-provider.js";
  43. import { resolveBashMaxOutputLength } from "../src/exec/bash-output-policy.js";
  44. import { createCwdCapturePlan, normalizeCapturedCwdForHost } from "../src/exec/cwd-capture.js";
  45. import {
  46. type BackgroundExecutionSnapshot,
  47. type BackgroundExecutionStartResult,
  48. gitBashPathToWindowsPath,
  49. type ExecutionEvent,
  50. type ExecutionResult,
  51. type ExecutionRequest,
  52. type ExecutionRunOptions,
  53. windowsPathToGitBashPath,
  54. } from "@zcode/contracts";
  55. import { ZCODE_NO_PROXY_ENV_KEY, ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
  56. const POSIX_BASH_PATH =
  57. process.platform === "win32"
  58. ? undefined
  59. : findExecutable(["bash", "/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]);
  60. const WINDOWS_GIT_BASH_PATH =
  61. process.platform === "win32" ? resolveWindowsGitBashShell(process.env) : undefined;
  62. function findExecutable(candidates: Array<string | undefined>): string | undefined {
  63. return candidates.find((candidate) => candidate !== undefined && commandExists(candidate));
  64. }
  65. function commandExists(command: string): command is string {
  66. try {
  67. execFileSync(command, ["--version"], { stdio: "ignore" });
  68. return true;
  69. } catch {
  70. return false;
  71. }
  72. }
  73. type BashBackgroundLifecycleCapableAdapter = NodeExecutionAdapter & {
  74. runBashWithBackgroundLifecycle?: (
  75. request: ExecutionRequest,
  76. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  77. options?: ExecutionRunOptions,
  78. ) => Promise<
  79. | {
  80. kind: "foreground";
  81. result: ExecutionResult;
  82. }
  83. | {
  84. kind: "backgrounded";
  85. task: BackgroundExecutionStartResult;
  86. }
  87. >;
  88. waitForBackgroundTask?: (
  89. taskId: string,
  90. options?: { signal?: AbortSignal },
  91. ) => Promise<BackgroundExecutionSnapshot | undefined>;
  92. };
  93. describe("NodeExecutionAdapter", () => {
  94. it("auto-backgrounds a foreground command when its timeout elapses", async () => {
  95. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-"));
  96. const adapter = new NodeExecutionAdapter({
  97. outputRootDir: root,
  98. progressIntervalMs: 10,
  99. progressThresholdMs: 1,
  100. });
  101. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  102. try {
  103. const result = await capable.runBashWithBackgroundLifecycle!(
  104. {
  105. command: {
  106. mode: "argv",
  107. file: process.execPath,
  108. args: ["-e", "setTimeout(() => process.stdout.write('late'), 60)"],
  109. },
  110. timeoutMs: 10,
  111. outputLimit: {
  112. persistOutput: "always",
  113. },
  114. trace: {
  115. sessionId: "exec-auto-background-session",
  116. attributes: {
  117. toolCallId: "toolu_auto_background",
  118. },
  119. } as any,
  120. },
  121. { mode: "auto_on_timeout" },
  122. );
  123. expect(result.kind).toBe("backgrounded");
  124. expect(result.task.taskId).toMatch(/^exec_/u);
  125. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  126. expect(snapshot?.status).toBe("completed");
  127. expect(snapshot?.result?.stdout.text).toBe("late");
  128. } finally {
  129. await adapter.close();
  130. await rm(root, { recursive: true, force: true });
  131. }
  132. });
  133. it("keeps explicit background execution alive after its input timeout", async () => {
  134. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-timeout-"));
  135. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  136. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  137. try {
  138. const result = await capable.runBashWithBackgroundLifecycle!(
  139. {
  140. command: {
  141. mode: "argv",
  142. file: process.execPath,
  143. args: ["-e", "setTimeout(() => process.stdout.write('survived'), 80)"],
  144. },
  145. timeoutMs: 5,
  146. trace: {
  147. sessionId: "exec-explicit-background-timeout-session",
  148. attributes: { toolCallId: "toolu_explicit_background_timeout" },
  149. } as any,
  150. },
  151. { mode: "explicit" },
  152. );
  153. expect(result.kind).toBe("backgrounded");
  154. await sleep(25);
  155. expect((await capable.getBackgroundTask(result.task.taskId))?.status).toBe("running");
  156. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  157. expect(snapshot?.status).toBe("completed");
  158. expect(snapshot?.result?.stdout.text).toBe("survived");
  159. } finally {
  160. await adapter.close();
  161. await rm(root, { recursive: true, force: true });
  162. }
  163. });
  164. it("detaches parent abort after an explicit background commit", async () => {
  165. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-detach-"));
  166. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  167. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  168. const parentTurn = new AbortController();
  169. try {
  170. const result = await capable.runBashWithBackgroundLifecycle!(
  171. {
  172. command: {
  173. mode: "argv",
  174. file: process.execPath,
  175. args: ["-e", "setTimeout(() => process.stdout.write('detached'), 70)"],
  176. },
  177. timeoutMs: 5,
  178. trace: {
  179. sessionId: "exec-explicit-background-detach-session",
  180. attributes: { toolCallId: "toolu_explicit_background_detach" },
  181. } as any,
  182. },
  183. { mode: "explicit" },
  184. { signal: parentTurn.signal },
  185. );
  186. expect(result.kind).toBe("backgrounded");
  187. parentTurn.abort();
  188. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  189. expect(snapshot?.status).toBe("completed");
  190. expect(snapshot?.result?.stdout.text).toBe("detached");
  191. } finally {
  192. await adapter.close();
  193. await rm(root, { recursive: true, force: true });
  194. }
  195. });
  196. it("still allows an explicit lifecycle task to be stopped directly", async () => {
  197. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-stop-"));
  198. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  199. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  200. try {
  201. const result = await capable.runBashWithBackgroundLifecycle!(
  202. {
  203. command: {
  204. mode: "argv",
  205. file: process.execPath,
  206. args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
  207. },
  208. timeoutMs: 5,
  209. },
  210. { mode: "explicit" },
  211. );
  212. expect(result.kind).toBe("backgrounded");
  213. const stopped = await capable.cancelBackgroundTask(result.task.taskId);
  214. expect(stopped?.status).toBe("cancelled");
  215. } finally {
  216. await adapter.close();
  217. await rm(root, { recursive: true, force: true });
  218. }
  219. });
  220. it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
  221. "kills a cooperative Bash descendant outside the root process group",
  222. async () => {
  223. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-cross-pgid-stop-"));
  224. const adapter = new NodeExecutionAdapter({
  225. outputRootDir,
  226. progressIntervalMs: 10,
  227. progressThresholdMs: 0,
  228. });
  229. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  230. let launcherPid = Number.NaN;
  231. let workerPid = Number.NaN;
  232. const workerScript = [
  233. "process.stdout.write('worker:' + process.pid + '\\n');",
  234. "setInterval(() => {}, 10_000);",
  235. ].join("");
  236. const launcherScript = [
  237. "const { spawn } = require('node:child_process');",
  238. "process.stdout.write('launcher:' + process.pid + '\\n');",
  239. `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
  240. "worker.on('exit', () => process.exit());",
  241. "setInterval(() => {}, 10_000);",
  242. ].join("");
  243. try {
  244. const result = await capable.runBashWithBackgroundLifecycle!(
  245. {
  246. command: {
  247. mode: "shell",
  248. command: `set -m; ${quotePosixShellArgument(process.execPath)} -e ${quotePosixShellArgument(launcherScript)} & wait`,
  249. shellProfile: "posix-bash",
  250. shellOverride: {
  251. dialect: "posix",
  252. display: { name: "bash" },
  253. path: POSIX_BASH_PATH!,
  254. source: "auto-detected",
  255. },
  256. },
  257. },
  258. { mode: "explicit" },
  259. );
  260. expect(result.kind).toBe("backgrounded");
  261. let runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
  262. for (let attempt = 0; attempt < 100; attempt += 1) {
  263. const output = await readFile(result.task.outputPath!, "utf8");
  264. launcherPid = Number(/launcher:(\d+)/u.exec(output)?.[1]);
  265. workerPid = Number(/worker:(\d+)/u.exec(output)?.[1]);
  266. if (
  267. Number.isInteger(launcherPid) &&
  268. launcherPid > 0 &&
  269. Number.isInteger(workerPid) &&
  270. workerPid > 0
  271. ) {
  272. break;
  273. }
  274. await sleep(20);
  275. runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
  276. }
  277. expect(Number.isInteger(launcherPid), JSON.stringify(runningSnapshot)).toBe(true);
  278. expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
  279. expect(Number.isInteger(runningSnapshot?.pid)).toBe(true);
  280. expect(readPosixProcessGroupId(launcherPid)).not.toBe(
  281. readPosixProcessGroupId(runningSnapshot!.pid!),
  282. );
  283. expect(isProcessAlive(launcherPid)).toBe(true);
  284. expect(isProcessAlive(workerPid)).toBe(true);
  285. await adapter.cancelBackgroundTask(result.task.taskId);
  286. let launcherStillRunning = true;
  287. let workerStillRunning = true;
  288. for (let attempt = 0; attempt < 120; attempt += 1) {
  289. launcherStillRunning = isProcessAlive(launcherPid);
  290. workerStillRunning = isProcessAlive(workerPid);
  291. if (!launcherStillRunning && !workerStillRunning) break;
  292. await sleep(25);
  293. }
  294. expect(launcherStillRunning).toBe(false);
  295. expect(workerStillRunning).toBe(false);
  296. let terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
  297. for (let attempt = 0; attempt < 100 && !terminalSnapshot?.result; attempt += 1) {
  298. await sleep(20);
  299. terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
  300. }
  301. expect(terminalSnapshot).toMatchObject({
  302. status: "cancelled",
  303. result: { status: "cancelled" },
  304. });
  305. } finally {
  306. if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
  307. process.kill(workerPid, "SIGKILL");
  308. }
  309. if (Number.isInteger(launcherPid) && launcherPid > 0 && isProcessAlive(launcherPid)) {
  310. process.kill(launcherPid, "SIGKILL");
  311. }
  312. await adapter.close();
  313. await rm(outputRootDir, { force: true, recursive: true });
  314. }
  315. },
  316. );
  317. it.skipIf(process.platform === "win32")(
  318. "keeps Bash descendant enumeration out of generic argv cancellation",
  319. async () => {
  320. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-generic-group-stop-"));
  321. const adapter = new NodeExecutionAdapter({ outputRootDir });
  322. let workerPid = Number.NaN;
  323. const workerScript = "setInterval(() => {}, 10_000);";
  324. const launcherScript = [
  325. "const { spawn } = require('node:child_process');",
  326. `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
  327. "process.stdout.write('worker:' + worker.pid + '\\n');",
  328. "worker.unref();",
  329. "setInterval(() => {}, 10_000);",
  330. ].join("");
  331. try {
  332. const started = await adapter.start({
  333. command: {
  334. mode: "argv",
  335. file: process.execPath,
  336. args: ["-e", launcherScript],
  337. },
  338. });
  339. let runningSnapshot = await adapter.getBackgroundTask(started.taskId);
  340. for (let attempt = 0; attempt < 100; attempt += 1) {
  341. workerPid = Number(/worker:(\d+)/u.exec(runningSnapshot?.stdoutTail ?? "")?.[1]);
  342. if (Number.isInteger(workerPid) && workerPid > 0) break;
  343. await sleep(20);
  344. runningSnapshot = await adapter.getBackgroundTask(started.taskId);
  345. }
  346. expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
  347. expect(readPosixProcessGroupId(workerPid)).not.toBe(
  348. readPosixProcessGroupId(runningSnapshot!.pid!),
  349. );
  350. await adapter.cancelBackgroundTask(started.taskId);
  351. // Bug 根因:PPID 后代枚举属于 Bash runtime;通用 ExecutionPort 必须保留
  352. // 原有的进程组停止边界,不能顺带获得新的跨 PGID kill 能力。
  353. await sleep(850);
  354. expect(isProcessAlive(workerPid)).toBe(true);
  355. } finally {
  356. if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
  357. process.kill(workerPid, "SIGKILL");
  358. }
  359. await adapter.close();
  360. await rm(outputRootDir, { force: true, recursive: true });
  361. }
  362. },
  363. );
  364. it("cancels an explicit lifecycle task when the adapter closes", async () => {
  365. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-close-"));
  366. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  367. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  368. try {
  369. const result = await capable.runBashWithBackgroundLifecycle!(
  370. {
  371. command: {
  372. mode: "argv",
  373. file: process.execPath,
  374. args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
  375. },
  376. timeoutMs: 5,
  377. },
  378. { mode: "explicit" },
  379. );
  380. expect(result.kind).toBe("backgrounded");
  381. await adapter.close();
  382. const snapshot = await capable.getBackgroundTask(result.task.taskId);
  383. expect(snapshot?.status).toBe("cancelled");
  384. expect(snapshot?.result?.status).toBe("cancelled");
  385. } finally {
  386. await adapter.close();
  387. await rm(root, { recursive: true, force: true });
  388. }
  389. });
  390. it("cancels before background commit when the parent is already aborted", async () => {
  391. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-pre-abort-"));
  392. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  393. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  394. const parentTurn = new AbortController();
  395. parentTurn.abort();
  396. try {
  397. const result = await capable.runBashWithBackgroundLifecycle!(
  398. {
  399. command: {
  400. mode: "argv",
  401. file: process.execPath,
  402. args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 30)"],
  403. },
  404. timeoutMs: 5,
  405. trace: {
  406. sessionId: "exec-explicit-background-pre-abort-session",
  407. attributes: { toolCallId: "toolu_explicit_background_pre_abort" },
  408. } as any,
  409. },
  410. { mode: "explicit" },
  411. { signal: parentTurn.signal },
  412. );
  413. expect(result.kind).toBe("foreground");
  414. expect(result.result.status).toBe("cancelled");
  415. } finally {
  416. await adapter.close();
  417. await rm(root, { recursive: true, force: true });
  418. }
  419. });
  420. it("returns an explicit spawn failure without publishing a background task", async () => {
  421. const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-spawn-fail-"));
  422. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  423. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  424. try {
  425. const result = await capable.runBashWithBackgroundLifecycle!(
  426. {
  427. command: {
  428. mode: "argv",
  429. file: join(root, "missing-executable"),
  430. },
  431. timeoutMs: 5,
  432. trace: {
  433. sessionId: "exec-explicit-background-spawn-fail-session",
  434. attributes: { toolCallId: "toolu_explicit_background_spawn_fail" },
  435. } as any,
  436. },
  437. { mode: "explicit" },
  438. );
  439. expect(result.kind).toBe("foreground");
  440. expect(result.result.status).toBe("spawn_error");
  441. } finally {
  442. await adapter.close();
  443. await rm(root, { recursive: true, force: true });
  444. }
  445. });
  446. it("settles completion, timeout, and abort boundary races exactly once", async () => {
  447. const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-races-"));
  448. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  449. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  450. const backgroundTaskIds = new Set<string>();
  451. try {
  452. for (let attempt = 0; attempt < 12; attempt++) {
  453. const parentTurn = new AbortController();
  454. let outcomeCount = 0;
  455. let forwardedTerminalEvents = 0;
  456. const childDelayMs = attempt % 3 === 2 ? 5 : 12;
  457. const result = await capable.runBashWithBackgroundLifecycle!(
  458. {
  459. command: {
  460. mode: "argv",
  461. file: process.execPath,
  462. args: [
  463. "-e",
  464. `setTimeout(() => process.stdout.write('race-${attempt}'), ${childDelayMs})`,
  465. ],
  466. },
  467. timeoutMs: 5,
  468. trace: {
  469. sessionId: `exec-background-race-${attempt}`,
  470. attributes: { toolCallId: `toolu_background_race_${attempt}` },
  471. } as any,
  472. },
  473. { mode: "auto_on_timeout" },
  474. {
  475. signal: parentTurn.signal,
  476. onEvent: (event) => {
  477. if (event.type === "completed" || event.type === "failed") {
  478. forwardedTerminalEvents += 1;
  479. }
  480. if (event.type === "started" && attempt % 3 === 0) {
  481. queueMicrotask(() => parentTurn.abort());
  482. } else if (event.type === "started" && attempt % 3 === 2) {
  483. setTimeout(() => parentTurn.abort(), 5);
  484. }
  485. },
  486. },
  487. ).then((outcome) => {
  488. outcomeCount += 1;
  489. return outcome;
  490. });
  491. if (result.kind === "backgrounded") {
  492. expect(backgroundTaskIds.has(result.task.taskId)).toBe(false);
  493. backgroundTaskIds.add(result.task.taskId);
  494. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  495. expect(snapshot?.status).toBe("completed");
  496. } else {
  497. expect(["cancelled", "completed"]).toContain(result.result.status);
  498. }
  499. await sleep(5);
  500. expect(outcomeCount).toBe(1);
  501. expect(forwardedTerminalEvents).toBeLessThanOrEqual(1);
  502. }
  503. } finally {
  504. await adapter.close();
  505. await rm(root, { recursive: true, force: true });
  506. }
  507. });
  508. it("stops forwarding foreground progress after auto-backgrounding", async () => {
  509. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-progress-"));
  510. const adapter = new NodeExecutionAdapter({
  511. outputRootDir: root,
  512. progressIntervalMs: 5,
  513. progressThresholdMs: 1,
  514. });
  515. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  516. const progressEvents: ExecutionEvent[] = [];
  517. try {
  518. const result = await capable.runBashWithBackgroundLifecycle!(
  519. {
  520. command: {
  521. mode: "argv",
  522. file: process.execPath,
  523. args: [
  524. "-e",
  525. [
  526. "let writes = 0;",
  527. "const timer = setInterval(() => {",
  528. " process.stdout.write(String(writes));",
  529. " writes += 1;",
  530. " if (writes >= 8) { clearInterval(timer); process.exit(0); }",
  531. "}, 20);",
  532. ].join(""),
  533. ],
  534. },
  535. timeoutMs: 25,
  536. outputLimit: {
  537. persistOutput: "always",
  538. },
  539. trace: {
  540. sessionId: "exec-auto-background-progress-session",
  541. attributes: {
  542. toolCallId: "toolu_auto_background_progress",
  543. },
  544. } as any,
  545. },
  546. { mode: "auto_on_timeout" },
  547. {
  548. onEvent: (event) => {
  549. if (event.type === "progress") progressEvents.push(event);
  550. },
  551. },
  552. );
  553. expect(result.kind).toBe("backgrounded");
  554. const forwardedProgressAfterBackground = progressEvents.length;
  555. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  556. expect(snapshot?.status).toBe("completed");
  557. expect(progressEvents).toHaveLength(forwardedProgressAfterBackground);
  558. } finally {
  559. await adapter.close();
  560. await rm(root, { recursive: true, force: true });
  561. }
  562. });
  563. it("resolves failed snapshots for auto-backgrounded foreground commands", async () => {
  564. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-fail-"));
  565. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  566. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  567. try {
  568. const result = await capable.runBashWithBackgroundLifecycle!(
  569. {
  570. command: {
  571. mode: "argv",
  572. file: process.execPath,
  573. args: [
  574. "-e",
  575. "setTimeout(() => { process.stderr.write('boom'); process.exit(7); }, 60)",
  576. ],
  577. },
  578. timeoutMs: 10,
  579. outputLimit: {
  580. persistOutput: "always",
  581. },
  582. trace: {
  583. sessionId: "exec-auto-background-fail-session",
  584. attributes: {
  585. toolCallId: "toolu_auto_background_fail",
  586. },
  587. } as any,
  588. },
  589. { mode: "auto_on_timeout" },
  590. );
  591. expect(result.kind).toBe("backgrounded");
  592. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  593. expect(snapshot?.status).toBe("failed");
  594. expect(snapshot?.result?.exitCode).toBe(7);
  595. expect(snapshot?.result?.stderr.text).toBe("boom");
  596. } finally {
  597. await adapter.close();
  598. await rm(root, { recursive: true, force: true });
  599. }
  600. });
  601. it("keeps foreground results foreground when commands finish before timeout", async () => {
  602. const adapter = new NodeExecutionAdapter();
  603. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  604. try {
  605. const result = await capable.runBashWithBackgroundLifecycle!(
  606. {
  607. command: {
  608. mode: "argv",
  609. file: process.execPath,
  610. args: ["-e", "process.stdout.write('ok')"],
  611. },
  612. timeoutMs: 1_000,
  613. },
  614. { mode: "auto_on_timeout" },
  615. );
  616. expect(result.kind).toBe("foreground");
  617. expect(result.result.status).toBe("completed");
  618. expect(result.result.stdout.text).toBe("ok");
  619. } finally {
  620. await adapter.close();
  621. }
  622. });
  623. it("removes auto-background output artifacts when foreground completion wins", async () => {
  624. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-cleanup-"));
  625. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  626. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  627. const stdoutPath = join(root, "cleanup-session", "cleanup-tool-stdout.log");
  628. const stderrPath = join(root, "cleanup-session", "cleanup-tool-stderr.log");
  629. try {
  630. const result = await capable.runBashWithBackgroundLifecycle!(
  631. {
  632. command: {
  633. mode: "argv",
  634. file: process.execPath,
  635. args: ["-e", "process.stdout.write('ok')"],
  636. },
  637. timeoutMs: 1_000,
  638. trace: {
  639. sessionId: "cleanup-session",
  640. attributes: {
  641. toolCallId: "cleanup-tool",
  642. },
  643. } as any,
  644. },
  645. { mode: "auto_on_timeout" },
  646. );
  647. expect(result.kind).toBe("foreground");
  648. expect(result.result.stdout.artifactPath).toBeUndefined();
  649. expect(result.result.stderr.artifactPath).toBeUndefined();
  650. await expect(readFile(stdoutPath, "utf8")).rejects.toMatchObject({
  651. code: "ENOENT",
  652. });
  653. await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
  654. code: "ENOENT",
  655. });
  656. } finally {
  657. await adapter.close();
  658. await rm(root, { recursive: true, force: true });
  659. }
  660. });
  661. it("settles foreground completion when redundant artifact cleanup fails", async () => {
  662. const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-cleanup-failure-"));
  663. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  664. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  665. const stdoutPath = join(root, "cleanup-failure-session", "cleanup-failure-tool-stdout.log");
  666. const retainedFile = join(stdoutPath, "retained.log");
  667. vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
  668. await options?.onEvent?.({
  669. type: "started",
  670. pid: 123,
  671. timestamp: new Date(0),
  672. });
  673. await unlink(stdoutPath);
  674. await mkdir(stdoutPath);
  675. await writeFile(retainedFile, "cleanup failed");
  676. return {
  677. status: "completed",
  678. exitCode: 0,
  679. stdout: {
  680. text: "ok",
  681. bytes: 2,
  682. truncated: false,
  683. artifactBytes: 2,
  684. artifactPath: stdoutPath,
  685. artifactTruncated: false,
  686. },
  687. stderr: { text: "", bytes: 0, truncated: false },
  688. durationMs: 1,
  689. timedOut: false,
  690. cancelled: false,
  691. startedAt: new Date(0),
  692. completedAt: new Date(1),
  693. };
  694. });
  695. try {
  696. const result = await capable.runBashWithBackgroundLifecycle!(
  697. {
  698. command: { mode: "argv", file: process.execPath },
  699. timeoutMs: 1_000,
  700. trace: {
  701. sessionId: "cleanup-failure-session",
  702. attributes: { toolCallId: "cleanup-failure-tool" },
  703. } as any,
  704. },
  705. { mode: "auto_on_timeout" },
  706. );
  707. expect(result.kind).toBe("foreground");
  708. expect(result.result.stdout.artifactPath).toBeUndefined();
  709. expect(result.result.stdout.artifactBytes).toBeUndefined();
  710. await expect(readFile(retainedFile, "utf8")).resolves.toBe("cleanup failed");
  711. } finally {
  712. await adapter.close();
  713. await rm(root, { recursive: true, force: true });
  714. }
  715. });
  716. it("settles foreground completion with honest metadata when artifact truncation fails", async () => {
  717. const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-truncate-failure-"));
  718. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  719. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  720. const stdoutPath = join(root, "truncate-failure-session", "truncate-failure-tool-stdout.log");
  721. const retainedFile = join(stdoutPath, "retained.log");
  722. vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
  723. await options?.onEvent?.({
  724. type: "started",
  725. pid: 123,
  726. timestamp: new Date(0),
  727. });
  728. await unlink(stdoutPath);
  729. await mkdir(stdoutPath);
  730. await writeFile(retainedFile, "not truncated");
  731. return {
  732. status: "completed",
  733. exitCode: 0,
  734. stdout: {
  735. text: "ok",
  736. bytes: 2,
  737. truncated: false,
  738. artifactBytes: 13,
  739. artifactPath: stdoutPath,
  740. artifactTruncated: false,
  741. },
  742. stderr: { text: "", bytes: 0, truncated: false },
  743. durationMs: 1,
  744. timedOut: false,
  745. cancelled: false,
  746. startedAt: new Date(0),
  747. completedAt: new Date(1),
  748. };
  749. });
  750. try {
  751. const result = await capable.runBashWithBackgroundLifecycle!(
  752. {
  753. command: { mode: "argv", file: process.execPath },
  754. timeoutMs: 1_000,
  755. outputLimit: {
  756. maxPersistedBytes: 4,
  757. persistOutput: "always",
  758. },
  759. trace: {
  760. sessionId: "truncate-failure-session",
  761. attributes: { toolCallId: "truncate-failure-tool" },
  762. } as any,
  763. },
  764. { mode: "auto_on_timeout" },
  765. );
  766. expect(result.kind).toBe("foreground");
  767. expect(result.result.stdout).toMatchObject({
  768. artifactBytes: 13,
  769. artifactPath: stdoutPath,
  770. artifactTruncated: false,
  771. });
  772. await expect(readFile(retainedFile, "utf8")).resolves.toBe("not truncated");
  773. } finally {
  774. await adapter.close();
  775. await rm(root, { recursive: true, force: true });
  776. }
  777. });
  778. it("keeps explicitly requested foreground output artifacts when foreground completion wins", async () => {
  779. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-preserve-"));
  780. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  781. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  782. const stdoutPath = join(root, "preserve-session", "preserve-tool-stdout.log");
  783. const stderrPath = join(root, "preserve-session", "preserve-tool-stderr.log");
  784. try {
  785. const result = await capable.runBashWithBackgroundLifecycle!(
  786. {
  787. command: {
  788. mode: "argv",
  789. file: process.execPath,
  790. args: ["-e", "process.stdout.write('ok')"],
  791. },
  792. timeoutMs: 1_000,
  793. outputLimit: {
  794. persistOutput: "always",
  795. },
  796. trace: {
  797. sessionId: "preserve-session",
  798. attributes: {
  799. toolCallId: "preserve-tool",
  800. },
  801. } as any,
  802. },
  803. { mode: "auto_on_timeout" },
  804. );
  805. expect(result.kind).toBe("foreground");
  806. expect(result.result.stdout.artifactPath).toBe(stdoutPath);
  807. await expect(readFile(stdoutPath, "utf8")).resolves.toBe("ok");
  808. await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
  809. code: "ENOENT",
  810. });
  811. } finally {
  812. await adapter.close();
  813. await rm(root, { recursive: true, force: true });
  814. }
  815. });
  816. it("does not stop auto-backgrounded commands at the foreground persisted output limit", async () => {
  817. const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-limit-"));
  818. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  819. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  820. try {
  821. const result = await capable.runBashWithBackgroundLifecycle!(
  822. {
  823. command: {
  824. mode: "argv",
  825. file: process.execPath,
  826. args: [
  827. "-e",
  828. [
  829. "let writes = 0;",
  830. "const timer = setInterval(() => {",
  831. " process.stdout.write('x'.repeat(512));",
  832. " writes += 1;",
  833. " if (writes >= 200) { clearInterval(timer); process.exit(0); }",
  834. "}, 1);",
  835. ].join(""),
  836. ],
  837. },
  838. timeoutMs: 20,
  839. outputLimit: {
  840. maxInlineBytes: 0,
  841. maxPersistedBytes: 1_024,
  842. persistOutput: "always",
  843. },
  844. trace: {
  845. sessionId: "limit-session",
  846. attributes: {
  847. toolCallId: "limit-tool",
  848. },
  849. } as any,
  850. },
  851. { mode: "auto_on_timeout" },
  852. );
  853. expect(result.kind).toBe("backgrounded");
  854. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  855. expect(snapshot?.status).toBe("completed");
  856. expect(snapshot?.error).toBeUndefined();
  857. expect(snapshot?.result?.exitCode).toBe(0);
  858. expect(snapshot?.result?.stdout.artifactBytes).toBeGreaterThan(1_024);
  859. expect(snapshot?.result?.stdout.artifactTruncated).toBe(false);
  860. } finally {
  861. await adapter.close();
  862. await rm(root, { recursive: true, force: true });
  863. }
  864. });
  865. it.skipIf(!POSIX_BASH_PATH)(
  866. "stops foreground Bash at the periodic soft limit and removes its oversized file",
  867. async () => {
  868. const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-hard-cap-"));
  869. const adapter = new NodeExecutionAdapter({
  870. outputRootDir: root,
  871. progressIntervalMs: 10,
  872. });
  873. const outputLimit = 1_024;
  874. try {
  875. const result = await adapter.run(
  876. {
  877. command: {
  878. mode: "shell",
  879. command: `${JSON.stringify(process.execPath)} -e ${JSON.stringify("process.stdout.write('x'.repeat(4096)); setInterval(() => {}, 1000)")}`,
  880. shellProfile: "posix-bash",
  881. shellOverride: POSIX_BASH_PATH,
  882. },
  883. timeoutMs: 0,
  884. outputLimit: {
  885. maxInlineBytes: 0,
  886. maxPersistedBytes: outputLimit,
  887. persistOutput: "always",
  888. },
  889. },
  890. {
  891. onPersistedLimit: () => undefined,
  892. shouldStopOnPersistedLimit: () => true,
  893. } as ExecutionRunOptions & {
  894. onPersistedLimit: () => void;
  895. shouldStopOnPersistedLimit: () => boolean;
  896. },
  897. );
  898. expect(result).toMatchObject({
  899. status: "cancelled",
  900. exitCode: 137,
  901. cancelled: true,
  902. error: { type: "output_limit" },
  903. stdout: {
  904. bytes: 4096,
  905. },
  906. });
  907. expect(result.stdout.artifactPath).toBeUndefined();
  908. } finally {
  909. await adapter.close();
  910. await rm(root, { recursive: true, force: true });
  911. }
  912. },
  913. 15_000,
  914. );
  915. it("applies the shared 5GiB watchdog policy after Bash background commit", async () => {
  916. const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-watchdog-"));
  917. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  918. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  919. let capturedRequest: ExecutionRequest | undefined;
  920. let sharesPersistedLimitAcrossStreams = false;
  921. let shouldStopOnPersistedLimit = false;
  922. const runSpy = vi.spyOn(adapter, "run").mockImplementation(async (request, options) => {
  923. capturedRequest = request;
  924. const internalOptions = options as ExecutionRunOptions & {
  925. sharePersistedOutputLimitAcrossStreams?: boolean;
  926. shouldStopOnPersistedLimit?: () => boolean;
  927. };
  928. await options?.onEvent?.({
  929. type: "started",
  930. pid: 123,
  931. timestamp: new Date(0),
  932. });
  933. shouldStopOnPersistedLimit = internalOptions.shouldStopOnPersistedLimit?.() === true;
  934. sharesPersistedLimitAcrossStreams =
  935. internalOptions.sharePersistedOutputLimitAcrossStreams === true;
  936. return {
  937. status: "completed",
  938. exitCode: 0,
  939. stdout: { text: "", bytes: 0, truncated: false },
  940. stderr: { text: "", bytes: 0, truncated: false },
  941. durationMs: 1,
  942. timedOut: false,
  943. cancelled: false,
  944. startedAt: new Date(0),
  945. completedAt: new Date(1),
  946. };
  947. });
  948. try {
  949. const result = await capable.runBashWithBackgroundLifecycle!(
  950. {
  951. command: { mode: "argv", file: process.execPath },
  952. timeoutMs: 5,
  953. outputLimit: {
  954. killProcessOnPersistedLimit: true,
  955. maxPersistedBytes: 1_024,
  956. persistOutput: "on_truncate",
  957. },
  958. },
  959. { mode: "explicit" },
  960. );
  961. expect(result.kind).toBe("backgrounded");
  962. expect(capturedRequest?.timeoutMs).toBe(0);
  963. expect(capturedRequest?.outputLimit).toMatchObject({
  964. killProcessOnPersistedLimit: false,
  965. maxPersistedBytes: 5 * 1024 * 1024 * 1024,
  966. persistOutput: "always",
  967. });
  968. expect(sharesPersistedLimitAcrossStreams).toBe(true);
  969. expect(shouldStopOnPersistedLimit).toBe(true);
  970. expect(runSpy).toHaveBeenCalledTimes(1);
  971. } finally {
  972. await adapter.close();
  973. await rm(root, { recursive: true, force: true });
  974. }
  975. });
  976. it("normalizes a background Bash output-limit stop to killed exit 137 semantics", async () => {
  977. const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-limit-result-"));
  978. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  979. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  980. vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
  981. const internalOptions = options as ExecutionRunOptions & {
  982. onPersistedLimit?: () => void;
  983. };
  984. await options?.onEvent?.({
  985. type: "started",
  986. pid: 123,
  987. timestamp: new Date(0),
  988. });
  989. internalOptions.onPersistedLimit?.();
  990. return {
  991. status: "failed",
  992. exitCode: 0,
  993. stdout: {
  994. text: "",
  995. bytes: 5 * 1024 * 1024 * 1024 + 1,
  996. truncated: true,
  997. },
  998. stderr: { text: "", bytes: 0, truncated: false },
  999. durationMs: 1,
  1000. timedOut: false,
  1001. cancelled: false,
  1002. startedAt: new Date(0),
  1003. completedAt: new Date(1),
  1004. };
  1005. });
  1006. try {
  1007. const result = await capable.runBashWithBackgroundLifecycle!(
  1008. {
  1009. command: { mode: "argv", file: process.execPath },
  1010. outputLimit: { persistOutput: "always" },
  1011. },
  1012. { mode: "explicit" },
  1013. );
  1014. expect(result.kind).toBe("backgrounded");
  1015. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  1016. expect(snapshot?.result).toMatchObject({
  1017. status: "cancelled",
  1018. cancelled: true,
  1019. timedOut: false,
  1020. exitCode: 137,
  1021. error: {
  1022. type: "output_limit",
  1023. message: "Background command killed: output file exceeded 5GB",
  1024. },
  1025. });
  1026. } finally {
  1027. await adapter.close();
  1028. await rm(root, { recursive: true, force: true });
  1029. }
  1030. });
  1031. it.skipIf(!POSIX_BASH_PATH)(
  1032. "does not apply the runtime soft limit before its first check and retains the full foreground file",
  1033. async () => {
  1034. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-final-limit-"));
  1035. const adapter = new NodeExecutionAdapter({
  1036. outputRootDir: root,
  1037. progressIntervalMs: 60_000,
  1038. });
  1039. let persistedLimitNotified = false;
  1040. try {
  1041. const result = await adapter.run(
  1042. {
  1043. command: {
  1044. mode: "shell",
  1045. command: "printf abc",
  1046. shellProfile: "posix-bash",
  1047. shellOverride: POSIX_BASH_PATH,
  1048. },
  1049. timeoutMs: 0,
  1050. outputLimit: {
  1051. maxInlineBytes: 1,
  1052. maxPersistedBytes: 2,
  1053. maxArtifactBytes: 1,
  1054. persistOutput: "on_truncate",
  1055. },
  1056. },
  1057. {
  1058. onPersistedLimit: () => {
  1059. persistedLimitNotified = true;
  1060. },
  1061. shouldStopOnPersistedLimit: () => false,
  1062. } as ExecutionRunOptions & {
  1063. onPersistedLimit: () => void;
  1064. shouldStopOnPersistedLimit: () => boolean;
  1065. },
  1066. );
  1067. expect(result).toMatchObject({
  1068. status: "completed",
  1069. exitCode: 0,
  1070. timedOut: false,
  1071. cancelled: false,
  1072. stdout: {
  1073. bytes: 3,
  1074. text: "a",
  1075. artifactBytes: 3,
  1076. artifactTruncated: false,
  1077. },
  1078. });
  1079. expect(result.error).toBeUndefined();
  1080. expect(persistedLimitNotified).toBe(false);
  1081. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
  1082. } finally {
  1083. await adapter.close();
  1084. await rm(root, { recursive: true, force: true });
  1085. }
  1086. },
  1087. );
  1088. it.skipIf(!POSIX_BASH_PATH)(
  1089. "ignores the legacy Bash artifact cap after lifecycle completion",
  1090. async () => {
  1091. const root = await mkdtemp(join(tmpdir(), "zcode-exec-lifecycle-artifact-cap-"));
  1092. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  1093. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  1094. try {
  1095. const result = await capable.runBashWithBackgroundLifecycle!(
  1096. {
  1097. command: {
  1098. mode: "shell",
  1099. command: "printf abc",
  1100. shellProfile: "posix-bash",
  1101. shellOverride: POSIX_BASH_PATH,
  1102. },
  1103. timeoutMs: 1_000,
  1104. outputLimit: {
  1105. maxInlineBytes: 0,
  1106. maxPersistedBytes: 100,
  1107. maxArtifactBytes: 1,
  1108. persistOutput: "always",
  1109. },
  1110. trace: {
  1111. sessionId: "lifecycle-artifact-cap-session",
  1112. attributes: { toolCallId: "lifecycle-artifact-cap-tool" },
  1113. } as any,
  1114. },
  1115. { mode: "auto_on_timeout" },
  1116. );
  1117. expect(result.kind).toBe("foreground");
  1118. expect(result.result).toMatchObject({
  1119. status: "completed",
  1120. stdout: {
  1121. bytes: 3,
  1122. artifactBytes: 3,
  1123. artifactTruncated: false,
  1124. },
  1125. });
  1126. await expect(readFile(result.result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
  1127. } finally {
  1128. await adapter.close();
  1129. await rm(root, { recursive: true, force: true });
  1130. }
  1131. },
  1132. );
  1133. it.skipIf(!POSIX_BASH_PATH)(
  1134. "stops watching at root exit even when descendants later exceed the soft limit",
  1135. async () => {
  1136. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-retained-output-limit-"));
  1137. const adapter = new NodeExecutionAdapter({
  1138. outputRootDir: root,
  1139. progressIntervalMs: 10,
  1140. progressThresholdMs: 0,
  1141. });
  1142. try {
  1143. const result = await adapter.run(
  1144. {
  1145. command: {
  1146. mode: "shell",
  1147. command: "(sleep 0.05; printf 0123456789; sleep 1) & printf x",
  1148. shellProfile: "posix-bash",
  1149. shellOverride: POSIX_BASH_PATH,
  1150. },
  1151. timeoutMs: 0,
  1152. outputLimit: {
  1153. killProcessOnPersistedLimit: true,
  1154. maxInlineBytes: 30_000,
  1155. maxPersistedBytes: 3,
  1156. persistOutput: "always",
  1157. },
  1158. },
  1159. {
  1160. shouldRetainExecutionAfterRootExit: () => true,
  1161. } as ExecutionRunOptions & {
  1162. shouldRetainExecutionAfterRootExit: () => boolean;
  1163. },
  1164. );
  1165. expect(result.status).toBe("completed");
  1166. expect(result.error).toBeUndefined();
  1167. expect(result.stdout.text).toBe("x");
  1168. await sleep(1_200);
  1169. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("x0123456789");
  1170. } finally {
  1171. await adapter.close();
  1172. await rm(root, { recursive: true, force: true });
  1173. }
  1174. },
  1175. );
  1176. it("runs argv commands without a shell and streams output events", async () => {
  1177. const adapter = new NodeExecutionAdapter();
  1178. const events: ExecutionEvent[] = [];
  1179. const result = await adapter.run(
  1180. {
  1181. command: {
  1182. mode: "argv",
  1183. file: process.execPath,
  1184. args: ["-e", "process.stdout.write('ok')"],
  1185. },
  1186. },
  1187. {
  1188. onEvent: (event) => {
  1189. events.push(event);
  1190. },
  1191. },
  1192. );
  1193. expect(result.status).toBe("completed");
  1194. expect(result.exitCode).toBe(0);
  1195. expect(result.stdout.text).toBe("ok");
  1196. expect(events[0]?.type).toBe("started");
  1197. expect(events.some((event) => event.type === "stdout")).toBe(true);
  1198. expect(events.at(-1)?.type).toBe("completed");
  1199. });
  1200. it("captures final cwd for successful foreground shell commands when requested", async () => {
  1201. const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-"));
  1202. const child = join(root, " child with spaces ");
  1203. await mkdir(child);
  1204. try {
  1205. const adapter = new NodeExecutionAdapter();
  1206. const result = await adapter.run({
  1207. command: {
  1208. mode: "shell",
  1209. command: `cd ${JSON.stringify(child)}`,
  1210. },
  1211. cwd: root,
  1212. captureCwdAfterSuccess: true,
  1213. });
  1214. expect(result.status).toBe("completed");
  1215. expect(result.exitCode).toBe(0);
  1216. expect(result.resolvedCwd).toBe(await realpath(child));
  1217. } finally {
  1218. await rm(root, { recursive: true, force: true });
  1219. }
  1220. });
  1221. it.skipIf(process.platform !== "win32")(
  1222. "captures final cwd for Windows cmd shell commands when requested",
  1223. async () => {
  1224. const root = await mkdtemp(join(tmpdir(), "zcode-exec-win-cwd-"));
  1225. const child = join(root, "child");
  1226. await mkdir(child);
  1227. try {
  1228. const adapter = new NodeExecutionAdapter();
  1229. const result = await adapter.run({
  1230. command: {
  1231. mode: "shell",
  1232. command: `cd /d "${child}"`,
  1233. },
  1234. cwd: root,
  1235. captureCwdAfterSuccess: true,
  1236. });
  1237. expect(result.status).toBe("completed");
  1238. expect(result.exitCode).toBe(0);
  1239. expect(result.resolvedCwd).toBe(await realpath(child));
  1240. } finally {
  1241. await rm(root, { recursive: true, force: true });
  1242. }
  1243. },
  1244. );
  1245. it("does not capture cwd for generic shell commands by default", async () => {
  1246. const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-default-"));
  1247. const child = join(root, "child");
  1248. await mkdir(child);
  1249. try {
  1250. const adapter = new NodeExecutionAdapter();
  1251. const result = await adapter.run({
  1252. command: {
  1253. mode: "shell",
  1254. command: `cd ${JSON.stringify(child)}`,
  1255. },
  1256. cwd: root,
  1257. });
  1258. expect(result.status).toBe("completed");
  1259. expect(result.exitCode).toBe(0);
  1260. expect(result.resolvedCwd).toBeUndefined();
  1261. } finally {
  1262. await rm(root, { recursive: true, force: true });
  1263. }
  1264. });
  1265. it("does not capture cwd when the shell command exits non-zero", async () => {
  1266. const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-fail-"));
  1267. const child = join(root, "child");
  1268. await mkdir(child);
  1269. try {
  1270. const adapter = new NodeExecutionAdapter();
  1271. const result = await adapter.run({
  1272. command: {
  1273. mode: "shell",
  1274. command: `cd ${JSON.stringify(child)}; false`,
  1275. },
  1276. cwd: root,
  1277. captureCwdAfterSuccess: true,
  1278. });
  1279. expect(result.status).toBe("failed");
  1280. expect(result.exitCode).toBe(1);
  1281. expect(result.resolvedCwd).toBeUndefined();
  1282. } finally {
  1283. await rm(root, { recursive: true, force: true });
  1284. }
  1285. });
  1286. it.skipIf(!POSIX_BASH_PATH)(
  1287. "runs posix-bash shell profile commands with bash/zsh syntax",
  1288. async () => {
  1289. const root = await mkdtemp(join(tmpdir(), "zcode-exec-posix-bash-"));
  1290. const home = join(root, "home");
  1291. await mkdir(home, { recursive: true });
  1292. try {
  1293. const adapter = new NodeExecutionAdapter({
  1294. outputRootDir: root,
  1295. processEnv: {
  1296. ...process.env,
  1297. HOME: home,
  1298. SHELL: POSIX_BASH_PATH!,
  1299. },
  1300. });
  1301. const result = await adapter.run({
  1302. command: {
  1303. mode: "shell",
  1304. command: "cat <(printf ok)",
  1305. shellProfile: "posix-bash",
  1306. shellOverride: {
  1307. dialect: "posix",
  1308. display: { name: "bash" },
  1309. path: POSIX_BASH_PATH!,
  1310. source: "auto-detected",
  1311. },
  1312. },
  1313. });
  1314. expect(result.status).toBe("completed");
  1315. expect(result.exitCode).toBe(0);
  1316. expect(result.stdout.text).toBe("ok");
  1317. } finally {
  1318. await rm(root, { recursive: true, force: true });
  1319. }
  1320. },
  1321. );
  1322. it.skipIf(!POSIX_BASH_PATH)(
  1323. "creates shell init snapshots with login shell and runs user commands without login",
  1324. async () => {
  1325. const root = await mkdtemp(join(tmpdir(), "zcode-exec-login-mode-"));
  1326. const home = join(root, "home");
  1327. const bin = join(root, "bin");
  1328. const shellLog = join(root, "shell-args.log");
  1329. const shellWrapper = join(bin, "bash-wrapper");
  1330. await mkdir(home, { recursive: true });
  1331. await mkdir(bin, { recursive: true });
  1332. await writeFile(
  1333. shellWrapper,
  1334. [
  1335. "#!/usr/bin/env bash",
  1336. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1337. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1338. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1339. "",
  1340. ].join("\n"),
  1341. { mode: 0o755 },
  1342. );
  1343. try {
  1344. const adapter = new NodeExecutionAdapter({
  1345. outputRootDir: root,
  1346. processEnv: {
  1347. ...process.env,
  1348. HOME: home,
  1349. SHELL: shellWrapper,
  1350. ZCODE_TEST_SHELL_LOG: shellLog,
  1351. },
  1352. });
  1353. const result = await adapter.run({
  1354. command: {
  1355. mode: "shell",
  1356. command: 'shopt -q login_shell; rc=$?; printf "%s" "$rc"',
  1357. shellProfile: "posix-bash",
  1358. shellOverride: {
  1359. dialect: "posix",
  1360. display: { name: "bash" },
  1361. path: shellWrapper,
  1362. source: "auto-detected",
  1363. },
  1364. },
  1365. });
  1366. expect(result.status).toBe("completed");
  1367. expect(result.exitCode).toBe(0);
  1368. expect(result.stdout.text).toBe("1");
  1369. const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
  1370. expect(invocations[0]).toContain("-c -l");
  1371. expect(invocations.at(-1)).toMatch(/^-c /u);
  1372. expect(invocations.at(-1)).not.toContain("-l ");
  1373. } finally {
  1374. await rm(root, { recursive: true, force: true });
  1375. }
  1376. },
  1377. );
  1378. it.skipIf(!POSIX_BASH_PATH)(
  1379. "injects embedded search prelude into posix-bash shell profile commands",
  1380. async () => {
  1381. const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-"));
  1382. const home = join(root, "home");
  1383. await mkdir(home, { recursive: true });
  1384. const shimScript = [
  1385. "if (process.argv[1] !== 'grep') process.exit(11);",
  1386. "process.stdout.write(`shim:${process.argv.slice(2).join('|')}`);",
  1387. ].join("");
  1388. try {
  1389. const adapter = new NodeExecutionAdapter({
  1390. outputRootDir: root,
  1391. processEnv: {
  1392. ...process.env,
  1393. HOME: home,
  1394. SHELL: POSIX_BASH_PATH!,
  1395. },
  1396. });
  1397. const result = await adapter.run({
  1398. command: {
  1399. mode: "shell",
  1400. command: "grep needle file.txt",
  1401. shellProfile: "posix-bash",
  1402. shellOverride: {
  1403. dialect: "posix",
  1404. display: { name: "bash" },
  1405. path: POSIX_BASH_PATH!,
  1406. source: "auto-detected",
  1407. },
  1408. },
  1409. bashPrelude: {
  1410. kind: "embedded-search",
  1411. backend: {
  1412. kind: "internal-cli",
  1413. command: process.execPath,
  1414. args: ["-e", shimScript],
  1415. },
  1416. },
  1417. });
  1418. expect(result.status).toBe("completed");
  1419. expect(result.exitCode).toBe(0);
  1420. expect(result.stdout.text).toBe("shim:needle|file.txt");
  1421. } finally {
  1422. await rm(root, { recursive: true, force: true });
  1423. }
  1424. },
  1425. );
  1426. it.skipIf(!POSIX_BASH_PATH)(
  1427. "falls back to native grep when embedded search backend is unavailable and preserves stdin",
  1428. async () => {
  1429. const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-fallback-"));
  1430. const home = join(root, "home");
  1431. await mkdir(home, { recursive: true });
  1432. try {
  1433. const adapter = new NodeExecutionAdapter({
  1434. outputRootDir: root,
  1435. processEnv: {
  1436. ...process.env,
  1437. HOME: home,
  1438. SHELL: POSIX_BASH_PATH!,
  1439. },
  1440. });
  1441. const result = await adapter.run({
  1442. command: {
  1443. mode: "shell",
  1444. command: "printf 'before\\nneedle from stdin\\nafter\\n' | grep needle",
  1445. shellProfile: "posix-bash",
  1446. shellOverride: {
  1447. dialect: "posix",
  1448. display: { name: "bash" },
  1449. path: POSIX_BASH_PATH!,
  1450. source: "auto-detected",
  1451. },
  1452. },
  1453. bashPrelude: {
  1454. kind: "embedded-search",
  1455. backend: {
  1456. kind: "internal-cli",
  1457. command: join(root, "missing-zcode"),
  1458. args: ["__internal-search"],
  1459. },
  1460. },
  1461. });
  1462. expect(result.status).toBe("completed");
  1463. expect(result.exitCode).toBe(0);
  1464. expect(result.stdout.text).toBe("needle from stdin\n");
  1465. } finally {
  1466. await rm(root, { recursive: true, force: true });
  1467. }
  1468. },
  1469. );
  1470. it.skipIf(!POSIX_BASH_PATH)(
  1471. "sources shell init snapshot and skips login for the user command after creation",
  1472. async () => {
  1473. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-integration-"));
  1474. const home = join(root, "home");
  1475. const bin = join(root, "bin");
  1476. const shellLog = join(root, "shell-args.log");
  1477. const shellWrapper = join(bin, "bash-wrapper");
  1478. await mkdir(home, { recursive: true });
  1479. await mkdir(bin, { recursive: true });
  1480. await writeFile(
  1481. join(home, ".bashrc"),
  1482. "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
  1483. );
  1484. await writeFile(
  1485. shellWrapper,
  1486. [
  1487. "#!/usr/bin/env bash",
  1488. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1489. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1490. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1491. "",
  1492. ].join("\n"),
  1493. { mode: 0o755 },
  1494. );
  1495. try {
  1496. const adapter = new NodeExecutionAdapter({
  1497. outputRootDir: root,
  1498. processEnv: {
  1499. ...process.env,
  1500. HOME: home,
  1501. SHELL: shellWrapper,
  1502. ZCODE_TEST_SHELL_LOG: shellLog,
  1503. },
  1504. });
  1505. const result = await adapter.run({
  1506. command: {
  1507. mode: "shell",
  1508. command: "zcode_snapshot_alias",
  1509. shellProfile: "posix-bash",
  1510. shellOverride: {
  1511. dialect: "posix",
  1512. display: { name: "bash" },
  1513. path: shellWrapper,
  1514. source: "auto-detected",
  1515. },
  1516. },
  1517. trace: {
  1518. sessionId: "shell-init-session",
  1519. },
  1520. });
  1521. expect(result.status).toBe("completed");
  1522. expect(result.exitCode).toBe(0);
  1523. expect(result.stdout.text).toBe("alias-from-snapshot");
  1524. const log = await readFile(shellLog, "utf8");
  1525. const invocations = log.trim().split("\n");
  1526. expect(invocations[0]).toContain("-c -l");
  1527. expect(invocations.at(-1)).toMatch(/^-c /u);
  1528. expect(invocations.at(-1)).not.toContain("-l ");
  1529. const snapshotSessionDir = join(root, "shell-snapshots");
  1530. const beforeClose = await readdir(snapshotSessionDir);
  1531. expect(beforeClose.some((file) => file.endsWith(".sh"))).toBe(true);
  1532. await adapter.close();
  1533. const afterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
  1534. if (
  1535. typeof error === "object" &&
  1536. error !== null &&
  1537. "code" in error &&
  1538. error.code === "ENOENT"
  1539. ) {
  1540. return [];
  1541. }
  1542. throw error;
  1543. });
  1544. expect(afterClose).toEqual([]);
  1545. } finally {
  1546. await rm(root, { recursive: true, force: true });
  1547. }
  1548. },
  1549. );
  1550. it.skipIf(!POSIX_BASH_PATH)(
  1551. "creates shell init snapshots with the resolved shell environment",
  1552. async () => {
  1553. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-env-"));
  1554. const home = join(root, "home");
  1555. const bin = join(root, "bin");
  1556. const shellWrapper = join(bin, "bash-wrapper");
  1557. await mkdir(home, { recursive: true });
  1558. await mkdir(bin, { recursive: true });
  1559. await writeFile(
  1560. join(home, ".bashrc"),
  1561. [
  1562. 'if [ "$SHELL" = "$ZCODE_EXPECTED_SHELL" ] && [ "$GIT_EDITOR" = "true" ]; then',
  1563. " alias zcode_env_overlay_alias='printf env-overlay-ok'",
  1564. "fi",
  1565. "",
  1566. ].join("\n"),
  1567. );
  1568. await writeFile(
  1569. shellWrapper,
  1570. ["#!/usr/bin/env bash", `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`, ""].join("\n"),
  1571. { mode: 0o755 },
  1572. );
  1573. try {
  1574. const adapter = new NodeExecutionAdapter({
  1575. outputRootDir: root,
  1576. processEnv: {
  1577. ...process.env,
  1578. GIT_EDITOR: "stale-editor",
  1579. HOME: home,
  1580. SHELL: "/bin/fish",
  1581. ZCODE_EXPECTED_SHELL: shellWrapper,
  1582. },
  1583. });
  1584. const result = await adapter.run({
  1585. command: {
  1586. mode: "shell",
  1587. command: "zcode_env_overlay_alias",
  1588. shellProfile: "posix-bash",
  1589. shellOverride: {
  1590. dialect: "posix",
  1591. display: { name: "bash" },
  1592. path: shellWrapper,
  1593. source: "auto-detected",
  1594. },
  1595. },
  1596. trace: {
  1597. sessionId: "shell-init-session",
  1598. },
  1599. });
  1600. expect(result.status).toBe("completed");
  1601. expect(result.exitCode).toBe(0);
  1602. expect(result.stdout.text).toBe("env-overlay-ok");
  1603. } finally {
  1604. await rm(root, { recursive: true, force: true });
  1605. }
  1606. },
  1607. );
  1608. it.skipIf(!POSIX_BASH_PATH)(
  1609. "falls back to login shell when a cached shell init snapshot file is missing",
  1610. async () => {
  1611. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-missing-"));
  1612. const home = join(root, "home");
  1613. const bin = join(root, "bin");
  1614. const shellLog = join(root, "shell-args.log");
  1615. const shellWrapper = join(bin, "bash-wrapper");
  1616. await mkdir(home, { recursive: true });
  1617. await mkdir(bin, { recursive: true });
  1618. await writeFile(
  1619. join(home, ".bashrc"),
  1620. "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
  1621. );
  1622. await writeFile(
  1623. shellWrapper,
  1624. [
  1625. "#!/usr/bin/env bash",
  1626. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1627. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1628. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1629. "",
  1630. ].join("\n"),
  1631. { mode: 0o755 },
  1632. );
  1633. try {
  1634. const adapter = new NodeExecutionAdapter({
  1635. outputRootDir: root,
  1636. processEnv: {
  1637. ...process.env,
  1638. HOME: home,
  1639. SHELL: shellWrapper,
  1640. ZCODE_TEST_SHELL_LOG: shellLog,
  1641. },
  1642. });
  1643. const first = await adapter.run({
  1644. command: {
  1645. mode: "shell",
  1646. command: "zcode_snapshot_alias",
  1647. shellProfile: "posix-bash",
  1648. shellOverride: {
  1649. dialect: "posix",
  1650. display: { name: "bash" },
  1651. path: shellWrapper,
  1652. source: "auto-detected",
  1653. },
  1654. },
  1655. trace: {
  1656. sessionId: "shell-init-session",
  1657. },
  1658. });
  1659. expect(first.status).toBe("completed");
  1660. expect(first.stdout.text).toBe("alias-from-snapshot");
  1661. const snapshotSessionDir = join(root, "shell-snapshots");
  1662. const snapshotFiles = await readdir(snapshotSessionDir);
  1663. const snapshotFile = snapshotFiles.find((file) => file.endsWith(".sh"));
  1664. expect(snapshotFile).toBeDefined();
  1665. await unlink(join(snapshotSessionDir, snapshotFile!));
  1666. const second = await adapter.run({
  1667. command: {
  1668. mode: "shell",
  1669. command: "printf second-ok",
  1670. shellProfile: "posix-bash",
  1671. shellOverride: {
  1672. dialect: "posix",
  1673. display: { name: "bash" },
  1674. path: shellWrapper,
  1675. source: "auto-detected",
  1676. },
  1677. },
  1678. trace: {
  1679. sessionId: "shell-init-session",
  1680. },
  1681. });
  1682. expect(second.status).toBe("completed");
  1683. expect(second.stdout.text).toBe("second-ok");
  1684. const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
  1685. expect(invocations[0]).toContain("-c -l");
  1686. expect(invocations[1]).toMatch(/^-c /u);
  1687. expect(invocations[1]).not.toContain("-l ");
  1688. expect(invocations[2]).toContain("-c -l");
  1689. } finally {
  1690. await rm(root, { recursive: true, force: true });
  1691. }
  1692. },
  1693. );
  1694. it.skipIf(!POSIX_BASH_PATH)(
  1695. "does not spawn the user command when closing during shell init snapshot creation",
  1696. async () => {
  1697. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-close-"));
  1698. const bin = join(root, "bin");
  1699. const shellLog = join(root, "shell-args.log");
  1700. const shellWrapper = join(bin, "bash-wrapper");
  1701. await mkdir(bin, { recursive: true });
  1702. await writeFile(
  1703. shellWrapper,
  1704. [
  1705. "#!/usr/bin/env bash",
  1706. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1707. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1708. "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
  1709. " sleep 0.2",
  1710. "fi",
  1711. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1712. "",
  1713. ].join("\n"),
  1714. { mode: 0o755 },
  1715. );
  1716. try {
  1717. const adapter = new NodeExecutionAdapter({
  1718. outputRootDir: root,
  1719. processEnv: {
  1720. ...process.env,
  1721. SHELL: shellWrapper,
  1722. ZCODE_TEST_SHELL_LOG: shellLog,
  1723. },
  1724. });
  1725. const runPromise = adapter.run({
  1726. command: {
  1727. mode: "shell",
  1728. command: "printf user-command-ran",
  1729. shellProfile: "posix-bash",
  1730. shellOverride: {
  1731. dialect: "posix",
  1732. display: { name: "bash" },
  1733. path: shellWrapper,
  1734. source: "auto-detected",
  1735. },
  1736. },
  1737. trace: {
  1738. sessionId: "shell-init-session",
  1739. },
  1740. });
  1741. await sleep(50);
  1742. await adapter.close();
  1743. const result = await runPromise;
  1744. expect(result.status).toBe("cancelled");
  1745. expect(result.stdout.text).toBe("");
  1746. const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
  1747. expect(invocations).toHaveLength(1);
  1748. expect(invocations[0]).toContain("-c -l");
  1749. expect(invocations[0]).toContain("SNAPSHOT_FILE=");
  1750. const snapshotSessionDir = join(root, "shell-snapshots");
  1751. const snapshotsAfterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
  1752. if (
  1753. typeof error === "object" &&
  1754. error !== null &&
  1755. "code" in error &&
  1756. error.code === "ENOENT"
  1757. ) {
  1758. return [];
  1759. }
  1760. throw error;
  1761. });
  1762. expect(snapshotsAfterClose).toEqual([]);
  1763. } finally {
  1764. await rm(root, { recursive: true, force: true });
  1765. }
  1766. },
  1767. );
  1768. it.skipIf(!POSIX_BASH_PATH)(
  1769. "does not spawn the user command when aborted during shell init snapshot creation",
  1770. async () => {
  1771. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-abort-"));
  1772. const bin = join(root, "bin");
  1773. const shellLog = join(root, "shell-args.log");
  1774. const shellWrapper = join(bin, "bash-wrapper");
  1775. await mkdir(bin, { recursive: true });
  1776. await writeFile(
  1777. shellWrapper,
  1778. [
  1779. "#!/usr/bin/env bash",
  1780. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1781. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1782. "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
  1783. " sleep 0.2",
  1784. "fi",
  1785. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1786. "",
  1787. ].join("\n"),
  1788. { mode: 0o755 },
  1789. );
  1790. try {
  1791. const adapter = new NodeExecutionAdapter({
  1792. outputRootDir: root,
  1793. processEnv: {
  1794. ...process.env,
  1795. SHELL: shellWrapper,
  1796. ZCODE_TEST_SHELL_LOG: shellLog,
  1797. },
  1798. });
  1799. const controller = new AbortController();
  1800. const runPromise = adapter.run(
  1801. {
  1802. command: {
  1803. mode: "shell",
  1804. command: "printf user-command-ran",
  1805. shellProfile: "posix-bash",
  1806. shellOverride: {
  1807. dialect: "posix",
  1808. display: { name: "bash" },
  1809. path: shellWrapper,
  1810. source: "auto-detected",
  1811. },
  1812. },
  1813. trace: {
  1814. sessionId: "shell-init-session",
  1815. },
  1816. },
  1817. { signal: controller.signal },
  1818. );
  1819. await sleep(50);
  1820. controller.abort();
  1821. const result = await runPromise;
  1822. expect(result.status).toBe("cancelled");
  1823. expect(result.stdout.text).toBe("");
  1824. const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
  1825. expect(invocations).toHaveLength(1);
  1826. expect(invocations[0]).toContain("-c -l");
  1827. expect(invocations[0]).toContain("SNAPSHOT_FILE=");
  1828. await adapter.close();
  1829. } finally {
  1830. await rm(root, { recursive: true, force: true });
  1831. }
  1832. },
  1833. );
  1834. it.skipIf(!POSIX_BASH_PATH)(
  1835. "falls back to login shell when shell init snapshot creation fails",
  1836. async () => {
  1837. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-fallback-"));
  1838. const bin = join(root, "bin");
  1839. const shellLog = join(root, "shell-args.log");
  1840. const shellWrapper = join(bin, "bash-wrapper");
  1841. await mkdir(bin, { recursive: true });
  1842. await writeFile(
  1843. shellWrapper,
  1844. [
  1845. "#!/usr/bin/env bash",
  1846. 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
  1847. "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
  1848. "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
  1849. " exit 42",
  1850. "fi",
  1851. `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
  1852. "",
  1853. ].join("\n"),
  1854. { mode: 0o755 },
  1855. );
  1856. try {
  1857. const adapter = new NodeExecutionAdapter({
  1858. outputRootDir: root,
  1859. processEnv: {
  1860. ...process.env,
  1861. SHELL: shellWrapper,
  1862. ZCODE_TEST_SHELL_LOG: shellLog,
  1863. },
  1864. });
  1865. const result = await adapter.run({
  1866. command: {
  1867. mode: "shell",
  1868. command: "printf fallback-ok",
  1869. shellProfile: "posix-bash",
  1870. shellOverride: {
  1871. dialect: "posix",
  1872. display: { name: "bash" },
  1873. path: shellWrapper,
  1874. source: "auto-detected",
  1875. },
  1876. },
  1877. trace: {
  1878. sessionId: "shell-init-session",
  1879. },
  1880. });
  1881. expect(result.status).toBe("completed");
  1882. expect(result.stdout.text).toBe("fallback-ok");
  1883. const log = await readFile(shellLog, "utf8");
  1884. const invocations = log.trim().split("\n");
  1885. expect(invocations[0]).toContain("-c -l");
  1886. expect(invocations.at(-1)).toContain("-c -l");
  1887. } finally {
  1888. await rm(root, { recursive: true, force: true });
  1889. }
  1890. },
  1891. );
  1892. it.skipIf(!POSIX_BASH_PATH)(
  1893. "keeps cwd capture after shell init snapshot source commands",
  1894. async () => {
  1895. const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-cwd-"));
  1896. const home = join(root, "home");
  1897. const child = join(root, "child");
  1898. await mkdir(home, { recursive: true });
  1899. await mkdir(child, { recursive: true });
  1900. await writeFile(join(home, ".bashrc"), 'zcode_cd_child() { cd "$ZCODE_TEST_CHILD"; }\n');
  1901. try {
  1902. const adapter = new NodeExecutionAdapter({
  1903. outputRootDir: root,
  1904. processEnv: {
  1905. ...process.env,
  1906. HOME: home,
  1907. SHELL: POSIX_BASH_PATH!,
  1908. ZCODE_TEST_CHILD: child,
  1909. },
  1910. });
  1911. const result = await adapter.run({
  1912. command: {
  1913. mode: "shell",
  1914. command: "zcode_cd_child",
  1915. shellProfile: "posix-bash",
  1916. shellOverride: {
  1917. dialect: "posix",
  1918. display: { name: "bash" },
  1919. path: POSIX_BASH_PATH!,
  1920. source: "auto-detected",
  1921. },
  1922. },
  1923. captureCwdAfterSuccess: true,
  1924. cwd: root,
  1925. trace: {
  1926. sessionId: "shell-init-session",
  1927. },
  1928. });
  1929. expect(result.status).toBe("completed");
  1930. expect(result.exitCode).toBe(0);
  1931. expect(result.resolvedCwd).toBe(await realpath(child));
  1932. } finally {
  1933. await rm(root, { recursive: true, force: true });
  1934. }
  1935. },
  1936. );
  1937. it.skipIf(!POSIX_BASH_PATH)(
  1938. "runs posix-bash shell profile commands with bash-specific syntax when bash is the user shell",
  1939. async () => {
  1940. const adapter = new NodeExecutionAdapter({
  1941. processEnv: {
  1942. ...process.env,
  1943. SHELL: POSIX_BASH_PATH ?? "/bin/bash",
  1944. },
  1945. });
  1946. const result = await adapter.run({
  1947. command: {
  1948. mode: "shell",
  1949. command: [
  1950. "arr=(a b)",
  1951. "printf '%s\\n' \"${arr[1]}\"",
  1952. "false | true",
  1953. "printf '%s\\n' \"${PIPESTATUS[0]} ${PIPESTATUS[1]}\"",
  1954. "[[ -n x ]] && printf '%s\\n' ok",
  1955. ].join("\n"),
  1956. shellProfile: "posix-bash",
  1957. },
  1958. });
  1959. expect(result.status).toBe("completed");
  1960. expect(result.exitCode).toBe(0);
  1961. expect(result.stdout.text).toBe("b\n1 0\nok\n");
  1962. },
  1963. );
  1964. it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
  1965. "runs Bash syntax through Git Bash on Windows",
  1966. async () => {
  1967. const adapter = new NodeExecutionAdapter();
  1968. const result = await adapter.run({
  1969. command: {
  1970. mode: "shell",
  1971. shellProfile: "posix-bash",
  1972. command: [
  1973. "arr=(a b)",
  1974. "printf 'array=%s\\n' \"${arr[1]}\"",
  1975. "cat <(printf process)",
  1976. ].join("\n"),
  1977. },
  1978. captureCwdAfterSuccess: true,
  1979. timeoutMs: 5000,
  1980. });
  1981. expect(result.status).toBe("completed");
  1982. expect(result.stdout.text).toContain("array=b");
  1983. expect(result.stdout.text).toContain("process");
  1984. },
  1985. );
  1986. it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
  1987. "writes Windows Git Bash stdout and stderr directly to one canonical output",
  1988. async () => {
  1989. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-git-bash-merged-"));
  1990. const adapter = new NodeExecutionAdapter({ outputRootDir });
  1991. try {
  1992. const result = await adapter.run({
  1993. command: {
  1994. mode: "shell",
  1995. shellProfile: "posix-bash",
  1996. command:
  1997. "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
  1998. },
  1999. outputLimit: {
  2000. maxInlineBytes: 30_000,
  2001. maxPersistedBytes: 64 * 1024 * 1024,
  2002. persistOutput: "always",
  2003. },
  2004. trace: {
  2005. sessionId: "git-bash-merged-session",
  2006. attributes: { toolCallId: "git-bash-merged-tool" },
  2007. } as any,
  2008. });
  2009. const outputPath = join(
  2010. outputRootDir,
  2011. "git-bash-merged-session",
  2012. "git-bash-merged-tool-stdout.log",
  2013. );
  2014. expect(result.status).toBe("completed");
  2015. expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
  2016. expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
  2017. expect(result.stdout.artifactPath).toBe(outputPath);
  2018. await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
  2019. await expect(
  2020. stat(join(outputRootDir, "git-bash-merged-session", "git-bash-merged-tool-stderr.log")),
  2021. ).rejects.toMatchObject({ code: "ENOENT" });
  2022. } finally {
  2023. await adapter.close();
  2024. await rm(outputRootDir, { force: true, recursive: true });
  2025. }
  2026. },
  2027. );
  2028. it("creates a cmd-compatible cwd capture wrapper for Windows shell commands", () => {
  2029. const windowsPlan = createCwdCapturePlan(
  2030. {
  2031. command: {
  2032. mode: "shell",
  2033. command: "cd C:\\repo",
  2034. },
  2035. captureCwdAfterSuccess: true,
  2036. },
  2037. { dialect: "cmd", platform: "win32" },
  2038. );
  2039. expect(windowsPlan.cwdFilePath).toBeDefined();
  2040. expect(windowsPlan.command).toMatchObject({
  2041. mode: "shell",
  2042. });
  2043. expect(windowsPlan.command.command).toContain("cd C:\\repo");
  2044. expect(windowsPlan.command.command).toContain('set "__zcode_status=%ERRORLEVEL%"');
  2045. expect(windowsPlan.command.command).toContain('if "%__zcode_status%"=="0" cd > "');
  2046. expect(windowsPlan.command.command).toContain("exit /b %__zcode_status%");
  2047. });
  2048. it("does not create a cwd capture wrapper for argv commands", () => {
  2049. const argvPlan = createCwdCapturePlan(
  2050. {
  2051. command: {
  2052. mode: "argv",
  2053. file: "pwd",
  2054. },
  2055. captureCwdAfterSuccess: true,
  2056. },
  2057. { dialect: "posix", platform: "darwin" },
  2058. );
  2059. expect(argvPlan).toEqual({
  2060. command: {
  2061. mode: "argv",
  2062. file: "pwd",
  2063. },
  2064. });
  2065. });
  2066. it("preserves shell profile when creating a cwd capture wrapper", () => {
  2067. const plan = createCwdCapturePlan(
  2068. {
  2069. command: {
  2070. mode: "shell",
  2071. command: "pwd",
  2072. shellProfile: "posix-bash",
  2073. },
  2074. captureCwdAfterSuccess: true,
  2075. },
  2076. { dialect: "posix", platform: "linux" },
  2077. );
  2078. expect(plan.command.mode).toBe("shell");
  2079. if (plan.command.mode === "shell") {
  2080. expect(plan.command.shellProfile).toBe("posix-bash");
  2081. expect(plan.command.command).toContain("pwd");
  2082. expect(plan.command.command).toContain("__zcode_status=$?");
  2083. }
  2084. });
  2085. it("uses POSIX cwd capture syntax for Windows Git Bash", () => {
  2086. const plan = createCwdCapturePlan(
  2087. {
  2088. command: {
  2089. mode: "shell",
  2090. command: "cd subdir",
  2091. shellProfile: "posix-bash",
  2092. },
  2093. captureCwdAfterSuccess: true,
  2094. },
  2095. { dialect: "git-bash", platform: "win32" },
  2096. );
  2097. expect(plan.command.mode).toBe("shell");
  2098. if (plan.command.mode === "shell") {
  2099. expect(plan.command.command).toContain("__zcode_status=$?");
  2100. expect(plan.command.command).toContain("pwd -P >");
  2101. expect(plan.command.command).not.toContain("%ERRORLEVEL%");
  2102. }
  2103. });
  2104. it("normalizes captured Git Bash cwd back to a Windows host path", () => {
  2105. expect(normalizeCapturedCwdForHost("/c/path/to/repo", "git-bash")).toBe("C:\\path\\to\\repo");
  2106. expect(normalizeCapturedCwdForHost("C:\\path\\to\\repo", "cmd")).toBe("C:\\path\\to\\repo");
  2107. });
  2108. it("emits progress events with elapsed time, byte counts, and tail output", async () => {
  2109. const adapter = new NodeExecutionAdapter({
  2110. progressIntervalMs: 5,
  2111. progressThresholdMs: 1,
  2112. });
  2113. const events: ExecutionEvent[] = [];
  2114. const result = await adapter.run(
  2115. {
  2116. command: {
  2117. mode: "argv",
  2118. file: process.execPath,
  2119. args: [
  2120. "-e",
  2121. "process.stdout.write('first'); setTimeout(() => process.stdout.write('second'), 30); setTimeout(() => {}, 70)",
  2122. ],
  2123. },
  2124. },
  2125. {
  2126. onEvent: (event) => {
  2127. events.push(event);
  2128. },
  2129. },
  2130. );
  2131. const progress = events.find(
  2132. (event): event is Extract<ExecutionEvent, { type: "progress" }> =>
  2133. event.type === "progress" && event.stdoutBytes > 0,
  2134. );
  2135. expect(result.status).toBe("completed");
  2136. expect(progress).toBeDefined();
  2137. expect(progress?.elapsedMs).toBeGreaterThan(0);
  2138. expect(progress?.stdoutBytes).toBeGreaterThan(0);
  2139. expect(progress?.stdoutTail).toContain("first");
  2140. });
  2141. it("applies cwd and env overlay through spawn options", async () => {
  2142. const adapter = new NodeExecutionAdapter();
  2143. const cwd = await realpath(await mkdtemp(join(tmpdir(), "zcode-exec-")));
  2144. const previousUnsetValue = process.env.ZCODE_EXEC_UNSET;
  2145. process.env.ZCODE_EXEC_UNSET = "remove-me";
  2146. try {
  2147. const result = await adapter.run({
  2148. command: {
  2149. mode: "argv",
  2150. file: process.execPath,
  2151. args: [
  2152. "-e",
  2153. [
  2154. "process.stdout.write(JSON.stringify({",
  2155. "cwd: process.cwd(),",
  2156. "value: process.env.ZCODE_EXEC_TEST,",
  2157. "unset: process.env.ZCODE_EXEC_UNSET ?? null",
  2158. "}))",
  2159. ].join(""),
  2160. ],
  2161. },
  2162. cwd,
  2163. env: {
  2164. base: "inherit",
  2165. set: {
  2166. ZCODE_EXEC_TEST: "yes",
  2167. },
  2168. unset: ["ZCODE_EXEC_UNSET"],
  2169. },
  2170. });
  2171. const parsed = JSON.parse(result.stdout.text) as {
  2172. cwd: string;
  2173. value?: string;
  2174. unset: string | null;
  2175. };
  2176. expect(result.status).toBe("completed");
  2177. expect(parsed.cwd).toBe(cwd);
  2178. expect(parsed.value).toBe("yes");
  2179. expect(parsed.unset).toBeNull();
  2180. } finally {
  2181. if (previousUnsetValue === undefined) {
  2182. delete process.env.ZCODE_EXEC_UNSET;
  2183. } else {
  2184. process.env.ZCODE_EXEC_UNSET = previousUnsetValue;
  2185. }
  2186. await rm(cwd, { force: true, recursive: true });
  2187. }
  2188. });
  2189. it("deduplicates Windows environment keys when applying overlays", () => {
  2190. const env = buildExecutionEnv(
  2191. {
  2192. base: "inherit",
  2193. set: {
  2194. PATH: "C:\\next-bin",
  2195. },
  2196. unset: ["temp"],
  2197. },
  2198. {
  2199. platform: "win32",
  2200. processEnv: {
  2201. Path: "C:\\base-bin",
  2202. TEMP: "C:\\Temp",
  2203. ZCODE_KEEP: "yes",
  2204. },
  2205. },
  2206. );
  2207. expect(env.PATH).toBe("C:\\next-bin");
  2208. expect(env.Path).toBeUndefined();
  2209. expect(env.TEMP).toBeUndefined();
  2210. expect(env.ZCODE_KEEP).toBe("yes");
  2211. });
  2212. it("injects configured network egress variables for subprocesses", () => {
  2213. const env = buildExecutionEnv(
  2214. {
  2215. base: "empty",
  2216. },
  2217. {
  2218. network: {
  2219. caCertFile: "/tmp/zcode-ca.pem",
  2220. httpProxy: "127.0.0.1:8888",
  2221. noProxy: "localhost,127.0.0.1",
  2222. },
  2223. platform: "linux",
  2224. processEnv: {
  2225. HTTP_PROXY: "http://shell-proxy:8080",
  2226. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  2227. },
  2228. },
  2229. );
  2230. expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
  2231. expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:8888");
  2232. expect(env.ALL_PROXY).toBe("http://127.0.0.1:8888");
  2233. expect(env.http_proxy).toBe("http://127.0.0.1:8888");
  2234. expect(env.https_proxy).toBe("http://127.0.0.1:8888");
  2235. expect(env.all_proxy).toBe("http://127.0.0.1:8888");
  2236. expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
  2237. expect(env.no_proxy).toBe("localhost,127.0.0.1");
  2238. expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
  2239. expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
  2240. expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
  2241. expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
  2242. expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
  2243. });
  2244. it("ignores ambient standard proxy and CA env for subprocesses", () => {
  2245. const env = buildExecutionEnv(undefined, {
  2246. network: {},
  2247. platform: "linux",
  2248. processEnv: {
  2249. NODE_ENV: "development",
  2250. http_proxy: "http://shell-proxy:8080",
  2251. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  2252. no_proxy: ".example.test",
  2253. PATH: "/usr/bin:/bin",
  2254. },
  2255. });
  2256. expect(env.NODE_ENV).toBeUndefined();
  2257. expect(env.HTTP_PROXY).toBeUndefined();
  2258. expect(env.http_proxy).toBeUndefined();
  2259. expect(env.NO_PROXY).toBeUndefined();
  2260. expect(env.no_proxy).toBeUndefined();
  2261. expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
  2262. expect(env.SSL_CERT_FILE).toBeUndefined();
  2263. expect(env.REQUESTS_CA_BUNDLE).toBeUndefined();
  2264. expect(env.CURL_CA_BUNDLE).toBeUndefined();
  2265. expect(env.GIT_SSL_CAINFO).toBeUndefined();
  2266. expect(env.PATH).toBe("/usr/bin:/bin");
  2267. });
  2268. it("restores captured user proxy and CA env for inherited subprocesses", () => {
  2269. const env = buildExecutionEnv(undefined, {
  2270. network: {},
  2271. platform: "linux",
  2272. processEnv: {
  2273. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  2274. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  2275. http_proxy: "http://shell-proxy:8080",
  2276. no_proxy: ".example.test",
  2277. npm_config_proxy: "http://npm-proxy:8080",
  2278. }),
  2279. NODE_ENV: "development",
  2280. PATH: "/usr/bin:/bin",
  2281. },
  2282. });
  2283. expect(env.NODE_ENV).toBeUndefined();
  2284. expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
  2285. expect(env.HTTP_PROXY).toBeUndefined();
  2286. expect(env.http_proxy).toBe("http://shell-proxy:8080");
  2287. expect(env.NO_PROXY).toBeUndefined();
  2288. expect(env.no_proxy).toBe(".example.test");
  2289. expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/shell-ca.pem");
  2290. expect(env.npm_config_proxy).toBe("http://npm-proxy:8080");
  2291. expect(env.PATH).toBe("/usr/bin:/bin");
  2292. });
  2293. it("does not restore captured user env when command base is empty", () => {
  2294. const env = buildExecutionEnv(
  2295. {
  2296. base: "empty",
  2297. },
  2298. {
  2299. network: {},
  2300. platform: "linux",
  2301. processEnv: {
  2302. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  2303. HTTP_PROXY: "http://shell-proxy:8080",
  2304. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  2305. }),
  2306. },
  2307. },
  2308. );
  2309. expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
  2310. expect(env.HTTP_PROXY).toBeUndefined();
  2311. expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
  2312. });
  2313. it("derives subprocess proxy and CA env from explicit ZCode runtime keys", () => {
  2314. const env = buildExecutionEnv(
  2315. {
  2316. base: "empty",
  2317. },
  2318. {
  2319. network: {},
  2320. platform: "linux",
  2321. processEnv: {
  2322. ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
  2323. ZCODE_HTTP_PROXY: "127.0.0.1:8888",
  2324. [ZCODE_NO_PROXY_ENV_KEY]: "localhost,127.0.0.1",
  2325. },
  2326. },
  2327. );
  2328. expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
  2329. expect(env.http_proxy).toBe("http://127.0.0.1:8888");
  2330. expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
  2331. expect(env.no_proxy).toBe("localhost,127.0.0.1");
  2332. expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
  2333. expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
  2334. expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
  2335. expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
  2336. expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
  2337. });
  2338. it("lets per-command env overlays override injected network env", () => {
  2339. const env = buildExecutionEnv(
  2340. {
  2341. base: "empty",
  2342. set: {
  2343. HTTP_PROXY: "http://command-proxy:8080",
  2344. },
  2345. unset: ["SSL_CERT_FILE"],
  2346. },
  2347. {
  2348. network: {
  2349. caCertFile: "/tmp/zcode-ca.pem",
  2350. httpProxy: "http://zcode-proxy:8080",
  2351. },
  2352. platform: "linux",
  2353. processEnv: {},
  2354. },
  2355. );
  2356. expect(env.HTTP_PROXY).toBe("http://command-proxy:8080");
  2357. expect(env.HTTPS_PROXY).toBe("http://zcode-proxy:8080");
  2358. expect(env.SSL_CERT_FILE).toBeUndefined();
  2359. expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
  2360. });
  2361. it("adds a UTF-8 locale for subprocess text output when the parent locale is C", () => {
  2362. const env = buildExecutionEnv(undefined, {
  2363. platform: "darwin",
  2364. processEnv: {
  2365. LANG: "C",
  2366. LC_ALL: "",
  2367. LC_CTYPE: "POSIX",
  2368. PATH: "/usr/bin:/bin",
  2369. },
  2370. });
  2371. expect(env.LANG).toBe("en_US.UTF-8");
  2372. expect(env.LC_ALL).toBe("en_US.UTF-8");
  2373. expect(env.LC_CTYPE).toBe("en_US.UTF-8");
  2374. expect(env.PYTHONIOENCODING).toBe("utf-8");
  2375. expect(env.PYTHONUTF8).toBe("1");
  2376. });
  2377. it.skipIf(process.platform === "win32")(
  2378. "keeps unicode path text from POSIX tools even when the parent locale is C",
  2379. async () => {
  2380. const root = await mkdtemp(join(tmpdir(), "zcode-exec-cn-"));
  2381. const dir = join(root, "草稿");
  2382. const file = join(dir, "file.txt");
  2383. await mkdir(dir, { recursive: true });
  2384. await writeFile(file, "a\nb\n");
  2385. const adapter = new NodeExecutionAdapter({
  2386. processEnv: {
  2387. ...process.env,
  2388. LANG: "C",
  2389. LC_ALL: "",
  2390. LC_CTYPE: "C",
  2391. },
  2392. });
  2393. try {
  2394. const result = await adapter.run({
  2395. command: {
  2396. mode: "argv",
  2397. file: "wc",
  2398. args: ["-l", file],
  2399. },
  2400. });
  2401. expect(result.status).toBe("completed");
  2402. expect(result.stdout.text).toContain("草稿");
  2403. expect(result.stdout.text).not.toContain("??");
  2404. } finally {
  2405. await rm(root, { force: true, recursive: true });
  2406. }
  2407. },
  2408. );
  2409. it("decodes Windows legacy Chinese output without corrupting UTF-8 output", () => {
  2410. const legacy = iconv.encode("草稿", "gb18030");
  2411. const westernLegacy = iconv.encode("é", "cp1252");
  2412. const utf8 = Buffer.from("草稿", "utf8");
  2413. expect(decodeExecutionOutputBuffer(legacy, "gb18030")).toBe("草稿");
  2414. expect(decodeExecutionOutputBuffer(westernLegacy, "cp1252")).toBe("é");
  2415. expect(decodeExecutionOutputBuffer(utf8, "gb18030")).toBe("草稿");
  2416. });
  2417. it.skipIf(!POSIX_BASH_PATH)("can rewrite posix-bash commands without -l", () => {
  2418. const command = resolveExecutionCommand(
  2419. {
  2420. mode: "shell",
  2421. command: "echo before",
  2422. shellProfile: "posix-bash",
  2423. shellOverride: {
  2424. dialect: "posix",
  2425. display: { name: "bash" },
  2426. path: POSIX_BASH_PATH!,
  2427. source: "auto-detected",
  2428. },
  2429. },
  2430. {
  2431. env: process.env,
  2432. platform: process.platform,
  2433. },
  2434. );
  2435. expect(command.args).toEqual(["-c", "-l", "echo before"]);
  2436. const withoutLogin = setResolvedShellLoginMode(command, false);
  2437. expect(withoutLogin.args).toEqual(["-c", "echo before"]);
  2438. const rewritten = applyResolvedShellCommandForTest(withoutLogin, "echo after");
  2439. expect(rewritten.args).toEqual(["-c", "echo after"]);
  2440. });
  2441. it("resolves Windows .cmd argv commands through cmd.exe", () => {
  2442. const resolved = resolveExecutionCommand(
  2443. {
  2444. mode: "argv",
  2445. file: "pnpm",
  2446. args: ["--version"],
  2447. },
  2448. {
  2449. cwd: "C:\\repo",
  2450. env: {
  2451. ComSpec: "C:\\Windows\\System32\\cmd.exe",
  2452. Path: "C:\\tools;C:\\other",
  2453. PATHEXT: ".COM;.EXE;.BAT;.CMD",
  2454. },
  2455. exists: (path) => path === "C:\\tools\\pnpm.cmd",
  2456. platform: "win32",
  2457. },
  2458. );
  2459. expect(resolved).toEqual({
  2460. args: ["/d", "/s", "/c", "C:\\tools\\pnpm.cmd --version"],
  2461. cwdDialect: "cmd",
  2462. file: "C:\\Windows\\System32\\cmd.exe",
  2463. shell: false,
  2464. });
  2465. });
  2466. it("quotes Windows .cmd argv arguments without requiring git-bash", () => {
  2467. const resolved = resolveExecutionCommand(
  2468. {
  2469. mode: "argv",
  2470. file: "pnpm",
  2471. args: ["run", "say hi", "A&B", "100%done", "caret^value", "pipe|value"],
  2472. },
  2473. {
  2474. cwd: "C:\\repo",
  2475. env: {
  2476. ComSpec: "C:\\Windows\\System32\\cmd.exe",
  2477. Path: "C:\\Program Files\\node tools",
  2478. PATHEXT: ".COM;.EXE;.BAT;.CMD",
  2479. },
  2480. exists: (path) => path === "C:\\Program Files\\node tools\\pnpm.cmd",
  2481. platform: "win32",
  2482. },
  2483. );
  2484. expect(resolved).toEqual({
  2485. args: [
  2486. "/d",
  2487. "/s",
  2488. "/c",
  2489. '"C:\\Program Files\\node tools\\pnpm.cmd" run "say hi" "A^&B" "100^%done" "caret^^value" "pipe^|value"',
  2490. ],
  2491. cwdDialect: "cmd",
  2492. file: "C:\\Windows\\System32\\cmd.exe",
  2493. shell: false,
  2494. });
  2495. });
  2496. it("keeps Windows .exe argv commands shell-free after PATH resolution", () => {
  2497. const resolved = resolveExecutionCommand(
  2498. {
  2499. mode: "argv",
  2500. file: "tool",
  2501. args: ["run"],
  2502. },
  2503. {
  2504. env: {
  2505. PATH: "C:\\tools",
  2506. PATHEXT: ".EXE;.CMD",
  2507. },
  2508. exists: (path) => path === "C:\\tools\\tool.exe",
  2509. platform: "win32",
  2510. },
  2511. );
  2512. expect(resolved).toEqual({
  2513. args: ["run"],
  2514. cwdDialect: "cmd",
  2515. file: "C:\\tools\\tool.exe",
  2516. shell: false,
  2517. });
  2518. });
  2519. it("uses ComSpec as the default Windows shell", () => {
  2520. const resolved = resolveExecutionCommand(
  2521. {
  2522. mode: "shell",
  2523. command: "dir",
  2524. },
  2525. {
  2526. env: {
  2527. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2528. },
  2529. platform: "win32",
  2530. },
  2531. );
  2532. expect(resolved).toEqual({
  2533. args: [],
  2534. cwdDialect: "cmd",
  2535. file: "dir",
  2536. shell: "C:\\Windows\\System32\\cmd.exe",
  2537. });
  2538. });
  2539. it("keeps generic Windows shell commands on the legacy shell path", () => {
  2540. const resolved = resolveExecutionCommand(
  2541. {
  2542. mode: "shell",
  2543. command: "dir",
  2544. shellOverride: {
  2545. dialect: "git-bash",
  2546. id: "git-bash:C:\\Program Files\\Git\\bin\\bash.exe",
  2547. label: "Git Bash",
  2548. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  2549. source: "user-config",
  2550. },
  2551. },
  2552. {
  2553. env: {
  2554. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2555. SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
  2556. },
  2557. exists: () => {
  2558. throw new Error("Git Bash resolver should not run without shellProfile");
  2559. },
  2560. platform: "win32",
  2561. },
  2562. );
  2563. expect(resolved).toEqual({
  2564. args: [],
  2565. cwdDialect: "cmd",
  2566. file: "dir",
  2567. shell: "C:\\Windows\\System32\\cmd.exe",
  2568. });
  2569. });
  2570. it("keeps generic POSIX shell commands on the legacy Node shell path", () => {
  2571. const resolved = resolveExecutionCommand(
  2572. {
  2573. mode: "shell",
  2574. command: "echo ok",
  2575. },
  2576. {
  2577. env: {
  2578. PATH: "/bin:/usr/bin",
  2579. SHELL: "/bin/bash",
  2580. },
  2581. exists: () => {
  2582. throw new Error("posix shell resolver should not run without shellProfile");
  2583. },
  2584. platform: "linux",
  2585. },
  2586. );
  2587. expect(resolved).toEqual({
  2588. args: [],
  2589. cwdDialect: "posix",
  2590. file: "echo ok",
  2591. shell: true,
  2592. });
  2593. });
  2594. it("uses a valid user-configured Windows Git Bash override before auto detection", () => {
  2595. const resolved = resolveExecutionCommand(
  2596. {
  2597. mode: "shell",
  2598. command: "printf 'ok\\n'",
  2599. shellProfile: "posix-bash",
  2600. shellOverride: {
  2601. dialect: "git-bash",
  2602. id: "git-bash:D:\\Tools\\Git\\bin\\bash.exe",
  2603. label: "Git Bash",
  2604. path: "D:\\Tools\\Git\\bin\\bash.exe",
  2605. source: "user-config",
  2606. },
  2607. },
  2608. {
  2609. env: {
  2610. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2611. PATH: "C:\\Windows\\System32",
  2612. },
  2613. exists: (path) =>
  2614. path === "D:\\Tools\\Git\\bin\\bash.exe" ||
  2615. path === "C:\\Program Files\\Git\\bin\\bash.exe",
  2616. platform: "win32",
  2617. },
  2618. );
  2619. expect(resolved).toMatchObject({
  2620. args: ["-c", "-l", expect.any(String)],
  2621. cwdDialect: "git-bash",
  2622. file: "D:\\Tools\\Git\\bin\\bash.exe",
  2623. shell: false,
  2624. });
  2625. });
  2626. it("falls back to auto detection when the user-configured shell no longer exists", () => {
  2627. const resolved = resolveExecutionCommand(
  2628. {
  2629. mode: "shell",
  2630. command: "printf 'ok\\n'",
  2631. shellProfile: "posix-bash",
  2632. shellOverride: {
  2633. dialect: "git-bash",
  2634. id: "git-bash:D:\\Missing\\bash.exe",
  2635. label: "Git Bash",
  2636. path: "D:\\Missing\\bash.exe",
  2637. source: "user-config",
  2638. },
  2639. },
  2640. {
  2641. env: {
  2642. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2643. PATH: "C:\\Windows\\System32",
  2644. },
  2645. exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
  2646. platform: "win32",
  2647. },
  2648. );
  2649. expect(resolved).toMatchObject({
  2650. cwdDialect: "git-bash",
  2651. file: "C:\\Program Files\\Git\\bin\\bash.exe",
  2652. shell: false,
  2653. });
  2654. });
  2655. it("resolves Windows Git Bash from the default Program Files path for posix-bash", () => {
  2656. const resolved = resolveExecutionCommand(
  2657. {
  2658. mode: "shell",
  2659. command: "printf 'ok\\n'",
  2660. shellProfile: "posix-bash",
  2661. },
  2662. {
  2663. env: {
  2664. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2665. PATH: "C:\\Windows\\System32",
  2666. },
  2667. exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
  2668. platform: "win32",
  2669. },
  2670. );
  2671. expect(resolved).toMatchObject({
  2672. args: ["-c", "-l", expect.any(String)],
  2673. cwdDialect: "git-bash",
  2674. file: "C:\\Program Files\\Git\\bin\\bash.exe",
  2675. shell: false,
  2676. });
  2677. });
  2678. it("resolves Windows Git Bash from git.exe on PATH", () => {
  2679. const resolved = resolveExecutionCommand(
  2680. {
  2681. mode: "shell",
  2682. command: "printf 'ok\\n'",
  2683. shellProfile: "posix-bash",
  2684. },
  2685. {
  2686. env: {
  2687. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2688. PATH: "D:\\Apps\\Git\\cmd",
  2689. },
  2690. exists: (path) =>
  2691. path === "D:\\Apps\\Git\\cmd\\git.exe" || path === "D:\\Apps\\Git\\bin\\bash.exe",
  2692. platform: "win32",
  2693. },
  2694. );
  2695. expect(resolved).toMatchObject({
  2696. args: ["-c", "-l", expect.any(String)],
  2697. cwdDialect: "git-bash",
  2698. file: "D:\\Apps\\Git\\bin\\bash.exe",
  2699. shell: false,
  2700. });
  2701. });
  2702. it("uses a valid user-configured Windows cmd override before auto detection", () => {
  2703. const resolved = resolveExecutionCommand(
  2704. {
  2705. mode: "shell",
  2706. command: "dir",
  2707. shellProfile: "posix-bash",
  2708. shellOverride: {
  2709. dialect: "cmd",
  2710. id: "cmd:C:\\Windows\\System32\\cmd.exe",
  2711. label: "CMD",
  2712. path: "C:\\Windows\\System32\\cmd.exe",
  2713. source: "user-config",
  2714. },
  2715. },
  2716. {
  2717. env: {
  2718. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2719. PATH: "C:\\Windows\\System32",
  2720. },
  2721. exists: (path) =>
  2722. path === "C:\\Windows\\System32\\cmd.exe" ||
  2723. path === "C:\\Program Files\\Git\\bin\\bash.exe",
  2724. platform: "win32",
  2725. },
  2726. );
  2727. expect(resolved).toEqual({
  2728. args: [],
  2729. cwdDialect: "cmd",
  2730. file: "dir",
  2731. shell: "C:\\Windows\\System32\\cmd.exe",
  2732. });
  2733. });
  2734. it("uses the cmd.exe fallback override before auto Git Bash detection", () => {
  2735. const resolved = resolveExecutionCommand(
  2736. {
  2737. mode: "shell",
  2738. command: "dir",
  2739. shellProfile: "posix-bash",
  2740. shellOverride: {
  2741. dialect: "cmd",
  2742. id: "cmd:cmd.exe",
  2743. label: "CMD",
  2744. path: "cmd.exe",
  2745. source: "user-config",
  2746. },
  2747. },
  2748. {
  2749. env: {
  2750. PATH: "C:\\Program Files\\Git\\cmd",
  2751. },
  2752. exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
  2753. platform: "win32",
  2754. },
  2755. );
  2756. expect(resolved).toEqual({
  2757. args: [],
  2758. cwdDialect: "cmd",
  2759. file: "dir",
  2760. shell: "cmd.exe",
  2761. });
  2762. });
  2763. it("falls back to ComSpec when Windows Git Bash cannot be resolved", () => {
  2764. const resolved = resolveExecutionCommand(
  2765. {
  2766. mode: "shell",
  2767. command: "dir",
  2768. shellProfile: "posix-bash",
  2769. },
  2770. {
  2771. env: {
  2772. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2773. PATH: "C:\\tools",
  2774. SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
  2775. },
  2776. exists: () => false,
  2777. platform: "win32",
  2778. },
  2779. );
  2780. expect(resolved).toEqual({
  2781. args: [],
  2782. cwdDialect: "cmd",
  2783. file: "dir",
  2784. shell: "C:\\Windows\\System32\\cmd.exe",
  2785. });
  2786. });
  2787. it("keeps CMD parentheses and metacharacters unchanged in the Bash fallback", () => {
  2788. const command = "if exist input.txt (echo yes) else (echo no) & echo done";
  2789. const resolved = resolveExecutionCommand(
  2790. {
  2791. mode: "shell",
  2792. command,
  2793. shellProfile: "posix-bash",
  2794. },
  2795. {
  2796. env: {
  2797. COMSPEC: "C:\\Windows\\System32\\cmd.exe",
  2798. PATH: "C:\\tools",
  2799. },
  2800. exists: () => false,
  2801. platform: "win32",
  2802. },
  2803. );
  2804. expect(resolved).toEqual({
  2805. args: [],
  2806. cwdDialect: "cmd",
  2807. file: command,
  2808. shell: "C:\\Windows\\System32\\cmd.exe",
  2809. });
  2810. });
  2811. it("converts Windows and Git Bash paths in both directions", () => {
  2812. expect(windowsPathToGitBashPath("C:\\repo\\sub")).toBe("/c/repo/sub");
  2813. expect(windowsPathToGitBashPath("C:/repo/sub")).toBe("/c/repo/sub");
  2814. expect(windowsPathToGitBashPath("C:repo\\sub")).toBe("C:repo/sub");
  2815. expect(windowsPathToGitBashPath("\\\\server\\share\\repo")).toBe("//server/share/repo");
  2816. expect(gitBashPathToWindowsPath("/c/repo/sub")).toBe("C:\\repo\\sub");
  2817. expect(gitBashPathToWindowsPath("/cygdrive/d/repo")).toBe("D:\\repo");
  2818. expect(gitBashPathToWindowsPath("//server/share/repo")).toBe("\\\\server\\share\\repo");
  2819. });
  2820. it.skipIf(process.platform === "win32")(
  2821. "resolves posix-bash shell commands through bash without Node shell wrapping",
  2822. () => {
  2823. const resolved = resolveExecutionCommand(
  2824. {
  2825. mode: "shell",
  2826. command: "echo ok",
  2827. shellProfile: "posix-bash",
  2828. },
  2829. {
  2830. env: {
  2831. PATH: "/custom/bin",
  2832. SHELL: "/bin/bash",
  2833. },
  2834. exists: (path) => path === "/bin/bash",
  2835. platform: "linux",
  2836. },
  2837. );
  2838. expect(resolved).toEqual({
  2839. args: ["-c", "-l", "echo ok"],
  2840. cwdDialect: "posix",
  2841. envOverlay: {
  2842. GIT_EDITOR: "true",
  2843. SHELL: "/bin/bash",
  2844. },
  2845. file: "/bin/bash",
  2846. shell: false,
  2847. usesLoginShell: true,
  2848. });
  2849. },
  2850. );
  2851. it.skipIf(process.platform === "win32")(
  2852. "prefers zsh for posix-bash shell commands when the user shell is not bash",
  2853. () => {
  2854. const resolution = resolveEffectiveBashShellSelection({
  2855. env: {
  2856. PATH: "/zsh/bin:/bash/bin",
  2857. SHELL: "/bin/fish",
  2858. },
  2859. exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
  2860. platform: "darwin",
  2861. });
  2862. const resolved = resolveExecutionCommand(
  2863. {
  2864. mode: "shell",
  2865. command: "echo ok",
  2866. shellProfile: "posix-bash",
  2867. },
  2868. {
  2869. env: {
  2870. PATH: "/zsh/bin:/bash/bin",
  2871. SHELL: "/bin/fish",
  2872. },
  2873. exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
  2874. platform: "darwin",
  2875. },
  2876. );
  2877. expect(resolution.selection).toMatchObject({
  2878. dialect: "posix",
  2879. display: { name: "zsh" },
  2880. path: "/zsh/bin/zsh",
  2881. source: "auto-detected",
  2882. });
  2883. expect(resolution.provider?.file).toBe("/zsh/bin/zsh");
  2884. expect(resolved.file).toBe("/zsh/bin/zsh");
  2885. expect(resolved.args).toEqual(["-c", "-l", "echo ok"]);
  2886. expect(resolved.shell).toBe(false);
  2887. expect(resolved.envOverlay).toMatchObject({
  2888. SHELL: "/zsh/bin/zsh",
  2889. });
  2890. },
  2891. );
  2892. it.skipIf(process.platform === "win32")(
  2893. "falls back to fixed POSIX shell directories for posix-bash commands",
  2894. () => {
  2895. const resolved = resolveExecutionCommand(
  2896. {
  2897. mode: "shell",
  2898. command: "echo ok",
  2899. shellProfile: "posix-bash",
  2900. },
  2901. {
  2902. env: {
  2903. PATH: "/custom/bin",
  2904. SHELL: "/bin/fish",
  2905. },
  2906. exists: (path) => path === "/usr/bin/bash",
  2907. platform: "linux",
  2908. },
  2909. );
  2910. expect(resolved).toMatchObject({
  2911. args: ["-c", "-l", "echo ok"],
  2912. file: "/usr/bin/bash",
  2913. shell: false,
  2914. });
  2915. },
  2916. );
  2917. it.skipIf(process.platform === "win32")(
  2918. "uses the provided auto-detected shell snapshot instead of re-detecting POSIX shells",
  2919. () => {
  2920. const resolved = resolveExecutionCommand(
  2921. {
  2922. mode: "shell",
  2923. command: "echo ok",
  2924. shellOverride: {
  2925. dialect: "posix",
  2926. display: { name: "zsh" },
  2927. id: "auto:zsh",
  2928. label: "zsh",
  2929. path: "/snapshot/bin/zsh",
  2930. source: "auto-detected",
  2931. },
  2932. shellProfile: "posix-bash",
  2933. },
  2934. {
  2935. env: {
  2936. PATH: "/current/bin",
  2937. SHELL: "/bin/fish",
  2938. },
  2939. exists: (path) => path === "/current/bin/bash",
  2940. platform: "linux",
  2941. },
  2942. );
  2943. expect(resolved).toMatchObject({
  2944. args: ["-c", "-l", "echo ok"],
  2945. file: "/snapshot/bin/zsh",
  2946. shell: false,
  2947. });
  2948. },
  2949. );
  2950. it.skipIf(process.platform === "win32")(
  2951. "falls back to the legacy shell command when posix-bash cannot resolve bash or zsh",
  2952. () => {
  2953. const resolution = resolveEffectiveBashShellSelection({
  2954. env: {
  2955. PATH: "/no-shells",
  2956. SHELL: "/bin/fish",
  2957. },
  2958. exists: () => false,
  2959. platform: "linux",
  2960. });
  2961. const resolved = resolveExecutionCommand(
  2962. {
  2963. mode: "shell",
  2964. command: "echo ok",
  2965. shellProfile: "posix-bash",
  2966. },
  2967. {
  2968. env: {
  2969. PATH: "/no-shells",
  2970. SHELL: "/bin/fish",
  2971. },
  2972. exists: () => false,
  2973. platform: "linux",
  2974. },
  2975. );
  2976. expect(resolution.selection).toMatchObject({
  2977. dialect: "legacy-shell",
  2978. display: { name: "system shell" },
  2979. source: "legacy-fallback",
  2980. });
  2981. expect(resolution.provider).toBeUndefined();
  2982. expect(resolved).toEqual({
  2983. args: [],
  2984. cwdDialect: "posix",
  2985. file: "echo ok",
  2986. shell: true,
  2987. });
  2988. },
  2989. );
  2990. it.skipIf(process.platform === "win32")(
  2991. "preserves a legacy shell snapshot instead of re-detecting POSIX shells",
  2992. () => {
  2993. const resolved = resolveExecutionCommand(
  2994. {
  2995. mode: "shell",
  2996. command: "echo ok",
  2997. shellOverride: {
  2998. dialect: "legacy-shell",
  2999. display: { name: "system shell" },
  3000. source: "legacy-fallback",
  3001. },
  3002. shellProfile: "posix-bash",
  3003. },
  3004. {
  3005. env: {
  3006. PATH: "/current/bin",
  3007. SHELL: "/bin/fish",
  3008. },
  3009. exists: (path) => path === "/current/bin/bash",
  3010. platform: "linux",
  3011. },
  3012. );
  3013. expect(resolved).toEqual({
  3014. args: [],
  3015. cwdDialect: "posix",
  3016. file: "echo ok",
  3017. shell: true,
  3018. });
  3019. },
  3020. );
  3021. it("describes auto-detected Windows Git Bash as the effective Bash shell", () => {
  3022. const resolution = resolveEffectiveBashShellSelection({
  3023. env: {
  3024. PATH: "",
  3025. },
  3026. exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
  3027. platform: "win32",
  3028. });
  3029. expect(resolution.selection).toMatchObject({
  3030. dialect: "git-bash",
  3031. display: { name: "Git Bash" },
  3032. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  3033. source: "auto-detected",
  3034. });
  3035. expect(resolution.provider).toMatchObject({
  3036. dialect: "git-bash",
  3037. file: "C:\\Program Files\\Git\\bin\\bash.exe",
  3038. shell: false,
  3039. });
  3040. });
  3041. it("uses the provided auto-detected Windows Git Bash snapshot instead of re-detecting", () => {
  3042. const resolved = resolveExecutionCommand(
  3043. {
  3044. mode: "shell",
  3045. command: "pwd",
  3046. shellOverride: {
  3047. dialect: "git-bash",
  3048. display: { name: "Git Bash" },
  3049. id: "auto:git-bash",
  3050. label: "Git Bash",
  3051. path: "D:\\Git\\bin\\bash.exe",
  3052. source: "auto-detected",
  3053. },
  3054. shellProfile: "posix-bash",
  3055. },
  3056. {
  3057. env: {
  3058. PATH: "",
  3059. },
  3060. exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
  3061. platform: "win32",
  3062. },
  3063. );
  3064. expect(resolved).toMatchObject({
  3065. args: ["-c", "-l", "pwd"],
  3066. file: "D:\\Git\\bin\\bash.exe",
  3067. shell: false,
  3068. });
  3069. });
  3070. it("keeps explicit Windows CMD selection ahead of auto-detected Git Bash", () => {
  3071. const resolution = resolveEffectiveBashShellSelection({
  3072. env: {
  3073. PATH: "",
  3074. },
  3075. exists: (path) => path === "cmd.exe" || path === "C:\\Program Files\\Git\\bin\\bash.exe",
  3076. override: {
  3077. dialect: "cmd",
  3078. display: { name: "CMD" },
  3079. id: "cmd",
  3080. label: "CMD",
  3081. path: "cmd.exe",
  3082. source: "user-config",
  3083. },
  3084. platform: "win32",
  3085. });
  3086. expect(resolution.selection).toMatchObject({
  3087. dialect: "cmd",
  3088. display: { name: "CMD" },
  3089. path: "cmd.exe",
  3090. source: "user-config",
  3091. });
  3092. expect(resolution.provider).toMatchObject({
  3093. dialect: "cmd",
  3094. file: "cmd.exe",
  3095. shell: "cmd.exe",
  3096. });
  3097. });
  3098. it("returns non-zero exits as structured failed results", async () => {
  3099. const adapter = new NodeExecutionAdapter();
  3100. const result = await adapter.run({
  3101. command: {
  3102. mode: "argv",
  3103. file: process.execPath,
  3104. args: ["-e", "process.stderr.write('bad'); process.exit(7)"],
  3105. },
  3106. });
  3107. expect(result.status).toBe("failed");
  3108. expect(result.exitCode).toBe(7);
  3109. expect(result.stderr.text).toBe("bad");
  3110. });
  3111. it("keeps the Agent alive when a successful child closes stdin before a large write", async () => {
  3112. const adapter = new NodeExecutionAdapter();
  3113. const result = await adapter.run({
  3114. command: {
  3115. mode: "argv",
  3116. file: process.execPath,
  3117. args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(0), 20);"],
  3118. },
  3119. stdin: "x".repeat(1024 * 1024),
  3120. });
  3121. expect(result.status).toBe("completed");
  3122. expect(result.exitCode).toBe(0);
  3123. expect(result.error).toBeUndefined();
  3124. });
  3125. it("preserves a non-zero exit when the child closes stdin before a large write", async () => {
  3126. const adapter = new NodeExecutionAdapter();
  3127. const result = await adapter.run({
  3128. command: {
  3129. mode: "argv",
  3130. file: process.execPath,
  3131. args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(7), 20);"],
  3132. },
  3133. stdin: "x".repeat(1024 * 1024),
  3134. });
  3135. expect(result.status).toBe("failed");
  3136. expect(result.exitCode).toBe(7);
  3137. });
  3138. it("delivers a large stdin payload when the child consumes it", async () => {
  3139. const adapter = new NodeExecutionAdapter();
  3140. const stdin = "你好, ZCode!\n".repeat(100_000);
  3141. const result = await adapter.run({
  3142. command: {
  3143. mode: "argv",
  3144. file: process.execPath,
  3145. args: [
  3146. "-e",
  3147. [
  3148. "let bytes = 0;",
  3149. "process.stdin.on('data', chunk => { bytes += chunk.length; });",
  3150. "process.stdin.on('end', () => process.stdout.write(String(bytes)));",
  3151. ].join(" "),
  3152. ],
  3153. },
  3154. stdin,
  3155. });
  3156. expect(result.status).toBe("completed");
  3157. expect(result.exitCode).toBe(0);
  3158. expect(result.stdout.text).toBe(String(Buffer.byteLength(stdin)));
  3159. });
  3160. it("stops commands with a structured timeout result", async () => {
  3161. const adapter = new NodeExecutionAdapter();
  3162. const result = await adapter.run({
  3163. command: {
  3164. mode: "argv",
  3165. file: process.execPath,
  3166. args: ["-e", "setTimeout(() => {}, 5000)"],
  3167. },
  3168. timeoutMs: 50,
  3169. });
  3170. expect(result.status).toBe("timed_out");
  3171. expect(result.timedOut).toBe(true);
  3172. expect(result.cancelled).toBe(false);
  3173. expect(result.error).toEqual({
  3174. type: "timeout",
  3175. message: "Command timed out after 50ms",
  3176. });
  3177. });
  3178. it("timeout 只约束子进程运行阶段,准备较慢的命令不会未启动就被判 timed_out", async () => {
  3179. // 回归:protected-resource sandbox 时代计时器被提前到准备阶段(覆盖 capability probe),
  3180. // sandbox 撤除后该行为一度被保留——shell 初始化较慢或 timeout 较短时,命令还没 spawn
  3181. // 就返回 timed_out。计时器必须在 spawn 之后才启动。
  3182. const adapter = new NodeExecutionAdapter();
  3183. const internals = adapter as unknown as {
  3184. prepareChildSpawn: (request: unknown) => Promise<unknown>;
  3185. };
  3186. const originalPrepare = internals.prepareChildSpawn.bind(adapter);
  3187. internals.prepareChildSpawn = async (request: unknown) => {
  3188. await new Promise((resolve) => setTimeout(resolve, 150));
  3189. return originalPrepare(request);
  3190. };
  3191. const result = await adapter.run({
  3192. command: {
  3193. mode: "argv",
  3194. file: process.execPath,
  3195. args: ["-e", "process.exit(0)"],
  3196. },
  3197. timeoutMs: 60,
  3198. });
  3199. expect(result.status).toBe("completed");
  3200. expect(result.timedOut).toBe(false);
  3201. expect(result.exitCode).toBe(0);
  3202. });
  3203. it("stops commands with a structured cancellation result", async () => {
  3204. const adapter = new NodeExecutionAdapter();
  3205. const controller = new AbortController();
  3206. setTimeout(() => controller.abort(), 50);
  3207. const result = await adapter.run(
  3208. {
  3209. command: {
  3210. mode: "argv",
  3211. file: process.execPath,
  3212. args: ["-e", "setTimeout(() => {}, 5000)"],
  3213. },
  3214. },
  3215. {
  3216. signal: controller.signal,
  3217. },
  3218. );
  3219. expect(result.status).toBe("cancelled");
  3220. expect(result.cancelled).toBe(true);
  3221. expect(result.timedOut).toBe(false);
  3222. });
  3223. it("closes running background tasks during adapter shutdown", async () => {
  3224. const adapter = new NodeExecutionAdapter();
  3225. const started = await adapter.start({
  3226. command: {
  3227. mode: "argv",
  3228. file: process.execPath,
  3229. args: ["-e", "setTimeout(() => {}, 10_000)"],
  3230. },
  3231. });
  3232. await adapter.close();
  3233. const snapshot = await adapter.getBackgroundTask(started.taskId);
  3234. expect(snapshot?.status).toBe("cancelled");
  3235. expect(snapshot?.result?.status).toBe("cancelled");
  3236. });
  3237. it.skipIf(process.platform === "win32")(
  3238. "kills child processes in the same process group when shutting down",
  3239. async () => {
  3240. const adapter = new NodeExecutionAdapter();
  3241. let childPidText = "";
  3242. const script = [
  3243. "const { spawn } = require('node:child_process');",
  3244. "const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 10_000)'], { stdio: 'ignore' });",
  3245. "process.stdout.write(String(child.pid));",
  3246. "setTimeout(() => {}, 10_000);",
  3247. ].join(" ");
  3248. const runPromise = adapter.run(
  3249. {
  3250. command: {
  3251. mode: "argv",
  3252. file: process.execPath,
  3253. args: ["-e", script],
  3254. },
  3255. },
  3256. {
  3257. onEvent: (event) => {
  3258. if (event.type === "stdout") {
  3259. childPidText += event.text;
  3260. }
  3261. },
  3262. },
  3263. );
  3264. let childPid = Number.NaN;
  3265. for (let attempt = 0; attempt < 50; attempt += 1) {
  3266. const trimmed = childPidText.trim();
  3267. childPid = Number(trimmed);
  3268. if (trimmed.length > 0 && Number.isInteger(childPid) && childPid > 0) {
  3269. break;
  3270. }
  3271. await sleep(20);
  3272. }
  3273. expect(Number.isInteger(childPid)).toBe(true);
  3274. expect(childPid).toBeGreaterThan(0);
  3275. await adapter.close();
  3276. const result = await runPromise;
  3277. expect(result.status).toBe("cancelled");
  3278. let childStillRunning = true;
  3279. for (let attempt = 0; attempt < 50; attempt += 1) {
  3280. childStillRunning = isProcessAlive(childPid);
  3281. if (!childStillRunning) {
  3282. break;
  3283. }
  3284. await sleep(20);
  3285. }
  3286. expect(childStillRunning).toBe(false);
  3287. },
  3288. );
  3289. it.skipIf(process.platform === "win32")(
  3290. "keeps inherited-pipe descendants owned until background shutdown",
  3291. async () => {
  3292. const adapter = new NodeExecutionAdapter();
  3293. let output = "";
  3294. let descendantPid = Number.NaN;
  3295. const descendantScript = [
  3296. "process.on('SIGTERM', () => {});",
  3297. "setInterval(() => {}, 10_000);",
  3298. ].join("");
  3299. const wrapperScript = [
  3300. "const { spawn } = require('node:child_process');",
  3301. `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
  3302. "process.stdout.write(`descendant:${child.pid}\\n`);",
  3303. "child.unref();",
  3304. ].join("");
  3305. try {
  3306. const started = await adapter.start(
  3307. {
  3308. command: {
  3309. mode: "argv",
  3310. file: process.execPath,
  3311. args: ["-e", wrapperScript],
  3312. },
  3313. },
  3314. {
  3315. onEvent: (event) => {
  3316. if (event.type === "stdout") output += event.text;
  3317. },
  3318. },
  3319. );
  3320. for (let attempt = 0; attempt < 100; attempt += 1) {
  3321. descendantPid = Number(/descendant:(\d+)/u.exec(output)?.[1]);
  3322. if (Number.isInteger(descendantPid) && descendantPid > 0) break;
  3323. await sleep(20);
  3324. }
  3325. expect(Number.isInteger(descendantPid)).toBe(true);
  3326. // 超过旧实现的一秒 drain 窗口后仍应由 execution 持有,而不是伪 completed。
  3327. await sleep(1_100);
  3328. expect((await adapter.getBackgroundTask(started.taskId))?.status).toBe("running");
  3329. await adapter.close();
  3330. const snapshot = await adapter.getBackgroundTask(started.taskId);
  3331. expect(snapshot?.status).toBe("cancelled");
  3332. expect(snapshot?.result?.status).toBe("cancelled");
  3333. expect(isProcessAlive(descendantPid)).toBe(false);
  3334. } finally {
  3335. if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
  3336. process.kill(descendantPid, "SIGKILL");
  3337. }
  3338. await adapter.close();
  3339. }
  3340. },
  3341. );
  3342. it.skipIf(process.platform === "win32")(
  3343. "cleans inherited-pipe descendants after the foreground drain deadline",
  3344. async () => {
  3345. const adapter = new NodeExecutionAdapter();
  3346. let descendantPid = Number.NaN;
  3347. const descendantScript = "setInterval(() => {}, 10_000);";
  3348. const wrapperScript = [
  3349. "const { spawn } = require('node:child_process');",
  3350. `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
  3351. "process.stdout.write(`descendant:${child.pid}\\n`);",
  3352. "child.unref();",
  3353. ].join("");
  3354. try {
  3355. const result = await adapter.run({
  3356. command: {
  3357. mode: "argv",
  3358. file: process.execPath,
  3359. args: ["-e", wrapperScript],
  3360. },
  3361. });
  3362. descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
  3363. expect(result.status).toBe("completed");
  3364. expect(Number.isInteger(descendantPid)).toBe(true);
  3365. expect(isProcessAlive(descendantPid)).toBe(false);
  3366. } finally {
  3367. if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
  3368. process.kill(descendantPid, "SIGKILL");
  3369. }
  3370. await adapter.close();
  3371. }
  3372. },
  3373. );
  3374. it.skipIf(process.platform === "win32")(
  3375. "releases inherited pipes when a descendant escapes the original process group",
  3376. async () => {
  3377. const adapter = new NodeExecutionAdapter();
  3378. let descendantPid = Number.NaN;
  3379. const descendantScript = "setInterval(() => {}, 10_000);";
  3380. const wrapperScript = [
  3381. "const { spawn } = require('node:child_process');",
  3382. `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
  3383. "process.stdout.write(`descendant:${child.pid}\\n`);",
  3384. "child.unref();",
  3385. ].join("");
  3386. try {
  3387. const startedAt = Date.now();
  3388. const result = await adapter.run({
  3389. command: {
  3390. mode: "argv",
  3391. file: process.execPath,
  3392. args: ["-e", wrapperScript],
  3393. },
  3394. });
  3395. descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
  3396. expect(result.status).toBe("completed");
  3397. expect(Number.isInteger(descendantPid)).toBe(true);
  3398. expect(Date.now() - startedAt).toBeLessThan(4_000);
  3399. // 已脱离原 PGID 的第三方进程无法由纯 Node 可靠寻址,但不能继续用 pipe 保活 CLI。
  3400. expect(isProcessAlive(descendantPid)).toBe(true);
  3401. } finally {
  3402. if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
  3403. process.kill(descendantPid, "SIGKILL");
  3404. }
  3405. await adapter.close();
  3406. }
  3407. },
  3408. );
  3409. it.skipIf(!POSIX_BASH_PATH)(
  3410. "removes a precreated Bash output file when cancelled before spawn",
  3411. async () => {
  3412. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-pre-spawn-cancel-"));
  3413. const parentTurn = new AbortController();
  3414. parentTurn.abort();
  3415. const adapter = new NodeExecutionAdapter({ outputRootDir: root });
  3416. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  3417. try {
  3418. const result = await capable.runBashWithBackgroundLifecycle!(
  3419. {
  3420. command: {
  3421. mode: "shell",
  3422. command: "printf unexpected",
  3423. shellProfile: "posix-bash",
  3424. shellOverride: {
  3425. dialect: "posix",
  3426. display: { name: "bash" },
  3427. path: POSIX_BASH_PATH!,
  3428. source: "auto-detected",
  3429. },
  3430. },
  3431. outputLimit: {
  3432. maxInlineBytes: 30_000,
  3433. maxPersistedBytes: 64 * 1024 * 1024,
  3434. persistOutput: "always",
  3435. },
  3436. trace: {
  3437. sessionId: "bash-pre-spawn-cancel-session",
  3438. attributes: { toolCallId: "bash-pre-spawn-cancel-tool" },
  3439. } as any,
  3440. },
  3441. { mode: "explicit" },
  3442. { signal: parentTurn.signal },
  3443. );
  3444. expect(result.kind).toBe("foreground");
  3445. expect(result.result.status).toBe("cancelled");
  3446. await expect(
  3447. stat(
  3448. join(root, "bash-pre-spawn-cancel-session", "bash-pre-spawn-cancel-tool-stdout.log"),
  3449. ),
  3450. ).rejects.toMatchObject({ code: "ENOENT" });
  3451. } finally {
  3452. await adapter.close();
  3453. await rm(root, { recursive: true, force: true });
  3454. }
  3455. },
  3456. );
  3457. it.skipIf(!POSIX_BASH_PATH)(
  3458. "writes Bash stdout and stderr directly to one canonical output",
  3459. async () => {
  3460. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-merged-"));
  3461. const home = join(outputRootDir, "home");
  3462. await mkdir(home, { recursive: true });
  3463. const processEnv = {
  3464. ...process.env,
  3465. HOME: home,
  3466. SHELL: POSIX_BASH_PATH!,
  3467. };
  3468. delete processEnv.BASH_MAX_OUTPUT_LENGTH;
  3469. const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
  3470. try {
  3471. const result = await adapter.run({
  3472. command: {
  3473. mode: "shell",
  3474. command:
  3475. "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
  3476. shellProfile: "posix-bash",
  3477. shellOverride: {
  3478. dialect: "posix",
  3479. display: { name: "bash" },
  3480. path: POSIX_BASH_PATH!,
  3481. source: "auto-detected",
  3482. },
  3483. },
  3484. outputLimit: {
  3485. maxInlineBytes: 30_000,
  3486. maxPersistedBytes: 64 * 1024 * 1024,
  3487. persistOutput: "always",
  3488. },
  3489. trace: {
  3490. sessionId: "bash-merged-session",
  3491. attributes: { toolCallId: "bash-merged-tool" },
  3492. } as any,
  3493. });
  3494. const outputPath = join(
  3495. outputRootDir,
  3496. "bash-merged-session",
  3497. "bash-merged-tool-stdout.log",
  3498. );
  3499. expect(result.status).toBe("completed");
  3500. expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
  3501. expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
  3502. expect(result.stdout.artifactPath).toBe(outputPath);
  3503. await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
  3504. expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
  3505. await expect(
  3506. stat(join(outputRootDir, "bash-merged-session", "bash-merged-tool-stderr.log")),
  3507. ).rejects.toMatchObject({ code: "ENOENT" });
  3508. const failed = await adapter.run({
  3509. command: {
  3510. mode: "shell",
  3511. command: "printf 'before\\n'; printf 'failure\\n' >&2; exit 7",
  3512. shellProfile: "posix-bash",
  3513. shellOverride: {
  3514. dialect: "posix",
  3515. display: { name: "bash" },
  3516. path: POSIX_BASH_PATH!,
  3517. source: "auto-detected",
  3518. },
  3519. },
  3520. outputLimit: {
  3521. maxInlineBytes: 30_000,
  3522. maxPersistedBytes: 64 * 1024 * 1024,
  3523. persistOutput: "on_truncate",
  3524. },
  3525. trace: {
  3526. sessionId: "bash-merged-session",
  3527. attributes: { toolCallId: "bash-merged-failed-tool" },
  3528. } as any,
  3529. });
  3530. expect(failed).toMatchObject({
  3531. status: "failed",
  3532. exitCode: 7,
  3533. stdout: {
  3534. text: "before\nfailure\n",
  3535. },
  3536. stderr: {
  3537. text: "",
  3538. bytes: 0,
  3539. },
  3540. });
  3541. } finally {
  3542. await adapter.close();
  3543. await rm(outputRootDir, { force: true, recursive: true });
  3544. }
  3545. },
  3546. );
  3547. it.skipIf(!POSIX_BASH_PATH)(
  3548. "reports filesystem diagnostics for empty failed Bash output",
  3549. async () => {
  3550. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-lost-"));
  3551. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3552. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  3553. const cases = [
  3554. {
  3555. id: "disk-full",
  3556. statfs: {
  3557. bavail: 9n,
  3558. bfree: 9n,
  3559. blocks: 10n,
  3560. bsize: 1024n * 1024n,
  3561. ffree: 10_000n,
  3562. files: 10_000n,
  3563. type: 0n,
  3564. },
  3565. diagnostic: (outputDirectory: string) =>
  3566. `Command output was lost: the temp filesystem at ${outputDirectory} is full (9MB free). The child process's stdout/stderr writes failed with ENOSPC. Free up space on this filesystem.`,
  3567. },
  3568. {
  3569. id: "inode-full",
  3570. statfs: {
  3571. bavail: 100n,
  3572. bfree: 100n,
  3573. blocks: 100n,
  3574. bsize: 1024n * 1024n,
  3575. ffree: 999n,
  3576. files: 10_000n,
  3577. type: 0n,
  3578. },
  3579. diagnostic: (outputDirectory: string) =>
  3580. `Command output was lost: the temp filesystem at ${outputDirectory} is out of inodes (999 free). The child process's stdout/stderr writes failed with ENOSPC. Free up space on this filesystem.`,
  3581. },
  3582. ];
  3583. try {
  3584. for (const testCase of cases) {
  3585. statfsMock.mockResolvedValueOnce(testCase.statfs);
  3586. const result = await capable.runBashWithBackgroundLifecycle!(
  3587. {
  3588. command: {
  3589. mode: "shell",
  3590. command: "exit 7",
  3591. shellProfile: "posix-bash",
  3592. shellOverride: {
  3593. dialect: "posix",
  3594. display: { name: "bash" },
  3595. path: POSIX_BASH_PATH!,
  3596. source: "auto-detected",
  3597. },
  3598. },
  3599. timeoutMs: 5_000,
  3600. outputLimit: {
  3601. maxInlineBytes: 30_000,
  3602. maxPersistedBytes: 64 * 1024 * 1024,
  3603. persistOutput: "on_truncate",
  3604. },
  3605. trace: {
  3606. sessionId: `bash-${testCase.id}-session`,
  3607. attributes: { toolCallId: `bash-${testCase.id}-tool` },
  3608. } as any,
  3609. },
  3610. { mode: "auto_on_timeout" },
  3611. );
  3612. const outputDirectory = join(outputRootDir, `bash-${testCase.id}-session`);
  3613. expect(result.kind).toBe("foreground");
  3614. expect(result.result).toMatchObject({
  3615. status: "failed",
  3616. exitCode: 7,
  3617. stdout: {
  3618. text: testCase.diagnostic(outputDirectory),
  3619. },
  3620. stderr: {
  3621. text: "",
  3622. bytes: 0,
  3623. },
  3624. });
  3625. expect(result.result.stdout.artifactPath).toBeUndefined();
  3626. expect(statfsMock).toHaveBeenCalledWith(outputDirectory, { bigint: true });
  3627. }
  3628. } finally {
  3629. await adapter.close();
  3630. await rm(outputRootDir, { force: true, recursive: true });
  3631. }
  3632. },
  3633. );
  3634. it.skipIf(!POSIX_BASH_PATH)(
  3635. "retains a secure zero-byte Bash artifact when persistence is always",
  3636. async () => {
  3637. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-empty-artifact-"));
  3638. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3639. try {
  3640. const result = await adapter.run({
  3641. command: {
  3642. mode: "shell",
  3643. command: ":",
  3644. shellProfile: "posix-bash",
  3645. shellOverride: {
  3646. dialect: "posix",
  3647. display: { name: "bash" },
  3648. path: POSIX_BASH_PATH!,
  3649. source: "auto-detected",
  3650. },
  3651. },
  3652. outputLimit: {
  3653. maxInlineBytes: 30_000,
  3654. maxPersistedBytes: 64 * 1024 * 1024,
  3655. persistOutput: "always",
  3656. },
  3657. trace: {
  3658. sessionId: "bash-empty-artifact-session",
  3659. attributes: { toolCallId: "bash-empty-artifact-tool" },
  3660. } as any,
  3661. });
  3662. const outputPath = join(
  3663. outputRootDir,
  3664. "bash-empty-artifact-session",
  3665. "bash-empty-artifact-tool-stdout.log",
  3666. );
  3667. expect(result).toMatchObject({
  3668. status: "completed",
  3669. stdout: {
  3670. artifactBytes: 0,
  3671. artifactPath: outputPath,
  3672. artifactTruncated: false,
  3673. bytes: 0,
  3674. text: "",
  3675. truncated: false,
  3676. },
  3677. });
  3678. await expect(readFile(outputPath, "utf8")).resolves.toBe("");
  3679. expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
  3680. } finally {
  3681. await adapter.close();
  3682. await rm(outputRootDir, { force: true, recursive: true });
  3683. }
  3684. },
  3685. );
  3686. it.skipIf(!POSIX_BASH_PATH)(
  3687. "settles Bash output preparation failures before spawning",
  3688. async () => {
  3689. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-prepare-"));
  3690. const blockedSessionPath = join(outputRootDir, "blocked-session");
  3691. await writeFile(blockedSessionPath, "not a directory");
  3692. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3693. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  3694. const events: ExecutionEvent[] = [];
  3695. try {
  3696. const result = await capable.runBashWithBackgroundLifecycle!(
  3697. {
  3698. command: {
  3699. mode: "shell",
  3700. command: "printf unexpected",
  3701. shellProfile: "posix-bash",
  3702. shellOverride: {
  3703. dialect: "posix",
  3704. display: { name: "bash" },
  3705. path: POSIX_BASH_PATH!,
  3706. source: "auto-detected",
  3707. },
  3708. },
  3709. outputLimit: {
  3710. maxInlineBytes: 30_000,
  3711. maxPersistedBytes: 64 * 1024 * 1024,
  3712. persistOutput: "always",
  3713. },
  3714. trace: {
  3715. sessionId: "blocked-session",
  3716. attributes: { toolCallId: "blocked-tool" },
  3717. } as any,
  3718. },
  3719. { mode: "auto_on_timeout" },
  3720. {
  3721. onEvent: (event) => {
  3722. events.push(event);
  3723. },
  3724. },
  3725. );
  3726. expect(result.kind).toBe("foreground");
  3727. expect(result.result.status).toBe("spawn_error");
  3728. expect(result.result.error?.message).toContain("blocked-session");
  3729. expect(events.some((event) => event.type === "started")).toBe(false);
  3730. } finally {
  3731. await adapter.close();
  3732. await rm(outputRootDir, { force: true, recursive: true });
  3733. }
  3734. },
  3735. );
  3736. it.skipIf(!POSIX_BASH_PATH)("settles a Bash artifact open failure before spawning", async () => {
  3737. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-open-"));
  3738. const outputPath = join(outputRootDir, "open-failure-session", "open-failure-tool-stdout.log");
  3739. await mkdir(outputPath, { recursive: true });
  3740. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3741. try {
  3742. const result = await adapter.run({
  3743. command: {
  3744. mode: "shell",
  3745. command: "printf output",
  3746. shellProfile: "posix-bash",
  3747. shellOverride: {
  3748. dialect: "posix",
  3749. display: { name: "bash" },
  3750. path: POSIX_BASH_PATH!,
  3751. source: "auto-detected",
  3752. },
  3753. },
  3754. outputLimit: {
  3755. maxInlineBytes: 1,
  3756. maxPersistedBytes: 64,
  3757. persistOutput: "on_truncate",
  3758. },
  3759. trace: {
  3760. sessionId: "open-failure-session",
  3761. attributes: { toolCallId: "open-failure-tool" },
  3762. } as any,
  3763. });
  3764. expect(result.status).toBe("spawn_error");
  3765. expect(result.stdout.artifactPath).toBeUndefined();
  3766. expect(result.stdout.bytes).toBe(0);
  3767. expect(result.error?.message).toContain("open-failure-tool-stdout.log");
  3768. } finally {
  3769. await adapter.close();
  3770. await rm(outputRootDir, { force: true, recursive: true });
  3771. }
  3772. });
  3773. it.skipIf(!POSIX_BASH_PATH)("does not create a parent WriteStream for Bash output", async () => {
  3774. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-write-"));
  3775. const outputPath = join(
  3776. outputRootDir,
  3777. "write-failure-session",
  3778. "write-failure-tool-stdout.log",
  3779. );
  3780. const probePath = join(outputRootDir, "file-handle-probe");
  3781. const probeHandle = await open(probePath, "w");
  3782. const fileHandlePrototype = Object.getPrototypeOf(probeHandle) as {
  3783. createWriteStream: typeof probeHandle.createWriteStream;
  3784. };
  3785. await probeHandle.close();
  3786. await unlink(probePath);
  3787. const createWriteStreamSpy = vi.spyOn(fileHandlePrototype, "createWriteStream");
  3788. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3789. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  3790. try {
  3791. const launch = await capable.runBashWithBackgroundLifecycle!(
  3792. {
  3793. command: {
  3794. mode: "shell",
  3795. command: "printf first; sleep 0.2; printf second",
  3796. shellProfile: "posix-bash",
  3797. shellOverride: {
  3798. dialect: "posix",
  3799. display: { name: "bash" },
  3800. path: POSIX_BASH_PATH!,
  3801. source: "auto-detected",
  3802. },
  3803. },
  3804. outputLimit: {
  3805. maxInlineBytes: 30_000,
  3806. maxPersistedBytes: 64 * 1024 * 1024,
  3807. persistOutput: "always",
  3808. },
  3809. trace: {
  3810. sessionId: "write-failure-session",
  3811. attributes: { toolCallId: "write-failure-tool" },
  3812. } as any,
  3813. },
  3814. { mode: "explicit" },
  3815. );
  3816. expect(launch.kind).toBe("backgrounded");
  3817. if (launch.kind !== "backgrounded") throw new Error("Expected background launch");
  3818. const snapshot = await capable.waitForBackgroundTask!(launch.task.taskId);
  3819. expect(snapshot).toMatchObject({
  3820. outputPath,
  3821. status: "completed",
  3822. stdoutPersistedOutputPath: outputPath,
  3823. });
  3824. expect(snapshot?.result?.stdout.text).toBe("firstsecond");
  3825. expect(snapshot?.result?.stdout.artifactPath).toBe(outputPath);
  3826. expect(createWriteStreamSpy).not.toHaveBeenCalled();
  3827. await expect(readFile(outputPath, "utf8")).resolves.toBe("firstsecond");
  3828. } finally {
  3829. createWriteStreamSpy.mockRestore();
  3830. await adapter.close();
  3831. await rm(outputRootDir, { force: true, recursive: true });
  3832. }
  3833. });
  3834. it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
  3835. "rejects a symlinked Bash canonical output path",
  3836. async () => {
  3837. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-symlink-"));
  3838. const sessionDir = join(outputRootDir, "symlink-session");
  3839. const targetPath = join(outputRootDir, "target.log");
  3840. const outputPath = join(sessionDir, "symlink-tool-stdout.log");
  3841. await mkdir(sessionDir, { recursive: true });
  3842. await writeFile(targetPath, "preserved");
  3843. await symlink(targetPath, outputPath);
  3844. const adapter = new NodeExecutionAdapter({ outputRootDir });
  3845. try {
  3846. const result = await adapter.run({
  3847. command: {
  3848. mode: "shell",
  3849. command: "printf overwritten",
  3850. shellProfile: "posix-bash",
  3851. shellOverride: {
  3852. dialect: "posix",
  3853. display: { name: "bash" },
  3854. path: POSIX_BASH_PATH!,
  3855. source: "auto-detected",
  3856. },
  3857. },
  3858. outputLimit: {
  3859. maxInlineBytes: 30_000,
  3860. maxPersistedBytes: 64,
  3861. persistOutput: "always",
  3862. },
  3863. trace: {
  3864. sessionId: "symlink-session",
  3865. attributes: { toolCallId: "symlink-tool" },
  3866. } as any,
  3867. });
  3868. expect(result.status).toBe("spawn_error");
  3869. await expect(readFile(targetPath, "utf8")).resolves.toBe("preserved");
  3870. } finally {
  3871. await adapter.close();
  3872. await rm(outputRootDir, { force: true, recursive: true });
  3873. }
  3874. },
  3875. );
  3876. it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
  3877. "does not kill descendants when the Bash root exits normally",
  3878. async () => {
  3879. const adapter = new NodeExecutionAdapter();
  3880. let descendantPid = Number.NaN;
  3881. try {
  3882. const result = await adapter.run({
  3883. command: {
  3884. mode: "shell",
  3885. command:
  3886. "(trap '' TERM HUP; while :; do sleep 10; done) & printf 'descendant:%s\\n' \"$!\"",
  3887. shellProfile: "posix-bash",
  3888. shellOverride: {
  3889. dialect: "posix",
  3890. display: { name: "bash" },
  3891. path: POSIX_BASH_PATH!,
  3892. source: "auto-detected",
  3893. },
  3894. },
  3895. });
  3896. descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
  3897. expect(result.status).toBe("completed");
  3898. expect(Number.isInteger(descendantPid)).toBe(true);
  3899. // Bash 工具在 root 进程退出时结算,正常完成不主动清理后代;测试自行收尾。
  3900. expect(isProcessAlive(descendantPid)).toBe(true);
  3901. } finally {
  3902. if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
  3903. process.kill(descendantPid, "SIGKILL");
  3904. }
  3905. await adapter.close();
  3906. }
  3907. },
  3908. );
  3909. it.skipIf(!POSIX_BASH_PATH && !WINDOWS_GIT_BASH_PATH)(
  3910. "settles the background task at root exit before late descendant output",
  3911. async () => {
  3912. const bashPath = POSIX_BASH_PATH ?? WINDOWS_GIT_BASH_PATH!;
  3913. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-descendant-progress-"));
  3914. const adapter = new NodeExecutionAdapter({
  3915. outputRootDir,
  3916. progressIntervalMs: 50,
  3917. progressThresholdMs: 0,
  3918. });
  3919. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  3920. try {
  3921. const result = await capable.runBashWithBackgroundLifecycle!(
  3922. {
  3923. command: {
  3924. mode: "shell",
  3925. command: "(sleep 0.5; printf late) & printf early",
  3926. shellProfile: "posix-bash",
  3927. shellOverride: {
  3928. dialect: "posix",
  3929. display: { name: "bash" },
  3930. path: bashPath,
  3931. source: "auto-detected",
  3932. },
  3933. },
  3934. outputLimit: {
  3935. maxInlineBytes: 30_000,
  3936. maxPersistedBytes: 64 * 1024 * 1024,
  3937. persistOutput: "always",
  3938. },
  3939. trace: {
  3940. sessionId: "bash-descendant-progress-session",
  3941. attributes: { toolCallId: "bash-descendant-progress-tool" },
  3942. } as any,
  3943. },
  3944. { mode: "explicit" },
  3945. );
  3946. expect(result.kind).toBe("backgrounded");
  3947. const completed = await capable.waitForBackgroundTask!(result.task.taskId);
  3948. expect(completed).toMatchObject({
  3949. status: "completed",
  3950. result: {
  3951. stdout: {
  3952. text: "early",
  3953. },
  3954. },
  3955. });
  3956. expect(result.task.outputPath).toBeTypeOf("string");
  3957. await sleep(600);
  3958. await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("earlylate");
  3959. } finally {
  3960. await adapter.close();
  3961. await rm(outputRootDir, { force: true, recursive: true });
  3962. }
  3963. },
  3964. );
  3965. it("keeps generic argv stdout and stderr separate", async () => {
  3966. const adapter = new NodeExecutionAdapter();
  3967. try {
  3968. const result = await adapter.run({
  3969. command: {
  3970. mode: "argv",
  3971. file: process.execPath,
  3972. args: ["-e", "process.stdout.write('stdout'); process.stderr.write('stderr')"],
  3973. },
  3974. });
  3975. expect(result.stdout.text).toBe("stdout");
  3976. expect(result.stderr.text).toBe("stderr");
  3977. } finally {
  3978. await adapter.close();
  3979. }
  3980. });
  3981. it.skipIf(!POSIX_BASH_PATH)(
  3982. "deletes redundant Bash files and keeps complete retained files without losing observed size",
  3983. async () => {
  3984. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-cap-"));
  3985. const processEnv = { ...process.env };
  3986. delete processEnv.BASH_MAX_OUTPUT_LENGTH;
  3987. const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
  3988. const shellOverride = {
  3989. dialect: "posix" as const,
  3990. display: { name: "bash" },
  3991. path: POSIX_BASH_PATH!,
  3992. source: "auto-detected" as const,
  3993. };
  3994. try {
  3995. const smallResult = await adapter.run({
  3996. command: {
  3997. mode: "shell",
  3998. command: "printf ok",
  3999. shellProfile: "posix-bash",
  4000. shellOverride,
  4001. },
  4002. outputLimit: {
  4003. maxInlineBytes: 3,
  4004. maxPersistedBytes: 4,
  4005. maxArtifactBytes: 4,
  4006. persistOutput: "on_truncate",
  4007. },
  4008. trace: {
  4009. sessionId: "bash-cap-session",
  4010. attributes: { toolCallId: "bash-small-tool" },
  4011. } as any,
  4012. });
  4013. const smallPath = join(outputRootDir, "bash-cap-session", "bash-small-tool-stdout.log");
  4014. expect(smallResult.stdout).toMatchObject({
  4015. text: "ok",
  4016. bytes: 2,
  4017. truncated: false,
  4018. });
  4019. expect(smallResult.stdout.artifactPath).toBeUndefined();
  4020. await expect(stat(smallPath)).rejects.toMatchObject({ code: "ENOENT" });
  4021. const largeResult = await adapter.run({
  4022. command: {
  4023. mode: "shell",
  4024. command: "printf abcdef",
  4025. shellProfile: "posix-bash",
  4026. shellOverride,
  4027. },
  4028. outputLimit: {
  4029. maxInlineBytes: 3,
  4030. maxPersistedBytes: 4,
  4031. maxArtifactBytes: 4,
  4032. persistOutput: "on_truncate",
  4033. },
  4034. trace: {
  4035. sessionId: "bash-cap-session",
  4036. attributes: { toolCallId: "bash-large-tool" },
  4037. } as any,
  4038. });
  4039. expect(largeResult.stdout).toMatchObject({
  4040. text: "abc",
  4041. bytes: 6,
  4042. truncated: true,
  4043. artifactBytes: 6,
  4044. artifactTruncated: false,
  4045. });
  4046. await expect(readFile(largeResult.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
  4047. } finally {
  4048. await adapter.close();
  4049. await rm(outputRootDir, { force: true, recursive: true });
  4050. }
  4051. },
  4052. );
  4053. it.skipIf(!POSIX_BASH_PATH)(
  4054. "allows a short Bash command to finish before the first soft-limit check",
  4055. async () => {
  4056. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-limit-"));
  4057. const processEnv = { ...process.env };
  4058. delete processEnv.BASH_MAX_OUTPUT_LENGTH;
  4059. const adapter = new NodeExecutionAdapter({
  4060. outputRootDir,
  4061. processEnv,
  4062. progressIntervalMs: 5,
  4063. progressThresholdMs: 0,
  4064. });
  4065. try {
  4066. const result = await adapter.run({
  4067. command: {
  4068. mode: "shell",
  4069. command: "printf abcdef",
  4070. shellProfile: "posix-bash",
  4071. shellOverride: {
  4072. dialect: "posix",
  4073. display: { name: "bash" },
  4074. path: POSIX_BASH_PATH!,
  4075. source: "auto-detected",
  4076. },
  4077. },
  4078. timeoutMs: 5_000,
  4079. outputLimit: {
  4080. killProcessOnPersistedLimit: true,
  4081. maxInlineBytes: 3,
  4082. maxPersistedBytes: 4,
  4083. persistOutput: "always",
  4084. },
  4085. trace: {
  4086. sessionId: "bash-watchdog-session",
  4087. attributes: { toolCallId: "bash-watchdog-tool" },
  4088. } as any,
  4089. });
  4090. expect(result).toMatchObject({
  4091. status: "completed",
  4092. stdout: {
  4093. text: "abc",
  4094. bytes: 6,
  4095. artifactBytes: 6,
  4096. artifactTruncated: false,
  4097. },
  4098. });
  4099. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
  4100. expect(result.error).toBeUndefined();
  4101. } finally {
  4102. await adapter.close();
  4103. await rm(outputRootDir, { force: true, recursive: true });
  4104. }
  4105. },
  4106. );
  4107. it("parses BASH_MAX_OUTPUT_LENGTH within its documented bounds", () => {
  4108. expect(resolveBashMaxOutputLength({}, 30_000)).toBe(30_000);
  4109. expect(resolveBashMaxOutputLength({}, 120)).toBe(120);
  4110. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: " " }, 120)).toBe(30_000);
  4111. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "4096suffix" })).toBe(4096);
  4112. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "invalid" })).toBe(30_000);
  4113. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "0" })).toBe(30_000);
  4114. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "-1" })).toBe(30_000);
  4115. expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "200000" })).toBe(150_000);
  4116. });
  4117. it.skipIf(!POSIX_BASH_PATH)(
  4118. "applies BASH_MAX_OUTPUT_LENGTH when reading the Bash output file",
  4119. async () => {
  4120. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-env-limit-"));
  4121. const adapter = new NodeExecutionAdapter({
  4122. outputRootDir: root,
  4123. processEnv: {
  4124. ...process.env,
  4125. BASH_MAX_OUTPUT_LENGTH: "4suffix",
  4126. },
  4127. });
  4128. try {
  4129. const result = await adapter.run({
  4130. command: {
  4131. mode: "shell",
  4132. command: "printf abcdef",
  4133. shellProfile: "posix-bash",
  4134. shellOverride: {
  4135. dialect: "posix",
  4136. display: { name: "bash" },
  4137. path: POSIX_BASH_PATH!,
  4138. source: "auto-detected",
  4139. },
  4140. },
  4141. outputLimit: {
  4142. maxInlineBytes: 100,
  4143. maxPersistedBytes: 64,
  4144. persistOutput: "on_truncate",
  4145. },
  4146. trace: {
  4147. sessionId: "bash-env-limit-session",
  4148. attributes: { toolCallId: "bash-env-limit-tool" },
  4149. } as any,
  4150. });
  4151. expect(result.stdout).toMatchObject({
  4152. text: "abcd",
  4153. bytes: 6,
  4154. truncated: true,
  4155. artifactBytes: 6,
  4156. });
  4157. } finally {
  4158. await adapter.close();
  4159. await rm(root, { recursive: true, force: true });
  4160. }
  4161. },
  4162. );
  4163. it.skipIf(!POSIX_BASH_PATH)(
  4164. "keeps the 30000-byte Bash boundary inline and persists byte 30001",
  4165. async () => {
  4166. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-default-limit-"));
  4167. const processEnv = { ...process.env };
  4168. delete processEnv.BASH_MAX_OUTPUT_LENGTH;
  4169. const adapter = new NodeExecutionAdapter({
  4170. outputRootDir: root,
  4171. processEnv,
  4172. });
  4173. try {
  4174. for (const size of [30_000, 30_001]) {
  4175. const result = await adapter.run({
  4176. command: {
  4177. mode: "shell",
  4178. command: `${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`,
  4179. shellProfile: "posix-bash",
  4180. shellOverride: {
  4181. dialect: "posix",
  4182. display: { name: "bash" },
  4183. path: POSIX_BASH_PATH!,
  4184. source: "auto-detected",
  4185. },
  4186. },
  4187. outputLimit: {
  4188. maxInlineBytes: 30_000,
  4189. maxPersistedBytes: 64 * 1024 * 1024,
  4190. persistOutput: "on_truncate",
  4191. },
  4192. trace: {
  4193. sessionId: "bash-default-limit-session",
  4194. attributes: { toolCallId: `bash-default-limit-${size}` },
  4195. } as any,
  4196. });
  4197. expect(result.stdout.bytes).toBe(size);
  4198. expect(result.stdout.text).toHaveLength(30_000);
  4199. expect(result.stdout.truncated).toBe(size > 30_000);
  4200. expect(result.stdout.artifactPath !== undefined).toBe(size > 30_000);
  4201. }
  4202. } finally {
  4203. await adapter.close();
  4204. await rm(root, { recursive: true, force: true });
  4205. }
  4206. },
  4207. );
  4208. it("truncates inline output while preserving observed byte counts", async () => {
  4209. const adapter = new NodeExecutionAdapter();
  4210. const result = await adapter.run({
  4211. command: {
  4212. mode: "argv",
  4213. file: process.execPath,
  4214. args: ["-e", "process.stdout.write('abcdef')"],
  4215. },
  4216. outputLimit: {
  4217. maxInlineBytes: 3,
  4218. },
  4219. });
  4220. expect(result.stdout.text).toBe("abc");
  4221. expect(result.stdout.bytes).toBe(6);
  4222. expect(result.stdout.truncated).toBe(true);
  4223. });
  4224. it("persists full stream output once inline output is truncated", async () => {
  4225. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
  4226. const adapter = new NodeExecutionAdapter({ outputRootDir });
  4227. try {
  4228. const result = await adapter.run({
  4229. command: {
  4230. mode: "argv",
  4231. file: process.execPath,
  4232. args: ["-e", "process.stdout.write('abcdef')"],
  4233. },
  4234. outputLimit: {
  4235. maxInlineBytes: 3,
  4236. persistOutput: "on_truncate",
  4237. },
  4238. trace: {
  4239. traceId: "trace-output" as never,
  4240. sessionId: "session-output" as never,
  4241. attributes: {
  4242. toolCallId: "tool-output",
  4243. },
  4244. },
  4245. });
  4246. expect(result.stdout.text).toBe("abc");
  4247. expect(result.stdout.truncated).toBe(true);
  4248. expect(result.stdout.artifactPath).toBeDefined();
  4249. expect(result.stdout.artifactBytes).toBe(6);
  4250. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
  4251. } finally {
  4252. await rm(outputRootDir, { force: true, recursive: true });
  4253. }
  4254. });
  4255. it("uses the ZCode storage root for persisted output when no output root is injected", async () => {
  4256. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-exec-storage-root-"));
  4257. const adapter = new NodeExecutionAdapter({
  4258. processEnv: {
  4259. ...process.env,
  4260. ZCODE_STORAGE_DIR: storageRoot,
  4261. },
  4262. });
  4263. try {
  4264. const result = await adapter.run({
  4265. command: {
  4266. mode: "argv",
  4267. file: process.execPath,
  4268. args: ["-e", "process.stdout.write('abcdef')"],
  4269. },
  4270. outputLimit: {
  4271. maxInlineBytes: 3,
  4272. persistOutput: "on_truncate",
  4273. },
  4274. trace: {
  4275. traceId: "trace-storage-root" as never,
  4276. sessionId: "session-storage-root" as never,
  4277. attributes: {
  4278. toolCallId: "tool-storage-root",
  4279. },
  4280. },
  4281. });
  4282. expect(result.stdout.artifactPath).toBe(
  4283. join(storageRoot, "cli", "exec", "session-storage-root", "tool-storage-root-stdout.log"),
  4284. );
  4285. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
  4286. } finally {
  4287. await rm(storageRoot, { force: true, recursive: true });
  4288. }
  4289. });
  4290. it("caps persisted stream output while continuing to drain the child", async () => {
  4291. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
  4292. const adapter = new NodeExecutionAdapter({ outputRootDir });
  4293. try {
  4294. const result = await adapter.run({
  4295. command: {
  4296. mode: "argv",
  4297. file: process.execPath,
  4298. args: ["-e", "process.stdout.write('abcdef')"],
  4299. },
  4300. outputLimit: {
  4301. maxInlineBytes: 3,
  4302. maxPersistedBytes: 4,
  4303. persistOutput: "on_truncate",
  4304. },
  4305. });
  4306. expect(result.status).toBe("completed");
  4307. expect(result.stdout.bytes).toBe(6);
  4308. expect(result.stdout.artifactBytes).toBe(4);
  4309. expect(result.stdout.artifactTruncated).toBe(true);
  4310. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcd");
  4311. } finally {
  4312. await rm(outputRootDir, { force: true, recursive: true });
  4313. }
  4314. });
  4315. it("kills the process when persisted output reaches a watchdog limit", async () => {
  4316. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
  4317. const adapter = new NodeExecutionAdapter({ outputRootDir });
  4318. try {
  4319. const result = await adapter.run({
  4320. command: {
  4321. mode: "argv",
  4322. file: process.execPath,
  4323. args: ["-e", "process.stdout.write('x'.repeat(100)); setTimeout(() => {}, 5000)"],
  4324. },
  4325. timeoutMs: 5000,
  4326. outputLimit: {
  4327. maxInlineBytes: 0,
  4328. maxPersistedBytes: 4,
  4329. persistOutput: "always",
  4330. killProcessOnPersistedLimit: true,
  4331. },
  4332. });
  4333. expect(result.status).toBe("failed");
  4334. expect(result.error?.type).toBe("output_limit");
  4335. expect(result.stdout.bytes).toBe(100);
  4336. expect(result.stdout.artifactBytes).toBe(4);
  4337. expect(result.stdout.artifactTruncated).toBe(true);
  4338. await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("xxxx");
  4339. } finally {
  4340. await rm(outputRootDir, { force: true, recursive: true });
  4341. }
  4342. });
  4343. it("shares one persisted watchdog limit across stdout and stderr", async () => {
  4344. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-aggregate-output-"));
  4345. const adapter = new NodeExecutionAdapter({ outputRootDir });
  4346. try {
  4347. const result = await adapter.run(
  4348. {
  4349. command: {
  4350. mode: "argv",
  4351. file: process.execPath,
  4352. args: [
  4353. "-e",
  4354. "process.stdout.write('a'.repeat(8)); process.stderr.write('b'.repeat(8)); setTimeout(() => {}, 5000)",
  4355. ],
  4356. },
  4357. timeoutMs: 5000,
  4358. outputLimit: {
  4359. maxInlineBytes: 0,
  4360. maxPersistedBytes: 10,
  4361. persistOutput: "always",
  4362. killProcessOnPersistedLimit: true,
  4363. },
  4364. },
  4365. {
  4366. sharePersistedOutputLimitAcrossStreams: true,
  4367. } as ExecutionRunOptions & {
  4368. sharePersistedOutputLimitAcrossStreams: boolean;
  4369. },
  4370. );
  4371. expect(result.status).toBe("failed");
  4372. expect(result.error?.type).toBe("output_limit");
  4373. expect((result.stdout.artifactBytes ?? 0) + (result.stderr.artifactBytes ?? 0)).toBe(10);
  4374. const [stdoutArtifact, stderrArtifact] = await Promise.all([
  4375. readFile(result.stdout.artifactPath!),
  4376. readFile(result.stderr.artifactPath!),
  4377. ]);
  4378. expect(stdoutArtifact.byteLength + stderrArtifact.byteLength).toBe(10);
  4379. } finally {
  4380. await adapter.close();
  4381. await rm(outputRootDir, { force: true, recursive: true });
  4382. }
  4383. });
  4384. it("tracks background executions until completion", async () => {
  4385. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-background-"));
  4386. const adapter = new NodeExecutionAdapter({ outputRootDir });
  4387. try {
  4388. const started = await adapter.start({
  4389. command: {
  4390. mode: "argv",
  4391. file: process.execPath,
  4392. args: ["-e", "setTimeout(() => process.stdout.write('bg'), 25)"],
  4393. },
  4394. outputLimit: {
  4395. persistOutput: "always",
  4396. },
  4397. trace: {
  4398. traceId: "trace-bg" as never,
  4399. sessionId: "session-bg" as never,
  4400. attributes: {
  4401. toolCallId: "tool-bg",
  4402. },
  4403. },
  4404. });
  4405. expect(started.status).toBe("running");
  4406. expect(started.outputPath).toBe(join(outputRootDir, "session-bg", "tool-bg-stdout.log"));
  4407. expect(started.stdoutPersistedOutputPath).toBe(started.outputPath);
  4408. expect(started.stderrPersistedOutputPath).toBe(
  4409. join(outputRootDir, "session-bg", "tool-bg-stderr.log"),
  4410. );
  4411. await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("");
  4412. await expect(readFile(started.stderrPersistedOutputPath!, "utf8")).resolves.toBe("");
  4413. let snapshot = await adapter.getBackgroundTask(started.taskId);
  4414. for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
  4415. await sleep(20);
  4416. snapshot = await adapter.getBackgroundTask(started.taskId);
  4417. }
  4418. expect(snapshot?.status).toBe("completed");
  4419. expect(snapshot?.outputPath).toBe(started.outputPath);
  4420. expect(snapshot?.stdoutPersistedOutputPath).toBe(started.stdoutPersistedOutputPath);
  4421. expect(snapshot?.stderrPersistedOutputPath).toBe(started.stderrPersistedOutputPath);
  4422. expect(snapshot?.result?.stdout.text).toBe("bg");
  4423. await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("bg");
  4424. } finally {
  4425. await rm(outputRootDir, { force: true, recursive: true });
  4426. }
  4427. });
  4428. it("does not capture cwd for background shell executions", async () => {
  4429. const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-cwd-"));
  4430. const child = join(root, "child");
  4431. await mkdir(child);
  4432. const adapter = new NodeExecutionAdapter();
  4433. try {
  4434. const started = await adapter.start({
  4435. command: {
  4436. mode: "shell",
  4437. command: `cd ${JSON.stringify(child)}; printf bg`,
  4438. },
  4439. cwd: root,
  4440. captureCwdAfterSuccess: true,
  4441. });
  4442. let snapshot = await adapter.getBackgroundTask(started.taskId);
  4443. for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
  4444. await sleep(20);
  4445. snapshot = await adapter.getBackgroundTask(started.taskId);
  4446. }
  4447. expect(snapshot?.status).toBe("completed");
  4448. expect(snapshot?.result?.stdout.text).toBe("bg");
  4449. expect(snapshot?.result?.resolvedCwd).toBeUndefined();
  4450. } finally {
  4451. await rm(root, { recursive: true, force: true });
  4452. }
  4453. });
  4454. it.skipIf(!POSIX_BASH_PATH)(
  4455. "runs posix-bash shell profile commands in background executions",
  4456. async () => {
  4457. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-"));
  4458. const home = join(root, "home");
  4459. await mkdir(home, { recursive: true });
  4460. try {
  4461. const adapter = new NodeExecutionAdapter({
  4462. outputRootDir: root,
  4463. processEnv: {
  4464. ...process.env,
  4465. HOME: home,
  4466. SHELL: POSIX_BASH_PATH!,
  4467. },
  4468. });
  4469. const started = await adapter.start({
  4470. command: {
  4471. mode: "shell",
  4472. command: "cat <(printf bg)",
  4473. shellProfile: "posix-bash",
  4474. shellOverride: {
  4475. dialect: "posix",
  4476. display: { name: "bash" },
  4477. path: POSIX_BASH_PATH!,
  4478. source: "auto-detected",
  4479. },
  4480. },
  4481. captureCwdAfterSuccess: true,
  4482. });
  4483. let snapshot = await adapter.getBackgroundTask(started.taskId);
  4484. for (let attempt = 0; attempt < 50 && snapshot?.status === "running"; attempt++) {
  4485. await sleep(20);
  4486. snapshot = await adapter.getBackgroundTask(started.taskId);
  4487. }
  4488. expect(snapshot?.status).toBe("completed");
  4489. expect(snapshot?.result?.stdout.text).toBe("bg");
  4490. expect(snapshot?.result?.resolvedCwd).toBeUndefined();
  4491. } finally {
  4492. await rm(root, { recursive: true, force: true });
  4493. }
  4494. },
  4495. );
  4496. it.skipIf(!POSIX_BASH_PATH)(
  4497. "keeps one canonical Bash output file across explicit background commit",
  4498. async () => {
  4499. const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-output-"));
  4500. const home = join(root, "home");
  4501. await mkdir(home, { recursive: true });
  4502. const adapter = new NodeExecutionAdapter({
  4503. outputRootDir: root,
  4504. processEnv: {
  4505. ...process.env,
  4506. HOME: home,
  4507. SHELL: POSIX_BASH_PATH!,
  4508. },
  4509. progressIntervalMs: 5,
  4510. progressThresholdMs: 1,
  4511. });
  4512. const capable = adapter as BashBackgroundLifecycleCapableAdapter;
  4513. try {
  4514. const result = await capable.runBashWithBackgroundLifecycle!(
  4515. {
  4516. command: {
  4517. mode: "shell",
  4518. command: "printf 'out\\n'; printf 'err\\n' >&2; sleep 0.05; printf 'done\\n'",
  4519. shellProfile: "posix-bash",
  4520. shellOverride: {
  4521. dialect: "posix",
  4522. display: { name: "bash" },
  4523. path: POSIX_BASH_PATH!,
  4524. source: "auto-detected",
  4525. },
  4526. },
  4527. outputLimit: {
  4528. maxInlineBytes: 30_000,
  4529. maxPersistedBytes: 64 * 1024 * 1024,
  4530. persistOutput: "on_truncate",
  4531. },
  4532. trace: {
  4533. sessionId: "bash-background-output-session",
  4534. attributes: { toolCallId: "bash-background-output-tool" },
  4535. } as any,
  4536. },
  4537. { mode: "explicit" },
  4538. );
  4539. expect(result.kind).toBe("backgrounded");
  4540. expect(result.task.outputPath).toBe(result.task.stdoutPersistedOutputPath);
  4541. expect(result.task.stderrPersistedOutputPath).toBeUndefined();
  4542. await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBeDefined();
  4543. await vi.waitFor(async () => {
  4544. expect(await readFile(result.task.outputPath!, "utf8")).toContain("out");
  4545. });
  4546. const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
  4547. expect(snapshot?.status).toBe("completed");
  4548. expect(snapshot?.stdoutPersistedOutputPath).toBe(result.task.outputPath);
  4549. expect(snapshot?.stderrPersistedOutputPath).toBeUndefined();
  4550. expect(snapshot?.result?.stdout.text).toBe("out\nerr\ndone\n");
  4551. expect(snapshot?.result?.stderr).toEqual({
  4552. text: "",
  4553. bytes: 0,
  4554. truncated: false,
  4555. });
  4556. await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("out\nerr\ndone\n");
  4557. } finally {
  4558. await adapter.close();
  4559. await rm(root, { recursive: true, force: true });
  4560. }
  4561. },
  4562. );
  4563. it("updates background snapshots with progress output", async () => {
  4564. const adapter = new NodeExecutionAdapter({
  4565. progressIntervalMs: 10,
  4566. progressTailBytes: 128,
  4567. progressThresholdMs: 1,
  4568. });
  4569. const started = await adapter.start({
  4570. command: {
  4571. mode: "argv",
  4572. file: process.execPath,
  4573. args: ["-e", "process.stdout.write('ready'); setTimeout(() => {}, 1000)"],
  4574. },
  4575. });
  4576. let snapshot = await adapter.getBackgroundTask(started.taskId);
  4577. for (let attempt = 0; attempt < 50 && snapshot?.stdoutBytes !== 5; attempt++) {
  4578. await sleep(20);
  4579. snapshot = await adapter.getBackgroundTask(started.taskId);
  4580. }
  4581. expect(snapshot?.status).toBe("running");
  4582. expect(snapshot?.stdoutBytes).toBe(5);
  4583. expect(snapshot?.stdoutTail).toBe("ready");
  4584. const cancelled = await adapter.cancelBackgroundTask(started.taskId);
  4585. expect(cancelled?.status).toBe("cancelled");
  4586. });
  4587. });
  4588. function isProcessAlive(pid: number): boolean {
  4589. try {
  4590. process.kill(pid, 0);
  4591. } catch {
  4592. return false;
  4593. }
  4594. if (process.platform === "win32") {
  4595. return true;
  4596. }
  4597. try {
  4598. const state = execFileSync("ps", ["-o", "stat=", "-p", String(pid)], {
  4599. encoding: "utf8",
  4600. }).trim();
  4601. return state.length > 0 && !state.startsWith("Z");
  4602. } catch {
  4603. return false;
  4604. }
  4605. }
  4606. function quotePosixShellArgument(value: string): string {
  4607. return `'${value.replaceAll("'", `'\\''`)}'`;
  4608. }
  4609. function readPosixProcessGroupId(pid: number): number {
  4610. return Number(
  4611. execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], { encoding: "utf8" }).trim(),
  4612. );
  4613. }