unfault 0.9.5

Unfault — a cognitive context engine for thoughtful engineers
Documentation
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
425
//! # Config Command
//!
//! Manages CLI configuration including LLM settings for the `ask` command.
//!
//! ## Usage
//!
//! ```bash
//! # Show current configuration
//! unfault config show
//!
//! # Configure OpenAI for insights
//! unfault config llm openai --model gpt-4
//!
//! # Configure Anthropic
//! unfault config llm anthropic --model claude-3-5-sonnet-latest
//!
//! # Configure local Ollama
//! unfault config llm ollama --endpoint http://localhost:11434 --model llama3.2
//!
//! # Configure custom OpenAI-compatible endpoint
//! unfault config llm custom --endpoint https://api.example.com/v1 --model custom-model
//!
//! # Show current LLM configuration
//! unfault config llm show
//!
//! # Remove LLM configuration
//! unfault config llm remove
//! ```

use anyhow::Result;
use colored::Colorize;

use crate::config::{Config, LlmConfig};
use crate::exit_codes::*;

/// LLM provider types for configuration
#[derive(Debug, Clone)]
pub enum LlmProvider {
    /// OpenAI API (GPT-4, GPT-3.5, etc.)
    OpenAI {
        model: String,
        api_key: Option<String>,
    },
    /// Anthropic API (Claude models)
    Anthropic {
        model: String,
        api_key: Option<String>,
    },
    /// Local Ollama instance
    Ollama { endpoint: String, model: String },
    /// Custom OpenAI-compatible endpoint
    Custom {
        endpoint: String,
        model: String,
        api_key: Option<String>,
    },
}

/// Arguments for the config show command
#[derive(Debug)]
pub struct ConfigShowArgs {
    /// Show full API key (default: masked)
    pub show_secrets: bool,
}

/// Arguments for the config llm command
#[derive(Debug)]
pub enum ConfigLlmArgs {
    /// Configure an LLM provider
    Set(LlmProvider),
    /// Show current LLM configuration
    Show { show_secrets: bool },
    /// Remove LLM configuration
    Remove,
}

/// Execute the config show command
///
/// Displays all current configuration settings.
///
/// # Arguments
///
/// * `args` - Command arguments
///
/// # Returns
///
/// * `Ok(EXIT_SUCCESS)` - Configuration displayed successfully
/// * `Ok(EXIT_CONFIG_ERROR)` - No configuration found
pub fn execute_show(args: ConfigShowArgs) -> Result<i32> {
    let config = match Config::load() {
        Ok(config) => config,
        Err(_) => {
            eprintln!(
                "{} No configuration found. Run `unfault login` first.",
                "Error:".red().bold()
            );
            return Ok(EXIT_CONFIG_ERROR);
        }
    };

    println!();
    println!("{}", "Unfault Configuration".bold().underline());
    println!();

    // LLM Configuration
    println!("{}", "LLM (BYOLLM)".cyan().bold());
    if let Some(ref llm) = config.llm {
        println!("  {} {}", "Provider:".dimmed(), llm.provider);
        println!("  {} {}", "Endpoint:".dimmed(), llm.endpoint);
        println!("  {} {}", "Model:".dimmed(), llm.model);
        if let Some(ref env_var) = llm.api_key_env {
            let has_key = std::env::var(env_var).is_ok();
            let status = if has_key {
                "✓ set".green().to_string()
            } else {
                "✗ not set".red().to_string()
            };
            println!("  {} {} ({})", "API Key Env:".dimmed(), env_var, status);
        }
        if llm.api_key.is_some() {
            let display = if args.show_secrets {
                llm.api_key.as_ref().unwrap().clone()
            } else {
                llm.masked_api_key().unwrap_or_else(|| "****".to_string())
            };
            println!("  {} {}", "API Key:".dimmed(), display);
        }
        let ready = if llm.is_ready() {
            "✓ ready".green()
        } else {
            "✗ not ready (API key missing)".red()
        };
        println!("  {} {}", "Status:".dimmed(), ready);
    } else {
        println!("  {}", "Not configured".dimmed());
        println!();
        println!("  {} Configure with:", "".cyan());
        println!("    unfault config llm openai --model gpt-4");
        println!("    unfault config llm anthropic --model claude-3-5-sonnet-latest");
        println!(
            "    unfault config llm ollama --endpoint http://localhost:11434 --model llama3.2"
        );
    }
    println!();

    Ok(EXIT_SUCCESS)
}

/// Execute the config llm command
///
/// Configures, shows, or removes LLM settings.
///
/// # Arguments
///
/// * `args` - Command arguments
///
/// # Returns
///
/// * `Ok(EXIT_SUCCESS)` - Operation completed successfully
/// * `Ok(EXIT_CONFIG_ERROR)` - Configuration error
pub fn execute_llm(args: ConfigLlmArgs) -> Result<i32> {
    match args {
        ConfigLlmArgs::Set(provider) => set_llm_config(provider),
        ConfigLlmArgs::Show { show_secrets } => show_llm_config(show_secrets),
        ConfigLlmArgs::Remove => remove_llm_config(),
    }
}

/// Set LLM configuration
fn set_llm_config(provider: LlmProvider) -> Result<i32> {
    let mut config = match Config::load() {
        Ok(config) => config,
        Err(_) => {
            eprintln!(
                "{} No configuration found. Run `unfault login` first.",
                "Error:".red().bold()
            );
            return Ok(EXIT_CONFIG_ERROR);
        }
    };

    let llm_config = match provider {
        LlmProvider::OpenAI { model, api_key } => {
            let mut cfg = LlmConfig::openai(&model);
            if let Some(key) = api_key {
                cfg.api_key = Some(key);
            }
            cfg
        }
        LlmProvider::Anthropic { model, api_key } => {
            let mut cfg = LlmConfig::anthropic(&model);
            if let Some(key) = api_key {
                cfg.api_key = Some(key);
            }
            cfg
        }
        LlmProvider::Ollama { endpoint, model } => LlmConfig::ollama(&endpoint, &model),
        LlmProvider::Custom {
            endpoint,
            model,
            api_key,
        } => {
            let mut cfg = LlmConfig::custom(&endpoint, &model);
            cfg.api_key = api_key;
            cfg
        }
    };

    let provider_name = llm_config.provider.clone();
    let model_name = llm_config.model.clone();

    config.llm = Some(llm_config.clone());
    config.save()?;

    println!();
    println!("{} LLM configured successfully!", "".green().bold());
    println!();
    println!("  {} {}", "Provider:".dimmed(), provider_name);
    println!("  {} {}", "Model:".dimmed(), model_name);
    println!("  {} {}", "Endpoint:".dimmed(), llm_config.endpoint);

    // Check if API key is available
    if !llm_config.is_ready() {
        println!();
        eprintln!(
            "{} API key not found. Set the {} environment variable.",
            "".yellow().bold(),
            llm_config.api_key_env.as_deref().unwrap_or("API_KEY")
        );
    } else {
        println!();
        println!("  {} Ready to use with `unfault ask`", "".cyan());
    }
    println!();

    Ok(EXIT_SUCCESS)
}

/// Show current LLM configuration
fn show_llm_config(show_secrets: bool) -> Result<i32> {
    let config = match Config::load() {
        Ok(config) => config,
        Err(_) => {
            eprintln!(
                "{} No configuration found. Run `unfault login` first.",
                "Error:".red().bold()
            );
            return Ok(EXIT_CONFIG_ERROR);
        }
    };

    println!();
    println!("{}", "LLM Configuration".bold().underline());
    println!();

    if let Some(ref llm) = config.llm {
        println!("  {} {}", "Provider:".dimmed(), llm.provider);
        println!("  {} {}", "Endpoint:".dimmed(), llm.endpoint);
        println!("  {} {}", "Model:".dimmed(), llm.model);

        if let Some(ref env_var) = llm.api_key_env {
            let has_key = std::env::var(env_var).is_ok();
            let status = if has_key {
                "✓ set".green().to_string()
            } else {
                "✗ not set".red().to_string()
            };
            println!("  {} {} ({})", "API Key Env:".dimmed(), env_var, status);
        }

        if llm.api_key.is_some() {
            let display = if show_secrets {
                llm.api_key.as_ref().unwrap().clone()
            } else {
                llm.masked_api_key().unwrap_or_else(|| "****".to_string())
            };
            println!("  {} {}", "API Key:".dimmed(), display);
        }

        let ready = if llm.is_ready() {
            "✓ ready".green()
        } else {
            "✗ not ready (API key missing)".red()
        };
        println!();
        println!("  {} {}", "Status:".dimmed(), ready);
    } else {
        println!("  {}", "Not configured".dimmed());
        println!();
        println!("  {} Configure with:", "".cyan());
        println!("    unfault config llm openai --model gpt-4");
        println!("    unfault config llm anthropic --model claude-3-5-sonnet-latest");
        println!(
            "    unfault config llm ollama --endpoint http://localhost:11434 --model llama3.2"
        );
    }
    println!();

    Ok(EXIT_SUCCESS)
}

/// Remove LLM configuration
fn remove_llm_config() -> Result<i32> {
    let mut config = match Config::load() {
        Ok(config) => config,
        Err(_) => {
            eprintln!(
                "{} No configuration found. Run `unfault login` first.",
                "Error:".red().bold()
            );
            return Ok(EXIT_CONFIG_ERROR);
        }
    };

    if config.llm.is_none() {
        println!();
        println!("{} LLM configuration is not set.", "".blue());
        println!();
        return Ok(EXIT_SUCCESS);
    }

    config.remove_llm();
    config.save()?;

    println!();
    println!("{} LLM configuration removed.", "".green().bold());
    println!();

    Ok(EXIT_SUCCESS)
}

/// Mask a key for display
#[cfg(test)]
fn mask_key(key: &str) -> String {
    if key.len() > 8 {
        format!("{}...{}", &key[..4], &key[key.len() - 4..])
    } else {
        "****".to_string()
    }
}

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

    #[test]
    fn test_mask_key_long() {
        let key = "sk_live_1234567890abcdef";
        let masked = mask_key(key);
        assert_eq!(masked, "sk_l...cdef");
    }

    #[test]
    fn test_mask_key_short() {
        let key = "short";
        let masked = mask_key(key);
        assert_eq!(masked, "****");
    }

    #[test]
    fn test_llm_provider_openai() {
        let provider = LlmProvider::OpenAI {
            model: "gpt-4".to_string(),
            api_key: None,
        };
        match provider {
            LlmProvider::OpenAI { model, api_key } => {
                assert_eq!(model, "gpt-4");
                assert!(api_key.is_none());
            }
            _ => panic!("Expected OpenAI provider"),
        }
    }

    #[test]
    fn test_llm_provider_anthropic() {
        let provider = LlmProvider::Anthropic {
            model: "claude-3-5-sonnet-latest".to_string(),
            api_key: Some("test-key".to_string()),
        };
        match provider {
            LlmProvider::Anthropic { model, api_key } => {
                assert_eq!(model, "claude-3-5-sonnet-latest");
                assert_eq!(api_key, Some("test-key".to_string()));
            }
            _ => panic!("Expected Anthropic provider"),
        }
    }

    #[test]
    fn test_llm_provider_ollama() {
        let provider = LlmProvider::Ollama {
            endpoint: "http://localhost:11434".to_string(),
            model: "llama3.2".to_string(),
        };
        match provider {
            LlmProvider::Ollama { endpoint, model } => {
                assert_eq!(endpoint, "http://localhost:11434");
                assert_eq!(model, "llama3.2");
            }
            _ => panic!("Expected Ollama provider"),
        }
    }

    #[test]
    fn test_llm_provider_custom() {
        let provider = LlmProvider::Custom {
            endpoint: "https://api.example.com/v1".to_string(),
            model: "custom-model".to_string(),
            api_key: None,
        };
        match provider {
            LlmProvider::Custom {
                endpoint,
                model,
                api_key,
            } => {
                assert_eq!(endpoint, "https://api.example.com/v1");
                assert_eq!(model, "custom-model");
                assert!(api_key.is_none());
            }
            _ => panic!("Expected Custom provider"),
        }
    }
}