main.rs 116 KB

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