app.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. use std::io::{self, Write};
  2. use std::path::PathBuf;
  3. use crate::args::{OutputFormat, PermissionMode};
  4. use crate::input::LineEditor;
  5. use crate::render::{Spinner, TerminalRenderer};
  6. use runtime::{ConversationClient, ConversationMessage, RuntimeError, StreamEvent, UsageSummary};
  7. #[derive(Debug, Clone, PartialEq, Eq)]
  8. pub struct SessionConfig {
  9. pub model: String,
  10. pub permission_mode: PermissionMode,
  11. pub config: Option<PathBuf>,
  12. pub output_format: OutputFormat,
  13. }
  14. #[derive(Debug, Clone, PartialEq, Eq)]
  15. pub struct SessionState {
  16. pub turns: usize,
  17. pub compacted_messages: usize,
  18. pub last_model: String,
  19. pub last_usage: UsageSummary,
  20. }
  21. impl SessionState {
  22. #[must_use]
  23. pub fn new(model: impl Into<String>) -> Self {
  24. Self {
  25. turns: 0,
  26. compacted_messages: 0,
  27. last_model: model.into(),
  28. last_usage: UsageSummary::default(),
  29. }
  30. }
  31. }
  32. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  33. pub enum CommandResult {
  34. Continue,
  35. }
  36. #[derive(Debug, Clone, PartialEq, Eq)]
  37. pub enum SlashCommand {
  38. Help,
  39. Status,
  40. Compact,
  41. Unknown(String),
  42. }
  43. impl SlashCommand {
  44. #[must_use]
  45. pub fn parse(input: &str) -> Option<Self> {
  46. let trimmed = input.trim();
  47. if !trimmed.starts_with('/') {
  48. return None;
  49. }
  50. let command = trimmed
  51. .trim_start_matches('/')
  52. .split_whitespace()
  53. .next()
  54. .unwrap_or_default();
  55. Some(match command {
  56. "help" => Self::Help,
  57. "status" => Self::Status,
  58. "compact" => Self::Compact,
  59. other => Self::Unknown(other.to_string()),
  60. })
  61. }
  62. }
  63. struct SlashCommandHandler {
  64. command: SlashCommand,
  65. summary: &'static str,
  66. }
  67. const SLASH_COMMAND_HANDLERS: &[SlashCommandHandler] = &[
  68. SlashCommandHandler {
  69. command: SlashCommand::Help,
  70. summary: "Show command help",
  71. },
  72. SlashCommandHandler {
  73. command: SlashCommand::Status,
  74. summary: "Show current session status",
  75. },
  76. SlashCommandHandler {
  77. command: SlashCommand::Compact,
  78. summary: "Compact local session history",
  79. },
  80. ];
  81. pub struct CliApp {
  82. config: SessionConfig,
  83. renderer: TerminalRenderer,
  84. state: SessionState,
  85. conversation_client: ConversationClient,
  86. conversation_history: Vec<ConversationMessage>,
  87. }
  88. impl CliApp {
  89. pub fn new(config: SessionConfig) -> Result<Self, RuntimeError> {
  90. let state = SessionState::new(config.model.clone());
  91. let conversation_client = ConversationClient::from_env(config.model.clone())?;
  92. Ok(Self {
  93. config,
  94. renderer: TerminalRenderer::new(),
  95. state,
  96. conversation_client,
  97. conversation_history: Vec::new(),
  98. })
  99. }
  100. pub fn run_repl(&mut self) -> io::Result<()> {
  101. let editor = LineEditor::new("› ");
  102. println!("Rusty Claude CLI interactive mode");
  103. println!("Type /help for commands. Shift+Enter or Ctrl+J inserts a newline.");
  104. while let Some(input) = editor.read_line()? {
  105. if input.trim().is_empty() {
  106. continue;
  107. }
  108. self.handle_submission(&input, &mut io::stdout())?;
  109. }
  110. Ok(())
  111. }
  112. pub fn run_prompt(&mut self, prompt: &str, out: &mut impl Write) -> io::Result<()> {
  113. self.render_response(prompt, out)
  114. }
  115. pub fn handle_submission(
  116. &mut self,
  117. input: &str,
  118. out: &mut impl Write,
  119. ) -> io::Result<CommandResult> {
  120. if let Some(command) = SlashCommand::parse(input) {
  121. return self.dispatch_slash_command(command, out);
  122. }
  123. self.state.turns += 1;
  124. self.render_response(input, out)?;
  125. Ok(CommandResult::Continue)
  126. }
  127. fn dispatch_slash_command(
  128. &mut self,
  129. command: SlashCommand,
  130. out: &mut impl Write,
  131. ) -> io::Result<CommandResult> {
  132. match command {
  133. SlashCommand::Help => Self::handle_help(out),
  134. SlashCommand::Status => self.handle_status(out),
  135. SlashCommand::Compact => self.handle_compact(out),
  136. SlashCommand::Unknown(name) => {
  137. writeln!(out, "Unknown slash command: /{name}")?;
  138. Ok(CommandResult::Continue)
  139. }
  140. }
  141. }
  142. fn handle_help(out: &mut impl Write) -> io::Result<CommandResult> {
  143. writeln!(out, "Available commands:")?;
  144. for handler in SLASH_COMMAND_HANDLERS {
  145. let name = match handler.command {
  146. SlashCommand::Help => "/help",
  147. SlashCommand::Status => "/status",
  148. SlashCommand::Compact => "/compact",
  149. SlashCommand::Unknown(_) => continue,
  150. };
  151. writeln!(out, " {name:<9} {}", handler.summary)?;
  152. }
  153. Ok(CommandResult::Continue)
  154. }
  155. fn handle_status(&mut self, out: &mut impl Write) -> io::Result<CommandResult> {
  156. writeln!(
  157. out,
  158. "status: turns={} model={} permission-mode={:?} output-format={:?} last-usage={} in/{} out config={}",
  159. self.state.turns,
  160. self.state.last_model,
  161. self.config.permission_mode,
  162. self.config.output_format,
  163. self.state.last_usage.input_tokens,
  164. self.state.last_usage.output_tokens,
  165. self.config
  166. .config
  167. .as_ref()
  168. .map_or_else(|| String::from("<none>"), |path| path.display().to_string())
  169. )?;
  170. Ok(CommandResult::Continue)
  171. }
  172. fn handle_compact(&mut self, out: &mut impl Write) -> io::Result<CommandResult> {
  173. self.state.compacted_messages += self.state.turns;
  174. self.state.turns = 0;
  175. self.conversation_history.clear();
  176. writeln!(
  177. out,
  178. "Compacted session history into a local summary ({} messages total compacted).",
  179. self.state.compacted_messages
  180. )?;
  181. Ok(CommandResult::Continue)
  182. }
  183. fn handle_stream_event(
  184. renderer: &TerminalRenderer,
  185. event: StreamEvent,
  186. stream_spinner: &mut Spinner,
  187. tool_spinner: &mut Spinner,
  188. saw_text: &mut bool,
  189. turn_usage: &mut UsageSummary,
  190. out: &mut impl Write,
  191. ) {
  192. match event {
  193. StreamEvent::TextDelta(delta) => {
  194. if !*saw_text {
  195. let _ =
  196. stream_spinner.finish("Streaming response", renderer.color_theme(), out);
  197. *saw_text = true;
  198. }
  199. let _ = write!(out, "{delta}");
  200. let _ = out.flush();
  201. }
  202. StreamEvent::ToolCallStart { name, input } => {
  203. if *saw_text {
  204. let _ = writeln!(out);
  205. }
  206. let _ = tool_spinner.tick(
  207. &format!("Running tool `{name}` with {input}"),
  208. renderer.color_theme(),
  209. out,
  210. );
  211. }
  212. StreamEvent::ToolCallResult {
  213. name,
  214. output,
  215. is_error,
  216. } => {
  217. let label = if is_error {
  218. format!("Tool `{name}` failed")
  219. } else {
  220. format!("Tool `{name}` completed")
  221. };
  222. let _ = tool_spinner.finish(&label, renderer.color_theme(), out);
  223. let rendered_output = format!("### Tool `{name}`\n\n```text\n{output}\n```\n");
  224. let _ = renderer.stream_markdown(&rendered_output, out);
  225. }
  226. StreamEvent::Usage(usage) => {
  227. *turn_usage = usage;
  228. }
  229. }
  230. }
  231. fn write_turn_output(
  232. &self,
  233. summary: &runtime::TurnSummary,
  234. out: &mut impl Write,
  235. ) -> io::Result<()> {
  236. match self.config.output_format {
  237. OutputFormat::Text => {
  238. writeln!(
  239. out,
  240. "\nToken usage: {} input / {} output",
  241. self.state.last_usage.input_tokens, self.state.last_usage.output_tokens
  242. )?;
  243. }
  244. OutputFormat::Json => {
  245. writeln!(
  246. out,
  247. "{}",
  248. serde_json::json!({
  249. "message": summary.assistant_text,
  250. "usage": {
  251. "input_tokens": self.state.last_usage.input_tokens,
  252. "output_tokens": self.state.last_usage.output_tokens,
  253. }
  254. })
  255. )?;
  256. }
  257. OutputFormat::Ndjson => {
  258. writeln!(
  259. out,
  260. "{}",
  261. serde_json::json!({
  262. "type": "message",
  263. "text": summary.assistant_text,
  264. "usage": {
  265. "input_tokens": self.state.last_usage.input_tokens,
  266. "output_tokens": self.state.last_usage.output_tokens,
  267. }
  268. })
  269. )?;
  270. }
  271. }
  272. Ok(())
  273. }
  274. fn render_response(&mut self, input: &str, out: &mut impl Write) -> io::Result<()> {
  275. let mut stream_spinner = Spinner::new();
  276. stream_spinner.tick(
  277. "Opening conversation stream",
  278. self.renderer.color_theme(),
  279. out,
  280. )?;
  281. let mut turn_usage = UsageSummary::default();
  282. let mut tool_spinner = Spinner::new();
  283. let mut saw_text = false;
  284. let renderer = &self.renderer;
  285. let result =
  286. self.conversation_client
  287. .run_turn(&mut self.conversation_history, input, |event| {
  288. Self::handle_stream_event(
  289. renderer,
  290. event,
  291. &mut stream_spinner,
  292. &mut tool_spinner,
  293. &mut saw_text,
  294. &mut turn_usage,
  295. out,
  296. );
  297. });
  298. let summary = match result {
  299. Ok(summary) => summary,
  300. Err(error) => {
  301. stream_spinner.fail(
  302. "Streaming response failed",
  303. self.renderer.color_theme(),
  304. out,
  305. )?;
  306. return Err(io::Error::other(error));
  307. }
  308. };
  309. self.state.last_usage = summary.usage.clone();
  310. if saw_text {
  311. writeln!(out)?;
  312. } else {
  313. stream_spinner.finish("Streaming response", self.renderer.color_theme(), out)?;
  314. }
  315. self.write_turn_output(&summary, out)?;
  316. let _ = turn_usage;
  317. Ok(())
  318. }
  319. }
  320. #[cfg(test)]
  321. mod tests {
  322. use std::path::PathBuf;
  323. use crate::args::{OutputFormat, PermissionMode};
  324. use super::{CommandResult, SessionConfig, SlashCommand};
  325. #[test]
  326. fn parses_required_slash_commands() {
  327. assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
  328. assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
  329. assert_eq!(
  330. SlashCommand::parse("/compact now"),
  331. Some(SlashCommand::Compact)
  332. );
  333. }
  334. #[test]
  335. fn help_output_lists_commands() {
  336. let mut out = Vec::new();
  337. let result = super::CliApp::handle_help(&mut out).expect("help succeeds");
  338. assert_eq!(result, CommandResult::Continue);
  339. let output = String::from_utf8_lossy(&out);
  340. assert!(output.contains("/help"));
  341. assert!(output.contains("/status"));
  342. assert!(output.contains("/compact"));
  343. }
  344. #[test]
  345. fn session_state_tracks_config_values() {
  346. let config = SessionConfig {
  347. model: "claude".into(),
  348. permission_mode: PermissionMode::WorkspaceWrite,
  349. config: Some(PathBuf::from("settings.toml")),
  350. output_format: OutputFormat::Text,
  351. };
  352. assert_eq!(config.model, "claude");
  353. assert_eq!(config.permission_mode, PermissionMode::WorkspaceWrite);
  354. assert_eq!(config.config, Some(PathBuf::from("settings.toml")));
  355. }
  356. }