| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025 |
- import {
- mkdir,
- mkdtemp,
- open,
- readdir,
- readFile,
- realpath,
- rm,
- stat,
- symlink,
- unlink,
- writeFile,
- } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { execFileSync } from "node:child_process";
- import iconv from "iconv-lite";
- import { setTimeout as sleep } from "node:timers/promises";
- import { describe, expect, it, vi } from "vitest";
- const { statfsMock } = vi.hoisted(() => ({
- statfsMock: vi.fn(),
- }));
- vi.mock("node:fs/promises", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:fs/promises")>();
- statfsMock.mockImplementation(actual.statfs);
- return {
- ...actual,
- statfs: statfsMock,
- };
- });
- import {
- applyResolvedShellCommandForTest,
- buildExecutionEnv,
- decodeExecutionOutputBuffer,
- NodeExecutionAdapter,
- resolveExecutionCommand,
- setResolvedShellLoginMode,
- } from "../src/exec/index.js";
- import {
- resolveEffectiveBashShellSelection,
- resolveWindowsGitBashShell,
- } from "../src/exec/bash-shell-provider.js";
- import { resolveBashMaxOutputLength } from "../src/exec/bash-output-policy.js";
- import { createCwdCapturePlan, normalizeCapturedCwdForHost } from "../src/exec/cwd-capture.js";
- import {
- type BackgroundExecutionSnapshot,
- type BackgroundExecutionStartResult,
- gitBashPathToWindowsPath,
- type ExecutionEvent,
- type ExecutionResult,
- type ExecutionRequest,
- type ExecutionRunOptions,
- windowsPathToGitBashPath,
- } from "@zcode/contracts";
- import { ZCODE_NO_PROXY_ENV_KEY, ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
- const POSIX_BASH_PATH =
- process.platform === "win32"
- ? undefined
- : findExecutable(["bash", "/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]);
- const WINDOWS_GIT_BASH_PATH =
- process.platform === "win32" ? resolveWindowsGitBashShell(process.env) : undefined;
- function findExecutable(candidates: Array<string | undefined>): string | undefined {
- return candidates.find((candidate) => candidate !== undefined && commandExists(candidate));
- }
- function commandExists(command: string): command is string {
- try {
- execFileSync(command, ["--version"], { stdio: "ignore" });
- return true;
- } catch {
- return false;
- }
- }
- type BashBackgroundLifecycleCapableAdapter = NodeExecutionAdapter & {
- runBashWithBackgroundLifecycle?: (
- request: ExecutionRequest,
- lifecycle: { mode: "explicit" | "auto_on_timeout" },
- options?: ExecutionRunOptions,
- ) => Promise<
- | {
- kind: "foreground";
- result: ExecutionResult;
- }
- | {
- kind: "backgrounded";
- task: BackgroundExecutionStartResult;
- }
- >;
- waitForBackgroundTask?: (
- taskId: string,
- options?: { signal?: AbortSignal },
- ) => Promise<BackgroundExecutionSnapshot | undefined>;
- };
- describe("NodeExecutionAdapter", () => {
- it("auto-backgrounds a foreground command when its timeout elapses", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const removedMethodName = ["run", "Backgroundable"].join("");
- expect(removedMethodName in adapter).toBe(false);
- expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
- expect(capable.waitForBackgroundTask).toBeTypeOf("function");
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('late'), 60)"],
- },
- timeoutMs: 10,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-session",
- attributes: {
- toolCallId: "toolu_auto_background",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(result.task.taskId).toMatch(/^exec_/u);
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("late");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps explicit background execution alive after its input timeout", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-timeout-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('survived'), 80)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-timeout-session",
- attributes: { toolCallId: "toolu_explicit_background_timeout" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- await sleep(25);
- expect((await capable.getBackgroundTask(result.task.taskId))?.status).toBe("running");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("survived");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("detaches parent abort after an explicit background commit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-detach-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const parentTurn = new AbortController();
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('detached'), 70)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-detach-session",
- attributes: { toolCallId: "toolu_explicit_background_detach" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("backgrounded");
- parentTurn.abort();
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("detached");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("still allows an explicit lifecycle task to be stopped directly", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-stop-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
- },
- timeoutMs: 5,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const stopped = await capable.cancelBackgroundTask(result.task.taskId);
- expect(stopped?.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "kills a cooperative Bash descendant outside the root process group",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-cross-pgid-stop-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- progressIntervalMs: 10,
- progressThresholdMs: 0,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- let launcherPid = Number.NaN;
- let workerPid = Number.NaN;
- const workerScript = [
- "process.stdout.write('worker:' + process.pid + '\\n');",
- "setInterval(() => {}, 10_000);",
- ].join("");
- const launcherScript = [
- "const { spawn } = require('node:child_process');",
- "process.stdout.write('launcher:' + process.pid + '\\n');",
- `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "worker.on('exit', () => process.exit());",
- "setInterval(() => {}, 10_000);",
- ].join("");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: `set -m; ${quotePosixShellArgument(process.execPath)} -e ${quotePosixShellArgument(launcherScript)} & wait`,
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- let runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const output = await readFile(result.task.outputPath!, "utf8");
- launcherPid = Number(/launcher:(\d+)/u.exec(output)?.[1]);
- workerPid = Number(/worker:(\d+)/u.exec(output)?.[1]);
- if (
- Number.isInteger(launcherPid) &&
- launcherPid > 0 &&
- Number.isInteger(workerPid) &&
- workerPid > 0
- ) {
- break;
- }
- await sleep(20);
- runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- }
- expect(Number.isInteger(launcherPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(Number.isInteger(runningSnapshot?.pid)).toBe(true);
- expect(readPosixProcessGroupId(launcherPid)).not.toBe(
- readPosixProcessGroupId(runningSnapshot!.pid!),
- );
- expect(isProcessAlive(launcherPid)).toBe(true);
- expect(isProcessAlive(workerPid)).toBe(true);
- await adapter.cancelBackgroundTask(result.task.taskId);
- let launcherStillRunning = true;
- let workerStillRunning = true;
- for (let attempt = 0; attempt < 120; attempt += 1) {
- launcherStillRunning = isProcessAlive(launcherPid);
- workerStillRunning = isProcessAlive(workerPid);
- if (!launcherStillRunning && !workerStillRunning) break;
- await sleep(25);
- }
- expect(launcherStillRunning).toBe(false);
- expect(workerStillRunning).toBe(false);
- let terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- for (let attempt = 0; attempt < 100 && !terminalSnapshot?.result; attempt += 1) {
- await sleep(20);
- terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- }
- expect(terminalSnapshot).toMatchObject({
- status: "cancelled",
- result: { status: "cancelled" },
- });
- } finally {
- if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
- process.kill(workerPid, "SIGKILL");
- }
- if (Number.isInteger(launcherPid) && launcherPid > 0 && isProcessAlive(launcherPid)) {
- process.kill(launcherPid, "SIGKILL");
- }
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "keeps Bash descendant enumeration out of generic argv cancellation",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-generic-group-stop-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- let workerPid = Number.NaN;
- const workerScript = "setInterval(() => {}, 10_000);";
- const launcherScript = [
- "const { spawn } = require('node:child_process');",
- `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write('worker:' + worker.pid + '\\n');",
- "worker.unref();",
- "setInterval(() => {}, 10_000);",
- ].join("");
- try {
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", launcherScript],
- },
- });
- let runningSnapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 100; attempt += 1) {
- workerPid = Number(/worker:(\d+)/u.exec(runningSnapshot?.stdoutTail ?? "")?.[1]);
- if (Number.isInteger(workerPid) && workerPid > 0) break;
- await sleep(20);
- runningSnapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(readPosixProcessGroupId(workerPid)).not.toBe(
- readPosixProcessGroupId(runningSnapshot!.pid!),
- );
- await adapter.cancelBackgroundTask(started.taskId);
- // Bug 根因:PPID 后代枚举属于 Bash runtime;通用 ExecutionPort 必须保留
- // 原有的进程组停止边界,不能顺带获得新的跨 PGID kill 能力。
- await sleep(850);
- expect(isProcessAlive(workerPid)).toBe(true);
- } finally {
- if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
- process.kill(workerPid, "SIGKILL");
- }
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("cancels an explicit lifecycle task when the adapter closes", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-close-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
- },
- timeoutMs: 5,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- await adapter.close();
- const snapshot = await capable.getBackgroundTask(result.task.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("cancels before background commit when the parent is already aborted", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-pre-abort-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const parentTurn = new AbortController();
- parentTurn.abort();
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 30)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-pre-abort-session",
- attributes: { toolCallId: "toolu_explicit_background_pre_abort" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("returns an explicit spawn failure without publishing a background task", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-spawn-fail-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: join(root, "missing-executable"),
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-spawn-fail-session",
- attributes: { toolCallId: "toolu_explicit_background_spawn_fail" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("spawn_error");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles completion, timeout, and abort boundary races exactly once", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-races-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const backgroundTaskIds = new Set<string>();
- try {
- for (let attempt = 0; attempt < 12; attempt++) {
- const parentTurn = new AbortController();
- let outcomeCount = 0;
- let forwardedTerminalEvents = 0;
- const childDelayMs = attempt % 3 === 2 ? 5 : 12;
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- `setTimeout(() => process.stdout.write('race-${attempt}'), ${childDelayMs})`,
- ],
- },
- timeoutMs: 5,
- trace: {
- sessionId: `exec-background-race-${attempt}`,
- attributes: { toolCallId: `toolu_background_race_${attempt}` },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- signal: parentTurn.signal,
- onEvent: (event) => {
- if (event.type === "completed" || event.type === "failed") {
- forwardedTerminalEvents += 1;
- }
- if (event.type === "started" && attempt % 3 === 0) {
- queueMicrotask(() => parentTurn.abort());
- } else if (event.type === "started" && attempt % 3 === 2) {
- setTimeout(() => parentTurn.abort(), 5);
- }
- },
- },
- ).then((outcome) => {
- outcomeCount += 1;
- return outcome;
- });
- if (result.kind === "backgrounded") {
- expect(backgroundTaskIds.has(result.task.taskId)).toBe(false);
- backgroundTaskIds.add(result.task.taskId);
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- } else {
- expect(["cancelled", "completed"]).toContain(result.result.status);
- }
- await sleep(5);
- expect(outcomeCount).toBe(1);
- expect(forwardedTerminalEvents).toBeLessThanOrEqual(1);
- }
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("stops forwarding foreground progress after auto-backgrounding", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-progress-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const progressEvents: ExecutionEvent[] = [];
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let writes = 0;",
- "const timer = setInterval(() => {",
- " process.stdout.write(String(writes));",
- " writes += 1;",
- " if (writes >= 8) { clearInterval(timer); process.exit(0); }",
- "}, 20);",
- ].join(""),
- ],
- },
- timeoutMs: 25,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-progress-session",
- attributes: {
- toolCallId: "toolu_auto_background_progress",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- onEvent: (event) => {
- if (event.type === "progress") progressEvents.push(event);
- },
- },
- );
- expect(result.kind).toBe("backgrounded");
- const forwardedProgressAfterBackground = progressEvents.length;
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(progressEvents).toHaveLength(forwardedProgressAfterBackground);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("resolves failed snapshots for auto-backgrounded foreground commands", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-fail-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
- expect(capable.waitForBackgroundTask).toBeTypeOf("function");
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "setTimeout(() => { process.stderr.write('boom'); process.exit(7); }, 60)",
- ],
- },
- timeoutMs: 10,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-fail-session",
- attributes: {
- toolCallId: "toolu_auto_background_fail",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("failed");
- expect(snapshot?.result?.exitCode).toBe(7);
- expect(snapshot?.result?.stderr.text).toBe("boom");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps foreground results foreground when commands finish before timeout", async () => {
- const adapter = new NodeExecutionAdapter();
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("completed");
- expect(result.result.stdout.text).toBe("ok");
- } finally {
- await adapter.close();
- }
- });
- it("removes auto-background output artifacts when foreground completion wins", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-cleanup-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "cleanup-session", "cleanup-tool-stdout.log");
- const stderrPath = join(root, "cleanup-session", "cleanup-tool-stderr.log");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- trace: {
- sessionId: "cleanup-session",
- attributes: {
- toolCallId: "cleanup-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(result.result.stderr.artifactPath).toBeUndefined();
- await expect(readFile(stdoutPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles foreground completion when redundant artifact cleanup fails", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-cleanup-failure-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "cleanup-failure-session", "cleanup-failure-tool-stdout.log");
- const retainedFile = join(stdoutPath, "retained.log");
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- await unlink(stdoutPath);
- await mkdir(stdoutPath);
- await writeFile(retainedFile, "cleanup failed");
- return {
- status: "completed",
- exitCode: 0,
- stdout: {
- text: "ok",
- bytes: 2,
- truncated: false,
- artifactBytes: 2,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 1_000,
- trace: {
- sessionId: "cleanup-failure-session",
- attributes: { toolCallId: "cleanup-failure-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(result.result.stdout.artifactBytes).toBeUndefined();
- await expect(readFile(retainedFile, "utf8")).resolves.toBe("cleanup failed");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles foreground completion with honest metadata when artifact truncation fails", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-truncate-failure-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "truncate-failure-session", "truncate-failure-tool-stdout.log");
- const retainedFile = join(stdoutPath, "retained.log");
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- await unlink(stdoutPath);
- await mkdir(stdoutPath);
- await writeFile(retainedFile, "not truncated");
- return {
- status: "completed",
- exitCode: 0,
- stdout: {
- text: "ok",
- bytes: 2,
- truncated: false,
- artifactBytes: 13,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 1_000,
- outputLimit: {
- maxPersistedBytes: 4,
- persistOutput: "always",
- },
- trace: {
- sessionId: "truncate-failure-session",
- attributes: { toolCallId: "truncate-failure-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout).toMatchObject({
- artifactBytes: 13,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- });
- await expect(readFile(retainedFile, "utf8")).resolves.toBe("not truncated");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps explicitly requested foreground output artifacts when foreground completion wins", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-preserve-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "preserve-session", "preserve-tool-stdout.log");
- const stderrPath = join(root, "preserve-session", "preserve-tool-stderr.log");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "preserve-session",
- attributes: {
- toolCallId: "preserve-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBe(stdoutPath);
- await expect(readFile(stdoutPath, "utf8")).resolves.toBe("ok");
- await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("does not stop auto-backgrounded commands at the foreground persisted output limit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-limit-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let writes = 0;",
- "const timer = setInterval(() => {",
- " process.stdout.write('x'.repeat(512));",
- " writes += 1;",
- " if (writes >= 200) { clearInterval(timer); process.exit(0); }",
- "}, 1);",
- ].join(""),
- ],
- },
- timeoutMs: 20,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 1_024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "limit-session",
- attributes: {
- toolCallId: "limit-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.error).toBeUndefined();
- expect(snapshot?.result?.exitCode).toBe(0);
- expect(snapshot?.result?.stdout.artifactBytes).toBeGreaterThan(1_024);
- expect(snapshot?.result?.stdout.artifactTruncated).toBe(false);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "stops foreground Bash at the periodic soft limit and removes its oversized file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-hard-cap-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- });
- const outputLimit = 1_024;
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: `${JSON.stringify(process.execPath)} -e ${JSON.stringify("process.stdout.write('x'.repeat(4096)); setInterval(() => {}, 1000)")}`,
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: outputLimit,
- persistOutput: "always",
- },
- },
- {
- onPersistedLimit: () => undefined,
- shouldStopOnPersistedLimit: () => true,
- } as ExecutionRunOptions & {
- onPersistedLimit: () => void;
- shouldStopOnPersistedLimit: () => boolean;
- },
- );
- expect(result).toMatchObject({
- status: "cancelled",
- exitCode: 137,
- cancelled: true,
- error: { type: "output_limit" },
- stdout: {
- bytes: 4096,
- },
- });
- expect(result.stdout.artifactPath).toBeUndefined();
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- 15_000,
- );
- it("applies the shared 5GiB watchdog policy after Bash background commit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-watchdog-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- let capturedRequest: ExecutionRequest | undefined;
- let sharesPersistedLimitAcrossStreams = false;
- let shouldStopOnPersistedLimit = false;
- const runSpy = vi.spyOn(adapter, "run").mockImplementation(async (request, options) => {
- capturedRequest = request;
- const internalOptions = options as ExecutionRunOptions & {
- sharePersistedOutputLimitAcrossStreams?: boolean;
- shouldStopOnPersistedLimit?: () => boolean;
- };
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- shouldStopOnPersistedLimit = internalOptions.shouldStopOnPersistedLimit?.() === true;
- sharesPersistedLimitAcrossStreams =
- internalOptions.sharePersistedOutputLimitAcrossStreams === true;
- return {
- status: "completed",
- exitCode: 0,
- stdout: { text: "", bytes: 0, truncated: false },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 5,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxPersistedBytes: 1_024,
- persistOutput: "on_truncate",
- },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(capturedRequest?.timeoutMs).toBe(0);
- expect(capturedRequest?.outputLimit).toMatchObject({
- killProcessOnPersistedLimit: false,
- maxPersistedBytes: 5 * 1024 * 1024 * 1024,
- persistOutput: "always",
- });
- expect(sharesPersistedLimitAcrossStreams).toBe(true);
- expect(shouldStopOnPersistedLimit).toBe(true);
- expect(runSpy).toHaveBeenCalledTimes(1);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("normalizes a background Bash output-limit stop to killed exit 137 semantics", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-limit-result-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- const internalOptions = options as ExecutionRunOptions & {
- onPersistedLimit?: () => void;
- };
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- internalOptions.onPersistedLimit?.();
- return {
- status: "failed",
- exitCode: 0,
- stdout: {
- text: "",
- bytes: 5 * 1024 * 1024 * 1024 + 1,
- truncated: true,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- outputLimit: { persistOutput: "always" },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.result).toMatchObject({
- status: "cancelled",
- cancelled: true,
- timedOut: false,
- exitCode: 137,
- error: {
- type: "output_limit",
- message: "Background command killed: output file exceeded 5GB",
- },
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "does not apply the runtime soft limit before its first check and retains the full foreground file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-final-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 60_000,
- });
- let persistedLimitNotified = false;
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: "printf abc",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- maxInlineBytes: 1,
- maxPersistedBytes: 2,
- maxArtifactBytes: 1,
- persistOutput: "on_truncate",
- },
- },
- {
- onPersistedLimit: () => {
- persistedLimitNotified = true;
- },
- shouldStopOnPersistedLimit: () => false,
- } as ExecutionRunOptions & {
- onPersistedLimit: () => void;
- shouldStopOnPersistedLimit: () => boolean;
- },
- );
- expect(result).toMatchObject({
- status: "completed",
- exitCode: 0,
- timedOut: false,
- cancelled: false,
- stdout: {
- bytes: 3,
- text: "a",
- artifactBytes: 3,
- artifactTruncated: false,
- },
- });
- expect(result.error).toBeUndefined();
- expect(persistedLimitNotified).toBe(false);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "ignores the legacy Bash artifact cap after lifecycle completion",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-lifecycle-artifact-cap-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf abc",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 1_000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 100,
- maxArtifactBytes: 1,
- persistOutput: "always",
- },
- trace: {
- sessionId: "lifecycle-artifact-cap-session",
- attributes: { toolCallId: "lifecycle-artifact-cap-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result).toMatchObject({
- status: "completed",
- stdout: {
- bytes: 3,
- artifactBytes: 3,
- artifactTruncated: false,
- },
- });
- await expect(readFile(result.result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "stops watching at root exit even when descendants later exceed the soft limit",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-retained-output-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- progressThresholdMs: 0,
- });
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: "(sleep 0.05; printf 0123456789; sleep 1) & printf x",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxInlineBytes: 30_000,
- maxPersistedBytes: 3,
- persistOutput: "always",
- },
- },
- {
- shouldRetainExecutionAfterRootExit: () => true,
- } as ExecutionRunOptions & {
- shouldRetainExecutionAfterRootExit: () => boolean;
- },
- );
- expect(result.status).toBe("completed");
- expect(result.error).toBeUndefined();
- expect(result.stdout.text).toBe("x");
- await sleep(1_200);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("x0123456789");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("runs argv commands without a shell and streams output events", async () => {
- const adapter = new NodeExecutionAdapter();
- const events: ExecutionEvent[] = [];
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("ok");
- expect(events[0]?.type).toBe("started");
- expect(events.some((event) => event.type === "stdout")).toBe(true);
- expect(events.at(-1)?.type).toBe("completed");
- });
- it("captures final cwd for successful foreground shell commands when requested", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-"));
- const child = join(root, " child with spaces ");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(process.platform !== "win32")(
- "captures final cwd for Windows cmd shell commands when requested",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-win-cwd-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd /d "${child}"`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("does not capture cwd for generic shell commands by default", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-default-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}`,
- },
- cwd: root,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it("does not capture cwd when the shell command exits non-zero", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-fail-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}; false`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(1);
- expect(result.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands with bash/zsh syntax",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-posix-bash-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "cat <(printf ok)",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("ok");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "creates shell init snapshots with login shell and runs user commands without login",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-login-mode-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: 'shopt -q login_shell; rc=$?; printf "%s" "$rc"',
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("1");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toMatch(/^-c /u);
- expect(invocations.at(-1)).not.toContain("-l ");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "injects embedded search prelude into posix-bash shell profile commands",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- const shimScript = [
- "if (process.argv[1] !== 'grep') process.exit(11);",
- "process.stdout.write(`shim:${process.argv.slice(2).join('|')}`);",
- ].join("");
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "grep needle file.txt",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- bashPrelude: {
- kind: "embedded-search",
- backend: {
- kind: "internal-cli",
- command: process.execPath,
- args: ["-e", shimScript],
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("shim:needle|file.txt");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to native grep when embedded search backend is unavailable and preserves stdin",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-fallback-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf 'before\\nneedle from stdin\\nafter\\n' | grep needle",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- bashPrelude: {
- kind: "embedded-search",
- backend: {
- kind: "internal-cli",
- command: join(root, "missing-zcode"),
- args: ["__internal-search"],
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("needle from stdin\n");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "sources shell init snapshot and skips login for the user command after creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-integration-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
- );
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_snapshot_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("alias-from-snapshot");
- const log = await readFile(shellLog, "utf8");
- const invocations = log.trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toMatch(/^-c /u);
- expect(invocations.at(-1)).not.toContain("-l ");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const beforeClose = await readdir(snapshotSessionDir);
- expect(beforeClose.some((file) => file.endsWith(".sh"))).toBe(true);
- await adapter.close();
- const afterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
- if (
- typeof error === "object" &&
- error !== null &&
- "code" in error &&
- error.code === "ENOENT"
- ) {
- return [];
- }
- throw error;
- });
- expect(afterClose).toEqual([]);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "creates shell init snapshots with the resolved shell environment",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-env-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- [
- 'if [ "$SHELL" = "$ZCODE_EXPECTED_SHELL" ] && [ "$GIT_EDITOR" = "true" ]; then',
- " alias zcode_env_overlay_alias='printf env-overlay-ok'",
- "fi",
- "",
- ].join("\n"),
- );
- await writeFile(
- shellWrapper,
- ["#!/usr/bin/env bash", `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`, ""].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- GIT_EDITOR: "stale-editor",
- HOME: home,
- SHELL: "/bin/fish",
- ZCODE_EXPECTED_SHELL: shellWrapper,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_env_overlay_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("env-overlay-ok");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to login shell when a cached shell init snapshot file is missing",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-missing-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
- );
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const first = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_snapshot_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(first.status).toBe("completed");
- expect(first.stdout.text).toBe("alias-from-snapshot");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const snapshotFiles = await readdir(snapshotSessionDir);
- const snapshotFile = snapshotFiles.find((file) => file.endsWith(".sh"));
- expect(snapshotFile).toBeDefined();
- await unlink(join(snapshotSessionDir, snapshotFile!));
- const second = await adapter.run({
- command: {
- mode: "shell",
- command: "printf second-ok",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(second.status).toBe("completed");
- expect(second.stdout.text).toBe("second-ok");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[1]).toMatch(/^-c /u);
- expect(invocations[1]).not.toContain("-l ");
- expect(invocations[2]).toContain("-c -l");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "does not spawn the user command when closing during shell init snapshot creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-close-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " sleep 0.2",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const runPromise = adapter.run({
- command: {
- mode: "shell",
- command: "printf user-command-ran",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- await sleep(50);
- await adapter.close();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- expect(result.stdout.text).toBe("");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations).toHaveLength(1);
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[0]).toContain("SNAPSHOT_FILE=");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const snapshotsAfterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
- if (
- typeof error === "object" &&
- error !== null &&
- "code" in error &&
- error.code === "ENOENT"
- ) {
- return [];
- }
- throw error;
- });
- expect(snapshotsAfterClose).toEqual([]);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "does not spawn the user command when aborted during shell init snapshot creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-abort-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " sleep 0.2",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const controller = new AbortController();
- const runPromise = adapter.run(
- {
- command: {
- mode: "shell",
- command: "printf user-command-ran",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- },
- { signal: controller.signal },
- );
- await sleep(50);
- controller.abort();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- expect(result.stdout.text).toBe("");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations).toHaveLength(1);
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[0]).toContain("SNAPSHOT_FILE=");
- await adapter.close();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to login shell when shell init snapshot creation fails",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-fallback-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " exit 42",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf fallback-ok",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("fallback-ok");
- const log = await readFile(shellLog, "utf8");
- const invocations = log.trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toContain("-c -l");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps cwd capture after shell init snapshot source commands",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-cwd-"));
- const home = join(root, "home");
- const child = join(root, "child");
- await mkdir(home, { recursive: true });
- await mkdir(child, { recursive: true });
- await writeFile(join(home, ".bashrc"), 'zcode_cd_child() { cd "$ZCODE_TEST_CHILD"; }\n');
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- ZCODE_TEST_CHILD: child,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_cd_child",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- captureCwdAfterSuccess: true,
- cwd: root,
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands with bash-specific syntax when bash is the user shell",
- async () => {
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- SHELL: POSIX_BASH_PATH ?? "/bin/bash",
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: [
- "arr=(a b)",
- "printf '%s\\n' \"${arr[1]}\"",
- "false | true",
- "printf '%s\\n' \"${PIPESTATUS[0]} ${PIPESTATUS[1]}\"",
- "[[ -n x ]] && printf '%s\\n' ok",
- ].join("\n"),
- shellProfile: "posix-bash",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("b\n1 0\nok\n");
- },
- );
- it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
- "runs Bash syntax through Git Bash on Windows",
- async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- shellProfile: "posix-bash",
- command: [
- "arr=(a b)",
- "printf 'array=%s\\n' \"${arr[1]}\"",
- "cat <(printf process)",
- ].join("\n"),
- },
- captureCwdAfterSuccess: true,
- timeoutMs: 5000,
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toContain("array=b");
- expect(result.stdout.text).toContain("process");
- },
- );
- it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
- "writes Windows Git Bash stdout and stderr directly to one canonical output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-git-bash-merged-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- shellProfile: "posix-bash",
- command:
- "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "git-bash-merged-session",
- attributes: { toolCallId: "git-bash-merged-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "git-bash-merged-session",
- "git-bash-merged-tool-stdout.log",
- );
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
- expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
- expect(result.stdout.artifactPath).toBe(outputPath);
- await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
- await expect(
- stat(join(outputRootDir, "git-bash-merged-session", "git-bash-merged-tool-stderr.log")),
- ).rejects.toMatchObject({ code: "ENOENT" });
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("creates a cmd-compatible cwd capture wrapper for Windows shell commands", () => {
- const windowsPlan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "cd C:\\repo",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "cmd", platform: "win32" },
- );
- expect(windowsPlan.cwdFilePath).toBeDefined();
- expect(windowsPlan.command).toMatchObject({
- mode: "shell",
- });
- expect(windowsPlan.command.command).toContain("cd C:\\repo");
- expect(windowsPlan.command.command).toContain('set "__zcode_status=%ERRORLEVEL%"');
- expect(windowsPlan.command.command).toContain('if "%__zcode_status%"=="0" cd > "');
- expect(windowsPlan.command.command).toContain("exit /b %__zcode_status%");
- });
- it("does not create a cwd capture wrapper for argv commands", () => {
- const argvPlan = createCwdCapturePlan(
- {
- command: {
- mode: "argv",
- file: "pwd",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "posix", platform: "darwin" },
- );
- expect(argvPlan).toEqual({
- command: {
- mode: "argv",
- file: "pwd",
- },
- });
- });
- it("preserves shell profile when creating a cwd capture wrapper", () => {
- const plan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "pwd",
- shellProfile: "posix-bash",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "posix", platform: "linux" },
- );
- expect(plan.command.mode).toBe("shell");
- if (plan.command.mode === "shell") {
- expect(plan.command.shellProfile).toBe("posix-bash");
- expect(plan.command.command).toContain("pwd");
- expect(plan.command.command).toContain("__zcode_status=$?");
- }
- });
- it("uses POSIX cwd capture syntax for Windows Git Bash", () => {
- const plan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "cd subdir",
- shellProfile: "posix-bash",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "git-bash", platform: "win32" },
- );
- expect(plan.command.mode).toBe("shell");
- if (plan.command.mode === "shell") {
- expect(plan.command.command).toContain("__zcode_status=$?");
- expect(plan.command.command).toContain("pwd -P >");
- expect(plan.command.command).not.toContain("%ERRORLEVEL%");
- }
- });
- it("normalizes captured Git Bash cwd back to a Windows host path", () => {
- expect(normalizeCapturedCwdForHost("/c/path/to/repo", "git-bash")).toBe("C:\\path\\to\\repo");
- expect(normalizeCapturedCwdForHost("C:\\path\\to\\repo", "cmd")).toBe("C:\\path\\to\\repo");
- });
- it("emits progress events with elapsed time, byte counts, and tail output", async () => {
- const adapter = new NodeExecutionAdapter({
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const events: ExecutionEvent[] = [];
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "process.stdout.write('first'); setTimeout(() => process.stdout.write('second'), 30); setTimeout(() => {}, 70)",
- ],
- },
- },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- const progress = events.find(
- (event): event is Extract<ExecutionEvent, { type: "progress" }> =>
- event.type === "progress" && event.stdoutBytes > 0,
- );
- expect(result.status).toBe("completed");
- expect(progress).toBeDefined();
- expect(progress?.elapsedMs).toBeGreaterThan(0);
- expect(progress?.stdoutBytes).toBeGreaterThan(0);
- expect(progress?.stdoutTail).toContain("first");
- });
- it("applies cwd and env overlay through spawn options", async () => {
- const adapter = new NodeExecutionAdapter();
- const cwd = await realpath(await mkdtemp(join(tmpdir(), "zcode-exec-")));
- const previousUnsetValue = process.env.ZCODE_EXEC_UNSET;
- process.env.ZCODE_EXEC_UNSET = "remove-me";
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "process.stdout.write(JSON.stringify({",
- "cwd: process.cwd(),",
- "value: process.env.ZCODE_EXEC_TEST,",
- "unset: process.env.ZCODE_EXEC_UNSET ?? null",
- "}))",
- ].join(""),
- ],
- },
- cwd,
- env: {
- base: "inherit",
- set: {
- ZCODE_EXEC_TEST: "yes",
- },
- unset: ["ZCODE_EXEC_UNSET"],
- },
- });
- const parsed = JSON.parse(result.stdout.text) as {
- cwd: string;
- value?: string;
- unset: string | null;
- };
- expect(result.status).toBe("completed");
- expect(parsed.cwd).toBe(cwd);
- expect(parsed.value).toBe("yes");
- expect(parsed.unset).toBeNull();
- } finally {
- if (previousUnsetValue === undefined) {
- delete process.env.ZCODE_EXEC_UNSET;
- } else {
- process.env.ZCODE_EXEC_UNSET = previousUnsetValue;
- }
- await rm(cwd, { force: true, recursive: true });
- }
- });
- it("deduplicates Windows environment keys when applying overlays", () => {
- const env = buildExecutionEnv(
- {
- base: "inherit",
- set: {
- PATH: "C:\\next-bin",
- },
- unset: ["temp"],
- },
- {
- platform: "win32",
- processEnv: {
- Path: "C:\\base-bin",
- TEMP: "C:\\Temp",
- ZCODE_KEEP: "yes",
- },
- },
- );
- expect(env.PATH).toBe("C:\\next-bin");
- expect(env.Path).toBeUndefined();
- expect(env.TEMP).toBeUndefined();
- expect(env.ZCODE_KEEP).toBe("yes");
- });
- it("injects configured network egress variables for subprocesses", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {
- caCertFile: "/tmp/zcode-ca.pem",
- httpProxy: "127.0.0.1:8888",
- noProxy: "localhost,127.0.0.1",
- },
- platform: "linux",
- processEnv: {
- HTTP_PROXY: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- },
- },
- );
- expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.ALL_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.http_proxy).toBe("http://127.0.0.1:8888");
- expect(env.https_proxy).toBe("http://127.0.0.1:8888");
- expect(env.all_proxy).toBe("http://127.0.0.1:8888");
- expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
- expect(env.no_proxy).toBe("localhost,127.0.0.1");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
- expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
- });
- it("ignores ambient standard proxy and CA env for subprocesses", () => {
- const env = buildExecutionEnv(undefined, {
- network: {},
- platform: "linux",
- processEnv: {
- NODE_ENV: "development",
- http_proxy: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- no_proxy: ".example.test",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.NODE_ENV).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.http_proxy).toBeUndefined();
- expect(env.NO_PROXY).toBeUndefined();
- expect(env.no_proxy).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
- expect(env.SSL_CERT_FILE).toBeUndefined();
- expect(env.REQUESTS_CA_BUNDLE).toBeUndefined();
- expect(env.CURL_CA_BUNDLE).toBeUndefined();
- expect(env.GIT_SSL_CAINFO).toBeUndefined();
- expect(env.PATH).toBe("/usr/bin:/bin");
- });
- it("restores captured user proxy and CA env for inherited subprocesses", () => {
- const env = buildExecutionEnv(undefined, {
- network: {},
- platform: "linux",
- processEnv: {
- [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- http_proxy: "http://shell-proxy:8080",
- no_proxy: ".example.test",
- npm_config_proxy: "http://npm-proxy:8080",
- }),
- NODE_ENV: "development",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.NODE_ENV).toBeUndefined();
- expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.http_proxy).toBe("http://shell-proxy:8080");
- expect(env.NO_PROXY).toBeUndefined();
- expect(env.no_proxy).toBe(".example.test");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/shell-ca.pem");
- expect(env.npm_config_proxy).toBe("http://npm-proxy:8080");
- expect(env.PATH).toBe("/usr/bin:/bin");
- });
- it("does not restore captured user env when command base is empty", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {},
- platform: "linux",
- processEnv: {
- [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
- HTTP_PROXY: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- }),
- },
- },
- );
- expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
- });
- it("derives subprocess proxy and CA env from explicit ZCode runtime keys", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {},
- platform: "linux",
- processEnv: {
- ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
- ZCODE_HTTP_PROXY: "127.0.0.1:8888",
- [ZCODE_NO_PROXY_ENV_KEY]: "localhost,127.0.0.1",
- },
- },
- );
- expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.http_proxy).toBe("http://127.0.0.1:8888");
- expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
- expect(env.no_proxy).toBe("localhost,127.0.0.1");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
- expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
- });
- it("lets per-command env overlays override injected network env", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- set: {
- HTTP_PROXY: "http://command-proxy:8080",
- },
- unset: ["SSL_CERT_FILE"],
- },
- {
- network: {
- caCertFile: "/tmp/zcode-ca.pem",
- httpProxy: "http://zcode-proxy:8080",
- },
- platform: "linux",
- processEnv: {},
- },
- );
- expect(env.HTTP_PROXY).toBe("http://command-proxy:8080");
- expect(env.HTTPS_PROXY).toBe("http://zcode-proxy:8080");
- expect(env.SSL_CERT_FILE).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- });
- it("adds a UTF-8 locale for subprocess text output when the parent locale is C", () => {
- const env = buildExecutionEnv(undefined, {
- platform: "darwin",
- processEnv: {
- LANG: "C",
- LC_ALL: "",
- LC_CTYPE: "POSIX",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.LANG).toBe("en_US.UTF-8");
- expect(env.LC_ALL).toBe("en_US.UTF-8");
- expect(env.LC_CTYPE).toBe("en_US.UTF-8");
- expect(env.PYTHONIOENCODING).toBe("utf-8");
- expect(env.PYTHONUTF8).toBe("1");
- });
- it.skipIf(process.platform === "win32")(
- "keeps unicode path text from POSIX tools even when the parent locale is C",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cn-"));
- const dir = join(root, "草稿");
- const file = join(dir, "file.txt");
- await mkdir(dir, { recursive: true });
- await writeFile(file, "a\nb\n");
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- LANG: "C",
- LC_ALL: "",
- LC_CTYPE: "C",
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: "wc",
- args: ["-l", file],
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toContain("草稿");
- expect(result.stdout.text).not.toContain("??");
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- },
- );
- it("decodes Windows legacy Chinese output without corrupting UTF-8 output", () => {
- const legacy = iconv.encode("草稿", "gb18030");
- const westernLegacy = iconv.encode("é", "cp1252");
- const utf8 = Buffer.from("草稿", "utf8");
- expect(decodeExecutionOutputBuffer(legacy, "gb18030")).toBe("草稿");
- expect(decodeExecutionOutputBuffer(westernLegacy, "cp1252")).toBe("é");
- expect(decodeExecutionOutputBuffer(utf8, "gb18030")).toBe("草稿");
- });
- it.skipIf(!POSIX_BASH_PATH)("can rewrite posix-bash commands without -l", () => {
- const command = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo before",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- {
- env: process.env,
- platform: process.platform,
- },
- );
- expect(command.args).toEqual(["-c", "-l", "echo before"]);
- const withoutLogin = setResolvedShellLoginMode(command, false);
- expect(withoutLogin.args).toEqual(["-c", "echo before"]);
- const rewritten = applyResolvedShellCommandForTest(withoutLogin, "echo after");
- expect(rewritten.args).toEqual(["-c", "echo after"]);
- });
- it("resolves Windows .cmd argv commands through cmd.exe", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "argv",
- file: "pnpm",
- args: ["--version"],
- },
- {
- cwd: "C:\\repo",
- env: {
- ComSpec: "C:\\Windows\\System32\\cmd.exe",
- Path: "C:\\tools;C:\\other",
- PATHEXT: ".COM;.EXE;.BAT;.CMD",
- },
- exists: (path) => path === "C:\\tools\\pnpm.cmd",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: ["/d", "/s", "/c", "C:\\tools\\pnpm.cmd --version"],
- cwdDialect: "cmd",
- file: "C:\\Windows\\System32\\cmd.exe",
- shell: false,
- });
- });
- it("quotes Windows .cmd argv arguments without requiring git-bash", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "argv",
- file: "pnpm",
- args: ["run", "say hi", "A&B", "100%done", "caret^value", "pipe|value"],
- },
- {
- cwd: "C:\\repo",
- env: {
- ComSpec: "C:\\Windows\\System32\\cmd.exe",
- Path: "C:\\Program Files\\node tools",
- PATHEXT: ".COM;.EXE;.BAT;.CMD",
- },
- exists: (path) => path === "C:\\Program Files\\node tools\\pnpm.cmd",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [
- "/d",
- "/s",
- "/c",
- '"C:\\Program Files\\node tools\\pnpm.cmd" run "say hi" "A^&B" "100^%done" "caret^^value" "pipe^|value"',
- ],
- cwdDialect: "cmd",
- file: "C:\\Windows\\System32\\cmd.exe",
- shell: false,
- });
- });
- it("keeps Windows .exe argv commands shell-free after PATH resolution", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "argv",
- file: "tool",
- args: ["run"],
- },
- {
- env: {
- PATH: "C:\\tools",
- PATHEXT: ".EXE;.CMD",
- },
- exists: (path) => path === "C:\\tools\\tool.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: ["run"],
- cwdDialect: "cmd",
- file: "C:\\tools\\tool.exe",
- shell: false,
- });
- });
- it("uses ComSpec as the default Windows shell", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- },
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps generic Windows shell commands on the legacy shell path", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:C:\\Program Files\\Git\\bin\\bash.exe",
- label: "Git Bash",
- path: "C:\\Program Files\\Git\\bin\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
- },
- exists: () => {
- throw new Error("Git Bash resolver should not run without shellProfile");
- },
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps generic POSIX shell commands on the legacy Node shell path", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- },
- {
- env: {
- PATH: "/bin:/usr/bin",
- SHELL: "/bin/bash",
- },
- exists: () => {
- throw new Error("posix shell resolver should not run without shellProfile");
- },
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- });
- it("uses a valid user-configured Windows Git Bash override before auto detection", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:D:\\Tools\\Git\\bin\\bash.exe",
- label: "Git Bash",
- path: "D:\\Tools\\Git\\bin\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) =>
- path === "D:\\Tools\\Git\\bin\\bash.exe" ||
- path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "D:\\Tools\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("falls back to auto detection when the user-configured shell no longer exists", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:D:\\Missing\\bash.exe",
- label: "Git Bash",
- path: "D:\\Missing\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- cwdDialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("resolves Windows Git Bash from the default Program Files path for posix-bash", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("resolves Windows Git Bash from git.exe on PATH", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "D:\\Apps\\Git\\cmd",
- },
- exists: (path) =>
- path === "D:\\Apps\\Git\\cmd\\git.exe" || path === "D:\\Apps\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "D:\\Apps\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("uses a valid user-configured Windows cmd override before auto detection", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "cmd",
- id: "cmd:C:\\Windows\\System32\\cmd.exe",
- label: "CMD",
- path: "C:\\Windows\\System32\\cmd.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) =>
- path === "C:\\Windows\\System32\\cmd.exe" ||
- path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("uses the cmd.exe fallback override before auto Git Bash detection", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "cmd",
- id: "cmd:cmd.exe",
- label: "CMD",
- path: "cmd.exe",
- source: "user-config",
- },
- },
- {
- env: {
- PATH: "C:\\Program Files\\Git\\cmd",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "cmd.exe",
- });
- });
- it("falls back to ComSpec when Windows Git Bash cannot be resolved", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\tools",
- SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
- },
- exists: () => false,
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps CMD parentheses and metacharacters unchanged in the Bash fallback", () => {
- const command = "if exist input.txt (echo yes) else (echo no) & echo done";
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command,
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\tools",
- },
- exists: () => false,
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: command,
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("converts Windows and Git Bash paths in both directions", () => {
- expect(windowsPathToGitBashPath("C:\\repo\\sub")).toBe("/c/repo/sub");
- expect(windowsPathToGitBashPath("C:/repo/sub")).toBe("/c/repo/sub");
- expect(windowsPathToGitBashPath("C:repo\\sub")).toBe("C:repo/sub");
- expect(windowsPathToGitBashPath("\\\\server\\share\\repo")).toBe("//server/share/repo");
- expect(gitBashPathToWindowsPath("/c/repo/sub")).toBe("C:\\repo\\sub");
- expect(gitBashPathToWindowsPath("/cygdrive/d/repo")).toBe("D:\\repo");
- expect(gitBashPathToWindowsPath("//server/share/repo")).toBe("\\\\server\\share\\repo");
- });
- it.skipIf(process.platform === "win32")(
- "resolves posix-bash shell commands through bash without Node shell wrapping",
- () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/custom/bin",
- SHELL: "/bin/bash",
- },
- exists: (path) => path === "/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: ["-c", "-l", "echo ok"],
- cwdDialect: "posix",
- envOverlay: {
- GIT_EDITOR: "true",
- SHELL: "/bin/bash",
- },
- file: "/bin/bash",
- shell: false,
- usesLoginShell: true,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "prefers zsh for posix-bash shell commands when the user shell is not bash",
- () => {
- const resolution = resolveEffectiveBashShellSelection({
- env: {
- PATH: "/zsh/bin:/bash/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
- platform: "darwin",
- });
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/zsh/bin:/bash/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
- platform: "darwin",
- },
- );
- expect(resolution.selection).toMatchObject({
- dialect: "posix",
- display: { name: "zsh" },
- path: "/zsh/bin/zsh",
- source: "auto-detected",
- });
- expect(resolution.provider?.file).toBe("/zsh/bin/zsh");
- expect(resolved.file).toBe("/zsh/bin/zsh");
- expect(resolved.args).toEqual(["-c", "-l", "echo ok"]);
- expect(resolved.shell).toBe(false);
- expect(resolved.envOverlay).toMatchObject({
- SHELL: "/zsh/bin/zsh",
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "falls back to fixed POSIX shell directories for posix-bash commands",
- () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/custom/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/usr/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "echo ok"],
- file: "/usr/bin/bash",
- shell: false,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "uses the provided auto-detected shell snapshot instead of re-detecting POSIX shells",
- () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellOverride: {
- dialect: "posix",
- display: { name: "zsh" },
- id: "auto:zsh",
- label: "zsh",
- path: "/snapshot/bin/zsh",
- source: "auto-detected",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/current/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/current/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "echo ok"],
- file: "/snapshot/bin/zsh",
- shell: false,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "falls back to the legacy shell command when posix-bash cannot resolve bash or zsh",
- () => {
- const resolution = resolveEffectiveBashShellSelection({
- env: {
- PATH: "/no-shells",
- SHELL: "/bin/fish",
- },
- exists: () => false,
- platform: "linux",
- });
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/no-shells",
- SHELL: "/bin/fish",
- },
- exists: () => false,
- platform: "linux",
- },
- );
- expect(resolution.selection).toMatchObject({
- dialect: "legacy-shell",
- display: { name: "system shell" },
- source: "legacy-fallback",
- });
- expect(resolution.provider).toBeUndefined();
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "preserves a legacy shell snapshot instead of re-detecting POSIX shells",
- () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellOverride: {
- dialect: "legacy-shell",
- display: { name: "system shell" },
- source: "legacy-fallback",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/current/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/current/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- },
- );
- it("describes auto-detected Windows Git Bash as the effective Bash shell", () => {
- const resolution = resolveEffectiveBashShellSelection({
- env: {
- PATH: "",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- });
- expect(resolution.selection).toMatchObject({
- dialect: "git-bash",
- display: { name: "Git Bash" },
- path: "C:\\Program Files\\Git\\bin\\bash.exe",
- source: "auto-detected",
- });
- expect(resolution.provider).toMatchObject({
- dialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("uses the provided auto-detected Windows Git Bash snapshot instead of re-detecting", () => {
- const resolved = resolveExecutionCommand(
- {
- mode: "shell",
- command: "pwd",
- shellOverride: {
- dialect: "git-bash",
- display: { name: "Git Bash" },
- id: "auto:git-bash",
- label: "Git Bash",
- path: "D:\\Git\\bin\\bash.exe",
- source: "auto-detected",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "pwd"],
- file: "D:\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("keeps explicit Windows CMD selection ahead of auto-detected Git Bash", () => {
- const resolution = resolveEffectiveBashShellSelection({
- env: {
- PATH: "",
- },
- exists: (path) => path === "cmd.exe" || path === "C:\\Program Files\\Git\\bin\\bash.exe",
- override: {
- dialect: "cmd",
- display: { name: "CMD" },
- id: "cmd",
- label: "CMD",
- path: "cmd.exe",
- source: "user-config",
- },
- platform: "win32",
- });
- expect(resolution.selection).toMatchObject({
- dialect: "cmd",
- display: { name: "CMD" },
- path: "cmd.exe",
- source: "user-config",
- });
- expect(resolution.provider).toMatchObject({
- dialect: "cmd",
- file: "cmd.exe",
- shell: "cmd.exe",
- });
- });
- it("returns non-zero exits as structured failed results", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stderr.write('bad'); process.exit(7)"],
- },
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(7);
- expect(result.stderr.text).toBe("bad");
- });
- it("keeps the Agent alive when a successful child closes stdin before a large write", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(0), 20);"],
- },
- stdin: "x".repeat(1024 * 1024),
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.error).toBeUndefined();
- });
- it("preserves a non-zero exit when the child closes stdin before a large write", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(7), 20);"],
- },
- stdin: "x".repeat(1024 * 1024),
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(7);
- });
- it("delivers a large stdin payload when the child consumes it", async () => {
- const adapter = new NodeExecutionAdapter();
- const stdin = "你好, ZCode!\n".repeat(100_000);
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let bytes = 0;",
- "process.stdin.on('data', chunk => { bytes += chunk.length; });",
- "process.stdin.on('end', () => process.stdout.write(String(bytes)));",
- ].join(" "),
- ],
- },
- stdin,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe(String(Buffer.byteLength(stdin)));
- });
- it("stops commands with a structured timeout result", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 5000)"],
- },
- timeoutMs: 50,
- });
- expect(result.status).toBe("timed_out");
- expect(result.timedOut).toBe(true);
- expect(result.cancelled).toBe(false);
- expect(result.error).toEqual({
- type: "timeout",
- message: "Command timed out after 50ms",
- });
- });
- it("timeout 只约束子进程运行阶段,准备较慢的命令不会未启动就被判 timed_out", async () => {
- // 回归:protected-resource sandbox 时代计时器被提前到准备阶段(覆盖 capability probe),
- // sandbox 撤除后该行为一度被保留——shell 初始化较慢或 timeout 较短时,命令还没 spawn
- // 就返回 timed_out。计时器必须在 spawn 之后才启动。
- const adapter = new NodeExecutionAdapter();
- const internals = adapter as unknown as {
- prepareChildSpawn: (request: unknown) => Promise<unknown>;
- };
- const originalPrepare = internals.prepareChildSpawn.bind(adapter);
- internals.prepareChildSpawn = async (request: unknown) => {
- await new Promise((resolve) => setTimeout(resolve, 150));
- return originalPrepare(request);
- };
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.exit(0)"],
- },
- timeoutMs: 60,
- });
- expect(result.status).toBe("completed");
- expect(result.timedOut).toBe(false);
- expect(result.exitCode).toBe(0);
- });
- it("stops commands with a structured cancellation result", async () => {
- const adapter = new NodeExecutionAdapter();
- const controller = new AbortController();
- setTimeout(() => controller.abort(), 50);
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 5000)"],
- },
- },
- {
- signal: controller.signal,
- },
- );
- expect(result.status).toBe("cancelled");
- expect(result.cancelled).toBe(true);
- expect(result.timedOut).toBe(false);
- });
- it("closes running background tasks during adapter shutdown", async () => {
- const adapter = new NodeExecutionAdapter();
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 10_000)"],
- },
- });
- await adapter.close();
- const snapshot = await adapter.getBackgroundTask(started.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- });
- it.skipIf(process.platform === "win32")(
- "kills child processes in the same process group when shutting down",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let childPidText = "";
- const script = [
- "const { spawn } = require('node:child_process');",
- "const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 10_000)'], { stdio: 'ignore' });",
- "process.stdout.write(String(child.pid));",
- "setTimeout(() => {}, 10_000);",
- ].join(" ");
- const runPromise = adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", script],
- },
- },
- {
- onEvent: (event) => {
- if (event.type === "stdout") {
- childPidText += event.text;
- }
- },
- },
- );
- let childPid = Number.NaN;
- for (let attempt = 0; attempt < 50; attempt += 1) {
- const trimmed = childPidText.trim();
- childPid = Number(trimmed);
- if (trimmed.length > 0 && Number.isInteger(childPid) && childPid > 0) {
- break;
- }
- await sleep(20);
- }
- expect(Number.isInteger(childPid)).toBe(true);
- expect(childPid).toBeGreaterThan(0);
- await adapter.close();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- let childStillRunning = true;
- for (let attempt = 0; attempt < 50; attempt += 1) {
- childStillRunning = isProcessAlive(childPid);
- if (!childStillRunning) {
- break;
- }
- await sleep(20);
- }
- expect(childStillRunning).toBe(false);
- },
- );
- it.skipIf(process.platform === "win32")(
- "keeps inherited-pipe descendants owned until background shutdown",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let output = "";
- let descendantPid = Number.NaN;
- const descendantScript = [
- "process.on('SIGTERM', () => {});",
- "setInterval(() => {}, 10_000);",
- ].join("");
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const started = await adapter.start(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- },
- {
- onEvent: (event) => {
- if (event.type === "stdout") output += event.text;
- },
- },
- );
- for (let attempt = 0; attempt < 100; attempt += 1) {
- descendantPid = Number(/descendant:(\d+)/u.exec(output)?.[1]);
- if (Number.isInteger(descendantPid) && descendantPid > 0) break;
- await sleep(20);
- }
- expect(Number.isInteger(descendantPid)).toBe(true);
- // 超过旧实现的一秒 drain 窗口后仍应由 execution 持有,而不是伪 completed。
- await sleep(1_100);
- expect((await adapter.getBackgroundTask(started.taskId))?.status).toBe("running");
- await adapter.close();
- const snapshot = await adapter.getBackgroundTask(started.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- expect(isProcessAlive(descendantPid)).toBe(false);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "cleans inherited-pipe descendants after the foreground drain deadline",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- const descendantScript = "setInterval(() => {}, 10_000);";
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- expect(isProcessAlive(descendantPid)).toBe(false);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "releases inherited pipes when a descendant escapes the original process group",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- const descendantScript = "setInterval(() => {}, 10_000);";
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const startedAt = Date.now();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- expect(Date.now() - startedAt).toBeLessThan(4_000);
- // 已脱离原 PGID 的第三方进程无法由纯 Node 可靠寻址,但不能继续用 pipe 保活 CLI。
- expect(isProcessAlive(descendantPid)).toBe(true);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "removes a precreated Bash output file when cancelled before spawn",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-pre-spawn-cancel-"));
- const parentTurn = new AbortController();
- parentTurn.abort();
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf unexpected",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-pre-spawn-cancel-session",
- attributes: { toolCallId: "bash-pre-spawn-cancel-tool" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("cancelled");
- await expect(
- stat(
- join(root, "bash-pre-spawn-cancel-session", "bash-pre-spawn-cancel-tool-stdout.log"),
- ),
- ).rejects.toMatchObject({ code: "ENOENT" });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "writes Bash stdout and stderr directly to one canonical output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-merged-"));
- const home = join(outputRootDir, "home");
- await mkdir(home, { recursive: true });
- const processEnv = {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command:
- "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-merged-session",
- attributes: { toolCallId: "bash-merged-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "bash-merged-session",
- "bash-merged-tool-stdout.log",
- );
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
- expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
- expect(result.stdout.artifactPath).toBe(outputPath);
- await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
- expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
- await expect(
- stat(join(outputRootDir, "bash-merged-session", "bash-merged-tool-stderr.log")),
- ).rejects.toMatchObject({ code: "ENOENT" });
- const failed = await adapter.run({
- command: {
- mode: "shell",
- command: "printf 'before\\n'; printf 'failure\\n' >&2; exit 7",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-merged-session",
- attributes: { toolCallId: "bash-merged-failed-tool" },
- } as any,
- });
- expect(failed).toMatchObject({
- status: "failed",
- exitCode: 7,
- stdout: {
- text: "before\nfailure\n",
- },
- stderr: {
- text: "",
- bytes: 0,
- },
- });
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "reports filesystem diagnostics for empty failed Bash output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-lost-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const cases = [
- {
- id: "disk-full",
- statfs: {
- bavail: 9n,
- bfree: 9n,
- blocks: 10n,
- bsize: 1024n * 1024n,
- ffree: 10_000n,
- files: 10_000n,
- type: 0n,
- },
- diagnostic: (outputDirectory: string) =>
- `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.`,
- },
- {
- id: "inode-full",
- statfs: {
- bavail: 100n,
- bfree: 100n,
- blocks: 100n,
- bsize: 1024n * 1024n,
- ffree: 999n,
- files: 10_000n,
- type: 0n,
- },
- diagnostic: (outputDirectory: string) =>
- `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.`,
- },
- ];
- try {
- for (const testCase of cases) {
- statfsMock.mockResolvedValueOnce(testCase.statfs);
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "exit 7",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- timeoutMs: 5_000,
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: `bash-${testCase.id}-session`,
- attributes: { toolCallId: `bash-${testCase.id}-tool` },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- const outputDirectory = join(outputRootDir, `bash-${testCase.id}-session`);
- expect(result.kind).toBe("foreground");
- expect(result.result).toMatchObject({
- status: "failed",
- exitCode: 7,
- stdout: {
- text: testCase.diagnostic(outputDirectory),
- },
- stderr: {
- text: "",
- bytes: 0,
- },
- });
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(statfsMock).toHaveBeenCalledWith(outputDirectory, { bigint: true });
- }
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "retains a secure zero-byte Bash artifact when persistence is always",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-empty-artifact-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: ":",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-empty-artifact-session",
- attributes: { toolCallId: "bash-empty-artifact-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "bash-empty-artifact-session",
- "bash-empty-artifact-tool-stdout.log",
- );
- expect(result).toMatchObject({
- status: "completed",
- stdout: {
- artifactBytes: 0,
- artifactPath: outputPath,
- artifactTruncated: false,
- bytes: 0,
- text: "",
- truncated: false,
- },
- });
- await expect(readFile(outputPath, "utf8")).resolves.toBe("");
- expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "settles Bash output preparation failures before spawning",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-prepare-"));
- const blockedSessionPath = join(outputRootDir, "blocked-session");
- await writeFile(blockedSessionPath, "not a directory");
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const events: ExecutionEvent[] = [];
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf unexpected",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "blocked-session",
- attributes: { toolCallId: "blocked-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("spawn_error");
- expect(result.result.error?.message).toContain("blocked-session");
- expect(events.some((event) => event.type === "started")).toBe(false);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)("settles a Bash artifact open failure before spawning", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-open-"));
- const outputPath = join(outputRootDir, "open-failure-session", "open-failure-tool-stdout.log");
- await mkdir(outputPath, { recursive: true });
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf output",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 1,
- maxPersistedBytes: 64,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "open-failure-session",
- attributes: { toolCallId: "open-failure-tool" },
- } as any,
- });
- expect(result.status).toBe("spawn_error");
- expect(result.stdout.artifactPath).toBeUndefined();
- expect(result.stdout.bytes).toBe(0);
- expect(result.error?.message).toContain("open-failure-tool-stdout.log");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)("does not create a parent WriteStream for Bash output", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-write-"));
- const outputPath = join(
- outputRootDir,
- "write-failure-session",
- "write-failure-tool-stdout.log",
- );
- const probePath = join(outputRootDir, "file-handle-probe");
- const probeHandle = await open(probePath, "w");
- const fileHandlePrototype = Object.getPrototypeOf(probeHandle) as {
- createWriteStream: typeof probeHandle.createWriteStream;
- };
- await probeHandle.close();
- await unlink(probePath);
- const createWriteStreamSpy = vi.spyOn(fileHandlePrototype, "createWriteStream");
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const launch = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf first; sleep 0.2; printf second",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "write-failure-session",
- attributes: { toolCallId: "write-failure-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(launch.kind).toBe("backgrounded");
- if (launch.kind !== "backgrounded") throw new Error("Expected background launch");
- const snapshot = await capable.waitForBackgroundTask!(launch.task.taskId);
- expect(snapshot).toMatchObject({
- outputPath,
- status: "completed",
- stdoutPersistedOutputPath: outputPath,
- });
- expect(snapshot?.result?.stdout.text).toBe("firstsecond");
- expect(snapshot?.result?.stdout.artifactPath).toBe(outputPath);
- expect(createWriteStreamSpy).not.toHaveBeenCalled();
- await expect(readFile(outputPath, "utf8")).resolves.toBe("firstsecond");
- } finally {
- createWriteStreamSpy.mockRestore();
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "rejects a symlinked Bash canonical output path",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-symlink-"));
- const sessionDir = join(outputRootDir, "symlink-session");
- const targetPath = join(outputRootDir, "target.log");
- const outputPath = join(sessionDir, "symlink-tool-stdout.log");
- await mkdir(sessionDir, { recursive: true });
- await writeFile(targetPath, "preserved");
- await symlink(targetPath, outputPath);
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf overwritten",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64,
- persistOutput: "always",
- },
- trace: {
- sessionId: "symlink-session",
- attributes: { toolCallId: "symlink-tool" },
- } as any,
- });
- expect(result.status).toBe("spawn_error");
- await expect(readFile(targetPath, "utf8")).resolves.toBe("preserved");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "does not kill descendants when the Bash root exits normally",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command:
- "(trap '' TERM HUP; while :; do sleep 10; done) & printf 'descendant:%s\\n' \"$!\"",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- // Bash 工具在 root 进程退出时结算,正常完成不主动清理后代;测试自行收尾。
- expect(isProcessAlive(descendantPid)).toBe(true);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH && !WINDOWS_GIT_BASH_PATH)(
- "settles the background task at root exit before late descendant output",
- async () => {
- const bashPath = POSIX_BASH_PATH ?? WINDOWS_GIT_BASH_PATH!;
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-descendant-progress-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- progressIntervalMs: 50,
- progressThresholdMs: 0,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "(sleep 0.5; printf late) & printf early",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: bashPath,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-descendant-progress-session",
- attributes: { toolCallId: "bash-descendant-progress-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const completed = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(completed).toMatchObject({
- status: "completed",
- result: {
- stdout: {
- text: "early",
- },
- },
- });
- expect(result.task.outputPath).toBeTypeOf("string");
- await sleep(600);
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("earlylate");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("keeps generic argv stdout and stderr separate", async () => {
- const adapter = new NodeExecutionAdapter();
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('stdout'); process.stderr.write('stderr')"],
- },
- });
- expect(result.stdout.text).toBe("stdout");
- expect(result.stderr.text).toBe("stderr");
- } finally {
- await adapter.close();
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "deletes redundant Bash files and keeps complete retained files without losing observed size",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-cap-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
- const shellOverride = {
- dialect: "posix" as const,
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected" as const,
- };
- try {
- const smallResult = await adapter.run({
- command: {
- mode: "shell",
- command: "printf ok",
- shellProfile: "posix-bash",
- shellOverride,
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- maxArtifactBytes: 4,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-cap-session",
- attributes: { toolCallId: "bash-small-tool" },
- } as any,
- });
- const smallPath = join(outputRootDir, "bash-cap-session", "bash-small-tool-stdout.log");
- expect(smallResult.stdout).toMatchObject({
- text: "ok",
- bytes: 2,
- truncated: false,
- });
- expect(smallResult.stdout.artifactPath).toBeUndefined();
- await expect(stat(smallPath)).rejects.toMatchObject({ code: "ENOENT" });
- const largeResult = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride,
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- maxArtifactBytes: 4,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-cap-session",
- attributes: { toolCallId: "bash-large-tool" },
- } as any,
- });
- expect(largeResult.stdout).toMatchObject({
- text: "abc",
- bytes: 6,
- truncated: true,
- artifactBytes: 6,
- artifactTruncated: false,
- });
- await expect(readFile(largeResult.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "allows a short Bash command to finish before the first soft-limit check",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-limit-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- processEnv,
- progressIntervalMs: 5,
- progressThresholdMs: 0,
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- timeoutMs: 5_000,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-watchdog-session",
- attributes: { toolCallId: "bash-watchdog-tool" },
- } as any,
- });
- expect(result).toMatchObject({
- status: "completed",
- stdout: {
- text: "abc",
- bytes: 6,
- artifactBytes: 6,
- artifactTruncated: false,
- },
- });
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- expect(result.error).toBeUndefined();
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("parses BASH_MAX_OUTPUT_LENGTH within its documented bounds", () => {
- expect(resolveBashMaxOutputLength({}, 30_000)).toBe(30_000);
- expect(resolveBashMaxOutputLength({}, 120)).toBe(120);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: " " }, 120)).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "4096suffix" })).toBe(4096);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "invalid" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "0" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "-1" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "200000" })).toBe(150_000);
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "applies BASH_MAX_OUTPUT_LENGTH when reading the Bash output file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-env-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- BASH_MAX_OUTPUT_LENGTH: "4suffix",
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 100,
- maxPersistedBytes: 64,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-env-limit-session",
- attributes: { toolCallId: "bash-env-limit-tool" },
- } as any,
- });
- expect(result.stdout).toMatchObject({
- text: "abcd",
- bytes: 6,
- truncated: true,
- artifactBytes: 6,
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps the 30000-byte Bash boundary inline and persists byte 30001",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-default-limit-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv,
- });
- try {
- for (const size of [30_000, 30_001]) {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`,
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-default-limit-session",
- attributes: { toolCallId: `bash-default-limit-${size}` },
- } as any,
- });
- expect(result.stdout.bytes).toBe(size);
- expect(result.stdout.text).toHaveLength(30_000);
- expect(result.stdout.truncated).toBe(size > 30_000);
- expect(result.stdout.artifactPath !== undefined).toBe(size > 30_000);
- }
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("truncates inline output while preserving observed byte counts", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- },
- });
- expect(result.stdout.text).toBe("abc");
- expect(result.stdout.bytes).toBe(6);
- expect(result.stdout.truncated).toBe(true);
- });
- it("persists full stream output once inline output is truncated", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- persistOutput: "on_truncate",
- },
- trace: {
- traceId: "trace-output" as never,
- sessionId: "session-output" as never,
- attributes: {
- toolCallId: "tool-output",
- },
- },
- });
- expect(result.stdout.text).toBe("abc");
- expect(result.stdout.truncated).toBe(true);
- expect(result.stdout.artifactPath).toBeDefined();
- expect(result.stdout.artifactBytes).toBe(6);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("uses the ZCode storage root for persisted output when no output root is injected", async () => {
- const storageRoot = await mkdtemp(join(tmpdir(), "zcode-exec-storage-root-"));
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- ZCODE_STORAGE_DIR: storageRoot,
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- persistOutput: "on_truncate",
- },
- trace: {
- traceId: "trace-storage-root" as never,
- sessionId: "session-storage-root" as never,
- attributes: {
- toolCallId: "tool-storage-root",
- },
- },
- });
- expect(result.stdout.artifactPath).toBe(
- join(storageRoot, "cli", "exec", "session-storage-root", "tool-storage-root-stdout.log"),
- );
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await rm(storageRoot, { force: true, recursive: true });
- }
- });
- it("caps persisted stream output while continuing to drain the child", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- persistOutput: "on_truncate",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.bytes).toBe(6);
- expect(result.stdout.artifactBytes).toBe(4);
- expect(result.stdout.artifactTruncated).toBe(true);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcd");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("kills the process when persisted output reaches a watchdog limit", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('x'.repeat(100)); setTimeout(() => {}, 5000)"],
- },
- timeoutMs: 5000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 4,
- persistOutput: "always",
- killProcessOnPersistedLimit: true,
- },
- });
- expect(result.status).toBe("failed");
- expect(result.error?.type).toBe("output_limit");
- expect(result.stdout.bytes).toBe(100);
- expect(result.stdout.artifactBytes).toBe(4);
- expect(result.stdout.artifactTruncated).toBe(true);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("xxxx");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("shares one persisted watchdog limit across stdout and stderr", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-aggregate-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "process.stdout.write('a'.repeat(8)); process.stderr.write('b'.repeat(8)); setTimeout(() => {}, 5000)",
- ],
- },
- timeoutMs: 5000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 10,
- persistOutput: "always",
- killProcessOnPersistedLimit: true,
- },
- },
- {
- sharePersistedOutputLimitAcrossStreams: true,
- } as ExecutionRunOptions & {
- sharePersistedOutputLimitAcrossStreams: boolean;
- },
- );
- expect(result.status).toBe("failed");
- expect(result.error?.type).toBe("output_limit");
- expect((result.stdout.artifactBytes ?? 0) + (result.stderr.artifactBytes ?? 0)).toBe(10);
- const [stdoutArtifact, stderrArtifact] = await Promise.all([
- readFile(result.stdout.artifactPath!),
- readFile(result.stderr.artifactPath!),
- ]);
- expect(stdoutArtifact.byteLength + stderrArtifact.byteLength).toBe(10);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("tracks background executions until completion", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-background-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('bg'), 25)"],
- },
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- traceId: "trace-bg" as never,
- sessionId: "session-bg" as never,
- attributes: {
- toolCallId: "tool-bg",
- },
- },
- });
- expect(started.status).toBe("running");
- expect(started.outputPath).toBe(join(outputRootDir, "session-bg", "tool-bg-stdout.log"));
- expect(started.stdoutPersistedOutputPath).toBe(started.outputPath);
- expect(started.stderrPersistedOutputPath).toBe(
- join(outputRootDir, "session-bg", "tool-bg-stderr.log"),
- );
- await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("");
- await expect(readFile(started.stderrPersistedOutputPath!, "utf8")).resolves.toBe("");
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.outputPath).toBe(started.outputPath);
- expect(snapshot?.stdoutPersistedOutputPath).toBe(started.stdoutPersistedOutputPath);
- expect(snapshot?.stderrPersistedOutputPath).toBe(started.stderrPersistedOutputPath);
- expect(snapshot?.result?.stdout.text).toBe("bg");
- await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("bg");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("does not capture cwd for background shell executions", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-cwd-"));
- const child = join(root, "child");
- await mkdir(child);
- const adapter = new NodeExecutionAdapter();
- try {
- const started = await adapter.start({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}; printf bg`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("bg");
- expect(snapshot?.result?.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands in background executions",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const started = await adapter.start({
- command: {
- mode: "shell",
- command: "cat <(printf bg)",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- captureCwdAfterSuccess: true,
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 50 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("bg");
- expect(snapshot?.result?.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps one canonical Bash output file across explicit background commit",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-output-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf 'out\\n'; printf 'err\\n' >&2; sleep 0.05; printf 'done\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-background-output-session",
- attributes: { toolCallId: "bash-background-output-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(result.task.outputPath).toBe(result.task.stdoutPersistedOutputPath);
- expect(result.task.stderrPersistedOutputPath).toBeUndefined();
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBeDefined();
- await vi.waitFor(async () => {
- expect(await readFile(result.task.outputPath!, "utf8")).toContain("out");
- });
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.stdoutPersistedOutputPath).toBe(result.task.outputPath);
- expect(snapshot?.stderrPersistedOutputPath).toBeUndefined();
- expect(snapshot?.result?.stdout.text).toBe("out\nerr\ndone\n");
- expect(snapshot?.result?.stderr).toEqual({
- text: "",
- bytes: 0,
- truncated: false,
- });
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("out\nerr\ndone\n");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("updates background snapshots with progress output", async () => {
- const adapter = new NodeExecutionAdapter({
- progressIntervalMs: 10,
- progressTailBytes: 128,
- progressThresholdMs: 1,
- });
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ready'); setTimeout(() => {}, 1000)"],
- },
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 50 && snapshot?.stdoutBytes !== 5; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("running");
- expect(snapshot?.stdoutBytes).toBe(5);
- expect(snapshot?.stdoutTail).toBe("ready");
- const cancelled = await adapter.cancelBackgroundTask(started.taskId);
- expect(cancelled?.status).toBe("cancelled");
- });
- });
- function isProcessAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- } catch {
- return false;
- }
- if (process.platform === "win32") {
- return true;
- }
- try {
- const state = execFileSync("ps", ["-o", "stat=", "-p", String(pid)], {
- encoding: "utf8",
- }).trim();
- return state.length > 0 && !state.startsWith("Z");
- } catch {
- return false;
- }
- }
- function quotePosixShellArgument(value: string): string {
- return `'${value.replaceAll("'", `'\\''`)}'`;
- }
- function readPosixProcessGroupId(pid: number): number {
- return Number(
- execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], { encoding: "utf8" }).trim(),
- );
- }
|