main.rs 230 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793
  1. #![allow(
  2. dead_code,
  3. unused_imports,
  4. unused_variables,
  5. clippy::unneeded_struct_pattern,
  6. clippy::unnecessary_wraps,
  7. clippy::unused_self
  8. )]
  9. mod init;
  10. mod input;
  11. mod render;
  12. use std::collections::BTreeSet;
  13. use std::env;
  14. use std::fs;
  15. use std::io::{self, Read, Write};
  16. use std::net::TcpListener;
  17. use std::ops::{Deref, DerefMut};
  18. use std::path::{Path, PathBuf};
  19. use std::process::Command;
  20. use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
  21. use std::sync::{Arc, Mutex};
  22. use std::thread::{self, JoinHandle};
  23. use std::time::{Duration, Instant, UNIX_EPOCH};
  24. use api::{
  25. resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
  26. InputMessage, MessageRequest, MessageResponse, OutputContentBlock, PromptCache,
  27. StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
  28. };
  29. use commands::{
  30. handle_agents_slash_command, handle_mcp_slash_command, handle_plugins_slash_command,
  31. handle_skills_slash_command, render_slash_command_help, resume_supported_slash_commands,
  32. slash_command_specs, validate_slash_command_input, SlashCommand,
  33. };
  34. use compat_harness::{extract_manifest, UpstreamPaths};
  35. use init::initialize_repo;
  36. use plugins::{PluginHooks, PluginManager, PluginManagerConfig, PluginRegistry};
  37. use render::{MarkdownStreamState, Spinner, TerminalRenderer};
  38. use runtime::{
  39. clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
  40. parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
  41. ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
  42. ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest, OAuthConfig,
  43. OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, PromptCacheEvent,
  44. RuntimeError, Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
  45. };
  46. use serde_json::json;
  47. use tools::GlobalToolRegistry;
  48. const DEFAULT_MODEL: &str = "claude-opus-4-6";
  49. fn max_tokens_for_model(model: &str) -> u32 {
  50. if model.contains("opus") {
  51. 32_000
  52. } else {
  53. 64_000
  54. }
  55. }
  56. const DEFAULT_DATE: &str = "2026-03-31";
  57. const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
  58. const VERSION: &str = env!("CARGO_PKG_VERSION");
  59. const BUILD_TARGET: Option<&str> = option_env!("TARGET");
  60. const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
  61. const INTERNAL_PROGRESS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3);
  62. const PRIMARY_SESSION_EXTENSION: &str = "jsonl";
  63. const LEGACY_SESSION_EXTENSION: &str = "json";
  64. const LATEST_SESSION_REFERENCE: &str = "latest";
  65. const SESSION_REFERENCE_ALIASES: &[&str] = &[LATEST_SESSION_REFERENCE, "last", "recent"];
  66. const CLI_OPTION_SUGGESTIONS: &[&str] = &[
  67. "--help",
  68. "-h",
  69. "--version",
  70. "-V",
  71. "--model",
  72. "--output-format",
  73. "--permission-mode",
  74. "--dangerously-skip-permissions",
  75. "--allowedTools",
  76. "--allowed-tools",
  77. "--resume",
  78. "--print",
  79. "-p",
  80. ];
  81. type AllowedToolSet = BTreeSet<String>;
  82. fn main() {
  83. if let Err(error) = run() {
  84. let message = error.to_string();
  85. if message.contains("`claw --help`") {
  86. eprintln!("error: {message}");
  87. } else {
  88. eprintln!(
  89. "error: {message}
  90. Run `claw --help` for usage."
  91. );
  92. }
  93. std::process::exit(1);
  94. }
  95. }
  96. fn run() -> Result<(), Box<dyn std::error::Error>> {
  97. let args: Vec<String> = env::args().skip(1).collect();
  98. match parse_args(&args)? {
  99. CliAction::DumpManifests => dump_manifests(),
  100. CliAction::BootstrapPlan => print_bootstrap_plan(),
  101. CliAction::Agents { args } => LiveCli::print_agents(args.as_deref())?,
  102. CliAction::Mcp { args } => LiveCli::print_mcp(args.as_deref())?,
  103. CliAction::Skills { args } => LiveCli::print_skills(args.as_deref())?,
  104. CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
  105. CliAction::Version => print_version(),
  106. CliAction::ResumeSession {
  107. session_path,
  108. commands,
  109. } => resume_session(&session_path, &commands),
  110. CliAction::Status {
  111. model,
  112. permission_mode,
  113. } => print_status_snapshot(&model, permission_mode)?,
  114. CliAction::Sandbox => print_sandbox_status_snapshot()?,
  115. CliAction::Prompt {
  116. prompt,
  117. model,
  118. output_format,
  119. allowed_tools,
  120. permission_mode,
  121. } => LiveCli::new(model, true, allowed_tools, permission_mode)?
  122. .run_turn_with_output(&prompt, output_format)?,
  123. CliAction::Login => run_login()?,
  124. CliAction::Logout => run_logout()?,
  125. CliAction::Init => run_init()?,
  126. CliAction::Repl {
  127. model,
  128. allowed_tools,
  129. permission_mode,
  130. } => run_repl(model, allowed_tools, permission_mode)?,
  131. CliAction::Help => print_help(),
  132. }
  133. Ok(())
  134. }
  135. #[derive(Debug, Clone, PartialEq, Eq)]
  136. enum CliAction {
  137. DumpManifests,
  138. BootstrapPlan,
  139. Agents {
  140. args: Option<String>,
  141. },
  142. Mcp {
  143. args: Option<String>,
  144. },
  145. Skills {
  146. args: Option<String>,
  147. },
  148. PrintSystemPrompt {
  149. cwd: PathBuf,
  150. date: String,
  151. },
  152. Version,
  153. ResumeSession {
  154. session_path: PathBuf,
  155. commands: Vec<String>,
  156. },
  157. Status {
  158. model: String,
  159. permission_mode: PermissionMode,
  160. },
  161. Sandbox,
  162. Prompt {
  163. prompt: String,
  164. model: String,
  165. output_format: CliOutputFormat,
  166. allowed_tools: Option<AllowedToolSet>,
  167. permission_mode: PermissionMode,
  168. },
  169. Login,
  170. Logout,
  171. Init,
  172. Repl {
  173. model: String,
  174. allowed_tools: Option<AllowedToolSet>,
  175. permission_mode: PermissionMode,
  176. },
  177. // prompt-mode formatting is only supported for non-interactive runs
  178. Help,
  179. }
  180. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  181. enum CliOutputFormat {
  182. Text,
  183. Json,
  184. }
  185. impl CliOutputFormat {
  186. fn parse(value: &str) -> Result<Self, String> {
  187. match value {
  188. "text" => Ok(Self::Text),
  189. "json" => Ok(Self::Json),
  190. other => Err(format!(
  191. "unsupported value for --output-format: {other} (expected text or json)"
  192. )),
  193. }
  194. }
  195. }
  196. #[allow(clippy::too_many_lines)]
  197. fn parse_args(args: &[String]) -> Result<CliAction, String> {
  198. let mut model = DEFAULT_MODEL.to_string();
  199. let mut output_format = CliOutputFormat::Text;
  200. let mut permission_mode = default_permission_mode();
  201. let mut wants_help = false;
  202. let mut wants_version = false;
  203. let mut allowed_tool_values = Vec::new();
  204. let mut rest = Vec::new();
  205. let mut index = 0;
  206. while index < args.len() {
  207. match args[index].as_str() {
  208. "--help" | "-h" if rest.is_empty() => {
  209. wants_help = true;
  210. index += 1;
  211. }
  212. "--version" | "-V" => {
  213. wants_version = true;
  214. index += 1;
  215. }
  216. "--model" => {
  217. let value = args
  218. .get(index + 1)
  219. .ok_or_else(|| "missing value for --model".to_string())?;
  220. model = resolve_model_alias(value).to_string();
  221. index += 2;
  222. }
  223. flag if flag.starts_with("--model=") => {
  224. model = resolve_model_alias(&flag[8..]).to_string();
  225. index += 1;
  226. }
  227. "--output-format" => {
  228. let value = args
  229. .get(index + 1)
  230. .ok_or_else(|| "missing value for --output-format".to_string())?;
  231. output_format = CliOutputFormat::parse(value)?;
  232. index += 2;
  233. }
  234. "--permission-mode" => {
  235. let value = args
  236. .get(index + 1)
  237. .ok_or_else(|| "missing value for --permission-mode".to_string())?;
  238. permission_mode = parse_permission_mode_arg(value)?;
  239. index += 2;
  240. }
  241. flag if flag.starts_with("--output-format=") => {
  242. output_format = CliOutputFormat::parse(&flag[16..])?;
  243. index += 1;
  244. }
  245. flag if flag.starts_with("--permission-mode=") => {
  246. permission_mode = parse_permission_mode_arg(&flag[18..])?;
  247. index += 1;
  248. }
  249. "--dangerously-skip-permissions" => {
  250. permission_mode = PermissionMode::DangerFullAccess;
  251. index += 1;
  252. }
  253. "-p" => {
  254. // Claw Code compat: -p "prompt" = one-shot prompt
  255. let prompt = args[index + 1..].join(" ");
  256. if prompt.trim().is_empty() {
  257. return Err("-p requires a prompt string".to_string());
  258. }
  259. return Ok(CliAction::Prompt {
  260. prompt,
  261. model: resolve_model_alias(&model).to_string(),
  262. output_format,
  263. allowed_tools: normalize_allowed_tools(&allowed_tool_values)?,
  264. permission_mode,
  265. });
  266. }
  267. "--print" => {
  268. // Claw Code compat: --print makes output non-interactive
  269. output_format = CliOutputFormat::Text;
  270. index += 1;
  271. }
  272. "--resume" if rest.is_empty() => {
  273. rest.push("--resume".to_string());
  274. index += 1;
  275. }
  276. flag if rest.is_empty() && flag.starts_with("--resume=") => {
  277. rest.push("--resume".to_string());
  278. rest.push(flag[9..].to_string());
  279. index += 1;
  280. }
  281. "--allowedTools" | "--allowed-tools" => {
  282. let value = args
  283. .get(index + 1)
  284. .ok_or_else(|| "missing value for --allowedTools".to_string())?;
  285. allowed_tool_values.push(value.clone());
  286. index += 2;
  287. }
  288. flag if flag.starts_with("--allowedTools=") => {
  289. allowed_tool_values.push(flag[15..].to_string());
  290. index += 1;
  291. }
  292. flag if flag.starts_with("--allowed-tools=") => {
  293. allowed_tool_values.push(flag[16..].to_string());
  294. index += 1;
  295. }
  296. other if rest.is_empty() && other.starts_with('-') => {
  297. return Err(format_unknown_option(other))
  298. }
  299. other => {
  300. rest.push(other.to_string());
  301. index += 1;
  302. }
  303. }
  304. }
  305. if wants_help {
  306. return Ok(CliAction::Help);
  307. }
  308. if wants_version {
  309. return Ok(CliAction::Version);
  310. }
  311. let allowed_tools = normalize_allowed_tools(&allowed_tool_values)?;
  312. if rest.is_empty() {
  313. return Ok(CliAction::Repl {
  314. model,
  315. allowed_tools,
  316. permission_mode,
  317. });
  318. }
  319. if rest.first().map(String::as_str) == Some("--resume") {
  320. return parse_resume_args(&rest[1..]);
  321. }
  322. if let Some(action) = parse_single_word_command_alias(&rest, &model, permission_mode) {
  323. return action;
  324. }
  325. match rest[0].as_str() {
  326. "dump-manifests" => Ok(CliAction::DumpManifests),
  327. "bootstrap-plan" => Ok(CliAction::BootstrapPlan),
  328. "agents" => Ok(CliAction::Agents {
  329. args: join_optional_args(&rest[1..]),
  330. }),
  331. "mcp" => Ok(CliAction::Mcp {
  332. args: join_optional_args(&rest[1..]),
  333. }),
  334. "skills" => Ok(CliAction::Skills {
  335. args: join_optional_args(&rest[1..]),
  336. }),
  337. "system-prompt" => parse_system_prompt_args(&rest[1..]),
  338. "login" => Ok(CliAction::Login),
  339. "logout" => Ok(CliAction::Logout),
  340. "init" => Ok(CliAction::Init),
  341. "prompt" => {
  342. let prompt = rest[1..].join(" ");
  343. if prompt.trim().is_empty() {
  344. return Err("prompt subcommand requires a prompt string".to_string());
  345. }
  346. Ok(CliAction::Prompt {
  347. prompt,
  348. model,
  349. output_format,
  350. allowed_tools,
  351. permission_mode,
  352. })
  353. }
  354. other if other.starts_with('/') => parse_direct_slash_cli_action(&rest),
  355. _other => Ok(CliAction::Prompt {
  356. prompt: rest.join(" "),
  357. model,
  358. output_format,
  359. allowed_tools,
  360. permission_mode,
  361. }),
  362. }
  363. }
  364. fn parse_single_word_command_alias(
  365. rest: &[String],
  366. model: &str,
  367. permission_mode: PermissionMode,
  368. ) -> Option<Result<CliAction, String>> {
  369. if rest.len() != 1 {
  370. return None;
  371. }
  372. match rest[0].as_str() {
  373. "help" => Some(Ok(CliAction::Help)),
  374. "version" => Some(Ok(CliAction::Version)),
  375. "status" => Some(Ok(CliAction::Status {
  376. model: model.to_string(),
  377. permission_mode,
  378. })),
  379. "sandbox" => Some(Ok(CliAction::Sandbox)),
  380. other => bare_slash_command_guidance(other).map(Err),
  381. }
  382. }
  383. fn bare_slash_command_guidance(command_name: &str) -> Option<String> {
  384. if matches!(
  385. command_name,
  386. "dump-manifests"
  387. | "bootstrap-plan"
  388. | "agents"
  389. | "mcp"
  390. | "skills"
  391. | "system-prompt"
  392. | "login"
  393. | "logout"
  394. | "init"
  395. | "prompt"
  396. ) {
  397. return None;
  398. }
  399. let slash_command = slash_command_specs()
  400. .iter()
  401. .find(|spec| spec.name == command_name)?;
  402. let guidance = if slash_command.resume_supported {
  403. format!(
  404. "`claw {command_name}` is a slash command. Use `claw --resume SESSION.jsonl /{command_name}` or start `claw` and run `/{command_name}`."
  405. )
  406. } else {
  407. format!(
  408. "`claw {command_name}` is a slash command. Start `claw` and run `/{command_name}` inside the REPL."
  409. )
  410. };
  411. Some(guidance)
  412. }
  413. fn join_optional_args(args: &[String]) -> Option<String> {
  414. let joined = args.join(" ");
  415. let trimmed = joined.trim();
  416. (!trimmed.is_empty()).then(|| trimmed.to_string())
  417. }
  418. fn parse_direct_slash_cli_action(rest: &[String]) -> Result<CliAction, String> {
  419. let raw = rest.join(" ");
  420. match SlashCommand::parse(&raw) {
  421. Ok(Some(SlashCommand::Help)) => Ok(CliAction::Help),
  422. Ok(Some(SlashCommand::Agents { args })) => Ok(CliAction::Agents { args }),
  423. Ok(Some(SlashCommand::Mcp { action, target })) => Ok(CliAction::Mcp {
  424. args: match (action, target) {
  425. (None, None) => None,
  426. (Some(action), None) => Some(action),
  427. (Some(action), Some(target)) => Some(format!("{action} {target}")),
  428. (None, Some(target)) => Some(target),
  429. },
  430. }),
  431. Ok(Some(SlashCommand::Skills { args })) => Ok(CliAction::Skills { args }),
  432. Ok(Some(SlashCommand::Unknown(name))) => Err(format_unknown_direct_slash_command(&name)),
  433. Ok(Some(command)) => Err({
  434. let _ = command;
  435. format!(
  436. "slash command {command_name} is interactive-only. Start `claw` and run it there, or use `claw --resume SESSION.jsonl {command_name}` / `claw --resume {latest} {command_name}` when the command is marked [resume] in /help.",
  437. command_name = rest[0],
  438. latest = LATEST_SESSION_REFERENCE,
  439. )
  440. }),
  441. Ok(None) => Err(format!("unknown subcommand: {}", rest[0])),
  442. Err(error) => Err(error.to_string()),
  443. }
  444. }
  445. fn format_unknown_option(option: &str) -> String {
  446. let mut message = format!("unknown option: {option}");
  447. if let Some(suggestion) = suggest_closest_term(option, CLI_OPTION_SUGGESTIONS) {
  448. message.push_str("\nDid you mean ");
  449. message.push_str(suggestion);
  450. message.push('?');
  451. }
  452. message.push_str("\nRun `claw --help` for usage.");
  453. message
  454. }
  455. fn format_unknown_direct_slash_command(name: &str) -> String {
  456. let mut message = format!("unknown slash command outside the REPL: /{name}");
  457. if let Some(suggestions) = render_suggestion_line("Did you mean", &suggest_slash_commands(name))
  458. {
  459. message.push('\n');
  460. message.push_str(&suggestions);
  461. }
  462. message.push_str("\nRun `claw --help` for CLI usage, or start `claw` and use /help.");
  463. message
  464. }
  465. fn format_unknown_slash_command(name: &str) -> String {
  466. let mut message = format!("Unknown slash command: /{name}");
  467. if let Some(suggestions) = render_suggestion_line("Did you mean", &suggest_slash_commands(name))
  468. {
  469. message.push('\n');
  470. message.push_str(&suggestions);
  471. }
  472. message.push_str("\n Help /help lists available slash commands");
  473. message
  474. }
  475. fn render_suggestion_line(label: &str, suggestions: &[String]) -> Option<String> {
  476. (!suggestions.is_empty()).then(|| format!(" {label:<16} {}", suggestions.join(", "),))
  477. }
  478. fn suggest_slash_commands(input: &str) -> Vec<String> {
  479. let mut candidates = slash_command_specs()
  480. .iter()
  481. .flat_map(|spec| {
  482. std::iter::once(spec.name)
  483. .chain(spec.aliases.iter().copied())
  484. .map(|name| format!("/{name}"))
  485. .collect::<Vec<_>>()
  486. })
  487. .collect::<Vec<_>>();
  488. candidates.sort();
  489. candidates.dedup();
  490. let candidate_refs = candidates.iter().map(String::as_str).collect::<Vec<_>>();
  491. ranked_suggestions(input.trim_start_matches('/'), &candidate_refs)
  492. .into_iter()
  493. .map(str::to_string)
  494. .collect()
  495. }
  496. fn suggest_closest_term<'a>(input: &str, candidates: &'a [&'a str]) -> Option<&'a str> {
  497. ranked_suggestions(input, candidates).into_iter().next()
  498. }
  499. fn ranked_suggestions<'a>(input: &str, candidates: &'a [&'a str]) -> Vec<&'a str> {
  500. let normalized_input = input.trim_start_matches('/').to_ascii_lowercase();
  501. let mut ranked = candidates
  502. .iter()
  503. .filter_map(|candidate| {
  504. let normalized_candidate = candidate.trim_start_matches('/').to_ascii_lowercase();
  505. let distance = levenshtein_distance(&normalized_input, &normalized_candidate);
  506. let prefix_bonus = usize::from(
  507. !(normalized_candidate.starts_with(&normalized_input)
  508. || normalized_input.starts_with(&normalized_candidate)),
  509. );
  510. let score = distance + prefix_bonus;
  511. (score <= 4).then_some((score, *candidate))
  512. })
  513. .collect::<Vec<_>>();
  514. ranked.sort_by(|left, right| left.cmp(right).then_with(|| left.1.cmp(right.1)));
  515. ranked
  516. .into_iter()
  517. .map(|(_, candidate)| candidate)
  518. .take(3)
  519. .collect()
  520. }
  521. fn levenshtein_distance(left: &str, right: &str) -> usize {
  522. if left.is_empty() {
  523. return right.chars().count();
  524. }
  525. if right.is_empty() {
  526. return left.chars().count();
  527. }
  528. let right_chars = right.chars().collect::<Vec<_>>();
  529. let mut previous = (0..=right_chars.len()).collect::<Vec<_>>();
  530. let mut current = vec![0; right_chars.len() + 1];
  531. for (left_index, left_char) in left.chars().enumerate() {
  532. current[0] = left_index + 1;
  533. for (right_index, right_char) in right_chars.iter().enumerate() {
  534. let substitution_cost = usize::from(left_char != *right_char);
  535. current[right_index + 1] = (previous[right_index + 1] + 1)
  536. .min(current[right_index] + 1)
  537. .min(previous[right_index] + substitution_cost);
  538. }
  539. previous.clone_from(&current);
  540. }
  541. previous[right_chars.len()]
  542. }
  543. fn resolve_model_alias(model: &str) -> &str {
  544. match model {
  545. "opus" => "claude-opus-4-6",
  546. "sonnet" => "claude-sonnet-4-6",
  547. "haiku" => "claude-haiku-4-5-20251213",
  548. _ => model,
  549. }
  550. }
  551. fn normalize_allowed_tools(values: &[String]) -> Result<Option<AllowedToolSet>, String> {
  552. current_tool_registry()?.normalize_allowed_tools(values)
  553. }
  554. fn current_tool_registry() -> Result<GlobalToolRegistry, String> {
  555. let cwd = env::current_dir().map_err(|error| error.to_string())?;
  556. let loader = ConfigLoader::default_for(&cwd);
  557. let runtime_config = loader.load().map_err(|error| error.to_string())?;
  558. let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  559. let plugin_tools = plugin_manager
  560. .aggregated_tools()
  561. .map_err(|error| error.to_string())?;
  562. GlobalToolRegistry::with_plugin_tools(plugin_tools)
  563. }
  564. fn parse_permission_mode_arg(value: &str) -> Result<PermissionMode, String> {
  565. normalize_permission_mode(value)
  566. .ok_or_else(|| {
  567. format!(
  568. "unsupported permission mode '{value}'. Use read-only, workspace-write, or danger-full-access."
  569. )
  570. })
  571. .map(permission_mode_from_label)
  572. }
  573. fn permission_mode_from_label(mode: &str) -> PermissionMode {
  574. match mode {
  575. "read-only" => PermissionMode::ReadOnly,
  576. "workspace-write" => PermissionMode::WorkspaceWrite,
  577. "danger-full-access" => PermissionMode::DangerFullAccess,
  578. other => panic!("unsupported permission mode label: {other}"),
  579. }
  580. }
  581. fn default_permission_mode() -> PermissionMode {
  582. env::var("RUSTY_CLAUDE_PERMISSION_MODE")
  583. .ok()
  584. .as_deref()
  585. .and_then(normalize_permission_mode)
  586. .map_or(PermissionMode::DangerFullAccess, permission_mode_from_label)
  587. }
  588. fn filter_tool_specs(
  589. tool_registry: &GlobalToolRegistry,
  590. allowed_tools: Option<&AllowedToolSet>,
  591. ) -> Vec<ToolDefinition> {
  592. tool_registry.definitions(allowed_tools)
  593. }
  594. fn parse_system_prompt_args(args: &[String]) -> Result<CliAction, String> {
  595. let mut cwd = env::current_dir().map_err(|error| error.to_string())?;
  596. let mut date = DEFAULT_DATE.to_string();
  597. let mut index = 0;
  598. while index < args.len() {
  599. match args[index].as_str() {
  600. "--cwd" => {
  601. let value = args
  602. .get(index + 1)
  603. .ok_or_else(|| "missing value for --cwd".to_string())?;
  604. cwd = PathBuf::from(value);
  605. index += 2;
  606. }
  607. "--date" => {
  608. let value = args
  609. .get(index + 1)
  610. .ok_or_else(|| "missing value for --date".to_string())?;
  611. date.clone_from(value);
  612. index += 2;
  613. }
  614. other => return Err(format!("unknown system-prompt option: {other}")),
  615. }
  616. }
  617. Ok(CliAction::PrintSystemPrompt { cwd, date })
  618. }
  619. fn parse_resume_args(args: &[String]) -> Result<CliAction, String> {
  620. let (session_path, command_tokens): (PathBuf, &[String]) = match args.first() {
  621. None => (PathBuf::from(LATEST_SESSION_REFERENCE), &[]),
  622. Some(first) if looks_like_slash_command_token(first) => {
  623. (PathBuf::from(LATEST_SESSION_REFERENCE), args)
  624. }
  625. Some(first) => (PathBuf::from(first), &args[1..]),
  626. };
  627. let mut commands = Vec::new();
  628. let mut current_command = String::new();
  629. for token in command_tokens {
  630. if token.trim_start().starts_with('/') {
  631. if resume_command_can_absorb_token(&current_command, token) {
  632. current_command.push(' ');
  633. current_command.push_str(token);
  634. continue;
  635. }
  636. if !current_command.is_empty() {
  637. commands.push(current_command);
  638. }
  639. current_command = String::from(token.as_str());
  640. continue;
  641. }
  642. if current_command.is_empty() {
  643. return Err("--resume trailing arguments must be slash commands".to_string());
  644. }
  645. current_command.push(' ');
  646. current_command.push_str(token);
  647. }
  648. if !current_command.is_empty() {
  649. commands.push(current_command);
  650. }
  651. Ok(CliAction::ResumeSession {
  652. session_path,
  653. commands,
  654. })
  655. }
  656. fn resume_command_can_absorb_token(current_command: &str, token: &str) -> bool {
  657. matches!(
  658. SlashCommand::parse(current_command),
  659. Ok(Some(SlashCommand::Export { path: None }))
  660. ) && !looks_like_slash_command_token(token)
  661. }
  662. fn looks_like_slash_command_token(token: &str) -> bool {
  663. let trimmed = token.trim_start();
  664. let Some(name) = trimmed.strip_prefix('/').and_then(|value| {
  665. value
  666. .split_whitespace()
  667. .next()
  668. .map(str::trim)
  669. .filter(|value| !value.is_empty())
  670. }) else {
  671. return false;
  672. };
  673. slash_command_specs()
  674. .iter()
  675. .any(|spec| spec.name == name || spec.aliases.contains(&name))
  676. }
  677. fn dump_manifests() {
  678. let workspace_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
  679. let paths = UpstreamPaths::from_workspace_dir(&workspace_dir);
  680. match extract_manifest(&paths) {
  681. Ok(manifest) => {
  682. println!("commands: {}", manifest.commands.entries().len());
  683. println!("tools: {}", manifest.tools.entries().len());
  684. println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
  685. }
  686. Err(error) => {
  687. eprintln!("failed to extract manifests: {error}");
  688. std::process::exit(1);
  689. }
  690. }
  691. }
  692. fn print_bootstrap_plan() {
  693. for phase in runtime::BootstrapPlan::claude_code_default().phases() {
  694. println!("- {phase:?}");
  695. }
  696. }
  697. fn default_oauth_config() -> OAuthConfig {
  698. OAuthConfig {
  699. client_id: String::from("9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
  700. authorize_url: String::from("https://platform.claude.com/oauth/authorize"),
  701. token_url: String::from("https://platform.claude.com/v1/oauth/token"),
  702. callback_port: None,
  703. manual_redirect_url: None,
  704. scopes: vec![
  705. String::from("user:profile"),
  706. String::from("user:inference"),
  707. String::from("user:sessions:claude_code"),
  708. ],
  709. }
  710. }
  711. fn run_login() -> Result<(), Box<dyn std::error::Error>> {
  712. let cwd = env::current_dir()?;
  713. let config = ConfigLoader::default_for(&cwd).load()?;
  714. let default_oauth = default_oauth_config();
  715. let oauth = config.oauth().unwrap_or(&default_oauth);
  716. let callback_port = oauth.callback_port.unwrap_or(DEFAULT_OAUTH_CALLBACK_PORT);
  717. let redirect_uri = runtime::loopback_redirect_uri(callback_port);
  718. let pkce = generate_pkce_pair()?;
  719. let state = generate_state()?;
  720. let authorize_url =
  721. OAuthAuthorizationRequest::from_config(oauth, redirect_uri.clone(), state.clone(), &pkce)
  722. .build_url();
  723. println!("Starting Claude OAuth login...");
  724. println!("Listening for callback on {redirect_uri}");
  725. if let Err(error) = open_browser(&authorize_url) {
  726. eprintln!("warning: failed to open browser automatically: {error}");
  727. println!("Open this URL manually:\n{authorize_url}");
  728. }
  729. let callback = wait_for_oauth_callback(callback_port)?;
  730. if let Some(error) = callback.error {
  731. let description = callback
  732. .error_description
  733. .unwrap_or_else(|| "authorization failed".to_string());
  734. return Err(io::Error::other(format!("{error}: {description}")).into());
  735. }
  736. let code = callback.code.ok_or_else(|| {
  737. io::Error::new(io::ErrorKind::InvalidData, "callback did not include code")
  738. })?;
  739. let returned_state = callback.state.ok_or_else(|| {
  740. io::Error::new(io::ErrorKind::InvalidData, "callback did not include state")
  741. })?;
  742. if returned_state != state {
  743. return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
  744. }
  745. let client = AnthropicClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
  746. let exchange_request =
  747. OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
  748. let runtime = tokio::runtime::Runtime::new()?;
  749. let token_set = runtime.block_on(client.exchange_oauth_code(oauth, &exchange_request))?;
  750. save_oauth_credentials(&runtime::OAuthTokenSet {
  751. access_token: token_set.access_token,
  752. refresh_token: token_set.refresh_token,
  753. expires_at: token_set.expires_at,
  754. scopes: token_set.scopes,
  755. })?;
  756. println!("Claude OAuth login complete.");
  757. Ok(())
  758. }
  759. fn run_logout() -> Result<(), Box<dyn std::error::Error>> {
  760. clear_oauth_credentials()?;
  761. println!("Claude OAuth credentials cleared.");
  762. Ok(())
  763. }
  764. fn open_browser(url: &str) -> io::Result<()> {
  765. let commands = if cfg!(target_os = "macos") {
  766. vec![("open", vec![url])]
  767. } else if cfg!(target_os = "windows") {
  768. vec![("cmd", vec!["/C", "start", "", url])]
  769. } else {
  770. vec![("xdg-open", vec![url])]
  771. };
  772. for (program, args) in commands {
  773. match Command::new(program).args(args).spawn() {
  774. Ok(_) => return Ok(()),
  775. Err(error) if error.kind() == io::ErrorKind::NotFound => {}
  776. Err(error) => return Err(error),
  777. }
  778. }
  779. Err(io::Error::new(
  780. io::ErrorKind::NotFound,
  781. "no supported browser opener command found",
  782. ))
  783. }
  784. fn wait_for_oauth_callback(
  785. port: u16,
  786. ) -> Result<runtime::OAuthCallbackParams, Box<dyn std::error::Error>> {
  787. let listener = TcpListener::bind(("127.0.0.1", port))?;
  788. let (mut stream, _) = listener.accept()?;
  789. let mut buffer = [0_u8; 4096];
  790. let bytes_read = stream.read(&mut buffer)?;
  791. let request = String::from_utf8_lossy(&buffer[..bytes_read]);
  792. let request_line = request.lines().next().ok_or_else(|| {
  793. io::Error::new(io::ErrorKind::InvalidData, "missing callback request line")
  794. })?;
  795. let target = request_line.split_whitespace().nth(1).ok_or_else(|| {
  796. io::Error::new(
  797. io::ErrorKind::InvalidData,
  798. "missing callback request target",
  799. )
  800. })?;
  801. let callback = parse_oauth_callback_request_target(target)
  802. .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
  803. let body = if callback.error.is_some() {
  804. "Claude OAuth login failed. You can close this window."
  805. } else {
  806. "Claude OAuth login succeeded. You can close this window."
  807. };
  808. let response = format!(
  809. "HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
  810. body.len(),
  811. body
  812. );
  813. stream.write_all(response.as_bytes())?;
  814. Ok(callback)
  815. }
  816. fn print_system_prompt(cwd: PathBuf, date: String) {
  817. match load_system_prompt(cwd, date, env::consts::OS, "unknown") {
  818. Ok(sections) => println!("{}", sections.join("\n\n")),
  819. Err(error) => {
  820. eprintln!("failed to build system prompt: {error}");
  821. std::process::exit(1);
  822. }
  823. }
  824. }
  825. fn print_version() {
  826. println!("{}", render_version_report());
  827. }
  828. fn resume_session(session_path: &Path, commands: &[String]) {
  829. let resolved_path = if session_path.exists() {
  830. session_path.to_path_buf()
  831. } else {
  832. match resolve_session_reference(&session_path.display().to_string()) {
  833. Ok(handle) => handle.path,
  834. Err(error) => {
  835. eprintln!("failed to restore session: {error}");
  836. std::process::exit(1);
  837. }
  838. }
  839. };
  840. let session = match Session::load_from_path(&resolved_path) {
  841. Ok(session) => session,
  842. Err(error) => {
  843. eprintln!("failed to restore session: {error}");
  844. std::process::exit(1);
  845. }
  846. };
  847. if commands.is_empty() {
  848. println!(
  849. "Restored session from {} ({} messages).",
  850. resolved_path.display(),
  851. session.messages.len()
  852. );
  853. return;
  854. }
  855. let mut session = session;
  856. for raw_command in commands {
  857. let command = match SlashCommand::parse(raw_command) {
  858. Ok(Some(command)) => command,
  859. Ok(None) => {
  860. eprintln!("unsupported resumed command: {raw_command}");
  861. std::process::exit(2);
  862. }
  863. Err(error) => {
  864. eprintln!("{error}");
  865. std::process::exit(2);
  866. }
  867. };
  868. match run_resume_command(&resolved_path, &session, &command) {
  869. Ok(ResumeCommandOutcome {
  870. session: next_session,
  871. message,
  872. }) => {
  873. session = next_session;
  874. if let Some(message) = message {
  875. println!("{message}");
  876. }
  877. }
  878. Err(error) => {
  879. eprintln!("{error}");
  880. std::process::exit(2);
  881. }
  882. }
  883. }
  884. }
  885. #[derive(Debug, Clone)]
  886. struct ResumeCommandOutcome {
  887. session: Session,
  888. message: Option<String>,
  889. }
  890. #[derive(Debug, Clone)]
  891. struct StatusContext {
  892. cwd: PathBuf,
  893. session_path: Option<PathBuf>,
  894. loaded_config_files: usize,
  895. discovered_config_files: usize,
  896. memory_file_count: usize,
  897. project_root: Option<PathBuf>,
  898. git_branch: Option<String>,
  899. git_summary: GitWorkspaceSummary,
  900. sandbox_status: runtime::SandboxStatus,
  901. }
  902. #[derive(Debug, Clone, Copy)]
  903. struct StatusUsage {
  904. message_count: usize,
  905. turns: u32,
  906. latest: TokenUsage,
  907. cumulative: TokenUsage,
  908. estimated_tokens: usize,
  909. }
  910. #[allow(clippy::struct_field_names)]
  911. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
  912. struct GitWorkspaceSummary {
  913. changed_files: usize,
  914. staged_files: usize,
  915. unstaged_files: usize,
  916. untracked_files: usize,
  917. conflicted_files: usize,
  918. }
  919. impl GitWorkspaceSummary {
  920. fn is_clean(self) -> bool {
  921. self.changed_files == 0
  922. }
  923. fn headline(self) -> String {
  924. if self.is_clean() {
  925. "clean".to_string()
  926. } else {
  927. let mut details = Vec::new();
  928. if self.staged_files > 0 {
  929. details.push(format!("{} staged", self.staged_files));
  930. }
  931. if self.unstaged_files > 0 {
  932. details.push(format!("{} unstaged", self.unstaged_files));
  933. }
  934. if self.untracked_files > 0 {
  935. details.push(format!("{} untracked", self.untracked_files));
  936. }
  937. if self.conflicted_files > 0 {
  938. details.push(format!("{} conflicted", self.conflicted_files));
  939. }
  940. format!(
  941. "dirty · {} files · {}",
  942. self.changed_files,
  943. details.join(", ")
  944. )
  945. }
  946. }
  947. }
  948. #[cfg(test)]
  949. fn format_unknown_slash_command_message(name: &str) -> String {
  950. let suggestions = suggest_slash_commands(name);
  951. if suggestions.is_empty() {
  952. format!("unknown slash command: /{name}. Use /help to list available commands.")
  953. } else {
  954. format!(
  955. "unknown slash command: /{name}. Did you mean {}? Use /help to list available commands.",
  956. suggestions.join(", ")
  957. )
  958. }
  959. }
  960. fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
  961. format!(
  962. "Model
  963. Current model {model}
  964. Session messages {message_count}
  965. Session turns {turns}
  966. Usage
  967. Inspect current model with /model
  968. Switch models with /model <name>"
  969. )
  970. }
  971. fn format_model_switch_report(previous: &str, next: &str, message_count: usize) -> String {
  972. format!(
  973. "Model updated
  974. Previous {previous}
  975. Current {next}
  976. Preserved msgs {message_count}"
  977. )
  978. }
  979. fn format_permissions_report(mode: &str) -> String {
  980. let modes = [
  981. ("read-only", "Read/search tools only", mode == "read-only"),
  982. (
  983. "workspace-write",
  984. "Edit files inside the workspace",
  985. mode == "workspace-write",
  986. ),
  987. (
  988. "danger-full-access",
  989. "Unrestricted tool access",
  990. mode == "danger-full-access",
  991. ),
  992. ]
  993. .into_iter()
  994. .map(|(name, description, is_current)| {
  995. let marker = if is_current {
  996. "● current"
  997. } else {
  998. "○ available"
  999. };
  1000. format!(" {name:<18} {marker:<11} {description}")
  1001. })
  1002. .collect::<Vec<_>>()
  1003. .join(
  1004. "
  1005. ",
  1006. );
  1007. format!(
  1008. "Permissions
  1009. Active mode {mode}
  1010. Mode status live session default
  1011. Modes
  1012. {modes}
  1013. Usage
  1014. Inspect current mode with /permissions
  1015. Switch modes with /permissions <mode>"
  1016. )
  1017. }
  1018. fn format_permissions_switch_report(previous: &str, next: &str) -> String {
  1019. format!(
  1020. "Permissions updated
  1021. Result mode switched
  1022. Previous mode {previous}
  1023. Active mode {next}
  1024. Applies to subsequent tool calls
  1025. Usage /permissions to inspect current mode"
  1026. )
  1027. }
  1028. fn format_cost_report(usage: TokenUsage) -> String {
  1029. format!(
  1030. "Cost
  1031. Input tokens {}
  1032. Output tokens {}
  1033. Cache create {}
  1034. Cache read {}
  1035. Total tokens {}",
  1036. usage.input_tokens,
  1037. usage.output_tokens,
  1038. usage.cache_creation_input_tokens,
  1039. usage.cache_read_input_tokens,
  1040. usage.total_tokens(),
  1041. )
  1042. }
  1043. fn format_resume_report(session_path: &str, message_count: usize, turns: u32) -> String {
  1044. format!(
  1045. "Session resumed
  1046. Session file {session_path}
  1047. Messages {message_count}
  1048. Turns {turns}"
  1049. )
  1050. }
  1051. fn render_resume_usage() -> String {
  1052. format!(
  1053. "Resume
  1054. Usage /resume <session-path|session-id|{LATEST_SESSION_REFERENCE}>
  1055. Auto-save .claw/sessions/<session-id>.{PRIMARY_SESSION_EXTENSION}
  1056. Tip use /session list to inspect saved sessions"
  1057. )
  1058. }
  1059. fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
  1060. if skipped {
  1061. format!(
  1062. "Compact
  1063. Result skipped
  1064. Reason session below compaction threshold
  1065. Messages kept {resulting_messages}"
  1066. )
  1067. } else {
  1068. format!(
  1069. "Compact
  1070. Result compacted
  1071. Messages removed {removed}
  1072. Messages kept {resulting_messages}"
  1073. )
  1074. }
  1075. }
  1076. fn format_auto_compaction_notice(removed: usize) -> String {
  1077. format!("[auto-compacted: removed {removed} messages]")
  1078. }
  1079. fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
  1080. parse_git_status_metadata_for(
  1081. &env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
  1082. status,
  1083. )
  1084. }
  1085. fn parse_git_status_branch(status: Option<&str>) -> Option<String> {
  1086. let status = status?;
  1087. let first_line = status.lines().next()?;
  1088. let line = first_line.strip_prefix("## ")?;
  1089. if line.starts_with("HEAD") {
  1090. return Some("detached HEAD".to_string());
  1091. }
  1092. let branch = line.split(['.', ' ']).next().unwrap_or_default().trim();
  1093. if branch.is_empty() {
  1094. None
  1095. } else {
  1096. Some(branch.to_string())
  1097. }
  1098. }
  1099. fn parse_git_workspace_summary(status: Option<&str>) -> GitWorkspaceSummary {
  1100. let mut summary = GitWorkspaceSummary::default();
  1101. let Some(status) = status else {
  1102. return summary;
  1103. };
  1104. for line in status.lines() {
  1105. if line.starts_with("## ") || line.trim().is_empty() {
  1106. continue;
  1107. }
  1108. summary.changed_files += 1;
  1109. let mut chars = line.chars();
  1110. let index_status = chars.next().unwrap_or(' ');
  1111. let worktree_status = chars.next().unwrap_or(' ');
  1112. if index_status == '?' && worktree_status == '?' {
  1113. summary.untracked_files += 1;
  1114. continue;
  1115. }
  1116. if index_status != ' ' {
  1117. summary.staged_files += 1;
  1118. }
  1119. if worktree_status != ' ' {
  1120. summary.unstaged_files += 1;
  1121. }
  1122. if (matches!(index_status, 'U' | 'A') && matches!(worktree_status, 'U' | 'A'))
  1123. || index_status == 'U'
  1124. || worktree_status == 'U'
  1125. {
  1126. summary.conflicted_files += 1;
  1127. }
  1128. }
  1129. summary
  1130. }
  1131. fn resolve_git_branch_for(cwd: &Path) -> Option<String> {
  1132. let branch = run_git_capture_in(cwd, &["branch", "--show-current"])?;
  1133. let branch = branch.trim();
  1134. if !branch.is_empty() {
  1135. return Some(branch.to_string());
  1136. }
  1137. let fallback = run_git_capture_in(cwd, &["rev-parse", "--abbrev-ref", "HEAD"])?;
  1138. let fallback = fallback.trim();
  1139. if fallback.is_empty() {
  1140. None
  1141. } else if fallback == "HEAD" {
  1142. Some("detached HEAD".to_string())
  1143. } else {
  1144. Some(fallback.to_string())
  1145. }
  1146. }
  1147. fn run_git_capture_in(cwd: &Path, args: &[&str]) -> Option<String> {
  1148. let output = std::process::Command::new("git")
  1149. .args(args)
  1150. .current_dir(cwd)
  1151. .output()
  1152. .ok()?;
  1153. if !output.status.success() {
  1154. return None;
  1155. }
  1156. String::from_utf8(output.stdout).ok()
  1157. }
  1158. fn find_git_root_in(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
  1159. let output = std::process::Command::new("git")
  1160. .args(["rev-parse", "--show-toplevel"])
  1161. .current_dir(cwd)
  1162. .output()?;
  1163. if !output.status.success() {
  1164. return Err("not a git repository".into());
  1165. }
  1166. let path = String::from_utf8(output.stdout)?.trim().to_string();
  1167. if path.is_empty() {
  1168. return Err("empty git root".into());
  1169. }
  1170. Ok(PathBuf::from(path))
  1171. }
  1172. fn parse_git_status_metadata_for(
  1173. cwd: &Path,
  1174. status: Option<&str>,
  1175. ) -> (Option<PathBuf>, Option<String>) {
  1176. let branch = resolve_git_branch_for(cwd).or_else(|| parse_git_status_branch(status));
  1177. let project_root = find_git_root_in(cwd).ok();
  1178. (project_root, branch)
  1179. }
  1180. #[allow(clippy::too_many_lines)]
  1181. fn run_resume_command(
  1182. session_path: &Path,
  1183. session: &Session,
  1184. command: &SlashCommand,
  1185. ) -> Result<ResumeCommandOutcome, Box<dyn std::error::Error>> {
  1186. match command {
  1187. SlashCommand::Help => Ok(ResumeCommandOutcome {
  1188. session: session.clone(),
  1189. message: Some(render_repl_help()),
  1190. }),
  1191. SlashCommand::Compact => {
  1192. let result = runtime::compact_session(
  1193. session,
  1194. CompactionConfig {
  1195. max_estimated_tokens: 0,
  1196. ..CompactionConfig::default()
  1197. },
  1198. );
  1199. let removed = result.removed_message_count;
  1200. let kept = result.compacted_session.messages.len();
  1201. let skipped = removed == 0;
  1202. result.compacted_session.save_to_path(session_path)?;
  1203. Ok(ResumeCommandOutcome {
  1204. session: result.compacted_session,
  1205. message: Some(format_compact_report(removed, kept, skipped)),
  1206. })
  1207. }
  1208. SlashCommand::Clear { confirm } => {
  1209. if !confirm {
  1210. return Ok(ResumeCommandOutcome {
  1211. session: session.clone(),
  1212. message: Some(
  1213. "clear: confirmation required; rerun with /clear --confirm".to_string(),
  1214. ),
  1215. });
  1216. }
  1217. let cleared = Session::new();
  1218. cleared.save_to_path(session_path)?;
  1219. Ok(ResumeCommandOutcome {
  1220. session: cleared,
  1221. message: Some(format!(
  1222. "Cleared resumed session file {}.",
  1223. session_path.display()
  1224. )),
  1225. })
  1226. }
  1227. SlashCommand::Status => {
  1228. let tracker = UsageTracker::from_session(session);
  1229. let usage = tracker.cumulative_usage();
  1230. Ok(ResumeCommandOutcome {
  1231. session: session.clone(),
  1232. message: Some(format_status_report(
  1233. "restored-session",
  1234. StatusUsage {
  1235. message_count: session.messages.len(),
  1236. turns: tracker.turns(),
  1237. latest: tracker.current_turn_usage(),
  1238. cumulative: usage,
  1239. estimated_tokens: 0,
  1240. },
  1241. default_permission_mode().as_str(),
  1242. &status_context(Some(session_path))?,
  1243. )),
  1244. })
  1245. }
  1246. SlashCommand::Sandbox => {
  1247. let cwd = env::current_dir()?;
  1248. let loader = ConfigLoader::default_for(&cwd);
  1249. let runtime_config = loader.load()?;
  1250. Ok(ResumeCommandOutcome {
  1251. session: session.clone(),
  1252. message: Some(format_sandbox_report(&resolve_sandbox_status(
  1253. runtime_config.sandbox(),
  1254. &cwd,
  1255. ))),
  1256. })
  1257. }
  1258. SlashCommand::Cost => {
  1259. let usage = UsageTracker::from_session(session).cumulative_usage();
  1260. Ok(ResumeCommandOutcome {
  1261. session: session.clone(),
  1262. message: Some(format_cost_report(usage)),
  1263. })
  1264. }
  1265. SlashCommand::Config { section } => Ok(ResumeCommandOutcome {
  1266. session: session.clone(),
  1267. message: Some(render_config_report(section.as_deref())?),
  1268. }),
  1269. SlashCommand::Mcp { action, target } => {
  1270. let cwd = env::current_dir()?;
  1271. let args = match (action.as_deref(), target.as_deref()) {
  1272. (None, None) => None,
  1273. (Some(action), None) => Some(action.to_string()),
  1274. (Some(action), Some(target)) => Some(format!("{action} {target}")),
  1275. (None, Some(target)) => Some(target.to_string()),
  1276. };
  1277. Ok(ResumeCommandOutcome {
  1278. session: session.clone(),
  1279. message: Some(handle_mcp_slash_command(args.as_deref(), &cwd)?),
  1280. })
  1281. }
  1282. SlashCommand::Memory => Ok(ResumeCommandOutcome {
  1283. session: session.clone(),
  1284. message: Some(render_memory_report()?),
  1285. }),
  1286. SlashCommand::Init => Ok(ResumeCommandOutcome {
  1287. session: session.clone(),
  1288. message: Some(init_claude_md()?),
  1289. }),
  1290. SlashCommand::Diff => Ok(ResumeCommandOutcome {
  1291. session: session.clone(),
  1292. message: Some(render_diff_report_for(
  1293. session_path.parent().unwrap_or_else(|| Path::new(".")),
  1294. )?),
  1295. }),
  1296. SlashCommand::Version => Ok(ResumeCommandOutcome {
  1297. session: session.clone(),
  1298. message: Some(render_version_report()),
  1299. }),
  1300. SlashCommand::Export { path } => {
  1301. let export_path = resolve_export_path(path.as_deref(), session)?;
  1302. fs::write(&export_path, render_export_text(session))?;
  1303. Ok(ResumeCommandOutcome {
  1304. session: session.clone(),
  1305. message: Some(format!(
  1306. "Export\n Result wrote transcript\n File {}\n Messages {}",
  1307. export_path.display(),
  1308. session.messages.len(),
  1309. )),
  1310. })
  1311. }
  1312. SlashCommand::Agents { args } => {
  1313. let cwd = env::current_dir()?;
  1314. Ok(ResumeCommandOutcome {
  1315. session: session.clone(),
  1316. message: Some(handle_agents_slash_command(args.as_deref(), &cwd)?),
  1317. })
  1318. }
  1319. SlashCommand::Skills { args } => {
  1320. let cwd = env::current_dir()?;
  1321. Ok(ResumeCommandOutcome {
  1322. session: session.clone(),
  1323. message: Some(handle_skills_slash_command(args.as_deref(), &cwd)?),
  1324. })
  1325. }
  1326. SlashCommand::Unknown(name) => Err(format_unknown_slash_command(name).into()),
  1327. SlashCommand::Bughunter { .. }
  1328. | SlashCommand::Commit { .. }
  1329. | SlashCommand::Pr { .. }
  1330. | SlashCommand::Issue { .. }
  1331. | SlashCommand::Ultraplan { .. }
  1332. | SlashCommand::Teleport { .. }
  1333. | SlashCommand::DebugToolCall { .. }
  1334. | SlashCommand::Resume { .. }
  1335. | SlashCommand::Model { .. }
  1336. | SlashCommand::Permissions { .. }
  1337. | SlashCommand::Session { .. }
  1338. | SlashCommand::Plugins { .. } => Err("unsupported resumed slash command".into()),
  1339. }
  1340. }
  1341. fn run_repl(
  1342. model: String,
  1343. allowed_tools: Option<AllowedToolSet>,
  1344. permission_mode: PermissionMode,
  1345. ) -> Result<(), Box<dyn std::error::Error>> {
  1346. let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
  1347. let mut editor =
  1348. input::LineEditor::new("> ", cli.repl_completion_candidates().unwrap_or_default());
  1349. println!("{}", cli.startup_banner());
  1350. loop {
  1351. editor.set_completions(cli.repl_completion_candidates().unwrap_or_default());
  1352. match editor.read_line()? {
  1353. input::ReadOutcome::Submit(input) => {
  1354. let trimmed = input.trim().to_string();
  1355. if trimmed.is_empty() {
  1356. continue;
  1357. }
  1358. if matches!(trimmed.as_str(), "/exit" | "/quit") {
  1359. cli.persist_session()?;
  1360. break;
  1361. }
  1362. match SlashCommand::parse(&trimmed) {
  1363. Ok(Some(command)) => {
  1364. if cli.handle_repl_command(command)? {
  1365. cli.persist_session()?;
  1366. }
  1367. continue;
  1368. }
  1369. Ok(None) => {}
  1370. Err(error) => {
  1371. eprintln!("{error}");
  1372. continue;
  1373. }
  1374. }
  1375. editor.push_history(input);
  1376. cli.run_turn(&trimmed)?;
  1377. }
  1378. input::ReadOutcome::Cancel => {}
  1379. input::ReadOutcome::Exit => {
  1380. cli.persist_session()?;
  1381. break;
  1382. }
  1383. }
  1384. }
  1385. Ok(())
  1386. }
  1387. #[derive(Debug, Clone)]
  1388. struct SessionHandle {
  1389. id: String,
  1390. path: PathBuf,
  1391. }
  1392. #[derive(Debug, Clone)]
  1393. struct ManagedSessionSummary {
  1394. id: String,
  1395. path: PathBuf,
  1396. modified_epoch_millis: u128,
  1397. message_count: usize,
  1398. parent_session_id: Option<String>,
  1399. branch_name: Option<String>,
  1400. }
  1401. struct LiveCli {
  1402. model: String,
  1403. allowed_tools: Option<AllowedToolSet>,
  1404. permission_mode: PermissionMode,
  1405. system_prompt: Vec<String>,
  1406. runtime: BuiltRuntime,
  1407. session: SessionHandle,
  1408. }
  1409. struct RuntimePluginState {
  1410. feature_config: runtime::RuntimeFeatureConfig,
  1411. tool_registry: GlobalToolRegistry,
  1412. plugin_registry: PluginRegistry,
  1413. }
  1414. struct BuiltRuntime {
  1415. runtime: Option<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>>,
  1416. plugin_registry: PluginRegistry,
  1417. plugins_active: bool,
  1418. }
  1419. impl BuiltRuntime {
  1420. fn new(
  1421. runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
  1422. plugin_registry: PluginRegistry,
  1423. ) -> Self {
  1424. Self {
  1425. runtime: Some(runtime),
  1426. plugin_registry,
  1427. plugins_active: true,
  1428. }
  1429. }
  1430. fn with_hook_abort_signal(mut self, hook_abort_signal: runtime::HookAbortSignal) -> Self {
  1431. let runtime = self
  1432. .runtime
  1433. .take()
  1434. .expect("runtime should exist before installing hook abort signal");
  1435. self.runtime = Some(runtime.with_hook_abort_signal(hook_abort_signal));
  1436. self
  1437. }
  1438. fn shutdown_plugins(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  1439. if self.plugins_active {
  1440. self.plugin_registry.shutdown()?;
  1441. self.plugins_active = false;
  1442. }
  1443. Ok(())
  1444. }
  1445. }
  1446. impl Deref for BuiltRuntime {
  1447. type Target = ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>;
  1448. fn deref(&self) -> &Self::Target {
  1449. self.runtime
  1450. .as_ref()
  1451. .expect("runtime should exist while built runtime is alive")
  1452. }
  1453. }
  1454. impl DerefMut for BuiltRuntime {
  1455. fn deref_mut(&mut self) -> &mut Self::Target {
  1456. self.runtime
  1457. .as_mut()
  1458. .expect("runtime should exist while built runtime is alive")
  1459. }
  1460. }
  1461. impl Drop for BuiltRuntime {
  1462. fn drop(&mut self) {
  1463. let _ = self.shutdown_plugins();
  1464. }
  1465. }
  1466. struct HookAbortMonitor {
  1467. stop_tx: Option<Sender<()>>,
  1468. join_handle: Option<JoinHandle<()>>,
  1469. }
  1470. impl HookAbortMonitor {
  1471. fn spawn(abort_signal: runtime::HookAbortSignal) -> Self {
  1472. Self::spawn_with_waiter(abort_signal, move |stop_rx, abort_signal| {
  1473. let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
  1474. .enable_all()
  1475. .build()
  1476. else {
  1477. return;
  1478. };
  1479. runtime.block_on(async move {
  1480. let wait_for_stop = tokio::task::spawn_blocking(move || {
  1481. let _ = stop_rx.recv();
  1482. });
  1483. tokio::select! {
  1484. result = tokio::signal::ctrl_c() => {
  1485. if result.is_ok() {
  1486. abort_signal.abort();
  1487. }
  1488. }
  1489. _ = wait_for_stop => {}
  1490. }
  1491. });
  1492. })
  1493. }
  1494. fn spawn_with_waiter<F>(abort_signal: runtime::HookAbortSignal, wait_for_interrupt: F) -> Self
  1495. where
  1496. F: FnOnce(Receiver<()>, runtime::HookAbortSignal) + Send + 'static,
  1497. {
  1498. let (stop_tx, stop_rx) = mpsc::channel();
  1499. let join_handle = thread::spawn(move || wait_for_interrupt(stop_rx, abort_signal));
  1500. Self {
  1501. stop_tx: Some(stop_tx),
  1502. join_handle: Some(join_handle),
  1503. }
  1504. }
  1505. fn stop(mut self) {
  1506. if let Some(stop_tx) = self.stop_tx.take() {
  1507. let _ = stop_tx.send(());
  1508. }
  1509. if let Some(join_handle) = self.join_handle.take() {
  1510. let _ = join_handle.join();
  1511. }
  1512. }
  1513. }
  1514. impl LiveCli {
  1515. fn new(
  1516. model: String,
  1517. enable_tools: bool,
  1518. allowed_tools: Option<AllowedToolSet>,
  1519. permission_mode: PermissionMode,
  1520. ) -> Result<Self, Box<dyn std::error::Error>> {
  1521. let system_prompt = build_system_prompt()?;
  1522. let session_state = Session::new();
  1523. let session = create_managed_session_handle(&session_state.session_id)?;
  1524. let runtime = build_runtime(
  1525. session_state.with_persistence_path(session.path.clone()),
  1526. &session.id,
  1527. model.clone(),
  1528. system_prompt.clone(),
  1529. enable_tools,
  1530. true,
  1531. allowed_tools.clone(),
  1532. permission_mode,
  1533. None,
  1534. )?;
  1535. let cli = Self {
  1536. model,
  1537. allowed_tools,
  1538. permission_mode,
  1539. system_prompt,
  1540. runtime,
  1541. session,
  1542. };
  1543. cli.persist_session()?;
  1544. Ok(cli)
  1545. }
  1546. fn startup_banner(&self) -> String {
  1547. let cwd = env::current_dir().map_or_else(
  1548. |_| "<unknown>".to_string(),
  1549. |path| path.display().to_string(),
  1550. );
  1551. let status = status_context(None).ok();
  1552. let git_branch = status
  1553. .as_ref()
  1554. .and_then(|context| context.git_branch.as_deref())
  1555. .unwrap_or("unknown");
  1556. let workspace = status.as_ref().map_or_else(
  1557. || "unknown".to_string(),
  1558. |context| context.git_summary.headline(),
  1559. );
  1560. let session_path = self.session.path.strip_prefix(Path::new(&cwd)).map_or_else(
  1561. |_| self.session.path.display().to_string(),
  1562. |path| path.display().to_string(),
  1563. );
  1564. format!(
  1565. "\x1b[38;5;196m\
  1566. ██████╗██╗ █████╗ ██╗ ██╗\n\
  1567. ██╔════╝██║ ██╔══██╗██║ ██║\n\
  1568. ██║ ██║ ███████║██║ █╗ ██║\n\
  1569. ██║ ██║ ██╔══██║██║███╗██║\n\
  1570. ╚██████╗███████╗██║ ██║╚███╔███╔╝\n\
  1571. ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝\x1b[0m \x1b[38;5;208mCode\x1b[0m 🦞\n\n\
  1572. \x1b[2mModel\x1b[0m {}\n\
  1573. \x1b[2mPermissions\x1b[0m {}\n\
  1574. \x1b[2mBranch\x1b[0m {}\n\
  1575. \x1b[2mWorkspace\x1b[0m {}\n\
  1576. \x1b[2mDirectory\x1b[0m {}\n\
  1577. \x1b[2mSession\x1b[0m {}\n\
  1578. \x1b[2mAuto-save\x1b[0m {}\n\n\
  1579. Type \x1b[1m/help\x1b[0m for commands · \x1b[1m/status\x1b[0m for live context · \x1b[2m/resume latest\x1b[0m jumps back to the newest session · \x1b[1m/diff\x1b[0m then \x1b[1m/commit\x1b[0m to ship · \x1b[2mTab\x1b[0m for workflow completions · \x1b[2mShift+Enter\x1b[0m for newline",
  1580. self.model,
  1581. self.permission_mode.as_str(),
  1582. git_branch,
  1583. workspace,
  1584. cwd,
  1585. self.session.id,
  1586. session_path,
  1587. )
  1588. }
  1589. fn repl_completion_candidates(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
  1590. Ok(slash_command_completion_candidates_with_sessions(
  1591. &self.model,
  1592. Some(&self.session.id),
  1593. list_managed_sessions()?
  1594. .into_iter()
  1595. .map(|session| session.id)
  1596. .collect(),
  1597. ))
  1598. }
  1599. fn prepare_turn_runtime(
  1600. &self,
  1601. emit_output: bool,
  1602. ) -> Result<(BuiltRuntime, HookAbortMonitor), Box<dyn std::error::Error>> {
  1603. let hook_abort_signal = runtime::HookAbortSignal::new();
  1604. let runtime = build_runtime(
  1605. self.runtime.session().clone(),
  1606. &self.session.id,
  1607. self.model.clone(),
  1608. self.system_prompt.clone(),
  1609. true,
  1610. emit_output,
  1611. self.allowed_tools.clone(),
  1612. self.permission_mode,
  1613. None,
  1614. )?
  1615. .with_hook_abort_signal(hook_abort_signal.clone());
  1616. let hook_abort_monitor = HookAbortMonitor::spawn(hook_abort_signal);
  1617. Ok((runtime, hook_abort_monitor))
  1618. }
  1619. fn replace_runtime(&mut self, runtime: BuiltRuntime) -> Result<(), Box<dyn std::error::Error>> {
  1620. self.runtime.shutdown_plugins()?;
  1621. self.runtime = runtime;
  1622. Ok(())
  1623. }
  1624. fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  1625. let (mut runtime, hook_abort_monitor) = self.prepare_turn_runtime(true)?;
  1626. let mut spinner = Spinner::new();
  1627. let mut stdout = io::stdout();
  1628. spinner.tick(
  1629. "🦀 Thinking...",
  1630. TerminalRenderer::new().color_theme(),
  1631. &mut stdout,
  1632. )?;
  1633. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1634. let result = runtime.run_turn(input, Some(&mut permission_prompter));
  1635. hook_abort_monitor.stop();
  1636. match result {
  1637. Ok(summary) => {
  1638. self.replace_runtime(runtime)?;
  1639. spinner.finish(
  1640. "✨ Done",
  1641. TerminalRenderer::new().color_theme(),
  1642. &mut stdout,
  1643. )?;
  1644. println!();
  1645. if let Some(event) = summary.auto_compaction {
  1646. println!(
  1647. "{}",
  1648. format_auto_compaction_notice(event.removed_message_count)
  1649. );
  1650. }
  1651. self.persist_session()?;
  1652. Ok(())
  1653. }
  1654. Err(error) => {
  1655. runtime.shutdown_plugins()?;
  1656. spinner.fail(
  1657. "❌ Request failed",
  1658. TerminalRenderer::new().color_theme(),
  1659. &mut stdout,
  1660. )?;
  1661. Err(Box::new(error))
  1662. }
  1663. }
  1664. }
  1665. fn run_turn_with_output(
  1666. &mut self,
  1667. input: &str,
  1668. output_format: CliOutputFormat,
  1669. ) -> Result<(), Box<dyn std::error::Error>> {
  1670. match output_format {
  1671. CliOutputFormat::Text => self.run_turn(input),
  1672. CliOutputFormat::Json => self.run_prompt_json(input),
  1673. }
  1674. }
  1675. fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  1676. let (mut runtime, hook_abort_monitor) = self.prepare_turn_runtime(false)?;
  1677. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1678. let result = runtime.run_turn(input, Some(&mut permission_prompter));
  1679. hook_abort_monitor.stop();
  1680. let summary = result?;
  1681. self.replace_runtime(runtime)?;
  1682. self.persist_session()?;
  1683. println!(
  1684. "{}",
  1685. json!({
  1686. "message": final_assistant_text(&summary),
  1687. "model": self.model,
  1688. "iterations": summary.iterations,
  1689. "auto_compaction": summary.auto_compaction.map(|event| json!({
  1690. "removed_messages": event.removed_message_count,
  1691. "notice": format_auto_compaction_notice(event.removed_message_count),
  1692. })),
  1693. "tool_uses": collect_tool_uses(&summary),
  1694. "tool_results": collect_tool_results(&summary),
  1695. "prompt_cache_events": collect_prompt_cache_events(&summary),
  1696. "usage": {
  1697. "input_tokens": summary.usage.input_tokens,
  1698. "output_tokens": summary.usage.output_tokens,
  1699. "cache_creation_input_tokens": summary.usage.cache_creation_input_tokens,
  1700. "cache_read_input_tokens": summary.usage.cache_read_input_tokens,
  1701. }
  1702. })
  1703. );
  1704. Ok(())
  1705. }
  1706. fn handle_repl_command(
  1707. &mut self,
  1708. command: SlashCommand,
  1709. ) -> Result<bool, Box<dyn std::error::Error>> {
  1710. Ok(match command {
  1711. SlashCommand::Help => {
  1712. println!("{}", render_repl_help());
  1713. false
  1714. }
  1715. SlashCommand::Status => {
  1716. self.print_status();
  1717. false
  1718. }
  1719. SlashCommand::Bughunter { scope } => {
  1720. self.run_bughunter(scope.as_deref())?;
  1721. false
  1722. }
  1723. SlashCommand::Commit => {
  1724. self.run_commit(None)?;
  1725. false
  1726. }
  1727. SlashCommand::Pr { context } => {
  1728. self.run_pr(context.as_deref())?;
  1729. false
  1730. }
  1731. SlashCommand::Issue { context } => {
  1732. self.run_issue(context.as_deref())?;
  1733. false
  1734. }
  1735. SlashCommand::Ultraplan { task } => {
  1736. self.run_ultraplan(task.as_deref())?;
  1737. false
  1738. }
  1739. SlashCommand::Teleport { target } => {
  1740. self.run_teleport(target.as_deref())?;
  1741. false
  1742. }
  1743. SlashCommand::DebugToolCall => {
  1744. self.run_debug_tool_call(None)?;
  1745. false
  1746. }
  1747. SlashCommand::Sandbox => {
  1748. Self::print_sandbox_status();
  1749. false
  1750. }
  1751. SlashCommand::Compact => {
  1752. self.compact()?;
  1753. false
  1754. }
  1755. SlashCommand::Model { model } => self.set_model(model)?,
  1756. SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
  1757. SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
  1758. SlashCommand::Cost => {
  1759. self.print_cost();
  1760. false
  1761. }
  1762. SlashCommand::Resume { session_path } => self.resume_session(session_path)?,
  1763. SlashCommand::Config { section } => {
  1764. Self::print_config(section.as_deref())?;
  1765. false
  1766. }
  1767. SlashCommand::Mcp { action, target } => {
  1768. let args = match (action.as_deref(), target.as_deref()) {
  1769. (None, None) => None,
  1770. (Some(action), None) => Some(action.to_string()),
  1771. (Some(action), Some(target)) => Some(format!("{action} {target}")),
  1772. (None, Some(target)) => Some(target.to_string()),
  1773. };
  1774. Self::print_mcp(args.as_deref())?;
  1775. false
  1776. }
  1777. SlashCommand::Memory => {
  1778. Self::print_memory()?;
  1779. false
  1780. }
  1781. SlashCommand::Init => {
  1782. run_init()?;
  1783. false
  1784. }
  1785. SlashCommand::Diff => {
  1786. Self::print_diff()?;
  1787. false
  1788. }
  1789. SlashCommand::Version => {
  1790. Self::print_version();
  1791. false
  1792. }
  1793. SlashCommand::Export { path } => {
  1794. self.export_session(path.as_deref())?;
  1795. false
  1796. }
  1797. SlashCommand::Session { action, target } => {
  1798. self.handle_session_command(action.as_deref(), target.as_deref())?
  1799. }
  1800. SlashCommand::Plugins { action, target } => {
  1801. self.handle_plugins_command(action.as_deref(), target.as_deref())?
  1802. }
  1803. SlashCommand::Agents { args } => {
  1804. Self::print_agents(args.as_deref())?;
  1805. false
  1806. }
  1807. SlashCommand::Skills { args } => {
  1808. Self::print_skills(args.as_deref())?;
  1809. false
  1810. }
  1811. SlashCommand::Unknown(name) => {
  1812. eprintln!("{}", format_unknown_slash_command(&name));
  1813. false
  1814. }
  1815. })
  1816. }
  1817. fn persist_session(&self) -> Result<(), Box<dyn std::error::Error>> {
  1818. self.runtime.session().save_to_path(&self.session.path)?;
  1819. Ok(())
  1820. }
  1821. fn print_status(&self) {
  1822. let cumulative = self.runtime.usage().cumulative_usage();
  1823. let latest = self.runtime.usage().current_turn_usage();
  1824. println!(
  1825. "{}",
  1826. format_status_report(
  1827. &self.model,
  1828. StatusUsage {
  1829. message_count: self.runtime.session().messages.len(),
  1830. turns: self.runtime.usage().turns(),
  1831. latest,
  1832. cumulative,
  1833. estimated_tokens: self.runtime.estimated_tokens(),
  1834. },
  1835. self.permission_mode.as_str(),
  1836. &status_context(Some(&self.session.path)).expect("status context should load"),
  1837. )
  1838. );
  1839. }
  1840. fn print_sandbox_status() {
  1841. let cwd = env::current_dir().expect("current dir");
  1842. let loader = ConfigLoader::default_for(&cwd);
  1843. let runtime_config = loader
  1844. .load()
  1845. .unwrap_or_else(|_| runtime::RuntimeConfig::empty());
  1846. println!(
  1847. "{}",
  1848. format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
  1849. );
  1850. }
  1851. fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
  1852. let Some(model) = model else {
  1853. println!(
  1854. "{}",
  1855. format_model_report(
  1856. &self.model,
  1857. self.runtime.session().messages.len(),
  1858. self.runtime.usage().turns(),
  1859. )
  1860. );
  1861. return Ok(false);
  1862. };
  1863. let model = resolve_model_alias(&model).to_string();
  1864. if model == self.model {
  1865. println!(
  1866. "{}",
  1867. format_model_report(
  1868. &self.model,
  1869. self.runtime.session().messages.len(),
  1870. self.runtime.usage().turns(),
  1871. )
  1872. );
  1873. return Ok(false);
  1874. }
  1875. let previous = self.model.clone();
  1876. let session = self.runtime.session().clone();
  1877. let message_count = session.messages.len();
  1878. let runtime = build_runtime(
  1879. session,
  1880. &self.session.id,
  1881. model.clone(),
  1882. self.system_prompt.clone(),
  1883. true,
  1884. true,
  1885. self.allowed_tools.clone(),
  1886. self.permission_mode,
  1887. None,
  1888. )?;
  1889. self.replace_runtime(runtime)?;
  1890. self.model.clone_from(&model);
  1891. println!(
  1892. "{}",
  1893. format_model_switch_report(&previous, &model, message_count)
  1894. );
  1895. Ok(true)
  1896. }
  1897. fn set_permissions(
  1898. &mut self,
  1899. mode: Option<String>,
  1900. ) -> Result<bool, Box<dyn std::error::Error>> {
  1901. let Some(mode) = mode else {
  1902. println!(
  1903. "{}",
  1904. format_permissions_report(self.permission_mode.as_str())
  1905. );
  1906. return Ok(false);
  1907. };
  1908. let normalized = normalize_permission_mode(&mode).ok_or_else(|| {
  1909. format!(
  1910. "unsupported permission mode '{mode}'. Use read-only, workspace-write, or danger-full-access."
  1911. )
  1912. })?;
  1913. if normalized == self.permission_mode.as_str() {
  1914. println!("{}", format_permissions_report(normalized));
  1915. return Ok(false);
  1916. }
  1917. let previous = self.permission_mode.as_str().to_string();
  1918. let session = self.runtime.session().clone();
  1919. self.permission_mode = permission_mode_from_label(normalized);
  1920. let runtime = build_runtime(
  1921. session,
  1922. &self.session.id,
  1923. self.model.clone(),
  1924. self.system_prompt.clone(),
  1925. true,
  1926. true,
  1927. self.allowed_tools.clone(),
  1928. self.permission_mode,
  1929. None,
  1930. )?;
  1931. self.replace_runtime(runtime)?;
  1932. println!(
  1933. "{}",
  1934. format_permissions_switch_report(&previous, normalized)
  1935. );
  1936. Ok(true)
  1937. }
  1938. fn clear_session(&mut self, confirm: bool) -> Result<bool, Box<dyn std::error::Error>> {
  1939. if !confirm {
  1940. println!(
  1941. "clear: confirmation required; run /clear --confirm to start a fresh session."
  1942. );
  1943. return Ok(false);
  1944. }
  1945. let session_state = Session::new();
  1946. self.session = create_managed_session_handle(&session_state.session_id)?;
  1947. let runtime = build_runtime(
  1948. session_state.with_persistence_path(self.session.path.clone()),
  1949. &self.session.id,
  1950. self.model.clone(),
  1951. self.system_prompt.clone(),
  1952. true,
  1953. true,
  1954. self.allowed_tools.clone(),
  1955. self.permission_mode,
  1956. None,
  1957. )?;
  1958. self.replace_runtime(runtime)?;
  1959. println!(
  1960. "Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
  1961. self.model,
  1962. self.permission_mode.as_str(),
  1963. self.session.id,
  1964. );
  1965. Ok(true)
  1966. }
  1967. fn print_cost(&self) {
  1968. let cumulative = self.runtime.usage().cumulative_usage();
  1969. println!("{}", format_cost_report(cumulative));
  1970. }
  1971. fn resume_session(
  1972. &mut self,
  1973. session_path: Option<String>,
  1974. ) -> Result<bool, Box<dyn std::error::Error>> {
  1975. let Some(session_ref) = session_path else {
  1976. println!("{}", render_resume_usage());
  1977. return Ok(false);
  1978. };
  1979. let handle = resolve_session_reference(&session_ref)?;
  1980. let session = Session::load_from_path(&handle.path)?;
  1981. let message_count = session.messages.len();
  1982. let session_id = session.session_id.clone();
  1983. let runtime = build_runtime(
  1984. session,
  1985. &handle.id,
  1986. self.model.clone(),
  1987. self.system_prompt.clone(),
  1988. true,
  1989. true,
  1990. self.allowed_tools.clone(),
  1991. self.permission_mode,
  1992. None,
  1993. )?;
  1994. self.replace_runtime(runtime)?;
  1995. self.session = SessionHandle {
  1996. id: session_id,
  1997. path: handle.path,
  1998. };
  1999. println!(
  2000. "{}",
  2001. format_resume_report(
  2002. &self.session.path.display().to_string(),
  2003. message_count,
  2004. self.runtime.usage().turns(),
  2005. )
  2006. );
  2007. Ok(true)
  2008. }
  2009. fn print_config(section: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2010. println!("{}", render_config_report(section)?);
  2011. Ok(())
  2012. }
  2013. fn print_memory() -> Result<(), Box<dyn std::error::Error>> {
  2014. println!("{}", render_memory_report()?);
  2015. Ok(())
  2016. }
  2017. fn print_agents(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2018. let cwd = env::current_dir()?;
  2019. println!("{}", handle_agents_slash_command(args, &cwd)?);
  2020. Ok(())
  2021. }
  2022. fn print_mcp(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2023. let cwd = env::current_dir()?;
  2024. println!("{}", handle_mcp_slash_command(args, &cwd)?);
  2025. Ok(())
  2026. }
  2027. fn print_skills(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2028. let cwd = env::current_dir()?;
  2029. println!("{}", handle_skills_slash_command(args, &cwd)?);
  2030. Ok(())
  2031. }
  2032. fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
  2033. println!("{}", render_diff_report()?);
  2034. Ok(())
  2035. }
  2036. fn print_version() {
  2037. println!("{}", render_version_report());
  2038. }
  2039. fn export_session(
  2040. &self,
  2041. requested_path: Option<&str>,
  2042. ) -> Result<(), Box<dyn std::error::Error>> {
  2043. let export_path = resolve_export_path(requested_path, self.runtime.session())?;
  2044. fs::write(&export_path, render_export_text(self.runtime.session()))?;
  2045. println!(
  2046. "Export\n Result wrote transcript\n File {}\n Messages {}",
  2047. export_path.display(),
  2048. self.runtime.session().messages.len(),
  2049. );
  2050. Ok(())
  2051. }
  2052. fn handle_session_command(
  2053. &mut self,
  2054. action: Option<&str>,
  2055. target: Option<&str>,
  2056. ) -> Result<bool, Box<dyn std::error::Error>> {
  2057. match action {
  2058. None | Some("list") => {
  2059. println!("{}", render_session_list(&self.session.id)?);
  2060. Ok(false)
  2061. }
  2062. Some("switch") => {
  2063. let Some(target) = target else {
  2064. println!("Usage: /session switch <session-id>");
  2065. return Ok(false);
  2066. };
  2067. let handle = resolve_session_reference(target)?;
  2068. let session = Session::load_from_path(&handle.path)?;
  2069. let message_count = session.messages.len();
  2070. let session_id = session.session_id.clone();
  2071. let runtime = build_runtime(
  2072. session,
  2073. &handle.id,
  2074. self.model.clone(),
  2075. self.system_prompt.clone(),
  2076. true,
  2077. true,
  2078. self.allowed_tools.clone(),
  2079. self.permission_mode,
  2080. None,
  2081. )?;
  2082. self.replace_runtime(runtime)?;
  2083. self.session = SessionHandle {
  2084. id: session_id,
  2085. path: handle.path,
  2086. };
  2087. println!(
  2088. "Session switched\n Active session {}\n File {}\n Messages {}",
  2089. self.session.id,
  2090. self.session.path.display(),
  2091. message_count,
  2092. );
  2093. Ok(true)
  2094. }
  2095. Some("fork") => {
  2096. let forked = self.runtime.fork_session(target.map(ToOwned::to_owned));
  2097. let parent_session_id = self.session.id.clone();
  2098. let handle = create_managed_session_handle(&forked.session_id)?;
  2099. let branch_name = forked
  2100. .fork
  2101. .as_ref()
  2102. .and_then(|fork| fork.branch_name.clone());
  2103. let forked = forked.with_persistence_path(handle.path.clone());
  2104. let message_count = forked.messages.len();
  2105. forked.save_to_path(&handle.path)?;
  2106. let runtime = build_runtime(
  2107. forked,
  2108. &handle.id,
  2109. self.model.clone(),
  2110. self.system_prompt.clone(),
  2111. true,
  2112. true,
  2113. self.allowed_tools.clone(),
  2114. self.permission_mode,
  2115. None,
  2116. )?;
  2117. self.replace_runtime(runtime)?;
  2118. self.session = handle;
  2119. println!(
  2120. "Session forked\n Parent session {}\n Active session {}\n Branch {}\n File {}\n Messages {}",
  2121. parent_session_id,
  2122. self.session.id,
  2123. branch_name.as_deref().unwrap_or("(unnamed)"),
  2124. self.session.path.display(),
  2125. message_count,
  2126. );
  2127. Ok(true)
  2128. }
  2129. Some(other) => {
  2130. println!(
  2131. "Unknown /session action '{other}'. Use /session list, /session switch <session-id>, or /session fork [branch-name]."
  2132. );
  2133. Ok(false)
  2134. }
  2135. }
  2136. }
  2137. fn handle_plugins_command(
  2138. &mut self,
  2139. action: Option<&str>,
  2140. target: Option<&str>,
  2141. ) -> Result<bool, Box<dyn std::error::Error>> {
  2142. let cwd = env::current_dir()?;
  2143. let loader = ConfigLoader::default_for(&cwd);
  2144. let runtime_config = loader.load()?;
  2145. let mut manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  2146. let result = handle_plugins_slash_command(action, target, &mut manager)?;
  2147. println!("{}", result.message);
  2148. if result.reload_runtime {
  2149. self.reload_runtime_features()?;
  2150. }
  2151. Ok(false)
  2152. }
  2153. fn reload_runtime_features(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  2154. let runtime = build_runtime(
  2155. self.runtime.session().clone(),
  2156. &self.session.id,
  2157. self.model.clone(),
  2158. self.system_prompt.clone(),
  2159. true,
  2160. true,
  2161. self.allowed_tools.clone(),
  2162. self.permission_mode,
  2163. None,
  2164. )?;
  2165. self.replace_runtime(runtime)?;
  2166. self.persist_session()
  2167. }
  2168. fn compact(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  2169. let result = self.runtime.compact(CompactionConfig::default());
  2170. let removed = result.removed_message_count;
  2171. let kept = result.compacted_session.messages.len();
  2172. let skipped = removed == 0;
  2173. let runtime = build_runtime(
  2174. result.compacted_session,
  2175. &self.session.id,
  2176. self.model.clone(),
  2177. self.system_prompt.clone(),
  2178. true,
  2179. true,
  2180. self.allowed_tools.clone(),
  2181. self.permission_mode,
  2182. None,
  2183. )?;
  2184. self.replace_runtime(runtime)?;
  2185. self.persist_session()?;
  2186. println!("{}", format_compact_report(removed, kept, skipped));
  2187. Ok(())
  2188. }
  2189. fn run_internal_prompt_text_with_progress(
  2190. &self,
  2191. prompt: &str,
  2192. enable_tools: bool,
  2193. progress: Option<InternalPromptProgressReporter>,
  2194. ) -> Result<String, Box<dyn std::error::Error>> {
  2195. let session = self.runtime.session().clone();
  2196. let mut runtime = build_runtime(
  2197. session,
  2198. &self.session.id,
  2199. self.model.clone(),
  2200. self.system_prompt.clone(),
  2201. enable_tools,
  2202. false,
  2203. self.allowed_tools.clone(),
  2204. self.permission_mode,
  2205. progress,
  2206. )?;
  2207. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  2208. let summary = runtime.run_turn(prompt, Some(&mut permission_prompter))?;
  2209. let text = final_assistant_text(&summary).trim().to_string();
  2210. runtime.shutdown_plugins()?;
  2211. Ok(text)
  2212. }
  2213. fn run_internal_prompt_text(
  2214. &self,
  2215. prompt: &str,
  2216. enable_tools: bool,
  2217. ) -> Result<String, Box<dyn std::error::Error>> {
  2218. self.run_internal_prompt_text_with_progress(prompt, enable_tools, None)
  2219. }
  2220. fn run_bughunter(&self, scope: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2221. println!("{}", format_bughunter_report(scope));
  2222. Ok(())
  2223. }
  2224. fn run_ultraplan(&self, task: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2225. println!("{}", format_ultraplan_report(task));
  2226. Ok(())
  2227. }
  2228. #[allow(clippy::unused_self)]
  2229. fn run_teleport(&self, target: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2230. let Some(target) = target.map(str::trim).filter(|value| !value.is_empty()) else {
  2231. println!("Usage: /teleport <symbol-or-path>");
  2232. return Ok(());
  2233. };
  2234. println!("{}", render_teleport_report(target)?);
  2235. Ok(())
  2236. }
  2237. fn run_debug_tool_call(&self, args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2238. validate_no_args("/debug-tool-call", args)?;
  2239. println!("{}", render_last_tool_debug_report(self.runtime.session())?);
  2240. Ok(())
  2241. }
  2242. fn run_commit(&mut self, args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2243. validate_no_args("/commit", args)?;
  2244. let status = git_output(&["status", "--short", "--branch"])?;
  2245. let summary = parse_git_workspace_summary(Some(&status));
  2246. let branch = parse_git_status_branch(Some(&status));
  2247. if summary.is_clean() {
  2248. println!("{}", format_commit_skipped_report());
  2249. return Ok(());
  2250. }
  2251. println!(
  2252. "{}",
  2253. format_commit_preflight_report(branch.as_deref(), summary)
  2254. );
  2255. Ok(())
  2256. }
  2257. fn run_pr(&self, context: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2258. let branch =
  2259. resolve_git_branch_for(&env::current_dir()?).unwrap_or_else(|| "unknown".to_string());
  2260. println!("{}", format_pr_report(&branch, context));
  2261. Ok(())
  2262. }
  2263. fn run_issue(&self, context: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  2264. println!("{}", format_issue_report(context));
  2265. Ok(())
  2266. }
  2267. }
  2268. fn sessions_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
  2269. let cwd = env::current_dir()?;
  2270. let path = cwd.join(".claw").join("sessions");
  2271. fs::create_dir_all(&path)?;
  2272. Ok(path)
  2273. }
  2274. fn create_managed_session_handle(
  2275. session_id: &str,
  2276. ) -> Result<SessionHandle, Box<dyn std::error::Error>> {
  2277. let id = session_id.to_string();
  2278. let path = sessions_dir()?.join(format!("{id}.{PRIMARY_SESSION_EXTENSION}"));
  2279. Ok(SessionHandle { id, path })
  2280. }
  2281. fn resolve_session_reference(reference: &str) -> Result<SessionHandle, Box<dyn std::error::Error>> {
  2282. if SESSION_REFERENCE_ALIASES
  2283. .iter()
  2284. .any(|alias| reference.eq_ignore_ascii_case(alias))
  2285. {
  2286. let latest = latest_managed_session()?;
  2287. return Ok(SessionHandle {
  2288. id: latest.id,
  2289. path: latest.path,
  2290. });
  2291. }
  2292. let direct = PathBuf::from(reference);
  2293. let looks_like_path = direct.extension().is_some() || direct.components().count() > 1;
  2294. let path = if direct.exists() {
  2295. direct
  2296. } else if looks_like_path {
  2297. return Err(format_missing_session_reference(reference).into());
  2298. } else {
  2299. resolve_managed_session_path(reference)?
  2300. };
  2301. let id = path
  2302. .file_name()
  2303. .and_then(|value| value.to_str())
  2304. .and_then(|name| {
  2305. name.strip_suffix(&format!(".{PRIMARY_SESSION_EXTENSION}"))
  2306. .or_else(|| name.strip_suffix(&format!(".{LEGACY_SESSION_EXTENSION}")))
  2307. })
  2308. .unwrap_or(reference)
  2309. .to_string();
  2310. Ok(SessionHandle { id, path })
  2311. }
  2312. fn resolve_managed_session_path(session_id: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
  2313. let directory = sessions_dir()?;
  2314. for extension in [PRIMARY_SESSION_EXTENSION, LEGACY_SESSION_EXTENSION] {
  2315. let path = directory.join(format!("{session_id}.{extension}"));
  2316. if path.exists() {
  2317. return Ok(path);
  2318. }
  2319. }
  2320. Err(format_missing_session_reference(session_id).into())
  2321. }
  2322. fn is_managed_session_file(path: &Path) -> bool {
  2323. path.extension()
  2324. .and_then(|ext| ext.to_str())
  2325. .is_some_and(|extension| {
  2326. extension == PRIMARY_SESSION_EXTENSION || extension == LEGACY_SESSION_EXTENSION
  2327. })
  2328. }
  2329. fn list_managed_sessions() -> Result<Vec<ManagedSessionSummary>, Box<dyn std::error::Error>> {
  2330. let mut sessions = Vec::new();
  2331. for entry in fs::read_dir(sessions_dir()?)? {
  2332. let entry = entry?;
  2333. let path = entry.path();
  2334. if !is_managed_session_file(&path) {
  2335. continue;
  2336. }
  2337. let metadata = entry.metadata()?;
  2338. let modified_epoch_millis = metadata
  2339. .modified()
  2340. .ok()
  2341. .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
  2342. .map(|duration| duration.as_millis())
  2343. .unwrap_or_default();
  2344. let (id, message_count, parent_session_id, branch_name) =
  2345. match Session::load_from_path(&path) {
  2346. Ok(session) => {
  2347. let parent_session_id = session
  2348. .fork
  2349. .as_ref()
  2350. .map(|fork| fork.parent_session_id.clone());
  2351. let branch_name = session
  2352. .fork
  2353. .as_ref()
  2354. .and_then(|fork| fork.branch_name.clone());
  2355. (
  2356. session.session_id,
  2357. session.messages.len(),
  2358. parent_session_id,
  2359. branch_name,
  2360. )
  2361. }
  2362. Err(_) => (
  2363. path.file_stem()
  2364. .and_then(|value| value.to_str())
  2365. .unwrap_or("unknown")
  2366. .to_string(),
  2367. 0,
  2368. None,
  2369. None,
  2370. ),
  2371. };
  2372. sessions.push(ManagedSessionSummary {
  2373. id,
  2374. path,
  2375. modified_epoch_millis,
  2376. message_count,
  2377. parent_session_id,
  2378. branch_name,
  2379. });
  2380. }
  2381. sessions.sort_by(|left, right| {
  2382. right
  2383. .modified_epoch_millis
  2384. .cmp(&left.modified_epoch_millis)
  2385. .then_with(|| right.id.cmp(&left.id))
  2386. });
  2387. Ok(sessions)
  2388. }
  2389. fn latest_managed_session() -> Result<ManagedSessionSummary, Box<dyn std::error::Error>> {
  2390. list_managed_sessions()?
  2391. .into_iter()
  2392. .next()
  2393. .ok_or_else(|| format_no_managed_sessions().into())
  2394. }
  2395. fn format_missing_session_reference(reference: &str) -> String {
  2396. format!(
  2397. "session not found: {reference}\nHint: managed sessions live in .claw/sessions/. Try `{LATEST_SESSION_REFERENCE}` for the most recent session or `/session list` in the REPL."
  2398. )
  2399. }
  2400. fn format_no_managed_sessions() -> String {
  2401. format!(
  2402. "no managed sessions found in .claw/sessions/\nStart `claw` to create a session, then rerun with `--resume {LATEST_SESSION_REFERENCE}`."
  2403. )
  2404. }
  2405. fn render_session_list(active_session_id: &str) -> Result<String, Box<dyn std::error::Error>> {
  2406. let sessions = list_managed_sessions()?;
  2407. let mut lines = vec![
  2408. "Sessions".to_string(),
  2409. format!(" Directory {}", sessions_dir()?.display()),
  2410. ];
  2411. if sessions.is_empty() {
  2412. lines.push(" No managed sessions saved yet.".to_string());
  2413. return Ok(lines.join("\n"));
  2414. }
  2415. for session in sessions {
  2416. let marker = if session.id == active_session_id {
  2417. "● current"
  2418. } else {
  2419. "○ saved"
  2420. };
  2421. let lineage = match (
  2422. session.branch_name.as_deref(),
  2423. session.parent_session_id.as_deref(),
  2424. ) {
  2425. (Some(branch_name), Some(parent_session_id)) => {
  2426. format!(" branch={branch_name} from={parent_session_id}")
  2427. }
  2428. (None, Some(parent_session_id)) => format!(" from={parent_session_id}"),
  2429. (Some(branch_name), None) => format!(" branch={branch_name}"),
  2430. (None, None) => String::new(),
  2431. };
  2432. lines.push(format!(
  2433. " {id:<20} {marker:<10} msgs={msgs:<4} modified={modified}{lineage} path={path}",
  2434. id = session.id,
  2435. msgs = session.message_count,
  2436. modified = format_session_modified_age(session.modified_epoch_millis),
  2437. lineage = lineage,
  2438. path = session.path.display(),
  2439. ));
  2440. }
  2441. Ok(lines.join("\n"))
  2442. }
  2443. fn format_session_modified_age(modified_epoch_millis: u128) -> String {
  2444. let now = std::time::SystemTime::now()
  2445. .duration_since(UNIX_EPOCH)
  2446. .ok()
  2447. .map_or(modified_epoch_millis, |duration| duration.as_millis());
  2448. let delta_seconds = now
  2449. .saturating_sub(modified_epoch_millis)
  2450. .checked_div(1_000)
  2451. .unwrap_or_default();
  2452. match delta_seconds {
  2453. 0..=4 => "just-now".to_string(),
  2454. 5..=59 => format!("{delta_seconds}s-ago"),
  2455. 60..=3_599 => format!("{}m-ago", delta_seconds / 60),
  2456. 3_600..=86_399 => format!("{}h-ago", delta_seconds / 3_600),
  2457. _ => format!("{}d-ago", delta_seconds / 86_400),
  2458. }
  2459. }
  2460. fn render_repl_help() -> String {
  2461. [
  2462. "REPL".to_string(),
  2463. " /exit Quit the REPL".to_string(),
  2464. " /quit Quit the REPL".to_string(),
  2465. " Up/Down Navigate prompt history".to_string(),
  2466. " Tab Complete commands, modes, and recent sessions".to_string(),
  2467. " Ctrl-C Clear input (or exit on empty prompt)".to_string(),
  2468. " Shift+Enter/Ctrl+J Insert a newline".to_string(),
  2469. " Auto-save .claw/sessions/<session-id>.jsonl".to_string(),
  2470. " Resume latest /resume latest".to_string(),
  2471. " Browse sessions /session list".to_string(),
  2472. String::new(),
  2473. render_slash_command_help(),
  2474. ]
  2475. .join(
  2476. "
  2477. ",
  2478. )
  2479. }
  2480. fn print_status_snapshot(
  2481. model: &str,
  2482. permission_mode: PermissionMode,
  2483. ) -> Result<(), Box<dyn std::error::Error>> {
  2484. println!(
  2485. "{}",
  2486. format_status_report(
  2487. model,
  2488. StatusUsage {
  2489. message_count: 0,
  2490. turns: 0,
  2491. latest: TokenUsage::default(),
  2492. cumulative: TokenUsage::default(),
  2493. estimated_tokens: 0,
  2494. },
  2495. permission_mode.as_str(),
  2496. &status_context(None)?,
  2497. )
  2498. );
  2499. Ok(())
  2500. }
  2501. fn status_context(
  2502. session_path: Option<&Path>,
  2503. ) -> Result<StatusContext, Box<dyn std::error::Error>> {
  2504. let cwd = env::current_dir()?;
  2505. let loader = ConfigLoader::default_for(&cwd);
  2506. let discovered_config_files = loader.discover().len();
  2507. let runtime_config = loader.load()?;
  2508. let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
  2509. let (project_root, git_branch) =
  2510. parse_git_status_metadata(project_context.git_status.as_deref());
  2511. let git_summary = parse_git_workspace_summary(project_context.git_status.as_deref());
  2512. let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
  2513. Ok(StatusContext {
  2514. cwd,
  2515. session_path: session_path.map(Path::to_path_buf),
  2516. loaded_config_files: runtime_config.loaded_entries().len(),
  2517. discovered_config_files,
  2518. memory_file_count: project_context.instruction_files.len(),
  2519. project_root,
  2520. git_branch,
  2521. git_summary,
  2522. sandbox_status,
  2523. })
  2524. }
  2525. fn format_status_report(
  2526. model: &str,
  2527. usage: StatusUsage,
  2528. permission_mode: &str,
  2529. context: &StatusContext,
  2530. ) -> String {
  2531. [
  2532. format!(
  2533. "Status
  2534. Model {model}
  2535. Permission mode {permission_mode}
  2536. Messages {}
  2537. Turns {}
  2538. Estimated tokens {}",
  2539. usage.message_count, usage.turns, usage.estimated_tokens,
  2540. ),
  2541. format!(
  2542. "Usage
  2543. Latest total {}
  2544. Cumulative input {}
  2545. Cumulative output {}
  2546. Cumulative total {}",
  2547. usage.latest.total_tokens(),
  2548. usage.cumulative.input_tokens,
  2549. usage.cumulative.output_tokens,
  2550. usage.cumulative.total_tokens(),
  2551. ),
  2552. format!(
  2553. "Workspace
  2554. Cwd {}
  2555. Project root {}
  2556. Git branch {}
  2557. Git state {}
  2558. Changed files {}
  2559. Staged {}
  2560. Unstaged {}
  2561. Untracked {}
  2562. Session {}
  2563. Config files loaded {}/{}
  2564. Memory files {}
  2565. Suggested flow /status → /diff → /commit",
  2566. context.cwd.display(),
  2567. context
  2568. .project_root
  2569. .as_ref()
  2570. .map_or_else(|| "unknown".to_string(), |path| path.display().to_string()),
  2571. context.git_branch.as_deref().unwrap_or("unknown"),
  2572. context.git_summary.headline(),
  2573. context.git_summary.changed_files,
  2574. context.git_summary.staged_files,
  2575. context.git_summary.unstaged_files,
  2576. context.git_summary.untracked_files,
  2577. context.session_path.as_ref().map_or_else(
  2578. || "live-repl".to_string(),
  2579. |path| path.display().to_string()
  2580. ),
  2581. context.loaded_config_files,
  2582. context.discovered_config_files,
  2583. context.memory_file_count,
  2584. ),
  2585. format_sandbox_report(&context.sandbox_status),
  2586. ]
  2587. .join(
  2588. "
  2589. ",
  2590. )
  2591. }
  2592. fn format_sandbox_report(status: &runtime::SandboxStatus) -> String {
  2593. format!(
  2594. "Sandbox
  2595. Enabled {}
  2596. Active {}
  2597. Supported {}
  2598. In container {}
  2599. Requested ns {}
  2600. Active ns {}
  2601. Requested net {}
  2602. Active net {}
  2603. Filesystem mode {}
  2604. Filesystem active {}
  2605. Allowed mounts {}
  2606. Markers {}
  2607. Fallback reason {}",
  2608. status.enabled,
  2609. status.active,
  2610. status.supported,
  2611. status.in_container,
  2612. status.requested.namespace_restrictions,
  2613. status.namespace_active,
  2614. status.requested.network_isolation,
  2615. status.network_active,
  2616. status.filesystem_mode.as_str(),
  2617. status.filesystem_active,
  2618. if status.allowed_mounts.is_empty() {
  2619. "<none>".to_string()
  2620. } else {
  2621. status.allowed_mounts.join(", ")
  2622. },
  2623. if status.container_markers.is_empty() {
  2624. "<none>".to_string()
  2625. } else {
  2626. status.container_markers.join(", ")
  2627. },
  2628. status
  2629. .fallback_reason
  2630. .clone()
  2631. .unwrap_or_else(|| "<none>".to_string()),
  2632. )
  2633. }
  2634. fn format_commit_preflight_report(branch: Option<&str>, summary: GitWorkspaceSummary) -> String {
  2635. format!(
  2636. "Commit
  2637. Result ready
  2638. Branch {}
  2639. Workspace {}
  2640. Changed files {}
  2641. Action create a git commit from the current workspace changes",
  2642. branch.unwrap_or("unknown"),
  2643. summary.headline(),
  2644. summary.changed_files,
  2645. )
  2646. }
  2647. fn format_commit_skipped_report() -> String {
  2648. "Commit
  2649. Result skipped
  2650. Reason no workspace changes
  2651. Action create a git commit from the current workspace changes
  2652. Next /status to inspect context · /diff to inspect repo changes"
  2653. .to_string()
  2654. }
  2655. fn print_sandbox_status_snapshot() -> Result<(), Box<dyn std::error::Error>> {
  2656. let cwd = env::current_dir()?;
  2657. let loader = ConfigLoader::default_for(&cwd);
  2658. let runtime_config = loader
  2659. .load()
  2660. .unwrap_or_else(|_| runtime::RuntimeConfig::empty());
  2661. println!(
  2662. "{}",
  2663. format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
  2664. );
  2665. Ok(())
  2666. }
  2667. fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
  2668. let cwd = env::current_dir()?;
  2669. let loader = ConfigLoader::default_for(&cwd);
  2670. let discovered = loader.discover();
  2671. let runtime_config = loader.load()?;
  2672. let mut lines = vec![
  2673. format!(
  2674. "Config
  2675. Working directory {}
  2676. Loaded files {}
  2677. Merged keys {}",
  2678. cwd.display(),
  2679. runtime_config.loaded_entries().len(),
  2680. runtime_config.merged().len()
  2681. ),
  2682. "Discovered files".to_string(),
  2683. ];
  2684. for entry in discovered {
  2685. let source = match entry.source {
  2686. ConfigSource::User => "user",
  2687. ConfigSource::Project => "project",
  2688. ConfigSource::Local => "local",
  2689. };
  2690. let status = if runtime_config
  2691. .loaded_entries()
  2692. .iter()
  2693. .any(|loaded_entry| loaded_entry.path == entry.path)
  2694. {
  2695. "loaded"
  2696. } else {
  2697. "missing"
  2698. };
  2699. lines.push(format!(
  2700. " {source:<7} {status:<7} {}",
  2701. entry.path.display()
  2702. ));
  2703. }
  2704. if let Some(section) = section {
  2705. lines.push(format!("Merged section: {section}"));
  2706. let value = match section {
  2707. "env" => runtime_config.get("env"),
  2708. "hooks" => runtime_config.get("hooks"),
  2709. "model" => runtime_config.get("model"),
  2710. "plugins" => runtime_config
  2711. .get("plugins")
  2712. .or_else(|| runtime_config.get("enabledPlugins")),
  2713. other => {
  2714. lines.push(format!(
  2715. " Unsupported config section '{other}'. Use env, hooks, model, or plugins."
  2716. ));
  2717. return Ok(lines.join(
  2718. "
  2719. ",
  2720. ));
  2721. }
  2722. };
  2723. lines.push(format!(
  2724. " {}",
  2725. match value {
  2726. Some(value) => value.render(),
  2727. None => "<unset>".to_string(),
  2728. }
  2729. ));
  2730. return Ok(lines.join(
  2731. "
  2732. ",
  2733. ));
  2734. }
  2735. lines.push("Merged JSON".to_string());
  2736. lines.push(format!(" {}", runtime_config.as_json().render()));
  2737. Ok(lines.join(
  2738. "
  2739. ",
  2740. ))
  2741. }
  2742. fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
  2743. let cwd = env::current_dir()?;
  2744. let project_context = ProjectContext::discover(&cwd, DEFAULT_DATE)?;
  2745. let mut lines = vec![format!(
  2746. "Memory
  2747. Working directory {}
  2748. Instruction files {}",
  2749. cwd.display(),
  2750. project_context.instruction_files.len()
  2751. )];
  2752. if project_context.instruction_files.is_empty() {
  2753. lines.push("Discovered files".to_string());
  2754. lines.push(
  2755. " No CLAUDE instruction files discovered in the current directory ancestry."
  2756. .to_string(),
  2757. );
  2758. } else {
  2759. lines.push("Discovered files".to_string());
  2760. for (index, file) in project_context.instruction_files.iter().enumerate() {
  2761. let preview = file.content.lines().next().unwrap_or("").trim();
  2762. let preview = if preview.is_empty() {
  2763. "<empty>"
  2764. } else {
  2765. preview
  2766. };
  2767. lines.push(format!(" {}. {}", index + 1, file.path.display(),));
  2768. lines.push(format!(
  2769. " lines={} preview={}",
  2770. file.content.lines().count(),
  2771. preview
  2772. ));
  2773. }
  2774. }
  2775. Ok(lines.join(
  2776. "
  2777. ",
  2778. ))
  2779. }
  2780. fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
  2781. let cwd = env::current_dir()?;
  2782. Ok(initialize_repo(&cwd)?.render())
  2783. }
  2784. fn run_init() -> Result<(), Box<dyn std::error::Error>> {
  2785. println!("{}", init_claude_md()?);
  2786. Ok(())
  2787. }
  2788. fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
  2789. match mode.trim() {
  2790. "read-only" => Some("read-only"),
  2791. "workspace-write" => Some("workspace-write"),
  2792. "danger-full-access" => Some("danger-full-access"),
  2793. _ => None,
  2794. }
  2795. }
  2796. fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
  2797. render_diff_report_for(&env::current_dir()?)
  2798. }
  2799. fn render_diff_report_for(cwd: &Path) -> Result<String, Box<dyn std::error::Error>> {
  2800. let staged = run_git_diff_command_in(cwd, &["diff", "--cached"])?;
  2801. let unstaged = run_git_diff_command_in(cwd, &["diff"])?;
  2802. if staged.trim().is_empty() && unstaged.trim().is_empty() {
  2803. return Ok(
  2804. "Diff\n Result clean working tree\n Detail no current changes"
  2805. .to_string(),
  2806. );
  2807. }
  2808. let mut sections = Vec::new();
  2809. if !staged.trim().is_empty() {
  2810. sections.push(format!("Staged changes:\n{}", staged.trim_end()));
  2811. }
  2812. if !unstaged.trim().is_empty() {
  2813. sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
  2814. }
  2815. Ok(format!("Diff\n\n{}", sections.join("\n\n")))
  2816. }
  2817. fn run_git_diff_command_in(
  2818. cwd: &Path,
  2819. args: &[&str],
  2820. ) -> Result<String, Box<dyn std::error::Error>> {
  2821. let output = std::process::Command::new("git")
  2822. .args(args)
  2823. .current_dir(cwd)
  2824. .output()?;
  2825. if !output.status.success() {
  2826. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2827. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2828. }
  2829. Ok(String::from_utf8(output.stdout)?)
  2830. }
  2831. fn render_teleport_report(target: &str) -> Result<String, Box<dyn std::error::Error>> {
  2832. let cwd = env::current_dir()?;
  2833. let file_list = Command::new("rg")
  2834. .args(["--files"])
  2835. .current_dir(&cwd)
  2836. .output()?;
  2837. let file_matches = if file_list.status.success() {
  2838. String::from_utf8(file_list.stdout)?
  2839. .lines()
  2840. .filter(|line| line.contains(target))
  2841. .take(10)
  2842. .map(ToOwned::to_owned)
  2843. .collect::<Vec<_>>()
  2844. } else {
  2845. Vec::new()
  2846. };
  2847. let content_output = Command::new("rg")
  2848. .args(["-n", "-S", "--color", "never", target, "."])
  2849. .current_dir(&cwd)
  2850. .output()?;
  2851. let mut lines = vec![
  2852. "Teleport".to_string(),
  2853. format!(" Target {target}"),
  2854. " Action search workspace files and content for the target".to_string(),
  2855. ];
  2856. if !file_matches.is_empty() {
  2857. lines.push(String::new());
  2858. lines.push("File matches".to_string());
  2859. lines.extend(file_matches.into_iter().map(|path| format!(" {path}")));
  2860. }
  2861. if content_output.status.success() {
  2862. let matches = String::from_utf8(content_output.stdout)?;
  2863. if !matches.trim().is_empty() {
  2864. lines.push(String::new());
  2865. lines.push("Content matches".to_string());
  2866. lines.push(truncate_for_prompt(&matches, 4_000));
  2867. }
  2868. }
  2869. if lines.len() == 1 {
  2870. lines.push(" Result no matches found".to_string());
  2871. }
  2872. Ok(lines.join("\n"))
  2873. }
  2874. fn render_last_tool_debug_report(session: &Session) -> Result<String, Box<dyn std::error::Error>> {
  2875. let last_tool_use = session
  2876. .messages
  2877. .iter()
  2878. .rev()
  2879. .find_map(|message| {
  2880. message.blocks.iter().rev().find_map(|block| match block {
  2881. ContentBlock::ToolUse { id, name, input } => {
  2882. Some((id.clone(), name.clone(), input.clone()))
  2883. }
  2884. _ => None,
  2885. })
  2886. })
  2887. .ok_or_else(|| "no prior tool call found in session".to_string())?;
  2888. let tool_result = session.messages.iter().rev().find_map(|message| {
  2889. message.blocks.iter().rev().find_map(|block| match block {
  2890. ContentBlock::ToolResult {
  2891. tool_use_id,
  2892. tool_name,
  2893. output,
  2894. is_error,
  2895. } if tool_use_id == &last_tool_use.0 => {
  2896. Some((tool_name.clone(), output.clone(), *is_error))
  2897. }
  2898. _ => None,
  2899. })
  2900. });
  2901. let mut lines = vec![
  2902. "Debug tool call".to_string(),
  2903. " Action inspect the last recorded tool call and its result".to_string(),
  2904. format!(" Tool id {}", last_tool_use.0),
  2905. format!(" Tool name {}", last_tool_use.1),
  2906. " Input".to_string(),
  2907. indent_block(&last_tool_use.2, 4),
  2908. ];
  2909. match tool_result {
  2910. Some((tool_name, output, is_error)) => {
  2911. lines.push(" Result".to_string());
  2912. lines.push(format!(" name {tool_name}"));
  2913. lines.push(format!(
  2914. " status {}",
  2915. if is_error { "error" } else { "ok" }
  2916. ));
  2917. lines.push(indent_block(&output, 4));
  2918. }
  2919. None => lines.push(" Result missing tool result".to_string()),
  2920. }
  2921. Ok(lines.join("\n"))
  2922. }
  2923. fn indent_block(value: &str, spaces: usize) -> String {
  2924. let indent = " ".repeat(spaces);
  2925. value
  2926. .lines()
  2927. .map(|line| format!("{indent}{line}"))
  2928. .collect::<Vec<_>>()
  2929. .join("\n")
  2930. }
  2931. fn validate_no_args(
  2932. command_name: &str,
  2933. args: Option<&str>,
  2934. ) -> Result<(), Box<dyn std::error::Error>> {
  2935. if let Some(args) = args.map(str::trim).filter(|value| !value.is_empty()) {
  2936. return Err(format!(
  2937. "{command_name} does not accept arguments. Received: {args}\nUsage: {command_name}"
  2938. )
  2939. .into());
  2940. }
  2941. Ok(())
  2942. }
  2943. fn format_bughunter_report(scope: Option<&str>) -> String {
  2944. format!(
  2945. "Bughunter
  2946. Scope {}
  2947. Action inspect the selected code for likely bugs and correctness issues
  2948. Output findings should include file paths, severity, and suggested fixes",
  2949. scope.unwrap_or("the current repository")
  2950. )
  2951. }
  2952. fn format_ultraplan_report(task: Option<&str>) -> String {
  2953. format!(
  2954. "Ultraplan
  2955. Task {}
  2956. Action break work into a multi-step execution plan
  2957. Output plan should cover goals, risks, sequencing, verification, and rollback",
  2958. task.unwrap_or("the current repo work")
  2959. )
  2960. }
  2961. fn format_pr_report(branch: &str, context: Option<&str>) -> String {
  2962. format!(
  2963. "PR
  2964. Branch {branch}
  2965. Context {}
  2966. Action draft or create a pull request for the current branch
  2967. Output title and markdown body suitable for GitHub",
  2968. context.unwrap_or("none")
  2969. )
  2970. }
  2971. fn format_issue_report(context: Option<&str>) -> String {
  2972. format!(
  2973. "Issue
  2974. Context {}
  2975. Action draft or create a GitHub issue from the current context
  2976. Output title and markdown body suitable for GitHub",
  2977. context.unwrap_or("none")
  2978. )
  2979. }
  2980. fn git_output(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
  2981. let output = Command::new("git")
  2982. .args(args)
  2983. .current_dir(env::current_dir()?)
  2984. .output()?;
  2985. if !output.status.success() {
  2986. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2987. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2988. }
  2989. Ok(String::from_utf8(output.stdout)?)
  2990. }
  2991. fn git_status_ok(args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
  2992. let output = Command::new("git")
  2993. .args(args)
  2994. .current_dir(env::current_dir()?)
  2995. .output()?;
  2996. if !output.status.success() {
  2997. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2998. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2999. }
  3000. Ok(())
  3001. }
  3002. fn command_exists(name: &str) -> bool {
  3003. Command::new("which")
  3004. .arg(name)
  3005. .output()
  3006. .map(|output| output.status.success())
  3007. .unwrap_or(false)
  3008. }
  3009. fn write_temp_text_file(
  3010. filename: &str,
  3011. contents: &str,
  3012. ) -> Result<PathBuf, Box<dyn std::error::Error>> {
  3013. let path = env::temp_dir().join(filename);
  3014. fs::write(&path, contents)?;
  3015. Ok(path)
  3016. }
  3017. fn recent_user_context(session: &Session, limit: usize) -> String {
  3018. let requests = session
  3019. .messages
  3020. .iter()
  3021. .filter(|message| message.role == MessageRole::User)
  3022. .filter_map(|message| {
  3023. message.blocks.iter().find_map(|block| match block {
  3024. ContentBlock::Text { text } => Some(text.trim().to_string()),
  3025. _ => None,
  3026. })
  3027. })
  3028. .rev()
  3029. .take(limit)
  3030. .collect::<Vec<_>>();
  3031. if requests.is_empty() {
  3032. "<no prior user messages>".to_string()
  3033. } else {
  3034. requests
  3035. .into_iter()
  3036. .rev()
  3037. .enumerate()
  3038. .map(|(index, text)| format!("{}. {}", index + 1, text))
  3039. .collect::<Vec<_>>()
  3040. .join("\n")
  3041. }
  3042. }
  3043. fn truncate_for_prompt(value: &str, limit: usize) -> String {
  3044. if value.chars().count() <= limit {
  3045. value.trim().to_string()
  3046. } else {
  3047. let truncated = value.chars().take(limit).collect::<String>();
  3048. format!("{}\n…[truncated]", truncated.trim_end())
  3049. }
  3050. }
  3051. fn sanitize_generated_message(value: &str) -> String {
  3052. value.trim().trim_matches('`').trim().replace("\r\n", "\n")
  3053. }
  3054. fn parse_titled_body(value: &str) -> Option<(String, String)> {
  3055. let normalized = sanitize_generated_message(value);
  3056. let title = normalized
  3057. .lines()
  3058. .find_map(|line| line.strip_prefix("TITLE:").map(str::trim))?;
  3059. let body_start = normalized.find("BODY:")?;
  3060. let body = normalized[body_start + "BODY:".len()..].trim();
  3061. Some((title.to_string(), body.to_string()))
  3062. }
  3063. fn render_version_report() -> String {
  3064. let git_sha = GIT_SHA.unwrap_or("unknown");
  3065. let target = BUILD_TARGET.unwrap_or("unknown");
  3066. format!(
  3067. "Claw Code\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
  3068. )
  3069. }
  3070. fn render_export_text(session: &Session) -> String {
  3071. let mut lines = vec!["# Conversation Export".to_string(), String::new()];
  3072. for (index, message) in session.messages.iter().enumerate() {
  3073. let role = match message.role {
  3074. MessageRole::System => "system",
  3075. MessageRole::User => "user",
  3076. MessageRole::Assistant => "assistant",
  3077. MessageRole::Tool => "tool",
  3078. };
  3079. lines.push(format!("## {}. {role}", index + 1));
  3080. for block in &message.blocks {
  3081. match block {
  3082. ContentBlock::Text { text } => lines.push(text.clone()),
  3083. ContentBlock::ToolUse { id, name, input } => {
  3084. lines.push(format!("[tool_use id={id} name={name}] {input}"));
  3085. }
  3086. ContentBlock::ToolResult {
  3087. tool_use_id,
  3088. tool_name,
  3089. output,
  3090. is_error,
  3091. } => {
  3092. lines.push(format!(
  3093. "[tool_result id={tool_use_id} name={tool_name} error={is_error}] {output}"
  3094. ));
  3095. }
  3096. }
  3097. }
  3098. lines.push(String::new());
  3099. }
  3100. lines.join("\n")
  3101. }
  3102. fn default_export_filename(session: &Session) -> String {
  3103. let stem = session
  3104. .messages
  3105. .iter()
  3106. .find_map(|message| match message.role {
  3107. MessageRole::User => message.blocks.iter().find_map(|block| match block {
  3108. ContentBlock::Text { text } => Some(text.as_str()),
  3109. _ => None,
  3110. }),
  3111. _ => None,
  3112. })
  3113. .map_or("conversation", |text| {
  3114. text.lines().next().unwrap_or("conversation")
  3115. })
  3116. .chars()
  3117. .map(|ch| {
  3118. if ch.is_ascii_alphanumeric() {
  3119. ch.to_ascii_lowercase()
  3120. } else {
  3121. '-'
  3122. }
  3123. })
  3124. .collect::<String>()
  3125. .split('-')
  3126. .filter(|part| !part.is_empty())
  3127. .take(8)
  3128. .collect::<Vec<_>>()
  3129. .join("-");
  3130. let fallback = if stem.is_empty() {
  3131. "conversation"
  3132. } else {
  3133. &stem
  3134. };
  3135. format!("{fallback}.txt")
  3136. }
  3137. fn resolve_export_path(
  3138. requested_path: Option<&str>,
  3139. session: &Session,
  3140. ) -> Result<PathBuf, Box<dyn std::error::Error>> {
  3141. let cwd = env::current_dir()?;
  3142. let file_name =
  3143. requested_path.map_or_else(|| default_export_filename(session), ToOwned::to_owned);
  3144. let final_name = if Path::new(&file_name)
  3145. .extension()
  3146. .is_some_and(|ext| ext.eq_ignore_ascii_case("txt"))
  3147. {
  3148. file_name
  3149. } else {
  3150. format!("{file_name}.txt")
  3151. };
  3152. Ok(cwd.join(final_name))
  3153. }
  3154. fn build_system_prompt() -> Result<Vec<String>, Box<dyn std::error::Error>> {
  3155. Ok(load_system_prompt(
  3156. env::current_dir()?,
  3157. DEFAULT_DATE,
  3158. env::consts::OS,
  3159. "unknown",
  3160. )?)
  3161. }
  3162. fn build_runtime_plugin_state() -> Result<RuntimePluginState, Box<dyn std::error::Error>> {
  3163. let cwd = env::current_dir()?;
  3164. let loader = ConfigLoader::default_for(&cwd);
  3165. let runtime_config = loader.load()?;
  3166. build_runtime_plugin_state_with_loader(&cwd, &loader, &runtime_config)
  3167. }
  3168. fn build_runtime_plugin_state_with_loader(
  3169. cwd: &Path,
  3170. loader: &ConfigLoader,
  3171. runtime_config: &runtime::RuntimeConfig,
  3172. ) -> Result<RuntimePluginState, Box<dyn std::error::Error>> {
  3173. let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  3174. let plugin_registry = plugin_manager.plugin_registry()?;
  3175. let plugin_hook_config =
  3176. runtime_hook_config_from_plugin_hooks(plugin_registry.aggregated_hooks()?);
  3177. let feature_config = runtime_config
  3178. .feature_config()
  3179. .clone()
  3180. .with_hooks(runtime_config.hooks().merged(&plugin_hook_config));
  3181. let tool_registry = GlobalToolRegistry::with_plugin_tools(plugin_registry.aggregated_tools()?)?;
  3182. Ok(RuntimePluginState {
  3183. feature_config,
  3184. tool_registry,
  3185. plugin_registry,
  3186. })
  3187. }
  3188. fn build_plugin_manager(
  3189. cwd: &Path,
  3190. loader: &ConfigLoader,
  3191. runtime_config: &runtime::RuntimeConfig,
  3192. ) -> PluginManager {
  3193. let plugin_settings = runtime_config.plugins();
  3194. let mut plugin_config = PluginManagerConfig::new(loader.config_home().to_path_buf());
  3195. plugin_config.enabled_plugins = plugin_settings.enabled_plugins().clone();
  3196. plugin_config.external_dirs = plugin_settings
  3197. .external_directories()
  3198. .iter()
  3199. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path))
  3200. .collect();
  3201. plugin_config.install_root = plugin_settings
  3202. .install_root()
  3203. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  3204. plugin_config.registry_path = plugin_settings
  3205. .registry_path()
  3206. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  3207. plugin_config.bundled_root = plugin_settings
  3208. .bundled_root()
  3209. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  3210. PluginManager::new(plugin_config)
  3211. }
  3212. fn resolve_plugin_path(cwd: &Path, config_home: &Path, value: &str) -> PathBuf {
  3213. let path = PathBuf::from(value);
  3214. if path.is_absolute() {
  3215. path
  3216. } else if value.starts_with('.') {
  3217. cwd.join(path)
  3218. } else {
  3219. config_home.join(path)
  3220. }
  3221. }
  3222. fn runtime_hook_config_from_plugin_hooks(hooks: PluginHooks) -> runtime::RuntimeHookConfig {
  3223. runtime::RuntimeHookConfig::new(
  3224. hooks.pre_tool_use,
  3225. hooks.post_tool_use,
  3226. hooks.post_tool_use_failure,
  3227. )
  3228. }
  3229. #[derive(Debug, Clone, PartialEq, Eq)]
  3230. struct InternalPromptProgressState {
  3231. command_label: &'static str,
  3232. task_label: String,
  3233. step: usize,
  3234. phase: String,
  3235. detail: Option<String>,
  3236. saw_final_text: bool,
  3237. }
  3238. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  3239. enum InternalPromptProgressEvent {
  3240. Started,
  3241. Update,
  3242. Heartbeat,
  3243. Complete,
  3244. Failed,
  3245. }
  3246. #[derive(Debug)]
  3247. struct InternalPromptProgressShared {
  3248. state: Mutex<InternalPromptProgressState>,
  3249. output_lock: Mutex<()>,
  3250. started_at: Instant,
  3251. }
  3252. #[derive(Debug, Clone)]
  3253. struct InternalPromptProgressReporter {
  3254. shared: Arc<InternalPromptProgressShared>,
  3255. }
  3256. #[derive(Debug)]
  3257. struct InternalPromptProgressRun {
  3258. reporter: InternalPromptProgressReporter,
  3259. heartbeat_stop: Option<mpsc::Sender<()>>,
  3260. heartbeat_handle: Option<thread::JoinHandle<()>>,
  3261. }
  3262. impl InternalPromptProgressReporter {
  3263. fn ultraplan(task: &str) -> Self {
  3264. Self {
  3265. shared: Arc::new(InternalPromptProgressShared {
  3266. state: Mutex::new(InternalPromptProgressState {
  3267. command_label: "Ultraplan",
  3268. task_label: task.to_string(),
  3269. step: 0,
  3270. phase: "planning started".to_string(),
  3271. detail: Some(format!("task: {task}")),
  3272. saw_final_text: false,
  3273. }),
  3274. output_lock: Mutex::new(()),
  3275. started_at: Instant::now(),
  3276. }),
  3277. }
  3278. }
  3279. fn emit(&self, event: InternalPromptProgressEvent, error: Option<&str>) {
  3280. let snapshot = self.snapshot();
  3281. let line = format_internal_prompt_progress_line(event, &snapshot, self.elapsed(), error);
  3282. self.write_line(&line);
  3283. }
  3284. fn mark_model_phase(&self) {
  3285. let snapshot = {
  3286. let mut state = self
  3287. .shared
  3288. .state
  3289. .lock()
  3290. .expect("internal prompt progress state poisoned");
  3291. state.step += 1;
  3292. state.phase = if state.step == 1 {
  3293. "analyzing request".to_string()
  3294. } else {
  3295. "reviewing findings".to_string()
  3296. };
  3297. state.detail = Some(format!("task: {}", state.task_label));
  3298. state.clone()
  3299. };
  3300. self.write_line(&format_internal_prompt_progress_line(
  3301. InternalPromptProgressEvent::Update,
  3302. &snapshot,
  3303. self.elapsed(),
  3304. None,
  3305. ));
  3306. }
  3307. fn mark_tool_phase(&self, name: &str, input: &str) {
  3308. let detail = describe_tool_progress(name, input);
  3309. let snapshot = {
  3310. let mut state = self
  3311. .shared
  3312. .state
  3313. .lock()
  3314. .expect("internal prompt progress state poisoned");
  3315. state.step += 1;
  3316. state.phase = format!("running {name}");
  3317. state.detail = Some(detail);
  3318. state.clone()
  3319. };
  3320. self.write_line(&format_internal_prompt_progress_line(
  3321. InternalPromptProgressEvent::Update,
  3322. &snapshot,
  3323. self.elapsed(),
  3324. None,
  3325. ));
  3326. }
  3327. fn mark_text_phase(&self, text: &str) {
  3328. let trimmed = text.trim();
  3329. if trimmed.is_empty() {
  3330. return;
  3331. }
  3332. let detail = truncate_for_summary(first_visible_line(trimmed), 120);
  3333. let snapshot = {
  3334. let mut state = self
  3335. .shared
  3336. .state
  3337. .lock()
  3338. .expect("internal prompt progress state poisoned");
  3339. if state.saw_final_text {
  3340. return;
  3341. }
  3342. state.saw_final_text = true;
  3343. state.step += 1;
  3344. state.phase = "drafting final plan".to_string();
  3345. state.detail = (!detail.is_empty()).then_some(detail);
  3346. state.clone()
  3347. };
  3348. self.write_line(&format_internal_prompt_progress_line(
  3349. InternalPromptProgressEvent::Update,
  3350. &snapshot,
  3351. self.elapsed(),
  3352. None,
  3353. ));
  3354. }
  3355. fn emit_heartbeat(&self) {
  3356. let snapshot = self.snapshot();
  3357. self.write_line(&format_internal_prompt_progress_line(
  3358. InternalPromptProgressEvent::Heartbeat,
  3359. &snapshot,
  3360. self.elapsed(),
  3361. None,
  3362. ));
  3363. }
  3364. fn snapshot(&self) -> InternalPromptProgressState {
  3365. self.shared
  3366. .state
  3367. .lock()
  3368. .expect("internal prompt progress state poisoned")
  3369. .clone()
  3370. }
  3371. fn elapsed(&self) -> Duration {
  3372. self.shared.started_at.elapsed()
  3373. }
  3374. fn write_line(&self, line: &str) {
  3375. let _guard = self
  3376. .shared
  3377. .output_lock
  3378. .lock()
  3379. .expect("internal prompt progress output lock poisoned");
  3380. let mut stdout = io::stdout();
  3381. let _ = writeln!(stdout, "{line}");
  3382. let _ = stdout.flush();
  3383. }
  3384. }
  3385. impl InternalPromptProgressRun {
  3386. fn start_ultraplan(task: &str) -> Self {
  3387. let reporter = InternalPromptProgressReporter::ultraplan(task);
  3388. reporter.emit(InternalPromptProgressEvent::Started, None);
  3389. let (heartbeat_stop, heartbeat_rx) = mpsc::channel();
  3390. let heartbeat_reporter = reporter.clone();
  3391. let heartbeat_handle = thread::spawn(move || loop {
  3392. match heartbeat_rx.recv_timeout(INTERNAL_PROGRESS_HEARTBEAT_INTERVAL) {
  3393. Ok(()) | Err(RecvTimeoutError::Disconnected) => break,
  3394. Err(RecvTimeoutError::Timeout) => heartbeat_reporter.emit_heartbeat(),
  3395. }
  3396. });
  3397. Self {
  3398. reporter,
  3399. heartbeat_stop: Some(heartbeat_stop),
  3400. heartbeat_handle: Some(heartbeat_handle),
  3401. }
  3402. }
  3403. fn reporter(&self) -> InternalPromptProgressReporter {
  3404. self.reporter.clone()
  3405. }
  3406. fn finish_success(&mut self) {
  3407. self.stop_heartbeat();
  3408. self.reporter
  3409. .emit(InternalPromptProgressEvent::Complete, None);
  3410. }
  3411. fn finish_failure(&mut self, error: &str) {
  3412. self.stop_heartbeat();
  3413. self.reporter
  3414. .emit(InternalPromptProgressEvent::Failed, Some(error));
  3415. }
  3416. fn stop_heartbeat(&mut self) {
  3417. if let Some(sender) = self.heartbeat_stop.take() {
  3418. let _ = sender.send(());
  3419. }
  3420. if let Some(handle) = self.heartbeat_handle.take() {
  3421. let _ = handle.join();
  3422. }
  3423. }
  3424. }
  3425. impl Drop for InternalPromptProgressRun {
  3426. fn drop(&mut self) {
  3427. self.stop_heartbeat();
  3428. }
  3429. }
  3430. fn format_internal_prompt_progress_line(
  3431. event: InternalPromptProgressEvent,
  3432. snapshot: &InternalPromptProgressState,
  3433. elapsed: Duration,
  3434. error: Option<&str>,
  3435. ) -> String {
  3436. let elapsed_seconds = elapsed.as_secs();
  3437. let step_label = if snapshot.step == 0 {
  3438. "current step pending".to_string()
  3439. } else {
  3440. format!("current step {}", snapshot.step)
  3441. };
  3442. let mut status_bits = vec![step_label, format!("phase {}", snapshot.phase)];
  3443. if let Some(detail) = snapshot
  3444. .detail
  3445. .as_deref()
  3446. .filter(|detail| !detail.is_empty())
  3447. {
  3448. status_bits.push(detail.to_string());
  3449. }
  3450. let status = status_bits.join(" · ");
  3451. match event {
  3452. InternalPromptProgressEvent::Started => {
  3453. format!(
  3454. "🧭 {} status · planning started · {status}",
  3455. snapshot.command_label
  3456. )
  3457. }
  3458. InternalPromptProgressEvent::Update => {
  3459. format!("… {} status · {status}", snapshot.command_label)
  3460. }
  3461. InternalPromptProgressEvent::Heartbeat => format!(
  3462. "… {} heartbeat · {elapsed_seconds}s elapsed · {status}",
  3463. snapshot.command_label
  3464. ),
  3465. InternalPromptProgressEvent::Complete => format!(
  3466. "✔ {} status · completed · {elapsed_seconds}s elapsed · {} steps total",
  3467. snapshot.command_label, snapshot.step
  3468. ),
  3469. InternalPromptProgressEvent::Failed => format!(
  3470. "✘ {} status · failed · {elapsed_seconds}s elapsed · {}",
  3471. snapshot.command_label,
  3472. error.unwrap_or("unknown error")
  3473. ),
  3474. }
  3475. }
  3476. fn describe_tool_progress(name: &str, input: &str) -> String {
  3477. let parsed: serde_json::Value =
  3478. serde_json::from_str(input).unwrap_or(serde_json::Value::String(input.to_string()));
  3479. match name {
  3480. "bash" | "Bash" => {
  3481. let command = parsed
  3482. .get("command")
  3483. .and_then(|value| value.as_str())
  3484. .unwrap_or_default();
  3485. if command.is_empty() {
  3486. "running shell command".to_string()
  3487. } else {
  3488. format!("command {}", truncate_for_summary(command.trim(), 100))
  3489. }
  3490. }
  3491. "read_file" | "Read" => format!("reading {}", extract_tool_path(&parsed)),
  3492. "write_file" | "Write" => format!("writing {}", extract_tool_path(&parsed)),
  3493. "edit_file" | "Edit" => format!("editing {}", extract_tool_path(&parsed)),
  3494. "glob_search" | "Glob" => {
  3495. let pattern = parsed
  3496. .get("pattern")
  3497. .and_then(|value| value.as_str())
  3498. .unwrap_or("?");
  3499. let scope = parsed
  3500. .get("path")
  3501. .and_then(|value| value.as_str())
  3502. .unwrap_or(".");
  3503. format!("glob `{pattern}` in {scope}")
  3504. }
  3505. "grep_search" | "Grep" => {
  3506. let pattern = parsed
  3507. .get("pattern")
  3508. .and_then(|value| value.as_str())
  3509. .unwrap_or("?");
  3510. let scope = parsed
  3511. .get("path")
  3512. .and_then(|value| value.as_str())
  3513. .unwrap_or(".");
  3514. format!("grep `{pattern}` in {scope}")
  3515. }
  3516. "web_search" | "WebSearch" => parsed
  3517. .get("query")
  3518. .and_then(|value| value.as_str())
  3519. .map_or_else(
  3520. || "running web search".to_string(),
  3521. |query| format!("query {}", truncate_for_summary(query, 100)),
  3522. ),
  3523. _ => {
  3524. let summary = summarize_tool_payload(input);
  3525. if summary.is_empty() {
  3526. format!("running {name}")
  3527. } else {
  3528. format!("{name}: {summary}")
  3529. }
  3530. }
  3531. }
  3532. }
  3533. #[allow(clippy::needless_pass_by_value)]
  3534. #[allow(clippy::too_many_arguments)]
  3535. fn build_runtime(
  3536. session: Session,
  3537. session_id: &str,
  3538. model: String,
  3539. system_prompt: Vec<String>,
  3540. enable_tools: bool,
  3541. emit_output: bool,
  3542. allowed_tools: Option<AllowedToolSet>,
  3543. permission_mode: PermissionMode,
  3544. progress_reporter: Option<InternalPromptProgressReporter>,
  3545. ) -> Result<BuiltRuntime, Box<dyn std::error::Error>> {
  3546. let runtime_plugin_state = build_runtime_plugin_state()?;
  3547. build_runtime_with_plugin_state(
  3548. session,
  3549. session_id,
  3550. model,
  3551. system_prompt,
  3552. enable_tools,
  3553. emit_output,
  3554. allowed_tools,
  3555. permission_mode,
  3556. progress_reporter,
  3557. runtime_plugin_state,
  3558. )
  3559. }
  3560. #[allow(clippy::needless_pass_by_value)]
  3561. #[allow(clippy::too_many_arguments)]
  3562. fn build_runtime_with_plugin_state(
  3563. session: Session,
  3564. session_id: &str,
  3565. model: String,
  3566. system_prompt: Vec<String>,
  3567. enable_tools: bool,
  3568. emit_output: bool,
  3569. allowed_tools: Option<AllowedToolSet>,
  3570. permission_mode: PermissionMode,
  3571. progress_reporter: Option<InternalPromptProgressReporter>,
  3572. runtime_plugin_state: RuntimePluginState,
  3573. ) -> Result<BuiltRuntime, Box<dyn std::error::Error>> {
  3574. let RuntimePluginState {
  3575. feature_config,
  3576. tool_registry,
  3577. plugin_registry,
  3578. } = runtime_plugin_state;
  3579. plugin_registry.initialize()?;
  3580. let mut runtime = ConversationRuntime::new_with_features(
  3581. session,
  3582. AnthropicRuntimeClient::new(
  3583. session_id,
  3584. model,
  3585. enable_tools,
  3586. emit_output,
  3587. allowed_tools.clone(),
  3588. tool_registry.clone(),
  3589. progress_reporter,
  3590. )?,
  3591. CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),
  3592. permission_policy(permission_mode, &feature_config, &tool_registry)
  3593. .map_err(std::io::Error::other)?,
  3594. system_prompt,
  3595. &feature_config,
  3596. );
  3597. if emit_output {
  3598. runtime = runtime.with_hook_progress_reporter(Box::new(CliHookProgressReporter));
  3599. }
  3600. Ok(BuiltRuntime::new(runtime, plugin_registry))
  3601. }
  3602. struct CliHookProgressReporter;
  3603. impl runtime::HookProgressReporter for CliHookProgressReporter {
  3604. fn on_event(&mut self, event: &runtime::HookProgressEvent) {
  3605. match event {
  3606. runtime::HookProgressEvent::Started {
  3607. event,
  3608. tool_name,
  3609. command,
  3610. } => eprintln!(
  3611. "[hook {event_name}] {tool_name}: {command}",
  3612. event_name = event.as_str()
  3613. ),
  3614. runtime::HookProgressEvent::Completed {
  3615. event,
  3616. tool_name,
  3617. command,
  3618. } => eprintln!(
  3619. "[hook done {event_name}] {tool_name}: {command}",
  3620. event_name = event.as_str()
  3621. ),
  3622. runtime::HookProgressEvent::Cancelled {
  3623. event,
  3624. tool_name,
  3625. command,
  3626. } => eprintln!(
  3627. "[hook cancelled {event_name}] {tool_name}: {command}",
  3628. event_name = event.as_str()
  3629. ),
  3630. }
  3631. }
  3632. }
  3633. struct CliPermissionPrompter {
  3634. current_mode: PermissionMode,
  3635. }
  3636. impl CliPermissionPrompter {
  3637. fn new(current_mode: PermissionMode) -> Self {
  3638. Self { current_mode }
  3639. }
  3640. }
  3641. impl runtime::PermissionPrompter for CliPermissionPrompter {
  3642. fn decide(
  3643. &mut self,
  3644. request: &runtime::PermissionRequest,
  3645. ) -> runtime::PermissionPromptDecision {
  3646. println!();
  3647. println!("Permission approval required");
  3648. println!(" Tool {}", request.tool_name);
  3649. println!(" Current mode {}", self.current_mode.as_str());
  3650. println!(" Required mode {}", request.required_mode.as_str());
  3651. if let Some(reason) = &request.reason {
  3652. println!(" Reason {reason}");
  3653. }
  3654. println!(" Input {}", request.input);
  3655. print!("Approve this tool call? [y/N]: ");
  3656. let _ = io::stdout().flush();
  3657. let mut response = String::new();
  3658. match io::stdin().read_line(&mut response) {
  3659. Ok(_) => {
  3660. let normalized = response.trim().to_ascii_lowercase();
  3661. if matches!(normalized.as_str(), "y" | "yes") {
  3662. runtime::PermissionPromptDecision::Allow
  3663. } else {
  3664. runtime::PermissionPromptDecision::Deny {
  3665. reason: format!(
  3666. "tool '{}' denied by user approval prompt",
  3667. request.tool_name
  3668. ),
  3669. }
  3670. }
  3671. }
  3672. Err(error) => runtime::PermissionPromptDecision::Deny {
  3673. reason: format!("permission approval failed: {error}"),
  3674. },
  3675. }
  3676. }
  3677. }
  3678. struct AnthropicRuntimeClient {
  3679. runtime: tokio::runtime::Runtime,
  3680. client: AnthropicClient,
  3681. model: String,
  3682. enable_tools: bool,
  3683. emit_output: bool,
  3684. allowed_tools: Option<AllowedToolSet>,
  3685. tool_registry: GlobalToolRegistry,
  3686. progress_reporter: Option<InternalPromptProgressReporter>,
  3687. }
  3688. impl AnthropicRuntimeClient {
  3689. fn new(
  3690. session_id: &str,
  3691. model: String,
  3692. enable_tools: bool,
  3693. emit_output: bool,
  3694. allowed_tools: Option<AllowedToolSet>,
  3695. tool_registry: GlobalToolRegistry,
  3696. progress_reporter: Option<InternalPromptProgressReporter>,
  3697. ) -> Result<Self, Box<dyn std::error::Error>> {
  3698. Ok(Self {
  3699. runtime: tokio::runtime::Runtime::new()?,
  3700. client: AnthropicClient::from_auth(resolve_cli_auth_source()?)
  3701. .with_base_url(api::read_base_url())
  3702. .with_prompt_cache(PromptCache::new(session_id)),
  3703. model,
  3704. enable_tools,
  3705. emit_output,
  3706. allowed_tools,
  3707. tool_registry,
  3708. progress_reporter,
  3709. })
  3710. }
  3711. }
  3712. fn resolve_cli_auth_source() -> Result<AuthSource, Box<dyn std::error::Error>> {
  3713. Ok(resolve_startup_auth_source(|| {
  3714. let cwd = env::current_dir().map_err(api::ApiError::from)?;
  3715. let config = ConfigLoader::default_for(&cwd).load().map_err(|error| {
  3716. api::ApiError::Auth(format!("failed to load runtime OAuth config: {error}"))
  3717. })?;
  3718. Ok(config.oauth().cloned())
  3719. })?)
  3720. }
  3721. impl ApiClient for AnthropicRuntimeClient {
  3722. #[allow(clippy::too_many_lines)]
  3723. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  3724. if let Some(progress_reporter) = &self.progress_reporter {
  3725. progress_reporter.mark_model_phase();
  3726. }
  3727. let message_request = MessageRequest {
  3728. model: self.model.clone(),
  3729. max_tokens: max_tokens_for_model(&self.model),
  3730. messages: convert_messages(&request.messages),
  3731. system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
  3732. tools: self
  3733. .enable_tools
  3734. .then(|| filter_tool_specs(&self.tool_registry, self.allowed_tools.as_ref())),
  3735. tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
  3736. stream: true,
  3737. };
  3738. self.runtime.block_on(async {
  3739. let mut stream = self
  3740. .client
  3741. .stream_message(&message_request)
  3742. .await
  3743. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3744. let mut stdout = io::stdout();
  3745. let mut sink = io::sink();
  3746. let out: &mut dyn Write = if self.emit_output {
  3747. &mut stdout
  3748. } else {
  3749. &mut sink
  3750. };
  3751. let renderer = TerminalRenderer::new();
  3752. let mut markdown_stream = MarkdownStreamState::default();
  3753. let mut events = Vec::new();
  3754. let mut pending_tool: Option<(String, String, String)> = None;
  3755. let mut saw_stop = false;
  3756. while let Some(event) = stream
  3757. .next_event()
  3758. .await
  3759. .map_err(|error| RuntimeError::new(error.to_string()))?
  3760. {
  3761. match event {
  3762. ApiStreamEvent::MessageStart(start) => {
  3763. for block in start.message.content {
  3764. push_output_block(block, out, &mut events, &mut pending_tool, true)?;
  3765. }
  3766. }
  3767. ApiStreamEvent::ContentBlockStart(start) => {
  3768. push_output_block(
  3769. start.content_block,
  3770. out,
  3771. &mut events,
  3772. &mut pending_tool,
  3773. true,
  3774. )?;
  3775. }
  3776. ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
  3777. ContentBlockDelta::TextDelta { text } => {
  3778. if !text.is_empty() {
  3779. if let Some(progress_reporter) = &self.progress_reporter {
  3780. progress_reporter.mark_text_phase(&text);
  3781. }
  3782. if let Some(rendered) = markdown_stream.push(&renderer, &text) {
  3783. write!(out, "{rendered}")
  3784. .and_then(|()| out.flush())
  3785. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3786. }
  3787. events.push(AssistantEvent::TextDelta(text));
  3788. }
  3789. }
  3790. ContentBlockDelta::InputJsonDelta { partial_json } => {
  3791. if let Some((_, _, input)) = &mut pending_tool {
  3792. input.push_str(&partial_json);
  3793. }
  3794. }
  3795. ContentBlockDelta::ThinkingDelta { .. }
  3796. | ContentBlockDelta::SignatureDelta { .. } => {}
  3797. },
  3798. ApiStreamEvent::ContentBlockStop(_) => {
  3799. if let Some(rendered) = markdown_stream.flush(&renderer) {
  3800. write!(out, "{rendered}")
  3801. .and_then(|()| out.flush())
  3802. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3803. }
  3804. if let Some((id, name, input)) = pending_tool.take() {
  3805. if let Some(progress_reporter) = &self.progress_reporter {
  3806. progress_reporter.mark_tool_phase(&name, &input);
  3807. }
  3808. // Display tool call now that input is fully accumulated
  3809. writeln!(out, "\n{}", format_tool_call_start(&name, &input))
  3810. .and_then(|()| out.flush())
  3811. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3812. events.push(AssistantEvent::ToolUse { id, name, input });
  3813. }
  3814. }
  3815. ApiStreamEvent::MessageDelta(delta) => {
  3816. events.push(AssistantEvent::Usage(delta.usage.token_usage()));
  3817. }
  3818. ApiStreamEvent::MessageStop(_) => {
  3819. saw_stop = true;
  3820. if let Some(rendered) = markdown_stream.flush(&renderer) {
  3821. write!(out, "{rendered}")
  3822. .and_then(|()| out.flush())
  3823. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3824. }
  3825. events.push(AssistantEvent::MessageStop);
  3826. }
  3827. }
  3828. }
  3829. push_prompt_cache_record(&self.client, &mut events);
  3830. if !saw_stop
  3831. && events.iter().any(|event| {
  3832. matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
  3833. || matches!(event, AssistantEvent::ToolUse { .. })
  3834. })
  3835. {
  3836. events.push(AssistantEvent::MessageStop);
  3837. }
  3838. if events
  3839. .iter()
  3840. .any(|event| matches!(event, AssistantEvent::MessageStop))
  3841. {
  3842. return Ok(events);
  3843. }
  3844. let response = self
  3845. .client
  3846. .send_message(&MessageRequest {
  3847. stream: false,
  3848. ..message_request.clone()
  3849. })
  3850. .await
  3851. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3852. let mut events = response_to_events(response, out)?;
  3853. push_prompt_cache_record(&self.client, &mut events);
  3854. Ok(events)
  3855. })
  3856. }
  3857. }
  3858. fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
  3859. summary
  3860. .assistant_messages
  3861. .last()
  3862. .map(|message| {
  3863. message
  3864. .blocks
  3865. .iter()
  3866. .filter_map(|block| match block {
  3867. ContentBlock::Text { text } => Some(text.as_str()),
  3868. _ => None,
  3869. })
  3870. .collect::<Vec<_>>()
  3871. .join("")
  3872. })
  3873. .unwrap_or_default()
  3874. }
  3875. fn collect_tool_uses(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  3876. summary
  3877. .assistant_messages
  3878. .iter()
  3879. .flat_map(|message| message.blocks.iter())
  3880. .filter_map(|block| match block {
  3881. ContentBlock::ToolUse { id, name, input } => Some(json!({
  3882. "id": id,
  3883. "name": name,
  3884. "input": input,
  3885. })),
  3886. _ => None,
  3887. })
  3888. .collect()
  3889. }
  3890. fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  3891. summary
  3892. .tool_results
  3893. .iter()
  3894. .flat_map(|message| message.blocks.iter())
  3895. .filter_map(|block| match block {
  3896. ContentBlock::ToolResult {
  3897. tool_use_id,
  3898. tool_name,
  3899. output,
  3900. is_error,
  3901. } => Some(json!({
  3902. "tool_use_id": tool_use_id,
  3903. "tool_name": tool_name,
  3904. "output": output,
  3905. "is_error": is_error,
  3906. })),
  3907. _ => None,
  3908. })
  3909. .collect()
  3910. }
  3911. fn collect_prompt_cache_events(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  3912. summary
  3913. .prompt_cache_events
  3914. .iter()
  3915. .map(|event| {
  3916. json!({
  3917. "unexpected": event.unexpected,
  3918. "reason": event.reason,
  3919. "previous_cache_read_input_tokens": event.previous_cache_read_input_tokens,
  3920. "current_cache_read_input_tokens": event.current_cache_read_input_tokens,
  3921. "token_drop": event.token_drop,
  3922. })
  3923. })
  3924. .collect()
  3925. }
  3926. fn slash_command_completion_candidates_with_sessions(
  3927. model: &str,
  3928. active_session_id: Option<&str>,
  3929. recent_session_ids: Vec<String>,
  3930. ) -> Vec<String> {
  3931. let mut completions = BTreeSet::new();
  3932. for spec in slash_command_specs() {
  3933. completions.insert(format!("/{}", spec.name));
  3934. for alias in spec.aliases {
  3935. completions.insert(format!("/{alias}"));
  3936. }
  3937. }
  3938. for candidate in [
  3939. "/bughunter ",
  3940. "/clear --confirm",
  3941. "/config ",
  3942. "/config env",
  3943. "/config hooks",
  3944. "/config model",
  3945. "/config plugins",
  3946. "/mcp ",
  3947. "/mcp list",
  3948. "/mcp show ",
  3949. "/export ",
  3950. "/issue ",
  3951. "/model ",
  3952. "/model opus",
  3953. "/model sonnet",
  3954. "/model haiku",
  3955. "/permissions ",
  3956. "/permissions read-only",
  3957. "/permissions workspace-write",
  3958. "/permissions danger-full-access",
  3959. "/plugin list",
  3960. "/plugin install ",
  3961. "/plugin enable ",
  3962. "/plugin disable ",
  3963. "/plugin uninstall ",
  3964. "/plugin update ",
  3965. "/plugins list",
  3966. "/pr ",
  3967. "/resume ",
  3968. "/session list",
  3969. "/session switch ",
  3970. "/session fork ",
  3971. "/teleport ",
  3972. "/ultraplan ",
  3973. "/agents help",
  3974. "/mcp help",
  3975. "/skills help",
  3976. ] {
  3977. completions.insert(candidate.to_string());
  3978. }
  3979. if !model.trim().is_empty() {
  3980. completions.insert(format!("/model {}", resolve_model_alias(model)));
  3981. completions.insert(format!("/model {model}"));
  3982. }
  3983. if let Some(active_session_id) = active_session_id.filter(|value| !value.trim().is_empty()) {
  3984. completions.insert(format!("/resume {active_session_id}"));
  3985. completions.insert(format!("/session switch {active_session_id}"));
  3986. }
  3987. for session_id in recent_session_ids
  3988. .into_iter()
  3989. .filter(|value| !value.trim().is_empty())
  3990. .take(10)
  3991. {
  3992. completions.insert(format!("/resume {session_id}"));
  3993. completions.insert(format!("/session switch {session_id}"));
  3994. }
  3995. completions.into_iter().collect()
  3996. }
  3997. fn format_tool_call_start(name: &str, input: &str) -> String {
  3998. let parsed: serde_json::Value =
  3999. serde_json::from_str(input).unwrap_or(serde_json::Value::String(input.to_string()));
  4000. let detail = match name {
  4001. "bash" | "Bash" => format_bash_call(&parsed),
  4002. "read_file" | "Read" => {
  4003. let path = extract_tool_path(&parsed);
  4004. format!("\x1b[2m📄 Reading {path}…\x1b[0m")
  4005. }
  4006. "write_file" | "Write" => {
  4007. let path = extract_tool_path(&parsed);
  4008. let lines = parsed
  4009. .get("content")
  4010. .and_then(|value| value.as_str())
  4011. .map_or(0, |content| content.lines().count());
  4012. format!("\x1b[1;32m✏️ Writing {path}\x1b[0m \x1b[2m({lines} lines)\x1b[0m")
  4013. }
  4014. "edit_file" | "Edit" => {
  4015. let path = extract_tool_path(&parsed);
  4016. let old_value = parsed
  4017. .get("old_string")
  4018. .or_else(|| parsed.get("oldString"))
  4019. .and_then(|value| value.as_str())
  4020. .unwrap_or_default();
  4021. let new_value = parsed
  4022. .get("new_string")
  4023. .or_else(|| parsed.get("newString"))
  4024. .and_then(|value| value.as_str())
  4025. .unwrap_or_default();
  4026. format!(
  4027. "\x1b[1;33m📝 Editing {path}\x1b[0m{}",
  4028. format_patch_preview(old_value, new_value)
  4029. .map(|preview| format!("\n{preview}"))
  4030. .unwrap_or_default()
  4031. )
  4032. }
  4033. "glob_search" | "Glob" => format_search_start("🔎 Glob", &parsed),
  4034. "grep_search" | "Grep" => format_search_start("🔎 Grep", &parsed),
  4035. "web_search" | "WebSearch" => parsed
  4036. .get("query")
  4037. .and_then(|value| value.as_str())
  4038. .unwrap_or("?")
  4039. .to_string(),
  4040. _ => summarize_tool_payload(input),
  4041. };
  4042. let border = "─".repeat(name.len() + 8);
  4043. format!(
  4044. "\x1b[38;5;245m╭─ \x1b[1;36m{name}\x1b[0;38;5;245m ─╮\x1b[0m\n\x1b[38;5;245m│\x1b[0m {detail}\n\x1b[38;5;245m╰{border}╯\x1b[0m"
  4045. )
  4046. }
  4047. fn format_tool_result(name: &str, output: &str, is_error: bool) -> String {
  4048. let icon = if is_error {
  4049. "\x1b[1;31m✗\x1b[0m"
  4050. } else {
  4051. "\x1b[1;32m✓\x1b[0m"
  4052. };
  4053. if is_error {
  4054. let summary = truncate_for_summary(output.trim(), 160);
  4055. return if summary.is_empty() {
  4056. format!("{icon} \x1b[38;5;245m{name}\x1b[0m")
  4057. } else {
  4058. format!("{icon} \x1b[38;5;245m{name}\x1b[0m\n\x1b[38;5;203m{summary}\x1b[0m")
  4059. };
  4060. }
  4061. let parsed: serde_json::Value =
  4062. serde_json::from_str(output).unwrap_or(serde_json::Value::String(output.to_string()));
  4063. match name {
  4064. "bash" | "Bash" => format_bash_result(icon, &parsed),
  4065. "read_file" | "Read" => format_read_result(icon, &parsed),
  4066. "write_file" | "Write" => format_write_result(icon, &parsed),
  4067. "edit_file" | "Edit" => format_edit_result(icon, &parsed),
  4068. "glob_search" | "Glob" => format_glob_result(icon, &parsed),
  4069. "grep_search" | "Grep" => format_grep_result(icon, &parsed),
  4070. _ => format_generic_tool_result(icon, name, &parsed),
  4071. }
  4072. }
  4073. const DISPLAY_TRUNCATION_NOTICE: &str =
  4074. "\x1b[2m… output truncated for display; full result preserved in session.\x1b[0m";
  4075. const READ_DISPLAY_MAX_LINES: usize = 80;
  4076. const READ_DISPLAY_MAX_CHARS: usize = 6_000;
  4077. const TOOL_OUTPUT_DISPLAY_MAX_LINES: usize = 60;
  4078. const TOOL_OUTPUT_DISPLAY_MAX_CHARS: usize = 4_000;
  4079. fn extract_tool_path(parsed: &serde_json::Value) -> String {
  4080. parsed
  4081. .get("file_path")
  4082. .or_else(|| parsed.get("filePath"))
  4083. .or_else(|| parsed.get("path"))
  4084. .and_then(|value| value.as_str())
  4085. .unwrap_or("?")
  4086. .to_string()
  4087. }
  4088. fn format_search_start(label: &str, parsed: &serde_json::Value) -> String {
  4089. let pattern = parsed
  4090. .get("pattern")
  4091. .and_then(|value| value.as_str())
  4092. .unwrap_or("?");
  4093. let scope = parsed
  4094. .get("path")
  4095. .and_then(|value| value.as_str())
  4096. .unwrap_or(".");
  4097. format!("{label} {pattern}\n\x1b[2min {scope}\x1b[0m")
  4098. }
  4099. fn format_patch_preview(old_value: &str, new_value: &str) -> Option<String> {
  4100. if old_value.is_empty() && new_value.is_empty() {
  4101. return None;
  4102. }
  4103. Some(format!(
  4104. "\x1b[38;5;203m- {}\x1b[0m\n\x1b[38;5;70m+ {}\x1b[0m",
  4105. truncate_for_summary(first_visible_line(old_value), 72),
  4106. truncate_for_summary(first_visible_line(new_value), 72)
  4107. ))
  4108. }
  4109. fn format_bash_call(parsed: &serde_json::Value) -> String {
  4110. let command = parsed
  4111. .get("command")
  4112. .and_then(|value| value.as_str())
  4113. .unwrap_or_default();
  4114. if command.is_empty() {
  4115. String::new()
  4116. } else {
  4117. format!(
  4118. "\x1b[48;5;236;38;5;255m $ {} \x1b[0m",
  4119. truncate_for_summary(command, 160)
  4120. )
  4121. }
  4122. }
  4123. fn first_visible_line(text: &str) -> &str {
  4124. text.lines()
  4125. .find(|line| !line.trim().is_empty())
  4126. .unwrap_or(text)
  4127. }
  4128. fn format_bash_result(icon: &str, parsed: &serde_json::Value) -> String {
  4129. use std::fmt::Write as _;
  4130. let mut lines = vec![format!("{icon} \x1b[38;5;245mbash\x1b[0m")];
  4131. if let Some(task_id) = parsed
  4132. .get("backgroundTaskId")
  4133. .and_then(|value| value.as_str())
  4134. {
  4135. write!(&mut lines[0], " backgrounded ({task_id})").expect("write to string");
  4136. } else if let Some(status) = parsed
  4137. .get("returnCodeInterpretation")
  4138. .and_then(|value| value.as_str())
  4139. .filter(|status| !status.is_empty())
  4140. {
  4141. write!(&mut lines[0], " {status}").expect("write to string");
  4142. }
  4143. if let Some(stdout) = parsed.get("stdout").and_then(|value| value.as_str()) {
  4144. if !stdout.trim().is_empty() {
  4145. lines.push(truncate_output_for_display(
  4146. stdout,
  4147. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  4148. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  4149. ));
  4150. }
  4151. }
  4152. if let Some(stderr) = parsed.get("stderr").and_then(|value| value.as_str()) {
  4153. if !stderr.trim().is_empty() {
  4154. lines.push(format!(
  4155. "\x1b[38;5;203m{}\x1b[0m",
  4156. truncate_output_for_display(
  4157. stderr,
  4158. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  4159. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  4160. )
  4161. ));
  4162. }
  4163. }
  4164. lines.join("\n\n")
  4165. }
  4166. fn format_read_result(icon: &str, parsed: &serde_json::Value) -> String {
  4167. let file = parsed.get("file").unwrap_or(parsed);
  4168. let path = extract_tool_path(file);
  4169. let start_line = file
  4170. .get("startLine")
  4171. .and_then(serde_json::Value::as_u64)
  4172. .unwrap_or(1);
  4173. let num_lines = file
  4174. .get("numLines")
  4175. .and_then(serde_json::Value::as_u64)
  4176. .unwrap_or(0);
  4177. let total_lines = file
  4178. .get("totalLines")
  4179. .and_then(serde_json::Value::as_u64)
  4180. .unwrap_or(num_lines);
  4181. let content = file
  4182. .get("content")
  4183. .and_then(|value| value.as_str())
  4184. .unwrap_or_default();
  4185. let end_line = start_line.saturating_add(num_lines.saturating_sub(1));
  4186. format!(
  4187. "{icon} \x1b[2m📄 Read {path} (lines {}-{} of {})\x1b[0m\n{}",
  4188. start_line,
  4189. end_line.max(start_line),
  4190. total_lines,
  4191. truncate_output_for_display(content, READ_DISPLAY_MAX_LINES, READ_DISPLAY_MAX_CHARS)
  4192. )
  4193. }
  4194. fn format_write_result(icon: &str, parsed: &serde_json::Value) -> String {
  4195. let path = extract_tool_path(parsed);
  4196. let kind = parsed
  4197. .get("type")
  4198. .and_then(|value| value.as_str())
  4199. .unwrap_or("write");
  4200. let line_count = parsed
  4201. .get("content")
  4202. .and_then(|value| value.as_str())
  4203. .map_or(0, |content| content.lines().count());
  4204. format!(
  4205. "{icon} \x1b[1;32m✏️ {} {path}\x1b[0m \x1b[2m({line_count} lines)\x1b[0m",
  4206. if kind == "create" { "Wrote" } else { "Updated" },
  4207. )
  4208. }
  4209. fn format_structured_patch_preview(parsed: &serde_json::Value) -> Option<String> {
  4210. let hunks = parsed.get("structuredPatch")?.as_array()?;
  4211. let mut preview = Vec::new();
  4212. for hunk in hunks.iter().take(2) {
  4213. let lines = hunk.get("lines")?.as_array()?;
  4214. for line in lines.iter().filter_map(|value| value.as_str()).take(6) {
  4215. match line.chars().next() {
  4216. Some('+') => preview.push(format!("\x1b[38;5;70m{line}\x1b[0m")),
  4217. Some('-') => preview.push(format!("\x1b[38;5;203m{line}\x1b[0m")),
  4218. _ => preview.push(line.to_string()),
  4219. }
  4220. }
  4221. }
  4222. if preview.is_empty() {
  4223. None
  4224. } else {
  4225. Some(preview.join("\n"))
  4226. }
  4227. }
  4228. fn format_edit_result(icon: &str, parsed: &serde_json::Value) -> String {
  4229. let path = extract_tool_path(parsed);
  4230. let suffix = if parsed
  4231. .get("replaceAll")
  4232. .and_then(serde_json::Value::as_bool)
  4233. .unwrap_or(false)
  4234. {
  4235. " (replace all)"
  4236. } else {
  4237. ""
  4238. };
  4239. let preview = format_structured_patch_preview(parsed).or_else(|| {
  4240. let old_value = parsed
  4241. .get("oldString")
  4242. .and_then(|value| value.as_str())
  4243. .unwrap_or_default();
  4244. let new_value = parsed
  4245. .get("newString")
  4246. .and_then(|value| value.as_str())
  4247. .unwrap_or_default();
  4248. format_patch_preview(old_value, new_value)
  4249. });
  4250. match preview {
  4251. Some(preview) => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m\n{preview}"),
  4252. None => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m"),
  4253. }
  4254. }
  4255. fn format_glob_result(icon: &str, parsed: &serde_json::Value) -> String {
  4256. let num_files = parsed
  4257. .get("numFiles")
  4258. .and_then(serde_json::Value::as_u64)
  4259. .unwrap_or(0);
  4260. let filenames = parsed
  4261. .get("filenames")
  4262. .and_then(|value| value.as_array())
  4263. .map(|files| {
  4264. files
  4265. .iter()
  4266. .filter_map(|value| value.as_str())
  4267. .take(8)
  4268. .collect::<Vec<_>>()
  4269. .join("\n")
  4270. })
  4271. .unwrap_or_default();
  4272. if filenames.is_empty() {
  4273. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files")
  4274. } else {
  4275. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files\n{filenames}")
  4276. }
  4277. }
  4278. fn format_grep_result(icon: &str, parsed: &serde_json::Value) -> String {
  4279. let num_matches = parsed
  4280. .get("numMatches")
  4281. .and_then(serde_json::Value::as_u64)
  4282. .unwrap_or(0);
  4283. let num_files = parsed
  4284. .get("numFiles")
  4285. .and_then(serde_json::Value::as_u64)
  4286. .unwrap_or(0);
  4287. let content = parsed
  4288. .get("content")
  4289. .and_then(|value| value.as_str())
  4290. .unwrap_or_default();
  4291. let filenames = parsed
  4292. .get("filenames")
  4293. .and_then(|value| value.as_array())
  4294. .map(|files| {
  4295. files
  4296. .iter()
  4297. .filter_map(|value| value.as_str())
  4298. .take(8)
  4299. .collect::<Vec<_>>()
  4300. .join("\n")
  4301. })
  4302. .unwrap_or_default();
  4303. let summary = format!(
  4304. "{icon} \x1b[38;5;245mgrep_search\x1b[0m {num_matches} matches across {num_files} files"
  4305. );
  4306. if !content.trim().is_empty() {
  4307. format!(
  4308. "{summary}\n{}",
  4309. truncate_output_for_display(
  4310. content,
  4311. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  4312. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  4313. )
  4314. )
  4315. } else if !filenames.is_empty() {
  4316. format!("{summary}\n{filenames}")
  4317. } else {
  4318. summary
  4319. }
  4320. }
  4321. fn format_generic_tool_result(icon: &str, name: &str, parsed: &serde_json::Value) -> String {
  4322. let rendered_output = match parsed {
  4323. serde_json::Value::String(text) => text.clone(),
  4324. serde_json::Value::Null => String::new(),
  4325. serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
  4326. serde_json::to_string_pretty(parsed).unwrap_or_else(|_| parsed.to_string())
  4327. }
  4328. _ => parsed.to_string(),
  4329. };
  4330. let preview = truncate_output_for_display(
  4331. &rendered_output,
  4332. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  4333. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  4334. );
  4335. if preview.is_empty() {
  4336. format!("{icon} \x1b[38;5;245m{name}\x1b[0m")
  4337. } else if preview.contains('\n') {
  4338. format!("{icon} \x1b[38;5;245m{name}\x1b[0m\n{preview}")
  4339. } else {
  4340. format!("{icon} \x1b[38;5;245m{name}:\x1b[0m {preview}")
  4341. }
  4342. }
  4343. fn summarize_tool_payload(payload: &str) -> String {
  4344. let compact = match serde_json::from_str::<serde_json::Value>(payload) {
  4345. Ok(value) => value.to_string(),
  4346. Err(_) => payload.trim().to_string(),
  4347. };
  4348. truncate_for_summary(&compact, 96)
  4349. }
  4350. fn truncate_for_summary(value: &str, limit: usize) -> String {
  4351. let mut chars = value.chars();
  4352. let truncated = chars.by_ref().take(limit).collect::<String>();
  4353. if chars.next().is_some() {
  4354. format!("{truncated}…")
  4355. } else {
  4356. truncated
  4357. }
  4358. }
  4359. fn truncate_output_for_display(content: &str, max_lines: usize, max_chars: usize) -> String {
  4360. let original = content.trim_end_matches('\n');
  4361. if original.is_empty() {
  4362. return String::new();
  4363. }
  4364. let mut preview_lines = Vec::new();
  4365. let mut used_chars = 0usize;
  4366. let mut truncated = false;
  4367. for (index, line) in original.lines().enumerate() {
  4368. if index >= max_lines {
  4369. truncated = true;
  4370. break;
  4371. }
  4372. let newline_cost = usize::from(!preview_lines.is_empty());
  4373. let available = max_chars.saturating_sub(used_chars + newline_cost);
  4374. if available == 0 {
  4375. truncated = true;
  4376. break;
  4377. }
  4378. let line_chars = line.chars().count();
  4379. if line_chars > available {
  4380. preview_lines.push(line.chars().take(available).collect::<String>());
  4381. truncated = true;
  4382. break;
  4383. }
  4384. preview_lines.push(line.to_string());
  4385. used_chars += newline_cost + line_chars;
  4386. }
  4387. let mut preview = preview_lines.join("\n");
  4388. if truncated {
  4389. if !preview.is_empty() {
  4390. preview.push('\n');
  4391. }
  4392. preview.push_str(DISPLAY_TRUNCATION_NOTICE);
  4393. }
  4394. preview
  4395. }
  4396. fn push_output_block(
  4397. block: OutputContentBlock,
  4398. out: &mut (impl Write + ?Sized),
  4399. events: &mut Vec<AssistantEvent>,
  4400. pending_tool: &mut Option<(String, String, String)>,
  4401. streaming_tool_input: bool,
  4402. ) -> Result<(), RuntimeError> {
  4403. match block {
  4404. OutputContentBlock::Text { text } => {
  4405. if !text.is_empty() {
  4406. let rendered = TerminalRenderer::new().markdown_to_ansi(&text);
  4407. write!(out, "{rendered}")
  4408. .and_then(|()| out.flush())
  4409. .map_err(|error| RuntimeError::new(error.to_string()))?;
  4410. events.push(AssistantEvent::TextDelta(text));
  4411. }
  4412. }
  4413. OutputContentBlock::ToolUse { id, name, input } => {
  4414. // During streaming, the initial content_block_start has an empty input ({}).
  4415. // The real input arrives via input_json_delta events. In
  4416. // non-streaming responses, preserve a legitimate empty object.
  4417. let initial_input = if streaming_tool_input
  4418. && input.is_object()
  4419. && input.as_object().is_some_and(serde_json::Map::is_empty)
  4420. {
  4421. String::new()
  4422. } else {
  4423. input.to_string()
  4424. };
  4425. *pending_tool = Some((id, name, initial_input));
  4426. }
  4427. OutputContentBlock::Thinking { .. } | OutputContentBlock::RedactedThinking { .. } => {}
  4428. }
  4429. Ok(())
  4430. }
  4431. fn response_to_events(
  4432. response: MessageResponse,
  4433. out: &mut (impl Write + ?Sized),
  4434. ) -> Result<Vec<AssistantEvent>, RuntimeError> {
  4435. let mut events = Vec::new();
  4436. let mut pending_tool = None;
  4437. for block in response.content {
  4438. push_output_block(block, out, &mut events, &mut pending_tool, false)?;
  4439. if let Some((id, name, input)) = pending_tool.take() {
  4440. events.push(AssistantEvent::ToolUse { id, name, input });
  4441. }
  4442. }
  4443. events.push(AssistantEvent::Usage(response.usage.token_usage()));
  4444. events.push(AssistantEvent::MessageStop);
  4445. Ok(events)
  4446. }
  4447. fn push_prompt_cache_record(client: &AnthropicClient, events: &mut Vec<AssistantEvent>) {
  4448. if let Some(record) = client.take_last_prompt_cache_record() {
  4449. if let Some(event) = prompt_cache_record_to_runtime_event(record) {
  4450. events.push(AssistantEvent::PromptCache(event));
  4451. }
  4452. }
  4453. }
  4454. fn prompt_cache_record_to_runtime_event(
  4455. record: api::PromptCacheRecord,
  4456. ) -> Option<PromptCacheEvent> {
  4457. let cache_break = record.cache_break?;
  4458. Some(PromptCacheEvent {
  4459. unexpected: cache_break.unexpected,
  4460. reason: cache_break.reason,
  4461. previous_cache_read_input_tokens: cache_break.previous_cache_read_input_tokens,
  4462. current_cache_read_input_tokens: cache_break.current_cache_read_input_tokens,
  4463. token_drop: cache_break.token_drop,
  4464. })
  4465. }
  4466. struct CliToolExecutor {
  4467. renderer: TerminalRenderer,
  4468. emit_output: bool,
  4469. allowed_tools: Option<AllowedToolSet>,
  4470. tool_registry: GlobalToolRegistry,
  4471. }
  4472. impl CliToolExecutor {
  4473. fn new(
  4474. allowed_tools: Option<AllowedToolSet>,
  4475. emit_output: bool,
  4476. tool_registry: GlobalToolRegistry,
  4477. ) -> Self {
  4478. Self {
  4479. renderer: TerminalRenderer::new(),
  4480. emit_output,
  4481. allowed_tools,
  4482. tool_registry,
  4483. }
  4484. }
  4485. }
  4486. impl ToolExecutor for CliToolExecutor {
  4487. fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
  4488. if self
  4489. .allowed_tools
  4490. .as_ref()
  4491. .is_some_and(|allowed| !allowed.contains(tool_name))
  4492. {
  4493. return Err(ToolError::new(format!(
  4494. "tool `{tool_name}` is not enabled by the current --allowedTools setting"
  4495. )));
  4496. }
  4497. let value = serde_json::from_str(input)
  4498. .map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
  4499. match self.tool_registry.execute(tool_name, &value) {
  4500. Ok(output) => {
  4501. if self.emit_output {
  4502. let markdown = format_tool_result(tool_name, &output, false);
  4503. self.renderer
  4504. .stream_markdown(&markdown, &mut io::stdout())
  4505. .map_err(|error| ToolError::new(error.to_string()))?;
  4506. }
  4507. Ok(output)
  4508. }
  4509. Err(error) => {
  4510. if self.emit_output {
  4511. let markdown = format_tool_result(tool_name, &error, true);
  4512. self.renderer
  4513. .stream_markdown(&markdown, &mut io::stdout())
  4514. .map_err(|stream_error| ToolError::new(stream_error.to_string()))?;
  4515. }
  4516. Err(ToolError::new(error))
  4517. }
  4518. }
  4519. }
  4520. }
  4521. fn permission_policy(
  4522. mode: PermissionMode,
  4523. feature_config: &runtime::RuntimeFeatureConfig,
  4524. tool_registry: &GlobalToolRegistry,
  4525. ) -> Result<PermissionPolicy, String> {
  4526. Ok(tool_registry.permission_specs(None)?.into_iter().fold(
  4527. PermissionPolicy::new(mode).with_permission_rules(feature_config.permission_rules()),
  4528. |policy, (name, required_permission)| {
  4529. policy.with_tool_requirement(name, required_permission)
  4530. },
  4531. ))
  4532. }
  4533. fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
  4534. messages
  4535. .iter()
  4536. .filter_map(|message| {
  4537. let role = match message.role {
  4538. MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
  4539. MessageRole::Assistant => "assistant",
  4540. };
  4541. let content = message
  4542. .blocks
  4543. .iter()
  4544. .map(|block| match block {
  4545. ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
  4546. ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
  4547. id: id.clone(),
  4548. name: name.clone(),
  4549. input: serde_json::from_str(input)
  4550. .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
  4551. },
  4552. ContentBlock::ToolResult {
  4553. tool_use_id,
  4554. output,
  4555. is_error,
  4556. ..
  4557. } => InputContentBlock::ToolResult {
  4558. tool_use_id: tool_use_id.clone(),
  4559. content: vec![ToolResultContentBlock::Text {
  4560. text: output.clone(),
  4561. }],
  4562. is_error: *is_error,
  4563. },
  4564. })
  4565. .collect::<Vec<_>>();
  4566. (!content.is_empty()).then(|| InputMessage {
  4567. role: role.to_string(),
  4568. content,
  4569. })
  4570. })
  4571. .collect()
  4572. }
  4573. #[allow(clippy::too_many_lines)]
  4574. fn print_help_to(out: &mut impl Write) -> io::Result<()> {
  4575. writeln!(out, "claw v{VERSION}")?;
  4576. writeln!(out)?;
  4577. writeln!(out, "Usage:")?;
  4578. writeln!(
  4579. out,
  4580. " claw [--model MODEL] [--allowedTools TOOL[,TOOL...]]"
  4581. )?;
  4582. writeln!(out, " Start the interactive REPL")?;
  4583. writeln!(
  4584. out,
  4585. " claw [--model MODEL] [--output-format text|json] prompt TEXT"
  4586. )?;
  4587. writeln!(out, " Send one prompt and exit")?;
  4588. writeln!(
  4589. out,
  4590. " claw [--model MODEL] [--output-format text|json] TEXT"
  4591. )?;
  4592. writeln!(out, " Shorthand non-interactive prompt mode")?;
  4593. writeln!(
  4594. out,
  4595. " claw --resume [SESSION.jsonl|session-id|latest] [/status] [/compact] [...]"
  4596. )?;
  4597. writeln!(
  4598. out,
  4599. " Inspect or maintain a saved session without entering the REPL"
  4600. )?;
  4601. writeln!(out, " claw help")?;
  4602. writeln!(out, " Alias for --help")?;
  4603. writeln!(out, " claw version")?;
  4604. writeln!(out, " Alias for --version")?;
  4605. writeln!(out, " claw status")?;
  4606. writeln!(
  4607. out,
  4608. " Show the current local workspace status snapshot"
  4609. )?;
  4610. writeln!(out, " claw sandbox")?;
  4611. writeln!(out, " Show the current sandbox isolation snapshot")?;
  4612. writeln!(out, " claw dump-manifests")?;
  4613. writeln!(out, " claw bootstrap-plan")?;
  4614. writeln!(out, " claw agents")?;
  4615. writeln!(out, " claw mcp")?;
  4616. writeln!(out, " claw skills")?;
  4617. writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
  4618. writeln!(out, " claw login")?;
  4619. writeln!(out, " claw logout")?;
  4620. writeln!(out, " claw init")?;
  4621. writeln!(out)?;
  4622. writeln!(out, "Flags:")?;
  4623. writeln!(
  4624. out,
  4625. " --model MODEL Override the active model"
  4626. )?;
  4627. writeln!(
  4628. out,
  4629. " --output-format FORMAT Non-interactive output format: text or json"
  4630. )?;
  4631. writeln!(
  4632. out,
  4633. " --permission-mode MODE Set read-only, workspace-write, or danger-full-access"
  4634. )?;
  4635. writeln!(
  4636. out,
  4637. " --dangerously-skip-permissions Skip all permission checks"
  4638. )?;
  4639. writeln!(out, " --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)")?;
  4640. writeln!(
  4641. out,
  4642. " --version, -V Print version and build information locally"
  4643. )?;
  4644. writeln!(out)?;
  4645. writeln!(out, "Interactive slash commands:")?;
  4646. writeln!(out, "{}", render_slash_command_help())?;
  4647. writeln!(out)?;
  4648. let resume_commands = resume_supported_slash_commands()
  4649. .into_iter()
  4650. .map(|spec| match spec.argument_hint {
  4651. Some(argument_hint) => format!("/{} {}", spec.name, argument_hint),
  4652. None => format!("/{}", spec.name),
  4653. })
  4654. .collect::<Vec<_>>()
  4655. .join(", ");
  4656. writeln!(out, "Resume-safe commands: {resume_commands}")?;
  4657. writeln!(out)?;
  4658. writeln!(out, "Session shortcuts:")?;
  4659. writeln!(
  4660. out,
  4661. " REPL turns auto-save to .claw/sessions/<session-id>.{PRIMARY_SESSION_EXTENSION}"
  4662. )?;
  4663. writeln!(
  4664. out,
  4665. " Use `{LATEST_SESSION_REFERENCE}` with --resume, /resume, or /session switch to target the newest saved session"
  4666. )?;
  4667. writeln!(
  4668. out,
  4669. " Use /session list in the REPL to browse managed sessions"
  4670. )?;
  4671. writeln!(out, "Examples:")?;
  4672. writeln!(out, " claw --model claude-opus \"summarize this repo\"")?;
  4673. writeln!(
  4674. out,
  4675. " claw --output-format json prompt \"explain src/main.rs\""
  4676. )?;
  4677. writeln!(
  4678. out,
  4679. " claw --allowedTools read,glob \"summarize Cargo.toml\""
  4680. )?;
  4681. writeln!(out, " claw --resume {LATEST_SESSION_REFERENCE}")?;
  4682. writeln!(
  4683. out,
  4684. " claw --resume {LATEST_SESSION_REFERENCE} /status /diff /export notes.txt"
  4685. )?;
  4686. writeln!(out, " claw agents")?;
  4687. writeln!(out, " claw mcp show my-server")?;
  4688. writeln!(out, " claw /skills")?;
  4689. writeln!(out, " claw login")?;
  4690. writeln!(out, " claw init")?;
  4691. Ok(())
  4692. }
  4693. fn print_help() {
  4694. let _ = print_help_to(&mut io::stdout());
  4695. }
  4696. #[cfg(test)]
  4697. mod tests {
  4698. use super::{
  4699. build_runtime_plugin_state_with_loader, build_runtime_with_plugin_state,
  4700. create_managed_session_handle, describe_tool_progress, filter_tool_specs,
  4701. format_bughunter_report, format_commit_preflight_report, format_commit_skipped_report,
  4702. format_compact_report, format_cost_report, format_internal_prompt_progress_line,
  4703. format_issue_report, format_model_report, format_model_switch_report,
  4704. format_permissions_report, format_permissions_switch_report, format_pr_report,
  4705. format_resume_report, format_status_report, format_tool_call_start, format_tool_result,
  4706. format_ultraplan_report, format_unknown_slash_command,
  4707. format_unknown_slash_command_message, normalize_permission_mode, parse_args,
  4708. parse_git_status_branch, parse_git_status_metadata_for, parse_git_workspace_summary,
  4709. permission_policy, print_help_to, push_output_block, render_config_report,
  4710. render_diff_report, render_memory_report, render_repl_help, render_resume_usage,
  4711. resolve_model_alias, resolve_session_reference, response_to_events,
  4712. resume_supported_slash_commands, run_resume_command,
  4713. slash_command_completion_candidates_with_sessions, status_context, validate_no_args,
  4714. CliAction, CliOutputFormat, GitWorkspaceSummary, InternalPromptProgressEvent,
  4715. InternalPromptProgressState, LiveCli, SlashCommand, StatusUsage, DEFAULT_MODEL,
  4716. };
  4717. use api::{MessageResponse, OutputContentBlock, Usage};
  4718. use plugins::{
  4719. PluginManager, PluginManagerConfig, PluginTool, PluginToolDefinition, PluginToolPermission,
  4720. };
  4721. use runtime::{
  4722. AssistantEvent, ConfigLoader, ContentBlock, ConversationMessage, MessageRole,
  4723. PermissionMode, Session,
  4724. };
  4725. use serde_json::json;
  4726. use std::fs;
  4727. use std::path::{Path, PathBuf};
  4728. use std::process::Command;
  4729. use std::sync::{Mutex, MutexGuard, OnceLock};
  4730. use std::time::{Duration, SystemTime, UNIX_EPOCH};
  4731. use tools::GlobalToolRegistry;
  4732. fn registry_with_plugin_tool() -> GlobalToolRegistry {
  4733. GlobalToolRegistry::with_plugin_tools(vec![PluginTool::new(
  4734. "plugin-demo@external",
  4735. "plugin-demo",
  4736. PluginToolDefinition {
  4737. name: "plugin_echo".to_string(),
  4738. description: Some("Echo plugin payload".to_string()),
  4739. input_schema: json!({
  4740. "type": "object",
  4741. "properties": {
  4742. "message": { "type": "string" }
  4743. },
  4744. "required": ["message"],
  4745. "additionalProperties": false
  4746. }),
  4747. },
  4748. "echo".to_string(),
  4749. Vec::new(),
  4750. PluginToolPermission::WorkspaceWrite,
  4751. None,
  4752. )])
  4753. .expect("plugin tool registry should build")
  4754. }
  4755. fn temp_dir() -> PathBuf {
  4756. let nanos = SystemTime::now()
  4757. .duration_since(UNIX_EPOCH)
  4758. .expect("time should be after epoch")
  4759. .as_nanos();
  4760. std::env::temp_dir().join(format!("rusty-claude-cli-{nanos}"))
  4761. }
  4762. fn git(args: &[&str], cwd: &Path) {
  4763. let status = Command::new("git")
  4764. .args(args)
  4765. .current_dir(cwd)
  4766. .status()
  4767. .expect("git command should run");
  4768. assert!(
  4769. status.success(),
  4770. "git command failed: git {}",
  4771. args.join(" ")
  4772. );
  4773. }
  4774. fn env_lock() -> MutexGuard<'static, ()> {
  4775. static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
  4776. LOCK.get_or_init(|| Mutex::new(()))
  4777. .lock()
  4778. .unwrap_or_else(std::sync::PoisonError::into_inner)
  4779. }
  4780. fn with_current_dir<T>(cwd: &Path, f: impl FnOnce() -> T) -> T {
  4781. let previous = std::env::current_dir().expect("cwd should load");
  4782. std::env::set_current_dir(cwd).expect("cwd should change");
  4783. let result = f();
  4784. std::env::set_current_dir(previous).expect("cwd should restore");
  4785. result
  4786. }
  4787. fn write_plugin_fixture(root: &Path, name: &str, include_hooks: bool, include_lifecycle: bool) {
  4788. fs::create_dir_all(root.join(".claude-plugin")).expect("manifest dir");
  4789. if include_hooks {
  4790. fs::create_dir_all(root.join("hooks")).expect("hooks dir");
  4791. fs::write(
  4792. root.join("hooks").join("pre.sh"),
  4793. "#!/bin/sh\nprintf 'plugin pre hook'\n",
  4794. )
  4795. .expect("write hook");
  4796. }
  4797. if include_lifecycle {
  4798. fs::create_dir_all(root.join("lifecycle")).expect("lifecycle dir");
  4799. fs::write(
  4800. root.join("lifecycle").join("init.sh"),
  4801. "#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
  4802. )
  4803. .expect("write init lifecycle");
  4804. fs::write(
  4805. root.join("lifecycle").join("shutdown.sh"),
  4806. "#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
  4807. )
  4808. .expect("write shutdown lifecycle");
  4809. }
  4810. let hooks = if include_hooks {
  4811. ",\n \"hooks\": {\n \"PreToolUse\": [\"./hooks/pre.sh\"]\n }"
  4812. } else {
  4813. ""
  4814. };
  4815. let lifecycle = if include_lifecycle {
  4816. ",\n \"lifecycle\": {\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }"
  4817. } else {
  4818. ""
  4819. };
  4820. fs::write(
  4821. root.join(".claude-plugin").join("plugin.json"),
  4822. format!(
  4823. "{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"runtime plugin fixture\"{hooks}{lifecycle}\n}}"
  4824. ),
  4825. )
  4826. .expect("write plugin manifest");
  4827. }
  4828. #[test]
  4829. fn defaults_to_repl_when_no_args() {
  4830. assert_eq!(
  4831. parse_args(&[]).expect("args should parse"),
  4832. CliAction::Repl {
  4833. model: DEFAULT_MODEL.to_string(),
  4834. allowed_tools: None,
  4835. permission_mode: PermissionMode::DangerFullAccess,
  4836. }
  4837. );
  4838. }
  4839. #[test]
  4840. fn parses_prompt_subcommand() {
  4841. let args = vec![
  4842. "prompt".to_string(),
  4843. "hello".to_string(),
  4844. "world".to_string(),
  4845. ];
  4846. assert_eq!(
  4847. parse_args(&args).expect("args should parse"),
  4848. CliAction::Prompt {
  4849. prompt: "hello world".to_string(),
  4850. model: DEFAULT_MODEL.to_string(),
  4851. output_format: CliOutputFormat::Text,
  4852. allowed_tools: None,
  4853. permission_mode: PermissionMode::DangerFullAccess,
  4854. }
  4855. );
  4856. }
  4857. #[test]
  4858. fn parses_bare_prompt_and_json_output_flag() {
  4859. let args = vec![
  4860. "--output-format=json".to_string(),
  4861. "--model".to_string(),
  4862. "claude-opus".to_string(),
  4863. "explain".to_string(),
  4864. "this".to_string(),
  4865. ];
  4866. assert_eq!(
  4867. parse_args(&args).expect("args should parse"),
  4868. CliAction::Prompt {
  4869. prompt: "explain this".to_string(),
  4870. model: "claude-opus".to_string(),
  4871. output_format: CliOutputFormat::Json,
  4872. allowed_tools: None,
  4873. permission_mode: PermissionMode::DangerFullAccess,
  4874. }
  4875. );
  4876. }
  4877. #[test]
  4878. fn resolves_model_aliases_in_args() {
  4879. let args = vec![
  4880. "--model".to_string(),
  4881. "opus".to_string(),
  4882. "explain".to_string(),
  4883. "this".to_string(),
  4884. ];
  4885. assert_eq!(
  4886. parse_args(&args).expect("args should parse"),
  4887. CliAction::Prompt {
  4888. prompt: "explain this".to_string(),
  4889. model: "claude-opus-4-6".to_string(),
  4890. output_format: CliOutputFormat::Text,
  4891. allowed_tools: None,
  4892. permission_mode: PermissionMode::DangerFullAccess,
  4893. }
  4894. );
  4895. }
  4896. #[test]
  4897. fn resolves_known_model_aliases() {
  4898. assert_eq!(resolve_model_alias("opus"), "claude-opus-4-6");
  4899. assert_eq!(resolve_model_alias("sonnet"), "claude-sonnet-4-6");
  4900. assert_eq!(resolve_model_alias("haiku"), "claude-haiku-4-5-20251213");
  4901. assert_eq!(resolve_model_alias("claude-opus"), "claude-opus");
  4902. }
  4903. #[test]
  4904. fn parses_version_flags_without_initializing_prompt_mode() {
  4905. assert_eq!(
  4906. parse_args(&["--version".to_string()]).expect("args should parse"),
  4907. CliAction::Version
  4908. );
  4909. assert_eq!(
  4910. parse_args(&["-V".to_string()]).expect("args should parse"),
  4911. CliAction::Version
  4912. );
  4913. }
  4914. #[test]
  4915. fn parses_permission_mode_flag() {
  4916. let args = vec!["--permission-mode=read-only".to_string()];
  4917. assert_eq!(
  4918. parse_args(&args).expect("args should parse"),
  4919. CliAction::Repl {
  4920. model: DEFAULT_MODEL.to_string(),
  4921. allowed_tools: None,
  4922. permission_mode: PermissionMode::ReadOnly,
  4923. }
  4924. );
  4925. }
  4926. #[test]
  4927. fn parses_allowed_tools_flags_with_aliases_and_lists() {
  4928. let args = vec![
  4929. "--allowedTools".to_string(),
  4930. "read,glob".to_string(),
  4931. "--allowed-tools=write_file".to_string(),
  4932. ];
  4933. assert_eq!(
  4934. parse_args(&args).expect("args should parse"),
  4935. CliAction::Repl {
  4936. model: DEFAULT_MODEL.to_string(),
  4937. allowed_tools: Some(
  4938. ["glob_search", "read_file", "write_file"]
  4939. .into_iter()
  4940. .map(str::to_string)
  4941. .collect()
  4942. ),
  4943. permission_mode: PermissionMode::DangerFullAccess,
  4944. }
  4945. );
  4946. }
  4947. #[test]
  4948. fn rejects_unknown_allowed_tools() {
  4949. let error = parse_args(&["--allowedTools".to_string(), "teleport".to_string()])
  4950. .expect_err("tool should be rejected");
  4951. assert!(error.contains("unsupported tool in --allowedTools: teleport"));
  4952. }
  4953. #[test]
  4954. fn parses_system_prompt_options() {
  4955. let args = vec![
  4956. "system-prompt".to_string(),
  4957. "--cwd".to_string(),
  4958. "/tmp/project".to_string(),
  4959. "--date".to_string(),
  4960. "2026-04-01".to_string(),
  4961. ];
  4962. assert_eq!(
  4963. parse_args(&args).expect("args should parse"),
  4964. CliAction::PrintSystemPrompt {
  4965. cwd: PathBuf::from("/tmp/project"),
  4966. date: "2026-04-01".to_string(),
  4967. }
  4968. );
  4969. }
  4970. #[test]
  4971. fn parses_login_and_logout_subcommands() {
  4972. assert_eq!(
  4973. parse_args(&["login".to_string()]).expect("login should parse"),
  4974. CliAction::Login
  4975. );
  4976. assert_eq!(
  4977. parse_args(&["logout".to_string()]).expect("logout should parse"),
  4978. CliAction::Logout
  4979. );
  4980. assert_eq!(
  4981. parse_args(&["init".to_string()]).expect("init should parse"),
  4982. CliAction::Init
  4983. );
  4984. assert_eq!(
  4985. parse_args(&["agents".to_string()]).expect("agents should parse"),
  4986. CliAction::Agents { args: None }
  4987. );
  4988. assert_eq!(
  4989. parse_args(&["mcp".to_string()]).expect("mcp should parse"),
  4990. CliAction::Mcp { args: None }
  4991. );
  4992. assert_eq!(
  4993. parse_args(&["skills".to_string()]).expect("skills should parse"),
  4994. CliAction::Skills { args: None }
  4995. );
  4996. assert_eq!(
  4997. parse_args(&["agents".to_string(), "--help".to_string()])
  4998. .expect("agents help should parse"),
  4999. CliAction::Agents {
  5000. args: Some("--help".to_string())
  5001. }
  5002. );
  5003. }
  5004. #[test]
  5005. fn parses_single_word_command_aliases_without_falling_back_to_prompt_mode() {
  5006. assert_eq!(
  5007. parse_args(&["help".to_string()]).expect("help should parse"),
  5008. CliAction::Help
  5009. );
  5010. assert_eq!(
  5011. parse_args(&["version".to_string()]).expect("version should parse"),
  5012. CliAction::Version
  5013. );
  5014. assert_eq!(
  5015. parse_args(&["status".to_string()]).expect("status should parse"),
  5016. CliAction::Status {
  5017. model: DEFAULT_MODEL.to_string(),
  5018. permission_mode: PermissionMode::DangerFullAccess,
  5019. }
  5020. );
  5021. assert_eq!(
  5022. parse_args(&["sandbox".to_string()]).expect("sandbox should parse"),
  5023. CliAction::Sandbox
  5024. );
  5025. }
  5026. #[test]
  5027. fn single_word_slash_command_names_return_guidance_instead_of_hitting_prompt_mode() {
  5028. let error = parse_args(&["cost".to_string()]).expect_err("cost should return guidance");
  5029. assert!(error.contains("slash command"));
  5030. assert!(error.contains("/cost"));
  5031. }
  5032. #[test]
  5033. fn multi_word_prompt_still_uses_shorthand_prompt_mode() {
  5034. assert_eq!(
  5035. parse_args(&["help".to_string(), "me".to_string(), "debug".to_string()])
  5036. .expect("prompt shorthand should still work"),
  5037. CliAction::Prompt {
  5038. prompt: "help me debug".to_string(),
  5039. model: DEFAULT_MODEL.to_string(),
  5040. output_format: CliOutputFormat::Text,
  5041. allowed_tools: None,
  5042. permission_mode: PermissionMode::DangerFullAccess,
  5043. }
  5044. );
  5045. }
  5046. #[test]
  5047. fn parses_direct_agents_mcp_and_skills_slash_commands() {
  5048. assert_eq!(
  5049. parse_args(&["/agents".to_string()]).expect("/agents should parse"),
  5050. CliAction::Agents { args: None }
  5051. );
  5052. assert_eq!(
  5053. parse_args(&["/mcp".to_string(), "show".to_string(), "demo".to_string()])
  5054. .expect("/mcp show demo should parse"),
  5055. CliAction::Mcp {
  5056. args: Some("show demo".to_string())
  5057. }
  5058. );
  5059. assert_eq!(
  5060. parse_args(&["/skills".to_string()]).expect("/skills should parse"),
  5061. CliAction::Skills { args: None }
  5062. );
  5063. assert_eq!(
  5064. parse_args(&["/skills".to_string(), "help".to_string()])
  5065. .expect("/skills help should parse"),
  5066. CliAction::Skills {
  5067. args: Some("help".to_string())
  5068. }
  5069. );
  5070. assert_eq!(
  5071. parse_args(&[
  5072. "/skills".to_string(),
  5073. "install".to_string(),
  5074. "./fixtures/help-skill".to_string(),
  5075. ])
  5076. .expect("/skills install should parse"),
  5077. CliAction::Skills {
  5078. args: Some("install ./fixtures/help-skill".to_string())
  5079. }
  5080. );
  5081. let error = parse_args(&["/status".to_string()])
  5082. .expect_err("/status should remain REPL-only when invoked directly");
  5083. assert!(error.contains("interactive-only"));
  5084. assert!(error.contains("claw --resume SESSION.jsonl /status"));
  5085. }
  5086. #[test]
  5087. fn direct_slash_commands_surface_shared_validation_errors() {
  5088. let compact_error = parse_args(&["/compact".to_string(), "now".to_string()])
  5089. .expect_err("invalid /compact shape should be rejected");
  5090. assert!(compact_error.contains("Unexpected arguments for /compact."));
  5091. assert!(compact_error.contains("Usage /compact"));
  5092. let plugins_error = parse_args(&[
  5093. "/plugins".to_string(),
  5094. "list".to_string(),
  5095. "extra".to_string(),
  5096. ])
  5097. .expect_err("invalid /plugins list shape should be rejected");
  5098. assert!(plugins_error.contains("Usage: /plugin list"));
  5099. assert!(plugins_error.contains("Aliases /plugins, /marketplace"));
  5100. }
  5101. #[test]
  5102. fn formats_unknown_slash_command_with_suggestions() {
  5103. let report = format_unknown_slash_command_message("stats");
  5104. assert!(report.contains("unknown slash command: /stats"));
  5105. assert!(report.contains("Did you mean /status?"));
  5106. assert!(report.contains("Use /help"));
  5107. }
  5108. #[test]
  5109. fn parses_resume_flag_with_slash_command() {
  5110. let args = vec![
  5111. "--resume".to_string(),
  5112. "session.jsonl".to_string(),
  5113. "/compact".to_string(),
  5114. ];
  5115. assert_eq!(
  5116. parse_args(&args).expect("args should parse"),
  5117. CliAction::ResumeSession {
  5118. session_path: PathBuf::from("session.jsonl"),
  5119. commands: vec!["/compact".to_string()],
  5120. }
  5121. );
  5122. }
  5123. #[test]
  5124. fn parses_resume_flag_without_path_as_latest_session() {
  5125. assert_eq!(
  5126. parse_args(&["--resume".to_string()]).expect("args should parse"),
  5127. CliAction::ResumeSession {
  5128. session_path: PathBuf::from("latest"),
  5129. commands: vec![],
  5130. }
  5131. );
  5132. assert_eq!(
  5133. parse_args(&["--resume".to_string(), "/status".to_string()])
  5134. .expect("resume shortcut should parse"),
  5135. CliAction::ResumeSession {
  5136. session_path: PathBuf::from("latest"),
  5137. commands: vec!["/status".to_string()],
  5138. }
  5139. );
  5140. }
  5141. #[test]
  5142. fn parses_resume_flag_with_multiple_slash_commands() {
  5143. let args = vec![
  5144. "--resume".to_string(),
  5145. "session.jsonl".to_string(),
  5146. "/status".to_string(),
  5147. "/compact".to_string(),
  5148. "/cost".to_string(),
  5149. ];
  5150. assert_eq!(
  5151. parse_args(&args).expect("args should parse"),
  5152. CliAction::ResumeSession {
  5153. session_path: PathBuf::from("session.jsonl"),
  5154. commands: vec![
  5155. "/status".to_string(),
  5156. "/compact".to_string(),
  5157. "/cost".to_string(),
  5158. ],
  5159. }
  5160. );
  5161. }
  5162. #[test]
  5163. fn rejects_unknown_options_with_helpful_guidance() {
  5164. let error = parse_args(&["--resum".to_string()]).expect_err("unknown option should fail");
  5165. assert!(error.contains("unknown option: --resum"));
  5166. assert!(error.contains("Did you mean --resume?"));
  5167. assert!(error.contains("claw --help"));
  5168. }
  5169. #[test]
  5170. fn parses_resume_flag_with_slash_command_arguments() {
  5171. let args = vec![
  5172. "--resume".to_string(),
  5173. "session.jsonl".to_string(),
  5174. "/export".to_string(),
  5175. "notes.txt".to_string(),
  5176. "/clear".to_string(),
  5177. "--confirm".to_string(),
  5178. ];
  5179. assert_eq!(
  5180. parse_args(&args).expect("args should parse"),
  5181. CliAction::ResumeSession {
  5182. session_path: PathBuf::from("session.jsonl"),
  5183. commands: vec![
  5184. "/export notes.txt".to_string(),
  5185. "/clear --confirm".to_string(),
  5186. ],
  5187. }
  5188. );
  5189. }
  5190. #[test]
  5191. fn parses_resume_flag_with_absolute_export_path() {
  5192. let args = vec![
  5193. "--resume".to_string(),
  5194. "session.jsonl".to_string(),
  5195. "/export".to_string(),
  5196. "/tmp/notes.txt".to_string(),
  5197. "/status".to_string(),
  5198. ];
  5199. assert_eq!(
  5200. parse_args(&args).expect("args should parse"),
  5201. CliAction::ResumeSession {
  5202. session_path: PathBuf::from("session.jsonl"),
  5203. commands: vec!["/export /tmp/notes.txt".to_string(), "/status".to_string()],
  5204. }
  5205. );
  5206. }
  5207. #[test]
  5208. fn filtered_tool_specs_respect_allowlist() {
  5209. let allowed = ["read_file", "grep_search"]
  5210. .into_iter()
  5211. .map(str::to_string)
  5212. .collect();
  5213. let filtered = filter_tool_specs(&GlobalToolRegistry::builtin(), Some(&allowed));
  5214. let names = filtered
  5215. .into_iter()
  5216. .map(|spec| spec.name)
  5217. .collect::<Vec<_>>();
  5218. assert_eq!(names, vec!["read_file", "grep_search"]);
  5219. }
  5220. #[test]
  5221. fn filtered_tool_specs_include_plugin_tools() {
  5222. let filtered = filter_tool_specs(&registry_with_plugin_tool(), None);
  5223. let names = filtered
  5224. .into_iter()
  5225. .map(|definition| definition.name)
  5226. .collect::<Vec<_>>();
  5227. assert!(names.contains(&"bash".to_string()));
  5228. assert!(names.contains(&"plugin_echo".to_string()));
  5229. }
  5230. #[test]
  5231. fn permission_policy_uses_plugin_tool_permissions() {
  5232. let feature_config = runtime::RuntimeFeatureConfig::default();
  5233. let policy = permission_policy(
  5234. PermissionMode::ReadOnly,
  5235. &feature_config,
  5236. &registry_with_plugin_tool(),
  5237. )
  5238. .expect("permission policy should build");
  5239. let required = policy.required_mode_for("plugin_echo");
  5240. assert_eq!(required, PermissionMode::WorkspaceWrite);
  5241. }
  5242. #[test]
  5243. fn shared_help_uses_resume_annotation_copy() {
  5244. let help = commands::render_slash_command_help();
  5245. assert!(help.contains("Slash commands"));
  5246. assert!(help.contains("works with --resume SESSION.jsonl"));
  5247. }
  5248. #[test]
  5249. fn repl_help_includes_shared_commands_and_exit() {
  5250. let help = render_repl_help();
  5251. assert!(help.contains("REPL"));
  5252. assert!(help.contains("/help"));
  5253. assert!(help.contains("Complete commands, modes, and recent sessions"));
  5254. assert!(help.contains("/status"));
  5255. assert!(help.contains("/sandbox"));
  5256. assert!(help.contains("/model [model]"));
  5257. assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
  5258. assert!(help.contains("/clear [--confirm]"));
  5259. assert!(help.contains("/cost"));
  5260. assert!(help.contains("/resume <session-path>"));
  5261. assert!(help.contains("/config [env|hooks|model|plugins]"));
  5262. assert!(help.contains("/mcp [list|show <server>|help]"));
  5263. assert!(help.contains("/memory"));
  5264. assert!(help.contains("/init"));
  5265. assert!(help.contains("/diff"));
  5266. assert!(help.contains("/version"));
  5267. assert!(help.contains("/export [file]"));
  5268. assert!(help.contains("/session [list|switch <session-id>|fork [branch-name]]"));
  5269. assert!(help.contains(
  5270. "/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
  5271. ));
  5272. assert!(help.contains("aliases: /plugins, /marketplace"));
  5273. assert!(help.contains("/agents"));
  5274. assert!(help.contains("/skills"));
  5275. assert!(help.contains("/exit"));
  5276. assert!(help.contains("Auto-save .claw/sessions/<session-id>.jsonl"));
  5277. assert!(help.contains("Resume latest /resume latest"));
  5278. }
  5279. #[test]
  5280. fn completion_candidates_include_workflow_shortcuts_and_dynamic_sessions() {
  5281. let completions = slash_command_completion_candidates_with_sessions(
  5282. "sonnet",
  5283. Some("session-current"),
  5284. vec!["session-old".to_string()],
  5285. );
  5286. assert!(completions.contains(&"/model claude-sonnet-4-6".to_string()));
  5287. assert!(completions.contains(&"/permissions workspace-write".to_string()));
  5288. assert!(completions.contains(&"/session list".to_string()));
  5289. assert!(completions.contains(&"/session switch session-current".to_string()));
  5290. assert!(completions.contains(&"/resume session-old".to_string()));
  5291. assert!(completions.contains(&"/mcp list".to_string()));
  5292. assert!(completions.contains(&"/ultraplan ".to_string()));
  5293. }
  5294. #[test]
  5295. #[ignore = "requires ANTHROPIC_API_KEY"]
  5296. fn startup_banner_mentions_workflow_completions() {
  5297. let _guard = env_lock();
  5298. let root = temp_dir();
  5299. fs::create_dir_all(&root).expect("root dir");
  5300. let banner = with_current_dir(&root, || {
  5301. LiveCli::new(
  5302. "claude-sonnet-4-6".to_string(),
  5303. true,
  5304. None,
  5305. PermissionMode::DangerFullAccess,
  5306. )
  5307. .expect("cli should initialize")
  5308. .startup_banner()
  5309. });
  5310. assert!(banner.contains("Tab"));
  5311. assert!(banner.contains("workflow completions"));
  5312. fs::remove_dir_all(root).expect("cleanup temp dir");
  5313. }
  5314. #[test]
  5315. fn resume_supported_command_list_matches_expected_surface() {
  5316. let names = resume_supported_slash_commands()
  5317. .into_iter()
  5318. .map(|spec| spec.name)
  5319. .collect::<Vec<_>>();
  5320. assert_eq!(
  5321. names,
  5322. vec![
  5323. "help", "status", "sandbox", "compact", "clear", "cost", "config", "mcp", "memory",
  5324. "init", "diff", "version", "export", "agents", "skills",
  5325. ]
  5326. );
  5327. }
  5328. #[test]
  5329. fn resume_report_uses_sectioned_layout() {
  5330. let report = format_resume_report("session.jsonl", 14, 6);
  5331. assert!(report.contains("Session resumed"));
  5332. assert!(report.contains("Session file session.jsonl"));
  5333. assert!(report.contains("Messages 14"));
  5334. assert!(report.contains("Turns 6"));
  5335. }
  5336. #[test]
  5337. fn compact_report_uses_structured_output() {
  5338. let compacted = format_compact_report(8, 5, false);
  5339. assert!(compacted.contains("Compact"));
  5340. assert!(compacted.contains("Result compacted"));
  5341. assert!(compacted.contains("Messages removed 8"));
  5342. let skipped = format_compact_report(0, 3, true);
  5343. assert!(skipped.contains("Result skipped"));
  5344. }
  5345. #[test]
  5346. fn cost_report_uses_sectioned_layout() {
  5347. let report = format_cost_report(runtime::TokenUsage {
  5348. input_tokens: 20,
  5349. output_tokens: 8,
  5350. cache_creation_input_tokens: 3,
  5351. cache_read_input_tokens: 1,
  5352. });
  5353. assert!(report.contains("Cost"));
  5354. assert!(report.contains("Input tokens 20"));
  5355. assert!(report.contains("Output tokens 8"));
  5356. assert!(report.contains("Cache create 3"));
  5357. assert!(report.contains("Cache read 1"));
  5358. assert!(report.contains("Total tokens 32"));
  5359. }
  5360. #[test]
  5361. fn permissions_report_uses_sectioned_layout() {
  5362. let report = format_permissions_report("workspace-write");
  5363. assert!(report.contains("Permissions"));
  5364. assert!(report.contains("Active mode workspace-write"));
  5365. assert!(report.contains("Modes"));
  5366. assert!(report.contains("read-only ○ available Read/search tools only"));
  5367. assert!(report.contains("workspace-write ● current Edit files inside the workspace"));
  5368. assert!(report.contains("danger-full-access ○ available Unrestricted tool access"));
  5369. }
  5370. #[test]
  5371. fn permissions_switch_report_is_structured() {
  5372. let report = format_permissions_switch_report("read-only", "workspace-write");
  5373. assert!(report.contains("Permissions updated"));
  5374. assert!(report.contains("Result mode switched"));
  5375. assert!(report.contains("Previous mode read-only"));
  5376. assert!(report.contains("Active mode workspace-write"));
  5377. assert!(report.contains("Applies to subsequent tool calls"));
  5378. }
  5379. #[test]
  5380. fn init_help_mentions_direct_subcommand() {
  5381. let mut help = Vec::new();
  5382. print_help_to(&mut help).expect("help should render");
  5383. let help = String::from_utf8(help).expect("help should be utf8");
  5384. assert!(help.contains("claw help"));
  5385. assert!(help.contains("claw version"));
  5386. assert!(help.contains("claw status"));
  5387. assert!(help.contains("claw sandbox"));
  5388. assert!(help.contains("claw init"));
  5389. assert!(help.contains("claw agents"));
  5390. assert!(help.contains("claw mcp"));
  5391. assert!(help.contains("claw skills"));
  5392. assert!(help.contains("claw /skills"));
  5393. }
  5394. #[test]
  5395. fn model_report_uses_sectioned_layout() {
  5396. let report = format_model_report("claude-sonnet", 12, 4);
  5397. assert!(report.contains("Model"));
  5398. assert!(report.contains("Current model claude-sonnet"));
  5399. assert!(report.contains("Session messages 12"));
  5400. assert!(report.contains("Switch models with /model <name>"));
  5401. }
  5402. #[test]
  5403. fn model_switch_report_preserves_context_summary() {
  5404. let report = format_model_switch_report("claude-sonnet", "claude-opus", 9);
  5405. assert!(report.contains("Model updated"));
  5406. assert!(report.contains("Previous claude-sonnet"));
  5407. assert!(report.contains("Current claude-opus"));
  5408. assert!(report.contains("Preserved msgs 9"));
  5409. }
  5410. #[test]
  5411. fn status_line_reports_model_and_token_totals() {
  5412. let status = format_status_report(
  5413. "claude-sonnet",
  5414. StatusUsage {
  5415. message_count: 7,
  5416. turns: 3,
  5417. latest: runtime::TokenUsage {
  5418. input_tokens: 5,
  5419. output_tokens: 4,
  5420. cache_creation_input_tokens: 1,
  5421. cache_read_input_tokens: 0,
  5422. },
  5423. cumulative: runtime::TokenUsage {
  5424. input_tokens: 20,
  5425. output_tokens: 8,
  5426. cache_creation_input_tokens: 2,
  5427. cache_read_input_tokens: 1,
  5428. },
  5429. estimated_tokens: 128,
  5430. },
  5431. "workspace-write",
  5432. &super::StatusContext {
  5433. cwd: PathBuf::from("/tmp/project"),
  5434. session_path: Some(PathBuf::from("session.jsonl")),
  5435. loaded_config_files: 2,
  5436. discovered_config_files: 3,
  5437. memory_file_count: 4,
  5438. project_root: Some(PathBuf::from("/tmp")),
  5439. git_branch: Some("main".to_string()),
  5440. git_summary: GitWorkspaceSummary {
  5441. changed_files: 3,
  5442. staged_files: 1,
  5443. unstaged_files: 1,
  5444. untracked_files: 1,
  5445. conflicted_files: 0,
  5446. },
  5447. sandbox_status: runtime::SandboxStatus::default(),
  5448. },
  5449. );
  5450. assert!(status.contains("Status"));
  5451. assert!(status.contains("Model claude-sonnet"));
  5452. assert!(status.contains("Permission mode workspace-write"));
  5453. assert!(status.contains("Messages 7"));
  5454. assert!(status.contains("Latest total 10"));
  5455. assert!(status.contains("Cumulative total 31"));
  5456. assert!(status.contains("Cwd /tmp/project"));
  5457. assert!(status.contains("Project root /tmp"));
  5458. assert!(status.contains("Git branch main"));
  5459. assert!(
  5460. status.contains("Git state dirty · 3 files · 1 staged, 1 unstaged, 1 untracked")
  5461. );
  5462. assert!(status.contains("Changed files 3"));
  5463. assert!(status.contains("Staged 1"));
  5464. assert!(status.contains("Unstaged 1"));
  5465. assert!(status.contains("Untracked 1"));
  5466. assert!(status.contains("Session session.jsonl"));
  5467. assert!(status.contains("Config files loaded 2/3"));
  5468. assert!(status.contains("Memory files 4"));
  5469. assert!(status.contains("Suggested flow /status → /diff → /commit"));
  5470. }
  5471. #[test]
  5472. fn commit_reports_surface_workspace_context() {
  5473. let summary = GitWorkspaceSummary {
  5474. changed_files: 2,
  5475. staged_files: 1,
  5476. unstaged_files: 1,
  5477. untracked_files: 0,
  5478. conflicted_files: 0,
  5479. };
  5480. let preflight = format_commit_preflight_report(Some("feature/ux"), summary);
  5481. assert!(preflight.contains("Result ready"));
  5482. assert!(preflight.contains("Branch feature/ux"));
  5483. assert!(preflight.contains("Workspace dirty · 2 files · 1 staged, 1 unstaged"));
  5484. assert!(preflight
  5485. .contains("Action create a git commit from the current workspace changes"));
  5486. }
  5487. #[test]
  5488. fn commit_skipped_report_points_to_next_steps() {
  5489. let report = format_commit_skipped_report();
  5490. assert!(report.contains("Reason no workspace changes"));
  5491. assert!(report
  5492. .contains("Action create a git commit from the current workspace changes"));
  5493. assert!(report.contains("/status to inspect context"));
  5494. assert!(report.contains("/diff to inspect repo changes"));
  5495. }
  5496. #[test]
  5497. fn runtime_slash_reports_describe_command_behavior() {
  5498. let bughunter = format_bughunter_report(Some("runtime"));
  5499. assert!(bughunter.contains("Scope runtime"));
  5500. assert!(bughunter.contains("inspect the selected code for likely bugs"));
  5501. let ultraplan = format_ultraplan_report(Some("ship the release"));
  5502. assert!(ultraplan.contains("Task ship the release"));
  5503. assert!(ultraplan.contains("break work into a multi-step execution plan"));
  5504. let pr = format_pr_report("feature/ux", Some("ready for review"));
  5505. assert!(pr.contains("Branch feature/ux"));
  5506. assert!(pr.contains("draft or create a pull request"));
  5507. let issue = format_issue_report(Some("flaky test"));
  5508. assert!(issue.contains("Context flaky test"));
  5509. assert!(issue.contains("draft or create a GitHub issue"));
  5510. }
  5511. #[test]
  5512. fn no_arg_commands_reject_unexpected_arguments() {
  5513. assert!(validate_no_args("/commit", None).is_ok());
  5514. let error = validate_no_args("/commit", Some("now"))
  5515. .expect_err("unexpected arguments should fail")
  5516. .to_string();
  5517. assert!(error.contains("/commit does not accept arguments"));
  5518. assert!(error.contains("Received: now"));
  5519. }
  5520. #[test]
  5521. fn config_report_supports_section_views() {
  5522. let report = render_config_report(Some("env")).expect("config report should render");
  5523. assert!(report.contains("Merged section: env"));
  5524. let plugins_report =
  5525. render_config_report(Some("plugins")).expect("plugins config report should render");
  5526. assert!(plugins_report.contains("Merged section: plugins"));
  5527. }
  5528. #[test]
  5529. fn memory_report_uses_sectioned_layout() {
  5530. let report = render_memory_report().expect("memory report should render");
  5531. assert!(report.contains("Memory"));
  5532. assert!(report.contains("Working directory"));
  5533. assert!(report.contains("Instruction files"));
  5534. assert!(report.contains("Discovered files"));
  5535. }
  5536. #[test]
  5537. fn config_report_uses_sectioned_layout() {
  5538. let report = render_config_report(None).expect("config report should render");
  5539. assert!(report.contains("Config"));
  5540. assert!(report.contains("Discovered files"));
  5541. assert!(report.contains("Merged JSON"));
  5542. }
  5543. #[test]
  5544. fn parses_git_status_metadata() {
  5545. let _guard = env_lock();
  5546. let temp_root = temp_dir();
  5547. fs::create_dir_all(&temp_root).expect("root dir");
  5548. let (project_root, branch) = parse_git_status_metadata_for(
  5549. &temp_root,
  5550. Some(
  5551. "## rcc/cli...origin/rcc/cli
  5552. M src/main.rs",
  5553. ),
  5554. );
  5555. assert_eq!(branch.as_deref(), Some("rcc/cli"));
  5556. assert!(project_root.is_none());
  5557. fs::remove_dir_all(temp_root).expect("cleanup temp dir");
  5558. }
  5559. #[test]
  5560. fn parses_detached_head_from_status_snapshot() {
  5561. let _guard = env_lock();
  5562. assert_eq!(
  5563. parse_git_status_branch(Some(
  5564. "## HEAD (no branch)
  5565. M src/main.rs"
  5566. )),
  5567. Some("detached HEAD".to_string())
  5568. );
  5569. }
  5570. #[test]
  5571. fn parses_git_workspace_summary_counts() {
  5572. let summary = parse_git_workspace_summary(Some(
  5573. "## feature/ux
  5574. M src/main.rs
  5575. M README.md
  5576. ?? notes.md
  5577. UU conflicted.rs",
  5578. ));
  5579. assert_eq!(
  5580. summary,
  5581. GitWorkspaceSummary {
  5582. changed_files: 4,
  5583. staged_files: 2,
  5584. unstaged_files: 2,
  5585. untracked_files: 1,
  5586. conflicted_files: 1,
  5587. }
  5588. );
  5589. assert_eq!(
  5590. summary.headline(),
  5591. "dirty · 4 files · 2 staged, 2 unstaged, 1 untracked, 1 conflicted"
  5592. );
  5593. }
  5594. #[test]
  5595. fn render_diff_report_shows_clean_tree_for_committed_repo() {
  5596. let _guard = env_lock();
  5597. let root = temp_dir();
  5598. fs::create_dir_all(&root).expect("root dir");
  5599. git(&["init", "--quiet"], &root);
  5600. git(&["config", "user.email", "tests@example.com"], &root);
  5601. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  5602. fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
  5603. git(&["add", "tracked.txt"], &root);
  5604. git(&["commit", "-m", "init", "--quiet"], &root);
  5605. let report = with_current_dir(&root, || {
  5606. render_diff_report().expect("diff report should render")
  5607. });
  5608. assert!(report.contains("clean working tree"));
  5609. fs::remove_dir_all(root).expect("cleanup temp dir");
  5610. }
  5611. #[test]
  5612. fn render_diff_report_includes_staged_and_unstaged_sections() {
  5613. let _guard = env_lock();
  5614. let root = temp_dir();
  5615. fs::create_dir_all(&root).expect("root dir");
  5616. git(&["init", "--quiet"], &root);
  5617. git(&["config", "user.email", "tests@example.com"], &root);
  5618. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  5619. fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
  5620. git(&["add", "tracked.txt"], &root);
  5621. git(&["commit", "-m", "init", "--quiet"], &root);
  5622. fs::write(root.join("tracked.txt"), "hello\nstaged\n").expect("update file");
  5623. git(&["add", "tracked.txt"], &root);
  5624. fs::write(root.join("tracked.txt"), "hello\nstaged\nunstaged\n")
  5625. .expect("update file twice");
  5626. let report = with_current_dir(&root, || {
  5627. render_diff_report().expect("diff report should render")
  5628. });
  5629. assert!(report.contains("Staged changes:"));
  5630. assert!(report.contains("Unstaged changes:"));
  5631. assert!(report.contains("tracked.txt"));
  5632. fs::remove_dir_all(root).expect("cleanup temp dir");
  5633. }
  5634. #[test]
  5635. fn render_diff_report_omits_ignored_files() {
  5636. let _guard = env_lock();
  5637. let root = temp_dir();
  5638. fs::create_dir_all(&root).expect("root dir");
  5639. git(&["init", "--quiet"], &root);
  5640. git(&["config", "user.email", "tests@example.com"], &root);
  5641. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  5642. fs::write(root.join(".gitignore"), ".omx/\nignored.txt\n").expect("write gitignore");
  5643. fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
  5644. git(&["add", ".gitignore", "tracked.txt"], &root);
  5645. git(&["commit", "-m", "init", "--quiet"], &root);
  5646. fs::create_dir_all(root.join(".omx")).expect("write omx dir");
  5647. fs::write(root.join(".omx").join("state.json"), "{}").expect("write ignored omx");
  5648. fs::write(root.join("ignored.txt"), "secret\n").expect("write ignored file");
  5649. fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("write tracked change");
  5650. let report = with_current_dir(&root, || {
  5651. render_diff_report().expect("diff report should render")
  5652. });
  5653. assert!(report.contains("tracked.txt"));
  5654. assert!(!report.contains("+++ b/ignored.txt"));
  5655. assert!(!report.contains("+++ b/.omx/state.json"));
  5656. fs::remove_dir_all(root).expect("cleanup temp dir");
  5657. }
  5658. #[test]
  5659. fn resume_diff_command_renders_report_for_saved_session() {
  5660. let _guard = env_lock();
  5661. let root = temp_dir();
  5662. fs::create_dir_all(&root).expect("root dir");
  5663. git(&["init", "--quiet"], &root);
  5664. git(&["config", "user.email", "tests@example.com"], &root);
  5665. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  5666. fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
  5667. git(&["add", "tracked.txt"], &root);
  5668. git(&["commit", "-m", "init", "--quiet"], &root);
  5669. fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("modify tracked");
  5670. let session_path = root.join("session.json");
  5671. Session::new()
  5672. .save_to_path(&session_path)
  5673. .expect("session should save");
  5674. let session = Session::load_from_path(&session_path).expect("session should load");
  5675. let outcome = with_current_dir(&root, || {
  5676. run_resume_command(&session_path, &session, &SlashCommand::Diff)
  5677. .expect("resume diff should work")
  5678. });
  5679. let message = outcome.message.expect("diff message should exist");
  5680. assert!(message.contains("Unstaged changes:"));
  5681. assert!(message.contains("tracked.txt"));
  5682. fs::remove_dir_all(root).expect("cleanup temp dir");
  5683. }
  5684. #[test]
  5685. fn status_context_reads_real_workspace_metadata() {
  5686. let context = status_context(None).expect("status context should load");
  5687. assert!(context.cwd.is_absolute());
  5688. assert!(context.discovered_config_files >= context.loaded_config_files);
  5689. assert!(context.loaded_config_files <= context.discovered_config_files);
  5690. }
  5691. #[test]
  5692. fn normalizes_supported_permission_modes() {
  5693. assert_eq!(normalize_permission_mode("read-only"), Some("read-only"));
  5694. assert_eq!(
  5695. normalize_permission_mode("workspace-write"),
  5696. Some("workspace-write")
  5697. );
  5698. assert_eq!(
  5699. normalize_permission_mode("danger-full-access"),
  5700. Some("danger-full-access")
  5701. );
  5702. assert_eq!(normalize_permission_mode("unknown"), None);
  5703. }
  5704. #[test]
  5705. fn clear_command_requires_explicit_confirmation_flag() {
  5706. assert_eq!(
  5707. SlashCommand::parse("/clear"),
  5708. Ok(Some(SlashCommand::Clear { confirm: false }))
  5709. );
  5710. assert_eq!(
  5711. SlashCommand::parse("/clear --confirm"),
  5712. Ok(Some(SlashCommand::Clear { confirm: true }))
  5713. );
  5714. }
  5715. #[test]
  5716. fn parses_resume_and_config_slash_commands() {
  5717. assert_eq!(
  5718. SlashCommand::parse("/resume saved-session.jsonl"),
  5719. Ok(Some(SlashCommand::Resume {
  5720. session_path: Some("saved-session.jsonl".to_string())
  5721. }))
  5722. );
  5723. assert_eq!(
  5724. SlashCommand::parse("/clear --confirm"),
  5725. Ok(Some(SlashCommand::Clear { confirm: true }))
  5726. );
  5727. assert_eq!(
  5728. SlashCommand::parse("/config"),
  5729. Ok(Some(SlashCommand::Config { section: None }))
  5730. );
  5731. assert_eq!(
  5732. SlashCommand::parse("/config env"),
  5733. Ok(Some(SlashCommand::Config {
  5734. section: Some("env".to_string())
  5735. }))
  5736. );
  5737. assert_eq!(
  5738. SlashCommand::parse("/memory"),
  5739. Ok(Some(SlashCommand::Memory))
  5740. );
  5741. assert_eq!(SlashCommand::parse("/init"), Ok(Some(SlashCommand::Init)));
  5742. assert_eq!(
  5743. SlashCommand::parse("/session fork incident-review"),
  5744. Ok(Some(SlashCommand::Session {
  5745. action: Some("fork".to_string()),
  5746. target: Some("incident-review".to_string())
  5747. }))
  5748. );
  5749. }
  5750. #[test]
  5751. fn help_mentions_jsonl_resume_examples() {
  5752. let mut help = Vec::new();
  5753. print_help_to(&mut help).expect("help should render");
  5754. let help = String::from_utf8(help).expect("help should be utf8");
  5755. assert!(help.contains("claw --resume [SESSION.jsonl|session-id|latest]"));
  5756. assert!(help.contains("Use `latest` with --resume, /resume, or /session switch"));
  5757. assert!(help.contains("claw --resume latest"));
  5758. assert!(help.contains("claw --resume latest /status /diff /export notes.txt"));
  5759. }
  5760. #[test]
  5761. fn managed_sessions_default_to_jsonl_and_resolve_legacy_json() {
  5762. let _guard = cwd_lock().lock().expect("cwd lock");
  5763. let workspace = temp_workspace("session-resolution");
  5764. std::fs::create_dir_all(&workspace).expect("workspace should create");
  5765. let previous = std::env::current_dir().expect("cwd");
  5766. std::env::set_current_dir(&workspace).expect("switch cwd");
  5767. let handle = create_managed_session_handle("session-alpha").expect("jsonl handle");
  5768. assert!(handle.path.ends_with("session-alpha.jsonl"));
  5769. let legacy_path = workspace.join(".claw/sessions/legacy.json");
  5770. std::fs::create_dir_all(
  5771. legacy_path
  5772. .parent()
  5773. .expect("legacy path should have parent directory"),
  5774. )
  5775. .expect("session dir should exist");
  5776. Session::new()
  5777. .with_persistence_path(legacy_path.clone())
  5778. .save_to_path(&legacy_path)
  5779. .expect("legacy session should save");
  5780. let resolved = resolve_session_reference("legacy").expect("legacy session should resolve");
  5781. assert_eq!(
  5782. resolved
  5783. .path
  5784. .canonicalize()
  5785. .expect("resolved path should exist"),
  5786. legacy_path
  5787. .canonicalize()
  5788. .expect("legacy path should exist")
  5789. );
  5790. std::env::set_current_dir(previous).expect("restore cwd");
  5791. std::fs::remove_dir_all(workspace).expect("workspace should clean up");
  5792. }
  5793. #[test]
  5794. fn latest_session_alias_resolves_most_recent_managed_session() {
  5795. let _guard = cwd_lock().lock().expect("cwd lock");
  5796. let workspace = temp_workspace("latest-session-alias");
  5797. std::fs::create_dir_all(&workspace).expect("workspace should create");
  5798. let previous = std::env::current_dir().expect("cwd");
  5799. std::env::set_current_dir(&workspace).expect("switch cwd");
  5800. let older = create_managed_session_handle("session-older").expect("older handle");
  5801. Session::new()
  5802. .with_persistence_path(older.path.clone())
  5803. .save_to_path(&older.path)
  5804. .expect("older session should save");
  5805. std::thread::sleep(Duration::from_millis(20));
  5806. let newer = create_managed_session_handle("session-newer").expect("newer handle");
  5807. Session::new()
  5808. .with_persistence_path(newer.path.clone())
  5809. .save_to_path(&newer.path)
  5810. .expect("newer session should save");
  5811. let resolved = resolve_session_reference("latest").expect("latest session should resolve");
  5812. assert_eq!(
  5813. resolved
  5814. .path
  5815. .canonicalize()
  5816. .expect("resolved path should exist"),
  5817. newer.path.canonicalize().expect("newer path should exist")
  5818. );
  5819. std::env::set_current_dir(previous).expect("restore cwd");
  5820. std::fs::remove_dir_all(workspace).expect("workspace should clean up");
  5821. }
  5822. #[test]
  5823. fn unknown_slash_command_guidance_suggests_nearby_commands() {
  5824. let message = format_unknown_slash_command("stats");
  5825. assert!(message.contains("Unknown slash command: /stats"));
  5826. assert!(message.contains("/status"));
  5827. assert!(message.contains("/help"));
  5828. }
  5829. #[test]
  5830. fn resume_usage_mentions_latest_shortcut() {
  5831. let usage = render_resume_usage();
  5832. assert!(usage.contains("/resume <session-path|session-id|latest>"));
  5833. assert!(usage.contains(".claw/sessions/<session-id>.jsonl"));
  5834. assert!(usage.contains("/session list"));
  5835. }
  5836. fn cwd_lock() -> &'static Mutex<()> {
  5837. static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
  5838. LOCK.get_or_init(|| Mutex::new(()))
  5839. }
  5840. fn temp_workspace(label: &str) -> PathBuf {
  5841. let nanos = std::time::SystemTime::now()
  5842. .duration_since(std::time::UNIX_EPOCH)
  5843. .expect("system time should be after epoch")
  5844. .as_nanos();
  5845. std::env::temp_dir().join(format!("claw-cli-{label}-{nanos}"))
  5846. }
  5847. #[test]
  5848. fn init_template_mentions_detected_rust_workspace() {
  5849. let rendered = crate::init::render_init_claude_md(std::path::Path::new("."));
  5850. assert!(rendered.contains("# CLAUDE.md"));
  5851. assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
  5852. }
  5853. #[test]
  5854. fn converts_tool_roundtrip_messages() {
  5855. let messages = vec![
  5856. ConversationMessage::user_text("hello"),
  5857. ConversationMessage::assistant(vec![ContentBlock::ToolUse {
  5858. id: "tool-1".to_string(),
  5859. name: "bash".to_string(),
  5860. input: "{\"command\":\"pwd\"}".to_string(),
  5861. }]),
  5862. ConversationMessage {
  5863. role: MessageRole::Tool,
  5864. blocks: vec![ContentBlock::ToolResult {
  5865. tool_use_id: "tool-1".to_string(),
  5866. tool_name: "bash".to_string(),
  5867. output: "ok".to_string(),
  5868. is_error: false,
  5869. }],
  5870. usage: None,
  5871. },
  5872. ];
  5873. let converted = super::convert_messages(&messages);
  5874. assert_eq!(converted.len(), 3);
  5875. assert_eq!(converted[1].role, "assistant");
  5876. assert_eq!(converted[2].role, "user");
  5877. }
  5878. #[test]
  5879. fn repl_help_mentions_history_completion_and_multiline() {
  5880. let help = render_repl_help();
  5881. assert!(help.contains("Up/Down"));
  5882. assert!(help.contains("Tab"));
  5883. assert!(help.contains("Shift+Enter/Ctrl+J"));
  5884. }
  5885. #[test]
  5886. fn tool_rendering_helpers_compact_output() {
  5887. let start = format_tool_call_start("read_file", r#"{"path":"src/main.rs"}"#);
  5888. assert!(start.contains("read_file"));
  5889. assert!(start.contains("src/main.rs"));
  5890. let done = format_tool_result(
  5891. "read_file",
  5892. r#"{"file":{"filePath":"src/main.rs","content":"hello","numLines":1,"startLine":1,"totalLines":1}}"#,
  5893. false,
  5894. );
  5895. assert!(done.contains("📄 Read src/main.rs"));
  5896. assert!(done.contains("hello"));
  5897. }
  5898. #[test]
  5899. fn tool_rendering_truncates_large_read_output_for_display_only() {
  5900. let content = (0..200)
  5901. .map(|index| format!("line {index:03}"))
  5902. .collect::<Vec<_>>()
  5903. .join("\n");
  5904. let output = json!({
  5905. "file": {
  5906. "filePath": "src/main.rs",
  5907. "content": content,
  5908. "numLines": 200,
  5909. "startLine": 1,
  5910. "totalLines": 200
  5911. }
  5912. })
  5913. .to_string();
  5914. let rendered = format_tool_result("read_file", &output, false);
  5915. assert!(rendered.contains("line 000"));
  5916. assert!(rendered.contains("line 079"));
  5917. assert!(!rendered.contains("line 199"));
  5918. assert!(rendered.contains("full result preserved in session"));
  5919. assert!(output.contains("line 199"));
  5920. }
  5921. #[test]
  5922. fn tool_rendering_truncates_large_bash_output_for_display_only() {
  5923. let stdout = (0..120)
  5924. .map(|index| format!("stdout {index:03}"))
  5925. .collect::<Vec<_>>()
  5926. .join("\n");
  5927. let output = json!({
  5928. "stdout": stdout,
  5929. "stderr": "",
  5930. "returnCodeInterpretation": "completed successfully"
  5931. })
  5932. .to_string();
  5933. let rendered = format_tool_result("bash", &output, false);
  5934. assert!(rendered.contains("stdout 000"));
  5935. assert!(rendered.contains("stdout 059"));
  5936. assert!(!rendered.contains("stdout 119"));
  5937. assert!(rendered.contains("full result preserved in session"));
  5938. assert!(output.contains("stdout 119"));
  5939. }
  5940. #[test]
  5941. fn tool_rendering_truncates_generic_long_output_for_display_only() {
  5942. let items = (0..120)
  5943. .map(|index| format!("payload {index:03}"))
  5944. .collect::<Vec<_>>();
  5945. let output = json!({
  5946. "summary": "plugin payload",
  5947. "items": items,
  5948. })
  5949. .to_string();
  5950. let rendered = format_tool_result("plugin_echo", &output, false);
  5951. assert!(rendered.contains("plugin_echo"));
  5952. assert!(rendered.contains("payload 000"));
  5953. assert!(rendered.contains("payload 040"));
  5954. assert!(!rendered.contains("payload 080"));
  5955. assert!(!rendered.contains("payload 119"));
  5956. assert!(rendered.contains("full result preserved in session"));
  5957. assert!(output.contains("payload 119"));
  5958. }
  5959. #[test]
  5960. fn tool_rendering_truncates_raw_generic_output_for_display_only() {
  5961. let output = (0..120)
  5962. .map(|index| format!("raw {index:03}"))
  5963. .collect::<Vec<_>>()
  5964. .join("\n");
  5965. let rendered = format_tool_result("plugin_echo", &output, false);
  5966. assert!(rendered.contains("plugin_echo"));
  5967. assert!(rendered.contains("raw 000"));
  5968. assert!(rendered.contains("raw 059"));
  5969. assert!(!rendered.contains("raw 119"));
  5970. assert!(rendered.contains("full result preserved in session"));
  5971. assert!(output.contains("raw 119"));
  5972. }
  5973. #[test]
  5974. fn ultraplan_progress_lines_include_phase_step_and_elapsed_status() {
  5975. let snapshot = InternalPromptProgressState {
  5976. command_label: "Ultraplan",
  5977. task_label: "ship plugin progress".to_string(),
  5978. step: 3,
  5979. phase: "running read_file".to_string(),
  5980. detail: Some("reading rust/crates/rusty-claude-cli/src/main.rs".to_string()),
  5981. saw_final_text: false,
  5982. };
  5983. let started = format_internal_prompt_progress_line(
  5984. InternalPromptProgressEvent::Started,
  5985. &snapshot,
  5986. Duration::from_secs(0),
  5987. None,
  5988. );
  5989. let heartbeat = format_internal_prompt_progress_line(
  5990. InternalPromptProgressEvent::Heartbeat,
  5991. &snapshot,
  5992. Duration::from_secs(9),
  5993. None,
  5994. );
  5995. let completed = format_internal_prompt_progress_line(
  5996. InternalPromptProgressEvent::Complete,
  5997. &snapshot,
  5998. Duration::from_secs(12),
  5999. None,
  6000. );
  6001. let failed = format_internal_prompt_progress_line(
  6002. InternalPromptProgressEvent::Failed,
  6003. &snapshot,
  6004. Duration::from_secs(12),
  6005. Some("network timeout"),
  6006. );
  6007. assert!(started.contains("planning started"));
  6008. assert!(started.contains("current step 3"));
  6009. assert!(heartbeat.contains("heartbeat"));
  6010. assert!(heartbeat.contains("9s elapsed"));
  6011. assert!(heartbeat.contains("phase running read_file"));
  6012. assert!(completed.contains("completed"));
  6013. assert!(completed.contains("3 steps total"));
  6014. assert!(failed.contains("failed"));
  6015. assert!(failed.contains("network timeout"));
  6016. }
  6017. #[test]
  6018. fn describe_tool_progress_summarizes_known_tools() {
  6019. assert_eq!(
  6020. describe_tool_progress("read_file", r#"{"path":"src/main.rs"}"#),
  6021. "reading src/main.rs"
  6022. );
  6023. assert!(
  6024. describe_tool_progress("bash", r#"{"command":"cargo test -p rusty-claude-cli"}"#)
  6025. .contains("cargo test -p rusty-claude-cli")
  6026. );
  6027. assert_eq!(
  6028. describe_tool_progress("grep_search", r#"{"pattern":"ultraplan","path":"rust"}"#),
  6029. "grep `ultraplan` in rust"
  6030. );
  6031. }
  6032. #[test]
  6033. fn push_output_block_renders_markdown_text() {
  6034. let mut out = Vec::new();
  6035. let mut events = Vec::new();
  6036. let mut pending_tool = None;
  6037. push_output_block(
  6038. OutputContentBlock::Text {
  6039. text: "# Heading".to_string(),
  6040. },
  6041. &mut out,
  6042. &mut events,
  6043. &mut pending_tool,
  6044. false,
  6045. )
  6046. .expect("text block should render");
  6047. let rendered = String::from_utf8(out).expect("utf8");
  6048. assert!(rendered.contains("Heading"));
  6049. assert!(rendered.contains('\u{1b}'));
  6050. }
  6051. #[test]
  6052. fn push_output_block_skips_empty_object_prefix_for_tool_streams() {
  6053. let mut out = Vec::new();
  6054. let mut events = Vec::new();
  6055. let mut pending_tool = None;
  6056. push_output_block(
  6057. OutputContentBlock::ToolUse {
  6058. id: "tool-1".to_string(),
  6059. name: "read_file".to_string(),
  6060. input: json!({}),
  6061. },
  6062. &mut out,
  6063. &mut events,
  6064. &mut pending_tool,
  6065. true,
  6066. )
  6067. .expect("tool block should accumulate");
  6068. assert!(events.is_empty());
  6069. assert_eq!(
  6070. pending_tool,
  6071. Some(("tool-1".to_string(), "read_file".to_string(), String::new(),))
  6072. );
  6073. }
  6074. #[test]
  6075. fn response_to_events_preserves_empty_object_json_input_outside_streaming() {
  6076. let mut out = Vec::new();
  6077. let events = response_to_events(
  6078. MessageResponse {
  6079. id: "msg-1".to_string(),
  6080. kind: "message".to_string(),
  6081. model: "claude-opus-4-6".to_string(),
  6082. role: "assistant".to_string(),
  6083. content: vec![OutputContentBlock::ToolUse {
  6084. id: "tool-1".to_string(),
  6085. name: "read_file".to_string(),
  6086. input: json!({}),
  6087. }],
  6088. stop_reason: Some("tool_use".to_string()),
  6089. stop_sequence: None,
  6090. usage: Usage {
  6091. input_tokens: 1,
  6092. output_tokens: 1,
  6093. cache_creation_input_tokens: 0,
  6094. cache_read_input_tokens: 0,
  6095. },
  6096. request_id: None,
  6097. },
  6098. &mut out,
  6099. )
  6100. .expect("response conversion should succeed");
  6101. assert!(matches!(
  6102. &events[0],
  6103. AssistantEvent::ToolUse { name, input, .. }
  6104. if name == "read_file" && input == "{}"
  6105. ));
  6106. }
  6107. #[test]
  6108. fn response_to_events_preserves_non_empty_json_input_outside_streaming() {
  6109. let mut out = Vec::new();
  6110. let events = response_to_events(
  6111. MessageResponse {
  6112. id: "msg-2".to_string(),
  6113. kind: "message".to_string(),
  6114. model: "claude-opus-4-6".to_string(),
  6115. role: "assistant".to_string(),
  6116. content: vec![OutputContentBlock::ToolUse {
  6117. id: "tool-2".to_string(),
  6118. name: "read_file".to_string(),
  6119. input: json!({ "path": "rust/Cargo.toml" }),
  6120. }],
  6121. stop_reason: Some("tool_use".to_string()),
  6122. stop_sequence: None,
  6123. usage: Usage {
  6124. input_tokens: 1,
  6125. output_tokens: 1,
  6126. cache_creation_input_tokens: 0,
  6127. cache_read_input_tokens: 0,
  6128. },
  6129. request_id: None,
  6130. },
  6131. &mut out,
  6132. )
  6133. .expect("response conversion should succeed");
  6134. assert!(matches!(
  6135. &events[0],
  6136. AssistantEvent::ToolUse { name, input, .. }
  6137. if name == "read_file" && input == "{\"path\":\"rust/Cargo.toml\"}"
  6138. ));
  6139. }
  6140. #[test]
  6141. fn response_to_events_ignores_thinking_blocks() {
  6142. let mut out = Vec::new();
  6143. let events = response_to_events(
  6144. MessageResponse {
  6145. id: "msg-3".to_string(),
  6146. kind: "message".to_string(),
  6147. model: "claude-opus-4-6".to_string(),
  6148. role: "assistant".to_string(),
  6149. content: vec![
  6150. OutputContentBlock::Thinking {
  6151. thinking: "step 1".to_string(),
  6152. signature: Some("sig_123".to_string()),
  6153. },
  6154. OutputContentBlock::Text {
  6155. text: "Final answer".to_string(),
  6156. },
  6157. ],
  6158. stop_reason: Some("end_turn".to_string()),
  6159. stop_sequence: None,
  6160. usage: Usage {
  6161. input_tokens: 1,
  6162. output_tokens: 1,
  6163. cache_creation_input_tokens: 0,
  6164. cache_read_input_tokens: 0,
  6165. },
  6166. request_id: None,
  6167. },
  6168. &mut out,
  6169. )
  6170. .expect("response conversion should succeed");
  6171. assert!(matches!(
  6172. &events[0],
  6173. AssistantEvent::TextDelta(text) if text == "Final answer"
  6174. ));
  6175. assert!(!String::from_utf8(out).expect("utf8").contains("step 1"));
  6176. }
  6177. #[test]
  6178. fn build_runtime_plugin_state_merges_plugin_hooks_into_runtime_features() {
  6179. let config_home = temp_dir();
  6180. let workspace = temp_dir();
  6181. let source_root = temp_dir();
  6182. fs::create_dir_all(&config_home).expect("config home");
  6183. fs::create_dir_all(&workspace).expect("workspace");
  6184. fs::create_dir_all(&source_root).expect("source root");
  6185. write_plugin_fixture(&source_root, "hook-runtime-demo", true, false);
  6186. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  6187. manager
  6188. .install(source_root.to_str().expect("utf8 source path"))
  6189. .expect("plugin install should succeed");
  6190. let loader = ConfigLoader::new(&workspace, &config_home);
  6191. let runtime_config = loader.load().expect("runtime config should load");
  6192. let state = build_runtime_plugin_state_with_loader(&workspace, &loader, &runtime_config)
  6193. .expect("plugin state should load");
  6194. let pre_hooks = state.feature_config.hooks().pre_tool_use();
  6195. assert_eq!(pre_hooks.len(), 1);
  6196. assert!(
  6197. pre_hooks[0].ends_with("hooks/pre.sh"),
  6198. "expected installed plugin hook path, got {pre_hooks:?}"
  6199. );
  6200. let _ = fs::remove_dir_all(config_home);
  6201. let _ = fs::remove_dir_all(workspace);
  6202. let _ = fs::remove_dir_all(source_root);
  6203. }
  6204. #[test]
  6205. fn build_runtime_runs_plugin_lifecycle_init_and_shutdown() {
  6206. let config_home = temp_dir();
  6207. let workspace = temp_dir();
  6208. let source_root = temp_dir();
  6209. fs::create_dir_all(&config_home).expect("config home");
  6210. fs::create_dir_all(&workspace).expect("workspace");
  6211. fs::create_dir_all(&source_root).expect("source root");
  6212. write_plugin_fixture(&source_root, "lifecycle-runtime-demo", false, true);
  6213. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  6214. let install = manager
  6215. .install(source_root.to_str().expect("utf8 source path"))
  6216. .expect("plugin install should succeed");
  6217. let log_path = install.install_path.join("lifecycle.log");
  6218. let loader = ConfigLoader::new(&workspace, &config_home);
  6219. let runtime_config = loader.load().expect("runtime config should load");
  6220. let runtime_plugin_state =
  6221. build_runtime_plugin_state_with_loader(&workspace, &loader, &runtime_config)
  6222. .expect("plugin state should load");
  6223. let mut runtime = build_runtime_with_plugin_state(
  6224. Session::new(),
  6225. "runtime-plugin-lifecycle",
  6226. DEFAULT_MODEL.to_string(),
  6227. vec!["test system prompt".to_string()],
  6228. true,
  6229. false,
  6230. None,
  6231. PermissionMode::DangerFullAccess,
  6232. None,
  6233. runtime_plugin_state,
  6234. )
  6235. .expect("runtime should build");
  6236. assert_eq!(
  6237. fs::read_to_string(&log_path).expect("init log should exist"),
  6238. "init\n"
  6239. );
  6240. runtime
  6241. .shutdown_plugins()
  6242. .expect("plugin shutdown should succeed");
  6243. assert_eq!(
  6244. fs::read_to_string(&log_path).expect("shutdown log should exist"),
  6245. "init\nshutdown\n"
  6246. );
  6247. let _ = fs::remove_dir_all(config_home);
  6248. let _ = fs::remove_dir_all(workspace);
  6249. let _ = fs::remove_dir_all(source_root);
  6250. }
  6251. }
  6252. #[cfg(test)]
  6253. mod sandbox_report_tests {
  6254. use super::{format_sandbox_report, HookAbortMonitor};
  6255. use runtime::HookAbortSignal;
  6256. use std::sync::mpsc;
  6257. use std::time::Duration;
  6258. #[test]
  6259. fn sandbox_report_renders_expected_fields() {
  6260. let report = format_sandbox_report(&runtime::SandboxStatus::default());
  6261. assert!(report.contains("Sandbox"));
  6262. assert!(report.contains("Enabled"));
  6263. assert!(report.contains("Filesystem mode"));
  6264. assert!(report.contains("Fallback reason"));
  6265. }
  6266. #[test]
  6267. fn hook_abort_monitor_stops_without_aborting() {
  6268. let abort_signal = HookAbortSignal::new();
  6269. let (ready_tx, ready_rx) = mpsc::channel();
  6270. let monitor = HookAbortMonitor::spawn_with_waiter(
  6271. abort_signal.clone(),
  6272. move |stop_rx, abort_signal| {
  6273. ready_tx.send(()).expect("ready signal");
  6274. let _ = stop_rx.recv();
  6275. assert!(!abort_signal.is_aborted());
  6276. },
  6277. );
  6278. ready_rx.recv().expect("waiter should be ready");
  6279. monitor.stop();
  6280. assert!(!abort_signal.is_aborted());
  6281. }
  6282. #[test]
  6283. fn hook_abort_monitor_propagates_interrupt() {
  6284. let abort_signal = HookAbortSignal::new();
  6285. let (done_tx, done_rx) = mpsc::channel();
  6286. let monitor = HookAbortMonitor::spawn_with_waiter(
  6287. abort_signal.clone(),
  6288. move |_stop_rx, abort_signal| {
  6289. abort_signal.abort();
  6290. done_tx.send(()).expect("done signal");
  6291. },
  6292. );
  6293. done_rx
  6294. .recv_timeout(Duration::from_secs(1))
  6295. .expect("interrupt should complete");
  6296. monitor.stop();
  6297. assert!(abort_signal.is_aborted());
  6298. }
  6299. }