main.rs 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090
  1. mod init;
  2. mod input;
  3. mod render;
  4. use std::collections::BTreeSet;
  5. use std::env;
  6. use std::fmt::Write as _;
  7. use std::fs;
  8. use std::io::{self, Read, Write};
  9. use std::net::TcpListener;
  10. use std::path::{Path, PathBuf};
  11. use std::process::Command;
  12. use std::sync::mpsc::{self, RecvTimeoutError};
  13. use std::sync::{Arc, Mutex};
  14. use std::thread;
  15. use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
  16. use api::{
  17. resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
  18. InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
  19. StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
  20. };
  21. use commands::{
  22. handle_agents_slash_command, handle_plugins_slash_command, handle_skills_slash_command,
  23. render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
  24. };
  25. use compat_harness::{extract_manifest, UpstreamPaths};
  26. use init::initialize_repo;
  27. use plugins::{PluginManager, PluginManagerConfig};
  28. use render::{MarkdownStreamState, Spinner, TerminalRenderer};
  29. use runtime::{
  30. clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
  31. parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials,
  32. ApiClient, ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource,
  33. ContentBlock, ConversationMessage, ConversationRuntime, MessageRole,
  34. OAuthAuthorizationRequest, OAuthConfig,
  35. OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
  36. Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
  37. };
  38. use serde_json::json;
  39. use tools::GlobalToolRegistry;
  40. const DEFAULT_MODEL: &str = "claude-opus-4-6";
  41. fn max_tokens_for_model(model: &str) -> u32 {
  42. if model.contains("opus") {
  43. 32_000
  44. } else {
  45. 64_000
  46. }
  47. }
  48. const DEFAULT_DATE: &str = "2026-03-31";
  49. const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
  50. const VERSION: &str = env!("CARGO_PKG_VERSION");
  51. const BUILD_TARGET: Option<&str> = option_env!("TARGET");
  52. const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
  53. const INTERNAL_PROGRESS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3);
  54. type AllowedToolSet = BTreeSet<String>;
  55. fn main() {
  56. if let Err(error) = run() {
  57. eprintln!(
  58. "error: {error}
  59. Run `claw --help` for usage."
  60. );
  61. std::process::exit(1);
  62. }
  63. }
  64. fn run() -> Result<(), Box<dyn std::error::Error>> {
  65. let args: Vec<String> = env::args().skip(1).collect();
  66. match parse_args(&args)? {
  67. CliAction::DumpManifests => dump_manifests(),
  68. CliAction::BootstrapPlan => print_bootstrap_plan(),
  69. CliAction::Agents { args } => LiveCli::print_agents(args.as_deref())?,
  70. CliAction::Skills { args } => LiveCli::print_skills(args.as_deref())?,
  71. CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
  72. CliAction::Version => print_version(),
  73. CliAction::ResumeSession {
  74. session_path,
  75. commands,
  76. } => resume_session(&session_path, &commands),
  77. CliAction::Prompt {
  78. prompt,
  79. model,
  80. output_format,
  81. allowed_tools,
  82. permission_mode,
  83. } => LiveCli::new(model, true, allowed_tools, permission_mode)?
  84. .run_turn_with_output(&prompt, output_format)?,
  85. CliAction::Login => run_login()?,
  86. CliAction::Logout => run_logout()?,
  87. CliAction::Init => run_init()?,
  88. CliAction::Repl {
  89. model,
  90. allowed_tools,
  91. permission_mode,
  92. } => run_repl(model, allowed_tools, permission_mode)?,
  93. CliAction::Help => print_help(),
  94. }
  95. Ok(())
  96. }
  97. #[derive(Debug, Clone, PartialEq, Eq)]
  98. enum CliAction {
  99. DumpManifests,
  100. BootstrapPlan,
  101. Agents {
  102. args: Option<String>,
  103. },
  104. Skills {
  105. args: Option<String>,
  106. },
  107. PrintSystemPrompt {
  108. cwd: PathBuf,
  109. date: String,
  110. },
  111. Version,
  112. ResumeSession {
  113. session_path: PathBuf,
  114. commands: Vec<String>,
  115. },
  116. Prompt {
  117. prompt: String,
  118. model: String,
  119. output_format: CliOutputFormat,
  120. allowed_tools: Option<AllowedToolSet>,
  121. permission_mode: PermissionMode,
  122. },
  123. Login,
  124. Logout,
  125. Init,
  126. Repl {
  127. model: String,
  128. allowed_tools: Option<AllowedToolSet>,
  129. permission_mode: PermissionMode,
  130. },
  131. // prompt-mode formatting is only supported for non-interactive runs
  132. Help,
  133. }
  134. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  135. enum CliOutputFormat {
  136. Text,
  137. Json,
  138. }
  139. impl CliOutputFormat {
  140. fn parse(value: &str) -> Result<Self, String> {
  141. match value {
  142. "text" => Ok(Self::Text),
  143. "json" => Ok(Self::Json),
  144. other => Err(format!(
  145. "unsupported value for --output-format: {other} (expected text or json)"
  146. )),
  147. }
  148. }
  149. }
  150. #[allow(clippy::too_many_lines)]
  151. fn parse_args(args: &[String]) -> Result<CliAction, String> {
  152. let mut model = DEFAULT_MODEL.to_string();
  153. let mut output_format = CliOutputFormat::Text;
  154. let mut permission_mode = default_permission_mode();
  155. let mut wants_version = false;
  156. let mut allowed_tool_values = Vec::new();
  157. let mut rest = Vec::new();
  158. let mut index = 0;
  159. while index < args.len() {
  160. match args[index].as_str() {
  161. "--version" | "-V" => {
  162. wants_version = true;
  163. index += 1;
  164. }
  165. "--model" => {
  166. let value = args
  167. .get(index + 1)
  168. .ok_or_else(|| "missing value for --model".to_string())?;
  169. model = resolve_model_alias(value).to_string();
  170. index += 2;
  171. }
  172. flag if flag.starts_with("--model=") => {
  173. model = resolve_model_alias(&flag[8..]).to_string();
  174. index += 1;
  175. }
  176. "--output-format" => {
  177. let value = args
  178. .get(index + 1)
  179. .ok_or_else(|| "missing value for --output-format".to_string())?;
  180. output_format = CliOutputFormat::parse(value)?;
  181. index += 2;
  182. }
  183. "--permission-mode" => {
  184. let value = args
  185. .get(index + 1)
  186. .ok_or_else(|| "missing value for --permission-mode".to_string())?;
  187. permission_mode = parse_permission_mode_arg(value)?;
  188. index += 2;
  189. }
  190. flag if flag.starts_with("--output-format=") => {
  191. output_format = CliOutputFormat::parse(&flag[16..])?;
  192. index += 1;
  193. }
  194. flag if flag.starts_with("--permission-mode=") => {
  195. permission_mode = parse_permission_mode_arg(&flag[18..])?;
  196. index += 1;
  197. }
  198. "--dangerously-skip-permissions" => {
  199. permission_mode = PermissionMode::DangerFullAccess;
  200. index += 1;
  201. }
  202. "-p" => {
  203. // Claw Code compat: -p "prompt" = one-shot prompt
  204. let prompt = args[index + 1..].join(" ");
  205. if prompt.trim().is_empty() {
  206. return Err("-p requires a prompt string".to_string());
  207. }
  208. return Ok(CliAction::Prompt {
  209. prompt,
  210. model: resolve_model_alias(&model).to_string(),
  211. output_format,
  212. allowed_tools: normalize_allowed_tools(&allowed_tool_values)?,
  213. permission_mode,
  214. });
  215. }
  216. "--print" => {
  217. // Claw Code compat: --print makes output non-interactive
  218. output_format = CliOutputFormat::Text;
  219. index += 1;
  220. }
  221. "--allowedTools" | "--allowed-tools" => {
  222. let value = args
  223. .get(index + 1)
  224. .ok_or_else(|| "missing value for --allowedTools".to_string())?;
  225. allowed_tool_values.push(value.clone());
  226. index += 2;
  227. }
  228. flag if flag.starts_with("--allowedTools=") => {
  229. allowed_tool_values.push(flag[15..].to_string());
  230. index += 1;
  231. }
  232. flag if flag.starts_with("--allowed-tools=") => {
  233. allowed_tool_values.push(flag[16..].to_string());
  234. index += 1;
  235. }
  236. other => {
  237. rest.push(other.to_string());
  238. index += 1;
  239. }
  240. }
  241. }
  242. if wants_version {
  243. return Ok(CliAction::Version);
  244. }
  245. let allowed_tools = normalize_allowed_tools(&allowed_tool_values)?;
  246. if rest.is_empty() {
  247. return Ok(CliAction::Repl {
  248. model,
  249. allowed_tools,
  250. permission_mode,
  251. });
  252. }
  253. if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
  254. return Ok(CliAction::Help);
  255. }
  256. if rest.first().map(String::as_str) == Some("--resume") {
  257. return parse_resume_args(&rest[1..]);
  258. }
  259. match rest[0].as_str() {
  260. "dump-manifests" => Ok(CliAction::DumpManifests),
  261. "bootstrap-plan" => Ok(CliAction::BootstrapPlan),
  262. "agents" => Ok(CliAction::Agents {
  263. args: join_optional_args(&rest[1..]),
  264. }),
  265. "skills" => Ok(CliAction::Skills {
  266. args: join_optional_args(&rest[1..]),
  267. }),
  268. "system-prompt" => parse_system_prompt_args(&rest[1..]),
  269. "login" => Ok(CliAction::Login),
  270. "logout" => Ok(CliAction::Logout),
  271. "init" => Ok(CliAction::Init),
  272. "prompt" => {
  273. let prompt = rest[1..].join(" ");
  274. if prompt.trim().is_empty() {
  275. return Err("prompt subcommand requires a prompt string".to_string());
  276. }
  277. Ok(CliAction::Prompt {
  278. prompt,
  279. model,
  280. output_format,
  281. allowed_tools,
  282. permission_mode,
  283. })
  284. }
  285. other if other.starts_with('/') => parse_direct_slash_cli_action(&rest),
  286. _other => Ok(CliAction::Prompt {
  287. prompt: rest.join(" "),
  288. model,
  289. output_format,
  290. allowed_tools,
  291. permission_mode,
  292. }),
  293. }
  294. }
  295. fn join_optional_args(args: &[String]) -> Option<String> {
  296. let joined = args.join(" ");
  297. let trimmed = joined.trim();
  298. (!trimmed.is_empty()).then(|| trimmed.to_string())
  299. }
  300. fn parse_direct_slash_cli_action(rest: &[String]) -> Result<CliAction, String> {
  301. let raw = rest.join(" ");
  302. match SlashCommand::parse(&raw) {
  303. Some(SlashCommand::Help) => Ok(CliAction::Help),
  304. Some(SlashCommand::Agents { args }) => Ok(CliAction::Agents { args }),
  305. Some(SlashCommand::Skills { args }) => Ok(CliAction::Skills { args }),
  306. Some(command) => Err(format!(
  307. "unsupported direct slash command outside the REPL: {command_name}",
  308. command_name = match command {
  309. SlashCommand::Unknown(name) => format!("/{name}"),
  310. _ => rest[0].clone(),
  311. }
  312. )),
  313. None => Err(format!("unknown subcommand: {}", rest[0])),
  314. }
  315. }
  316. fn resolve_model_alias(model: &str) -> &str {
  317. match model {
  318. "opus" => "claude-opus-4-6",
  319. "sonnet" => "claude-sonnet-4-6",
  320. "haiku" => "claude-haiku-4-5-20251213",
  321. _ => model,
  322. }
  323. }
  324. fn normalize_allowed_tools(values: &[String]) -> Result<Option<AllowedToolSet>, String> {
  325. current_tool_registry()?.normalize_allowed_tools(values)
  326. }
  327. fn current_tool_registry() -> Result<GlobalToolRegistry, String> {
  328. let cwd = env::current_dir().map_err(|error| error.to_string())?;
  329. let loader = ConfigLoader::default_for(&cwd);
  330. let runtime_config = loader.load().map_err(|error| error.to_string())?;
  331. let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  332. let plugin_tools = plugin_manager
  333. .aggregated_tools()
  334. .map_err(|error| error.to_string())?;
  335. GlobalToolRegistry::with_plugin_tools(plugin_tools)
  336. }
  337. fn parse_permission_mode_arg(value: &str) -> Result<PermissionMode, String> {
  338. normalize_permission_mode(value)
  339. .ok_or_else(|| {
  340. format!(
  341. "unsupported permission mode '{value}'. Use read-only, workspace-write, or danger-full-access."
  342. )
  343. })
  344. .map(permission_mode_from_label)
  345. }
  346. fn permission_mode_from_label(mode: &str) -> PermissionMode {
  347. match mode {
  348. "read-only" => PermissionMode::ReadOnly,
  349. "workspace-write" => PermissionMode::WorkspaceWrite,
  350. "danger-full-access" => PermissionMode::DangerFullAccess,
  351. other => panic!("unsupported permission mode label: {other}"),
  352. }
  353. }
  354. fn default_permission_mode() -> PermissionMode {
  355. env::var("RUSTY_CLAUDE_PERMISSION_MODE")
  356. .ok()
  357. .as_deref()
  358. .and_then(normalize_permission_mode)
  359. .map_or(PermissionMode::DangerFullAccess, permission_mode_from_label)
  360. }
  361. fn filter_tool_specs(
  362. tool_registry: &GlobalToolRegistry,
  363. allowed_tools: Option<&AllowedToolSet>,
  364. ) -> Vec<ToolDefinition> {
  365. tool_registry.definitions(allowed_tools)
  366. }
  367. fn parse_system_prompt_args(args: &[String]) -> Result<CliAction, String> {
  368. let mut cwd = env::current_dir().map_err(|error| error.to_string())?;
  369. let mut date = DEFAULT_DATE.to_string();
  370. let mut index = 0;
  371. while index < args.len() {
  372. match args[index].as_str() {
  373. "--cwd" => {
  374. let value = args
  375. .get(index + 1)
  376. .ok_or_else(|| "missing value for --cwd".to_string())?;
  377. cwd = PathBuf::from(value);
  378. index += 2;
  379. }
  380. "--date" => {
  381. let value = args
  382. .get(index + 1)
  383. .ok_or_else(|| "missing value for --date".to_string())?;
  384. date.clone_from(value);
  385. index += 2;
  386. }
  387. other => return Err(format!("unknown system-prompt option: {other}")),
  388. }
  389. }
  390. Ok(CliAction::PrintSystemPrompt { cwd, date })
  391. }
  392. fn parse_resume_args(args: &[String]) -> Result<CliAction, String> {
  393. let session_path = args
  394. .first()
  395. .ok_or_else(|| "missing session path for --resume".to_string())
  396. .map(PathBuf::from)?;
  397. let commands = args[1..].to_vec();
  398. if commands
  399. .iter()
  400. .any(|command| !command.trim_start().starts_with('/'))
  401. {
  402. return Err("--resume trailing arguments must be slash commands".to_string());
  403. }
  404. Ok(CliAction::ResumeSession {
  405. session_path,
  406. commands,
  407. })
  408. }
  409. fn dump_manifests() {
  410. let workspace_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
  411. let paths = UpstreamPaths::from_workspace_dir(&workspace_dir);
  412. match extract_manifest(&paths) {
  413. Ok(manifest) => {
  414. println!("commands: {}", manifest.commands.entries().len());
  415. println!("tools: {}", manifest.tools.entries().len());
  416. println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
  417. }
  418. Err(error) => {
  419. eprintln!("failed to extract manifests: {error}");
  420. std::process::exit(1);
  421. }
  422. }
  423. }
  424. fn print_bootstrap_plan() {
  425. for phase in runtime::BootstrapPlan::claude_code_default().phases() {
  426. println!("- {phase:?}");
  427. }
  428. }
  429. fn default_oauth_config() -> OAuthConfig {
  430. OAuthConfig {
  431. client_id: String::from("9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
  432. authorize_url: String::from("https://platform.claude.com/oauth/authorize"),
  433. token_url: String::from("https://platform.claude.com/v1/oauth/token"),
  434. callback_port: None,
  435. manual_redirect_url: None,
  436. scopes: vec![
  437. String::from("user:profile"),
  438. String::from("user:inference"),
  439. String::from("user:sessions:claude_code"),
  440. ],
  441. }
  442. }
  443. fn run_login() -> Result<(), Box<dyn std::error::Error>> {
  444. let cwd = env::current_dir()?;
  445. let config = ConfigLoader::default_for(&cwd).load()?;
  446. let default_oauth = default_oauth_config();
  447. let oauth = config.oauth().unwrap_or(&default_oauth);
  448. let callback_port = oauth.callback_port.unwrap_or(DEFAULT_OAUTH_CALLBACK_PORT);
  449. let redirect_uri = runtime::loopback_redirect_uri(callback_port);
  450. let pkce = generate_pkce_pair()?;
  451. let state = generate_state()?;
  452. let authorize_url =
  453. OAuthAuthorizationRequest::from_config(oauth, redirect_uri.clone(), state.clone(), &pkce)
  454. .build_url();
  455. println!("Starting Claude OAuth login...");
  456. println!("Listening for callback on {redirect_uri}");
  457. if let Err(error) = open_browser(&authorize_url) {
  458. eprintln!("warning: failed to open browser automatically: {error}");
  459. println!("Open this URL manually:\n{authorize_url}");
  460. }
  461. let callback = wait_for_oauth_callback(callback_port)?;
  462. if let Some(error) = callback.error {
  463. let description = callback
  464. .error_description
  465. .unwrap_or_else(|| "authorization failed".to_string());
  466. return Err(io::Error::other(format!("{error}: {description}")).into());
  467. }
  468. let code = callback.code.ok_or_else(|| {
  469. io::Error::new(io::ErrorKind::InvalidData, "callback did not include code")
  470. })?;
  471. let returned_state = callback.state.ok_or_else(|| {
  472. io::Error::new(io::ErrorKind::InvalidData, "callback did not include state")
  473. })?;
  474. if returned_state != state {
  475. return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
  476. }
  477. let client = AnthropicClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
  478. let exchange_request =
  479. OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
  480. let runtime = tokio::runtime::Runtime::new()?;
  481. let token_set = runtime.block_on(client.exchange_oauth_code(oauth, &exchange_request))?;
  482. save_oauth_credentials(&runtime::OAuthTokenSet {
  483. access_token: token_set.access_token,
  484. refresh_token: token_set.refresh_token,
  485. expires_at: token_set.expires_at,
  486. scopes: token_set.scopes,
  487. })?;
  488. println!("Claude OAuth login complete.");
  489. Ok(())
  490. }
  491. fn run_logout() -> Result<(), Box<dyn std::error::Error>> {
  492. clear_oauth_credentials()?;
  493. println!("Claude OAuth credentials cleared.");
  494. Ok(())
  495. }
  496. fn open_browser(url: &str) -> io::Result<()> {
  497. let commands = if cfg!(target_os = "macos") {
  498. vec![("open", vec![url])]
  499. } else if cfg!(target_os = "windows") {
  500. vec![("cmd", vec!["/C", "start", "", url])]
  501. } else {
  502. vec![("xdg-open", vec![url])]
  503. };
  504. for (program, args) in commands {
  505. match Command::new(program).args(args).spawn() {
  506. Ok(_) => return Ok(()),
  507. Err(error) if error.kind() == io::ErrorKind::NotFound => {}
  508. Err(error) => return Err(error),
  509. }
  510. }
  511. Err(io::Error::new(
  512. io::ErrorKind::NotFound,
  513. "no supported browser opener command found",
  514. ))
  515. }
  516. fn wait_for_oauth_callback(
  517. port: u16,
  518. ) -> Result<runtime::OAuthCallbackParams, Box<dyn std::error::Error>> {
  519. let listener = TcpListener::bind(("127.0.0.1", port))?;
  520. let (mut stream, _) = listener.accept()?;
  521. let mut buffer = [0_u8; 4096];
  522. let bytes_read = stream.read(&mut buffer)?;
  523. let request = String::from_utf8_lossy(&buffer[..bytes_read]);
  524. let request_line = request.lines().next().ok_or_else(|| {
  525. io::Error::new(io::ErrorKind::InvalidData, "missing callback request line")
  526. })?;
  527. let target = request_line.split_whitespace().nth(1).ok_or_else(|| {
  528. io::Error::new(
  529. io::ErrorKind::InvalidData,
  530. "missing callback request target",
  531. )
  532. })?;
  533. let callback = parse_oauth_callback_request_target(target)
  534. .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
  535. let body = if callback.error.is_some() {
  536. "Claude OAuth login failed. You can close this window."
  537. } else {
  538. "Claude OAuth login succeeded. You can close this window."
  539. };
  540. let response = format!(
  541. "HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
  542. body.len(),
  543. body
  544. );
  545. stream.write_all(response.as_bytes())?;
  546. Ok(callback)
  547. }
  548. fn print_system_prompt(cwd: PathBuf, date: String) {
  549. match load_system_prompt(cwd, date, env::consts::OS, "unknown") {
  550. Ok(sections) => println!("{}", sections.join("\n\n")),
  551. Err(error) => {
  552. eprintln!("failed to build system prompt: {error}");
  553. std::process::exit(1);
  554. }
  555. }
  556. }
  557. fn print_version() {
  558. println!("{}", render_version_report());
  559. }
  560. fn resume_session(session_path: &Path, commands: &[String]) {
  561. let session = match Session::load_from_path(session_path) {
  562. Ok(session) => session,
  563. Err(error) => {
  564. eprintln!("failed to restore session: {error}");
  565. std::process::exit(1);
  566. }
  567. };
  568. if commands.is_empty() {
  569. println!(
  570. "Restored session from {} ({} messages).",
  571. session_path.display(),
  572. session.messages.len()
  573. );
  574. return;
  575. }
  576. let mut session = session;
  577. for raw_command in commands {
  578. let Some(command) = SlashCommand::parse(raw_command) else {
  579. eprintln!("unsupported resumed command: {raw_command}");
  580. std::process::exit(2);
  581. };
  582. match run_resume_command(session_path, &session, &command) {
  583. Ok(ResumeCommandOutcome {
  584. session: next_session,
  585. message,
  586. }) => {
  587. session = next_session;
  588. if let Some(message) = message {
  589. println!("{message}");
  590. }
  591. }
  592. Err(error) => {
  593. eprintln!("{error}");
  594. std::process::exit(2);
  595. }
  596. }
  597. }
  598. }
  599. #[derive(Debug, Clone)]
  600. struct ResumeCommandOutcome {
  601. session: Session,
  602. message: Option<String>,
  603. }
  604. #[derive(Debug, Clone)]
  605. struct StatusContext {
  606. cwd: PathBuf,
  607. session_path: Option<PathBuf>,
  608. loaded_config_files: usize,
  609. discovered_config_files: usize,
  610. memory_file_count: usize,
  611. project_root: Option<PathBuf>,
  612. git_branch: Option<String>,
  613. sandbox_status: runtime::SandboxStatus,
  614. }
  615. #[derive(Debug, Clone, Copy)]
  616. struct StatusUsage {
  617. message_count: usize,
  618. turns: u32,
  619. latest: TokenUsage,
  620. cumulative: TokenUsage,
  621. estimated_tokens: usize,
  622. }
  623. fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
  624. format!(
  625. "Model
  626. Current model {model}
  627. Session messages {message_count}
  628. Session turns {turns}
  629. Usage
  630. Inspect current model with /model
  631. Switch models with /model <name>"
  632. )
  633. }
  634. fn format_model_switch_report(previous: &str, next: &str, message_count: usize) -> String {
  635. format!(
  636. "Model updated
  637. Previous {previous}
  638. Current {next}
  639. Preserved msgs {message_count}"
  640. )
  641. }
  642. fn format_permissions_report(mode: &str) -> String {
  643. let modes = [
  644. ("read-only", "Read/search tools only", mode == "read-only"),
  645. (
  646. "workspace-write",
  647. "Edit files inside the workspace",
  648. mode == "workspace-write",
  649. ),
  650. (
  651. "danger-full-access",
  652. "Unrestricted tool access",
  653. mode == "danger-full-access",
  654. ),
  655. ]
  656. .into_iter()
  657. .map(|(name, description, is_current)| {
  658. let marker = if is_current {
  659. "● current"
  660. } else {
  661. "○ available"
  662. };
  663. format!(" {name:<18} {marker:<11} {description}")
  664. })
  665. .collect::<Vec<_>>()
  666. .join(
  667. "
  668. ",
  669. );
  670. format!(
  671. "Permissions
  672. Active mode {mode}
  673. Mode status live session default
  674. Modes
  675. {modes}
  676. Usage
  677. Inspect current mode with /permissions
  678. Switch modes with /permissions <mode>"
  679. )
  680. }
  681. fn format_permissions_switch_report(previous: &str, next: &str) -> String {
  682. format!(
  683. "Permissions updated
  684. Result mode switched
  685. Previous mode {previous}
  686. Active mode {next}
  687. Applies to subsequent tool calls
  688. Usage /permissions to inspect current mode"
  689. )
  690. }
  691. fn format_cost_report(usage: TokenUsage) -> String {
  692. format!(
  693. "Cost
  694. Input tokens {}
  695. Output tokens {}
  696. Cache create {}
  697. Cache read {}
  698. Total tokens {}",
  699. usage.input_tokens,
  700. usage.output_tokens,
  701. usage.cache_creation_input_tokens,
  702. usage.cache_read_input_tokens,
  703. usage.total_tokens(),
  704. )
  705. }
  706. fn format_resume_report(session_path: &str, message_count: usize, turns: u32) -> String {
  707. format!(
  708. "Session resumed
  709. Session file {session_path}
  710. Messages {message_count}
  711. Turns {turns}"
  712. )
  713. }
  714. fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
  715. if skipped {
  716. format!(
  717. "Compact
  718. Result skipped
  719. Reason session below compaction threshold
  720. Messages kept {resulting_messages}"
  721. )
  722. } else {
  723. format!(
  724. "Compact
  725. Result compacted
  726. Messages removed {removed}
  727. Messages kept {resulting_messages}"
  728. )
  729. }
  730. }
  731. fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
  732. parse_git_status_metadata_for(
  733. &env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
  734. status,
  735. )
  736. }
  737. fn parse_git_status_branch(status: Option<&str>) -> Option<String> {
  738. let status = status?;
  739. let first_line = status.lines().next()?;
  740. let line = first_line.strip_prefix("## ")?;
  741. if line.starts_with("HEAD") {
  742. return Some("detached HEAD".to_string());
  743. }
  744. let branch = line.split(['.', ' ']).next().unwrap_or_default().trim();
  745. if branch.is_empty() {
  746. None
  747. } else {
  748. Some(branch.to_string())
  749. }
  750. }
  751. fn resolve_git_branch_for(cwd: &Path) -> Option<String> {
  752. let branch = run_git_capture_in(cwd, &["branch", "--show-current"])?;
  753. let branch = branch.trim();
  754. if !branch.is_empty() {
  755. return Some(branch.to_string());
  756. }
  757. let fallback = run_git_capture_in(cwd, &["rev-parse", "--abbrev-ref", "HEAD"])?;
  758. let fallback = fallback.trim();
  759. if fallback.is_empty() {
  760. None
  761. } else if fallback == "HEAD" {
  762. Some("detached HEAD".to_string())
  763. } else {
  764. Some(fallback.to_string())
  765. }
  766. }
  767. fn run_git_capture_in(cwd: &Path, args: &[&str]) -> Option<String> {
  768. let output = std::process::Command::new("git")
  769. .args(args)
  770. .current_dir(cwd)
  771. .output()
  772. .ok()?;
  773. if !output.status.success() {
  774. return None;
  775. }
  776. String::from_utf8(output.stdout).ok()
  777. }
  778. fn find_git_root_in(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
  779. let output = std::process::Command::new("git")
  780. .args(["rev-parse", "--show-toplevel"])
  781. .current_dir(cwd)
  782. .output()?;
  783. if !output.status.success() {
  784. return Err("not a git repository".into());
  785. }
  786. let path = String::from_utf8(output.stdout)?.trim().to_string();
  787. if path.is_empty() {
  788. return Err("empty git root".into());
  789. }
  790. Ok(PathBuf::from(path))
  791. }
  792. fn parse_git_status_metadata_for(
  793. cwd: &Path,
  794. status: Option<&str>,
  795. ) -> (Option<PathBuf>, Option<String>) {
  796. let branch = resolve_git_branch_for(cwd).or_else(|| parse_git_status_branch(status));
  797. let project_root = find_git_root_in(cwd).ok();
  798. (project_root, branch)
  799. }
  800. #[allow(clippy::too_many_lines)]
  801. fn run_resume_command(
  802. session_path: &Path,
  803. session: &Session,
  804. command: &SlashCommand,
  805. ) -> Result<ResumeCommandOutcome, Box<dyn std::error::Error>> {
  806. match command {
  807. SlashCommand::Help => Ok(ResumeCommandOutcome {
  808. session: session.clone(),
  809. message: Some(render_repl_help()),
  810. }),
  811. SlashCommand::Compact => {
  812. let result = runtime::compact_session(
  813. session,
  814. CompactionConfig {
  815. max_estimated_tokens: 0,
  816. ..CompactionConfig::default()
  817. },
  818. );
  819. let removed = result.removed_message_count;
  820. let kept = result.compacted_session.messages.len();
  821. let skipped = removed == 0;
  822. result.compacted_session.save_to_path(session_path)?;
  823. Ok(ResumeCommandOutcome {
  824. session: result.compacted_session,
  825. message: Some(format_compact_report(removed, kept, skipped)),
  826. })
  827. }
  828. SlashCommand::Clear { confirm } => {
  829. if !confirm {
  830. return Ok(ResumeCommandOutcome {
  831. session: session.clone(),
  832. message: Some(
  833. "clear: confirmation required; rerun with /clear --confirm".to_string(),
  834. ),
  835. });
  836. }
  837. let cleared = Session::new();
  838. cleared.save_to_path(session_path)?;
  839. Ok(ResumeCommandOutcome {
  840. session: cleared,
  841. message: Some(format!(
  842. "Cleared resumed session file {}.",
  843. session_path.display()
  844. )),
  845. })
  846. }
  847. SlashCommand::Status => {
  848. let tracker = UsageTracker::from_session(session);
  849. let usage = tracker.cumulative_usage();
  850. Ok(ResumeCommandOutcome {
  851. session: session.clone(),
  852. message: Some(format_status_report(
  853. "restored-session",
  854. StatusUsage {
  855. message_count: session.messages.len(),
  856. turns: tracker.turns(),
  857. latest: tracker.current_turn_usage(),
  858. cumulative: usage,
  859. estimated_tokens: 0,
  860. },
  861. default_permission_mode().as_str(),
  862. &status_context(Some(session_path))?,
  863. )),
  864. })
  865. }
  866. SlashCommand::Sandbox => {
  867. let cwd = env::current_dir()?;
  868. let loader = ConfigLoader::default_for(&cwd);
  869. let runtime_config = loader.load()?;
  870. Ok(ResumeCommandOutcome {
  871. session: session.clone(),
  872. message: Some(format_sandbox_report(&resolve_sandbox_status(
  873. runtime_config.sandbox(),
  874. &cwd,
  875. ))),
  876. })
  877. }
  878. SlashCommand::Cost => {
  879. let usage = UsageTracker::from_session(session).cumulative_usage();
  880. Ok(ResumeCommandOutcome {
  881. session: session.clone(),
  882. message: Some(format_cost_report(usage)),
  883. })
  884. }
  885. SlashCommand::Config { section } => Ok(ResumeCommandOutcome {
  886. session: session.clone(),
  887. message: Some(render_config_report(section.as_deref())?),
  888. }),
  889. SlashCommand::Memory => Ok(ResumeCommandOutcome {
  890. session: session.clone(),
  891. message: Some(render_memory_report()?),
  892. }),
  893. SlashCommand::Init => Ok(ResumeCommandOutcome {
  894. session: session.clone(),
  895. message: Some(init_claude_md()?),
  896. }),
  897. SlashCommand::Diff => Ok(ResumeCommandOutcome {
  898. session: session.clone(),
  899. message: Some(render_diff_report_for(
  900. session_path.parent().unwrap_or_else(|| Path::new(".")),
  901. )?),
  902. }),
  903. SlashCommand::Version => Ok(ResumeCommandOutcome {
  904. session: session.clone(),
  905. message: Some(render_version_report()),
  906. }),
  907. SlashCommand::Export { path } => {
  908. let export_path = resolve_export_path(path.as_deref(), session)?;
  909. fs::write(&export_path, render_export_text(session))?;
  910. Ok(ResumeCommandOutcome {
  911. session: session.clone(),
  912. message: Some(format!(
  913. "Export\n Result wrote transcript\n File {}\n Messages {}",
  914. export_path.display(),
  915. session.messages.len(),
  916. )),
  917. })
  918. }
  919. SlashCommand::Agents { args } => {
  920. let cwd = env::current_dir()?;
  921. Ok(ResumeCommandOutcome {
  922. session: session.clone(),
  923. message: Some(handle_agents_slash_command(args.as_deref(), &cwd)?),
  924. })
  925. }
  926. SlashCommand::Skills { args } => {
  927. let cwd = env::current_dir()?;
  928. Ok(ResumeCommandOutcome {
  929. session: session.clone(),
  930. message: Some(handle_skills_slash_command(args.as_deref(), &cwd)?),
  931. })
  932. }
  933. SlashCommand::Bughunter { .. }
  934. | SlashCommand::Commit
  935. | SlashCommand::Pr { .. }
  936. | SlashCommand::Issue { .. }
  937. | SlashCommand::Ultraplan { .. }
  938. | SlashCommand::Teleport { .. }
  939. | SlashCommand::DebugToolCall
  940. | SlashCommand::Resume { .. }
  941. | SlashCommand::Model { .. }
  942. | SlashCommand::Permissions { .. }
  943. | SlashCommand::Session { .. }
  944. | SlashCommand::Plugins { .. }
  945. | SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
  946. }
  947. }
  948. fn run_repl(
  949. model: String,
  950. allowed_tools: Option<AllowedToolSet>,
  951. permission_mode: PermissionMode,
  952. ) -> Result<(), Box<dyn std::error::Error>> {
  953. let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
  954. let mut editor = input::LineEditor::new("> ", slash_command_completion_candidates());
  955. println!("{}", cli.startup_banner());
  956. loop {
  957. match editor.read_line()? {
  958. input::ReadOutcome::Submit(input) => {
  959. let trimmed = input.trim().to_string();
  960. if trimmed.is_empty() {
  961. continue;
  962. }
  963. if matches!(trimmed.as_str(), "/exit" | "/quit") {
  964. cli.persist_session()?;
  965. break;
  966. }
  967. if let Some(command) = SlashCommand::parse(&trimmed) {
  968. if cli.handle_repl_command(command)? {
  969. cli.persist_session()?;
  970. }
  971. continue;
  972. }
  973. editor.push_history(input);
  974. cli.run_turn(&trimmed)?;
  975. }
  976. input::ReadOutcome::Cancel => {}
  977. input::ReadOutcome::Exit => {
  978. cli.persist_session()?;
  979. break;
  980. }
  981. }
  982. }
  983. Ok(())
  984. }
  985. #[derive(Debug, Clone)]
  986. struct SessionHandle {
  987. id: String,
  988. path: PathBuf,
  989. }
  990. #[derive(Debug, Clone)]
  991. struct ManagedSessionSummary {
  992. id: String,
  993. path: PathBuf,
  994. modified_epoch_secs: u64,
  995. message_count: usize,
  996. }
  997. struct LiveCli {
  998. model: String,
  999. allowed_tools: Option<AllowedToolSet>,
  1000. permission_mode: PermissionMode,
  1001. system_prompt: Vec<String>,
  1002. runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
  1003. session: SessionHandle,
  1004. }
  1005. impl LiveCli {
  1006. fn new(
  1007. model: String,
  1008. enable_tools: bool,
  1009. allowed_tools: Option<AllowedToolSet>,
  1010. permission_mode: PermissionMode,
  1011. ) -> Result<Self, Box<dyn std::error::Error>> {
  1012. let system_prompt = build_system_prompt()?;
  1013. let session = create_managed_session_handle()?;
  1014. let runtime = build_runtime(
  1015. Session::new(),
  1016. model.clone(),
  1017. system_prompt.clone(),
  1018. enable_tools,
  1019. true,
  1020. allowed_tools.clone(),
  1021. permission_mode,
  1022. None,
  1023. )?;
  1024. let cli = Self {
  1025. model,
  1026. allowed_tools,
  1027. permission_mode,
  1028. system_prompt,
  1029. runtime,
  1030. session,
  1031. };
  1032. cli.persist_session()?;
  1033. Ok(cli)
  1034. }
  1035. fn startup_banner(&self) -> String {
  1036. let cwd = env::current_dir().map_or_else(
  1037. |_| "<unknown>".to_string(),
  1038. |path| path.display().to_string(),
  1039. );
  1040. format!(
  1041. "\x1b[38;5;196m\
  1042. ██████╗██╗ █████╗ ██╗ ██╗\n\
  1043. ██╔════╝██║ ██╔══██╗██║ ██║\n\
  1044. ██║ ██║ ███████║██║ █╗ ██║\n\
  1045. ██║ ██║ ██╔══██║██║███╗██║\n\
  1046. ╚██████╗███████╗██║ ██║╚███╔███╔╝\n\
  1047. ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝\x1b[0m \x1b[38;5;208mCode\x1b[0m 🦞\n\n\
  1048. \x1b[2mModel\x1b[0m {}\n\
  1049. \x1b[2mPermissions\x1b[0m {}\n\
  1050. \x1b[2mDirectory\x1b[0m {}\n\
  1051. \x1b[2mSession\x1b[0m {}\n\n\
  1052. Type \x1b[1m/help\x1b[0m for commands · \x1b[2mShift+Enter\x1b[0m for newline",
  1053. self.model,
  1054. self.permission_mode.as_str(),
  1055. cwd,
  1056. self.session.id,
  1057. )
  1058. }
  1059. fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  1060. let mut spinner = Spinner::new();
  1061. let mut stdout = io::stdout();
  1062. spinner.tick(
  1063. "🦀 Thinking...",
  1064. TerminalRenderer::new().color_theme(),
  1065. &mut stdout,
  1066. )?;
  1067. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1068. let result = self.runtime.run_turn(input, Some(&mut permission_prompter));
  1069. match result {
  1070. Ok(_) => {
  1071. spinner.finish(
  1072. "✨ Done",
  1073. TerminalRenderer::new().color_theme(),
  1074. &mut stdout,
  1075. )?;
  1076. println!();
  1077. self.persist_session()?;
  1078. Ok(())
  1079. }
  1080. Err(error) => {
  1081. spinner.fail(
  1082. "❌ Request failed",
  1083. TerminalRenderer::new().color_theme(),
  1084. &mut stdout,
  1085. )?;
  1086. Err(Box::new(error))
  1087. }
  1088. }
  1089. }
  1090. fn run_turn_with_output(
  1091. &mut self,
  1092. input: &str,
  1093. output_format: CliOutputFormat,
  1094. ) -> Result<(), Box<dyn std::error::Error>> {
  1095. match output_format {
  1096. CliOutputFormat::Text => self.run_turn(input),
  1097. CliOutputFormat::Json => self.run_prompt_json(input),
  1098. }
  1099. }
  1100. fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  1101. let session = self.runtime.session().clone();
  1102. let mut runtime = build_runtime(
  1103. session,
  1104. self.model.clone(),
  1105. self.system_prompt.clone(),
  1106. true,
  1107. false,
  1108. self.allowed_tools.clone(),
  1109. self.permission_mode,
  1110. None,
  1111. )?;
  1112. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1113. let summary = runtime.run_turn(input, Some(&mut permission_prompter))?;
  1114. self.runtime = runtime;
  1115. self.persist_session()?;
  1116. println!(
  1117. "{}",
  1118. json!({
  1119. "message": final_assistant_text(&summary),
  1120. "model": self.model,
  1121. "iterations": summary.iterations,
  1122. "tool_uses": collect_tool_uses(&summary),
  1123. "tool_results": collect_tool_results(&summary),
  1124. "usage": {
  1125. "input_tokens": summary.usage.input_tokens,
  1126. "output_tokens": summary.usage.output_tokens,
  1127. "cache_creation_input_tokens": summary.usage.cache_creation_input_tokens,
  1128. "cache_read_input_tokens": summary.usage.cache_read_input_tokens,
  1129. }
  1130. })
  1131. );
  1132. Ok(())
  1133. }
  1134. fn handle_repl_command(
  1135. &mut self,
  1136. command: SlashCommand,
  1137. ) -> Result<bool, Box<dyn std::error::Error>> {
  1138. Ok(match command {
  1139. SlashCommand::Help => {
  1140. println!("{}", render_repl_help());
  1141. false
  1142. }
  1143. SlashCommand::Status => {
  1144. self.print_status();
  1145. false
  1146. }
  1147. SlashCommand::Bughunter { scope } => {
  1148. self.run_bughunter(scope.as_deref())?;
  1149. false
  1150. }
  1151. SlashCommand::Commit => {
  1152. self.run_commit()?;
  1153. true
  1154. }
  1155. SlashCommand::Pr { context } => {
  1156. self.run_pr(context.as_deref())?;
  1157. false
  1158. }
  1159. SlashCommand::Issue { context } => {
  1160. self.run_issue(context.as_deref())?;
  1161. false
  1162. }
  1163. SlashCommand::Ultraplan { task } => {
  1164. self.run_ultraplan(task.as_deref())?;
  1165. false
  1166. }
  1167. SlashCommand::Teleport { target } => {
  1168. self.run_teleport(target.as_deref())?;
  1169. false
  1170. }
  1171. SlashCommand::DebugToolCall => {
  1172. self.run_debug_tool_call()?;
  1173. false
  1174. }
  1175. SlashCommand::Sandbox => {
  1176. Self::print_sandbox_status();
  1177. false
  1178. }
  1179. SlashCommand::Compact => {
  1180. self.compact()?;
  1181. false
  1182. }
  1183. SlashCommand::Model { model } => self.set_model(model)?,
  1184. SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
  1185. SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
  1186. SlashCommand::Cost => {
  1187. self.print_cost();
  1188. false
  1189. }
  1190. SlashCommand::Resume { session_path } => self.resume_session(session_path)?,
  1191. SlashCommand::Config { section } => {
  1192. Self::print_config(section.as_deref())?;
  1193. false
  1194. }
  1195. SlashCommand::Memory => {
  1196. Self::print_memory()?;
  1197. false
  1198. }
  1199. SlashCommand::Init => {
  1200. run_init()?;
  1201. false
  1202. }
  1203. SlashCommand::Diff => {
  1204. Self::print_diff()?;
  1205. false
  1206. }
  1207. SlashCommand::Version => {
  1208. Self::print_version();
  1209. false
  1210. }
  1211. SlashCommand::Export { path } => {
  1212. self.export_session(path.as_deref())?;
  1213. false
  1214. }
  1215. SlashCommand::Session { action, target } => {
  1216. self.handle_session_command(action.as_deref(), target.as_deref())?
  1217. }
  1218. SlashCommand::Plugins { action, target } => {
  1219. self.handle_plugins_command(action.as_deref(), target.as_deref())?
  1220. }
  1221. SlashCommand::Agents { args } => {
  1222. Self::print_agents(args.as_deref())?;
  1223. false
  1224. }
  1225. SlashCommand::Skills { args } => {
  1226. Self::print_skills(args.as_deref())?;
  1227. false
  1228. }
  1229. SlashCommand::Unknown(name) => {
  1230. eprintln!("unknown slash command: /{name}");
  1231. false
  1232. }
  1233. })
  1234. }
  1235. fn persist_session(&self) -> Result<(), Box<dyn std::error::Error>> {
  1236. self.runtime.session().save_to_path(&self.session.path)?;
  1237. Ok(())
  1238. }
  1239. fn print_status(&self) {
  1240. let cumulative = self.runtime.usage().cumulative_usage();
  1241. let latest = self.runtime.usage().current_turn_usage();
  1242. println!(
  1243. "{}",
  1244. format_status_report(
  1245. &self.model,
  1246. StatusUsage {
  1247. message_count: self.runtime.session().messages.len(),
  1248. turns: self.runtime.usage().turns(),
  1249. latest,
  1250. cumulative,
  1251. estimated_tokens: self.runtime.estimated_tokens(),
  1252. },
  1253. self.permission_mode.as_str(),
  1254. &status_context(Some(&self.session.path)).expect("status context should load"),
  1255. )
  1256. );
  1257. }
  1258. fn print_sandbox_status() {
  1259. let cwd = env::current_dir().expect("current dir");
  1260. let loader = ConfigLoader::default_for(&cwd);
  1261. let runtime_config = loader
  1262. .load()
  1263. .unwrap_or_else(|_| runtime::RuntimeConfig::empty());
  1264. println!(
  1265. "{}",
  1266. format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
  1267. );
  1268. }
  1269. fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
  1270. let Some(model) = model else {
  1271. println!(
  1272. "{}",
  1273. format_model_report(
  1274. &self.model,
  1275. self.runtime.session().messages.len(),
  1276. self.runtime.usage().turns(),
  1277. )
  1278. );
  1279. return Ok(false);
  1280. };
  1281. let model = resolve_model_alias(&model).to_string();
  1282. if model == self.model {
  1283. println!(
  1284. "{}",
  1285. format_model_report(
  1286. &self.model,
  1287. self.runtime.session().messages.len(),
  1288. self.runtime.usage().turns(),
  1289. )
  1290. );
  1291. return Ok(false);
  1292. }
  1293. let previous = self.model.clone();
  1294. let session = self.runtime.session().clone();
  1295. let message_count = session.messages.len();
  1296. self.runtime = build_runtime(
  1297. session,
  1298. model.clone(),
  1299. self.system_prompt.clone(),
  1300. true,
  1301. true,
  1302. self.allowed_tools.clone(),
  1303. self.permission_mode,
  1304. None,
  1305. )?;
  1306. self.model.clone_from(&model);
  1307. println!(
  1308. "{}",
  1309. format_model_switch_report(&previous, &model, message_count)
  1310. );
  1311. Ok(true)
  1312. }
  1313. fn set_permissions(
  1314. &mut self,
  1315. mode: Option<String>,
  1316. ) -> Result<bool, Box<dyn std::error::Error>> {
  1317. let Some(mode) = mode else {
  1318. println!(
  1319. "{}",
  1320. format_permissions_report(self.permission_mode.as_str())
  1321. );
  1322. return Ok(false);
  1323. };
  1324. let normalized = normalize_permission_mode(&mode).ok_or_else(|| {
  1325. format!(
  1326. "unsupported permission mode '{mode}'. Use read-only, workspace-write, or danger-full-access."
  1327. )
  1328. })?;
  1329. if normalized == self.permission_mode.as_str() {
  1330. println!("{}", format_permissions_report(normalized));
  1331. return Ok(false);
  1332. }
  1333. let previous = self.permission_mode.as_str().to_string();
  1334. let session = self.runtime.session().clone();
  1335. self.permission_mode = permission_mode_from_label(normalized);
  1336. self.runtime = build_runtime(
  1337. session,
  1338. self.model.clone(),
  1339. self.system_prompt.clone(),
  1340. true,
  1341. true,
  1342. self.allowed_tools.clone(),
  1343. self.permission_mode,
  1344. None,
  1345. )?;
  1346. println!(
  1347. "{}",
  1348. format_permissions_switch_report(&previous, normalized)
  1349. );
  1350. Ok(true)
  1351. }
  1352. fn clear_session(&mut self, confirm: bool) -> Result<bool, Box<dyn std::error::Error>> {
  1353. if !confirm {
  1354. println!(
  1355. "clear: confirmation required; run /clear --confirm to start a fresh session."
  1356. );
  1357. return Ok(false);
  1358. }
  1359. self.session = create_managed_session_handle()?;
  1360. self.runtime = build_runtime(
  1361. Session::new(),
  1362. self.model.clone(),
  1363. self.system_prompt.clone(),
  1364. true,
  1365. true,
  1366. self.allowed_tools.clone(),
  1367. self.permission_mode,
  1368. None,
  1369. )?;
  1370. println!(
  1371. "Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
  1372. self.model,
  1373. self.permission_mode.as_str(),
  1374. self.session.id,
  1375. );
  1376. Ok(true)
  1377. }
  1378. fn print_cost(&self) {
  1379. let cumulative = self.runtime.usage().cumulative_usage();
  1380. println!("{}", format_cost_report(cumulative));
  1381. }
  1382. fn resume_session(
  1383. &mut self,
  1384. session_path: Option<String>,
  1385. ) -> Result<bool, Box<dyn std::error::Error>> {
  1386. let Some(session_ref) = session_path else {
  1387. println!("Usage: /resume <session-path>");
  1388. return Ok(false);
  1389. };
  1390. let handle = resolve_session_reference(&session_ref)?;
  1391. let session = Session::load_from_path(&handle.path)?;
  1392. let message_count = session.messages.len();
  1393. self.runtime = build_runtime(
  1394. session,
  1395. self.model.clone(),
  1396. self.system_prompt.clone(),
  1397. true,
  1398. true,
  1399. self.allowed_tools.clone(),
  1400. self.permission_mode,
  1401. None,
  1402. )?;
  1403. self.session = handle;
  1404. println!(
  1405. "{}",
  1406. format_resume_report(
  1407. &self.session.path.display().to_string(),
  1408. message_count,
  1409. self.runtime.usage().turns(),
  1410. )
  1411. );
  1412. Ok(true)
  1413. }
  1414. fn print_config(section: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1415. println!("{}", render_config_report(section)?);
  1416. Ok(())
  1417. }
  1418. fn print_memory() -> Result<(), Box<dyn std::error::Error>> {
  1419. println!("{}", render_memory_report()?);
  1420. Ok(())
  1421. }
  1422. fn print_agents(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1423. let cwd = env::current_dir()?;
  1424. println!("{}", handle_agents_slash_command(args, &cwd)?);
  1425. Ok(())
  1426. }
  1427. fn print_skills(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1428. let cwd = env::current_dir()?;
  1429. println!("{}", handle_skills_slash_command(args, &cwd)?);
  1430. Ok(())
  1431. }
  1432. fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
  1433. println!("{}", render_diff_report()?);
  1434. Ok(())
  1435. }
  1436. fn print_version() {
  1437. println!("{}", render_version_report());
  1438. }
  1439. fn export_session(
  1440. &self,
  1441. requested_path: Option<&str>,
  1442. ) -> Result<(), Box<dyn std::error::Error>> {
  1443. let export_path = resolve_export_path(requested_path, self.runtime.session())?;
  1444. fs::write(&export_path, render_export_text(self.runtime.session()))?;
  1445. println!(
  1446. "Export\n Result wrote transcript\n File {}\n Messages {}",
  1447. export_path.display(),
  1448. self.runtime.session().messages.len(),
  1449. );
  1450. Ok(())
  1451. }
  1452. fn handle_session_command(
  1453. &mut self,
  1454. action: Option<&str>,
  1455. target: Option<&str>,
  1456. ) -> Result<bool, Box<dyn std::error::Error>> {
  1457. match action {
  1458. None | Some("list") => {
  1459. println!("{}", render_session_list(&self.session.id)?);
  1460. Ok(false)
  1461. }
  1462. Some("switch") => {
  1463. let Some(target) = target else {
  1464. println!("Usage: /session switch <session-id>");
  1465. return Ok(false);
  1466. };
  1467. let handle = resolve_session_reference(target)?;
  1468. let session = Session::load_from_path(&handle.path)?;
  1469. let message_count = session.messages.len();
  1470. self.runtime = build_runtime(
  1471. session,
  1472. self.model.clone(),
  1473. self.system_prompt.clone(),
  1474. true,
  1475. true,
  1476. self.allowed_tools.clone(),
  1477. self.permission_mode,
  1478. None,
  1479. )?;
  1480. self.session = handle;
  1481. println!(
  1482. "Session switched\n Active session {}\n File {}\n Messages {}",
  1483. self.session.id,
  1484. self.session.path.display(),
  1485. message_count,
  1486. );
  1487. Ok(true)
  1488. }
  1489. Some(other) => {
  1490. println!("Unknown /session action '{other}'. Use /session list or /session switch <session-id>.");
  1491. Ok(false)
  1492. }
  1493. }
  1494. }
  1495. fn handle_plugins_command(
  1496. &mut self,
  1497. action: Option<&str>,
  1498. target: Option<&str>,
  1499. ) -> Result<bool, Box<dyn std::error::Error>> {
  1500. let cwd = env::current_dir()?;
  1501. let loader = ConfigLoader::default_for(&cwd);
  1502. let runtime_config = loader.load()?;
  1503. let mut manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  1504. let result = handle_plugins_slash_command(action, target, &mut manager)?;
  1505. println!("{}", result.message);
  1506. if result.reload_runtime {
  1507. self.reload_runtime_features()?;
  1508. }
  1509. Ok(false)
  1510. }
  1511. fn reload_runtime_features(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  1512. self.runtime = build_runtime(
  1513. self.runtime.session().clone(),
  1514. self.model.clone(),
  1515. self.system_prompt.clone(),
  1516. true,
  1517. true,
  1518. self.allowed_tools.clone(),
  1519. self.permission_mode,
  1520. None,
  1521. )?;
  1522. self.persist_session()
  1523. }
  1524. fn compact(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  1525. let result = self.runtime.compact(CompactionConfig::default());
  1526. let removed = result.removed_message_count;
  1527. let kept = result.compacted_session.messages.len();
  1528. let skipped = removed == 0;
  1529. self.runtime = build_runtime(
  1530. result.compacted_session,
  1531. self.model.clone(),
  1532. self.system_prompt.clone(),
  1533. true,
  1534. true,
  1535. self.allowed_tools.clone(),
  1536. self.permission_mode,
  1537. None,
  1538. )?;
  1539. self.persist_session()?;
  1540. println!("{}", format_compact_report(removed, kept, skipped));
  1541. Ok(())
  1542. }
  1543. fn run_internal_prompt_text_with_progress(
  1544. &self,
  1545. prompt: &str,
  1546. enable_tools: bool,
  1547. progress: Option<InternalPromptProgressReporter>,
  1548. ) -> Result<String, Box<dyn std::error::Error>> {
  1549. let session = self.runtime.session().clone();
  1550. let mut runtime = build_runtime(
  1551. session,
  1552. self.model.clone(),
  1553. self.system_prompt.clone(),
  1554. enable_tools,
  1555. false,
  1556. self.allowed_tools.clone(),
  1557. self.permission_mode,
  1558. progress,
  1559. )?;
  1560. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1561. let summary = runtime.run_turn(prompt, Some(&mut permission_prompter))?;
  1562. Ok(final_assistant_text(&summary).trim().to_string())
  1563. }
  1564. fn run_internal_prompt_text(
  1565. &self,
  1566. prompt: &str,
  1567. enable_tools: bool,
  1568. ) -> Result<String, Box<dyn std::error::Error>> {
  1569. self.run_internal_prompt_text_with_progress(prompt, enable_tools, None)
  1570. }
  1571. fn run_bughunter(&self, scope: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1572. let scope = scope.unwrap_or("the current repository");
  1573. let prompt = format!(
  1574. "You are /bughunter. Inspect {scope} and identify the most likely bugs or correctness issues. Prioritize concrete findings with file paths, severity, and suggested fixes. Use tools if needed."
  1575. );
  1576. println!("{}", self.run_internal_prompt_text(&prompt, true)?);
  1577. Ok(())
  1578. }
  1579. fn run_ultraplan(&self, task: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1580. let task = task.unwrap_or("the current repo work");
  1581. let prompt = format!(
  1582. "You are /ultraplan. Produce a deep multi-step execution plan for {task}. Include goals, risks, implementation sequence, verification steps, and rollback considerations. Use tools if needed."
  1583. );
  1584. let mut progress = InternalPromptProgressRun::start_ultraplan(task);
  1585. match self.run_internal_prompt_text_with_progress(&prompt, true, Some(progress.reporter()))
  1586. {
  1587. Ok(plan) => {
  1588. progress.finish_success();
  1589. println!("{plan}");
  1590. Ok(())
  1591. }
  1592. Err(error) => {
  1593. progress.finish_failure(&error.to_string());
  1594. Err(error)
  1595. }
  1596. }
  1597. }
  1598. #[allow(clippy::unused_self)]
  1599. fn run_teleport(&self, target: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1600. let Some(target) = target.map(str::trim).filter(|value| !value.is_empty()) else {
  1601. println!("Usage: /teleport <symbol-or-path>");
  1602. return Ok(());
  1603. };
  1604. println!("{}", render_teleport_report(target)?);
  1605. Ok(())
  1606. }
  1607. fn run_debug_tool_call(&self) -> Result<(), Box<dyn std::error::Error>> {
  1608. println!("{}", render_last_tool_debug_report(self.runtime.session())?);
  1609. Ok(())
  1610. }
  1611. fn run_commit(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  1612. let status = git_output(&["status", "--short"])?;
  1613. if status.trim().is_empty() {
  1614. println!("Commit\n Result skipped\n Reason no workspace changes");
  1615. return Ok(());
  1616. }
  1617. git_status_ok(&["add", "-A"])?;
  1618. let staged_stat = git_output(&["diff", "--cached", "--stat"])?;
  1619. let prompt = format!(
  1620. "Generate a git commit message in plain text Lore format only. Base it on this staged diff summary:\n\n{}\n\nRecent conversation context:\n{}",
  1621. truncate_for_prompt(&staged_stat, 8_000),
  1622. recent_user_context(self.runtime.session(), 6)
  1623. );
  1624. let message = sanitize_generated_message(&self.run_internal_prompt_text(&prompt, false)?);
  1625. if message.trim().is_empty() {
  1626. return Err("generated commit message was empty".into());
  1627. }
  1628. let path = write_temp_text_file("claw-commit-message.txt", &message)?;
  1629. let output = Command::new("git")
  1630. .args(["commit", "--file"])
  1631. .arg(&path)
  1632. .current_dir(env::current_dir()?)
  1633. .output()?;
  1634. if !output.status.success() {
  1635. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  1636. return Err(format!("git commit failed: {stderr}").into());
  1637. }
  1638. println!(
  1639. "Commit\n Result created\n Message file {}\n\n{}",
  1640. path.display(),
  1641. message.trim()
  1642. );
  1643. Ok(())
  1644. }
  1645. fn run_pr(&self, context: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1646. let staged = git_output(&["diff", "--stat"])?;
  1647. let prompt = format!(
  1648. "Generate a pull request title and body from this conversation and diff summary. Output plain text in this format exactly:\nTITLE: <title>\nBODY:\n<body markdown>\n\nContext hint: {}\n\nDiff summary:\n{}",
  1649. context.unwrap_or("none"),
  1650. truncate_for_prompt(&staged, 10_000)
  1651. );
  1652. let draft = sanitize_generated_message(&self.run_internal_prompt_text(&prompt, false)?);
  1653. let (title, body) = parse_titled_body(&draft)
  1654. .ok_or_else(|| "failed to parse generated PR title/body".to_string())?;
  1655. if command_exists("gh") {
  1656. let body_path = write_temp_text_file("claw-pr-body.md", &body)?;
  1657. let output = Command::new("gh")
  1658. .args(["pr", "create", "--title", &title, "--body-file"])
  1659. .arg(&body_path)
  1660. .current_dir(env::current_dir()?)
  1661. .output()?;
  1662. if output.status.success() {
  1663. let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
  1664. println!(
  1665. "PR\n Result created\n Title {title}\n URL {}",
  1666. if stdout.is_empty() { "<unknown>" } else { &stdout }
  1667. );
  1668. return Ok(());
  1669. }
  1670. }
  1671. println!("PR draft\n Title {title}\n\n{body}");
  1672. Ok(())
  1673. }
  1674. fn run_issue(&self, context: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1675. let prompt = format!(
  1676. "Generate a GitHub issue title and body from this conversation. Output plain text in this format exactly:\nTITLE: <title>\nBODY:\n<body markdown>\n\nContext hint: {}\n\nConversation context:\n{}",
  1677. context.unwrap_or("none"),
  1678. truncate_for_prompt(&recent_user_context(self.runtime.session(), 10), 10_000)
  1679. );
  1680. let draft = sanitize_generated_message(&self.run_internal_prompt_text(&prompt, false)?);
  1681. let (title, body) = parse_titled_body(&draft)
  1682. .ok_or_else(|| "failed to parse generated issue title/body".to_string())?;
  1683. if command_exists("gh") {
  1684. let body_path = write_temp_text_file("claw-issue-body.md", &body)?;
  1685. let output = Command::new("gh")
  1686. .args(["issue", "create", "--title", &title, "--body-file"])
  1687. .arg(&body_path)
  1688. .current_dir(env::current_dir()?)
  1689. .output()?;
  1690. if output.status.success() {
  1691. let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
  1692. println!(
  1693. "Issue\n Result created\n Title {title}\n URL {}",
  1694. if stdout.is_empty() { "<unknown>" } else { &stdout }
  1695. );
  1696. return Ok(());
  1697. }
  1698. }
  1699. println!("Issue draft\n Title {title}\n\n{body}");
  1700. Ok(())
  1701. }
  1702. }
  1703. fn sessions_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
  1704. let cwd = env::current_dir()?;
  1705. let path = cwd.join(".claw").join("sessions");
  1706. fs::create_dir_all(&path)?;
  1707. Ok(path)
  1708. }
  1709. fn create_managed_session_handle() -> Result<SessionHandle, Box<dyn std::error::Error>> {
  1710. let id = generate_session_id();
  1711. let path = sessions_dir()?.join(format!("{id}.json"));
  1712. Ok(SessionHandle { id, path })
  1713. }
  1714. fn generate_session_id() -> String {
  1715. let millis = SystemTime::now()
  1716. .duration_since(UNIX_EPOCH)
  1717. .map(|duration| duration.as_millis())
  1718. .unwrap_or_default();
  1719. format!("session-{millis}")
  1720. }
  1721. fn resolve_session_reference(reference: &str) -> Result<SessionHandle, Box<dyn std::error::Error>> {
  1722. let direct = PathBuf::from(reference);
  1723. let path = if direct.exists() {
  1724. direct
  1725. } else {
  1726. sessions_dir()?.join(format!("{reference}.json"))
  1727. };
  1728. if !path.exists() {
  1729. return Err(format!("session not found: {reference}").into());
  1730. }
  1731. let id = path
  1732. .file_stem()
  1733. .and_then(|value| value.to_str())
  1734. .unwrap_or(reference)
  1735. .to_string();
  1736. Ok(SessionHandle { id, path })
  1737. }
  1738. fn list_managed_sessions() -> Result<Vec<ManagedSessionSummary>, Box<dyn std::error::Error>> {
  1739. let mut sessions = Vec::new();
  1740. for entry in fs::read_dir(sessions_dir()?)? {
  1741. let entry = entry?;
  1742. let path = entry.path();
  1743. if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
  1744. continue;
  1745. }
  1746. let metadata = entry.metadata()?;
  1747. let modified_epoch_secs = metadata
  1748. .modified()
  1749. .ok()
  1750. .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
  1751. .map(|duration| duration.as_secs())
  1752. .unwrap_or_default();
  1753. let message_count = Session::load_from_path(&path)
  1754. .map(|session| session.messages.len())
  1755. .unwrap_or_default();
  1756. let id = path
  1757. .file_stem()
  1758. .and_then(|value| value.to_str())
  1759. .unwrap_or("unknown")
  1760. .to_string();
  1761. sessions.push(ManagedSessionSummary {
  1762. id,
  1763. path,
  1764. modified_epoch_secs,
  1765. message_count,
  1766. });
  1767. }
  1768. sessions.sort_by(|left, right| right.modified_epoch_secs.cmp(&left.modified_epoch_secs));
  1769. Ok(sessions)
  1770. }
  1771. fn render_session_list(active_session_id: &str) -> Result<String, Box<dyn std::error::Error>> {
  1772. let sessions = list_managed_sessions()?;
  1773. let mut lines = vec![
  1774. "Sessions".to_string(),
  1775. format!(" Directory {}", sessions_dir()?.display()),
  1776. ];
  1777. if sessions.is_empty() {
  1778. lines.push(" No managed sessions saved yet.".to_string());
  1779. return Ok(lines.join("\n"));
  1780. }
  1781. for session in sessions {
  1782. let marker = if session.id == active_session_id {
  1783. "● current"
  1784. } else {
  1785. "○ saved"
  1786. };
  1787. lines.push(format!(
  1788. " {id:<20} {marker:<10} msgs={msgs:<4} modified={modified} path={path}",
  1789. id = session.id,
  1790. msgs = session.message_count,
  1791. modified = session.modified_epoch_secs,
  1792. path = session.path.display(),
  1793. ));
  1794. }
  1795. Ok(lines.join("\n"))
  1796. }
  1797. fn render_repl_help() -> String {
  1798. [
  1799. "REPL".to_string(),
  1800. " /exit Quit the REPL".to_string(),
  1801. " /quit Quit the REPL".to_string(),
  1802. " Up/Down Navigate prompt history".to_string(),
  1803. " Tab Complete slash commands".to_string(),
  1804. " Ctrl-C Clear input (or exit on empty prompt)".to_string(),
  1805. " Shift+Enter/Ctrl+J Insert a newline".to_string(),
  1806. String::new(),
  1807. render_slash_command_help(),
  1808. ]
  1809. .join(
  1810. "
  1811. ",
  1812. )
  1813. }
  1814. fn status_context(
  1815. session_path: Option<&Path>,
  1816. ) -> Result<StatusContext, Box<dyn std::error::Error>> {
  1817. let cwd = env::current_dir()?;
  1818. let loader = ConfigLoader::default_for(&cwd);
  1819. let discovered_config_files = loader.discover().len();
  1820. let runtime_config = loader.load()?;
  1821. let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
  1822. let (project_root, git_branch) =
  1823. parse_git_status_metadata(project_context.git_status.as_deref());
  1824. let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
  1825. Ok(StatusContext {
  1826. cwd,
  1827. session_path: session_path.map(Path::to_path_buf),
  1828. loaded_config_files: runtime_config.loaded_entries().len(),
  1829. discovered_config_files,
  1830. memory_file_count: project_context.instruction_files.len(),
  1831. project_root,
  1832. git_branch,
  1833. sandbox_status,
  1834. })
  1835. }
  1836. fn format_status_report(
  1837. model: &str,
  1838. usage: StatusUsage,
  1839. permission_mode: &str,
  1840. context: &StatusContext,
  1841. ) -> String {
  1842. [
  1843. format!(
  1844. "Status
  1845. Model {model}
  1846. Permission mode {permission_mode}
  1847. Messages {}
  1848. Turns {}
  1849. Estimated tokens {}",
  1850. usage.message_count, usage.turns, usage.estimated_tokens,
  1851. ),
  1852. format!(
  1853. "Usage
  1854. Latest total {}
  1855. Cumulative input {}
  1856. Cumulative output {}
  1857. Cumulative total {}",
  1858. usage.latest.total_tokens(),
  1859. usage.cumulative.input_tokens,
  1860. usage.cumulative.output_tokens,
  1861. usage.cumulative.total_tokens(),
  1862. ),
  1863. format!(
  1864. "Workspace
  1865. Cwd {}
  1866. Project root {}
  1867. Git branch {}
  1868. Session {}
  1869. Config files loaded {}/{}
  1870. Memory files {}",
  1871. context.cwd.display(),
  1872. context
  1873. .project_root
  1874. .as_ref()
  1875. .map_or_else(|| "unknown".to_string(), |path| path.display().to_string()),
  1876. context.git_branch.as_deref().unwrap_or("unknown"),
  1877. context.session_path.as_ref().map_or_else(
  1878. || "live-repl".to_string(),
  1879. |path| path.display().to_string()
  1880. ),
  1881. context.loaded_config_files,
  1882. context.discovered_config_files,
  1883. context.memory_file_count,
  1884. ),
  1885. format_sandbox_report(&context.sandbox_status),
  1886. ]
  1887. .join(
  1888. "
  1889. ",
  1890. )
  1891. }
  1892. fn format_sandbox_report(status: &runtime::SandboxStatus) -> String {
  1893. format!(
  1894. "Sandbox
  1895. Enabled {}
  1896. Active {}
  1897. Supported {}
  1898. In container {}
  1899. Requested ns {}
  1900. Active ns {}
  1901. Requested net {}
  1902. Active net {}
  1903. Filesystem mode {}
  1904. Filesystem active {}
  1905. Allowed mounts {}
  1906. Markers {}
  1907. Fallback reason {}",
  1908. status.enabled,
  1909. status.active,
  1910. status.supported,
  1911. status.in_container,
  1912. status.requested.namespace_restrictions,
  1913. status.namespace_active,
  1914. status.requested.network_isolation,
  1915. status.network_active,
  1916. status.filesystem_mode.as_str(),
  1917. status.filesystem_active,
  1918. if status.allowed_mounts.is_empty() {
  1919. "<none>".to_string()
  1920. } else {
  1921. status.allowed_mounts.join(", ")
  1922. },
  1923. if status.container_markers.is_empty() {
  1924. "<none>".to_string()
  1925. } else {
  1926. status.container_markers.join(", ")
  1927. },
  1928. status
  1929. .fallback_reason
  1930. .clone()
  1931. .unwrap_or_else(|| "<none>".to_string()),
  1932. )
  1933. }
  1934. fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
  1935. let cwd = env::current_dir()?;
  1936. let loader = ConfigLoader::default_for(&cwd);
  1937. let discovered = loader.discover();
  1938. let runtime_config = loader.load()?;
  1939. let mut lines = vec![
  1940. format!(
  1941. "Config
  1942. Working directory {}
  1943. Loaded files {}
  1944. Merged keys {}",
  1945. cwd.display(),
  1946. runtime_config.loaded_entries().len(),
  1947. runtime_config.merged().len()
  1948. ),
  1949. "Discovered files".to_string(),
  1950. ];
  1951. for entry in discovered {
  1952. let source = match entry.source {
  1953. ConfigSource::User => "user",
  1954. ConfigSource::Project => "project",
  1955. ConfigSource::Local => "local",
  1956. };
  1957. let status = if runtime_config
  1958. .loaded_entries()
  1959. .iter()
  1960. .any(|loaded_entry| loaded_entry.path == entry.path)
  1961. {
  1962. "loaded"
  1963. } else {
  1964. "missing"
  1965. };
  1966. lines.push(format!(
  1967. " {source:<7} {status:<7} {}",
  1968. entry.path.display()
  1969. ));
  1970. }
  1971. if let Some(section) = section {
  1972. lines.push(format!("Merged section: {section}"));
  1973. let value = match section {
  1974. "env" => runtime_config.get("env"),
  1975. "hooks" => runtime_config.get("hooks"),
  1976. "model" => runtime_config.get("model"),
  1977. "plugins" => runtime_config
  1978. .get("plugins")
  1979. .or_else(|| runtime_config.get("enabledPlugins")),
  1980. other => {
  1981. lines.push(format!(
  1982. " Unsupported config section '{other}'. Use env, hooks, model, or plugins."
  1983. ));
  1984. return Ok(lines.join(
  1985. "
  1986. ",
  1987. ));
  1988. }
  1989. };
  1990. lines.push(format!(
  1991. " {}",
  1992. match value {
  1993. Some(value) => value.render(),
  1994. None => "<unset>".to_string(),
  1995. }
  1996. ));
  1997. return Ok(lines.join(
  1998. "
  1999. ",
  2000. ));
  2001. }
  2002. lines.push("Merged JSON".to_string());
  2003. lines.push(format!(" {}", runtime_config.as_json().render()));
  2004. Ok(lines.join(
  2005. "
  2006. ",
  2007. ))
  2008. }
  2009. fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
  2010. let cwd = env::current_dir()?;
  2011. let project_context = ProjectContext::discover(&cwd, DEFAULT_DATE)?;
  2012. let mut lines = vec![format!(
  2013. "Memory
  2014. Working directory {}
  2015. Instruction files {}",
  2016. cwd.display(),
  2017. project_context.instruction_files.len()
  2018. )];
  2019. if project_context.instruction_files.is_empty() {
  2020. lines.push("Discovered files".to_string());
  2021. lines.push(
  2022. " No CLAUDE instruction files discovered in the current directory ancestry."
  2023. .to_string(),
  2024. );
  2025. } else {
  2026. lines.push("Discovered files".to_string());
  2027. for (index, file) in project_context.instruction_files.iter().enumerate() {
  2028. let preview = file.content.lines().next().unwrap_or("").trim();
  2029. let preview = if preview.is_empty() {
  2030. "<empty>"
  2031. } else {
  2032. preview
  2033. };
  2034. lines.push(format!(" {}. {}", index + 1, file.path.display(),));
  2035. lines.push(format!(
  2036. " lines={} preview={}",
  2037. file.content.lines().count(),
  2038. preview
  2039. ));
  2040. }
  2041. }
  2042. Ok(lines.join(
  2043. "
  2044. ",
  2045. ))
  2046. }
  2047. fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
  2048. let cwd = env::current_dir()?;
  2049. Ok(initialize_repo(&cwd)?.render())
  2050. }
  2051. fn run_init() -> Result<(), Box<dyn std::error::Error>> {
  2052. println!("{}", init_claude_md()?);
  2053. Ok(())
  2054. }
  2055. fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
  2056. match mode.trim() {
  2057. "read-only" => Some("read-only"),
  2058. "workspace-write" => Some("workspace-write"),
  2059. "danger-full-access" => Some("danger-full-access"),
  2060. _ => None,
  2061. }
  2062. }
  2063. fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
  2064. render_diff_report_for(&env::current_dir()?)
  2065. }
  2066. fn render_diff_report_for(cwd: &Path) -> Result<String, Box<dyn std::error::Error>> {
  2067. let staged = run_git_diff_command_in(cwd, &["diff", "--cached"])?;
  2068. let unstaged = run_git_diff_command_in(cwd, &["diff"])?;
  2069. if staged.trim().is_empty() && unstaged.trim().is_empty() {
  2070. return Ok(
  2071. "Diff\n Result clean working tree\n Detail no current changes"
  2072. .to_string(),
  2073. );
  2074. }
  2075. let mut sections = Vec::new();
  2076. if !staged.trim().is_empty() {
  2077. sections.push(format!("Staged changes:\n{}", staged.trim_end()));
  2078. }
  2079. if !unstaged.trim().is_empty() {
  2080. sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
  2081. }
  2082. Ok(format!("Diff\n\n{}", sections.join("\n\n")))
  2083. }
  2084. fn run_git_diff_command_in(
  2085. cwd: &Path,
  2086. args: &[&str],
  2087. ) -> Result<String, Box<dyn std::error::Error>> {
  2088. let output = std::process::Command::new("git")
  2089. .args(args)
  2090. .current_dir(cwd)
  2091. .output()?;
  2092. if !output.status.success() {
  2093. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2094. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2095. }
  2096. Ok(String::from_utf8(output.stdout)?)
  2097. }
  2098. fn render_teleport_report(target: &str) -> Result<String, Box<dyn std::error::Error>> {
  2099. let cwd = env::current_dir()?;
  2100. let file_list = Command::new("rg")
  2101. .args(["--files"])
  2102. .current_dir(&cwd)
  2103. .output()?;
  2104. let file_matches = if file_list.status.success() {
  2105. String::from_utf8(file_list.stdout)?
  2106. .lines()
  2107. .filter(|line| line.contains(target))
  2108. .take(10)
  2109. .map(ToOwned::to_owned)
  2110. .collect::<Vec<_>>()
  2111. } else {
  2112. Vec::new()
  2113. };
  2114. let content_output = Command::new("rg")
  2115. .args(["-n", "-S", "--color", "never", target, "."])
  2116. .current_dir(&cwd)
  2117. .output()?;
  2118. let mut lines = vec![format!("Teleport\n Target {target}")];
  2119. if !file_matches.is_empty() {
  2120. lines.push(String::new());
  2121. lines.push("File matches".to_string());
  2122. lines.extend(file_matches.into_iter().map(|path| format!(" {path}")));
  2123. }
  2124. if content_output.status.success() {
  2125. let matches = String::from_utf8(content_output.stdout)?;
  2126. if !matches.trim().is_empty() {
  2127. lines.push(String::new());
  2128. lines.push("Content matches".to_string());
  2129. lines.push(truncate_for_prompt(&matches, 4_000));
  2130. }
  2131. }
  2132. if lines.len() == 1 {
  2133. lines.push(" Result no matches found".to_string());
  2134. }
  2135. Ok(lines.join("\n"))
  2136. }
  2137. fn render_last_tool_debug_report(session: &Session) -> Result<String, Box<dyn std::error::Error>> {
  2138. let last_tool_use = session
  2139. .messages
  2140. .iter()
  2141. .rev()
  2142. .find_map(|message| {
  2143. message.blocks.iter().rev().find_map(|block| match block {
  2144. ContentBlock::ToolUse { id, name, input } => {
  2145. Some((id.clone(), name.clone(), input.clone()))
  2146. }
  2147. _ => None,
  2148. })
  2149. })
  2150. .ok_or_else(|| "no prior tool call found in session".to_string())?;
  2151. let tool_result = session.messages.iter().rev().find_map(|message| {
  2152. message.blocks.iter().rev().find_map(|block| match block {
  2153. ContentBlock::ToolResult {
  2154. tool_use_id,
  2155. tool_name,
  2156. output,
  2157. is_error,
  2158. } if tool_use_id == &last_tool_use.0 => {
  2159. Some((tool_name.clone(), output.clone(), *is_error))
  2160. }
  2161. _ => None,
  2162. })
  2163. });
  2164. let mut lines = vec![
  2165. "Debug tool call".to_string(),
  2166. format!(" Tool id {}", last_tool_use.0),
  2167. format!(" Tool name {}", last_tool_use.1),
  2168. " Input".to_string(),
  2169. indent_block(&last_tool_use.2, 4),
  2170. ];
  2171. match tool_result {
  2172. Some((tool_name, output, is_error)) => {
  2173. lines.push(" Result".to_string());
  2174. lines.push(format!(" name {tool_name}"));
  2175. lines.push(format!(
  2176. " status {}",
  2177. if is_error { "error" } else { "ok" }
  2178. ));
  2179. lines.push(indent_block(&output, 4));
  2180. }
  2181. None => lines.push(" Result missing tool result".to_string()),
  2182. }
  2183. Ok(lines.join("\n"))
  2184. }
  2185. fn indent_block(value: &str, spaces: usize) -> String {
  2186. let indent = " ".repeat(spaces);
  2187. value
  2188. .lines()
  2189. .map(|line| format!("{indent}{line}"))
  2190. .collect::<Vec<_>>()
  2191. .join("\n")
  2192. }
  2193. fn git_output(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
  2194. let output = Command::new("git")
  2195. .args(args)
  2196. .current_dir(env::current_dir()?)
  2197. .output()?;
  2198. if !output.status.success() {
  2199. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2200. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2201. }
  2202. Ok(String::from_utf8(output.stdout)?)
  2203. }
  2204. fn git_status_ok(args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
  2205. let output = Command::new("git")
  2206. .args(args)
  2207. .current_dir(env::current_dir()?)
  2208. .output()?;
  2209. if !output.status.success() {
  2210. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  2211. return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
  2212. }
  2213. Ok(())
  2214. }
  2215. fn command_exists(name: &str) -> bool {
  2216. Command::new("which")
  2217. .arg(name)
  2218. .output()
  2219. .map(|output| output.status.success())
  2220. .unwrap_or(false)
  2221. }
  2222. fn write_temp_text_file(
  2223. filename: &str,
  2224. contents: &str,
  2225. ) -> Result<PathBuf, Box<dyn std::error::Error>> {
  2226. let path = env::temp_dir().join(filename);
  2227. fs::write(&path, contents)?;
  2228. Ok(path)
  2229. }
  2230. fn recent_user_context(session: &Session, limit: usize) -> String {
  2231. let requests = session
  2232. .messages
  2233. .iter()
  2234. .filter(|message| message.role == MessageRole::User)
  2235. .filter_map(|message| {
  2236. message.blocks.iter().find_map(|block| match block {
  2237. ContentBlock::Text { text } => Some(text.trim().to_string()),
  2238. _ => None,
  2239. })
  2240. })
  2241. .rev()
  2242. .take(limit)
  2243. .collect::<Vec<_>>();
  2244. if requests.is_empty() {
  2245. "<no prior user messages>".to_string()
  2246. } else {
  2247. requests
  2248. .into_iter()
  2249. .rev()
  2250. .enumerate()
  2251. .map(|(index, text)| format!("{}. {}", index + 1, text))
  2252. .collect::<Vec<_>>()
  2253. .join("\n")
  2254. }
  2255. }
  2256. fn truncate_for_prompt(value: &str, limit: usize) -> String {
  2257. if value.chars().count() <= limit {
  2258. value.trim().to_string()
  2259. } else {
  2260. let truncated = value.chars().take(limit).collect::<String>();
  2261. format!("{}\n…[truncated]", truncated.trim_end())
  2262. }
  2263. }
  2264. fn sanitize_generated_message(value: &str) -> String {
  2265. value.trim().trim_matches('`').trim().replace("\r\n", "\n")
  2266. }
  2267. fn parse_titled_body(value: &str) -> Option<(String, String)> {
  2268. let normalized = sanitize_generated_message(value);
  2269. let title = normalized
  2270. .lines()
  2271. .find_map(|line| line.strip_prefix("TITLE:").map(str::trim))?;
  2272. let body_start = normalized.find("BODY:")?;
  2273. let body = normalized[body_start + "BODY:".len()..].trim();
  2274. Some((title.to_string(), body.to_string()))
  2275. }
  2276. fn render_version_report() -> String {
  2277. let git_sha = GIT_SHA.unwrap_or("unknown");
  2278. let target = BUILD_TARGET.unwrap_or("unknown");
  2279. format!(
  2280. "Claw Code\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
  2281. )
  2282. }
  2283. fn render_export_text(session: &Session) -> String {
  2284. let mut lines = vec!["# Conversation Export".to_string(), String::new()];
  2285. for (index, message) in session.messages.iter().enumerate() {
  2286. let role = match message.role {
  2287. MessageRole::System => "system",
  2288. MessageRole::User => "user",
  2289. MessageRole::Assistant => "assistant",
  2290. MessageRole::Tool => "tool",
  2291. };
  2292. lines.push(format!("## {}. {role}", index + 1));
  2293. for block in &message.blocks {
  2294. match block {
  2295. ContentBlock::Text { text } => lines.push(text.clone()),
  2296. ContentBlock::ToolUse { id, name, input } => {
  2297. lines.push(format!("[tool_use id={id} name={name}] {input}"));
  2298. }
  2299. ContentBlock::ToolResult {
  2300. tool_use_id,
  2301. tool_name,
  2302. output,
  2303. is_error,
  2304. } => {
  2305. lines.push(format!(
  2306. "[tool_result id={tool_use_id} name={tool_name} error={is_error}] {output}"
  2307. ));
  2308. }
  2309. }
  2310. }
  2311. lines.push(String::new());
  2312. }
  2313. lines.join("\n")
  2314. }
  2315. fn default_export_filename(session: &Session) -> String {
  2316. let stem = session
  2317. .messages
  2318. .iter()
  2319. .find_map(|message| match message.role {
  2320. MessageRole::User => message.blocks.iter().find_map(|block| match block {
  2321. ContentBlock::Text { text } => Some(text.as_str()),
  2322. _ => None,
  2323. }),
  2324. _ => None,
  2325. })
  2326. .map_or("conversation", |text| {
  2327. text.lines().next().unwrap_or("conversation")
  2328. })
  2329. .chars()
  2330. .map(|ch| {
  2331. if ch.is_ascii_alphanumeric() {
  2332. ch.to_ascii_lowercase()
  2333. } else {
  2334. '-'
  2335. }
  2336. })
  2337. .collect::<String>()
  2338. .split('-')
  2339. .filter(|part| !part.is_empty())
  2340. .take(8)
  2341. .collect::<Vec<_>>()
  2342. .join("-");
  2343. let fallback = if stem.is_empty() {
  2344. "conversation"
  2345. } else {
  2346. &stem
  2347. };
  2348. format!("{fallback}.txt")
  2349. }
  2350. fn resolve_export_path(
  2351. requested_path: Option<&str>,
  2352. session: &Session,
  2353. ) -> Result<PathBuf, Box<dyn std::error::Error>> {
  2354. let cwd = env::current_dir()?;
  2355. let file_name =
  2356. requested_path.map_or_else(|| default_export_filename(session), ToOwned::to_owned);
  2357. let final_name = if Path::new(&file_name)
  2358. .extension()
  2359. .is_some_and(|ext| ext.eq_ignore_ascii_case("txt"))
  2360. {
  2361. file_name
  2362. } else {
  2363. format!("{file_name}.txt")
  2364. };
  2365. Ok(cwd.join(final_name))
  2366. }
  2367. fn build_system_prompt() -> Result<Vec<String>, Box<dyn std::error::Error>> {
  2368. Ok(load_system_prompt(
  2369. env::current_dir()?,
  2370. DEFAULT_DATE,
  2371. env::consts::OS,
  2372. "unknown",
  2373. )?)
  2374. }
  2375. fn build_runtime_plugin_state(
  2376. ) -> Result<(runtime::RuntimeFeatureConfig, GlobalToolRegistry), Box<dyn std::error::Error>> {
  2377. let cwd = env::current_dir()?;
  2378. let loader = ConfigLoader::default_for(&cwd);
  2379. let runtime_config = loader.load()?;
  2380. let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
  2381. let tool_registry = GlobalToolRegistry::with_plugin_tools(plugin_manager.aggregated_tools()?)?;
  2382. Ok((runtime_config.feature_config().clone(), tool_registry))
  2383. }
  2384. fn build_plugin_manager(
  2385. cwd: &Path,
  2386. loader: &ConfigLoader,
  2387. runtime_config: &runtime::RuntimeConfig,
  2388. ) -> PluginManager {
  2389. let plugin_settings = runtime_config.plugins();
  2390. let mut plugin_config = PluginManagerConfig::new(loader.config_home().to_path_buf());
  2391. plugin_config.enabled_plugins = plugin_settings.enabled_plugins().clone();
  2392. plugin_config.external_dirs = plugin_settings
  2393. .external_directories()
  2394. .iter()
  2395. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path))
  2396. .collect();
  2397. plugin_config.install_root = plugin_settings
  2398. .install_root()
  2399. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  2400. plugin_config.registry_path = plugin_settings
  2401. .registry_path()
  2402. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  2403. plugin_config.bundled_root = plugin_settings
  2404. .bundled_root()
  2405. .map(|path| resolve_plugin_path(cwd, loader.config_home(), path));
  2406. PluginManager::new(plugin_config)
  2407. }
  2408. fn resolve_plugin_path(cwd: &Path, config_home: &Path, value: &str) -> PathBuf {
  2409. let path = PathBuf::from(value);
  2410. if path.is_absolute() {
  2411. path
  2412. } else if value.starts_with('.') {
  2413. cwd.join(path)
  2414. } else {
  2415. config_home.join(path)
  2416. }
  2417. }
  2418. #[derive(Debug, Clone, PartialEq, Eq)]
  2419. struct InternalPromptProgressState {
  2420. command_label: &'static str,
  2421. task_label: String,
  2422. step: usize,
  2423. phase: String,
  2424. detail: Option<String>,
  2425. saw_final_text: bool,
  2426. }
  2427. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  2428. enum InternalPromptProgressEvent {
  2429. Started,
  2430. Update,
  2431. Heartbeat,
  2432. Complete,
  2433. Failed,
  2434. }
  2435. #[derive(Debug)]
  2436. struct InternalPromptProgressShared {
  2437. state: Mutex<InternalPromptProgressState>,
  2438. output_lock: Mutex<()>,
  2439. started_at: Instant,
  2440. }
  2441. #[derive(Debug, Clone)]
  2442. struct InternalPromptProgressReporter {
  2443. shared: Arc<InternalPromptProgressShared>,
  2444. }
  2445. #[derive(Debug)]
  2446. struct InternalPromptProgressRun {
  2447. reporter: InternalPromptProgressReporter,
  2448. heartbeat_stop: Option<mpsc::Sender<()>>,
  2449. heartbeat_handle: Option<thread::JoinHandle<()>>,
  2450. }
  2451. impl InternalPromptProgressReporter {
  2452. fn ultraplan(task: &str) -> Self {
  2453. Self {
  2454. shared: Arc::new(InternalPromptProgressShared {
  2455. state: Mutex::new(InternalPromptProgressState {
  2456. command_label: "Ultraplan",
  2457. task_label: task.to_string(),
  2458. step: 0,
  2459. phase: "planning started".to_string(),
  2460. detail: Some(format!("task: {task}")),
  2461. saw_final_text: false,
  2462. }),
  2463. output_lock: Mutex::new(()),
  2464. started_at: Instant::now(),
  2465. }),
  2466. }
  2467. }
  2468. fn emit(&self, event: InternalPromptProgressEvent, error: Option<&str>) {
  2469. let snapshot = self.snapshot();
  2470. let line = format_internal_prompt_progress_line(event, &snapshot, self.elapsed(), error);
  2471. self.write_line(&line);
  2472. }
  2473. fn mark_model_phase(&self) {
  2474. let snapshot = {
  2475. let mut state = self
  2476. .shared
  2477. .state
  2478. .lock()
  2479. .expect("internal prompt progress state poisoned");
  2480. state.step += 1;
  2481. state.phase = if state.step == 1 {
  2482. "analyzing request".to_string()
  2483. } else {
  2484. "reviewing findings".to_string()
  2485. };
  2486. state.detail = Some(format!("task: {}", state.task_label));
  2487. state.clone()
  2488. };
  2489. self.write_line(&format_internal_prompt_progress_line(
  2490. InternalPromptProgressEvent::Update,
  2491. &snapshot,
  2492. self.elapsed(),
  2493. None,
  2494. ));
  2495. }
  2496. fn mark_tool_phase(&self, name: &str, input: &str) {
  2497. let detail = describe_tool_progress(name, input);
  2498. let snapshot = {
  2499. let mut state = self
  2500. .shared
  2501. .state
  2502. .lock()
  2503. .expect("internal prompt progress state poisoned");
  2504. state.step += 1;
  2505. state.phase = format!("running {name}");
  2506. state.detail = Some(detail);
  2507. state.clone()
  2508. };
  2509. self.write_line(&format_internal_prompt_progress_line(
  2510. InternalPromptProgressEvent::Update,
  2511. &snapshot,
  2512. self.elapsed(),
  2513. None,
  2514. ));
  2515. }
  2516. fn mark_text_phase(&self, text: &str) {
  2517. let trimmed = text.trim();
  2518. if trimmed.is_empty() {
  2519. return;
  2520. }
  2521. let detail = truncate_for_summary(first_visible_line(trimmed), 120);
  2522. let snapshot = {
  2523. let mut state = self
  2524. .shared
  2525. .state
  2526. .lock()
  2527. .expect("internal prompt progress state poisoned");
  2528. if state.saw_final_text {
  2529. return;
  2530. }
  2531. state.saw_final_text = true;
  2532. state.step += 1;
  2533. state.phase = "drafting final plan".to_string();
  2534. state.detail = (!detail.is_empty()).then_some(detail);
  2535. state.clone()
  2536. };
  2537. self.write_line(&format_internal_prompt_progress_line(
  2538. InternalPromptProgressEvent::Update,
  2539. &snapshot,
  2540. self.elapsed(),
  2541. None,
  2542. ));
  2543. }
  2544. fn emit_heartbeat(&self) {
  2545. let snapshot = self.snapshot();
  2546. self.write_line(&format_internal_prompt_progress_line(
  2547. InternalPromptProgressEvent::Heartbeat,
  2548. &snapshot,
  2549. self.elapsed(),
  2550. None,
  2551. ));
  2552. }
  2553. fn snapshot(&self) -> InternalPromptProgressState {
  2554. self.shared
  2555. .state
  2556. .lock()
  2557. .expect("internal prompt progress state poisoned")
  2558. .clone()
  2559. }
  2560. fn elapsed(&self) -> Duration {
  2561. self.shared.started_at.elapsed()
  2562. }
  2563. fn write_line(&self, line: &str) {
  2564. let _guard = self
  2565. .shared
  2566. .output_lock
  2567. .lock()
  2568. .expect("internal prompt progress output lock poisoned");
  2569. let mut stdout = io::stdout();
  2570. let _ = writeln!(stdout, "{line}");
  2571. let _ = stdout.flush();
  2572. }
  2573. }
  2574. impl InternalPromptProgressRun {
  2575. fn start_ultraplan(task: &str) -> Self {
  2576. let reporter = InternalPromptProgressReporter::ultraplan(task);
  2577. reporter.emit(InternalPromptProgressEvent::Started, None);
  2578. let (heartbeat_stop, heartbeat_rx) = mpsc::channel();
  2579. let heartbeat_reporter = reporter.clone();
  2580. let heartbeat_handle = thread::spawn(move || loop {
  2581. match heartbeat_rx.recv_timeout(INTERNAL_PROGRESS_HEARTBEAT_INTERVAL) {
  2582. Ok(()) | Err(RecvTimeoutError::Disconnected) => break,
  2583. Err(RecvTimeoutError::Timeout) => heartbeat_reporter.emit_heartbeat(),
  2584. }
  2585. });
  2586. Self {
  2587. reporter,
  2588. heartbeat_stop: Some(heartbeat_stop),
  2589. heartbeat_handle: Some(heartbeat_handle),
  2590. }
  2591. }
  2592. fn reporter(&self) -> InternalPromptProgressReporter {
  2593. self.reporter.clone()
  2594. }
  2595. fn finish_success(&mut self) {
  2596. self.stop_heartbeat();
  2597. self.reporter
  2598. .emit(InternalPromptProgressEvent::Complete, None);
  2599. }
  2600. fn finish_failure(&mut self, error: &str) {
  2601. self.stop_heartbeat();
  2602. self.reporter
  2603. .emit(InternalPromptProgressEvent::Failed, Some(error));
  2604. }
  2605. fn stop_heartbeat(&mut self) {
  2606. if let Some(sender) = self.heartbeat_stop.take() {
  2607. let _ = sender.send(());
  2608. }
  2609. if let Some(handle) = self.heartbeat_handle.take() {
  2610. let _ = handle.join();
  2611. }
  2612. }
  2613. }
  2614. impl Drop for InternalPromptProgressRun {
  2615. fn drop(&mut self) {
  2616. self.stop_heartbeat();
  2617. }
  2618. }
  2619. fn format_internal_prompt_progress_line(
  2620. event: InternalPromptProgressEvent,
  2621. snapshot: &InternalPromptProgressState,
  2622. elapsed: Duration,
  2623. error: Option<&str>,
  2624. ) -> String {
  2625. let elapsed_seconds = elapsed.as_secs();
  2626. let step_label = if snapshot.step == 0 {
  2627. "current step pending".to_string()
  2628. } else {
  2629. format!("current step {}", snapshot.step)
  2630. };
  2631. let mut status_bits = vec![step_label, format!("phase {}", snapshot.phase)];
  2632. if let Some(detail) = snapshot
  2633. .detail
  2634. .as_deref()
  2635. .filter(|detail| !detail.is_empty())
  2636. {
  2637. status_bits.push(detail.to_string());
  2638. }
  2639. let status = status_bits.join(" · ");
  2640. match event {
  2641. InternalPromptProgressEvent::Started => {
  2642. format!(
  2643. "🧭 {} status · planning started · {status}",
  2644. snapshot.command_label
  2645. )
  2646. }
  2647. InternalPromptProgressEvent::Update => {
  2648. format!("… {} status · {status}", snapshot.command_label)
  2649. }
  2650. InternalPromptProgressEvent::Heartbeat => format!(
  2651. "… {} heartbeat · {elapsed_seconds}s elapsed · {status}",
  2652. snapshot.command_label
  2653. ),
  2654. InternalPromptProgressEvent::Complete => format!(
  2655. "✔ {} status · completed · {elapsed_seconds}s elapsed · {} steps total",
  2656. snapshot.command_label, snapshot.step
  2657. ),
  2658. InternalPromptProgressEvent::Failed => format!(
  2659. "✘ {} status · failed · {elapsed_seconds}s elapsed · {}",
  2660. snapshot.command_label,
  2661. error.unwrap_or("unknown error")
  2662. ),
  2663. }
  2664. }
  2665. fn describe_tool_progress(name: &str, input: &str) -> String {
  2666. let parsed: serde_json::Value =
  2667. serde_json::from_str(input).unwrap_or(serde_json::Value::String(input.to_string()));
  2668. match name {
  2669. "bash" | "Bash" => {
  2670. let command = parsed
  2671. .get("command")
  2672. .and_then(|value| value.as_str())
  2673. .unwrap_or_default();
  2674. if command.is_empty() {
  2675. "running shell command".to_string()
  2676. } else {
  2677. format!("command {}", truncate_for_summary(command.trim(), 100))
  2678. }
  2679. }
  2680. "read_file" | "Read" => format!("reading {}", extract_tool_path(&parsed)),
  2681. "write_file" | "Write" => format!("writing {}", extract_tool_path(&parsed)),
  2682. "edit_file" | "Edit" => format!("editing {}", extract_tool_path(&parsed)),
  2683. "glob_search" | "Glob" => {
  2684. let pattern = parsed
  2685. .get("pattern")
  2686. .and_then(|value| value.as_str())
  2687. .unwrap_or("?");
  2688. let scope = parsed
  2689. .get("path")
  2690. .and_then(|value| value.as_str())
  2691. .unwrap_or(".");
  2692. format!("glob `{pattern}` in {scope}")
  2693. }
  2694. "grep_search" | "Grep" => {
  2695. let pattern = parsed
  2696. .get("pattern")
  2697. .and_then(|value| value.as_str())
  2698. .unwrap_or("?");
  2699. let scope = parsed
  2700. .get("path")
  2701. .and_then(|value| value.as_str())
  2702. .unwrap_or(".");
  2703. format!("grep `{pattern}` in {scope}")
  2704. }
  2705. "web_search" | "WebSearch" => parsed
  2706. .get("query")
  2707. .and_then(|value| value.as_str())
  2708. .map_or_else(
  2709. || "running web search".to_string(),
  2710. |query| format!("query {}", truncate_for_summary(query, 100)),
  2711. ),
  2712. _ => {
  2713. let summary = summarize_tool_payload(input);
  2714. if summary.is_empty() {
  2715. format!("running {name}")
  2716. } else {
  2717. format!("{name}: {summary}")
  2718. }
  2719. }
  2720. }
  2721. }
  2722. #[allow(clippy::needless_pass_by_value)]
  2723. #[allow(clippy::too_many_arguments)]
  2724. fn build_runtime(
  2725. session: Session,
  2726. model: String,
  2727. system_prompt: Vec<String>,
  2728. enable_tools: bool,
  2729. emit_output: bool,
  2730. allowed_tools: Option<AllowedToolSet>,
  2731. permission_mode: PermissionMode,
  2732. progress_reporter: Option<InternalPromptProgressReporter>,
  2733. ) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>> {
  2734. let (feature_config, tool_registry) = build_runtime_plugin_state()?;
  2735. Ok(ConversationRuntime::new_with_features(
  2736. session,
  2737. AnthropicRuntimeClient::new(
  2738. model,
  2739. enable_tools,
  2740. emit_output,
  2741. allowed_tools.clone(),
  2742. tool_registry.clone(),
  2743. progress_reporter,
  2744. )?,
  2745. CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),
  2746. permission_policy(permission_mode, &tool_registry),
  2747. system_prompt,
  2748. feature_config,
  2749. ))
  2750. }
  2751. struct CliPermissionPrompter {
  2752. current_mode: PermissionMode,
  2753. }
  2754. impl CliPermissionPrompter {
  2755. fn new(current_mode: PermissionMode) -> Self {
  2756. Self { current_mode }
  2757. }
  2758. }
  2759. impl runtime::PermissionPrompter for CliPermissionPrompter {
  2760. fn decide(
  2761. &mut self,
  2762. request: &runtime::PermissionRequest,
  2763. ) -> runtime::PermissionPromptDecision {
  2764. println!();
  2765. println!("Permission approval required");
  2766. println!(" Tool {}", request.tool_name);
  2767. println!(" Current mode {}", self.current_mode.as_str());
  2768. println!(" Required mode {}", request.required_mode.as_str());
  2769. println!(" Input {}", request.input);
  2770. print!("Approve this tool call? [y/N]: ");
  2771. let _ = io::stdout().flush();
  2772. let mut response = String::new();
  2773. match io::stdin().read_line(&mut response) {
  2774. Ok(_) => {
  2775. let normalized = response.trim().to_ascii_lowercase();
  2776. if matches!(normalized.as_str(), "y" | "yes") {
  2777. runtime::PermissionPromptDecision::Allow
  2778. } else {
  2779. runtime::PermissionPromptDecision::Deny {
  2780. reason: format!(
  2781. "tool '{}' denied by user approval prompt",
  2782. request.tool_name
  2783. ),
  2784. }
  2785. }
  2786. }
  2787. Err(error) => runtime::PermissionPromptDecision::Deny {
  2788. reason: format!("permission approval failed: {error}"),
  2789. },
  2790. }
  2791. }
  2792. }
  2793. struct AnthropicRuntimeClient {
  2794. runtime: tokio::runtime::Runtime,
  2795. client: AnthropicClient,
  2796. model: String,
  2797. enable_tools: bool,
  2798. emit_output: bool,
  2799. allowed_tools: Option<AllowedToolSet>,
  2800. tool_registry: GlobalToolRegistry,
  2801. progress_reporter: Option<InternalPromptProgressReporter>,
  2802. }
  2803. impl AnthropicRuntimeClient {
  2804. fn new(
  2805. model: String,
  2806. enable_tools: bool,
  2807. emit_output: bool,
  2808. allowed_tools: Option<AllowedToolSet>,
  2809. tool_registry: GlobalToolRegistry,
  2810. progress_reporter: Option<InternalPromptProgressReporter>,
  2811. ) -> Result<Self, Box<dyn std::error::Error>> {
  2812. Ok(Self {
  2813. runtime: tokio::runtime::Runtime::new()?,
  2814. client: AnthropicClient::from_auth(resolve_cli_auth_source()?)
  2815. .with_base_url(api::read_base_url()),
  2816. model,
  2817. enable_tools,
  2818. emit_output,
  2819. allowed_tools,
  2820. tool_registry,
  2821. progress_reporter,
  2822. })
  2823. }
  2824. }
  2825. fn resolve_cli_auth_source() -> Result<AuthSource, Box<dyn std::error::Error>> {
  2826. Ok(resolve_startup_auth_source(|| {
  2827. let cwd = env::current_dir().map_err(api::ApiError::from)?;
  2828. let config = ConfigLoader::default_for(&cwd).load().map_err(|error| {
  2829. api::ApiError::Auth(format!("failed to load runtime OAuth config: {error}"))
  2830. })?;
  2831. Ok(config.oauth().cloned())
  2832. })?)
  2833. }
  2834. impl ApiClient for AnthropicRuntimeClient {
  2835. #[allow(clippy::too_many_lines)]
  2836. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  2837. if let Some(progress_reporter) = &self.progress_reporter {
  2838. progress_reporter.mark_model_phase();
  2839. }
  2840. let message_request = MessageRequest {
  2841. model: self.model.clone(),
  2842. max_tokens: max_tokens_for_model(&self.model),
  2843. messages: convert_messages(&request.messages),
  2844. system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
  2845. tools: self
  2846. .enable_tools
  2847. .then(|| filter_tool_specs(&self.tool_registry, self.allowed_tools.as_ref())),
  2848. tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
  2849. stream: true,
  2850. };
  2851. self.runtime.block_on(async {
  2852. let mut stream = self
  2853. .client
  2854. .stream_message(&message_request)
  2855. .await
  2856. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2857. let mut stdout = io::stdout();
  2858. let mut sink = io::sink();
  2859. let out: &mut dyn Write = if self.emit_output {
  2860. &mut stdout
  2861. } else {
  2862. &mut sink
  2863. };
  2864. let renderer = TerminalRenderer::new();
  2865. let mut markdown_stream = MarkdownStreamState::default();
  2866. let mut events = Vec::new();
  2867. let mut pending_tool: Option<(String, String, String)> = None;
  2868. let mut saw_stop = false;
  2869. while let Some(event) = stream
  2870. .next_event()
  2871. .await
  2872. .map_err(|error| RuntimeError::new(error.to_string()))?
  2873. {
  2874. match event {
  2875. ApiStreamEvent::MessageStart(start) => {
  2876. for block in start.message.content {
  2877. push_output_block(block, out, &mut events, &mut pending_tool, true)?;
  2878. }
  2879. }
  2880. ApiStreamEvent::ContentBlockStart(start) => {
  2881. push_output_block(
  2882. start.content_block,
  2883. out,
  2884. &mut events,
  2885. &mut pending_tool,
  2886. true,
  2887. )?;
  2888. }
  2889. ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
  2890. ContentBlockDelta::TextDelta { text } => {
  2891. if !text.is_empty() {
  2892. if let Some(progress_reporter) = &self.progress_reporter {
  2893. progress_reporter.mark_text_phase(&text);
  2894. }
  2895. if let Some(rendered) = markdown_stream.push(&renderer, &text) {
  2896. write!(out, "{rendered}")
  2897. .and_then(|()| out.flush())
  2898. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2899. }
  2900. events.push(AssistantEvent::TextDelta(text));
  2901. }
  2902. }
  2903. ContentBlockDelta::InputJsonDelta { partial_json } => {
  2904. if let Some((_, _, input)) = &mut pending_tool {
  2905. input.push_str(&partial_json);
  2906. }
  2907. }
  2908. ContentBlockDelta::ThinkingDelta { .. }
  2909. | ContentBlockDelta::SignatureDelta { .. } => {}
  2910. },
  2911. ApiStreamEvent::ContentBlockStop(_) => {
  2912. if let Some(rendered) = markdown_stream.flush(&renderer) {
  2913. write!(out, "{rendered}")
  2914. .and_then(|()| out.flush())
  2915. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2916. }
  2917. if let Some((id, name, input)) = pending_tool.take() {
  2918. if let Some(progress_reporter) = &self.progress_reporter {
  2919. progress_reporter.mark_tool_phase(&name, &input);
  2920. }
  2921. // Display tool call now that input is fully accumulated
  2922. writeln!(out, "\n{}", format_tool_call_start(&name, &input))
  2923. .and_then(|()| out.flush())
  2924. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2925. events.push(AssistantEvent::ToolUse { id, name, input });
  2926. }
  2927. }
  2928. ApiStreamEvent::MessageDelta(delta) => {
  2929. events.push(AssistantEvent::Usage(TokenUsage {
  2930. input_tokens: delta.usage.input_tokens,
  2931. output_tokens: delta.usage.output_tokens,
  2932. cache_creation_input_tokens: 0,
  2933. cache_read_input_tokens: 0,
  2934. }));
  2935. }
  2936. ApiStreamEvent::MessageStop(_) => {
  2937. saw_stop = true;
  2938. if let Some(rendered) = markdown_stream.flush(&renderer) {
  2939. write!(out, "{rendered}")
  2940. .and_then(|()| out.flush())
  2941. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2942. }
  2943. events.push(AssistantEvent::MessageStop);
  2944. }
  2945. }
  2946. }
  2947. if !saw_stop
  2948. && events.iter().any(|event| {
  2949. matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
  2950. || matches!(event, AssistantEvent::ToolUse { .. })
  2951. })
  2952. {
  2953. events.push(AssistantEvent::MessageStop);
  2954. }
  2955. if events
  2956. .iter()
  2957. .any(|event| matches!(event, AssistantEvent::MessageStop))
  2958. {
  2959. return Ok(events);
  2960. }
  2961. let response = self
  2962. .client
  2963. .send_message(&MessageRequest {
  2964. stream: false,
  2965. ..message_request.clone()
  2966. })
  2967. .await
  2968. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2969. response_to_events(response, out)
  2970. })
  2971. }
  2972. }
  2973. fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
  2974. summary
  2975. .assistant_messages
  2976. .last()
  2977. .map(|message| {
  2978. message
  2979. .blocks
  2980. .iter()
  2981. .filter_map(|block| match block {
  2982. ContentBlock::Text { text } => Some(text.as_str()),
  2983. _ => None,
  2984. })
  2985. .collect::<Vec<_>>()
  2986. .join("")
  2987. })
  2988. .unwrap_or_default()
  2989. }
  2990. fn collect_tool_uses(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  2991. summary
  2992. .assistant_messages
  2993. .iter()
  2994. .flat_map(|message| message.blocks.iter())
  2995. .filter_map(|block| match block {
  2996. ContentBlock::ToolUse { id, name, input } => Some(json!({
  2997. "id": id,
  2998. "name": name,
  2999. "input": input,
  3000. })),
  3001. _ => None,
  3002. })
  3003. .collect()
  3004. }
  3005. fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  3006. summary
  3007. .tool_results
  3008. .iter()
  3009. .flat_map(|message| message.blocks.iter())
  3010. .filter_map(|block| match block {
  3011. ContentBlock::ToolResult {
  3012. tool_use_id,
  3013. tool_name,
  3014. output,
  3015. is_error,
  3016. } => Some(json!({
  3017. "tool_use_id": tool_use_id,
  3018. "tool_name": tool_name,
  3019. "output": output,
  3020. "is_error": is_error,
  3021. })),
  3022. _ => None,
  3023. })
  3024. .collect()
  3025. }
  3026. fn slash_command_completion_candidates() -> Vec<String> {
  3027. slash_command_specs()
  3028. .iter()
  3029. .flat_map(|spec| {
  3030. std::iter::once(spec.name)
  3031. .chain(spec.aliases.iter().copied())
  3032. .map(|name| format!("/{name}"))
  3033. .collect::<Vec<_>>()
  3034. })
  3035. .collect()
  3036. }
  3037. fn format_tool_call_start(name: &str, input: &str) -> String {
  3038. let parsed: serde_json::Value =
  3039. serde_json::from_str(input).unwrap_or(serde_json::Value::String(input.to_string()));
  3040. let detail = match name {
  3041. "bash" | "Bash" => format_bash_call(&parsed),
  3042. "read_file" | "Read" => {
  3043. let path = extract_tool_path(&parsed);
  3044. format!("\x1b[2m📄 Reading {path}…\x1b[0m")
  3045. }
  3046. "write_file" | "Write" => {
  3047. let path = extract_tool_path(&parsed);
  3048. let lines = parsed
  3049. .get("content")
  3050. .and_then(|value| value.as_str())
  3051. .map_or(0, |content| content.lines().count());
  3052. format!("\x1b[1;32m✏️ Writing {path}\x1b[0m \x1b[2m({lines} lines)\x1b[0m")
  3053. }
  3054. "edit_file" | "Edit" => {
  3055. let path = extract_tool_path(&parsed);
  3056. let old_value = parsed
  3057. .get("old_string")
  3058. .or_else(|| parsed.get("oldString"))
  3059. .and_then(|value| value.as_str())
  3060. .unwrap_or_default();
  3061. let new_value = parsed
  3062. .get("new_string")
  3063. .or_else(|| parsed.get("newString"))
  3064. .and_then(|value| value.as_str())
  3065. .unwrap_or_default();
  3066. format!(
  3067. "\x1b[1;33m📝 Editing {path}\x1b[0m{}",
  3068. format_patch_preview(old_value, new_value)
  3069. .map(|preview| format!("\n{preview}"))
  3070. .unwrap_or_default()
  3071. )
  3072. }
  3073. "glob_search" | "Glob" => format_search_start("🔎 Glob", &parsed),
  3074. "grep_search" | "Grep" => format_search_start("🔎 Grep", &parsed),
  3075. "web_search" | "WebSearch" => parsed
  3076. .get("query")
  3077. .and_then(|value| value.as_str())
  3078. .unwrap_or("?")
  3079. .to_string(),
  3080. _ => summarize_tool_payload(input),
  3081. };
  3082. let border = "─".repeat(name.len() + 8);
  3083. format!(
  3084. "\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"
  3085. )
  3086. }
  3087. fn format_tool_result(name: &str, output: &str, is_error: bool) -> String {
  3088. let icon = if is_error {
  3089. "\x1b[1;31m✗\x1b[0m"
  3090. } else {
  3091. "\x1b[1;32m✓\x1b[0m"
  3092. };
  3093. if is_error {
  3094. let summary = truncate_for_summary(output.trim(), 160);
  3095. return if summary.is_empty() {
  3096. format!("{icon} \x1b[38;5;245m{name}\x1b[0m")
  3097. } else {
  3098. format!("{icon} \x1b[38;5;245m{name}\x1b[0m\n\x1b[38;5;203m{summary}\x1b[0m")
  3099. };
  3100. }
  3101. let parsed: serde_json::Value =
  3102. serde_json::from_str(output).unwrap_or(serde_json::Value::String(output.to_string()));
  3103. match name {
  3104. "bash" | "Bash" => format_bash_result(icon, &parsed),
  3105. "read_file" | "Read" => format_read_result(icon, &parsed),
  3106. "write_file" | "Write" => format_write_result(icon, &parsed),
  3107. "edit_file" | "Edit" => format_edit_result(icon, &parsed),
  3108. "glob_search" | "Glob" => format_glob_result(icon, &parsed),
  3109. "grep_search" | "Grep" => format_grep_result(icon, &parsed),
  3110. _ => format_generic_tool_result(icon, name, &parsed),
  3111. }
  3112. }
  3113. const DISPLAY_TRUNCATION_NOTICE: &str =
  3114. "\x1b[2m… output truncated for display; full result preserved in session.\x1b[0m";
  3115. const READ_DISPLAY_MAX_LINES: usize = 80;
  3116. const READ_DISPLAY_MAX_CHARS: usize = 6_000;
  3117. const TOOL_OUTPUT_DISPLAY_MAX_LINES: usize = 60;
  3118. const TOOL_OUTPUT_DISPLAY_MAX_CHARS: usize = 4_000;
  3119. fn extract_tool_path(parsed: &serde_json::Value) -> String {
  3120. parsed
  3121. .get("file_path")
  3122. .or_else(|| parsed.get("filePath"))
  3123. .or_else(|| parsed.get("path"))
  3124. .and_then(|value| value.as_str())
  3125. .unwrap_or("?")
  3126. .to_string()
  3127. }
  3128. fn format_search_start(label: &str, parsed: &serde_json::Value) -> String {
  3129. let pattern = parsed
  3130. .get("pattern")
  3131. .and_then(|value| value.as_str())
  3132. .unwrap_or("?");
  3133. let scope = parsed
  3134. .get("path")
  3135. .and_then(|value| value.as_str())
  3136. .unwrap_or(".");
  3137. format!("{label} {pattern}\n\x1b[2min {scope}\x1b[0m")
  3138. }
  3139. fn format_patch_preview(old_value: &str, new_value: &str) -> Option<String> {
  3140. if old_value.is_empty() && new_value.is_empty() {
  3141. return None;
  3142. }
  3143. Some(format!(
  3144. "\x1b[38;5;203m- {}\x1b[0m\n\x1b[38;5;70m+ {}\x1b[0m",
  3145. truncate_for_summary(first_visible_line(old_value), 72),
  3146. truncate_for_summary(first_visible_line(new_value), 72)
  3147. ))
  3148. }
  3149. fn format_bash_call(parsed: &serde_json::Value) -> String {
  3150. let command = parsed
  3151. .get("command")
  3152. .and_then(|value| value.as_str())
  3153. .unwrap_or_default();
  3154. if command.is_empty() {
  3155. String::new()
  3156. } else {
  3157. format!(
  3158. "\x1b[48;5;236;38;5;255m $ {} \x1b[0m",
  3159. truncate_for_summary(command, 160)
  3160. )
  3161. }
  3162. }
  3163. fn first_visible_line(text: &str) -> &str {
  3164. text.lines()
  3165. .find(|line| !line.trim().is_empty())
  3166. .unwrap_or(text)
  3167. }
  3168. fn format_bash_result(icon: &str, parsed: &serde_json::Value) -> String {
  3169. let mut lines = vec![format!("{icon} \x1b[38;5;245mbash\x1b[0m")];
  3170. if let Some(task_id) = parsed
  3171. .get("backgroundTaskId")
  3172. .and_then(|value| value.as_str())
  3173. {
  3174. write!(&mut lines[0], " backgrounded ({task_id})").expect("write to string");
  3175. } else if let Some(status) = parsed
  3176. .get("returnCodeInterpretation")
  3177. .and_then(|value| value.as_str())
  3178. .filter(|status| !status.is_empty())
  3179. {
  3180. write!(&mut lines[0], " {status}").expect("write to string");
  3181. }
  3182. if let Some(stdout) = parsed.get("stdout").and_then(|value| value.as_str()) {
  3183. if !stdout.trim().is_empty() {
  3184. lines.push(truncate_output_for_display(
  3185. stdout,
  3186. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  3187. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  3188. ));
  3189. }
  3190. }
  3191. if let Some(stderr) = parsed.get("stderr").and_then(|value| value.as_str()) {
  3192. if !stderr.trim().is_empty() {
  3193. lines.push(format!(
  3194. "\x1b[38;5;203m{}\x1b[0m",
  3195. truncate_output_for_display(
  3196. stderr,
  3197. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  3198. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  3199. )
  3200. ));
  3201. }
  3202. }
  3203. lines.join("\n\n")
  3204. }
  3205. fn format_read_result(icon: &str, parsed: &serde_json::Value) -> String {
  3206. let file = parsed.get("file").unwrap_or(parsed);
  3207. let path = extract_tool_path(file);
  3208. let start_line = file
  3209. .get("startLine")
  3210. .and_then(serde_json::Value::as_u64)
  3211. .unwrap_or(1);
  3212. let num_lines = file
  3213. .get("numLines")
  3214. .and_then(serde_json::Value::as_u64)
  3215. .unwrap_or(0);
  3216. let total_lines = file
  3217. .get("totalLines")
  3218. .and_then(serde_json::Value::as_u64)
  3219. .unwrap_or(num_lines);
  3220. let content = file
  3221. .get("content")
  3222. .and_then(|value| value.as_str())
  3223. .unwrap_or_default();
  3224. let end_line = start_line.saturating_add(num_lines.saturating_sub(1));
  3225. format!(
  3226. "{icon} \x1b[2m📄 Read {path} (lines {}-{} of {})\x1b[0m\n{}",
  3227. start_line,
  3228. end_line.max(start_line),
  3229. total_lines,
  3230. truncate_output_for_display(content, READ_DISPLAY_MAX_LINES, READ_DISPLAY_MAX_CHARS)
  3231. )
  3232. }
  3233. fn format_write_result(icon: &str, parsed: &serde_json::Value) -> String {
  3234. let path = extract_tool_path(parsed);
  3235. let kind = parsed
  3236. .get("type")
  3237. .and_then(|value| value.as_str())
  3238. .unwrap_or("write");
  3239. let line_count = parsed
  3240. .get("content")
  3241. .and_then(|value| value.as_str())
  3242. .map_or(0, |content| content.lines().count());
  3243. format!(
  3244. "{icon} \x1b[1;32m✏️ {} {path}\x1b[0m \x1b[2m({line_count} lines)\x1b[0m",
  3245. if kind == "create" { "Wrote" } else { "Updated" },
  3246. )
  3247. }
  3248. fn format_structured_patch_preview(parsed: &serde_json::Value) -> Option<String> {
  3249. let hunks = parsed.get("structuredPatch")?.as_array()?;
  3250. let mut preview = Vec::new();
  3251. for hunk in hunks.iter().take(2) {
  3252. let lines = hunk.get("lines")?.as_array()?;
  3253. for line in lines.iter().filter_map(|value| value.as_str()).take(6) {
  3254. match line.chars().next() {
  3255. Some('+') => preview.push(format!("\x1b[38;5;70m{line}\x1b[0m")),
  3256. Some('-') => preview.push(format!("\x1b[38;5;203m{line}\x1b[0m")),
  3257. _ => preview.push(line.to_string()),
  3258. }
  3259. }
  3260. }
  3261. if preview.is_empty() {
  3262. None
  3263. } else {
  3264. Some(preview.join("\n"))
  3265. }
  3266. }
  3267. fn format_edit_result(icon: &str, parsed: &serde_json::Value) -> String {
  3268. let path = extract_tool_path(parsed);
  3269. let suffix = if parsed
  3270. .get("replaceAll")
  3271. .and_then(serde_json::Value::as_bool)
  3272. .unwrap_or(false)
  3273. {
  3274. " (replace all)"
  3275. } else {
  3276. ""
  3277. };
  3278. let preview = format_structured_patch_preview(parsed).or_else(|| {
  3279. let old_value = parsed
  3280. .get("oldString")
  3281. .and_then(|value| value.as_str())
  3282. .unwrap_or_default();
  3283. let new_value = parsed
  3284. .get("newString")
  3285. .and_then(|value| value.as_str())
  3286. .unwrap_or_default();
  3287. format_patch_preview(old_value, new_value)
  3288. });
  3289. match preview {
  3290. Some(preview) => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m\n{preview}"),
  3291. None => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m"),
  3292. }
  3293. }
  3294. fn format_glob_result(icon: &str, parsed: &serde_json::Value) -> String {
  3295. let num_files = parsed
  3296. .get("numFiles")
  3297. .and_then(serde_json::Value::as_u64)
  3298. .unwrap_or(0);
  3299. let filenames = parsed
  3300. .get("filenames")
  3301. .and_then(|value| value.as_array())
  3302. .map(|files| {
  3303. files
  3304. .iter()
  3305. .filter_map(|value| value.as_str())
  3306. .take(8)
  3307. .collect::<Vec<_>>()
  3308. .join("\n")
  3309. })
  3310. .unwrap_or_default();
  3311. if filenames.is_empty() {
  3312. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files")
  3313. } else {
  3314. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files\n{filenames}")
  3315. }
  3316. }
  3317. fn format_grep_result(icon: &str, parsed: &serde_json::Value) -> String {
  3318. let num_matches = parsed
  3319. .get("numMatches")
  3320. .and_then(serde_json::Value::as_u64)
  3321. .unwrap_or(0);
  3322. let num_files = parsed
  3323. .get("numFiles")
  3324. .and_then(serde_json::Value::as_u64)
  3325. .unwrap_or(0);
  3326. let content = parsed
  3327. .get("content")
  3328. .and_then(|value| value.as_str())
  3329. .unwrap_or_default();
  3330. let filenames = parsed
  3331. .get("filenames")
  3332. .and_then(|value| value.as_array())
  3333. .map(|files| {
  3334. files
  3335. .iter()
  3336. .filter_map(|value| value.as_str())
  3337. .take(8)
  3338. .collect::<Vec<_>>()
  3339. .join("\n")
  3340. })
  3341. .unwrap_or_default();
  3342. let summary = format!(
  3343. "{icon} \x1b[38;5;245mgrep_search\x1b[0m {num_matches} matches across {num_files} files"
  3344. );
  3345. if !content.trim().is_empty() {
  3346. format!(
  3347. "{summary}\n{}",
  3348. truncate_output_for_display(
  3349. content,
  3350. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  3351. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  3352. )
  3353. )
  3354. } else if !filenames.is_empty() {
  3355. format!("{summary}\n{filenames}")
  3356. } else {
  3357. summary
  3358. }
  3359. }
  3360. fn format_generic_tool_result(icon: &str, name: &str, parsed: &serde_json::Value) -> String {
  3361. let rendered_output = match parsed {
  3362. serde_json::Value::String(text) => text.clone(),
  3363. serde_json::Value::Null => String::new(),
  3364. serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
  3365. serde_json::to_string_pretty(parsed).unwrap_or_else(|_| parsed.to_string())
  3366. }
  3367. _ => parsed.to_string(),
  3368. };
  3369. let preview = truncate_output_for_display(
  3370. &rendered_output,
  3371. TOOL_OUTPUT_DISPLAY_MAX_LINES,
  3372. TOOL_OUTPUT_DISPLAY_MAX_CHARS,
  3373. );
  3374. if preview.is_empty() {
  3375. format!("{icon} \x1b[38;5;245m{name}\x1b[0m")
  3376. } else if preview.contains('\n') {
  3377. format!("{icon} \x1b[38;5;245m{name}\x1b[0m\n{preview}")
  3378. } else {
  3379. format!("{icon} \x1b[38;5;245m{name}:\x1b[0m {preview}")
  3380. }
  3381. }
  3382. fn summarize_tool_payload(payload: &str) -> String {
  3383. let compact = match serde_json::from_str::<serde_json::Value>(payload) {
  3384. Ok(value) => value.to_string(),
  3385. Err(_) => payload.trim().to_string(),
  3386. };
  3387. truncate_for_summary(&compact, 96)
  3388. }
  3389. fn truncate_for_summary(value: &str, limit: usize) -> String {
  3390. let mut chars = value.chars();
  3391. let truncated = chars.by_ref().take(limit).collect::<String>();
  3392. if chars.next().is_some() {
  3393. format!("{truncated}…")
  3394. } else {
  3395. truncated
  3396. }
  3397. }
  3398. fn truncate_output_for_display(content: &str, max_lines: usize, max_chars: usize) -> String {
  3399. let original = content.trim_end_matches('\n');
  3400. if original.is_empty() {
  3401. return String::new();
  3402. }
  3403. let mut preview_lines = Vec::new();
  3404. let mut used_chars = 0usize;
  3405. let mut truncated = false;
  3406. for (index, line) in original.lines().enumerate() {
  3407. if index >= max_lines {
  3408. truncated = true;
  3409. break;
  3410. }
  3411. let newline_cost = usize::from(!preview_lines.is_empty());
  3412. let available = max_chars.saturating_sub(used_chars + newline_cost);
  3413. if available == 0 {
  3414. truncated = true;
  3415. break;
  3416. }
  3417. let line_chars = line.chars().count();
  3418. if line_chars > available {
  3419. preview_lines.push(line.chars().take(available).collect::<String>());
  3420. truncated = true;
  3421. break;
  3422. }
  3423. preview_lines.push(line.to_string());
  3424. used_chars += newline_cost + line_chars;
  3425. }
  3426. let mut preview = preview_lines.join("\n");
  3427. if truncated {
  3428. if !preview.is_empty() {
  3429. preview.push('\n');
  3430. }
  3431. preview.push_str(DISPLAY_TRUNCATION_NOTICE);
  3432. }
  3433. preview
  3434. }
  3435. fn push_output_block(
  3436. block: OutputContentBlock,
  3437. out: &mut (impl Write + ?Sized),
  3438. events: &mut Vec<AssistantEvent>,
  3439. pending_tool: &mut Option<(String, String, String)>,
  3440. streaming_tool_input: bool,
  3441. ) -> Result<(), RuntimeError> {
  3442. match block {
  3443. OutputContentBlock::Text { text } => {
  3444. if !text.is_empty() {
  3445. let rendered = TerminalRenderer::new().markdown_to_ansi(&text);
  3446. write!(out, "{rendered}")
  3447. .and_then(|()| out.flush())
  3448. .map_err(|error| RuntimeError::new(error.to_string()))?;
  3449. events.push(AssistantEvent::TextDelta(text));
  3450. }
  3451. }
  3452. OutputContentBlock::ToolUse { id, name, input } => {
  3453. // During streaming, the initial content_block_start has an empty input ({}).
  3454. // The real input arrives via input_json_delta events. In
  3455. // non-streaming responses, preserve a legitimate empty object.
  3456. let initial_input = if streaming_tool_input
  3457. && input.is_object()
  3458. && input.as_object().is_some_and(serde_json::Map::is_empty)
  3459. {
  3460. String::new()
  3461. } else {
  3462. input.to_string()
  3463. };
  3464. *pending_tool = Some((id, name, initial_input));
  3465. }
  3466. OutputContentBlock::Thinking { .. } | OutputContentBlock::RedactedThinking { .. } => {}
  3467. }
  3468. Ok(())
  3469. }
  3470. fn response_to_events(
  3471. response: MessageResponse,
  3472. out: &mut (impl Write + ?Sized),
  3473. ) -> Result<Vec<AssistantEvent>, RuntimeError> {
  3474. let mut events = Vec::new();
  3475. let mut pending_tool = None;
  3476. for block in response.content {
  3477. push_output_block(block, out, &mut events, &mut pending_tool, false)?;
  3478. if let Some((id, name, input)) = pending_tool.take() {
  3479. events.push(AssistantEvent::ToolUse { id, name, input });
  3480. }
  3481. }
  3482. events.push(AssistantEvent::Usage(TokenUsage {
  3483. input_tokens: response.usage.input_tokens,
  3484. output_tokens: response.usage.output_tokens,
  3485. cache_creation_input_tokens: response.usage.cache_creation_input_tokens,
  3486. cache_read_input_tokens: response.usage.cache_read_input_tokens,
  3487. }));
  3488. events.push(AssistantEvent::MessageStop);
  3489. Ok(events)
  3490. }
  3491. struct CliToolExecutor {
  3492. renderer: TerminalRenderer,
  3493. emit_output: bool,
  3494. allowed_tools: Option<AllowedToolSet>,
  3495. tool_registry: GlobalToolRegistry,
  3496. }
  3497. impl CliToolExecutor {
  3498. fn new(
  3499. allowed_tools: Option<AllowedToolSet>,
  3500. emit_output: bool,
  3501. tool_registry: GlobalToolRegistry,
  3502. ) -> Self {
  3503. Self {
  3504. renderer: TerminalRenderer::new(),
  3505. emit_output,
  3506. allowed_tools,
  3507. tool_registry,
  3508. }
  3509. }
  3510. }
  3511. impl ToolExecutor for CliToolExecutor {
  3512. fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
  3513. if self
  3514. .allowed_tools
  3515. .as_ref()
  3516. .is_some_and(|allowed| !allowed.contains(tool_name))
  3517. {
  3518. return Err(ToolError::new(format!(
  3519. "tool `{tool_name}` is not enabled by the current --allowedTools setting"
  3520. )));
  3521. }
  3522. let value = serde_json::from_str(input)
  3523. .map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
  3524. match self.tool_registry.execute(tool_name, &value) {
  3525. Ok(output) => {
  3526. if self.emit_output {
  3527. let markdown = format_tool_result(tool_name, &output, false);
  3528. self.renderer
  3529. .stream_markdown(&markdown, &mut io::stdout())
  3530. .map_err(|error| ToolError::new(error.to_string()))?;
  3531. }
  3532. Ok(output)
  3533. }
  3534. Err(error) => {
  3535. if self.emit_output {
  3536. let markdown = format_tool_result(tool_name, &error, true);
  3537. self.renderer
  3538. .stream_markdown(&markdown, &mut io::stdout())
  3539. .map_err(|stream_error| ToolError::new(stream_error.to_string()))?;
  3540. }
  3541. Err(ToolError::new(error))
  3542. }
  3543. }
  3544. }
  3545. }
  3546. fn permission_policy(mode: PermissionMode, tool_registry: &GlobalToolRegistry) -> PermissionPolicy {
  3547. tool_registry.permission_specs(None).into_iter().fold(
  3548. PermissionPolicy::new(mode),
  3549. |policy, (name, required_permission)| {
  3550. policy.with_tool_requirement(name, required_permission)
  3551. },
  3552. )
  3553. }
  3554. fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
  3555. messages
  3556. .iter()
  3557. .filter_map(|message| {
  3558. let role = match message.role {
  3559. MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
  3560. MessageRole::Assistant => "assistant",
  3561. };
  3562. let content = message
  3563. .blocks
  3564. .iter()
  3565. .map(|block| match block {
  3566. ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
  3567. ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
  3568. id: id.clone(),
  3569. name: name.clone(),
  3570. input: serde_json::from_str(input)
  3571. .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
  3572. },
  3573. ContentBlock::ToolResult {
  3574. tool_use_id,
  3575. output,
  3576. is_error,
  3577. ..
  3578. } => InputContentBlock::ToolResult {
  3579. tool_use_id: tool_use_id.clone(),
  3580. content: vec![ToolResultContentBlock::Text {
  3581. text: output.clone(),
  3582. }],
  3583. is_error: *is_error,
  3584. },
  3585. })
  3586. .collect::<Vec<_>>();
  3587. (!content.is_empty()).then(|| InputMessage {
  3588. role: role.to_string(),
  3589. content,
  3590. })
  3591. })
  3592. .collect()
  3593. }
  3594. fn print_help_to(out: &mut impl Write) -> io::Result<()> {
  3595. writeln!(out, "claw v{VERSION}")?;
  3596. writeln!(out)?;
  3597. writeln!(out, "Usage:")?;
  3598. writeln!(
  3599. out,
  3600. " claw [--model MODEL] [--allowedTools TOOL[,TOOL...]]"
  3601. )?;
  3602. writeln!(out, " Start the interactive REPL")?;
  3603. writeln!(
  3604. out,
  3605. " claw [--model MODEL] [--output-format text|json] prompt TEXT"
  3606. )?;
  3607. writeln!(out, " Send one prompt and exit")?;
  3608. writeln!(
  3609. out,
  3610. " claw [--model MODEL] [--output-format text|json] TEXT"
  3611. )?;
  3612. writeln!(out, " Shorthand non-interactive prompt mode")?;
  3613. writeln!(
  3614. out,
  3615. " claw --resume SESSION.json [/status] [/compact] [...]"
  3616. )?;
  3617. writeln!(
  3618. out,
  3619. " Inspect or maintain a saved session without entering the REPL"
  3620. )?;
  3621. writeln!(out, " claw dump-manifests")?;
  3622. writeln!(out, " claw bootstrap-plan")?;
  3623. writeln!(out, " claw agents")?;
  3624. writeln!(out, " claw skills")?;
  3625. writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
  3626. writeln!(out, " claw login")?;
  3627. writeln!(out, " claw logout")?;
  3628. writeln!(out, " claw init")?;
  3629. writeln!(out)?;
  3630. writeln!(out, "Flags:")?;
  3631. writeln!(
  3632. out,
  3633. " --model MODEL Override the active model"
  3634. )?;
  3635. writeln!(
  3636. out,
  3637. " --output-format FORMAT Non-interactive output format: text or json"
  3638. )?;
  3639. writeln!(
  3640. out,
  3641. " --permission-mode MODE Set read-only, workspace-write, or danger-full-access"
  3642. )?;
  3643. writeln!(
  3644. out,
  3645. " --dangerously-skip-permissions Skip all permission checks"
  3646. )?;
  3647. writeln!(out, " --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)")?;
  3648. writeln!(
  3649. out,
  3650. " --version, -V Print version and build information locally"
  3651. )?;
  3652. writeln!(out)?;
  3653. writeln!(out, "Interactive slash commands:")?;
  3654. writeln!(out, "{}", render_slash_command_help())?;
  3655. writeln!(out)?;
  3656. let resume_commands = resume_supported_slash_commands()
  3657. .into_iter()
  3658. .map(|spec| match spec.argument_hint {
  3659. Some(argument_hint) => format!("/{} {}", spec.name, argument_hint),
  3660. None => format!("/{}", spec.name),
  3661. })
  3662. .collect::<Vec<_>>()
  3663. .join(", ");
  3664. writeln!(out, "Resume-safe commands: {resume_commands}")?;
  3665. writeln!(out, "Examples:")?;
  3666. writeln!(out, " claw --model claude-opus \"summarize this repo\"")?;
  3667. writeln!(
  3668. out,
  3669. " claw --output-format json prompt \"explain src/main.rs\""
  3670. )?;
  3671. writeln!(
  3672. out,
  3673. " claw --allowedTools read,glob \"summarize Cargo.toml\""
  3674. )?;
  3675. writeln!(
  3676. out,
  3677. " claw --resume session.json /status /diff /export notes.txt"
  3678. )?;
  3679. writeln!(out, " claw agents")?;
  3680. writeln!(out, " claw /skills")?;
  3681. writeln!(out, " claw login")?;
  3682. writeln!(out, " claw init")?;
  3683. Ok(())
  3684. }
  3685. fn print_help() {
  3686. let _ = print_help_to(&mut io::stdout());
  3687. }
  3688. #[cfg(test)]
  3689. mod tests {
  3690. use super::{
  3691. describe_tool_progress, filter_tool_specs, format_compact_report, format_cost_report,
  3692. format_internal_prompt_progress_line, format_model_report, format_model_switch_report,
  3693. format_permissions_report,
  3694. format_permissions_switch_report, format_resume_report, format_status_report,
  3695. format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
  3696. parse_git_status_branch, parse_git_status_metadata, permission_policy, print_help_to,
  3697. push_output_block, render_config_report, render_diff_report, render_memory_report,
  3698. render_repl_help, resolve_model_alias, response_to_events,
  3699. resume_supported_slash_commands, run_resume_command, status_context, CliAction,
  3700. CliOutputFormat, InternalPromptProgressEvent, InternalPromptProgressState, SlashCommand,
  3701. StatusUsage, DEFAULT_MODEL,
  3702. };
  3703. use api::{MessageResponse, OutputContentBlock, Usage};
  3704. use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
  3705. use runtime::{
  3706. AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session,
  3707. };
  3708. use serde_json::json;
  3709. use std::fs;
  3710. use std::path::{Path, PathBuf};
  3711. use std::process::Command;
  3712. use std::sync::{Mutex, MutexGuard, OnceLock};
  3713. use std::time::{Duration, SystemTime, UNIX_EPOCH};
  3714. use tools::GlobalToolRegistry;
  3715. fn registry_with_plugin_tool() -> GlobalToolRegistry {
  3716. GlobalToolRegistry::with_plugin_tools(vec![PluginTool::new(
  3717. "plugin-demo@external",
  3718. "plugin-demo",
  3719. PluginToolDefinition {
  3720. name: "plugin_echo".to_string(),
  3721. description: Some("Echo plugin payload".to_string()),
  3722. input_schema: json!({
  3723. "type": "object",
  3724. "properties": {
  3725. "message": { "type": "string" }
  3726. },
  3727. "required": ["message"],
  3728. "additionalProperties": false
  3729. }),
  3730. },
  3731. "echo".to_string(),
  3732. Vec::new(),
  3733. PluginToolPermission::WorkspaceWrite,
  3734. None,
  3735. )])
  3736. .expect("plugin tool registry should build")
  3737. }
  3738. fn temp_dir() -> PathBuf {
  3739. let nanos = SystemTime::now()
  3740. .duration_since(UNIX_EPOCH)
  3741. .expect("time should be after epoch")
  3742. .as_nanos();
  3743. std::env::temp_dir().join(format!("rusty-claude-cli-{nanos}"))
  3744. }
  3745. fn git(args: &[&str], cwd: &Path) {
  3746. let status = Command::new("git")
  3747. .args(args)
  3748. .current_dir(cwd)
  3749. .status()
  3750. .expect("git command should run");
  3751. assert!(
  3752. status.success(),
  3753. "git command failed: git {}",
  3754. args.join(" ")
  3755. );
  3756. }
  3757. fn env_lock() -> MutexGuard<'static, ()> {
  3758. static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
  3759. LOCK.get_or_init(|| Mutex::new(()))
  3760. .lock()
  3761. .unwrap_or_else(std::sync::PoisonError::into_inner)
  3762. }
  3763. fn with_current_dir<T>(cwd: &Path, f: impl FnOnce() -> T) -> T {
  3764. let previous = std::env::current_dir().expect("cwd should load");
  3765. std::env::set_current_dir(cwd).expect("cwd should change");
  3766. let result = f();
  3767. std::env::set_current_dir(previous).expect("cwd should restore");
  3768. result
  3769. }
  3770. #[test]
  3771. fn defaults_to_repl_when_no_args() {
  3772. assert_eq!(
  3773. parse_args(&[]).expect("args should parse"),
  3774. CliAction::Repl {
  3775. model: DEFAULT_MODEL.to_string(),
  3776. allowed_tools: None,
  3777. permission_mode: PermissionMode::DangerFullAccess,
  3778. }
  3779. );
  3780. }
  3781. #[test]
  3782. fn parses_prompt_subcommand() {
  3783. let args = vec![
  3784. "prompt".to_string(),
  3785. "hello".to_string(),
  3786. "world".to_string(),
  3787. ];
  3788. assert_eq!(
  3789. parse_args(&args).expect("args should parse"),
  3790. CliAction::Prompt {
  3791. prompt: "hello world".to_string(),
  3792. model: DEFAULT_MODEL.to_string(),
  3793. output_format: CliOutputFormat::Text,
  3794. allowed_tools: None,
  3795. permission_mode: PermissionMode::DangerFullAccess,
  3796. }
  3797. );
  3798. }
  3799. #[test]
  3800. fn parses_bare_prompt_and_json_output_flag() {
  3801. let args = vec![
  3802. "--output-format=json".to_string(),
  3803. "--model".to_string(),
  3804. "claude-opus".to_string(),
  3805. "explain".to_string(),
  3806. "this".to_string(),
  3807. ];
  3808. assert_eq!(
  3809. parse_args(&args).expect("args should parse"),
  3810. CliAction::Prompt {
  3811. prompt: "explain this".to_string(),
  3812. model: "claude-opus".to_string(),
  3813. output_format: CliOutputFormat::Json,
  3814. allowed_tools: None,
  3815. permission_mode: PermissionMode::DangerFullAccess,
  3816. }
  3817. );
  3818. }
  3819. #[test]
  3820. fn resolves_model_aliases_in_args() {
  3821. let args = vec![
  3822. "--model".to_string(),
  3823. "opus".to_string(),
  3824. "explain".to_string(),
  3825. "this".to_string(),
  3826. ];
  3827. assert_eq!(
  3828. parse_args(&args).expect("args should parse"),
  3829. CliAction::Prompt {
  3830. prompt: "explain this".to_string(),
  3831. model: "claude-opus-4-6".to_string(),
  3832. output_format: CliOutputFormat::Text,
  3833. allowed_tools: None,
  3834. permission_mode: PermissionMode::DangerFullAccess,
  3835. }
  3836. );
  3837. }
  3838. #[test]
  3839. fn resolves_known_model_aliases() {
  3840. assert_eq!(resolve_model_alias("opus"), "claude-opus-4-6");
  3841. assert_eq!(resolve_model_alias("sonnet"), "claude-sonnet-4-6");
  3842. assert_eq!(resolve_model_alias("haiku"), "claude-haiku-4-5-20251213");
  3843. assert_eq!(resolve_model_alias("claude-opus"), "claude-opus");
  3844. }
  3845. #[test]
  3846. fn parses_version_flags_without_initializing_prompt_mode() {
  3847. assert_eq!(
  3848. parse_args(&["--version".to_string()]).expect("args should parse"),
  3849. CliAction::Version
  3850. );
  3851. assert_eq!(
  3852. parse_args(&["-V".to_string()]).expect("args should parse"),
  3853. CliAction::Version
  3854. );
  3855. }
  3856. #[test]
  3857. fn parses_permission_mode_flag() {
  3858. let args = vec!["--permission-mode=read-only".to_string()];
  3859. assert_eq!(
  3860. parse_args(&args).expect("args should parse"),
  3861. CliAction::Repl {
  3862. model: DEFAULT_MODEL.to_string(),
  3863. allowed_tools: None,
  3864. permission_mode: PermissionMode::ReadOnly,
  3865. }
  3866. );
  3867. }
  3868. #[test]
  3869. fn parses_allowed_tools_flags_with_aliases_and_lists() {
  3870. let args = vec![
  3871. "--allowedTools".to_string(),
  3872. "read,glob".to_string(),
  3873. "--allowed-tools=write_file".to_string(),
  3874. ];
  3875. assert_eq!(
  3876. parse_args(&args).expect("args should parse"),
  3877. CliAction::Repl {
  3878. model: DEFAULT_MODEL.to_string(),
  3879. allowed_tools: Some(
  3880. ["glob_search", "read_file", "write_file"]
  3881. .into_iter()
  3882. .map(str::to_string)
  3883. .collect()
  3884. ),
  3885. permission_mode: PermissionMode::DangerFullAccess,
  3886. }
  3887. );
  3888. }
  3889. #[test]
  3890. fn rejects_unknown_allowed_tools() {
  3891. let error = parse_args(&["--allowedTools".to_string(), "teleport".to_string()])
  3892. .expect_err("tool should be rejected");
  3893. assert!(error.contains("unsupported tool in --allowedTools: teleport"));
  3894. }
  3895. #[test]
  3896. fn parses_system_prompt_options() {
  3897. let args = vec![
  3898. "system-prompt".to_string(),
  3899. "--cwd".to_string(),
  3900. "/tmp/project".to_string(),
  3901. "--date".to_string(),
  3902. "2026-04-01".to_string(),
  3903. ];
  3904. assert_eq!(
  3905. parse_args(&args).expect("args should parse"),
  3906. CliAction::PrintSystemPrompt {
  3907. cwd: PathBuf::from("/tmp/project"),
  3908. date: "2026-04-01".to_string(),
  3909. }
  3910. );
  3911. }
  3912. #[test]
  3913. fn parses_login_and_logout_subcommands() {
  3914. assert_eq!(
  3915. parse_args(&["login".to_string()]).expect("login should parse"),
  3916. CliAction::Login
  3917. );
  3918. assert_eq!(
  3919. parse_args(&["logout".to_string()]).expect("logout should parse"),
  3920. CliAction::Logout
  3921. );
  3922. assert_eq!(
  3923. parse_args(&["init".to_string()]).expect("init should parse"),
  3924. CliAction::Init
  3925. );
  3926. assert_eq!(
  3927. parse_args(&["agents".to_string()]).expect("agents should parse"),
  3928. CliAction::Agents { args: None }
  3929. );
  3930. assert_eq!(
  3931. parse_args(&["skills".to_string()]).expect("skills should parse"),
  3932. CliAction::Skills { args: None }
  3933. );
  3934. assert_eq!(
  3935. parse_args(&["agents".to_string(), "--help".to_string()])
  3936. .expect("agents help should parse"),
  3937. CliAction::Agents {
  3938. args: Some("--help".to_string())
  3939. }
  3940. );
  3941. }
  3942. #[test]
  3943. fn parses_direct_agents_and_skills_slash_commands() {
  3944. assert_eq!(
  3945. parse_args(&["/agents".to_string()]).expect("/agents should parse"),
  3946. CliAction::Agents { args: None }
  3947. );
  3948. assert_eq!(
  3949. parse_args(&["/skills".to_string()]).expect("/skills should parse"),
  3950. CliAction::Skills { args: None }
  3951. );
  3952. assert_eq!(
  3953. parse_args(&["/skills".to_string(), "help".to_string()])
  3954. .expect("/skills help should parse"),
  3955. CliAction::Skills {
  3956. args: Some("help".to_string())
  3957. }
  3958. );
  3959. let error = parse_args(&["/status".to_string()])
  3960. .expect_err("/status should remain REPL-only when invoked directly");
  3961. assert!(error.contains("unsupported direct slash command"));
  3962. }
  3963. #[test]
  3964. fn parses_resume_flag_with_slash_command() {
  3965. let args = vec![
  3966. "--resume".to_string(),
  3967. "session.json".to_string(),
  3968. "/compact".to_string(),
  3969. ];
  3970. assert_eq!(
  3971. parse_args(&args).expect("args should parse"),
  3972. CliAction::ResumeSession {
  3973. session_path: PathBuf::from("session.json"),
  3974. commands: vec!["/compact".to_string()],
  3975. }
  3976. );
  3977. }
  3978. #[test]
  3979. fn parses_resume_flag_with_multiple_slash_commands() {
  3980. let args = vec![
  3981. "--resume".to_string(),
  3982. "session.json".to_string(),
  3983. "/status".to_string(),
  3984. "/compact".to_string(),
  3985. "/cost".to_string(),
  3986. ];
  3987. assert_eq!(
  3988. parse_args(&args).expect("args should parse"),
  3989. CliAction::ResumeSession {
  3990. session_path: PathBuf::from("session.json"),
  3991. commands: vec![
  3992. "/status".to_string(),
  3993. "/compact".to_string(),
  3994. "/cost".to_string(),
  3995. ],
  3996. }
  3997. );
  3998. }
  3999. #[test]
  4000. fn filtered_tool_specs_respect_allowlist() {
  4001. let allowed = ["read_file", "grep_search"]
  4002. .into_iter()
  4003. .map(str::to_string)
  4004. .collect();
  4005. let filtered = filter_tool_specs(&GlobalToolRegistry::builtin(), Some(&allowed));
  4006. let names = filtered
  4007. .into_iter()
  4008. .map(|spec| spec.name)
  4009. .collect::<Vec<_>>();
  4010. assert_eq!(names, vec!["read_file", "grep_search"]);
  4011. }
  4012. #[test]
  4013. fn filtered_tool_specs_include_plugin_tools() {
  4014. let filtered = filter_tool_specs(&registry_with_plugin_tool(), None);
  4015. let names = filtered
  4016. .into_iter()
  4017. .map(|definition| definition.name)
  4018. .collect::<Vec<_>>();
  4019. assert!(names.contains(&"bash".to_string()));
  4020. assert!(names.contains(&"plugin_echo".to_string()));
  4021. }
  4022. #[test]
  4023. fn permission_policy_uses_plugin_tool_permissions() {
  4024. let policy = permission_policy(PermissionMode::ReadOnly, &registry_with_plugin_tool());
  4025. let required = policy.required_mode_for("plugin_echo");
  4026. assert_eq!(required, PermissionMode::WorkspaceWrite);
  4027. }
  4028. #[test]
  4029. fn shared_help_uses_resume_annotation_copy() {
  4030. let help = commands::render_slash_command_help();
  4031. assert!(help.contains("Slash commands"));
  4032. assert!(help.contains("works with --resume SESSION.json"));
  4033. }
  4034. #[test]
  4035. fn repl_help_includes_shared_commands_and_exit() {
  4036. let help = render_repl_help();
  4037. assert!(help.contains("REPL"));
  4038. assert!(help.contains("/help"));
  4039. assert!(help.contains("/status"));
  4040. assert!(help.contains("/sandbox"));
  4041. assert!(help.contains("/model [model]"));
  4042. assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
  4043. assert!(help.contains("/clear [--confirm]"));
  4044. assert!(help.contains("/cost"));
  4045. assert!(help.contains("/resume <session-path>"));
  4046. assert!(help.contains("/config [env|hooks|model|plugins]"));
  4047. assert!(help.contains("/memory"));
  4048. assert!(help.contains("/init"));
  4049. assert!(help.contains("/diff"));
  4050. assert!(help.contains("/version"));
  4051. assert!(help.contains("/export [file]"));
  4052. assert!(help.contains("/session [list|switch <session-id>]"));
  4053. assert!(help.contains(
  4054. "/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
  4055. ));
  4056. assert!(help.contains("aliases: /plugins, /marketplace"));
  4057. assert!(help.contains("/agents"));
  4058. assert!(help.contains("/skills"));
  4059. assert!(help.contains("/exit"));
  4060. }
  4061. #[test]
  4062. fn resume_supported_command_list_matches_expected_surface() {
  4063. let names = resume_supported_slash_commands()
  4064. .into_iter()
  4065. .map(|spec| spec.name)
  4066. .collect::<Vec<_>>();
  4067. assert_eq!(
  4068. names,
  4069. vec![
  4070. "help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
  4071. "init", "diff", "version", "export", "agents", "skills",
  4072. ]
  4073. );
  4074. }
  4075. #[test]
  4076. fn resume_report_uses_sectioned_layout() {
  4077. let report = format_resume_report("session.json", 14, 6);
  4078. assert!(report.contains("Session resumed"));
  4079. assert!(report.contains("Session file session.json"));
  4080. assert!(report.contains("Messages 14"));
  4081. assert!(report.contains("Turns 6"));
  4082. }
  4083. #[test]
  4084. fn compact_report_uses_structured_output() {
  4085. let compacted = format_compact_report(8, 5, false);
  4086. assert!(compacted.contains("Compact"));
  4087. assert!(compacted.contains("Result compacted"));
  4088. assert!(compacted.contains("Messages removed 8"));
  4089. let skipped = format_compact_report(0, 3, true);
  4090. assert!(skipped.contains("Result skipped"));
  4091. }
  4092. #[test]
  4093. fn cost_report_uses_sectioned_layout() {
  4094. let report = format_cost_report(runtime::TokenUsage {
  4095. input_tokens: 20,
  4096. output_tokens: 8,
  4097. cache_creation_input_tokens: 3,
  4098. cache_read_input_tokens: 1,
  4099. });
  4100. assert!(report.contains("Cost"));
  4101. assert!(report.contains("Input tokens 20"));
  4102. assert!(report.contains("Output tokens 8"));
  4103. assert!(report.contains("Cache create 3"));
  4104. assert!(report.contains("Cache read 1"));
  4105. assert!(report.contains("Total tokens 32"));
  4106. }
  4107. #[test]
  4108. fn permissions_report_uses_sectioned_layout() {
  4109. let report = format_permissions_report("workspace-write");
  4110. assert!(report.contains("Permissions"));
  4111. assert!(report.contains("Active mode workspace-write"));
  4112. assert!(report.contains("Modes"));
  4113. assert!(report.contains("read-only ○ available Read/search tools only"));
  4114. assert!(report.contains("workspace-write ● current Edit files inside the workspace"));
  4115. assert!(report.contains("danger-full-access ○ available Unrestricted tool access"));
  4116. }
  4117. #[test]
  4118. fn permissions_switch_report_is_structured() {
  4119. let report = format_permissions_switch_report("read-only", "workspace-write");
  4120. assert!(report.contains("Permissions updated"));
  4121. assert!(report.contains("Result mode switched"));
  4122. assert!(report.contains("Previous mode read-only"));
  4123. assert!(report.contains("Active mode workspace-write"));
  4124. assert!(report.contains("Applies to subsequent tool calls"));
  4125. }
  4126. #[test]
  4127. fn init_help_mentions_direct_subcommand() {
  4128. let mut help = Vec::new();
  4129. print_help_to(&mut help).expect("help should render");
  4130. let help = String::from_utf8(help).expect("help should be utf8");
  4131. assert!(help.contains("claw init"));
  4132. assert!(help.contains("claw agents"));
  4133. assert!(help.contains("claw skills"));
  4134. assert!(help.contains("claw /skills"));
  4135. }
  4136. #[test]
  4137. fn model_report_uses_sectioned_layout() {
  4138. let report = format_model_report("claude-sonnet", 12, 4);
  4139. assert!(report.contains("Model"));
  4140. assert!(report.contains("Current model claude-sonnet"));
  4141. assert!(report.contains("Session messages 12"));
  4142. assert!(report.contains("Switch models with /model <name>"));
  4143. }
  4144. #[test]
  4145. fn model_switch_report_preserves_context_summary() {
  4146. let report = format_model_switch_report("claude-sonnet", "claude-opus", 9);
  4147. assert!(report.contains("Model updated"));
  4148. assert!(report.contains("Previous claude-sonnet"));
  4149. assert!(report.contains("Current claude-opus"));
  4150. assert!(report.contains("Preserved msgs 9"));
  4151. }
  4152. #[test]
  4153. fn status_line_reports_model_and_token_totals() {
  4154. let status = format_status_report(
  4155. "claude-sonnet",
  4156. StatusUsage {
  4157. message_count: 7,
  4158. turns: 3,
  4159. latest: runtime::TokenUsage {
  4160. input_tokens: 5,
  4161. output_tokens: 4,
  4162. cache_creation_input_tokens: 1,
  4163. cache_read_input_tokens: 0,
  4164. },
  4165. cumulative: runtime::TokenUsage {
  4166. input_tokens: 20,
  4167. output_tokens: 8,
  4168. cache_creation_input_tokens: 2,
  4169. cache_read_input_tokens: 1,
  4170. },
  4171. estimated_tokens: 128,
  4172. },
  4173. "workspace-write",
  4174. &super::StatusContext {
  4175. cwd: PathBuf::from("/tmp/project"),
  4176. session_path: Some(PathBuf::from("session.json")),
  4177. loaded_config_files: 2,
  4178. discovered_config_files: 3,
  4179. memory_file_count: 4,
  4180. project_root: Some(PathBuf::from("/tmp")),
  4181. git_branch: Some("main".to_string()),
  4182. sandbox_status: runtime::SandboxStatus::default(),
  4183. },
  4184. );
  4185. assert!(status.contains("Status"));
  4186. assert!(status.contains("Model claude-sonnet"));
  4187. assert!(status.contains("Permission mode workspace-write"));
  4188. assert!(status.contains("Messages 7"));
  4189. assert!(status.contains("Latest total 10"));
  4190. assert!(status.contains("Cumulative total 31"));
  4191. assert!(status.contains("Cwd /tmp/project"));
  4192. assert!(status.contains("Project root /tmp"));
  4193. assert!(status.contains("Git branch main"));
  4194. assert!(status.contains("Session session.json"));
  4195. assert!(status.contains("Config files loaded 2/3"));
  4196. assert!(status.contains("Memory files 4"));
  4197. }
  4198. #[test]
  4199. fn config_report_supports_section_views() {
  4200. let report = render_config_report(Some("env")).expect("config report should render");
  4201. assert!(report.contains("Merged section: env"));
  4202. let plugins_report =
  4203. render_config_report(Some("plugins")).expect("plugins config report should render");
  4204. assert!(plugins_report.contains("Merged section: plugins"));
  4205. }
  4206. #[test]
  4207. fn memory_report_uses_sectioned_layout() {
  4208. let report = render_memory_report().expect("memory report should render");
  4209. assert!(report.contains("Memory"));
  4210. assert!(report.contains("Working directory"));
  4211. assert!(report.contains("Instruction files"));
  4212. assert!(report.contains("Discovered files"));
  4213. }
  4214. #[test]
  4215. fn config_report_uses_sectioned_layout() {
  4216. let report = render_config_report(None).expect("config report should render");
  4217. assert!(report.contains("Config"));
  4218. assert!(report.contains("Discovered files"));
  4219. assert!(report.contains("Merged JSON"));
  4220. }
  4221. #[test]
  4222. fn parses_git_status_metadata() {
  4223. let _guard = env_lock();
  4224. let temp_root = temp_dir();
  4225. fs::create_dir_all(&temp_root).expect("root dir");
  4226. let (project_root, branch) = with_current_dir(&temp_root, || {
  4227. parse_git_status_metadata(Some(
  4228. "## rcc/cli...origin/rcc/cli
  4229. M src/main.rs",
  4230. ))
  4231. });
  4232. assert_eq!(branch.as_deref(), Some("rcc/cli"));
  4233. assert!(project_root.is_none());
  4234. fs::remove_dir_all(temp_root).expect("cleanup temp dir");
  4235. }
  4236. #[test]
  4237. fn parses_detached_head_from_status_snapshot() {
  4238. let _guard = env_lock();
  4239. assert_eq!(
  4240. parse_git_status_branch(Some(
  4241. "## HEAD (no branch)
  4242. M src/main.rs"
  4243. )),
  4244. Some("detached HEAD".to_string())
  4245. );
  4246. }
  4247. #[test]
  4248. fn render_diff_report_shows_clean_tree_for_committed_repo() {
  4249. let _guard = env_lock();
  4250. let root = temp_dir();
  4251. fs::create_dir_all(&root).expect("root dir");
  4252. git(&["init", "--quiet"], &root);
  4253. git(&["config", "user.email", "tests@example.com"], &root);
  4254. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  4255. fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
  4256. git(&["add", "tracked.txt"], &root);
  4257. git(&["commit", "-m", "init", "--quiet"], &root);
  4258. let report = with_current_dir(&root, || {
  4259. render_diff_report().expect("diff report should render")
  4260. });
  4261. assert!(report.contains("clean working tree"));
  4262. fs::remove_dir_all(root).expect("cleanup temp dir");
  4263. }
  4264. #[test]
  4265. fn render_diff_report_includes_staged_and_unstaged_sections() {
  4266. let _guard = env_lock();
  4267. let root = temp_dir();
  4268. fs::create_dir_all(&root).expect("root dir");
  4269. git(&["init", "--quiet"], &root);
  4270. git(&["config", "user.email", "tests@example.com"], &root);
  4271. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  4272. fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
  4273. git(&["add", "tracked.txt"], &root);
  4274. git(&["commit", "-m", "init", "--quiet"], &root);
  4275. fs::write(root.join("tracked.txt"), "hello\nstaged\n").expect("update file");
  4276. git(&["add", "tracked.txt"], &root);
  4277. fs::write(root.join("tracked.txt"), "hello\nstaged\nunstaged\n")
  4278. .expect("update file twice");
  4279. let report = with_current_dir(&root, || {
  4280. render_diff_report().expect("diff report should render")
  4281. });
  4282. assert!(report.contains("Staged changes:"));
  4283. assert!(report.contains("Unstaged changes:"));
  4284. assert!(report.contains("tracked.txt"));
  4285. fs::remove_dir_all(root).expect("cleanup temp dir");
  4286. }
  4287. #[test]
  4288. fn render_diff_report_omits_ignored_files() {
  4289. let _guard = env_lock();
  4290. let root = temp_dir();
  4291. fs::create_dir_all(&root).expect("root dir");
  4292. git(&["init", "--quiet"], &root);
  4293. git(&["config", "user.email", "tests@example.com"], &root);
  4294. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  4295. fs::write(root.join(".gitignore"), ".omx/\nignored.txt\n").expect("write gitignore");
  4296. fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
  4297. git(&["add", ".gitignore", "tracked.txt"], &root);
  4298. git(&["commit", "-m", "init", "--quiet"], &root);
  4299. fs::create_dir_all(root.join(".omx")).expect("write omx dir");
  4300. fs::write(root.join(".omx").join("state.json"), "{}").expect("write ignored omx");
  4301. fs::write(root.join("ignored.txt"), "secret\n").expect("write ignored file");
  4302. fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("write tracked change");
  4303. let report = with_current_dir(&root, || {
  4304. render_diff_report().expect("diff report should render")
  4305. });
  4306. assert!(report.contains("tracked.txt"));
  4307. assert!(!report.contains("+++ b/ignored.txt"));
  4308. assert!(!report.contains("+++ b/.omx/state.json"));
  4309. fs::remove_dir_all(root).expect("cleanup temp dir");
  4310. }
  4311. #[test]
  4312. fn resume_diff_command_renders_report_for_saved_session() {
  4313. let _guard = env_lock();
  4314. let root = temp_dir();
  4315. fs::create_dir_all(&root).expect("root dir");
  4316. git(&["init", "--quiet"], &root);
  4317. git(&["config", "user.email", "tests@example.com"], &root);
  4318. git(&["config", "user.name", "Rusty Claude Tests"], &root);
  4319. fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
  4320. git(&["add", "tracked.txt"], &root);
  4321. git(&["commit", "-m", "init", "--quiet"], &root);
  4322. fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("modify tracked");
  4323. let session_path = root.join("session.json");
  4324. Session::new()
  4325. .save_to_path(&session_path)
  4326. .expect("session should save");
  4327. let session = Session::load_from_path(&session_path).expect("session should load");
  4328. let outcome = with_current_dir(&root, || {
  4329. run_resume_command(&session_path, &session, &SlashCommand::Diff)
  4330. .expect("resume diff should work")
  4331. });
  4332. let message = outcome.message.expect("diff message should exist");
  4333. assert!(message.contains("Unstaged changes:"));
  4334. assert!(message.contains("tracked.txt"));
  4335. fs::remove_dir_all(root).expect("cleanup temp dir");
  4336. }
  4337. #[test]
  4338. fn status_context_reads_real_workspace_metadata() {
  4339. let context = status_context(None).expect("status context should load");
  4340. assert!(context.cwd.is_absolute());
  4341. assert!(context.discovered_config_files >= context.loaded_config_files);
  4342. assert!(context.loaded_config_files <= context.discovered_config_files);
  4343. }
  4344. #[test]
  4345. fn normalizes_supported_permission_modes() {
  4346. assert_eq!(normalize_permission_mode("read-only"), Some("read-only"));
  4347. assert_eq!(
  4348. normalize_permission_mode("workspace-write"),
  4349. Some("workspace-write")
  4350. );
  4351. assert_eq!(
  4352. normalize_permission_mode("danger-full-access"),
  4353. Some("danger-full-access")
  4354. );
  4355. assert_eq!(normalize_permission_mode("unknown"), None);
  4356. }
  4357. #[test]
  4358. fn clear_command_requires_explicit_confirmation_flag() {
  4359. assert_eq!(
  4360. SlashCommand::parse("/clear"),
  4361. Some(SlashCommand::Clear { confirm: false })
  4362. );
  4363. assert_eq!(
  4364. SlashCommand::parse("/clear --confirm"),
  4365. Some(SlashCommand::Clear { confirm: true })
  4366. );
  4367. }
  4368. #[test]
  4369. fn parses_resume_and_config_slash_commands() {
  4370. assert_eq!(
  4371. SlashCommand::parse("/resume saved-session.json"),
  4372. Some(SlashCommand::Resume {
  4373. session_path: Some("saved-session.json".to_string())
  4374. })
  4375. );
  4376. assert_eq!(
  4377. SlashCommand::parse("/clear --confirm"),
  4378. Some(SlashCommand::Clear { confirm: true })
  4379. );
  4380. assert_eq!(
  4381. SlashCommand::parse("/config"),
  4382. Some(SlashCommand::Config { section: None })
  4383. );
  4384. assert_eq!(
  4385. SlashCommand::parse("/config env"),
  4386. Some(SlashCommand::Config {
  4387. section: Some("env".to_string())
  4388. })
  4389. );
  4390. assert_eq!(SlashCommand::parse("/memory"), Some(SlashCommand::Memory));
  4391. assert_eq!(SlashCommand::parse("/init"), Some(SlashCommand::Init));
  4392. }
  4393. #[test]
  4394. fn init_template_mentions_detected_rust_workspace() {
  4395. let rendered = crate::init::render_init_claude_md(std::path::Path::new("."));
  4396. assert!(rendered.contains("# CLAUDE.md"));
  4397. assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
  4398. }
  4399. #[test]
  4400. fn converts_tool_roundtrip_messages() {
  4401. let messages = vec![
  4402. ConversationMessage::user_text("hello"),
  4403. ConversationMessage::assistant(vec![ContentBlock::ToolUse {
  4404. id: "tool-1".to_string(),
  4405. name: "bash".to_string(),
  4406. input: "{\"command\":\"pwd\"}".to_string(),
  4407. }]),
  4408. ConversationMessage {
  4409. role: MessageRole::Tool,
  4410. blocks: vec![ContentBlock::ToolResult {
  4411. tool_use_id: "tool-1".to_string(),
  4412. tool_name: "bash".to_string(),
  4413. output: "ok".to_string(),
  4414. is_error: false,
  4415. }],
  4416. usage: None,
  4417. },
  4418. ];
  4419. let converted = super::convert_messages(&messages);
  4420. assert_eq!(converted.len(), 3);
  4421. assert_eq!(converted[1].role, "assistant");
  4422. assert_eq!(converted[2].role, "user");
  4423. }
  4424. #[test]
  4425. fn repl_help_mentions_history_completion_and_multiline() {
  4426. let help = render_repl_help();
  4427. assert!(help.contains("Up/Down"));
  4428. assert!(help.contains("Tab"));
  4429. assert!(help.contains("Shift+Enter/Ctrl+J"));
  4430. }
  4431. #[test]
  4432. fn tool_rendering_helpers_compact_output() {
  4433. let start = format_tool_call_start("read_file", r#"{"path":"src/main.rs"}"#);
  4434. assert!(start.contains("read_file"));
  4435. assert!(start.contains("src/main.rs"));
  4436. let done = format_tool_result(
  4437. "read_file",
  4438. r#"{"file":{"filePath":"src/main.rs","content":"hello","numLines":1,"startLine":1,"totalLines":1}}"#,
  4439. false,
  4440. );
  4441. assert!(done.contains("📄 Read src/main.rs"));
  4442. assert!(done.contains("hello"));
  4443. }
  4444. #[test]
  4445. fn tool_rendering_truncates_large_read_output_for_display_only() {
  4446. let content = (0..200)
  4447. .map(|index| format!("line {index:03}"))
  4448. .collect::<Vec<_>>()
  4449. .join("\n");
  4450. let output = json!({
  4451. "file": {
  4452. "filePath": "src/main.rs",
  4453. "content": content,
  4454. "numLines": 200,
  4455. "startLine": 1,
  4456. "totalLines": 200
  4457. }
  4458. })
  4459. .to_string();
  4460. let rendered = format_tool_result("read_file", &output, false);
  4461. assert!(rendered.contains("line 000"));
  4462. assert!(rendered.contains("line 079"));
  4463. assert!(!rendered.contains("line 199"));
  4464. assert!(rendered.contains("full result preserved in session"));
  4465. assert!(output.contains("line 199"));
  4466. }
  4467. #[test]
  4468. fn tool_rendering_truncates_large_bash_output_for_display_only() {
  4469. let stdout = (0..120)
  4470. .map(|index| format!("stdout {index:03}"))
  4471. .collect::<Vec<_>>()
  4472. .join("\n");
  4473. let output = json!({
  4474. "stdout": stdout,
  4475. "stderr": "",
  4476. "returnCodeInterpretation": "completed successfully"
  4477. })
  4478. .to_string();
  4479. let rendered = format_tool_result("bash", &output, false);
  4480. assert!(rendered.contains("stdout 000"));
  4481. assert!(rendered.contains("stdout 059"));
  4482. assert!(!rendered.contains("stdout 119"));
  4483. assert!(rendered.contains("full result preserved in session"));
  4484. assert!(output.contains("stdout 119"));
  4485. }
  4486. #[test]
  4487. fn tool_rendering_truncates_generic_long_output_for_display_only() {
  4488. let items = (0..120)
  4489. .map(|index| format!("payload {index:03}"))
  4490. .collect::<Vec<_>>();
  4491. let output = json!({
  4492. "summary": "plugin payload",
  4493. "items": items,
  4494. })
  4495. .to_string();
  4496. let rendered = format_tool_result("plugin_echo", &output, false);
  4497. assert!(rendered.contains("plugin_echo"));
  4498. assert!(rendered.contains("payload 000"));
  4499. assert!(rendered.contains("payload 040"));
  4500. assert!(!rendered.contains("payload 080"));
  4501. assert!(!rendered.contains("payload 119"));
  4502. assert!(rendered.contains("full result preserved in session"));
  4503. assert!(output.contains("payload 119"));
  4504. }
  4505. #[test]
  4506. fn tool_rendering_truncates_raw_generic_output_for_display_only() {
  4507. let output = (0..120)
  4508. .map(|index| format!("raw {index:03}"))
  4509. .collect::<Vec<_>>()
  4510. .join("\n");
  4511. let rendered = format_tool_result("plugin_echo", &output, false);
  4512. assert!(rendered.contains("plugin_echo"));
  4513. assert!(rendered.contains("raw 000"));
  4514. assert!(rendered.contains("raw 059"));
  4515. assert!(!rendered.contains("raw 119"));
  4516. assert!(rendered.contains("full result preserved in session"));
  4517. assert!(output.contains("raw 119"));
  4518. }
  4519. #[test]
  4520. fn ultraplan_progress_lines_include_phase_step_and_elapsed_status() {
  4521. let snapshot = InternalPromptProgressState {
  4522. command_label: "Ultraplan",
  4523. task_label: "ship plugin progress".to_string(),
  4524. step: 3,
  4525. phase: "running read_file".to_string(),
  4526. detail: Some("reading rust/crates/rusty-claude-cli/src/main.rs".to_string()),
  4527. saw_final_text: false,
  4528. };
  4529. let started = format_internal_prompt_progress_line(
  4530. InternalPromptProgressEvent::Started,
  4531. &snapshot,
  4532. Duration::from_secs(0),
  4533. None,
  4534. );
  4535. let heartbeat = format_internal_prompt_progress_line(
  4536. InternalPromptProgressEvent::Heartbeat,
  4537. &snapshot,
  4538. Duration::from_secs(9),
  4539. None,
  4540. );
  4541. let completed = format_internal_prompt_progress_line(
  4542. InternalPromptProgressEvent::Complete,
  4543. &snapshot,
  4544. Duration::from_secs(12),
  4545. None,
  4546. );
  4547. let failed = format_internal_prompt_progress_line(
  4548. InternalPromptProgressEvent::Failed,
  4549. &snapshot,
  4550. Duration::from_secs(12),
  4551. Some("network timeout"),
  4552. );
  4553. assert!(started.contains("planning started"));
  4554. assert!(started.contains("current step 3"));
  4555. assert!(heartbeat.contains("heartbeat"));
  4556. assert!(heartbeat.contains("9s elapsed"));
  4557. assert!(heartbeat.contains("phase running read_file"));
  4558. assert!(completed.contains("completed"));
  4559. assert!(completed.contains("3 steps total"));
  4560. assert!(failed.contains("failed"));
  4561. assert!(failed.contains("network timeout"));
  4562. }
  4563. #[test]
  4564. fn describe_tool_progress_summarizes_known_tools() {
  4565. assert_eq!(
  4566. describe_tool_progress("read_file", r#"{"path":"src/main.rs"}"#),
  4567. "reading src/main.rs"
  4568. );
  4569. assert!(
  4570. describe_tool_progress("bash", r#"{"command":"cargo test -p rusty-claude-cli"}"#)
  4571. .contains("cargo test -p rusty-claude-cli")
  4572. );
  4573. assert_eq!(
  4574. describe_tool_progress("grep_search", r#"{"pattern":"ultraplan","path":"rust"}"#),
  4575. "grep `ultraplan` in rust"
  4576. );
  4577. }
  4578. #[test]
  4579. fn push_output_block_renders_markdown_text() {
  4580. let mut out = Vec::new();
  4581. let mut events = Vec::new();
  4582. let mut pending_tool = None;
  4583. push_output_block(
  4584. OutputContentBlock::Text {
  4585. text: "# Heading".to_string(),
  4586. },
  4587. &mut out,
  4588. &mut events,
  4589. &mut pending_tool,
  4590. false,
  4591. )
  4592. .expect("text block should render");
  4593. let rendered = String::from_utf8(out).expect("utf8");
  4594. assert!(rendered.contains("Heading"));
  4595. assert!(rendered.contains('\u{1b}'));
  4596. }
  4597. #[test]
  4598. fn push_output_block_skips_empty_object_prefix_for_tool_streams() {
  4599. let mut out = Vec::new();
  4600. let mut events = Vec::new();
  4601. let mut pending_tool = None;
  4602. push_output_block(
  4603. OutputContentBlock::ToolUse {
  4604. id: "tool-1".to_string(),
  4605. name: "read_file".to_string(),
  4606. input: json!({}),
  4607. },
  4608. &mut out,
  4609. &mut events,
  4610. &mut pending_tool,
  4611. true,
  4612. )
  4613. .expect("tool block should accumulate");
  4614. assert!(events.is_empty());
  4615. assert_eq!(
  4616. pending_tool,
  4617. Some(("tool-1".to_string(), "read_file".to_string(), String::new(),))
  4618. );
  4619. }
  4620. #[test]
  4621. fn response_to_events_preserves_empty_object_json_input_outside_streaming() {
  4622. let mut out = Vec::new();
  4623. let events = response_to_events(
  4624. MessageResponse {
  4625. id: "msg-1".to_string(),
  4626. kind: "message".to_string(),
  4627. model: "claude-opus-4-6".to_string(),
  4628. role: "assistant".to_string(),
  4629. content: vec![OutputContentBlock::ToolUse {
  4630. id: "tool-1".to_string(),
  4631. name: "read_file".to_string(),
  4632. input: json!({}),
  4633. }],
  4634. stop_reason: Some("tool_use".to_string()),
  4635. stop_sequence: None,
  4636. usage: Usage {
  4637. input_tokens: 1,
  4638. output_tokens: 1,
  4639. cache_creation_input_tokens: 0,
  4640. cache_read_input_tokens: 0,
  4641. },
  4642. request_id: None,
  4643. },
  4644. &mut out,
  4645. )
  4646. .expect("response conversion should succeed");
  4647. assert!(matches!(
  4648. &events[0],
  4649. AssistantEvent::ToolUse { name, input, .. }
  4650. if name == "read_file" && input == "{}"
  4651. ));
  4652. }
  4653. #[test]
  4654. fn response_to_events_preserves_non_empty_json_input_outside_streaming() {
  4655. let mut out = Vec::new();
  4656. let events = response_to_events(
  4657. MessageResponse {
  4658. id: "msg-2".to_string(),
  4659. kind: "message".to_string(),
  4660. model: "claude-opus-4-6".to_string(),
  4661. role: "assistant".to_string(),
  4662. content: vec![OutputContentBlock::ToolUse {
  4663. id: "tool-2".to_string(),
  4664. name: "read_file".to_string(),
  4665. input: json!({ "path": "rust/Cargo.toml" }),
  4666. }],
  4667. stop_reason: Some("tool_use".to_string()),
  4668. stop_sequence: None,
  4669. usage: Usage {
  4670. input_tokens: 1,
  4671. output_tokens: 1,
  4672. cache_creation_input_tokens: 0,
  4673. cache_read_input_tokens: 0,
  4674. },
  4675. request_id: None,
  4676. },
  4677. &mut out,
  4678. )
  4679. .expect("response conversion should succeed");
  4680. assert!(matches!(
  4681. &events[0],
  4682. AssistantEvent::ToolUse { name, input, .. }
  4683. if name == "read_file" && input == "{\"path\":\"rust/Cargo.toml\"}"
  4684. ));
  4685. }
  4686. #[test]
  4687. fn response_to_events_ignores_thinking_blocks() {
  4688. let mut out = Vec::new();
  4689. let events = response_to_events(
  4690. MessageResponse {
  4691. id: "msg-3".to_string(),
  4692. kind: "message".to_string(),
  4693. model: "claude-opus-4-6".to_string(),
  4694. role: "assistant".to_string(),
  4695. content: vec![
  4696. OutputContentBlock::Thinking {
  4697. thinking: "step 1".to_string(),
  4698. signature: Some("sig_123".to_string()),
  4699. },
  4700. OutputContentBlock::Text {
  4701. text: "Final answer".to_string(),
  4702. },
  4703. ],
  4704. stop_reason: Some("end_turn".to_string()),
  4705. stop_sequence: None,
  4706. usage: Usage {
  4707. input_tokens: 1,
  4708. output_tokens: 1,
  4709. cache_creation_input_tokens: 0,
  4710. cache_read_input_tokens: 0,
  4711. },
  4712. request_id: None,
  4713. },
  4714. &mut out,
  4715. )
  4716. .expect("response conversion should succeed");
  4717. assert!(matches!(
  4718. &events[0],
  4719. AssistantEvent::TextDelta(text) if text == "Final answer"
  4720. ));
  4721. assert!(!String::from_utf8(out).expect("utf8").contains("step 1"));
  4722. }
  4723. }
  4724. #[cfg(test)]
  4725. mod sandbox_report_tests {
  4726. use super::format_sandbox_report;
  4727. #[test]
  4728. fn sandbox_report_renders_expected_fields() {
  4729. let report = format_sandbox_report(&runtime::SandboxStatus::default());
  4730. assert!(report.contains("Sandbox"));
  4731. assert!(report.contains("Enabled"));
  4732. assert!(report.contains("Filesystem mode"));
  4733. assert!(report.contains("Fallback reason"));
  4734. }
  4735. }