syncable_cli/agent/
commands.rs

1//! Slash command definitions and interactive command picker
2//!
3//! Provides Gemini CLI-style "/" command system with:
4//! - Interactive command picker when typing "/"
5//! - Arrow key navigation
6//! - Auto-complete on Enter
7//! - Token usage tracking via /cost
8
9use crate::agent::ui::colors::ansi;
10use crossterm::{
11    cursor::{self, MoveUp, MoveToColumn},
12    event::{self, Event, KeyCode},
13    execute,
14    terminal::{self, Clear, ClearType},
15};
16use std::io::{self, Write};
17
18/// A slash command definition
19#[derive(Clone)]
20pub struct SlashCommand {
21    /// Command name (without the /)
22    pub name: &'static str,
23    /// Short alias (e.g., "m" for "model")
24    pub alias: Option<&'static str>,
25    /// Description shown in picker
26    pub description: &'static str,
27    /// Whether this command auto-executes on selection (vs. inserting text)
28    pub auto_execute: bool,
29}
30
31/// All available slash commands
32pub const SLASH_COMMANDS: &[SlashCommand] = &[
33    SlashCommand {
34        name: "model",
35        alias: Some("m"),
36        description: "Select a different AI model",
37        auto_execute: true,
38    },
39    SlashCommand {
40        name: "provider",
41        alias: Some("p"),
42        description: "Switch provider (OpenAI/Anthropic)",
43        auto_execute: true,
44    },
45    SlashCommand {
46        name: "cost",
47        alias: None,
48        description: "Show token usage and estimated cost",
49        auto_execute: true,
50    },
51    SlashCommand {
52        name: "clear",
53        alias: Some("c"),
54        description: "Clear conversation history",
55        auto_execute: true,
56    },
57    SlashCommand {
58        name: "help",
59        alias: Some("h"),
60        description: "Show available commands",
61        auto_execute: true,
62    },
63    SlashCommand {
64        name: "reset",
65        alias: Some("r"),
66        description: "Reset provider credentials",
67        auto_execute: true,
68    },
69    SlashCommand {
70        name: "profile",
71        alias: None,
72        description: "Manage provider profiles (multiple configs)",
73        auto_execute: true,
74    },
75    SlashCommand {
76        name: "plans",
77        alias: None,
78        description: "Show incomplete plans and continue",
79        auto_execute: true,
80    },
81    SlashCommand {
82        name: "exit",
83        alias: Some("q"),
84        description: "Exit the chat",
85        auto_execute: true,
86    },
87];
88
89/// Whether a token count is actual (from API) or approximate (estimated)
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum TokenCountType {
92    /// Actual count from API response
93    Actual,
94    /// Approximate count estimated from character count (~chars/4)
95    #[default]
96    Approximate,
97}
98
99/// Token usage statistics for /cost command
100/// Tracks actual vs approximate tokens similar to Forge
101#[derive(Debug, Default, Clone)]
102pub struct TokenUsage {
103    /// Total prompt/input tokens
104    pub prompt_tokens: u64,
105    /// Total completion/output tokens
106    pub completion_tokens: u64,
107    /// Cache read tokens (prompt caching)
108    pub cache_read_tokens: u64,
109    /// Cache creation tokens (prompt caching)
110    pub cache_creation_tokens: u64,
111    /// Thinking/reasoning tokens (extended thinking models)
112    pub thinking_tokens: u64,
113    /// Whether the counts are actual or approximate
114    pub count_type: TokenCountType,
115    /// Number of requests made
116    pub request_count: u64,
117    /// Session start time
118    pub session_start: Option<std::time::Instant>,
119}
120
121impl TokenUsage {
122    pub fn new() -> Self {
123        Self {
124            session_start: Some(std::time::Instant::now()),
125            ..Default::default()
126        }
127    }
128
129    /// Add actual tokens from API response
130    pub fn add_actual(&mut self, input: u64, output: u64) {
131        self.prompt_tokens += input;
132        self.completion_tokens += output;
133        self.request_count += 1;
134        // If we have any actual counts, mark as actual
135        if input > 0 || output > 0 {
136            self.count_type = TokenCountType::Actual;
137        }
138    }
139
140    /// Add actual tokens with cache and thinking info
141    pub fn add_actual_extended(
142        &mut self,
143        input: u64,
144        output: u64,
145        cache_read: u64,
146        cache_creation: u64,
147        thinking: u64,
148    ) {
149        self.prompt_tokens += input;
150        self.completion_tokens += output;
151        self.cache_read_tokens += cache_read;
152        self.cache_creation_tokens += cache_creation;
153        self.thinking_tokens += thinking;
154        self.request_count += 1;
155        self.count_type = TokenCountType::Actual;
156    }
157
158    /// Add estimated tokens (when API doesn't return actual counts)
159    /// Only updates if we don't already have actual counts for this session
160    pub fn add_estimated(&mut self, prompt: u64, completion: u64) {
161        self.prompt_tokens += prompt;
162        self.completion_tokens += completion;
163        self.request_count += 1;
164        // Keep as Approximate unless we've received actual counts
165    }
166
167    /// Legacy method for compatibility - adds estimated tokens
168    pub fn add_request(&mut self, prompt: u64, completion: u64) {
169        self.add_estimated(prompt, completion);
170    }
171
172    /// Estimate token count from text (rough approximation: ~4 chars per token)
173    /// Matches Forge's approach: char_count.div_ceil(4)
174    pub fn estimate_tokens(text: &str) -> u64 {
175        text.len().div_ceil(4) as u64
176    }
177
178    /// Get total tokens (input + output, excluding cache/thinking)
179    pub fn total_tokens(&self) -> u64 {
180        self.prompt_tokens + self.completion_tokens
181    }
182
183    /// Get total tokens including cache reads (effective context size)
184    pub fn total_with_cache(&self) -> u64 {
185        self.prompt_tokens + self.completion_tokens + self.cache_read_tokens
186    }
187
188    /// Format total tokens for display (with ~ prefix if approximate)
189    pub fn format_total(&self) -> String {
190        match self.count_type {
191            TokenCountType::Actual => format!("{}", self.total_tokens()),
192            TokenCountType::Approximate => format!("~{}", self.total_tokens()),
193        }
194    }
195
196    /// Get a short display string like Forge: "~1.2k" or "15k"
197    pub fn format_compact(&self) -> String {
198        let total = self.total_tokens();
199        let prefix = match self.count_type {
200            TokenCountType::Actual => "",
201            TokenCountType::Approximate => "~",
202        };
203
204        if total >= 1_000_000 {
205            format!("{}{:.1}M", prefix, total as f64 / 1_000_000.0)
206        } else if total >= 1_000 {
207            format!("{}{:.1}k", prefix, total as f64 / 1_000.0)
208        } else {
209            format!("{}{}", prefix, total)
210        }
211    }
212
213    /// Check if we have cache hits (prompt caching is working)
214    pub fn has_cache_hits(&self) -> bool {
215        self.cache_read_tokens > 0
216    }
217
218    /// Check if we have thinking tokens (extended thinking enabled)
219    pub fn has_thinking(&self) -> bool {
220        self.thinking_tokens > 0
221    }
222
223    /// Get session duration
224    pub fn session_duration(&self) -> std::time::Duration {
225        self.session_start
226            .map(|start| start.elapsed())
227            .unwrap_or_default()
228    }
229
230    /// Estimate cost based on model (rough estimates in USD)
231    /// Returns (input_cost, output_cost, total_cost)
232    pub fn estimate_cost(&self, model: &str) -> (f64, f64, f64) {
233        // Pricing per 1M tokens (as of Dec 2025, approximate)
234        let (input_per_m, output_per_m) = match model {
235            m if m.starts_with("gpt-5.2-mini") => (0.15, 0.60),
236            m if m.starts_with("gpt-5") => (2.50, 10.00),
237            m if m.starts_with("gpt-4o") => (2.50, 10.00),
238            m if m.starts_with("o1") => (15.00, 60.00),
239            m if m.contains("sonnet") => (3.00, 15.00),
240            m if m.contains("opus") => (15.00, 75.00),
241            m if m.contains("haiku") => (0.25, 1.25),
242            _ => (2.50, 10.00), // Default to GPT-4o pricing
243        };
244
245        let input_cost = (self.prompt_tokens as f64 / 1_000_000.0) * input_per_m;
246        let output_cost = (self.completion_tokens as f64 / 1_000_000.0) * output_per_m;
247        
248        (input_cost, output_cost, input_cost + output_cost)
249    }
250
251    /// Print cost report
252    pub fn print_report(&self, model: &str) {
253        let duration = self.session_duration();
254        let (input_cost, output_cost, total_cost) = self.estimate_cost(model);
255
256        // Determine accuracy indicator
257        let accuracy_note = match self.count_type {
258            TokenCountType::Actual => format!("{}actual counts{}", ansi::SUCCESS, ansi::RESET),
259            TokenCountType::Approximate => format!("{}~approximate{}", ansi::DIM, ansi::RESET),
260        };
261
262        println!();
263        println!("  {}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{}", ansi::PURPLE, ansi::RESET);
264        println!("  {}💰 Session Cost & Usage{}", ansi::PURPLE, ansi::RESET);
265        println!("  {}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{}", ansi::PURPLE, ansi::RESET);
266        println!();
267        println!("  {}Model:{} {}", ansi::DIM, ansi::RESET, model);
268        println!("  {}Duration:{} {:02}:{:02}:{:02}",
269            ansi::DIM, ansi::RESET,
270            duration.as_secs() / 3600,
271            (duration.as_secs() % 3600) / 60,
272            duration.as_secs() % 60
273        );
274        println!("  {}Requests:{} {}", ansi::DIM, ansi::RESET, self.request_count);
275        println!();
276        println!("  {}Tokens{} ({}){}:", ansi::CYAN, ansi::RESET, accuracy_note, ansi::RESET);
277        println!("    Input:    {:>10} tokens", self.prompt_tokens);
278        println!("    Output:   {:>10} tokens", self.completion_tokens);
279
280        // Show cache tokens if present
281        if self.cache_read_tokens > 0 || self.cache_creation_tokens > 0 {
282            println!();
283            println!("  {}Cache:{}", ansi::CYAN, ansi::RESET);
284            if self.cache_read_tokens > 0 {
285                println!("    Read:     {:>10} tokens {}(saved){}", self.cache_read_tokens, ansi::SUCCESS, ansi::RESET);
286            }
287            if self.cache_creation_tokens > 0 {
288                println!("    Created:  {:>10} tokens", self.cache_creation_tokens);
289            }
290        }
291
292        // Show thinking tokens if present
293        if self.thinking_tokens > 0 {
294            println!();
295            println!("  {}Thinking:{}", ansi::CYAN, ansi::RESET);
296            println!("    Reasoning:{:>10} tokens", self.thinking_tokens);
297        }
298
299        println!();
300        println!("    {}Total:    {:>10} tokens{}", ansi::BOLD, self.format_total(), ansi::RESET);
301        println!();
302        println!("  {}Estimated Cost:{}", ansi::SUCCESS, ansi::RESET);
303        println!("    Input:  ${:.4}", input_cost);
304        println!("    Output: ${:.4}", output_cost);
305        println!("    {}Total:  ${:.4}{}", ansi::BOLD, total_cost, ansi::RESET);
306        println!();
307
308        // Show note about accuracy
309        match self.count_type {
310            TokenCountType::Actual => {
311                println!("  {}(Based on actual API usage){}", ansi::DIM, ansi::RESET);
312            }
313            TokenCountType::Approximate => {
314                println!("  {}(Estimates based on ~4 chars/token){}", ansi::DIM, ansi::RESET);
315            }
316        }
317        println!();
318    }
319}
320
321/// Interactive command picker state
322pub struct CommandPicker {
323    /// Current filter text (after the /)
324    pub filter: String,
325    /// Currently selected index
326    pub selected_index: usize,
327    /// Filtered commands
328    pub filtered_commands: Vec<&'static SlashCommand>,
329}
330
331impl CommandPicker {
332    pub fn new() -> Self {
333        Self {
334            filter: String::new(),
335            selected_index: 0,
336            filtered_commands: SLASH_COMMANDS.iter().collect(),
337        }
338    }
339
340    /// Update filter and refresh filtered commands
341    pub fn set_filter(&mut self, filter: &str) {
342        self.filter = filter.to_lowercase();
343        self.filtered_commands = SLASH_COMMANDS
344            .iter()
345            .filter(|cmd| {
346                cmd.name.starts_with(&self.filter) ||
347                cmd.alias.map(|a| a.starts_with(&self.filter)).unwrap_or(false)
348            })
349            .collect();
350        
351        // Reset selection if out of bounds
352        if self.selected_index >= self.filtered_commands.len() {
353            self.selected_index = 0;
354        }
355    }
356
357    /// Move selection up
358    pub fn move_up(&mut self) {
359        if !self.filtered_commands.is_empty() && self.selected_index > 0 {
360            self.selected_index -= 1;
361        }
362    }
363
364    /// Move selection down  
365    pub fn move_down(&mut self) {
366        if !self.filtered_commands.is_empty() && self.selected_index < self.filtered_commands.len() - 1 {
367            self.selected_index += 1;
368        }
369    }
370
371    /// Get currently selected command
372    pub fn selected_command(&self) -> Option<&'static SlashCommand> {
373        self.filtered_commands.get(self.selected_index).copied()
374    }
375
376    /// Render the picker suggestions below current line
377    pub fn render_suggestions(&self) -> usize {
378        let mut stdout = io::stdout();
379        
380        if self.filtered_commands.is_empty() {
381            println!("\n  {}No matching commands{}", ansi::DIM, ansi::RESET);
382            let _ = stdout.flush();
383            return 1;
384        }
385
386        for (i, cmd) in self.filtered_commands.iter().enumerate() {
387            let is_selected = i == self.selected_index;
388            
389            if is_selected {
390                // Selected item - highlighted with arrow
391                println!("  {}▸ /{:<15}{} {}{}{}", 
392                    ansi::PURPLE, cmd.name, ansi::RESET,
393                    ansi::PURPLE, cmd.description, ansi::RESET);
394            } else {
395                // Normal item - dimmed
396                println!("  {}  /{:<15} {}{}", 
397                    ansi::DIM, cmd.name, cmd.description, ansi::RESET);
398            }
399        }
400        
401        let _ = stdout.flush();
402        self.filtered_commands.len()
403    }
404
405    /// Clear n lines above cursor
406    pub fn clear_lines(&self, num_lines: usize) {
407        let mut stdout = io::stdout();
408        for _ in 0..num_lines {
409            let _ = execute!(stdout, MoveUp(1), Clear(ClearType::CurrentLine));
410        }
411        let _ = stdout.flush();
412    }
413}
414
415/// Show interactive command picker and return selected command
416/// This is called when user types "/" - shows suggestions immediately
417/// Returns None if cancelled, Some(command_name) if selected
418pub fn show_command_picker(initial_filter: &str) -> Option<String> {
419    let mut picker = CommandPicker::new();
420    picker.set_filter(initial_filter);
421    
422    // Enable raw mode for real-time key handling
423    if terminal::enable_raw_mode().is_err() {
424        // Fallback to simple mode if raw mode fails
425        return show_simple_picker(&picker);
426    }
427    
428    let mut stdout = io::stdout();
429    let mut input_buffer = format!("/{}", initial_filter);
430    let mut last_rendered_lines = 0;
431    
432    // Initial render
433    println!(); // Move to new line for suggestions
434    last_rendered_lines = picker.render_suggestions();
435    
436    // Move back up to input line and position cursor
437    let _ = execute!(stdout, MoveUp(last_rendered_lines as u16 + 1), MoveToColumn(0));
438    print!("{}You: {}{}", ansi::SUCCESS, ansi::RESET, input_buffer);
439    let _ = stdout.flush();
440    
441    // Move down to after suggestions
442    let _ = execute!(stdout, cursor::MoveDown(last_rendered_lines as u16 + 1));
443    
444    let result = loop {
445        // Wait for key event
446        if let Ok(Event::Key(key_event)) = event::read() {
447            match key_event.code {
448                KeyCode::Esc => {
449                    // Cancel
450                    break None;
451                }
452                KeyCode::Enter => {
453                    // Select current
454                    if let Some(cmd) = picker.selected_command() {
455                        break Some(cmd.name.to_string());
456                    }
457                    break None;
458                }
459                KeyCode::Up => {
460                    picker.move_up();
461                }
462                KeyCode::Down => {
463                    picker.move_down();
464                }
465                KeyCode::Backspace => {
466                    if input_buffer.len() > 1 {
467                        input_buffer.pop();
468                        let filter = input_buffer.trim_start_matches('/');
469                        picker.set_filter(filter);
470                    } else {
471                        // Backspace on just "/" - cancel
472                        break None;
473                    }
474                }
475                KeyCode::Char(c) => {
476                    // Add character to filter
477                    input_buffer.push(c);
478                    let filter = input_buffer.trim_start_matches('/');
479                    picker.set_filter(filter);
480                    
481                    // If there's an exact match and user typed enough, auto-select
482                    if picker.filtered_commands.len() == 1 {
483                        // Perfect match - could auto-complete
484                    }
485                }
486                KeyCode::Tab => {
487                    // Tab to auto-complete current selection
488                    if let Some(cmd) = picker.selected_command() {
489                        break Some(cmd.name.to_string());
490                    }
491                }
492                _ => {}
493            }
494            
495            // Clear old suggestions and re-render
496            picker.clear_lines(last_rendered_lines);
497            
498            // Re-render input line
499            let _ = execute!(stdout, Clear(ClearType::CurrentLine), MoveToColumn(0));
500            print!("{}You: {}{}", ansi::SUCCESS, ansi::RESET, input_buffer);
501            let _ = stdout.flush();
502            
503            // Render suggestions below
504            println!();
505            last_rendered_lines = picker.render_suggestions();
506            
507            // Move back to input line position
508            let _ = execute!(stdout, MoveUp(last_rendered_lines as u16 + 1));
509            let _ = execute!(stdout, MoveToColumn((5 + input_buffer.len()) as u16));
510            let _ = stdout.flush();
511            
512            // Move down to after suggestions for next iteration
513            let _ = execute!(stdout, cursor::MoveDown(last_rendered_lines as u16 + 1));
514        }
515    };
516    
517    // Disable raw mode
518    let _ = terminal::disable_raw_mode();
519    
520    // Clean up display
521    picker.clear_lines(last_rendered_lines);
522    let _ = execute!(stdout, Clear(ClearType::CurrentLine), MoveToColumn(0));
523    let _ = stdout.flush();
524    
525    result
526}
527
528/// Fallback simple picker when raw mode is not available
529fn show_simple_picker(picker: &CommandPicker) -> Option<String> {
530    println!();
531    println!("  {}📋 Available Commands:{}", ansi::CYAN, ansi::RESET);
532    println!();
533    
534    for (i, cmd) in picker.filtered_commands.iter().enumerate() {
535        print!("  {} {}/{:<12}", format!("[{}]", i + 1), ansi::PURPLE, cmd.name);
536        if let Some(alias) = cmd.alias {
537            print!(" ({})", alias);
538        }
539        println!("{} - {}{}{}", ansi::RESET, ansi::DIM, cmd.description, ansi::RESET);
540    }
541    
542    println!();
543    print!("  Select (1-{}) or press Enter to cancel: ", picker.filtered_commands.len());
544    let _ = io::stdout().flush();
545    
546    let mut input = String::new();
547    if io::stdin().read_line(&mut input).is_ok() {
548        let input = input.trim();
549        if let Ok(num) = input.parse::<usize>() {
550            if num >= 1 && num <= picker.filtered_commands.len() {
551                return Some(picker.filtered_commands[num - 1].name.to_string());
552            }
553        }
554    }
555    
556    None
557}
558
559/// Check if a command matches a query (name or alias)
560pub fn match_command(query: &str) -> Option<&'static SlashCommand> {
561    let query = query.trim_start_matches('/').to_lowercase();
562    
563    SLASH_COMMANDS.iter().find(|cmd| {
564        cmd.name == query || cmd.alias.map(|a| a == query).unwrap_or(false)
565    })
566}