sage-cli 0.13.57

Command-line interface for Sage Agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! CLI onboarding wizard for first-time setup
//!
//! This module provides an interactive terminal experience for configuring
//! API keys and providers when starting sage for the first time.

use crate::console::CliConsole;
use colored::*;
use console::{Key, Term};
use dialoguer::{Select, theme::ColorfulTheme};
use indicatif::{ProgressBar, ProgressStyle};
use sage_core::config::credential::{
    ConfigStatus, StatusBarHint, hint_from_status, load_config_unified,
};
use sage_core::config::onboarding::OnboardingManager;
use sage_core::error::{SageError, SageResult};
use std::io::{self, Write};

/// Get the environment variable name for a provider
fn get_provider_env_var(provider: &str) -> &'static str {
    match provider {
        "anthropic" => "ANTHROPIC_API_KEY",
        "openai" => "OPENAI_API_KEY",
        "zai" => "ZAI_API_KEY",
        "google" => "GOOGLE_API_KEY",
        "glm" | "zhipu" => "GLM_API_KEY",
        "moonshot" | "kimi" => "MOONSHOT_API_KEY",
        "deepseek" => "DEEPSEEK_API_KEY",
        _ => "API_KEY",
    }
}

/// Get the help URL for a provider
fn get_provider_help_url(provider: &str) -> &'static str {
    match provider {
        "anthropic" => "https://console.anthropic.com/settings/keys",
        "openai" => "https://platform.openai.com/api-keys",
        "zai" => "https://docs.z.ai/api-reference/introduction",
        "google" => "https://makersuite.google.com/app/apikey",
        "glm" | "zhipu" => "https://open.bigmodel.cn/usercenter/apikeys",
        "moonshot" | "kimi" => "https://platform.kimi.ai/docs/models",
        "deepseek" => "https://platform.deepseek.com/api_keys",
        _ => "https://docs.sage-agent.dev/configuration",
    }
}

/// Simple validation spinner
struct ValidationSpinner {
    bar: ProgressBar,
}

impl ValidationSpinner {
    fn new(message: &str) -> Self {
        let bar = ProgressBar::new_spinner();
        let style = ProgressStyle::default_spinner()
            .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
            .template("{spinner:.blue} {msg}")
            .unwrap_or_else(|_| ProgressStyle::default_spinner());
        bar.set_style(style);
        bar.set_message(message.to_string());
        bar.enable_steady_tick(std::time::Duration::from_millis(100));
        Self { bar }
    }

    fn finish_success(&self, message: &str) {
        self.bar
            .finish_with_message(format!("{} {}", "".green(), message));
    }

    fn finish_warning(&self, message: &str) {
        self.bar
            .finish_with_message(format!("{} {}", "".yellow(), message));
    }
}

/// CLI onboarding wizard
pub struct CliOnboarding {
    manager: OnboardingManager,
    console: CliConsole,
    term: Term,
}

impl CliOnboarding {
    /// Create a new CLI onboarding wizard
    pub fn new() -> Self {
        Self {
            manager: OnboardingManager::with_defaults(),
            console: CliConsole::new(true),
            term: Term::stdout(),
        }
    }

    /// Check if onboarding is needed
    #[allow(dead_code)] // Used in tests; production uses check_config_status() instead
    pub fn is_needed(&self) -> bool {
        self.manager.is_needed()
    }

    /// Run the onboarding wizard
    pub async fn run(&mut self) -> SageResult<bool> {
        self.print_welcome_screen();

        // Move to provider selection
        self.manager.next_step()?;

        // Provider selection
        let provider = self.select_provider()?;
        self.manager.select_provider(&provider)?;
        self.manager.next_step()?;

        // API key input
        let api_key = self.input_api_key(&provider)?;
        self.manager.set_api_key(&api_key)?;

        // Validate key with spinner
        let spinner = ValidationSpinner::new("Validating API key...");
        let validation = self.manager.validate_api_key().await;

        if validation.valid {
            let model_info = validation.model_info.as_deref().unwrap_or("default");
            spinner.finish_success(&format!("API key validated! Model: {}", model_info));
        } else if let Some(error) = &validation.error {
            spinner.finish_warning(&format!("Validation warning: {}", error));
            self.console
                .info("The key will be saved but may not work correctly.");
        }

        // Ask to save
        if self.confirm("Save this configuration?")? {
            self.manager.save_configuration()?;
            self.console.success("Configuration saved!");

            self.print_completion_screen(&provider);
            return Ok(true);
        }

        self.console.info("Configuration not saved.");
        Ok(false)
    }

    /// Run login command (for /login)
    pub async fn run_login(&mut self) -> SageResult<bool> {
        println!();
        self.console.print_header("Configure API Key");
        println!();

        // Provider selection
        let provider = self.select_provider()?;
        self.manager.select_provider(&provider)?;

        // API key input
        let api_key = self.input_api_key(&provider)?;
        self.manager.set_api_key(&api_key)?;

        // Validate with spinner
        let spinner = ValidationSpinner::new("Validating API key...");
        let validation = self.manager.validate_api_key().await;

        if validation.valid {
            let model_info = validation.model_info.as_deref().unwrap_or("default");
            spinner.finish_success(&format!("Validated! Model: {}", model_info));
        } else if let Some(error) = &validation.error {
            spinner.finish_warning(&format!("Warning: {}", error));
        }

        // Save
        if self.confirm("Save this configuration?")? {
            self.manager.save_configuration()?;
            self.console
                .success(&format!("{} API key configured!", provider));
            return Ok(true);
        }

        Ok(false)
    }

    fn print_welcome_screen(&self) {
        println!();
        println!(
            "{}",
            "╭─────────────────────────────────────────────────────╮"
                .cyan()
                .bold()
        );
        println!(
            "{}",
            "│                                                     │"
                .cyan()
                .bold()
        );
        println!(
            "{}  {}  {}",
            "".cyan().bold(),
            "🌿 Welcome to Sage Agent".bold(),
            "".cyan().bold()
        );
        println!(
            "{}",
            "│                                                     │"
                .cyan()
                .bold()
        );
        println!(
            "{}  {}  {}",
            "".cyan().bold(),
            "Let's get you set up with an AI provider.".dimmed(),
            "".cyan().bold()
        );
        println!(
            "{}",
            "│                                                     │"
                .cyan()
                .bold()
        );
        println!(
            "{}",
            "╰─────────────────────────────────────────────────────╯"
                .cyan()
                .bold()
        );
        println!();
    }

    fn print_completion_screen(&self, provider: &str) {
        println!();
        println!(
            "{}",
            "╭─────────────────────────────────────────────────────╮"
                .green()
                .bold()
        );
        println!(
            "{}  {}  {}",
            "".green().bold(),
            "✓ Setup Complete!".green().bold(),
            "".green().bold()
        );
        println!(
            "{}",
            "│                                                     │"
                .green()
                .bold()
        );
        println!(
            "{}  {} {}{}",
            "".green().bold(),
            "Provider:".dimmed(),
            provider.cyan(),
            " ".repeat(40 - provider.len()) + ""
        );
        println!(
            "{}",
            "│                                                     │"
                .green()
                .bold()
        );
        println!(
            "{}  {}  {}",
            "".green().bold(),
            "Start chatting by typing your message below.".dimmed(),
            "".green().bold()
        );
        println!(
            "{}",
            "╰─────────────────────────────────────────────────────╯"
                .green()
                .bold()
        );
        println!();
    }

    fn select_provider(&self) -> SageResult<String> {
        let options = self.manager.providers();

        // Build display items with description
        let items: Vec<String> = options
            .iter()
            .map(|opt| format!("{} - {}", opt.name, opt.description))
            .collect();

        println!();
        let selection = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("Select your AI provider")
            .items(&items)
            .default(0)
            .interact()
            .map_err(|e| SageError::io(format!("selection error: {}", e)))?;

        let selected = &options[selection];
        self.console
            .success(&format!("Selected: {}", selected.name));

        Ok(selected.id.clone())
    }

    fn input_api_key(&self, provider: &str) -> SageResult<String> {
        let env_var = get_provider_env_var(provider);
        let help_url = get_provider_help_url(provider);

        println!();
        println!(
            "  {} Enter your {} API key:",
            "?".blue().bold(),
            provider.cyan()
        );
        println!();
        println!("  {}", "Tips:".dimmed());
        println!(
            "  {} Set {} to avoid re-entering",
            "".dimmed(),
            env_var.yellow()
        );
        println!(
            "  {} Get your key at: {}",
            "".dimmed(),
            help_url.underline()
        );
        println!();

        // Read API key with hidden input
        print!("  API Key: ");
        io::stdout()
            .flush()
            .map_err(|e| SageError::io(format!("flush error: {}", e)))?;

        let key = self.read_password()?;

        if key.is_empty() {
            return Err(SageError::invalid_input("API key cannot be empty"));
        }

        // Show masked key
        let masked = if key.len() > 8 {
            format!("{}...{}", &key[..4], &key[key.len() - 4..])
        } else {
            "*".repeat(key.len())
        };
        println!("  {}", format!("Key: {}", masked).dimmed());

        Ok(key)
    }

    fn read_password(&self) -> SageResult<String> {
        let mut password = String::new();

        loop {
            match self.term.read_key() {
                Ok(Key::Enter) => {
                    println!();
                    break;
                }
                Ok(Key::Backspace) => {
                    if !password.is_empty() {
                        password.pop();
                        print!("\x08 \x08"); // Erase last asterisk
                        io::stdout().flush().ok();
                    }
                }
                Ok(Key::Char(c)) if !c.is_control() => {
                    password.push(c);
                    print!("*");
                    io::stdout().flush().ok();
                }
                Ok(Key::CtrlC) => {
                    return Err(SageError::Cancelled);
                }
                _ => {}
            }
        }

        Ok(password)
    }

    fn confirm(&self, message: &str) -> SageResult<bool> {
        print!("  {} {} [Y/n]: ", "?".yellow().bold(), message);
        io::stdout()
            .flush()
            .map_err(|e| SageError::io(format!("flush error: {}", e)))?;

        // Use term.read_line() instead of stdin to work properly after read_key()
        let input = self
            .term
            .read_line()
            .map_err(|e| SageError::io(format!("read error: {}", e)))?;

        let answer = input.trim().to_lowercase();
        Ok(answer.is_empty() || answer == "y" || answer == "yes")
    }
}

impl Default for CliOnboarding {
    fn default() -> Self {
        Self::new()
    }
}

/// Check configuration status and return appropriate hint
pub fn check_config_status() -> (ConfigStatus, Option<StatusBarHint>) {
    let loaded = load_config_unified(None);
    let hint = hint_from_status(&loaded.status);
    (loaded.status.status, hint)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_onboarding_creation() {
        let onboarding = CliOnboarding::new();
        // Should be needed since no credentials are configured in test env
        // (unless OPENAI_API_KEY etc are set)
        assert!(onboarding.is_needed() || !onboarding.is_needed()); // Just test creation
    }

    #[test]
    fn test_check_config_status() {
        let (status, _hint) = check_config_status();
        // Status should be one of the valid values
        assert!(matches!(
            status,
            ConfigStatus::Complete | ConfigStatus::Partial | ConfigStatus::Unconfigured
        ));
    }
}