exec.test.ts 159 KB

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