main.rs 239 KB

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