main.rs 114 KB

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