paladin-ai 0.4.1

Enterprise AI orchestration framework with multi-agent coordination patterns
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Setup check command
//!
//! Validates the Paladin environment setup including:
//! - CLI version and Rust toolchain
//! - Environment variables and .env file
//! - LLM provider connectivity (OpenAI, Anthropic, DeepSeek)
//! - Optional service connectivity (Redis, Qdrant)

use crate::application::cli::error::{CliError, CliResult};
use crate::application::cli::formatters::output::OutputFormatter;
use crate::application::cli::formatters::progress::Spinner;
use reqwest::Client;
use serde_json::json;
use std::collections::HashMap;
use std::env;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

/// Validation result for a specific check
#[derive(Debug, Clone, PartialEq, Eq)]
enum CheckStatus {
    Pass,
    Warn(String),
    Fail(String),
    Skip(String),
}

/// Category of check being performed
#[derive(Debug, Clone, Copy)]
enum CheckCategory {
    System,
    Environment,
    Provider,
    Service,
}

impl CheckCategory {
    fn label(&self) -> &str {
        match self {
            CheckCategory::System => "System",
            CheckCategory::Environment => "Environment",
            CheckCategory::Provider => "LLM Provider",
            CheckCategory::Service => "Service",
        }
    }
}

/// Result of a single validation check
struct CheckResult {
    category: CheckCategory,
    name: String,
    status: CheckStatus,
}

impl CheckResult {
    fn new(category: CheckCategory, name: impl Into<String>, status: CheckStatus) -> Self {
        Self {
            category,
            name: name.into(),
            status,
        }
    }
}

// API Validation Functions (reused from onboarding)

/// Validate OpenAI API key by calling the models endpoint
async fn validate_openai_key(api_key: &str) -> CliResult<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|e| CliError::execution(format!("Failed to create HTTP client: {}", e)))?;

    let response = client
        .get("https://api.openai.com/v1/models")
        .header("Authorization", format!("Bearer {}", api_key))
        .send()
        .await
        .map_err(|e| CliError::execution(format!("API request failed: {}", e)))?;

    if response.status().is_success() {
        Ok(())
    } else {
        let status = response.status();
        Err(CliError::execution(format!(
            "OpenAI API validation failed ({})",
            status
        )))
    }
}

/// Validate Anthropic API key by making a minimal request
async fn validate_anthropic_key(api_key: &str) -> CliResult<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|e| CliError::execution(format!("Failed to create HTTP client: {}", e)))?;

    let body = json!({
        "model": "claude-3-haiku-20240307",
        "max_tokens": 1,
        "messages": [{"role": "user", "content": "test"}]
    });

    let response = client
        .post("https://api.anthropic.com/v1/messages")
        .header("x-api-key", api_key)
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json")
        .json(&body)
        .send()
        .await
        .map_err(|e| CliError::execution(format!("API request failed: {}", e)))?;

    if response.status().is_success() {
        Ok(())
    } else {
        let status = response.status();
        Err(CliError::execution(format!(
            "Anthropic API validation failed ({})",
            status
        )))
    }
}

/// Validate DeepSeek API key by calling the models endpoint
async fn validate_deepseek_key(api_key: &str) -> CliResult<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|e| CliError::execution(format!("Failed to create HTTP client: {}", e)))?;

    let response = client
        .get("https://api.deepseek.com/v1/models")
        .header("Authorization", format!("Bearer {}", api_key))
        .send()
        .await
        .map_err(|e| CliError::execution(format!("API request failed: {}", e)))?;

    if response.status().is_success() {
        Ok(())
    } else {
        let status = response.status();
        Err(CliError::execution(format!(
            "DeepSeek API validation failed ({})",
            status
        )))
    }
}

/// Check Redis connectivity
async fn check_redis_connectivity(redis_url: &str) -> CliResult<()> {
    // For now, just validate the URL format
    // Full redis connectivity check would require redis client dependency
    if redis_url.starts_with("redis://") || redis_url.starts_with("rediss://") {
        Ok(())
    } else {
        Err(CliError::configuration(format!(
            "Invalid Redis URL format: {}",
            redis_url
        )))
    }
}

/// Check Qdrant connectivity
async fn check_qdrant_connectivity(qdrant_url: &str) -> CliResult<()> {
    let client = Client::builder()
        .timeout(Duration::from_secs(5))
        .build()
        .map_err(|e| CliError::execution(format!("Failed to create HTTP client: {}", e)))?;

    // Try to get collections list
    let url = format!("{}/collections", qdrant_url.trim_end_matches('/'));
    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|e| CliError::execution(format!("Qdrant connection failed: {}", e)))?;

    if response.status().is_success() {
        Ok(())
    } else {
        Err(CliError::execution(format!(
            "Qdrant API check failed ({})",
            response.status()
        )))
    }
}

// Check Functions

/// Check Paladin CLI version
fn check_cli_version() -> CheckResult {
    let version = env!("CARGO_PKG_VERSION");
    CheckResult::new(
        CheckCategory::System,
        format!("Paladin CLI v{}", version),
        CheckStatus::Pass,
    )
}

/// Check Rust toolchain version
fn check_rust_version() -> CheckResult {
    let output = Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string());

    match output {
        Some(version) => CheckResult::new(
            CheckCategory::System,
            format!("Rust Toolchain ({})", version),
            CheckStatus::Pass,
        ),
        None => CheckResult::new(
            CheckCategory::System,
            "Rust Toolchain",
            CheckStatus::Fail("Could not detect Rust toolchain".into()),
        ),
    }
}

/// Check for .env file
fn check_env_file() -> CheckResult {
    let env_path = Path::new(".env");
    if env_path.exists() {
        CheckResult::new(CheckCategory::Environment, ".env file", CheckStatus::Pass)
    } else {
        CheckResult::new(
            CheckCategory::Environment,
            ".env file",
            CheckStatus::Warn("Not found - run 'paladin onboarding' to create".into()),
        )
    }
}

/// Check OpenAI configuration
async fn check_openai() -> CheckResult {
    match env::var("OPENAI_API_KEY") {
        Ok(api_key) if !api_key.is_empty() => match validate_openai_key(&api_key).await {
            Ok(_) => CheckResult::new(CheckCategory::Provider, "OpenAI", CheckStatus::Pass),
            Err(e) => CheckResult::new(
                CheckCategory::Provider,
                "OpenAI",
                CheckStatus::Fail(format!("API validation failed: {}", e)),
            ),
        },
        _ => CheckResult::new(
            CheckCategory::Provider,
            "OpenAI",
            CheckStatus::Skip("OPENAI_API_KEY not configured".into()),
        ),
    }
}

/// Check Anthropic configuration
async fn check_anthropic() -> CheckResult {
    match env::var("ANTHROPIC_API_KEY") {
        Ok(api_key) if !api_key.is_empty() => match validate_anthropic_key(&api_key).await {
            Ok(_) => CheckResult::new(CheckCategory::Provider, "Anthropic", CheckStatus::Pass),
            Err(e) => CheckResult::new(
                CheckCategory::Provider,
                "Anthropic",
                CheckStatus::Fail(format!("API validation failed: {}", e)),
            ),
        },
        _ => CheckResult::new(
            CheckCategory::Provider,
            "Anthropic",
            CheckStatus::Skip("ANTHROPIC_API_KEY not configured".into()),
        ),
    }
}

/// Check DeepSeek configuration
async fn check_deepseek() -> CheckResult {
    match env::var("DEEPSEEK_API_KEY") {
        Ok(api_key) if !api_key.is_empty() => match validate_deepseek_key(&api_key).await {
            Ok(_) => CheckResult::new(CheckCategory::Provider, "DeepSeek", CheckStatus::Pass),
            Err(e) => CheckResult::new(
                CheckCategory::Provider,
                "DeepSeek",
                CheckStatus::Fail(format!("API validation failed: {}", e)),
            ),
        },
        _ => CheckResult::new(
            CheckCategory::Provider,
            "DeepSeek",
            CheckStatus::Skip("DEEPSEEK_API_KEY not configured".into()),
        ),
    }
}

/// Check Redis configuration and connectivity
async fn check_redis() -> CheckResult {
    match env::var("REDIS_URL") {
        Ok(redis_url) if !redis_url.is_empty() => {
            match check_redis_connectivity(&redis_url).await {
                Ok(_) => CheckResult::new(CheckCategory::Service, "Redis", CheckStatus::Pass),
                Err(e) => CheckResult::new(
                    CheckCategory::Service,
                    "Redis",
                    CheckStatus::Fail(format!("Connection failed: {}", e)),
                ),
            }
        }
        _ => CheckResult::new(
            CheckCategory::Service,
            "Redis",
            CheckStatus::Skip("REDIS_URL not configured".into()),
        ),
    }
}

/// Check Qdrant configuration and connectivity
async fn check_qdrant() -> CheckResult {
    match env::var("QDRANT_URL") {
        Ok(qdrant_url) if !qdrant_url.is_empty() => {
            match check_qdrant_connectivity(&qdrant_url).await {
                Ok(_) => CheckResult::new(CheckCategory::Service, "Qdrant", CheckStatus::Pass),
                Err(e) => CheckResult::new(
                    CheckCategory::Service,
                    "Qdrant",
                    CheckStatus::Fail(format!("Connection failed: {}", e)),
                ),
            }
        }
        _ => CheckResult::new(
            CheckCategory::Service,
            "Qdrant",
            CheckStatus::Skip("QDRANT_URL not configured".into()),
        ),
    }
}

/// Run environment setup checks
pub async fn run_setup_check(verbose: bool) -> Result<i32, CliError> {
    let formatter = OutputFormatter::new();

    formatter.header("Paladin Setup Check");
    println!();

    // Collect all checks
    let mut results = Vec::new();

    // System checks
    results.push(check_cli_version());
    results.push(check_rust_version());

    // Environment checks
    results.push(check_env_file());

    // Provider checks (with async validation)
    let spinner = Spinner::new("Checking LLM providers...");
    results.push(check_openai().await);
    results.push(check_anthropic().await);
    results.push(check_deepseek().await);
    spinner.finish_with_message("LLM provider checks complete");
    println!();

    // Service checks
    let spinner = Spinner::new("Checking optional services...");
    results.push(check_redis().await);
    results.push(check_qdrant().await);
    spinner.finish_with_message("Service checks complete");
    println!();

    // Group results by category
    let mut categorized: HashMap<String, Vec<&CheckResult>> = HashMap::new();
    for result in &results {
        categorized
            .entry(result.category.label().to_string())
            .or_default()
            .push(result);
    }

    // Display results by category
    let mut has_failures = false;
    let mut has_warnings = false;

    for (category, checks) in &categorized {
        println!("{}:", category);
        for check in checks {
            match &check.status {
                CheckStatus::Pass => {
                    println!("{} ", check.name);
                    if verbose {
                        formatter.info("  All checks passed");
                    }
                }
                CheckStatus::Warn(msg) => {
                    has_warnings = true;
                    println!("{} ", check.name);
                    formatter.warning(&format!("  {}", msg));
                }
                CheckStatus::Fail(msg) => {
                    has_failures = true;
                    println!("{} ", check.name);
                    formatter.error(&format!("  {}", msg));
                }
                CheckStatus::Skip(msg) => {
                    if verbose {
                        println!("{} ", check.name);
                        formatter.info(&format!("  {}", msg));
                    }
                }
            }
        }
        println!();
    }

    // Summary
    let pass_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Pass))
        .count();
    let warn_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Warn(_)))
        .count();
    let fail_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Fail(_)))
        .count();
    let skip_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Skip(_)))
        .count();

    formatter.header("Summary");
    println!("  Passed: {}", pass_count);
    if warn_count > 0 {
        println!("  Warnings: {}", warn_count);
    }
    if fail_count > 0 {
        println!("  Failed: {}", fail_count);
    }
    if verbose && skip_count > 0 {
        println!("  Skipped: {}", skip_count);
    }
    println!();

    // Exit code
    let exit_code = if has_failures {
        formatter.error("Setup check failed - please address the errors above");
        1
    } else if has_warnings {
        formatter.warning("Setup check completed with warnings");
        2
    } else {
        formatter.success("All checks passed! ✨");
        0
    };

    println!();
    if exit_code > 0 {
        formatter.box_message(&[
            "Next Steps:",
            "1. Run 'paladin onboarding' to configure missing providers",
            "2. Verify environment variables in your .env file",
            "3. Run 'paladin setup-check' again to verify",
        ]);
    }

    Ok(exit_code)
}

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

    #[test]
    fn test_check_cli_version() {
        let result = check_cli_version();
        assert_eq!(result.status, CheckStatus::Pass);
    }

    #[test]
    fn test_check_rust_version() {
        let result = check_rust_version();
        // Should either pass or fail, never skip
        assert!(matches!(
            result.status,
            CheckStatus::Pass | CheckStatus::Fail(_)
        ));
    }

    #[test]
    fn test_check_env_file() {
        let result = check_env_file();
        // Should either pass or warn, never fail
        assert!(matches!(
            result.status,
            CheckStatus::Pass | CheckStatus::Warn(_)
        ));
    }

    #[tokio::test]
    #[ignore] // Requires valid API key
    async fn test_validate_openai_key_invalid() {
        let result = validate_openai_key("invalid-key-12345").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    #[ignore] // Requires valid API key
    async fn test_validate_anthropic_key_invalid() {
        let result = validate_anthropic_key("invalid-key-12345").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    #[ignore] // Requires valid API key
    async fn test_validate_deepseek_key_invalid() {
        let result = validate_deepseek_key("invalid-key-12345").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_check_openai_no_env() {
        // Temporarily remove env var
        unsafe {
            env::remove_var("OPENAI_API_KEY");
        }
        let result = check_openai().await;
        assert!(matches!(result.status, CheckStatus::Skip(_)));
    }

    #[tokio::test]
    async fn test_check_redis_invalid_url() {
        let result = check_redis_connectivity("invalid-url").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_check_redis_valid_url_format() {
        let result = check_redis_connectivity("redis://localhost:6379").await;
        assert!(result.is_ok());
    }
}