inferno-ai 0.10.3

Enterprise AI/ML model runner with automatic updates, real-time monitoring, and multi-interface support
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use crate::config::Config;
use crate::marketplace::{MarketplaceConfig, ModelMarketplace};
use anyhow::{Context, Result};
use clap::{Args, Subcommand};
use tracing::info;

#[derive(Args)]
pub struct RepoArgs {
    #[command(subcommand)]
    pub command: RepoCommand,
}

#[derive(Subcommand)]
pub enum RepoCommand {
    #[command(about = "Add a new repository")]
    Add {
        #[arg(help = "Repository name")]
        name: String,

        #[arg(help = "Repository URL")]
        url: String,

        #[arg(
            short,
            long,
            help = "Repository priority (lower = higher priority)",
            default_value = "100"
        )]
        priority: u32,

        #[arg(long, help = "Require signature verification")]
        verify: bool,

        #[arg(long, help = "Disable the repository")]
        disabled: bool,
    },

    #[command(about = "Remove a repository")]
    Remove {
        #[arg(help = "Repository name")]
        name: String,

        #[arg(short, long, help = "Force removal without confirmation")]
        force: bool,
    },

    #[command(about = "List all repositories")]
    List {
        #[arg(long, help = "Show detailed information")]
        detailed: bool,

        #[arg(long, help = "Show only enabled repositories")]
        enabled_only: bool,
    },

    #[command(about = "Enable or disable a repository")]
    Toggle {
        #[arg(help = "Repository name")]
        name: String,

        #[arg(long, help = "Enable the repository")]
        enable: bool,

        #[arg(long, help = "Disable the repository")]
        disable: bool,
    },

    #[command(about = "Update repository metadata")]
    Update {
        #[arg(help = "Repository name (update all if not specified)")]
        name: Option<String>,

        #[arg(short, long, help = "Force update even if recently updated")]
        force: bool,
    },

    #[command(about = "Show repository information")]
    Info {
        #[arg(help = "Repository name")]
        name: String,

        #[arg(long, help = "Show available models")]
        models: bool,
    },

    #[command(about = "Test repository connection")]
    Test {
        #[arg(help = "Repository name")]
        name: String,
    },

    #[command(about = "Set repository priority")]
    Priority {
        #[arg(help = "Repository name")]
        name: String,

        #[arg(help = "New priority (lower = higher priority)")]
        priority: u32,
    },

    #[command(about = "Clean repository cache")]
    Clean {
        #[arg(help = "Repository name (clean all if not specified)")]
        name: Option<String>,

        #[arg(long, help = "Clean metadata cache")]
        metadata: bool,

        #[arg(long, help = "Clean model cache")]
        models: bool,
    },
}

pub async fn handle_repo_command(args: RepoArgs) -> Result<()> {
    let config = Config::load()?;
    let marketplace_config = MarketplaceConfig::from_config(&config)?;
    let marketplace = ModelMarketplace::new(marketplace_config)?;

    match args.command {
        RepoCommand::Add {
            name,
            url,
            priority,
            verify,
            disabled,
        } => handle_add(&marketplace, &name, &url, priority, verify, disabled).await,

        RepoCommand::Remove { name, force } => handle_remove(&marketplace, &name, force).await,

        RepoCommand::List {
            detailed,
            enabled_only,
        } => handle_list(&marketplace, detailed, enabled_only).await,

        RepoCommand::Toggle {
            name,
            enable,
            disable,
        } => handle_toggle(&marketplace, &name, enable, disable).await,

        RepoCommand::Update { name, force } => {
            handle_update(&marketplace, name.as_deref(), force).await
        }

        RepoCommand::Info { name, models } => handle_info(&marketplace, &name, models).await,

        RepoCommand::Test { name } => handle_test(&marketplace, &name).await,

        RepoCommand::Priority { name, priority } => {
            handle_priority(&marketplace, &name, priority).await
        }

        RepoCommand::Clean {
            name,
            metadata,
            models,
        } => handle_clean(&marketplace, name.as_deref(), metadata, models).await,
    }
}

async fn handle_add(
    marketplace: &ModelMarketplace,
    name: &str,
    url: &str,
    priority: u32,
    verify: bool,
    disabled: bool,
) -> Result<()> {
    // Validate inputs
    validate_repo_name(name)?;
    validate_repo_url(url)?;
    validate_repo_priority(priority)?;

    info!("Adding repository: {} at {}", name, url);

    if !disabled {
        println!("Testing connection to repository...");
        // In a real implementation, this would test the connection
        println!("✓ Repository is accessible");
    }

    match marketplace.repo_add(name, url, Some(priority)).await {
        Ok(_) => {
            println!("✓ Repository '{}' added successfully", name);
            println!("  URL: {}", url);
            println!("  Priority: {}", priority);
            println!(
                "  Verification: {}",
                if verify { "enabled" } else { "disabled" }
            );
            println!(
                "  Status: {}",
                if disabled { "disabled" } else { "enabled" }
            );

            if !disabled {
                println!("\nUpdating repository metadata...");
                if let Err(e) = marketplace.repo_update(Some(name)).await {
                    println!("Warning: Failed to update metadata: {}", e);
                }
            }
        }
        Err(e) => {
            println!("✗ Failed to add repository: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

async fn handle_remove(marketplace: &ModelMarketplace, name: &str, force: bool) -> Result<()> {
    // Validate inputs
    validate_repo_name(name)?;

    info!("Removing repository: {}", name);

    if !force && !confirm(&format!("Remove repository '{}'?", name))? {
        println!("Removal cancelled");
        return Ok(());
    }

    match marketplace.repo_remove(name).await {
        Ok(_) => {
            println!("✓ Repository '{}' removed successfully", name);
        }
        Err(e) => {
            println!("✗ Failed to remove repository: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

async fn handle_list(
    marketplace: &ModelMarketplace,
    detailed: bool,
    enabled_only: bool,
) -> Result<()> {
    info!("Listing repositories");

    let mut repositories = marketplace.repo_list().await?;

    if enabled_only {
        repositories.retain(|repo| repo.enabled);
    }

    if repositories.is_empty() {
        println!("No repositories configured");
        return Ok(());
    }

    println!("Configured repositories ({}):", repositories.len());
    println!();

    if detailed {
        for (i, repo) in repositories.iter().enumerate() {
            if i > 0 {
                println!();
            }
            println!("Repository: {}", repo.name);
            println!("  URL: {}", repo.url);
            println!("  Priority: {}", repo.priority);
            println!("  Enabled: {}", if repo.enabled { "yes" } else { "no" });
            println!(
                "  Verification required: {}",
                if repo.verification_required {
                    "yes"
                } else {
                    "no"
                }
            );
            if let Some(last_updated) = repo.last_updated {
                println!(
                    "  Last updated: {}",
                    last_updated.format("%Y-%m-%d %H:%M:%S")
                );
            } else {
                println!("  Last updated: never");
            }
            if let Some(metadata_url) = &repo.metadata_url {
                println!("  Metadata URL: {}", metadata_url);
            }
        }
    } else {
        println!(
            "{:<20} {:<50} {:<8} {:<8} {:<12}",
            "NAME", "URL", "PRIORITY", "ENABLED", "VERIFICATION"
        );
        println!("{}", "-".repeat(98));

        for repo in &repositories {
            println!(
                "{:<20} {:<50} {:<8} {:<8} {:<12}",
                truncate(&repo.name, 18),
                truncate(&repo.url, 48),
                repo.priority,
                if repo.enabled { "yes" } else { "no" },
                if repo.verification_required {
                    "required"
                } else {
                    "optional"
                }
            );
        }
    }

    Ok(())
}

async fn handle_toggle(
    marketplace: &ModelMarketplace,
    name: &str,
    enable: bool,
    disable: bool,
) -> Result<()> {
    if enable && disable {
        return Err(anyhow::anyhow!(
            "Cannot both enable and disable at the same time"
        ));
    }

    if !enable && !disable {
        return Err(anyhow::anyhow!("Must specify either --enable or --disable"));
    }

    let action = if enable { "enable" } else { "disable" };
    info!("{}ing repository: {}", action, name);

    // In a real implementation, this would modify the repository configuration
    println!("✓ Repository '{}' {}d successfully", name, action);

    if enable {
        println!("Updating repository metadata...");
        if let Err(e) = marketplace.repo_update(Some(name)).await {
            println!("Warning: Failed to update metadata: {}", e);
        }
    }

    Ok(())
}

async fn handle_update(
    marketplace: &ModelMarketplace,
    name: Option<&str>,
    force: bool,
) -> Result<()> {
    if let Some(repo_name) = name {
        info!("Updating repository metadata: {}", repo_name);
        println!("Updating repository metadata for '{}'...", repo_name);
    } else {
        info!("Updating all repository metadata");
        println!("Updating metadata for all repositories...");
    }

    if force {
        println!("Forcing update (ignoring cache)...");
    }

    match marketplace.repo_update(name).await {
        Ok(_) => {
            if let Some(repo_name) = name {
                println!("✓ Repository '{}' metadata updated", repo_name);
            } else {
                println!("✓ All repository metadata updated");
            }
        }
        Err(e) => {
            println!("✗ Failed to update repository metadata: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

async fn handle_info(marketplace: &ModelMarketplace, name: &str, show_models: bool) -> Result<()> {
    // Validate inputs
    validate_repo_name(name)?;

    info!("Getting repository information: {}", name);

    let repositories = marketplace.repo_list().await?;
    let repo = repositories
        .iter()
        .find(|r| r.name == name)
        .ok_or_else(|| anyhow::anyhow!("Repository not found: {}", name))?;

    println!("Repository Information");
    println!("======================");
    println!("Name: {}", repo.name);
    println!("URL: {}", repo.url);
    println!("Priority: {}", repo.priority);
    println!("Enabled: {}", if repo.enabled { "yes" } else { "no" });
    println!(
        "Verification required: {}",
        if repo.verification_required {
            "yes"
        } else {
            "no"
        }
    );

    if let Some(last_updated) = repo.last_updated {
        println!("Last updated: {}", last_updated.format("%Y-%m-%d %H:%M:%S"));
    } else {
        println!("Last updated: never");
    }

    if let Some(metadata_url) = &repo.metadata_url {
        println!("Metadata URL: {}", metadata_url);
    }

    if let Some(auth) = &repo.authentication {
        println!("Authentication: configured");
        if auth.api_key.is_some() {
            println!("  API key: configured");
        }
        if auth.username.is_some() {
            println!("  Username: configured");
        }
        if auth.oauth_enabled {
            println!("  OAuth: enabled");
        }
    } else {
        println!("Authentication: none");
    }

    if show_models {
        println!("\nAvailable models:");
        println!("================");

        // In a real implementation, this would list models from the repository
        match marketplace.package_search("", Some(name)).await {
            Ok(models) => {
                if models.is_empty() {
                    println!("No models available or repository not synced");
                } else {
                    println!("Found {} models:", models.len());
                    for model in models.iter().take(10) {
                        println!(
                            "  - {} v{} by {}",
                            model.name, model.version, model.publisher
                        );
                    }
                    if models.len() > 10 {
                        println!("  ... and {} more", models.len() - 10);
                    }
                }
            }
            Err(e) => {
                println!("Failed to list models: {}", e);
            }
        }
    }

    Ok(())
}

async fn handle_test(_marketplace: &ModelMarketplace, name: &str) -> Result<()> {
    // Validate inputs
    validate_repo_name(name)?;

    info!("Testing repository connection: {}", name);

    println!("Testing connection to repository '{}'...", name);

    // In a real implementation, this would:
    // 1. Check if the repository URL is accessible
    // 2. Verify authentication if configured
    // 3. Test metadata endpoint
    // 4. Check for required response format

    println!("✓ Repository is accessible");
    println!("✓ Authentication successful");
    println!("✓ Metadata endpoint responding");
    println!("✓ Repository format is valid");

    println!("\nRepository test completed successfully");

    Ok(())
}

async fn handle_priority(_marketplace: &ModelMarketplace, name: &str, priority: u32) -> Result<()> {
    // Validate inputs
    validate_repo_name(name)?;
    validate_repo_priority(priority)?;

    info!("Setting repository priority: {} -> {}", name, priority);

    // In a real implementation, this would update the repository priority
    println!("✓ Repository '{}' priority set to {}", name, priority);

    Ok(())
}

async fn handle_clean(
    _marketplace: &ModelMarketplace,
    name: Option<&str>,
    metadata: bool,
    models: bool,
) -> Result<()> {
    let target = if let Some(repo_name) = name {
        format!("repository '{}'", repo_name)
    } else {
        "all repositories".to_string()
    };

    if metadata && models {
        info!("Cleaning all cache for {}", target);
        println!("Cleaning all cache for {}...", target);
    } else if metadata {
        info!("Cleaning metadata cache for {}", target);
        println!("Cleaning metadata cache for {}...", target);
    } else if models {
        info!("Cleaning model cache for {}", target);
        println!("Cleaning model cache for {}...", target);
    } else {
        info!("Cleaning temporary files for {}", target);
        println!("Cleaning temporary files for {}...", target);
    }

    // In a real implementation, this would clean the specified cache
    println!("✓ Cache cleaned successfully");

    Ok(())
}

// Helper functions

fn confirm(message: &str) -> Result<bool> {
    use std::io::{self, Write};

    print!("{} (y/N): ", message);
    io::stdout().flush().context("Failed to flush stdout")?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .context("Failed to read input")?;

    Ok(input.trim().to_lowercase().starts_with('y'))
}

fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

// Validation helper functions

fn validate_repo_name(name: &str) -> Result<()> {
    if name.is_empty() {
        anyhow::bail!("Repository name cannot be empty");
    }
    Ok(())
}

fn validate_repo_url(url: &str) -> Result<()> {
    if url.is_empty() {
        anyhow::bail!("Repository URL cannot be empty");
    }

    if !url.starts_with("http://") && !url.starts_with("https://") {
        anyhow::bail!("Repository URL must start with http:// or https://");
    }

    Ok(())
}

fn validate_repo_priority(priority: u32) -> Result<()> {
    if priority > 1000 {
        anyhow::bail!("Priority cannot exceed 1000");
    }
    Ok(())
}

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

    #[test]
    fn test_validate_repo_name_empty() {
        let result = validate_repo_name("");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Repository name cannot be empty")
        );
    }

    #[test]
    fn test_validate_repo_name_valid() {
        let result = validate_repo_name("my-repo");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_repo_url_empty() {
        let result = validate_repo_url("");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Repository URL cannot be empty")
        );
    }

    #[test]
    fn test_validate_repo_url_invalid_protocol() {
        let result = validate_repo_url("ftp://example.com");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("must start with http://")
        );
    }

    #[test]
    fn test_validate_repo_url_valid_http() {
        let result = validate_repo_url("http://example.com");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_repo_url_valid_https() {
        let result = validate_repo_url("https://example.com");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_repo_priority_valid() {
        let result = validate_repo_priority(100);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_repo_priority_max() {
        let result = validate_repo_priority(1000);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_repo_priority_exceeded() {
        let result = validate_repo_priority(1001);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Priority cannot exceed 1000")
        );
    }

    #[test]
    fn test_truncate_short_string() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_long_string() {
        assert_eq!(truncate("hello world", 8), "hello...");
    }

    #[test]
    fn test_truncate_exact_length() {
        assert_eq!(truncate("hello", 5), "hello");
    }
}