main.rs 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537
  1. mod init;
  2. mod input;
  3. mod render;
  4. use std::collections::{BTreeMap, 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::time::{SystemTime, UNIX_EPOCH};
  13. use api::{
  14. resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
  15. InputMessage, JsonlTelemetrySink, MessageRequest, MessageResponse, OutputContentBlock,
  16. SessionTracer, StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition,
  17. ToolResultContentBlock,
  18. };
  19. use commands::{
  20. render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
  21. };
  22. use compat_harness::{extract_manifest, UpstreamPaths};
  23. use init::initialize_repo;
  24. use render::{MarkdownStreamState, Spinner, TerminalRenderer};
  25. use runtime::{
  26. clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
  27. parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
  28. AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
  29. ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest, OAuthConfig,
  30. OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
  31. Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
  32. };
  33. use serde_json::json;
  34. use tools::{execute_tool, mvp_tool_specs, ToolSpec};
  35. const DEFAULT_MODEL: &str = "claude-opus-4-6";
  36. fn max_tokens_for_model(model: &str) -> u32 {
  37. if model.contains("opus") {
  38. 32_000
  39. } else {
  40. 64_000
  41. }
  42. }
  43. const DEFAULT_DATE: &str = "2026-03-31";
  44. const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
  45. const TELEMETRY_LOG_PATH_ENV: &str = "CLAW_TELEMETRY_LOG_PATH";
  46. const VERSION: &str = env!("CARGO_PKG_VERSION");
  47. const BUILD_TARGET: Option<&str> = option_env!("TARGET");
  48. const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
  49. type AllowedToolSet = BTreeSet<String>;
  50. fn main() {
  51. if let Err(error) = run() {
  52. eprintln!(
  53. "error: {error}
  54. Run `claw --help` for usage."
  55. );
  56. std::process::exit(1);
  57. }
  58. }
  59. fn run() -> Result<(), Box<dyn std::error::Error>> {
  60. let args: Vec<String> = env::args().skip(1).collect();
  61. match parse_args(&args)? {
  62. CliAction::DumpManifests => dump_manifests(),
  63. CliAction::BootstrapPlan => print_bootstrap_plan(),
  64. CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
  65. CliAction::Version => print_version(),
  66. CliAction::ResumeSession {
  67. session_path,
  68. commands,
  69. } => resume_session(&session_path, &commands),
  70. CliAction::Prompt {
  71. prompt,
  72. model,
  73. output_format,
  74. allowed_tools,
  75. permission_mode,
  76. } => LiveCli::new(model, true, allowed_tools, permission_mode)?
  77. .run_turn_with_output(&prompt, output_format)?,
  78. CliAction::Login => run_login()?,
  79. CliAction::Logout => run_logout()?,
  80. CliAction::Init => run_init()?,
  81. CliAction::Repl {
  82. model,
  83. allowed_tools,
  84. permission_mode,
  85. } => run_repl(model, allowed_tools, permission_mode)?,
  86. CliAction::Help => print_help(),
  87. }
  88. Ok(())
  89. }
  90. #[derive(Debug, Clone, PartialEq, Eq)]
  91. enum CliAction {
  92. DumpManifests,
  93. BootstrapPlan,
  94. PrintSystemPrompt {
  95. cwd: PathBuf,
  96. date: String,
  97. },
  98. Version,
  99. ResumeSession {
  100. session_path: PathBuf,
  101. commands: Vec<String>,
  102. },
  103. Prompt {
  104. prompt: String,
  105. model: String,
  106. output_format: CliOutputFormat,
  107. allowed_tools: Option<AllowedToolSet>,
  108. permission_mode: PermissionMode,
  109. },
  110. Login,
  111. Logout,
  112. Init,
  113. Repl {
  114. model: String,
  115. allowed_tools: Option<AllowedToolSet>,
  116. permission_mode: PermissionMode,
  117. },
  118. // prompt-mode formatting is only supported for non-interactive runs
  119. Help,
  120. }
  121. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  122. enum CliOutputFormat {
  123. Text,
  124. Json,
  125. }
  126. impl CliOutputFormat {
  127. fn parse(value: &str) -> Result<Self, String> {
  128. match value {
  129. "text" => Ok(Self::Text),
  130. "json" => Ok(Self::Json),
  131. other => Err(format!(
  132. "unsupported value for --output-format: {other} (expected text or json)"
  133. )),
  134. }
  135. }
  136. }
  137. #[allow(clippy::too_many_lines)]
  138. fn parse_args(args: &[String]) -> Result<CliAction, String> {
  139. let mut model = DEFAULT_MODEL.to_string();
  140. let mut output_format = CliOutputFormat::Text;
  141. let mut permission_mode = default_permission_mode();
  142. let mut wants_version = false;
  143. let mut allowed_tool_values = Vec::new();
  144. let mut rest = Vec::new();
  145. let mut index = 0;
  146. while index < args.len() {
  147. match args[index].as_str() {
  148. "--version" | "-V" => {
  149. wants_version = true;
  150. index += 1;
  151. }
  152. "--model" => {
  153. let value = args
  154. .get(index + 1)
  155. .ok_or_else(|| "missing value for --model".to_string())?;
  156. model = resolve_model_alias(value).to_string();
  157. index += 2;
  158. }
  159. flag if flag.starts_with("--model=") => {
  160. model = resolve_model_alias(&flag[8..]).to_string();
  161. index += 1;
  162. }
  163. "--output-format" => {
  164. let value = args
  165. .get(index + 1)
  166. .ok_or_else(|| "missing value for --output-format".to_string())?;
  167. output_format = CliOutputFormat::parse(value)?;
  168. index += 2;
  169. }
  170. "--permission-mode" => {
  171. let value = args
  172. .get(index + 1)
  173. .ok_or_else(|| "missing value for --permission-mode".to_string())?;
  174. permission_mode = parse_permission_mode_arg(value)?;
  175. index += 2;
  176. }
  177. flag if flag.starts_with("--output-format=") => {
  178. output_format = CliOutputFormat::parse(&flag[16..])?;
  179. index += 1;
  180. }
  181. flag if flag.starts_with("--permission-mode=") => {
  182. permission_mode = parse_permission_mode_arg(&flag[18..])?;
  183. index += 1;
  184. }
  185. "--dangerously-skip-permissions" => {
  186. permission_mode = PermissionMode::DangerFullAccess;
  187. index += 1;
  188. }
  189. "-p" => {
  190. // Claude Code compat: -p "prompt" = one-shot prompt
  191. let prompt = args[index + 1..].join(" ");
  192. if prompt.trim().is_empty() {
  193. return Err("-p requires a prompt string".to_string());
  194. }
  195. return Ok(CliAction::Prompt {
  196. prompt,
  197. model: resolve_model_alias(&model).to_string(),
  198. output_format,
  199. allowed_tools: normalize_allowed_tools(&allowed_tool_values)?,
  200. permission_mode,
  201. });
  202. }
  203. "--print" => {
  204. // Claude Code compat: --print makes output non-interactive
  205. output_format = CliOutputFormat::Text;
  206. index += 1;
  207. }
  208. "--allowedTools" | "--allowed-tools" => {
  209. let value = args
  210. .get(index + 1)
  211. .ok_or_else(|| "missing value for --allowedTools".to_string())?;
  212. allowed_tool_values.push(value.clone());
  213. index += 2;
  214. }
  215. flag if flag.starts_with("--allowedTools=") => {
  216. allowed_tool_values.push(flag[15..].to_string());
  217. index += 1;
  218. }
  219. flag if flag.starts_with("--allowed-tools=") => {
  220. allowed_tool_values.push(flag[16..].to_string());
  221. index += 1;
  222. }
  223. other => {
  224. rest.push(other.to_string());
  225. index += 1;
  226. }
  227. }
  228. }
  229. if wants_version {
  230. return Ok(CliAction::Version);
  231. }
  232. let allowed_tools = normalize_allowed_tools(&allowed_tool_values)?;
  233. if rest.is_empty() {
  234. return Ok(CliAction::Repl {
  235. model,
  236. allowed_tools,
  237. permission_mode,
  238. });
  239. }
  240. if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
  241. return Ok(CliAction::Help);
  242. }
  243. if rest.first().map(String::as_str) == Some("--resume") {
  244. return parse_resume_args(&rest[1..]);
  245. }
  246. match rest[0].as_str() {
  247. "dump-manifests" => Ok(CliAction::DumpManifests),
  248. "bootstrap-plan" => Ok(CliAction::BootstrapPlan),
  249. "system-prompt" => parse_system_prompt_args(&rest[1..]),
  250. "login" => Ok(CliAction::Login),
  251. "logout" => Ok(CliAction::Logout),
  252. "init" => Ok(CliAction::Init),
  253. "prompt" => {
  254. let prompt = rest[1..].join(" ");
  255. if prompt.trim().is_empty() {
  256. return Err("prompt subcommand requires a prompt string".to_string());
  257. }
  258. Ok(CliAction::Prompt {
  259. prompt,
  260. model,
  261. output_format,
  262. allowed_tools,
  263. permission_mode,
  264. })
  265. }
  266. other if !other.starts_with('/') => Ok(CliAction::Prompt {
  267. prompt: rest.join(" "),
  268. model,
  269. output_format,
  270. allowed_tools,
  271. permission_mode,
  272. }),
  273. other => Err(format!("unknown subcommand: {other}")),
  274. }
  275. }
  276. fn resolve_model_alias(model: &str) -> &str {
  277. match model {
  278. "opus" => "claude-opus-4-6",
  279. "sonnet" => "claude-sonnet-4-6",
  280. "haiku" => "claude-haiku-4-5-20251213",
  281. _ => model,
  282. }
  283. }
  284. fn normalize_allowed_tools(values: &[String]) -> Result<Option<AllowedToolSet>, String> {
  285. if values.is_empty() {
  286. return Ok(None);
  287. }
  288. let canonical_names = mvp_tool_specs()
  289. .into_iter()
  290. .map(|spec| spec.name.to_string())
  291. .collect::<Vec<_>>();
  292. let mut name_map = canonical_names
  293. .iter()
  294. .map(|name| (normalize_tool_name(name), name.clone()))
  295. .collect::<BTreeMap<_, _>>();
  296. for (alias, canonical) in [
  297. ("read", "read_file"),
  298. ("write", "write_file"),
  299. ("edit", "edit_file"),
  300. ("glob", "glob_search"),
  301. ("grep", "grep_search"),
  302. ] {
  303. name_map.insert(alias.to_string(), canonical.to_string());
  304. }
  305. let mut allowed = AllowedToolSet::new();
  306. for value in values {
  307. for token in value
  308. .split(|ch: char| ch == ',' || ch.is_whitespace())
  309. .filter(|token| !token.is_empty())
  310. {
  311. let normalized = normalize_tool_name(token);
  312. let canonical = name_map.get(&normalized).ok_or_else(|| {
  313. format!(
  314. "unsupported tool in --allowedTools: {token} (expected one of: {})",
  315. canonical_names.join(", ")
  316. )
  317. })?;
  318. allowed.insert(canonical.clone());
  319. }
  320. }
  321. Ok(Some(allowed))
  322. }
  323. fn normalize_tool_name(value: &str) -> String {
  324. value.trim().replace('-', "_").to_ascii_lowercase()
  325. }
  326. fn parse_permission_mode_arg(value: &str) -> Result<PermissionMode, String> {
  327. normalize_permission_mode(value)
  328. .ok_or_else(|| {
  329. format!(
  330. "unsupported permission mode '{value}'. Use read-only, workspace-write, or danger-full-access."
  331. )
  332. })
  333. .map(permission_mode_from_label)
  334. }
  335. fn permission_mode_from_label(mode: &str) -> PermissionMode {
  336. match mode {
  337. "read-only" => PermissionMode::ReadOnly,
  338. "workspace-write" => PermissionMode::WorkspaceWrite,
  339. "danger-full-access" => PermissionMode::DangerFullAccess,
  340. other => panic!("unsupported permission mode label: {other}"),
  341. }
  342. }
  343. fn default_permission_mode() -> PermissionMode {
  344. env::var("RUSTY_CLAUDE_PERMISSION_MODE")
  345. .ok()
  346. .as_deref()
  347. .and_then(normalize_permission_mode)
  348. .map_or(PermissionMode::DangerFullAccess, permission_mode_from_label)
  349. }
  350. fn filter_tool_specs(allowed_tools: Option<&AllowedToolSet>) -> Vec<tools::ToolSpec> {
  351. mvp_tool_specs()
  352. .into_iter()
  353. .filter(|spec| allowed_tools.is_none_or(|allowed| allowed.contains(spec.name)))
  354. .collect()
  355. }
  356. fn parse_system_prompt_args(args: &[String]) -> Result<CliAction, String> {
  357. let mut cwd = env::current_dir().map_err(|error| error.to_string())?;
  358. let mut date = DEFAULT_DATE.to_string();
  359. let mut index = 0;
  360. while index < args.len() {
  361. match args[index].as_str() {
  362. "--cwd" => {
  363. let value = args
  364. .get(index + 1)
  365. .ok_or_else(|| "missing value for --cwd".to_string())?;
  366. cwd = PathBuf::from(value);
  367. index += 2;
  368. }
  369. "--date" => {
  370. let value = args
  371. .get(index + 1)
  372. .ok_or_else(|| "missing value for --date".to_string())?;
  373. date.clone_from(value);
  374. index += 2;
  375. }
  376. other => return Err(format!("unknown system-prompt option: {other}")),
  377. }
  378. }
  379. Ok(CliAction::PrintSystemPrompt { cwd, date })
  380. }
  381. fn parse_resume_args(args: &[String]) -> Result<CliAction, String> {
  382. let session_path = args
  383. .first()
  384. .ok_or_else(|| "missing session path for --resume".to_string())
  385. .map(PathBuf::from)?;
  386. let commands = args[1..].to_vec();
  387. if commands
  388. .iter()
  389. .any(|command| !command.trim_start().starts_with('/'))
  390. {
  391. return Err("--resume trailing arguments must be slash commands".to_string());
  392. }
  393. Ok(CliAction::ResumeSession {
  394. session_path,
  395. commands,
  396. })
  397. }
  398. fn dump_manifests() {
  399. let workspace_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
  400. let paths = UpstreamPaths::from_workspace_dir(&workspace_dir);
  401. match extract_manifest(&paths) {
  402. Ok(manifest) => {
  403. println!("commands: {}", manifest.commands.entries().len());
  404. println!("tools: {}", manifest.tools.entries().len());
  405. println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
  406. }
  407. Err(error) => {
  408. eprintln!("failed to extract manifests: {error}");
  409. std::process::exit(1);
  410. }
  411. }
  412. }
  413. fn print_bootstrap_plan() {
  414. for phase in runtime::BootstrapPlan::claude_code_default().phases() {
  415. println!("- {phase:?}");
  416. }
  417. }
  418. fn default_oauth_config() -> OAuthConfig {
  419. OAuthConfig {
  420. client_id: String::from("9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
  421. authorize_url: String::from("https://platform.claude.com/oauth/authorize"),
  422. token_url: String::from("https://platform.claude.com/v1/oauth/token"),
  423. callback_port: None,
  424. manual_redirect_url: None,
  425. scopes: vec![
  426. String::from("user:profile"),
  427. String::from("user:inference"),
  428. String::from("user:sessions:claude_code"),
  429. ],
  430. }
  431. }
  432. fn run_login() -> Result<(), Box<dyn std::error::Error>> {
  433. let cwd = env::current_dir()?;
  434. let config = ConfigLoader::default_for(&cwd).load()?;
  435. let default_oauth = default_oauth_config();
  436. let oauth = config.oauth().unwrap_or(&default_oauth);
  437. let callback_port = oauth.callback_port.unwrap_or(DEFAULT_OAUTH_CALLBACK_PORT);
  438. let redirect_uri = runtime::loopback_redirect_uri(callback_port);
  439. let pkce = generate_pkce_pair()?;
  440. let state = generate_state()?;
  441. let authorize_url =
  442. OAuthAuthorizationRequest::from_config(oauth, redirect_uri.clone(), state.clone(), &pkce)
  443. .build_url();
  444. println!("Starting Claude OAuth login...");
  445. println!("Listening for callback on {redirect_uri}");
  446. if let Err(error) = open_browser(&authorize_url) {
  447. eprintln!("warning: failed to open browser automatically: {error}");
  448. println!("Open this URL manually:\n{authorize_url}");
  449. }
  450. let callback = wait_for_oauth_callback(callback_port)?;
  451. if let Some(error) = callback.error {
  452. let description = callback
  453. .error_description
  454. .unwrap_or_else(|| "authorization failed".to_string());
  455. return Err(io::Error::other(format!("{error}: {description}")).into());
  456. }
  457. let code = callback.code.ok_or_else(|| {
  458. io::Error::new(io::ErrorKind::InvalidData, "callback did not include code")
  459. })?;
  460. let returned_state = callback.state.ok_or_else(|| {
  461. io::Error::new(io::ErrorKind::InvalidData, "callback did not include state")
  462. })?;
  463. if returned_state != state {
  464. return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
  465. }
  466. let client = AnthropicClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
  467. let exchange_request =
  468. OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
  469. let runtime = tokio::runtime::Runtime::new()?;
  470. let token_set = runtime.block_on(client.exchange_oauth_code(oauth, &exchange_request))?;
  471. save_oauth_credentials(&runtime::OAuthTokenSet {
  472. access_token: token_set.access_token,
  473. refresh_token: token_set.refresh_token,
  474. expires_at: token_set.expires_at,
  475. scopes: token_set.scopes,
  476. })?;
  477. println!("Claude OAuth login complete.");
  478. Ok(())
  479. }
  480. fn run_logout() -> Result<(), Box<dyn std::error::Error>> {
  481. clear_oauth_credentials()?;
  482. println!("Claude OAuth credentials cleared.");
  483. Ok(())
  484. }
  485. fn open_browser(url: &str) -> io::Result<()> {
  486. let commands = if cfg!(target_os = "macos") {
  487. vec![("open", vec![url])]
  488. } else if cfg!(target_os = "windows") {
  489. vec![("cmd", vec!["/C", "start", "", url])]
  490. } else {
  491. vec![("xdg-open", vec![url])]
  492. };
  493. for (program, args) in commands {
  494. match Command::new(program).args(args).spawn() {
  495. Ok(_) => return Ok(()),
  496. Err(error) if error.kind() == io::ErrorKind::NotFound => {}
  497. Err(error) => return Err(error),
  498. }
  499. }
  500. Err(io::Error::new(
  501. io::ErrorKind::NotFound,
  502. "no supported browser opener command found",
  503. ))
  504. }
  505. fn wait_for_oauth_callback(
  506. port: u16,
  507. ) -> Result<runtime::OAuthCallbackParams, Box<dyn std::error::Error>> {
  508. let listener = TcpListener::bind(("127.0.0.1", port))?;
  509. let (mut stream, _) = listener.accept()?;
  510. let mut buffer = [0_u8; 4096];
  511. let bytes_read = stream.read(&mut buffer)?;
  512. let request = String::from_utf8_lossy(&buffer[..bytes_read]);
  513. let request_line = request.lines().next().ok_or_else(|| {
  514. io::Error::new(io::ErrorKind::InvalidData, "missing callback request line")
  515. })?;
  516. let target = request_line.split_whitespace().nth(1).ok_or_else(|| {
  517. io::Error::new(
  518. io::ErrorKind::InvalidData,
  519. "missing callback request target",
  520. )
  521. })?;
  522. let callback = parse_oauth_callback_request_target(target)
  523. .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
  524. let body = if callback.error.is_some() {
  525. "Claude OAuth login failed. You can close this window."
  526. } else {
  527. "Claude OAuth login succeeded. You can close this window."
  528. };
  529. let response = format!(
  530. "HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
  531. body.len(),
  532. body
  533. );
  534. stream.write_all(response.as_bytes())?;
  535. Ok(callback)
  536. }
  537. fn print_system_prompt(cwd: PathBuf, date: String) {
  538. match load_system_prompt(cwd, date, env::consts::OS, "unknown") {
  539. Ok(sections) => println!("{}", sections.join("\n\n")),
  540. Err(error) => {
  541. eprintln!("failed to build system prompt: {error}");
  542. std::process::exit(1);
  543. }
  544. }
  545. }
  546. fn print_version() {
  547. println!("{}", render_version_report());
  548. }
  549. fn resume_session(session_path: &Path, commands: &[String]) {
  550. let session = match Session::load_from_path(session_path) {
  551. Ok(session) => session,
  552. Err(error) => {
  553. eprintln!("failed to restore session: {error}");
  554. std::process::exit(1);
  555. }
  556. };
  557. if commands.is_empty() {
  558. println!(
  559. "Restored session from {} ({} messages).",
  560. session_path.display(),
  561. session.messages.len()
  562. );
  563. return;
  564. }
  565. let mut session = session;
  566. for raw_command in commands {
  567. let Some(command) = SlashCommand::parse(raw_command) else {
  568. eprintln!("unsupported resumed command: {raw_command}");
  569. std::process::exit(2);
  570. };
  571. match run_resume_command(session_path, &session, &command) {
  572. Ok(ResumeCommandOutcome {
  573. session: next_session,
  574. message,
  575. }) => {
  576. session = next_session;
  577. if let Some(message) = message {
  578. println!("{message}");
  579. }
  580. }
  581. Err(error) => {
  582. eprintln!("{error}");
  583. std::process::exit(2);
  584. }
  585. }
  586. }
  587. }
  588. #[derive(Debug, Clone)]
  589. struct ResumeCommandOutcome {
  590. session: Session,
  591. message: Option<String>,
  592. }
  593. #[derive(Debug, Clone)]
  594. struct StatusContext {
  595. cwd: PathBuf,
  596. session_path: Option<PathBuf>,
  597. loaded_config_files: usize,
  598. discovered_config_files: usize,
  599. memory_file_count: usize,
  600. project_root: Option<PathBuf>,
  601. git_branch: Option<String>,
  602. }
  603. #[derive(Debug, Clone, Copy)]
  604. struct StatusUsage {
  605. message_count: usize,
  606. turns: u32,
  607. latest: TokenUsage,
  608. cumulative: TokenUsage,
  609. estimated_tokens: usize,
  610. }
  611. fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
  612. format!(
  613. "Model
  614. Current model {model}
  615. Session messages {message_count}
  616. Session turns {turns}
  617. Usage
  618. Inspect current model with /model
  619. Switch models with /model <name>"
  620. )
  621. }
  622. fn format_model_switch_report(previous: &str, next: &str, message_count: usize) -> String {
  623. format!(
  624. "Model updated
  625. Previous {previous}
  626. Current {next}
  627. Preserved msgs {message_count}"
  628. )
  629. }
  630. fn format_permissions_report(mode: &str) -> String {
  631. let modes = [
  632. ("read-only", "Read/search tools only", mode == "read-only"),
  633. (
  634. "workspace-write",
  635. "Edit files inside the workspace",
  636. mode == "workspace-write",
  637. ),
  638. (
  639. "danger-full-access",
  640. "Unrestricted tool access",
  641. mode == "danger-full-access",
  642. ),
  643. ]
  644. .into_iter()
  645. .map(|(name, description, is_current)| {
  646. let marker = if is_current {
  647. "● current"
  648. } else {
  649. "○ available"
  650. };
  651. format!(" {name:<18} {marker:<11} {description}")
  652. })
  653. .collect::<Vec<_>>()
  654. .join(
  655. "
  656. ",
  657. );
  658. format!(
  659. "Permissions
  660. Active mode {mode}
  661. Mode status live session default
  662. Modes
  663. {modes}
  664. Usage
  665. Inspect current mode with /permissions
  666. Switch modes with /permissions <mode>"
  667. )
  668. }
  669. fn format_permissions_switch_report(previous: &str, next: &str) -> String {
  670. format!(
  671. "Permissions updated
  672. Result mode switched
  673. Previous mode {previous}
  674. Active mode {next}
  675. Applies to subsequent tool calls
  676. Usage /permissions to inspect current mode"
  677. )
  678. }
  679. fn format_cost_report(usage: TokenUsage) -> String {
  680. format!(
  681. "Cost
  682. Input tokens {}
  683. Output tokens {}
  684. Cache create {}
  685. Cache read {}
  686. Total tokens {}",
  687. usage.input_tokens,
  688. usage.output_tokens,
  689. usage.cache_creation_input_tokens,
  690. usage.cache_read_input_tokens,
  691. usage.total_tokens(),
  692. )
  693. }
  694. fn format_resume_report(session_path: &str, message_count: usize, turns: u32) -> String {
  695. format!(
  696. "Session resumed
  697. Session file {session_path}
  698. Messages {message_count}
  699. Turns {turns}"
  700. )
  701. }
  702. fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
  703. if skipped {
  704. format!(
  705. "Compact
  706. Result skipped
  707. Reason session below compaction threshold
  708. Messages kept {resulting_messages}"
  709. )
  710. } else {
  711. format!(
  712. "Compact
  713. Result compacted
  714. Messages removed {removed}
  715. Messages kept {resulting_messages}"
  716. )
  717. }
  718. }
  719. fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
  720. let Some(status) = status else {
  721. return (None, None);
  722. };
  723. let branch = status.lines().next().and_then(|line| {
  724. line.strip_prefix("## ")
  725. .map(|line| {
  726. line.split(['.', ' '])
  727. .next()
  728. .unwrap_or_default()
  729. .to_string()
  730. })
  731. .filter(|value| !value.is_empty())
  732. });
  733. let project_root = find_git_root().ok();
  734. (project_root, branch)
  735. }
  736. fn find_git_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
  737. let output = std::process::Command::new("git")
  738. .args(["rev-parse", "--show-toplevel"])
  739. .current_dir(env::current_dir()?)
  740. .output()?;
  741. if !output.status.success() {
  742. return Err("not a git repository".into());
  743. }
  744. let path = String::from_utf8(output.stdout)?.trim().to_string();
  745. if path.is_empty() {
  746. return Err("empty git root".into());
  747. }
  748. Ok(PathBuf::from(path))
  749. }
  750. #[allow(clippy::too_many_lines)]
  751. fn run_resume_command(
  752. session_path: &Path,
  753. session: &Session,
  754. command: &SlashCommand,
  755. ) -> Result<ResumeCommandOutcome, Box<dyn std::error::Error>> {
  756. match command {
  757. SlashCommand::Help => Ok(ResumeCommandOutcome {
  758. session: session.clone(),
  759. message: Some(render_repl_help()),
  760. }),
  761. SlashCommand::Compact => {
  762. let result = runtime::compact_session(
  763. session,
  764. CompactionConfig {
  765. max_estimated_tokens: 0,
  766. ..CompactionConfig::default()
  767. },
  768. );
  769. let removed = result.removed_message_count;
  770. let kept = result.compacted_session.messages.len();
  771. let skipped = removed == 0;
  772. result.compacted_session.save_to_path(session_path)?;
  773. Ok(ResumeCommandOutcome {
  774. session: result.compacted_session,
  775. message: Some(format_compact_report(removed, kept, skipped)),
  776. })
  777. }
  778. SlashCommand::Clear { confirm } => {
  779. if !confirm {
  780. return Ok(ResumeCommandOutcome {
  781. session: session.clone(),
  782. message: Some(
  783. "clear: confirmation required; rerun with /clear --confirm".to_string(),
  784. ),
  785. });
  786. }
  787. let cleared = Session::new();
  788. cleared.save_to_path(session_path)?;
  789. Ok(ResumeCommandOutcome {
  790. session: cleared,
  791. message: Some(format!(
  792. "Cleared resumed session file {}.",
  793. session_path.display()
  794. )),
  795. })
  796. }
  797. SlashCommand::Status => {
  798. let tracker = UsageTracker::from_session(session);
  799. let usage = tracker.cumulative_usage();
  800. Ok(ResumeCommandOutcome {
  801. session: session.clone(),
  802. message: Some(format_status_report(
  803. "restored-session",
  804. StatusUsage {
  805. message_count: session.messages.len(),
  806. turns: tracker.turns(),
  807. latest: tracker.current_turn_usage(),
  808. cumulative: usage,
  809. estimated_tokens: 0,
  810. },
  811. default_permission_mode().as_str(),
  812. &status_context(Some(session_path))?,
  813. )),
  814. })
  815. }
  816. SlashCommand::Cost => {
  817. let usage = UsageTracker::from_session(session).cumulative_usage();
  818. Ok(ResumeCommandOutcome {
  819. session: session.clone(),
  820. message: Some(format_cost_report(usage)),
  821. })
  822. }
  823. SlashCommand::Config { section } => Ok(ResumeCommandOutcome {
  824. session: session.clone(),
  825. message: Some(render_config_report(section.as_deref())?),
  826. }),
  827. SlashCommand::Memory => Ok(ResumeCommandOutcome {
  828. session: session.clone(),
  829. message: Some(render_memory_report()?),
  830. }),
  831. SlashCommand::Init => Ok(ResumeCommandOutcome {
  832. session: session.clone(),
  833. message: Some(init_claude_md()?),
  834. }),
  835. SlashCommand::Diff => Ok(ResumeCommandOutcome {
  836. session: session.clone(),
  837. message: Some(render_diff_report()?),
  838. }),
  839. SlashCommand::Version => Ok(ResumeCommandOutcome {
  840. session: session.clone(),
  841. message: Some(render_version_report()),
  842. }),
  843. SlashCommand::Export { path } => {
  844. let export_path = resolve_export_path(path.as_deref(), session)?;
  845. fs::write(&export_path, render_export_text(session))?;
  846. Ok(ResumeCommandOutcome {
  847. session: session.clone(),
  848. message: Some(format!(
  849. "Export\n Result wrote transcript\n File {}\n Messages {}",
  850. export_path.display(),
  851. session.messages.len(),
  852. )),
  853. })
  854. }
  855. SlashCommand::Resume { .. }
  856. | SlashCommand::Model { .. }
  857. | SlashCommand::Permissions { .. }
  858. | SlashCommand::Session { .. }
  859. | SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
  860. }
  861. }
  862. fn run_repl(
  863. model: String,
  864. allowed_tools: Option<AllowedToolSet>,
  865. permission_mode: PermissionMode,
  866. ) -> Result<(), Box<dyn std::error::Error>> {
  867. let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
  868. let mut editor = input::LineEditor::new("> ", slash_command_completion_candidates());
  869. println!("{}", cli.startup_banner());
  870. loop {
  871. match editor.read_line()? {
  872. input::ReadOutcome::Submit(input) => {
  873. let trimmed = input.trim().to_string();
  874. if trimmed.is_empty() {
  875. continue;
  876. }
  877. if matches!(trimmed.as_str(), "/exit" | "/quit") {
  878. cli.persist_session()?;
  879. break;
  880. }
  881. if let Some(command) = SlashCommand::parse(&trimmed) {
  882. if cli.handle_repl_command(command)? {
  883. cli.persist_session()?;
  884. }
  885. continue;
  886. }
  887. editor.push_history(input);
  888. cli.run_turn(&trimmed)?;
  889. }
  890. input::ReadOutcome::Cancel => {}
  891. input::ReadOutcome::Exit => {
  892. cli.persist_session()?;
  893. break;
  894. }
  895. }
  896. }
  897. Ok(())
  898. }
  899. #[derive(Debug, Clone)]
  900. struct SessionHandle {
  901. id: String,
  902. path: PathBuf,
  903. }
  904. #[derive(Debug, Clone)]
  905. struct ManagedSessionSummary {
  906. id: String,
  907. path: PathBuf,
  908. modified_epoch_secs: u64,
  909. message_count: usize,
  910. }
  911. struct LiveCli {
  912. model: String,
  913. allowed_tools: Option<AllowedToolSet>,
  914. permission_mode: PermissionMode,
  915. system_prompt: Vec<String>,
  916. runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
  917. session: SessionHandle,
  918. }
  919. impl LiveCli {
  920. fn new(
  921. model: String,
  922. enable_tools: bool,
  923. allowed_tools: Option<AllowedToolSet>,
  924. permission_mode: PermissionMode,
  925. ) -> Result<Self, Box<dyn std::error::Error>> {
  926. let system_prompt = build_system_prompt()?;
  927. let session = create_managed_session_handle()?;
  928. let runtime = build_runtime(
  929. Session::new(),
  930. &session.id,
  931. model.clone(),
  932. system_prompt.clone(),
  933. enable_tools,
  934. true,
  935. allowed_tools.clone(),
  936. permission_mode,
  937. )?;
  938. let cli = Self {
  939. model,
  940. allowed_tools,
  941. permission_mode,
  942. system_prompt,
  943. runtime,
  944. session,
  945. };
  946. cli.persist_session()?;
  947. Ok(cli)
  948. }
  949. fn startup_banner(&self) -> String {
  950. let cwd = env::current_dir().map_or_else(
  951. |_| "<unknown>".to_string(),
  952. |path| path.display().to_string(),
  953. );
  954. format!(
  955. "\x1b[38;5;196m\
  956. ██████╗██╗ █████╗ ██╗ ██╗\n\
  957. ██╔════╝██║ ██╔══██╗██║ ██║\n\
  958. ██║ ██║ ███████║██║ █╗ ██║\n\
  959. ██║ ██║ ██╔══██║██║███╗██║\n\
  960. ╚██████╗███████╗██║ ██║╚███╔███╔╝\n\
  961. ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝\x1b[0m \x1b[38;5;208mCode\x1b[0m 🦞\n\n\
  962. \x1b[2mModel\x1b[0m {}\n\
  963. \x1b[2mPermissions\x1b[0m {}\n\
  964. \x1b[2mDirectory\x1b[0m {}\n\
  965. \x1b[2mSession\x1b[0m {}\n\n\
  966. Type \x1b[1m/help\x1b[0m for commands · \x1b[2mShift+Enter\x1b[0m for newline",
  967. self.model,
  968. self.permission_mode.as_str(),
  969. cwd,
  970. self.session.id,
  971. )
  972. }
  973. fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  974. let mut spinner = Spinner::new();
  975. let mut stdout = io::stdout();
  976. spinner.tick(
  977. "🦀 Thinking...",
  978. TerminalRenderer::new().color_theme(),
  979. &mut stdout,
  980. )?;
  981. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  982. let result = self.runtime.run_turn(input, Some(&mut permission_prompter));
  983. match result {
  984. Ok(_) => {
  985. spinner.finish(
  986. "✨ Done",
  987. TerminalRenderer::new().color_theme(),
  988. &mut stdout,
  989. )?;
  990. println!();
  991. self.persist_session()?;
  992. Ok(())
  993. }
  994. Err(error) => {
  995. spinner.fail(
  996. "❌ Request failed",
  997. TerminalRenderer::new().color_theme(),
  998. &mut stdout,
  999. )?;
  1000. Err(Box::new(error))
  1001. }
  1002. }
  1003. }
  1004. fn run_turn_with_output(
  1005. &mut self,
  1006. input: &str,
  1007. output_format: CliOutputFormat,
  1008. ) -> Result<(), Box<dyn std::error::Error>> {
  1009. match output_format {
  1010. CliOutputFormat::Text => self.run_turn(input),
  1011. CliOutputFormat::Json => self.run_prompt_json(input),
  1012. }
  1013. }
  1014. fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
  1015. let session = self.runtime.session().clone();
  1016. let mut runtime = build_runtime(
  1017. session,
  1018. &self.session.id,
  1019. self.model.clone(),
  1020. self.system_prompt.clone(),
  1021. true,
  1022. false,
  1023. self.allowed_tools.clone(),
  1024. self.permission_mode,
  1025. )?;
  1026. let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
  1027. let summary = runtime.run_turn(input, Some(&mut permission_prompter))?;
  1028. self.runtime = runtime;
  1029. self.persist_session()?;
  1030. println!(
  1031. "{}",
  1032. json!({
  1033. "message": final_assistant_text(&summary),
  1034. "model": self.model,
  1035. "iterations": summary.iterations,
  1036. "tool_uses": collect_tool_uses(&summary),
  1037. "tool_results": collect_tool_results(&summary),
  1038. "usage": {
  1039. "input_tokens": summary.usage.input_tokens,
  1040. "output_tokens": summary.usage.output_tokens,
  1041. "cache_creation_input_tokens": summary.usage.cache_creation_input_tokens,
  1042. "cache_read_input_tokens": summary.usage.cache_read_input_tokens,
  1043. }
  1044. })
  1045. );
  1046. Ok(())
  1047. }
  1048. fn handle_repl_command(
  1049. &mut self,
  1050. command: SlashCommand,
  1051. ) -> Result<bool, Box<dyn std::error::Error>> {
  1052. Ok(match command {
  1053. SlashCommand::Help => {
  1054. println!("{}", render_repl_help());
  1055. false
  1056. }
  1057. SlashCommand::Status => {
  1058. self.print_status();
  1059. false
  1060. }
  1061. SlashCommand::Compact => {
  1062. self.compact()?;
  1063. false
  1064. }
  1065. SlashCommand::Model { model } => self.set_model(model)?,
  1066. SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
  1067. SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
  1068. SlashCommand::Cost => {
  1069. self.print_cost();
  1070. false
  1071. }
  1072. SlashCommand::Resume { session_path } => self.resume_session(session_path)?,
  1073. SlashCommand::Config { section } => {
  1074. Self::print_config(section.as_deref())?;
  1075. false
  1076. }
  1077. SlashCommand::Memory => {
  1078. Self::print_memory()?;
  1079. false
  1080. }
  1081. SlashCommand::Init => {
  1082. run_init()?;
  1083. false
  1084. }
  1085. SlashCommand::Diff => {
  1086. Self::print_diff()?;
  1087. false
  1088. }
  1089. SlashCommand::Version => {
  1090. Self::print_version();
  1091. false
  1092. }
  1093. SlashCommand::Export { path } => {
  1094. self.export_session(path.as_deref())?;
  1095. false
  1096. }
  1097. SlashCommand::Session { action, target } => {
  1098. self.handle_session_command(action.as_deref(), target.as_deref())?
  1099. }
  1100. SlashCommand::Unknown(name) => {
  1101. eprintln!("unknown slash command: /{name}");
  1102. false
  1103. }
  1104. })
  1105. }
  1106. fn persist_session(&self) -> Result<(), Box<dyn std::error::Error>> {
  1107. self.runtime.session().save_to_path(&self.session.path)?;
  1108. Ok(())
  1109. }
  1110. fn print_status(&self) {
  1111. let cumulative = self.runtime.usage().cumulative_usage();
  1112. let latest = self.runtime.usage().current_turn_usage();
  1113. println!(
  1114. "{}",
  1115. format_status_report(
  1116. &self.model,
  1117. StatusUsage {
  1118. message_count: self.runtime.session().messages.len(),
  1119. turns: self.runtime.usage().turns(),
  1120. latest,
  1121. cumulative,
  1122. estimated_tokens: self.runtime.estimated_tokens(),
  1123. },
  1124. self.permission_mode.as_str(),
  1125. &status_context(Some(&self.session.path)).expect("status context should load"),
  1126. )
  1127. );
  1128. }
  1129. fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
  1130. let Some(model) = model else {
  1131. println!(
  1132. "{}",
  1133. format_model_report(
  1134. &self.model,
  1135. self.runtime.session().messages.len(),
  1136. self.runtime.usage().turns(),
  1137. )
  1138. );
  1139. return Ok(false);
  1140. };
  1141. let model = resolve_model_alias(&model).to_string();
  1142. if model == self.model {
  1143. println!(
  1144. "{}",
  1145. format_model_report(
  1146. &self.model,
  1147. self.runtime.session().messages.len(),
  1148. self.runtime.usage().turns(),
  1149. )
  1150. );
  1151. return Ok(false);
  1152. }
  1153. let previous = self.model.clone();
  1154. let session = self.runtime.session().clone();
  1155. let message_count = session.messages.len();
  1156. self.runtime = build_runtime(
  1157. session,
  1158. model.clone(),
  1159. self.system_prompt.clone(),
  1160. true,
  1161. true,
  1162. self.allowed_tools.clone(),
  1163. self.permission_mode,
  1164. )?;
  1165. self.model.clone_from(&model);
  1166. println!(
  1167. "{}",
  1168. format_model_switch_report(&previous, &model, message_count)
  1169. );
  1170. Ok(true)
  1171. }
  1172. fn set_permissions(
  1173. &mut self,
  1174. mode: Option<String>,
  1175. ) -> Result<bool, Box<dyn std::error::Error>> {
  1176. let Some(mode) = mode else {
  1177. println!(
  1178. "{}",
  1179. format_permissions_report(self.permission_mode.as_str())
  1180. );
  1181. return Ok(false);
  1182. };
  1183. let normalized = normalize_permission_mode(&mode).ok_or_else(|| {
  1184. format!(
  1185. "unsupported permission mode '{mode}'. Use read-only, workspace-write, or danger-full-access."
  1186. )
  1187. })?;
  1188. if normalized == self.permission_mode.as_str() {
  1189. println!("{}", format_permissions_report(normalized));
  1190. return Ok(false);
  1191. }
  1192. let previous = self.permission_mode.as_str().to_string();
  1193. let session = self.runtime.session().clone();
  1194. self.permission_mode = permission_mode_from_label(normalized);
  1195. self.runtime = build_runtime(
  1196. session,
  1197. &self.session.id,
  1198. self.model.clone(),
  1199. self.system_prompt.clone(),
  1200. true,
  1201. true,
  1202. self.allowed_tools.clone(),
  1203. self.permission_mode,
  1204. )?;
  1205. println!(
  1206. "{}",
  1207. format_permissions_switch_report(&previous, normalized)
  1208. );
  1209. Ok(true)
  1210. }
  1211. fn clear_session(&mut self, confirm: bool) -> Result<bool, Box<dyn std::error::Error>> {
  1212. if !confirm {
  1213. println!(
  1214. "clear: confirmation required; run /clear --confirm to start a fresh session."
  1215. );
  1216. return Ok(false);
  1217. }
  1218. self.session = create_managed_session_handle()?;
  1219. self.runtime = build_runtime(
  1220. Session::new(),
  1221. &self.session.id,
  1222. self.model.clone(),
  1223. self.system_prompt.clone(),
  1224. true,
  1225. true,
  1226. self.allowed_tools.clone(),
  1227. self.permission_mode,
  1228. )?;
  1229. println!(
  1230. "Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
  1231. self.model,
  1232. self.permission_mode.as_str(),
  1233. self.session.id,
  1234. );
  1235. Ok(true)
  1236. }
  1237. fn print_cost(&self) {
  1238. let cumulative = self.runtime.usage().cumulative_usage();
  1239. println!("{}", format_cost_report(cumulative));
  1240. }
  1241. fn resume_session(
  1242. &mut self,
  1243. session_path: Option<String>,
  1244. ) -> Result<bool, Box<dyn std::error::Error>> {
  1245. let Some(session_ref) = session_path else {
  1246. println!("Usage: /resume <session-path>");
  1247. return Ok(false);
  1248. };
  1249. let handle = resolve_session_reference(&session_ref)?;
  1250. let session = Session::load_from_path(&handle.path)?;
  1251. let message_count = session.messages.len();
  1252. self.runtime = build_runtime(
  1253. session,
  1254. &self.session.id,
  1255. self.model.clone(),
  1256. self.system_prompt.clone(),
  1257. true,
  1258. true,
  1259. self.allowed_tools.clone(),
  1260. self.permission_mode,
  1261. )?;
  1262. self.session = handle;
  1263. println!(
  1264. "{}",
  1265. format_resume_report(
  1266. &self.session.path.display().to_string(),
  1267. message_count,
  1268. self.runtime.usage().turns(),
  1269. )
  1270. );
  1271. Ok(true)
  1272. }
  1273. fn print_config(section: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
  1274. println!("{}", render_config_report(section)?);
  1275. Ok(())
  1276. }
  1277. fn print_memory() -> Result<(), Box<dyn std::error::Error>> {
  1278. println!("{}", render_memory_report()?);
  1279. Ok(())
  1280. }
  1281. fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
  1282. println!("{}", render_diff_report()?);
  1283. Ok(())
  1284. }
  1285. fn print_version() {
  1286. println!("{}", render_version_report());
  1287. }
  1288. fn export_session(
  1289. &self,
  1290. requested_path: Option<&str>,
  1291. ) -> Result<(), Box<dyn std::error::Error>> {
  1292. let export_path = resolve_export_path(requested_path, self.runtime.session())?;
  1293. fs::write(&export_path, render_export_text(self.runtime.session()))?;
  1294. println!(
  1295. "Export\n Result wrote transcript\n File {}\n Messages {}",
  1296. export_path.display(),
  1297. self.runtime.session().messages.len(),
  1298. );
  1299. Ok(())
  1300. }
  1301. fn handle_session_command(
  1302. &mut self,
  1303. action: Option<&str>,
  1304. target: Option<&str>,
  1305. ) -> Result<bool, Box<dyn std::error::Error>> {
  1306. match action {
  1307. None | Some("list") => {
  1308. println!("{}", render_session_list(&self.session.id)?);
  1309. Ok(false)
  1310. }
  1311. Some("switch") => {
  1312. let Some(target) = target else {
  1313. println!("Usage: /session switch <session-id>");
  1314. return Ok(false);
  1315. };
  1316. let handle = resolve_session_reference(target)?;
  1317. let session = Session::load_from_path(&handle.path)?;
  1318. let message_count = session.messages.len();
  1319. self.runtime = build_runtime(
  1320. session,
  1321. &handle.id,
  1322. self.model.clone(),
  1323. self.system_prompt.clone(),
  1324. true,
  1325. true,
  1326. self.allowed_tools.clone(),
  1327. self.permission_mode,
  1328. )?;
  1329. self.session = handle;
  1330. println!(
  1331. "Session switched\n Active session {}\n File {}\n Messages {}",
  1332. self.session.id,
  1333. self.session.path.display(),
  1334. message_count,
  1335. );
  1336. Ok(true)
  1337. }
  1338. Some(other) => {
  1339. println!("Unknown /session action '{other}'. Use /session list or /session switch <session-id>.");
  1340. Ok(false)
  1341. }
  1342. }
  1343. }
  1344. fn compact(&mut self) -> Result<(), Box<dyn std::error::Error>> {
  1345. let result = self.runtime.compact(CompactionConfig::default());
  1346. let removed = result.removed_message_count;
  1347. let kept = result.compacted_session.messages.len();
  1348. let skipped = removed == 0;
  1349. self.runtime = build_runtime(
  1350. result.compacted_session,
  1351. &self.session.id,
  1352. self.model.clone(),
  1353. self.system_prompt.clone(),
  1354. true,
  1355. true,
  1356. self.allowed_tools.clone(),
  1357. self.permission_mode,
  1358. )?;
  1359. self.persist_session()?;
  1360. println!("{}", format_compact_report(removed, kept, skipped));
  1361. Ok(())
  1362. }
  1363. }
  1364. fn sessions_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
  1365. let cwd = env::current_dir()?;
  1366. let path = cwd.join(".claude").join("sessions");
  1367. fs::create_dir_all(&path)?;
  1368. Ok(path)
  1369. }
  1370. fn create_managed_session_handle() -> Result<SessionHandle, Box<dyn std::error::Error>> {
  1371. let id = generate_session_id();
  1372. let path = sessions_dir()?.join(format!("{id}.json"));
  1373. Ok(SessionHandle { id, path })
  1374. }
  1375. fn generate_session_id() -> String {
  1376. let millis = SystemTime::now()
  1377. .duration_since(UNIX_EPOCH)
  1378. .map(|duration| duration.as_millis())
  1379. .unwrap_or_default();
  1380. format!("session-{millis}")
  1381. }
  1382. fn resolve_session_reference(reference: &str) -> Result<SessionHandle, Box<dyn std::error::Error>> {
  1383. let direct = PathBuf::from(reference);
  1384. let path = if direct.exists() {
  1385. direct
  1386. } else {
  1387. sessions_dir()?.join(format!("{reference}.json"))
  1388. };
  1389. if !path.exists() {
  1390. return Err(format!("session not found: {reference}").into());
  1391. }
  1392. let id = path
  1393. .file_stem()
  1394. .and_then(|value| value.to_str())
  1395. .unwrap_or(reference)
  1396. .to_string();
  1397. Ok(SessionHandle { id, path })
  1398. }
  1399. fn list_managed_sessions() -> Result<Vec<ManagedSessionSummary>, Box<dyn std::error::Error>> {
  1400. let mut sessions = Vec::new();
  1401. for entry in fs::read_dir(sessions_dir()?)? {
  1402. let entry = entry?;
  1403. let path = entry.path();
  1404. if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
  1405. continue;
  1406. }
  1407. let metadata = entry.metadata()?;
  1408. let modified_epoch_secs = metadata
  1409. .modified()
  1410. .ok()
  1411. .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
  1412. .map(|duration| duration.as_secs())
  1413. .unwrap_or_default();
  1414. let message_count = Session::load_from_path(&path)
  1415. .map(|session| session.messages.len())
  1416. .unwrap_or_default();
  1417. let id = path
  1418. .file_stem()
  1419. .and_then(|value| value.to_str())
  1420. .unwrap_or("unknown")
  1421. .to_string();
  1422. sessions.push(ManagedSessionSummary {
  1423. id,
  1424. path,
  1425. modified_epoch_secs,
  1426. message_count,
  1427. });
  1428. }
  1429. sessions.sort_by(|left, right| right.modified_epoch_secs.cmp(&left.modified_epoch_secs));
  1430. Ok(sessions)
  1431. }
  1432. fn render_session_list(active_session_id: &str) -> Result<String, Box<dyn std::error::Error>> {
  1433. let sessions = list_managed_sessions()?;
  1434. let mut lines = vec![
  1435. "Sessions".to_string(),
  1436. format!(" Directory {}", sessions_dir()?.display()),
  1437. ];
  1438. if sessions.is_empty() {
  1439. lines.push(" No managed sessions saved yet.".to_string());
  1440. return Ok(lines.join("\n"));
  1441. }
  1442. for session in sessions {
  1443. let marker = if session.id == active_session_id {
  1444. "● current"
  1445. } else {
  1446. "○ saved"
  1447. };
  1448. lines.push(format!(
  1449. " {id:<20} {marker:<10} msgs={msgs:<4} modified={modified} path={path}",
  1450. id = session.id,
  1451. msgs = session.message_count,
  1452. modified = session.modified_epoch_secs,
  1453. path = session.path.display(),
  1454. ));
  1455. }
  1456. Ok(lines.join("\n"))
  1457. }
  1458. fn render_repl_help() -> String {
  1459. [
  1460. "REPL".to_string(),
  1461. " /exit Quit the REPL".to_string(),
  1462. " /quit Quit the REPL".to_string(),
  1463. " Up/Down Navigate prompt history".to_string(),
  1464. " Tab Complete slash commands".to_string(),
  1465. " Ctrl-C Clear input (or exit on empty prompt)".to_string(),
  1466. " Shift+Enter/Ctrl+J Insert a newline".to_string(),
  1467. String::new(),
  1468. render_slash_command_help(),
  1469. ]
  1470. .join(
  1471. "
  1472. ",
  1473. )
  1474. }
  1475. fn status_context(
  1476. session_path: Option<&Path>,
  1477. ) -> Result<StatusContext, Box<dyn std::error::Error>> {
  1478. let cwd = env::current_dir()?;
  1479. let loader = ConfigLoader::default_for(&cwd);
  1480. let discovered_config_files = loader.discover().len();
  1481. let runtime_config = loader.load()?;
  1482. let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
  1483. let (project_root, git_branch) =
  1484. parse_git_status_metadata(project_context.git_status.as_deref());
  1485. Ok(StatusContext {
  1486. cwd,
  1487. session_path: session_path.map(Path::to_path_buf),
  1488. loaded_config_files: runtime_config.loaded_entries().len(),
  1489. discovered_config_files,
  1490. memory_file_count: project_context.instruction_files.len(),
  1491. project_root,
  1492. git_branch,
  1493. })
  1494. }
  1495. fn format_status_report(
  1496. model: &str,
  1497. usage: StatusUsage,
  1498. permission_mode: &str,
  1499. context: &StatusContext,
  1500. ) -> String {
  1501. [
  1502. format!(
  1503. "Status
  1504. Model {model}
  1505. Permission mode {permission_mode}
  1506. Messages {}
  1507. Turns {}
  1508. Estimated tokens {}",
  1509. usage.message_count, usage.turns, usage.estimated_tokens,
  1510. ),
  1511. format!(
  1512. "Usage
  1513. Latest total {}
  1514. Cumulative input {}
  1515. Cumulative output {}
  1516. Cumulative total {}",
  1517. usage.latest.total_tokens(),
  1518. usage.cumulative.input_tokens,
  1519. usage.cumulative.output_tokens,
  1520. usage.cumulative.total_tokens(),
  1521. ),
  1522. format!(
  1523. "Workspace
  1524. Cwd {}
  1525. Project root {}
  1526. Git branch {}
  1527. Session {}
  1528. Config files loaded {}/{}
  1529. Memory files {}",
  1530. context.cwd.display(),
  1531. context
  1532. .project_root
  1533. .as_ref()
  1534. .map_or_else(|| "unknown".to_string(), |path| path.display().to_string()),
  1535. context.git_branch.as_deref().unwrap_or("unknown"),
  1536. context.session_path.as_ref().map_or_else(
  1537. || "live-repl".to_string(),
  1538. |path| path.display().to_string()
  1539. ),
  1540. context.loaded_config_files,
  1541. context.discovered_config_files,
  1542. context.memory_file_count,
  1543. ),
  1544. ]
  1545. .join(
  1546. "
  1547. ",
  1548. )
  1549. }
  1550. fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
  1551. let cwd = env::current_dir()?;
  1552. let loader = ConfigLoader::default_for(&cwd);
  1553. let discovered = loader.discover();
  1554. let runtime_config = loader.load()?;
  1555. let mut lines = vec![
  1556. format!(
  1557. "Config
  1558. Working directory {}
  1559. Loaded files {}
  1560. Merged keys {}",
  1561. cwd.display(),
  1562. runtime_config.loaded_entries().len(),
  1563. runtime_config.merged().len()
  1564. ),
  1565. "Discovered files".to_string(),
  1566. ];
  1567. for entry in discovered {
  1568. let source = match entry.source {
  1569. ConfigSource::User => "user",
  1570. ConfigSource::Project => "project",
  1571. ConfigSource::Local => "local",
  1572. };
  1573. let status = if runtime_config
  1574. .loaded_entries()
  1575. .iter()
  1576. .any(|loaded_entry| loaded_entry.path == entry.path)
  1577. {
  1578. "loaded"
  1579. } else {
  1580. "missing"
  1581. };
  1582. lines.push(format!(
  1583. " {source:<7} {status:<7} {}",
  1584. entry.path.display()
  1585. ));
  1586. }
  1587. if let Some(section) = section {
  1588. lines.push(format!("Merged section: {section}"));
  1589. let value = match section {
  1590. "env" => runtime_config.get("env"),
  1591. "hooks" => runtime_config.get("hooks"),
  1592. "model" => runtime_config.get("model"),
  1593. other => {
  1594. lines.push(format!(
  1595. " Unsupported config section '{other}'. Use env, hooks, or model."
  1596. ));
  1597. return Ok(lines.join(
  1598. "
  1599. ",
  1600. ));
  1601. }
  1602. };
  1603. lines.push(format!(
  1604. " {}",
  1605. match value {
  1606. Some(value) => value.render(),
  1607. None => "<unset>".to_string(),
  1608. }
  1609. ));
  1610. return Ok(lines.join(
  1611. "
  1612. ",
  1613. ));
  1614. }
  1615. lines.push("Merged JSON".to_string());
  1616. lines.push(format!(" {}", runtime_config.as_json().render()));
  1617. Ok(lines.join(
  1618. "
  1619. ",
  1620. ))
  1621. }
  1622. fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
  1623. let cwd = env::current_dir()?;
  1624. let project_context = ProjectContext::discover(&cwd, DEFAULT_DATE)?;
  1625. let mut lines = vec![format!(
  1626. "Memory
  1627. Working directory {}
  1628. Instruction files {}",
  1629. cwd.display(),
  1630. project_context.instruction_files.len()
  1631. )];
  1632. if project_context.instruction_files.is_empty() {
  1633. lines.push("Discovered files".to_string());
  1634. lines.push(
  1635. " No CLAUDE instruction files discovered in the current directory ancestry."
  1636. .to_string(),
  1637. );
  1638. } else {
  1639. lines.push("Discovered files".to_string());
  1640. for (index, file) in project_context.instruction_files.iter().enumerate() {
  1641. let preview = file.content.lines().next().unwrap_or("").trim();
  1642. let preview = if preview.is_empty() {
  1643. "<empty>"
  1644. } else {
  1645. preview
  1646. };
  1647. lines.push(format!(" {}. {}", index + 1, file.path.display(),));
  1648. lines.push(format!(
  1649. " lines={} preview={}",
  1650. file.content.lines().count(),
  1651. preview
  1652. ));
  1653. }
  1654. }
  1655. Ok(lines.join(
  1656. "
  1657. ",
  1658. ))
  1659. }
  1660. fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
  1661. let cwd = env::current_dir()?;
  1662. Ok(initialize_repo(&cwd)?.render())
  1663. }
  1664. fn run_init() -> Result<(), Box<dyn std::error::Error>> {
  1665. println!("{}", init_claude_md()?);
  1666. Ok(())
  1667. }
  1668. fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
  1669. match mode.trim() {
  1670. "read-only" => Some("read-only"),
  1671. "workspace-write" => Some("workspace-write"),
  1672. "danger-full-access" => Some("danger-full-access"),
  1673. _ => None,
  1674. }
  1675. }
  1676. fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
  1677. let output = std::process::Command::new("git")
  1678. .args(["diff", "--", ":(exclude).omx"])
  1679. .current_dir(env::current_dir()?)
  1680. .output()?;
  1681. if !output.status.success() {
  1682. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  1683. return Err(format!("git diff failed: {stderr}").into());
  1684. }
  1685. let diff = String::from_utf8(output.stdout)?;
  1686. if diff.trim().is_empty() {
  1687. return Ok(
  1688. "Diff\n Result clean working tree\n Detail no current changes"
  1689. .to_string(),
  1690. );
  1691. }
  1692. Ok(format!("Diff\n\n{}", diff.trim_end()))
  1693. }
  1694. fn render_version_report() -> String {
  1695. let git_sha = GIT_SHA.unwrap_or("unknown");
  1696. let target = BUILD_TARGET.unwrap_or("unknown");
  1697. format!(
  1698. "Claw Code\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
  1699. )
  1700. }
  1701. fn render_export_text(session: &Session) -> String {
  1702. let mut lines = vec!["# Conversation Export".to_string(), String::new()];
  1703. for (index, message) in session.messages.iter().enumerate() {
  1704. let role = match message.role {
  1705. MessageRole::System => "system",
  1706. MessageRole::User => "user",
  1707. MessageRole::Assistant => "assistant",
  1708. MessageRole::Tool => "tool",
  1709. };
  1710. lines.push(format!("## {}. {role}", index + 1));
  1711. for block in &message.blocks {
  1712. match block {
  1713. ContentBlock::Text { text } => lines.push(text.clone()),
  1714. ContentBlock::ToolUse { id, name, input } => {
  1715. lines.push(format!("[tool_use id={id} name={name}] {input}"));
  1716. }
  1717. ContentBlock::ToolResult {
  1718. tool_use_id,
  1719. tool_name,
  1720. output,
  1721. is_error,
  1722. } => {
  1723. lines.push(format!(
  1724. "[tool_result id={tool_use_id} name={tool_name} error={is_error}] {output}"
  1725. ));
  1726. }
  1727. }
  1728. }
  1729. lines.push(String::new());
  1730. }
  1731. lines.join("\n")
  1732. }
  1733. fn default_export_filename(session: &Session) -> String {
  1734. let stem = session
  1735. .messages
  1736. .iter()
  1737. .find_map(|message| match message.role {
  1738. MessageRole::User => message.blocks.iter().find_map(|block| match block {
  1739. ContentBlock::Text { text } => Some(text.as_str()),
  1740. _ => None,
  1741. }),
  1742. _ => None,
  1743. })
  1744. .map_or("conversation", |text| {
  1745. text.lines().next().unwrap_or("conversation")
  1746. })
  1747. .chars()
  1748. .map(|ch| {
  1749. if ch.is_ascii_alphanumeric() {
  1750. ch.to_ascii_lowercase()
  1751. } else {
  1752. '-'
  1753. }
  1754. })
  1755. .collect::<String>()
  1756. .split('-')
  1757. .filter(|part| !part.is_empty())
  1758. .take(8)
  1759. .collect::<Vec<_>>()
  1760. .join("-");
  1761. let fallback = if stem.is_empty() {
  1762. "conversation"
  1763. } else {
  1764. &stem
  1765. };
  1766. format!("{fallback}.txt")
  1767. }
  1768. fn resolve_export_path(
  1769. requested_path: Option<&str>,
  1770. session: &Session,
  1771. ) -> Result<PathBuf, Box<dyn std::error::Error>> {
  1772. let cwd = env::current_dir()?;
  1773. let file_name =
  1774. requested_path.map_or_else(|| default_export_filename(session), ToOwned::to_owned);
  1775. let final_name = if Path::new(&file_name)
  1776. .extension()
  1777. .is_some_and(|ext| ext.eq_ignore_ascii_case("txt"))
  1778. {
  1779. file_name
  1780. } else {
  1781. format!("{file_name}.txt")
  1782. };
  1783. Ok(cwd.join(final_name))
  1784. }
  1785. fn build_system_prompt() -> Result<Vec<String>, Box<dyn std::error::Error>> {
  1786. Ok(load_system_prompt(
  1787. env::current_dir()?,
  1788. DEFAULT_DATE,
  1789. env::consts::OS,
  1790. "unknown",
  1791. )?)
  1792. }
  1793. fn build_runtime_feature_config(
  1794. ) -> Result<runtime::RuntimeFeatureConfig, Box<dyn std::error::Error>> {
  1795. let cwd = env::current_dir()?;
  1796. Ok(ConfigLoader::default_for(cwd)
  1797. .load()?
  1798. .feature_config()
  1799. .clone())
  1800. }
  1801. fn build_runtime(
  1802. session: Session,
  1803. session_id: &str,
  1804. model: String,
  1805. system_prompt: Vec<String>,
  1806. enable_tools: bool,
  1807. emit_output: bool,
  1808. allowed_tools: Option<AllowedToolSet>,
  1809. permission_mode: PermissionMode,
  1810. ) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
  1811. {
  1812. let session_tracer = build_session_tracer(session_id)?;
  1813. let api_client = match session_tracer.clone() {
  1814. Some(session_tracer) => AnthropicRuntimeClient::new(
  1815. model,
  1816. enable_tools,
  1817. emit_output,
  1818. allowed_tools.clone(),
  1819. )?
  1820. .with_session_tracer(session_tracer),
  1821. None => AnthropicRuntimeClient::new(model, enable_tools, emit_output, allowed_tools.clone())?,
  1822. };
  1823. let runtime = ConversationRuntime::new_with_features(
  1824. session,
  1825. api_client,
  1826. CliToolExecutor::new(allowed_tools, emit_output),
  1827. permission_policy(permission_mode),
  1828. system_prompt,
  1829. &build_runtime_feature_config()?,
  1830. );
  1831. Ok(match session_tracer {
  1832. Some(session_tracer) => runtime.with_session_tracer(session_tracer),
  1833. None => runtime,
  1834. })
  1835. }
  1836. fn build_session_tracer(
  1837. session_id: &str,
  1838. ) -> Result<Option<SessionTracer>, Box<dyn std::error::Error>> {
  1839. let Some(path) = env::var_os(TELEMETRY_LOG_PATH_ENV) else {
  1840. return Ok(None);
  1841. };
  1842. let sink = JsonlTelemetrySink::new(PathBuf::from(path))?;
  1843. Ok(Some(SessionTracer::new(
  1844. session_id.to_string(),
  1845. std::sync::Arc::new(sink),
  1846. )))
  1847. }
  1848. struct CliPermissionPrompter {
  1849. current_mode: PermissionMode,
  1850. }
  1851. impl CliPermissionPrompter {
  1852. fn new(current_mode: PermissionMode) -> Self {
  1853. Self { current_mode }
  1854. }
  1855. }
  1856. impl runtime::PermissionPrompter for CliPermissionPrompter {
  1857. fn decide(
  1858. &mut self,
  1859. request: &runtime::PermissionRequest,
  1860. ) -> runtime::PermissionPromptDecision {
  1861. println!();
  1862. println!("Permission approval required");
  1863. println!(" Tool {}", request.tool_name);
  1864. println!(" Current mode {}", self.current_mode.as_str());
  1865. println!(" Required mode {}", request.required_mode.as_str());
  1866. println!(" Input {}", request.input);
  1867. print!("Approve this tool call? [y/N]: ");
  1868. let _ = io::stdout().flush();
  1869. let mut response = String::new();
  1870. match io::stdin().read_line(&mut response) {
  1871. Ok(_) => {
  1872. let normalized = response.trim().to_ascii_lowercase();
  1873. if matches!(normalized.as_str(), "y" | "yes") {
  1874. runtime::PermissionPromptDecision::Allow
  1875. } else {
  1876. runtime::PermissionPromptDecision::Deny {
  1877. reason: format!(
  1878. "tool '{}' denied by user approval prompt",
  1879. request.tool_name
  1880. ),
  1881. }
  1882. }
  1883. }
  1884. Err(error) => runtime::PermissionPromptDecision::Deny {
  1885. reason: format!("permission approval failed: {error}"),
  1886. },
  1887. }
  1888. }
  1889. }
  1890. struct AnthropicRuntimeClient {
  1891. runtime: tokio::runtime::Runtime,
  1892. client: AnthropicClient,
  1893. model: String,
  1894. enable_tools: bool,
  1895. emit_output: bool,
  1896. allowed_tools: Option<AllowedToolSet>,
  1897. }
  1898. impl AnthropicRuntimeClient {
  1899. fn new(
  1900. model: String,
  1901. enable_tools: bool,
  1902. emit_output: bool,
  1903. allowed_tools: Option<AllowedToolSet>,
  1904. ) -> Result<Self, Box<dyn std::error::Error>> {
  1905. Ok(Self {
  1906. runtime: tokio::runtime::Runtime::new()?,
  1907. client: AnthropicClient::from_auth(resolve_cli_auth_source()?)
  1908. .with_base_url(api::read_base_url()),
  1909. model,
  1910. enable_tools,
  1911. emit_output,
  1912. allowed_tools,
  1913. })
  1914. }
  1915. fn with_session_tracer(mut self, session_tracer: SessionTracer) -> Self {
  1916. self.client = self.client.with_session_tracer(session_tracer);
  1917. self
  1918. }
  1919. }
  1920. fn resolve_cli_auth_source() -> Result<AuthSource, Box<dyn std::error::Error>> {
  1921. Ok(resolve_startup_auth_source(|| {
  1922. let cwd = env::current_dir().map_err(api::ApiError::from)?;
  1923. let config = ConfigLoader::default_for(&cwd).load().map_err(|error| {
  1924. api::ApiError::Auth(format!("failed to load runtime OAuth config: {error}"))
  1925. })?;
  1926. Ok(config.oauth().cloned())
  1927. })?)
  1928. }
  1929. impl ApiClient for AnthropicRuntimeClient {
  1930. #[allow(clippy::too_many_lines)]
  1931. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  1932. let message_request = MessageRequest {
  1933. model: self.model.clone(),
  1934. max_tokens: max_tokens_for_model(&self.model),
  1935. messages: convert_messages(&request.messages),
  1936. system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
  1937. tools: self.enable_tools.then(|| {
  1938. filter_tool_specs(self.allowed_tools.as_ref())
  1939. .into_iter()
  1940. .map(|spec| ToolDefinition {
  1941. name: spec.name.to_string(),
  1942. description: Some(spec.description.to_string()),
  1943. input_schema: spec.input_schema,
  1944. })
  1945. .collect()
  1946. }),
  1947. tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
  1948. stream: true,
  1949. };
  1950. self.runtime.block_on(async {
  1951. let mut stream = self
  1952. .client
  1953. .stream_message(&message_request)
  1954. .await
  1955. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1956. let mut stdout = io::stdout();
  1957. let mut sink = io::sink();
  1958. let out: &mut dyn Write = if self.emit_output {
  1959. &mut stdout
  1960. } else {
  1961. &mut sink
  1962. };
  1963. let renderer = TerminalRenderer::new();
  1964. let mut markdown_stream = MarkdownStreamState::default();
  1965. let mut events = Vec::new();
  1966. let mut pending_tool: Option<(String, String, String)> = None;
  1967. let mut saw_stop = false;
  1968. while let Some(event) = stream
  1969. .next_event()
  1970. .await
  1971. .map_err(|error| RuntimeError::new(error.to_string()))?
  1972. {
  1973. match event {
  1974. ApiStreamEvent::MessageStart(start) => {
  1975. for block in start.message.content {
  1976. push_output_block(block, out, &mut events, &mut pending_tool, true)?;
  1977. }
  1978. }
  1979. ApiStreamEvent::ContentBlockStart(start) => {
  1980. push_output_block(
  1981. start.content_block,
  1982. out,
  1983. &mut events,
  1984. &mut pending_tool,
  1985. true,
  1986. )?;
  1987. }
  1988. ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
  1989. ContentBlockDelta::TextDelta { text } => {
  1990. if !text.is_empty() {
  1991. if let Some(rendered) = markdown_stream.push(&renderer, &text) {
  1992. write!(out, "{rendered}")
  1993. .and_then(|()| out.flush())
  1994. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1995. }
  1996. events.push(AssistantEvent::TextDelta(text));
  1997. }
  1998. }
  1999. ContentBlockDelta::InputJsonDelta { partial_json } => {
  2000. if let Some((_, _, input)) = &mut pending_tool {
  2001. input.push_str(&partial_json);
  2002. }
  2003. }
  2004. },
  2005. ApiStreamEvent::ContentBlockStop(_) => {
  2006. if let Some(rendered) = markdown_stream.flush(&renderer) {
  2007. write!(out, "{rendered}")
  2008. .and_then(|()| out.flush())
  2009. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2010. }
  2011. if let Some((id, name, input)) = pending_tool.take() {
  2012. // Display tool call now that input is fully accumulated
  2013. writeln!(out, "\n{}", format_tool_call_start(&name, &input))
  2014. .and_then(|()| out.flush())
  2015. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2016. events.push(AssistantEvent::ToolUse { id, name, input });
  2017. }
  2018. }
  2019. ApiStreamEvent::MessageDelta(delta) => {
  2020. events.push(AssistantEvent::Usage(TokenUsage {
  2021. input_tokens: delta.usage.input_tokens,
  2022. output_tokens: delta.usage.output_tokens,
  2023. cache_creation_input_tokens: 0,
  2024. cache_read_input_tokens: 0,
  2025. }));
  2026. }
  2027. ApiStreamEvent::MessageStop(_) => {
  2028. saw_stop = true;
  2029. if let Some(rendered) = markdown_stream.flush(&renderer) {
  2030. write!(out, "{rendered}")
  2031. .and_then(|()| out.flush())
  2032. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2033. }
  2034. events.push(AssistantEvent::MessageStop);
  2035. }
  2036. }
  2037. }
  2038. if !saw_stop
  2039. && events.iter().any(|event| {
  2040. matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
  2041. || matches!(event, AssistantEvent::ToolUse { .. })
  2042. })
  2043. {
  2044. events.push(AssistantEvent::MessageStop);
  2045. }
  2046. if events
  2047. .iter()
  2048. .any(|event| matches!(event, AssistantEvent::MessageStop))
  2049. {
  2050. return Ok(events);
  2051. }
  2052. let response = self
  2053. .client
  2054. .send_message(&MessageRequest {
  2055. stream: false,
  2056. ..message_request.clone()
  2057. })
  2058. .await
  2059. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2060. response_to_events(response, out)
  2061. })
  2062. }
  2063. }
  2064. fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
  2065. summary
  2066. .assistant_messages
  2067. .last()
  2068. .map(|message| {
  2069. message
  2070. .blocks
  2071. .iter()
  2072. .filter_map(|block| match block {
  2073. ContentBlock::Text { text } => Some(text.as_str()),
  2074. _ => None,
  2075. })
  2076. .collect::<Vec<_>>()
  2077. .join("")
  2078. })
  2079. .unwrap_or_default()
  2080. }
  2081. fn collect_tool_uses(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  2082. summary
  2083. .assistant_messages
  2084. .iter()
  2085. .flat_map(|message| message.blocks.iter())
  2086. .filter_map(|block| match block {
  2087. ContentBlock::ToolUse { id, name, input } => Some(json!({
  2088. "id": id,
  2089. "name": name,
  2090. "input": input,
  2091. })),
  2092. _ => None,
  2093. })
  2094. .collect()
  2095. }
  2096. fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
  2097. summary
  2098. .tool_results
  2099. .iter()
  2100. .flat_map(|message| message.blocks.iter())
  2101. .filter_map(|block| match block {
  2102. ContentBlock::ToolResult {
  2103. tool_use_id,
  2104. tool_name,
  2105. output,
  2106. is_error,
  2107. } => Some(json!({
  2108. "tool_use_id": tool_use_id,
  2109. "tool_name": tool_name,
  2110. "output": output,
  2111. "is_error": is_error,
  2112. })),
  2113. _ => None,
  2114. })
  2115. .collect()
  2116. }
  2117. fn slash_command_completion_candidates() -> Vec<String> {
  2118. slash_command_specs()
  2119. .iter()
  2120. .map(|spec| format!("/{}", spec.name))
  2121. .collect()
  2122. }
  2123. fn format_tool_call_start(name: &str, input: &str) -> String {
  2124. let parsed: serde_json::Value =
  2125. serde_json::from_str(input).unwrap_or(serde_json::Value::String(input.to_string()));
  2126. let detail = match name {
  2127. "bash" | "Bash" => format_bash_call(&parsed),
  2128. "read_file" | "Read" => {
  2129. let path = extract_tool_path(&parsed);
  2130. format!("\x1b[2m📄 Reading {path}…\x1b[0m")
  2131. }
  2132. "write_file" | "Write" => {
  2133. let path = extract_tool_path(&parsed);
  2134. let lines = parsed
  2135. .get("content")
  2136. .and_then(|value| value.as_str())
  2137. .map_or(0, |content| content.lines().count());
  2138. format!("\x1b[1;32m✏️ Writing {path}\x1b[0m \x1b[2m({lines} lines)\x1b[0m")
  2139. }
  2140. "edit_file" | "Edit" => {
  2141. let path = extract_tool_path(&parsed);
  2142. let old_value = parsed
  2143. .get("old_string")
  2144. .or_else(|| parsed.get("oldString"))
  2145. .and_then(|value| value.as_str())
  2146. .unwrap_or_default();
  2147. let new_value = parsed
  2148. .get("new_string")
  2149. .or_else(|| parsed.get("newString"))
  2150. .and_then(|value| value.as_str())
  2151. .unwrap_or_default();
  2152. format!(
  2153. "\x1b[1;33m📝 Editing {path}\x1b[0m{}",
  2154. format_patch_preview(old_value, new_value)
  2155. .map(|preview| format!("\n{preview}"))
  2156. .unwrap_or_default()
  2157. )
  2158. }
  2159. "glob_search" | "Glob" => format_search_start("🔎 Glob", &parsed),
  2160. "grep_search" | "Grep" => format_search_start("🔎 Grep", &parsed),
  2161. "web_search" | "WebSearch" => parsed
  2162. .get("query")
  2163. .and_then(|value| value.as_str())
  2164. .unwrap_or("?")
  2165. .to_string(),
  2166. _ => summarize_tool_payload(input),
  2167. };
  2168. let border = "─".repeat(name.len() + 8);
  2169. format!(
  2170. "\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"
  2171. )
  2172. }
  2173. fn format_tool_result(name: &str, output: &str, is_error: bool) -> String {
  2174. let icon = if is_error {
  2175. "\x1b[1;31m✗\x1b[0m"
  2176. } else {
  2177. "\x1b[1;32m✓\x1b[0m"
  2178. };
  2179. if is_error {
  2180. let summary = truncate_for_summary(output.trim(), 160);
  2181. return if summary.is_empty() {
  2182. format!("{icon} \x1b[38;5;245m{name}\x1b[0m")
  2183. } else {
  2184. format!("{icon} \x1b[38;5;245m{name}\x1b[0m\n\x1b[38;5;203m{summary}\x1b[0m")
  2185. };
  2186. }
  2187. let parsed: serde_json::Value =
  2188. serde_json::from_str(output).unwrap_or(serde_json::Value::String(output.to_string()));
  2189. match name {
  2190. "bash" | "Bash" => format_bash_result(icon, &parsed),
  2191. "read_file" | "Read" => format_read_result(icon, &parsed),
  2192. "write_file" | "Write" => format_write_result(icon, &parsed),
  2193. "edit_file" | "Edit" => format_edit_result(icon, &parsed),
  2194. "glob_search" | "Glob" => format_glob_result(icon, &parsed),
  2195. "grep_search" | "Grep" => format_grep_result(icon, &parsed),
  2196. _ => {
  2197. let summary = truncate_for_summary(output.trim(), 200);
  2198. format!("{icon} \x1b[38;5;245m{name}:\x1b[0m {summary}")
  2199. }
  2200. }
  2201. }
  2202. fn extract_tool_path(parsed: &serde_json::Value) -> String {
  2203. parsed
  2204. .get("file_path")
  2205. .or_else(|| parsed.get("filePath"))
  2206. .or_else(|| parsed.get("path"))
  2207. .and_then(|value| value.as_str())
  2208. .unwrap_or("?")
  2209. .to_string()
  2210. }
  2211. fn format_search_start(label: &str, parsed: &serde_json::Value) -> String {
  2212. let pattern = parsed
  2213. .get("pattern")
  2214. .and_then(|value| value.as_str())
  2215. .unwrap_or("?");
  2216. let scope = parsed
  2217. .get("path")
  2218. .and_then(|value| value.as_str())
  2219. .unwrap_or(".");
  2220. format!("{label} {pattern}\n\x1b[2min {scope}\x1b[0m")
  2221. }
  2222. fn format_patch_preview(old_value: &str, new_value: &str) -> Option<String> {
  2223. if old_value.is_empty() && new_value.is_empty() {
  2224. return None;
  2225. }
  2226. Some(format!(
  2227. "\x1b[38;5;203m- {}\x1b[0m\n\x1b[38;5;70m+ {}\x1b[0m",
  2228. truncate_for_summary(first_visible_line(old_value), 72),
  2229. truncate_for_summary(first_visible_line(new_value), 72)
  2230. ))
  2231. }
  2232. fn format_bash_call(parsed: &serde_json::Value) -> String {
  2233. let command = parsed
  2234. .get("command")
  2235. .and_then(|value| value.as_str())
  2236. .unwrap_or_default();
  2237. if command.is_empty() {
  2238. String::new()
  2239. } else {
  2240. format!(
  2241. "\x1b[48;5;236;38;5;255m $ {} \x1b[0m",
  2242. truncate_for_summary(command, 160)
  2243. )
  2244. }
  2245. }
  2246. fn first_visible_line(text: &str) -> &str {
  2247. text.lines()
  2248. .find(|line| !line.trim().is_empty())
  2249. .unwrap_or(text)
  2250. }
  2251. fn format_bash_result(icon: &str, parsed: &serde_json::Value) -> String {
  2252. let mut lines = vec![format!("{icon} \x1b[38;5;245mbash\x1b[0m")];
  2253. if let Some(task_id) = parsed
  2254. .get("backgroundTaskId")
  2255. .and_then(|value| value.as_str())
  2256. {
  2257. write!(&mut lines[0], " backgrounded ({task_id})").expect("write to string");
  2258. } else if let Some(status) = parsed
  2259. .get("returnCodeInterpretation")
  2260. .and_then(|value| value.as_str())
  2261. .filter(|status| !status.is_empty())
  2262. {
  2263. write!(&mut lines[0], " {status}").expect("write to string");
  2264. }
  2265. if let Some(stdout) = parsed.get("stdout").and_then(|value| value.as_str()) {
  2266. if !stdout.trim().is_empty() {
  2267. lines.push(stdout.trim_end().to_string());
  2268. }
  2269. }
  2270. if let Some(stderr) = parsed.get("stderr").and_then(|value| value.as_str()) {
  2271. if !stderr.trim().is_empty() {
  2272. lines.push(format!("\x1b[38;5;203m{}\x1b[0m", stderr.trim_end()));
  2273. }
  2274. }
  2275. lines.join("\n\n")
  2276. }
  2277. fn format_read_result(icon: &str, parsed: &serde_json::Value) -> String {
  2278. let file = parsed.get("file").unwrap_or(parsed);
  2279. let path = extract_tool_path(file);
  2280. let start_line = file
  2281. .get("startLine")
  2282. .and_then(serde_json::Value::as_u64)
  2283. .unwrap_or(1);
  2284. let num_lines = file
  2285. .get("numLines")
  2286. .and_then(serde_json::Value::as_u64)
  2287. .unwrap_or(0);
  2288. let total_lines = file
  2289. .get("totalLines")
  2290. .and_then(serde_json::Value::as_u64)
  2291. .unwrap_or(num_lines);
  2292. let content = file
  2293. .get("content")
  2294. .and_then(|value| value.as_str())
  2295. .unwrap_or_default();
  2296. let end_line = start_line.saturating_add(num_lines.saturating_sub(1));
  2297. format!(
  2298. "{icon} \x1b[2m📄 Read {path} (lines {}-{} of {})\x1b[0m\n{}",
  2299. start_line,
  2300. end_line.max(start_line),
  2301. total_lines,
  2302. content
  2303. )
  2304. }
  2305. fn format_write_result(icon: &str, parsed: &serde_json::Value) -> String {
  2306. let path = extract_tool_path(parsed);
  2307. let kind = parsed
  2308. .get("type")
  2309. .and_then(|value| value.as_str())
  2310. .unwrap_or("write");
  2311. let line_count = parsed
  2312. .get("content")
  2313. .and_then(|value| value.as_str())
  2314. .map_or(0, |content| content.lines().count());
  2315. format!(
  2316. "{icon} \x1b[1;32m✏️ {} {path}\x1b[0m \x1b[2m({line_count} lines)\x1b[0m",
  2317. if kind == "create" { "Wrote" } else { "Updated" },
  2318. )
  2319. }
  2320. fn format_structured_patch_preview(parsed: &serde_json::Value) -> Option<String> {
  2321. let hunks = parsed.get("structuredPatch")?.as_array()?;
  2322. let mut preview = Vec::new();
  2323. for hunk in hunks.iter().take(2) {
  2324. let lines = hunk.get("lines")?.as_array()?;
  2325. for line in lines.iter().filter_map(|value| value.as_str()).take(6) {
  2326. match line.chars().next() {
  2327. Some('+') => preview.push(format!("\x1b[38;5;70m{line}\x1b[0m")),
  2328. Some('-') => preview.push(format!("\x1b[38;5;203m{line}\x1b[0m")),
  2329. _ => preview.push(line.to_string()),
  2330. }
  2331. }
  2332. }
  2333. if preview.is_empty() {
  2334. None
  2335. } else {
  2336. Some(preview.join("\n"))
  2337. }
  2338. }
  2339. fn format_edit_result(icon: &str, parsed: &serde_json::Value) -> String {
  2340. let path = extract_tool_path(parsed);
  2341. let suffix = if parsed
  2342. .get("replaceAll")
  2343. .and_then(serde_json::Value::as_bool)
  2344. .unwrap_or(false)
  2345. {
  2346. " (replace all)"
  2347. } else {
  2348. ""
  2349. };
  2350. let preview = format_structured_patch_preview(parsed).or_else(|| {
  2351. let old_value = parsed
  2352. .get("oldString")
  2353. .and_then(|value| value.as_str())
  2354. .unwrap_or_default();
  2355. let new_value = parsed
  2356. .get("newString")
  2357. .and_then(|value| value.as_str())
  2358. .unwrap_or_default();
  2359. format_patch_preview(old_value, new_value)
  2360. });
  2361. match preview {
  2362. Some(preview) => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m\n{preview}"),
  2363. None => format!("{icon} \x1b[1;33m📝 Edited {path}{suffix}\x1b[0m"),
  2364. }
  2365. }
  2366. fn format_glob_result(icon: &str, parsed: &serde_json::Value) -> String {
  2367. let num_files = parsed
  2368. .get("numFiles")
  2369. .and_then(serde_json::Value::as_u64)
  2370. .unwrap_or(0);
  2371. let filenames = parsed
  2372. .get("filenames")
  2373. .and_then(|value| value.as_array())
  2374. .map(|files| {
  2375. files
  2376. .iter()
  2377. .filter_map(|value| value.as_str())
  2378. .take(8)
  2379. .collect::<Vec<_>>()
  2380. .join("\n")
  2381. })
  2382. .unwrap_or_default();
  2383. if filenames.is_empty() {
  2384. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files")
  2385. } else {
  2386. format!("{icon} \x1b[38;5;245mglob_search\x1b[0m matched {num_files} files\n{filenames}")
  2387. }
  2388. }
  2389. fn format_grep_result(icon: &str, parsed: &serde_json::Value) -> String {
  2390. let num_matches = parsed
  2391. .get("numMatches")
  2392. .and_then(serde_json::Value::as_u64)
  2393. .unwrap_or(0);
  2394. let num_files = parsed
  2395. .get("numFiles")
  2396. .and_then(serde_json::Value::as_u64)
  2397. .unwrap_or(0);
  2398. let content = parsed
  2399. .get("content")
  2400. .and_then(|value| value.as_str())
  2401. .unwrap_or_default();
  2402. let filenames = parsed
  2403. .get("filenames")
  2404. .and_then(|value| value.as_array())
  2405. .map(|files| {
  2406. files
  2407. .iter()
  2408. .filter_map(|value| value.as_str())
  2409. .take(8)
  2410. .collect::<Vec<_>>()
  2411. .join("\n")
  2412. })
  2413. .unwrap_or_default();
  2414. let summary = format!(
  2415. "{icon} \x1b[38;5;245mgrep_search\x1b[0m {num_matches} matches across {num_files} files"
  2416. );
  2417. if !content.trim().is_empty() {
  2418. format!("{summary}\n{}", content.trim_end())
  2419. } else if !filenames.is_empty() {
  2420. format!("{summary}\n{filenames}")
  2421. } else {
  2422. summary
  2423. }
  2424. }
  2425. fn summarize_tool_payload(payload: &str) -> String {
  2426. let compact = match serde_json::from_str::<serde_json::Value>(payload) {
  2427. Ok(value) => value.to_string(),
  2428. Err(_) => payload.trim().to_string(),
  2429. };
  2430. truncate_for_summary(&compact, 96)
  2431. }
  2432. fn truncate_for_summary(value: &str, limit: usize) -> String {
  2433. let mut chars = value.chars();
  2434. let truncated = chars.by_ref().take(limit).collect::<String>();
  2435. if chars.next().is_some() {
  2436. format!("{truncated}…")
  2437. } else {
  2438. truncated
  2439. }
  2440. }
  2441. fn push_output_block(
  2442. block: OutputContentBlock,
  2443. out: &mut (impl Write + ?Sized),
  2444. events: &mut Vec<AssistantEvent>,
  2445. pending_tool: &mut Option<(String, String, String)>,
  2446. streaming_tool_input: bool,
  2447. ) -> Result<(), RuntimeError> {
  2448. match block {
  2449. OutputContentBlock::Text { text } => {
  2450. if !text.is_empty() {
  2451. let rendered = TerminalRenderer::new().markdown_to_ansi(&text);
  2452. write!(out, "{rendered}")
  2453. .and_then(|()| out.flush())
  2454. .map_err(|error| RuntimeError::new(error.to_string()))?;
  2455. events.push(AssistantEvent::TextDelta(text));
  2456. }
  2457. }
  2458. OutputContentBlock::ToolUse { id, name, input } => {
  2459. // During streaming, the initial content_block_start has an empty input ({}).
  2460. // The real input arrives via input_json_delta events. In
  2461. // non-streaming responses, preserve a legitimate empty object.
  2462. let initial_input = if streaming_tool_input
  2463. && input.is_object()
  2464. && input.as_object().is_some_and(serde_json::Map::is_empty)
  2465. {
  2466. String::new()
  2467. } else {
  2468. input.to_string()
  2469. };
  2470. *pending_tool = Some((id, name, initial_input));
  2471. }
  2472. }
  2473. Ok(())
  2474. }
  2475. fn response_to_events(
  2476. response: MessageResponse,
  2477. out: &mut (impl Write + ?Sized),
  2478. ) -> Result<Vec<AssistantEvent>, RuntimeError> {
  2479. let mut events = Vec::new();
  2480. let mut pending_tool = None;
  2481. for block in response.content {
  2482. push_output_block(block, out, &mut events, &mut pending_tool, false)?;
  2483. if let Some((id, name, input)) = pending_tool.take() {
  2484. events.push(AssistantEvent::ToolUse { id, name, input });
  2485. }
  2486. }
  2487. events.push(AssistantEvent::Usage(TokenUsage {
  2488. input_tokens: response.usage.input_tokens,
  2489. output_tokens: response.usage.output_tokens,
  2490. cache_creation_input_tokens: response.usage.cache_creation_input_tokens,
  2491. cache_read_input_tokens: response.usage.cache_read_input_tokens,
  2492. }));
  2493. events.push(AssistantEvent::MessageStop);
  2494. Ok(events)
  2495. }
  2496. struct CliToolExecutor {
  2497. renderer: TerminalRenderer,
  2498. emit_output: bool,
  2499. allowed_tools: Option<AllowedToolSet>,
  2500. }
  2501. impl CliToolExecutor {
  2502. fn new(allowed_tools: Option<AllowedToolSet>, emit_output: bool) -> Self {
  2503. Self {
  2504. renderer: TerminalRenderer::new(),
  2505. emit_output,
  2506. allowed_tools,
  2507. }
  2508. }
  2509. }
  2510. impl ToolExecutor for CliToolExecutor {
  2511. fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
  2512. if self
  2513. .allowed_tools
  2514. .as_ref()
  2515. .is_some_and(|allowed| !allowed.contains(tool_name))
  2516. {
  2517. return Err(ToolError::new(format!(
  2518. "tool `{tool_name}` is not enabled by the current --allowedTools setting"
  2519. )));
  2520. }
  2521. let value = serde_json::from_str(input)
  2522. .map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
  2523. match execute_tool(tool_name, &value) {
  2524. Ok(output) => {
  2525. if self.emit_output {
  2526. let markdown = format_tool_result(tool_name, &output, false);
  2527. self.renderer
  2528. .stream_markdown(&markdown, &mut io::stdout())
  2529. .map_err(|error| ToolError::new(error.to_string()))?;
  2530. }
  2531. Ok(output)
  2532. }
  2533. Err(error) => {
  2534. if self.emit_output {
  2535. let markdown = format_tool_result(tool_name, &error, true);
  2536. self.renderer
  2537. .stream_markdown(&markdown, &mut io::stdout())
  2538. .map_err(|stream_error| ToolError::new(stream_error.to_string()))?;
  2539. }
  2540. Err(ToolError::new(error))
  2541. }
  2542. }
  2543. }
  2544. }
  2545. fn permission_policy(mode: PermissionMode) -> PermissionPolicy {
  2546. tool_permission_specs()
  2547. .into_iter()
  2548. .fold(PermissionPolicy::new(mode), |policy, spec| {
  2549. policy.with_tool_requirement(spec.name, spec.required_permission)
  2550. })
  2551. }
  2552. fn tool_permission_specs() -> Vec<ToolSpec> {
  2553. mvp_tool_specs()
  2554. }
  2555. fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
  2556. messages
  2557. .iter()
  2558. .filter_map(|message| {
  2559. let role = match message.role {
  2560. MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
  2561. MessageRole::Assistant => "assistant",
  2562. };
  2563. let content = message
  2564. .blocks
  2565. .iter()
  2566. .map(|block| match block {
  2567. ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
  2568. ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
  2569. id: id.clone(),
  2570. name: name.clone(),
  2571. input: serde_json::from_str(input)
  2572. .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
  2573. },
  2574. ContentBlock::ToolResult {
  2575. tool_use_id,
  2576. output,
  2577. is_error,
  2578. ..
  2579. } => InputContentBlock::ToolResult {
  2580. tool_use_id: tool_use_id.clone(),
  2581. content: vec![ToolResultContentBlock::Text {
  2582. text: output.clone(),
  2583. }],
  2584. is_error: *is_error,
  2585. },
  2586. })
  2587. .collect::<Vec<_>>();
  2588. (!content.is_empty()).then(|| InputMessage {
  2589. role: role.to_string(),
  2590. content,
  2591. })
  2592. })
  2593. .collect()
  2594. }
  2595. fn print_help_to(out: &mut impl Write) -> io::Result<()> {
  2596. writeln!(out, "claw v{VERSION}")?;
  2597. writeln!(out)?;
  2598. writeln!(out, "Usage:")?;
  2599. writeln!(
  2600. out,
  2601. " claw [--model MODEL] [--allowedTools TOOL[,TOOL...]]"
  2602. )?;
  2603. writeln!(out, " Start the interactive REPL")?;
  2604. writeln!(
  2605. out,
  2606. " claw [--model MODEL] [--output-format text|json] prompt TEXT"
  2607. )?;
  2608. writeln!(out, " Send one prompt and exit")?;
  2609. writeln!(
  2610. out,
  2611. " claw [--model MODEL] [--output-format text|json] TEXT"
  2612. )?;
  2613. writeln!(out, " Shorthand non-interactive prompt mode")?;
  2614. writeln!(
  2615. out,
  2616. " claw --resume SESSION.json [/status] [/compact] [...]"
  2617. )?;
  2618. writeln!(
  2619. out,
  2620. " Inspect or maintain a saved session without entering the REPL"
  2621. )?;
  2622. writeln!(out, " claw dump-manifests")?;
  2623. writeln!(out, " claw bootstrap-plan")?;
  2624. writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
  2625. writeln!(out, " claw login")?;
  2626. writeln!(out, " claw logout")?;
  2627. writeln!(out, " claw init")?;
  2628. writeln!(out)?;
  2629. writeln!(out, "Flags:")?;
  2630. writeln!(
  2631. out,
  2632. " --model MODEL Override the active model"
  2633. )?;
  2634. writeln!(
  2635. out,
  2636. " --output-format FORMAT Non-interactive output format: text or json"
  2637. )?;
  2638. writeln!(
  2639. out,
  2640. " --permission-mode MODE Set read-only, workspace-write, or danger-full-access"
  2641. )?;
  2642. writeln!(
  2643. out,
  2644. " --dangerously-skip-permissions Skip all permission checks"
  2645. )?;
  2646. writeln!(out, " --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)")?;
  2647. writeln!(
  2648. out,
  2649. " --version, -V Print version and build information locally"
  2650. )?;
  2651. writeln!(out)?;
  2652. writeln!(out, "Interactive slash commands:")?;
  2653. writeln!(out, "{}", render_slash_command_help())?;
  2654. writeln!(out)?;
  2655. let resume_commands = resume_supported_slash_commands()
  2656. .into_iter()
  2657. .map(|spec| match spec.argument_hint {
  2658. Some(argument_hint) => format!("/{} {}", spec.name, argument_hint),
  2659. None => format!("/{}", spec.name),
  2660. })
  2661. .collect::<Vec<_>>()
  2662. .join(", ");
  2663. writeln!(out, "Resume-safe commands: {resume_commands}")?;
  2664. writeln!(out, "Examples:")?;
  2665. writeln!(out, " claw --model claude-opus \"summarize this repo\"")?;
  2666. writeln!(
  2667. out,
  2668. " claw --output-format json prompt \"explain src/main.rs\""
  2669. )?;
  2670. writeln!(
  2671. out,
  2672. " claw --allowedTools read,glob \"summarize Cargo.toml\""
  2673. )?;
  2674. writeln!(
  2675. out,
  2676. " claw --resume session.json /status /diff /export notes.txt"
  2677. )?;
  2678. writeln!(out, " claw login")?;
  2679. writeln!(out, " claw init")?;
  2680. Ok(())
  2681. }
  2682. fn print_help() {
  2683. let _ = print_help_to(&mut io::stdout());
  2684. }
  2685. #[cfg(test)]
  2686. mod tests {
  2687. use super::{
  2688. filter_tool_specs, format_compact_report, format_cost_report, format_model_report,
  2689. format_model_switch_report, format_permissions_report, format_permissions_switch_report,
  2690. format_resume_report, format_status_report, format_tool_call_start, format_tool_result,
  2691. normalize_permission_mode, parse_args, parse_git_status_metadata, print_help_to,
  2692. push_output_block, render_config_report, render_memory_report, render_repl_help,
  2693. resolve_model_alias, response_to_events, resume_supported_slash_commands, status_context,
  2694. CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
  2695. };
  2696. use api::{MessageResponse, OutputContentBlock, Usage};
  2697. use runtime::{AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode};
  2698. use serde_json::json;
  2699. use std::path::PathBuf;
  2700. #[test]
  2701. fn defaults_to_repl_when_no_args() {
  2702. assert_eq!(
  2703. parse_args(&[]).expect("args should parse"),
  2704. CliAction::Repl {
  2705. model: DEFAULT_MODEL.to_string(),
  2706. allowed_tools: None,
  2707. permission_mode: PermissionMode::DangerFullAccess,
  2708. }
  2709. );
  2710. }
  2711. #[test]
  2712. fn parses_prompt_subcommand() {
  2713. let args = vec![
  2714. "prompt".to_string(),
  2715. "hello".to_string(),
  2716. "world".to_string(),
  2717. ];
  2718. assert_eq!(
  2719. parse_args(&args).expect("args should parse"),
  2720. CliAction::Prompt {
  2721. prompt: "hello world".to_string(),
  2722. model: DEFAULT_MODEL.to_string(),
  2723. output_format: CliOutputFormat::Text,
  2724. allowed_tools: None,
  2725. permission_mode: PermissionMode::DangerFullAccess,
  2726. }
  2727. );
  2728. }
  2729. #[test]
  2730. fn parses_bare_prompt_and_json_output_flag() {
  2731. let args = vec![
  2732. "--output-format=json".to_string(),
  2733. "--model".to_string(),
  2734. "claude-opus".to_string(),
  2735. "explain".to_string(),
  2736. "this".to_string(),
  2737. ];
  2738. assert_eq!(
  2739. parse_args(&args).expect("args should parse"),
  2740. CliAction::Prompt {
  2741. prompt: "explain this".to_string(),
  2742. model: "claude-opus".to_string(),
  2743. output_format: CliOutputFormat::Json,
  2744. allowed_tools: None,
  2745. permission_mode: PermissionMode::DangerFullAccess,
  2746. }
  2747. );
  2748. }
  2749. #[test]
  2750. fn resolves_model_aliases_in_args() {
  2751. let args = vec![
  2752. "--model".to_string(),
  2753. "opus".to_string(),
  2754. "explain".to_string(),
  2755. "this".to_string(),
  2756. ];
  2757. assert_eq!(
  2758. parse_args(&args).expect("args should parse"),
  2759. CliAction::Prompt {
  2760. prompt: "explain this".to_string(),
  2761. model: "claude-opus-4-6".to_string(),
  2762. output_format: CliOutputFormat::Text,
  2763. allowed_tools: None,
  2764. permission_mode: PermissionMode::DangerFullAccess,
  2765. }
  2766. );
  2767. }
  2768. #[test]
  2769. fn resolves_known_model_aliases() {
  2770. assert_eq!(resolve_model_alias("opus"), "claude-opus-4-6");
  2771. assert_eq!(resolve_model_alias("sonnet"), "claude-sonnet-4-6");
  2772. assert_eq!(resolve_model_alias("haiku"), "claude-haiku-4-5-20251213");
  2773. assert_eq!(resolve_model_alias("claude-opus"), "claude-opus");
  2774. }
  2775. #[test]
  2776. fn parses_version_flags_without_initializing_prompt_mode() {
  2777. assert_eq!(
  2778. parse_args(&["--version".to_string()]).expect("args should parse"),
  2779. CliAction::Version
  2780. );
  2781. assert_eq!(
  2782. parse_args(&["-V".to_string()]).expect("args should parse"),
  2783. CliAction::Version
  2784. );
  2785. }
  2786. #[test]
  2787. fn parses_permission_mode_flag() {
  2788. let args = vec!["--permission-mode=read-only".to_string()];
  2789. assert_eq!(
  2790. parse_args(&args).expect("args should parse"),
  2791. CliAction::Repl {
  2792. model: DEFAULT_MODEL.to_string(),
  2793. allowed_tools: None,
  2794. permission_mode: PermissionMode::ReadOnly,
  2795. }
  2796. );
  2797. }
  2798. #[test]
  2799. fn parses_allowed_tools_flags_with_aliases_and_lists() {
  2800. let args = vec![
  2801. "--allowedTools".to_string(),
  2802. "read,glob".to_string(),
  2803. "--allowed-tools=write_file".to_string(),
  2804. ];
  2805. assert_eq!(
  2806. parse_args(&args).expect("args should parse"),
  2807. CliAction::Repl {
  2808. model: DEFAULT_MODEL.to_string(),
  2809. allowed_tools: Some(
  2810. ["glob_search", "read_file", "write_file"]
  2811. .into_iter()
  2812. .map(str::to_string)
  2813. .collect()
  2814. ),
  2815. permission_mode: PermissionMode::DangerFullAccess,
  2816. }
  2817. );
  2818. }
  2819. #[test]
  2820. fn rejects_unknown_allowed_tools() {
  2821. let error = parse_args(&["--allowedTools".to_string(), "teleport".to_string()])
  2822. .expect_err("tool should be rejected");
  2823. assert!(error.contains("unsupported tool in --allowedTools: teleport"));
  2824. }
  2825. #[test]
  2826. fn parses_system_prompt_options() {
  2827. let args = vec![
  2828. "system-prompt".to_string(),
  2829. "--cwd".to_string(),
  2830. "/tmp/project".to_string(),
  2831. "--date".to_string(),
  2832. "2026-04-01".to_string(),
  2833. ];
  2834. assert_eq!(
  2835. parse_args(&args).expect("args should parse"),
  2836. CliAction::PrintSystemPrompt {
  2837. cwd: PathBuf::from("/tmp/project"),
  2838. date: "2026-04-01".to_string(),
  2839. }
  2840. );
  2841. }
  2842. #[test]
  2843. fn parses_login_and_logout_subcommands() {
  2844. assert_eq!(
  2845. parse_args(&["login".to_string()]).expect("login should parse"),
  2846. CliAction::Login
  2847. );
  2848. assert_eq!(
  2849. parse_args(&["logout".to_string()]).expect("logout should parse"),
  2850. CliAction::Logout
  2851. );
  2852. assert_eq!(
  2853. parse_args(&["init".to_string()]).expect("init should parse"),
  2854. CliAction::Init
  2855. );
  2856. }
  2857. #[test]
  2858. fn parses_resume_flag_with_slash_command() {
  2859. let args = vec![
  2860. "--resume".to_string(),
  2861. "session.json".to_string(),
  2862. "/compact".to_string(),
  2863. ];
  2864. assert_eq!(
  2865. parse_args(&args).expect("args should parse"),
  2866. CliAction::ResumeSession {
  2867. session_path: PathBuf::from("session.json"),
  2868. commands: vec!["/compact".to_string()],
  2869. }
  2870. );
  2871. }
  2872. #[test]
  2873. fn parses_resume_flag_with_multiple_slash_commands() {
  2874. let args = vec![
  2875. "--resume".to_string(),
  2876. "session.json".to_string(),
  2877. "/status".to_string(),
  2878. "/compact".to_string(),
  2879. "/cost".to_string(),
  2880. ];
  2881. assert_eq!(
  2882. parse_args(&args).expect("args should parse"),
  2883. CliAction::ResumeSession {
  2884. session_path: PathBuf::from("session.json"),
  2885. commands: vec![
  2886. "/status".to_string(),
  2887. "/compact".to_string(),
  2888. "/cost".to_string(),
  2889. ],
  2890. }
  2891. );
  2892. }
  2893. #[test]
  2894. fn filtered_tool_specs_respect_allowlist() {
  2895. let allowed = ["read_file", "grep_search"]
  2896. .into_iter()
  2897. .map(str::to_string)
  2898. .collect();
  2899. let filtered = filter_tool_specs(Some(&allowed));
  2900. let names = filtered
  2901. .into_iter()
  2902. .map(|spec| spec.name)
  2903. .collect::<Vec<_>>();
  2904. assert_eq!(names, vec!["read_file", "grep_search"]);
  2905. }
  2906. #[test]
  2907. fn shared_help_uses_resume_annotation_copy() {
  2908. let help = commands::render_slash_command_help();
  2909. assert!(help.contains("Slash commands"));
  2910. assert!(help.contains("works with --resume SESSION.json"));
  2911. }
  2912. #[test]
  2913. fn repl_help_includes_shared_commands_and_exit() {
  2914. let help = render_repl_help();
  2915. assert!(help.contains("REPL"));
  2916. assert!(help.contains("/help"));
  2917. assert!(help.contains("/status"));
  2918. assert!(help.contains("/model [model]"));
  2919. assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
  2920. assert!(help.contains("/clear [--confirm]"));
  2921. assert!(help.contains("/cost"));
  2922. assert!(help.contains("/resume <session-path>"));
  2923. assert!(help.contains("/config [env|hooks|model]"));
  2924. assert!(help.contains("/memory"));
  2925. assert!(help.contains("/init"));
  2926. assert!(help.contains("/diff"));
  2927. assert!(help.contains("/version"));
  2928. assert!(help.contains("/export [file]"));
  2929. assert!(help.contains("/session [list|switch <session-id>]"));
  2930. assert!(help.contains("/exit"));
  2931. }
  2932. #[test]
  2933. fn resume_supported_command_list_matches_expected_surface() {
  2934. let names = resume_supported_slash_commands()
  2935. .into_iter()
  2936. .map(|spec| spec.name)
  2937. .collect::<Vec<_>>();
  2938. assert_eq!(
  2939. names,
  2940. vec![
  2941. "help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
  2942. "version", "export",
  2943. ]
  2944. );
  2945. }
  2946. #[test]
  2947. fn resume_report_uses_sectioned_layout() {
  2948. let report = format_resume_report("session.json", 14, 6);
  2949. assert!(report.contains("Session resumed"));
  2950. assert!(report.contains("Session file session.json"));
  2951. assert!(report.contains("Messages 14"));
  2952. assert!(report.contains("Turns 6"));
  2953. }
  2954. #[test]
  2955. fn compact_report_uses_structured_output() {
  2956. let compacted = format_compact_report(8, 5, false);
  2957. assert!(compacted.contains("Compact"));
  2958. assert!(compacted.contains("Result compacted"));
  2959. assert!(compacted.contains("Messages removed 8"));
  2960. let skipped = format_compact_report(0, 3, true);
  2961. assert!(skipped.contains("Result skipped"));
  2962. }
  2963. #[test]
  2964. fn cost_report_uses_sectioned_layout() {
  2965. let report = format_cost_report(runtime::TokenUsage {
  2966. input_tokens: 20,
  2967. output_tokens: 8,
  2968. cache_creation_input_tokens: 3,
  2969. cache_read_input_tokens: 1,
  2970. });
  2971. assert!(report.contains("Cost"));
  2972. assert!(report.contains("Input tokens 20"));
  2973. assert!(report.contains("Output tokens 8"));
  2974. assert!(report.contains("Cache create 3"));
  2975. assert!(report.contains("Cache read 1"));
  2976. assert!(report.contains("Total tokens 32"));
  2977. }
  2978. #[test]
  2979. fn permissions_report_uses_sectioned_layout() {
  2980. let report = format_permissions_report("workspace-write");
  2981. assert!(report.contains("Permissions"));
  2982. assert!(report.contains("Active mode workspace-write"));
  2983. assert!(report.contains("Modes"));
  2984. assert!(report.contains("read-only ○ available Read/search tools only"));
  2985. assert!(report.contains("workspace-write ● current Edit files inside the workspace"));
  2986. assert!(report.contains("danger-full-access ○ available Unrestricted tool access"));
  2987. }
  2988. #[test]
  2989. fn permissions_switch_report_is_structured() {
  2990. let report = format_permissions_switch_report("read-only", "workspace-write");
  2991. assert!(report.contains("Permissions updated"));
  2992. assert!(report.contains("Result mode switched"));
  2993. assert!(report.contains("Previous mode read-only"));
  2994. assert!(report.contains("Active mode workspace-write"));
  2995. assert!(report.contains("Applies to subsequent tool calls"));
  2996. }
  2997. #[test]
  2998. fn init_help_mentions_direct_subcommand() {
  2999. let mut help = Vec::new();
  3000. print_help_to(&mut help).expect("help should render");
  3001. let help = String::from_utf8(help).expect("help should be utf8");
  3002. assert!(help.contains("claw init"));
  3003. }
  3004. #[test]
  3005. fn model_report_uses_sectioned_layout() {
  3006. let report = format_model_report("claude-sonnet", 12, 4);
  3007. assert!(report.contains("Model"));
  3008. assert!(report.contains("Current model claude-sonnet"));
  3009. assert!(report.contains("Session messages 12"));
  3010. assert!(report.contains("Switch models with /model <name>"));
  3011. }
  3012. #[test]
  3013. fn model_switch_report_preserves_context_summary() {
  3014. let report = format_model_switch_report("claude-sonnet", "claude-opus", 9);
  3015. assert!(report.contains("Model updated"));
  3016. assert!(report.contains("Previous claude-sonnet"));
  3017. assert!(report.contains("Current claude-opus"));
  3018. assert!(report.contains("Preserved msgs 9"));
  3019. }
  3020. #[test]
  3021. fn status_line_reports_model_and_token_totals() {
  3022. let status = format_status_report(
  3023. "claude-sonnet",
  3024. StatusUsage {
  3025. message_count: 7,
  3026. turns: 3,
  3027. latest: runtime::TokenUsage {
  3028. input_tokens: 5,
  3029. output_tokens: 4,
  3030. cache_creation_input_tokens: 1,
  3031. cache_read_input_tokens: 0,
  3032. },
  3033. cumulative: runtime::TokenUsage {
  3034. input_tokens: 20,
  3035. output_tokens: 8,
  3036. cache_creation_input_tokens: 2,
  3037. cache_read_input_tokens: 1,
  3038. },
  3039. estimated_tokens: 128,
  3040. },
  3041. "workspace-write",
  3042. &super::StatusContext {
  3043. cwd: PathBuf::from("/tmp/project"),
  3044. session_path: Some(PathBuf::from("session.json")),
  3045. loaded_config_files: 2,
  3046. discovered_config_files: 3,
  3047. memory_file_count: 4,
  3048. project_root: Some(PathBuf::from("/tmp")),
  3049. git_branch: Some("main".to_string()),
  3050. },
  3051. );
  3052. assert!(status.contains("Status"));
  3053. assert!(status.contains("Model claude-sonnet"));
  3054. assert!(status.contains("Permission mode workspace-write"));
  3055. assert!(status.contains("Messages 7"));
  3056. assert!(status.contains("Latest total 10"));
  3057. assert!(status.contains("Cumulative total 31"));
  3058. assert!(status.contains("Cwd /tmp/project"));
  3059. assert!(status.contains("Project root /tmp"));
  3060. assert!(status.contains("Git branch main"));
  3061. assert!(status.contains("Session session.json"));
  3062. assert!(status.contains("Config files loaded 2/3"));
  3063. assert!(status.contains("Memory files 4"));
  3064. }
  3065. #[test]
  3066. fn config_report_supports_section_views() {
  3067. let report = render_config_report(Some("env")).expect("config report should render");
  3068. assert!(report.contains("Merged section: env"));
  3069. }
  3070. #[test]
  3071. fn memory_report_uses_sectioned_layout() {
  3072. let report = render_memory_report().expect("memory report should render");
  3073. assert!(report.contains("Memory"));
  3074. assert!(report.contains("Working directory"));
  3075. assert!(report.contains("Instruction files"));
  3076. assert!(report.contains("Discovered files"));
  3077. }
  3078. #[test]
  3079. fn config_report_uses_sectioned_layout() {
  3080. let report = render_config_report(None).expect("config report should render");
  3081. assert!(report.contains("Config"));
  3082. assert!(report.contains("Discovered files"));
  3083. assert!(report.contains("Merged JSON"));
  3084. }
  3085. #[test]
  3086. fn parses_git_status_metadata() {
  3087. let (root, branch) = parse_git_status_metadata(Some(
  3088. "## rcc/cli...origin/rcc/cli
  3089. M src/main.rs",
  3090. ));
  3091. assert_eq!(branch.as_deref(), Some("rcc/cli"));
  3092. let _ = root;
  3093. }
  3094. #[test]
  3095. fn status_context_reads_real_workspace_metadata() {
  3096. let context = status_context(None).expect("status context should load");
  3097. assert!(context.cwd.is_absolute());
  3098. assert_eq!(context.discovered_config_files, 5);
  3099. assert!(context.loaded_config_files <= context.discovered_config_files);
  3100. }
  3101. #[test]
  3102. fn normalizes_supported_permission_modes() {
  3103. assert_eq!(normalize_permission_mode("read-only"), Some("read-only"));
  3104. assert_eq!(
  3105. normalize_permission_mode("workspace-write"),
  3106. Some("workspace-write")
  3107. );
  3108. assert_eq!(
  3109. normalize_permission_mode("danger-full-access"),
  3110. Some("danger-full-access")
  3111. );
  3112. assert_eq!(normalize_permission_mode("unknown"), None);
  3113. }
  3114. #[test]
  3115. fn clear_command_requires_explicit_confirmation_flag() {
  3116. assert_eq!(
  3117. SlashCommand::parse("/clear"),
  3118. Some(SlashCommand::Clear { confirm: false })
  3119. );
  3120. assert_eq!(
  3121. SlashCommand::parse("/clear --confirm"),
  3122. Some(SlashCommand::Clear { confirm: true })
  3123. );
  3124. }
  3125. #[test]
  3126. fn parses_resume_and_config_slash_commands() {
  3127. assert_eq!(
  3128. SlashCommand::parse("/resume saved-session.json"),
  3129. Some(SlashCommand::Resume {
  3130. session_path: Some("saved-session.json".to_string())
  3131. })
  3132. );
  3133. assert_eq!(
  3134. SlashCommand::parse("/clear --confirm"),
  3135. Some(SlashCommand::Clear { confirm: true })
  3136. );
  3137. assert_eq!(
  3138. SlashCommand::parse("/config"),
  3139. Some(SlashCommand::Config { section: None })
  3140. );
  3141. assert_eq!(
  3142. SlashCommand::parse("/config env"),
  3143. Some(SlashCommand::Config {
  3144. section: Some("env".to_string())
  3145. })
  3146. );
  3147. assert_eq!(SlashCommand::parse("/memory"), Some(SlashCommand::Memory));
  3148. assert_eq!(SlashCommand::parse("/init"), Some(SlashCommand::Init));
  3149. }
  3150. #[test]
  3151. fn init_template_mentions_detected_rust_workspace() {
  3152. let rendered = crate::init::render_init_claude_md(std::path::Path::new("."));
  3153. assert!(rendered.contains("# CLAUDE.md"));
  3154. assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
  3155. }
  3156. #[test]
  3157. fn converts_tool_roundtrip_messages() {
  3158. let messages = vec![
  3159. ConversationMessage::user_text("hello"),
  3160. ConversationMessage::assistant(vec![ContentBlock::ToolUse {
  3161. id: "tool-1".to_string(),
  3162. name: "bash".to_string(),
  3163. input: "{\"command\":\"pwd\"}".to_string(),
  3164. }]),
  3165. ConversationMessage {
  3166. role: MessageRole::Tool,
  3167. blocks: vec![ContentBlock::ToolResult {
  3168. tool_use_id: "tool-1".to_string(),
  3169. tool_name: "bash".to_string(),
  3170. output: "ok".to_string(),
  3171. is_error: false,
  3172. }],
  3173. usage: None,
  3174. },
  3175. ];
  3176. let converted = super::convert_messages(&messages);
  3177. assert_eq!(converted.len(), 3);
  3178. assert_eq!(converted[1].role, "assistant");
  3179. assert_eq!(converted[2].role, "user");
  3180. }
  3181. #[test]
  3182. fn repl_help_mentions_history_completion_and_multiline() {
  3183. let help = render_repl_help();
  3184. assert!(help.contains("Up/Down"));
  3185. assert!(help.contains("Tab"));
  3186. assert!(help.contains("Shift+Enter/Ctrl+J"));
  3187. }
  3188. #[test]
  3189. fn tool_rendering_helpers_compact_output() {
  3190. let start = format_tool_call_start("read_file", r#"{"path":"src/main.rs"}"#);
  3191. assert!(start.contains("read_file"));
  3192. assert!(start.contains("src/main.rs"));
  3193. let done = format_tool_result(
  3194. "read_file",
  3195. r#"{"file":{"filePath":"src/main.rs","content":"hello","numLines":1,"startLine":1,"totalLines":1}}"#,
  3196. false,
  3197. );
  3198. assert!(done.contains("📄 Read src/main.rs"));
  3199. assert!(done.contains("hello"));
  3200. }
  3201. #[test]
  3202. fn push_output_block_renders_markdown_text() {
  3203. let mut out = Vec::new();
  3204. let mut events = Vec::new();
  3205. let mut pending_tool = None;
  3206. push_output_block(
  3207. OutputContentBlock::Text {
  3208. text: "# Heading".to_string(),
  3209. },
  3210. &mut out,
  3211. &mut events,
  3212. &mut pending_tool,
  3213. false,
  3214. )
  3215. .expect("text block should render");
  3216. let rendered = String::from_utf8(out).expect("utf8");
  3217. assert!(rendered.contains("Heading"));
  3218. assert!(rendered.contains('\u{1b}'));
  3219. }
  3220. #[test]
  3221. fn push_output_block_skips_empty_object_prefix_for_tool_streams() {
  3222. let mut out = Vec::new();
  3223. let mut events = Vec::new();
  3224. let mut pending_tool = None;
  3225. push_output_block(
  3226. OutputContentBlock::ToolUse {
  3227. id: "tool-1".to_string(),
  3228. name: "read_file".to_string(),
  3229. input: json!({}),
  3230. },
  3231. &mut out,
  3232. &mut events,
  3233. &mut pending_tool,
  3234. true,
  3235. )
  3236. .expect("tool block should accumulate");
  3237. assert!(events.is_empty());
  3238. assert_eq!(
  3239. pending_tool,
  3240. Some(("tool-1".to_string(), "read_file".to_string(), String::new(),))
  3241. );
  3242. }
  3243. #[test]
  3244. fn response_to_events_preserves_empty_object_json_input_outside_streaming() {
  3245. let mut out = Vec::new();
  3246. let events = response_to_events(
  3247. MessageResponse {
  3248. id: "msg-1".to_string(),
  3249. kind: "message".to_string(),
  3250. model: "claude-opus-4-6".to_string(),
  3251. role: "assistant".to_string(),
  3252. content: vec![OutputContentBlock::ToolUse {
  3253. id: "tool-1".to_string(),
  3254. name: "read_file".to_string(),
  3255. input: json!({}),
  3256. }],
  3257. stop_reason: Some("tool_use".to_string()),
  3258. stop_sequence: None,
  3259. usage: Usage {
  3260. input_tokens: 1,
  3261. output_tokens: 1,
  3262. cache_creation_input_tokens: 0,
  3263. cache_read_input_tokens: 0,
  3264. },
  3265. request_id: None,
  3266. },
  3267. &mut out,
  3268. )
  3269. .expect("response conversion should succeed");
  3270. assert!(matches!(
  3271. &events[0],
  3272. AssistantEvent::ToolUse { name, input, .. }
  3273. if name == "read_file" && input == "{}"
  3274. ));
  3275. }
  3276. #[test]
  3277. fn response_to_events_preserves_non_empty_json_input_outside_streaming() {
  3278. let mut out = Vec::new();
  3279. let events = response_to_events(
  3280. MessageResponse {
  3281. id: "msg-2".to_string(),
  3282. kind: "message".to_string(),
  3283. model: "claude-opus-4-6".to_string(),
  3284. role: "assistant".to_string(),
  3285. content: vec![OutputContentBlock::ToolUse {
  3286. id: "tool-2".to_string(),
  3287. name: "read_file".to_string(),
  3288. input: json!({ "path": "rust/Cargo.toml" }),
  3289. }],
  3290. stop_reason: Some("tool_use".to_string()),
  3291. stop_sequence: None,
  3292. usage: Usage {
  3293. input_tokens: 1,
  3294. output_tokens: 1,
  3295. cache_creation_input_tokens: 0,
  3296. cache_read_input_tokens: 0,
  3297. },
  3298. request_id: None,
  3299. },
  3300. &mut out,
  3301. )
  3302. .expect("response conversion should succeed");
  3303. assert!(matches!(
  3304. &events[0],
  3305. AssistantEvent::ToolUse { name, input, .. }
  3306. if name == "read_file" && input == "{\"path\":\"rust/Cargo.toml\"}"
  3307. ));
  3308. }
  3309. }