exec.test.ts 184 KB

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