Skip to main content

roboticus_cli/cli/admin/
plugins.rs

1use super::*;
2
3use roboticus_plugin_sdk::manifest::PluginManifest;
4use sha2::{Digest, Sha256};
5
6// ── Install source detection ────────────────────────────────────
7
8enum InstallSource {
9    /// Local directory containing plugin.toml (dev mode)
10    Directory(std::path::PathBuf),
11    /// Local .ic.zip archive
12    Archive(std::path::PathBuf),
13    /// Catalog plugin name (fetched from registry)
14    Catalog(String),
15}
16
17fn detect_source(source: &str) -> InstallSource {
18    let path = std::path::Path::new(source);
19    let has_path_sep = source.contains('/') || source.contains('\\');
20    let is_zip = path.extension().and_then(|e| e.to_str()) == Some("zip");
21
22    if is_zip {
23        // Anything ending in .zip is treated as an archive path
24        InstallSource::Archive(path.to_path_buf())
25    } else if has_path_sep || path.exists() {
26        // Contains path separators or exists on disk → filesystem directory
27        InstallSource::Directory(path.to_path_buf())
28    } else {
29        // Bare name like "claude-code" → catalog lookup
30        InstallSource::Catalog(source.to_string())
31    }
32}
33
34// ── Plugin listing ────────────────────────────────────────────
35
36pub async fn cmd_plugins_list(
37    base_url: &str,
38    json: bool,
39) -> Result<(), Box<dyn std::error::Error>> {
40    let resp = super::http_client()?
41        .get(format!("{base_url}/api/plugins"))
42        .send()
43        .await?;
44    let body: serde_json::Value = resp.json().await?;
45    if json {
46        println!("{}", serde_json::to_string_pretty(&body)?);
47        return Ok(());
48    }
49
50    let plugins = body
51        .get("plugins")
52        .and_then(|v| v.as_array())
53        .cloned()
54        .unwrap_or_default();
55
56    if plugins.is_empty() {
57        println!("\n  No plugins installed.\n");
58        return Ok(());
59    }
60
61    println!(
62        "\n  {:<20} {:<10} {:<10} {:<10}",
63        "Plugin", "Version", "Status", "Tools"
64    );
65    println!("  {}", "─".repeat(55));
66    for p in &plugins {
67        let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("?");
68        let version = p.get("version").and_then(|v| v.as_str()).unwrap_or("?");
69        let status = p.get("status").and_then(|v| v.as_str()).unwrap_or("?");
70        let tools = p
71            .get("tools")
72            .and_then(|v| v.as_array())
73            .map(|a| a.len())
74            .unwrap_or(0);
75        println!(
76            "  {:<20} {:<10} {:<10} {:<10}",
77            name, version, status, tools
78        );
79    }
80    println!();
81    Ok(())
82}
83
84// ── Plugin info ─────────────────────────────────────────────
85
86pub async fn cmd_plugin_info(
87    base_url: &str,
88    name: &str,
89    json: bool,
90) -> Result<(), Box<dyn std::error::Error>> {
91    let (_dim, bold, _accent, green, yellow, red, _cyan, reset, _mono) = colors();
92    let (ok, _action, _warn, _detail, _err_icon) = icons();
93    let resp = super::http_client()?
94        .get(format!("{base_url}/api/plugins"))
95        .send()
96        .await?;
97    let body: serde_json::Value = resp.json().await.unwrap_or_else(|e| {
98        tracing::warn!("failed to parse plugin info response: {e}");
99        serde_json::Value::default()
100    });
101    if json {
102        println!("{}", serde_json::to_string_pretty(&body)?);
103        return Ok(());
104    }
105    let plugins: Vec<serde_json::Value> = body
106        .get("plugins")
107        .and_then(|v| v.as_array())
108        .cloned()
109        .unwrap_or_default();
110
111    let plugin = plugins
112        .iter()
113        .find(|p| p.get("name").and_then(|v| v.as_str()) == Some(name));
114
115    match plugin {
116        Some(p) => {
117            println!("\n  {bold}Plugin: {name}{reset}\n");
118            if let Some(v) = p.get("version").and_then(|v| v.as_str()) {
119                println!("  Version:     {v}");
120            }
121            if let Some(d) = p.get("description").and_then(|v| v.as_str()) {
122                println!("  Description: {d}");
123            }
124            let status = p
125                .get("status")
126                .and_then(|v| v.as_str())
127                .map(|s| s.to_ascii_lowercase())
128                .or_else(|| {
129                    p.get("enabled").and_then(|v| v.as_bool()).map(|b| {
130                        if b {
131                            "active".to_string()
132                        } else {
133                            "disabled".to_string()
134                        }
135                    })
136                })
137                .unwrap_or_else(|| "unknown".to_string());
138            println!(
139                "  Status:      {}",
140                if status == "active" || status == "loaded" {
141                    format!("{green}{status}{reset}")
142                } else if status == "disabled" || status == "error" {
143                    format!("{red}{status}{reset}")
144                } else {
145                    format!("{yellow}{status}{reset}")
146                }
147            );
148            if let Some(path) = p.get("manifest_path").and_then(|v| v.as_str()) {
149                println!("  Manifest:    {path}");
150            }
151            if let Some(tools) = p.get("tools").and_then(|v| v.as_array()) {
152                println!("  Tools:       {}", tools.len());
153                for tool in tools {
154                    if let Some(tn) = tool.get("name").and_then(|v| v.as_str()) {
155                        println!("    {ok} {tn}");
156                    }
157                }
158            }
159            println!();
160        }
161        None => {
162            eprintln!("  Plugin not found: {name}");
163            return Err(format!("plugin not found: {name}").into());
164        }
165    }
166    Ok(())
167}
168
169// ── Shared helpers ──────────────────────────────────────────
170
171fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
172    if !dst.exists() {
173        std::fs::create_dir_all(dst)?;
174    }
175    for entry in std::fs::read_dir(src)? {
176        let entry = entry?;
177        let ty = entry.file_type()?;
178        if ty.is_symlink() {
179            continue;
180        }
181        let dest_path = dst.join(entry.file_name());
182        if ty.is_dir() {
183            copy_dir_recursive(&entry.path(), &dest_path)?;
184        } else if ty.is_file() {
185            std::fs::copy(entry.path(), &dest_path)?;
186        }
187    }
188    Ok(())
189}
190
191pub(crate) fn companion_skill_install_name(plugin_name: &str, skill_rel: &str) -> String {
192    let skill_filename = std::path::Path::new(skill_rel)
193        .file_name()
194        .unwrap_or_default()
195        .to_string_lossy();
196    let hash = Sha256::digest(skill_rel.as_bytes());
197    let short = hex::encode(&hash[..6]);
198    format!("{plugin_name}--{short}--{skill_filename}")
199}
200
201fn check_requirements(manifest: &PluginManifest) -> bool {
202    let (_dim, bold, _accent, green, yellow, red, cyan, reset, _mono) = colors();
203    let (ok, action, warn, _detail, err_icon) = icons();
204
205    if manifest.requirements.is_empty() {
206        return true;
207    }
208
209    println!(
210        "\n  {action} Checking requirements for {bold}{}{reset}...\n",
211        manifest.name
212    );
213    let results = manifest.check_requirements();
214    let mut has_missing_required = false;
215
216    for (req, found) in &results {
217        if *found {
218            println!(
219                "    {ok} {green}{}{reset} ({}) — found",
220                req.name, req.command
221            );
222        } else if req.optional {
223            println!(
224                "    {warn} {yellow}{}{reset} ({}) — not found (optional)",
225                req.name, req.command
226            );
227        } else {
228            has_missing_required = true;
229            println!(
230                "    {err_icon} {red}{}{reset} ({}) — not found",
231                req.name, req.command
232            );
233            if let Some(hint) = &req.install_hint {
234                println!("      Install: {cyan}{hint}{reset}");
235            }
236        }
237    }
238    println!();
239
240    if has_missing_required {
241        eprintln!(
242            "  {err_icon} Cannot install {}: missing required dependencies.",
243            manifest.name
244        );
245        eprintln!("  Install the missing requirements above and try again.\n");
246        return false;
247    }
248    true
249}
250
251fn check_companion_skills_exist(manifest: &PluginManifest, source_dir: &std::path::Path) -> bool {
252    let (_dim, _bold, _accent, _green, _yellow, _red, _cyan, _reset, _mono) = colors();
253    let (_ok, _action, _warn, _detail, err_icon) = icons();
254
255    for skill_path in &manifest.companion_skills {
256        let full = source_dir.join(skill_path);
257        if !full.exists() {
258            eprintln!("  {err_icon} Companion skill not found in bundle: {skill_path}");
259            return false;
260        }
261    }
262    true
263}
264
265fn check_not_installed(plugin_name: &str) -> Result<std::path::PathBuf, ()> {
266    let roboticus_dir = roboticus_core::home_dir().join(".roboticus");
267    let plugins_dir = roboticus_dir.join("plugins");
268    let dest = plugins_dir.join(plugin_name);
269
270    if dest.exists() {
271        eprintln!("  Plugin already installed: {plugin_name}");
272        eprintln!("  Uninstall first with: roboticus plugins uninstall {plugin_name}");
273        return Err(());
274    }
275    Ok(dest)
276}
277
278fn deploy_companion_skills(
279    manifest: &PluginManifest,
280    source_dir: &std::path::Path,
281) -> Result<(), Box<dyn std::error::Error>> {
282    let (ok, _action, _warn, _detail, _err_icon) = icons();
283    if manifest.companion_skills.is_empty() {
284        return Ok(());
285    }
286
287    let roboticus_dir = roboticus_core::home_dir().join(".roboticus");
288    let skills_dir = roboticus_dir.join("skills");
289    std::fs::create_dir_all(&skills_dir)?;
290
291    let mut installed = Vec::new();
292    for skill_rel in &manifest.companion_skills {
293        let src_skill = source_dir.join(skill_rel);
294        let installed_name = companion_skill_install_name(&manifest.name, skill_rel);
295        let dest_skill = skills_dir.join(&installed_name);
296
297        if let Err(e) = std::fs::copy(&src_skill, &dest_skill) {
298            // best-effort: rollback cleanup on install failure
299            for path in installed.iter().rev() {
300                let _ = std::fs::remove_file(path);
301            }
302            return Err(Box::new(e));
303        }
304        installed.push(dest_skill);
305        println!("  {ok} Installed companion skill: {installed_name}");
306    }
307    Ok(())
308}
309
310fn print_plugin_summary(manifest: &PluginManifest, source_label: &str) {
311    let (_dim, bold, _accent, green, _yellow, _red, _cyan, reset, _mono) = colors();
312    let (ok, _action, _warn, _detail, _err_icon) = icons();
313
314    println!("\n  {ok} Installed plugin: {bold}{}{reset}", manifest.name);
315    println!("  Version: {green}{}{reset}", manifest.version);
316    if !manifest.description.is_empty() {
317        println!("  {}", truncate_str(&manifest.description, 72));
318    }
319    println!("  Source:  {source_label}");
320    println!("  Restart the server to activate.\n");
321}
322
323fn truncate_str(s: &str, max: usize) -> String {
324    if max == 0 {
325        return String::new();
326    }
327    if s.len() <= max {
328        return s.to_string();
329    }
330    // Walk char boundaries to find the last safe index within budget
331    let end = s
332        .char_indices()
333        .map(|(i, _)| i)
334        .take(max)
335        .last()
336        .unwrap_or(0);
337    format!("{}…", &s[..end])
338}
339
340fn prompt_yes_no(prompt: &str) -> bool {
341    use std::io::Write;
342    print!("  {prompt} [y/N] ");
343    std::io::stdout().flush().ok();
344    let mut input = String::new();
345    if std::io::stdin().read_line(&mut input).is_err() {
346        return false;
347    }
348    matches!(input.trim().to_ascii_lowercase().as_str(), "y" | "yes")
349}
350
351// ── Install: unified entry point ────────────────────────────
352
353pub async fn cmd_plugin_install(source: &str) -> Result<(), Box<dyn std::error::Error>> {
354    match detect_source(source) {
355        InstallSource::Directory(path) => install_from_directory(&path),
356        InstallSource::Archive(path) => install_from_archive(&path),
357        InstallSource::Catalog(name) => install_from_catalog(&name).await,
358    }
359}
360
361// ── Install from local directory (dev mode) ─────────────────
362
363fn install_from_directory(source_path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
364    let (_dim, _bold, _accent, _green, _yellow, _red, _cyan, _reset, _mono) = colors();
365    let (_ok, _action, warn, _detail, err_icon) = icons();
366
367    if !source_path.exists() {
368        return Err(format!("source not found: {}", source_path.display()).into());
369    }
370
371    let manifest_path = source_path.join("plugin.toml");
372    if !manifest_path.exists() {
373        return Err(format!("no plugin.toml found in {}", source_path.display()).into());
374    }
375
376    let manifest = PluginManifest::from_file(&manifest_path)
377        .map_err(|e| format!("Invalid plugin.toml: {e}"))?;
378
379    // Vet the plugin before installing (same gate as pack and server startup)
380    let report = manifest.vet(source_path);
381    for w in &report.warnings {
382        eprintln!("    {warn} {w}");
383    }
384    if !report.is_ok() {
385        for e in &report.errors {
386            eprintln!("    {err_icon} {e}");
387        }
388        eprintln!("\n  {err_icon} Plugin failed vetting. Fix errors above before installing.\n");
389        return Err("plugin vetting failed".into());
390    }
391
392    if !check_requirements(&manifest) {
393        return Err("missing required plugin dependencies".into());
394    }
395    if !check_companion_skills_exist(&manifest, source_path) {
396        return Err("companion skill files missing from plugin bundle".into());
397    }
398    let dest = match check_not_installed(&manifest.name) {
399        Ok(d) => d,
400        Err(()) => return Err(format!("plugin '{}' already installed", manifest.name).into()),
401    };
402
403    std::fs::create_dir_all(&dest)?;
404    if let Err(e) = copy_dir_recursive(source_path, &dest) {
405        // best-effort: rollback cleanup on install failure
406        let _ = std::fs::remove_dir_all(&dest);
407        return Err(Box::new(e));
408    }
409
410    if let Err(e) = deploy_companion_skills(&manifest, source_path) {
411        // best-effort: rollback cleanup on install failure
412        let _ = std::fs::remove_dir_all(&dest);
413        return Err(e);
414    }
415    print_plugin_summary(&manifest, &format!("directory: {}", source_path.display()));
416    Ok(())
417}
418
419// ── Install from .ic.zip archive ────────────────────────────
420
421fn install_from_archive(archive_path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
422    use roboticus_plugin_sdk::archive;
423
424    let (_dim, bold, _accent, green, _yellow, _red, cyan, reset, _mono) = colors();
425    let (ok, action, _warn, _detail, err_icon) = icons();
426
427    if !archive_path.exists() {
428        return Err(format!("archive not found: {}", archive_path.display()).into());
429    }
430
431    println!("\n  {action} Unpacking {}...", archive_path.display());
432
433    // Unpack to staging area
434    let staging_dir = roboticus_core::home_dir()
435        .join(".roboticus")
436        .join("staging");
437    std::fs::create_dir_all(&staging_dir)?;
438
439    let result = archive::unpack(archive_path, &staging_dir)
440        .map_err(|e| format!("Failed to unpack archive: {e}"))?;
441
442    println!(
443        "  {ok} Unpacked {bold}{}{reset} v{green}{}{reset} ({} files)",
444        result.manifest.name, result.manifest.version, result.file_count
445    );
446    println!("  {ok} SHA-256: {cyan}{}{reset}", &result.sha256[..16]);
447
448    // Requirements check
449    if !check_requirements(&result.manifest) {
450        // best-effort: staging cleanup on early exit
451        let _ = std::fs::remove_dir_all(&result.dest_dir);
452        return Err("missing required plugin dependencies".into());
453    }
454
455    // Check not already installed
456    let dest = match check_not_installed(&result.manifest.name) {
457        Ok(d) => d,
458        Err(()) => {
459            // best-effort: staging cleanup on early exit
460            let _ = std::fs::remove_dir_all(&result.dest_dir);
461            return Err(format!("plugin '{}' already installed", result.manifest.name).into());
462        }
463    };
464
465    // Prompt user
466    if !prompt_yes_no(&format!(
467        "Install {} v{}?",
468        result.manifest.name, result.manifest.version
469    )) {
470        println!("  Cancelled.");
471        let _ = std::fs::remove_dir_all(&result.dest_dir);
472        return Ok(());
473    }
474
475    // Move from staging to plugins dir
476    std::fs::create_dir_all(dest.parent().unwrap_or(&dest))?;
477    std::fs::rename(&result.dest_dir, &dest).or_else(|_| {
478        // rename fails across filesystems; fall back to copy + remove
479        if let Err(e) = copy_dir_recursive(&result.dest_dir, &dest) {
480            let _ = std::fs::remove_dir_all(&dest);
481            return Err(e);
482        }
483        std::fs::remove_dir_all(&result.dest_dir)
484    })?;
485
486    if let Err(e) = deploy_companion_skills(&result.manifest, &dest) {
487        // Roll back partial install on post-move failure.
488        if let Err(clean_err) = std::fs::remove_dir_all(&dest) {
489            eprintln!(
490                "  {err_icon} Companion skill deployment failed and rollback also failed: {clean_err}"
491            );
492        }
493        return Err(e);
494    }
495    print_plugin_summary(
496        &result.manifest,
497        &format!("archive: {}", archive_path.display()),
498    );
499    Ok(())
500}
501
502// ── Install from remote catalog ─────────────────────────────
503
504async fn install_from_catalog(name: &str) -> Result<(), Box<dyn std::error::Error>> {
505    use crate::cli::update;
506    use roboticus_plugin_sdk::archive;
507
508    let (_dim, bold, _accent, green, _yellow, red, cyan, reset, _mono) = colors();
509    let (ok, action, _warn, _detail, err_icon) = icons();
510
511    println!("\n  {action} Searching catalog for {bold}{name}{reset}...");
512
513    // Fetch registry manifest
514    let config_path = roboticus_core::config::resolve_config_path(None);
515    let config_str = config_path
516        .as_ref()
517        .map(|p| p.to_string_lossy().to_string())
518        .unwrap_or_default();
519    let registry_url = update::resolve_registry_url(None, &config_str);
520    let client = super::http_client()?;
521    let manifest = update::fetch_manifest(&client, &registry_url).await?;
522
523    let catalog = manifest
524        .packs
525        .plugins
526        .as_ref()
527        .ok_or("No plugin catalog available in the registry")?;
528
529    let entry = catalog
530        .find(name)
531        .ok_or_else(|| format!("Plugin '{name}' not found in catalog"))?;
532
533    println!(
534        "  {ok} Found: {bold}{}{reset} v{green}{}{reset}",
535        entry.name, entry.version
536    );
537    println!("  {}", truncate_str(&entry.description, 72));
538    println!("  Author: {}", entry.author);
539    println!("  Tier:   {}", entry.tier);
540
541    // Check not already installed
542    if check_not_installed(&entry.name).is_err() {
543        return Err(format!("plugin '{}' already installed", entry.name).into());
544    }
545
546    // Prompt before download
547    if !prompt_yes_no(&format!(
548        "Download and install {} v{}?",
549        entry.name, entry.version
550    )) {
551        println!("  Cancelled.");
552        return Ok(());
553    }
554
555    // Download archive
556    let base_url = update::registry_base_url(&registry_url);
557    let archive_url = format!("{base_url}/{}", entry.path);
558
559    let client = super::http_client()?;
560    let resp = super::spin_while(
561        &format!("Downloading {}", entry.path),
562        client.get(&archive_url).send(),
563    )
564    .await?;
565
566    if !resp.status().is_success() {
567        return Err(format!("download failed: HTTP {}", resp.status()).into());
568    }
569
570    let bytes = super::spin_while("Receiving bytes", resp.bytes()).await?;
571    println!("  {ok} Downloaded {} bytes", bytes.len());
572
573    // Verify checksum against catalog
574    println!("  {action} Verifying SHA-256...");
575    archive::verify_bytes_checksum(&bytes, &entry.sha256)
576        .map_err(|e| format!("Checksum verification failed: {e}"))?;
577    println!(
578        "  {ok} Checksum verified: {cyan}{}{reset}",
579        &entry.sha256[..16]
580    );
581
582    // Unpack to staging
583    let staging_dir = roboticus_core::home_dir()
584        .join(".roboticus")
585        .join("staging");
586    std::fs::create_dir_all(&staging_dir)?;
587
588    let result = archive::unpack_bytes(&bytes, &staging_dir, entry.sha256.clone())
589        .map_err(|e| format!("Failed to unpack archive: {e}"))?;
590
591    // Identity check: manifest name must match catalog entry name
592    if result.manifest.name != entry.name {
593        let _ = std::fs::remove_dir_all(&result.dest_dir);
594        return Err(format!(
595            "identity mismatch: catalog says '{}' but archive contains '{}'",
596            entry.name, result.manifest.name
597        )
598        .into());
599    }
600
601    // Re-check "already installed" against manifest name (authoritative identity)
602    if check_not_installed(&result.manifest.name).is_err() {
603        let _ = std::fs::remove_dir_all(&result.dest_dir);
604        return Err(format!("plugin '{}' already installed", result.manifest.name).into());
605    }
606
607    // Requirements check
608    if !check_requirements(&result.manifest) {
609        let _ = std::fs::remove_dir_all(&result.dest_dir);
610        return Err("missing required plugin dependencies".into());
611    }
612
613    // Move from staging to plugins dir
614    let dest = roboticus_core::home_dir()
615        .join(".roboticus")
616        .join("plugins")
617        .join(&result.manifest.name);
618    std::fs::create_dir_all(dest.parent().unwrap_or(&dest))?;
619    std::fs::rename(&result.dest_dir, &dest).or_else(|_| {
620        if let Err(e) = copy_dir_recursive(&result.dest_dir, &dest) {
621            let _ = std::fs::remove_dir_all(&dest);
622            return Err(e);
623        }
624        std::fs::remove_dir_all(&result.dest_dir)
625    })?;
626
627    if let Err(e) = deploy_companion_skills(&result.manifest, &dest) {
628        // Roll back partial install on post-move failure.
629        if let Err(clean_err) = std::fs::remove_dir_all(&dest) {
630            eprintln!(
631                "  {err_icon} Companion skill deployment failed and rollback also failed: {clean_err}"
632            );
633        }
634        return Err(e);
635    }
636    print_plugin_summary(&result.manifest, &format!("catalog: {name}"));
637    Ok(())
638}
639
640// ── Uninstall ───────────────────────────────────────────────
641
642pub fn cmd_plugin_uninstall(name: &str) -> Result<(), Box<dyn std::error::Error>> {
643    let (_dim, _bold, _accent, _green, _yellow, _red, _cyan, _reset, _mono) = colors();
644    let (ok, _action, warn, _detail, _err_icon) = icons();
645    let roboticus_dir = roboticus_core::home_dir().join(".roboticus");
646    let plugin_dir = roboticus_dir.join("plugins").join(name);
647
648    if !plugin_dir.exists() {
649        eprintln!("  Plugin not found: {name}");
650        return Err(format!("plugin not found: {name}").into());
651    }
652
653    // Remove companion skills if the manifest declares them
654    let manifest_path = plugin_dir.join("plugin.toml");
655    if manifest_path.exists()
656        && let Ok(manifest) = PluginManifest::from_file(&manifest_path)
657    {
658        let skills_dir = roboticus_dir.join("skills");
659        for skill_rel in &manifest.companion_skills {
660            let installed_name = companion_skill_install_name(name, skill_rel);
661            let skill_path = skills_dir.join(&installed_name);
662            if skill_path.exists() {
663                if let Err(e) = std::fs::remove_file(&skill_path) {
664                    eprintln!("  {warn} Could not remove companion skill {installed_name}: {e}",);
665                } else {
666                    println!("  {ok} Removed companion skill: {installed_name}");
667                }
668            } else {
669                // Backward compat: legacy flat naming — only remove if content matches
670                let legacy_name = std::path::Path::new(skill_rel)
671                    .file_name()
672                    .unwrap_or_default()
673                    .to_string_lossy()
674                    .to_string();
675                let old_prefixed_name = format!("{name}--{legacy_name}");
676                let legacy_path = skills_dir.join(&legacy_name);
677                let old_prefixed_path = skills_dir.join(&old_prefixed_name);
678                let source_path = plugin_dir.join(skill_rel);
679                let same_content = std::fs::read(&legacy_path)
680                    .ok()
681                    .zip(std::fs::read(&source_path).ok())
682                    .map(|(a, b)| a == b)
683                    .unwrap_or(false);
684                if same_content {
685                    if let Err(e) = std::fs::remove_file(&legacy_path) {
686                        eprintln!(
687                            "  {warn} Could not remove legacy companion skill {legacy_name}: {e}",
688                        );
689                    } else {
690                        println!("  {ok} Removed legacy companion skill: {legacy_name}");
691                    }
692                }
693                let old_prefixed_same_content = std::fs::read(&old_prefixed_path)
694                    .ok()
695                    .zip(std::fs::read(&source_path).ok())
696                    .map(|(a, b)| a == b)
697                    .unwrap_or(false);
698                if old_prefixed_same_content {
699                    if let Err(e) = std::fs::remove_file(&old_prefixed_path) {
700                        eprintln!(
701                            "  {warn} Could not remove legacy companion skill {old_prefixed_name}: {e}",
702                        );
703                    } else {
704                        println!("  {ok} Removed legacy companion skill: {old_prefixed_name}");
705                    }
706                }
707            }
708        }
709    }
710
711    // Remove companion skills if the manifest declares them
712    let manifest_path = plugin_dir.join("plugin.toml");
713    if manifest_path.exists()
714        && let Ok(manifest) = PluginManifest::from_file(&manifest_path)
715    {
716        let skills_dir = roboticus_dir.join("skills");
717        for skill_rel in &manifest.companion_skills {
718            let installed_name = companion_skill_install_name(name, skill_rel);
719            let skill_path = skills_dir.join(&installed_name);
720            if skill_path.exists() {
721                if let Err(e) = std::fs::remove_file(&skill_path) {
722                    eprintln!("  {warn} Could not remove companion skill {installed_name}: {e}",);
723                } else {
724                    println!("  {ok} Removed companion skill: {installed_name}");
725                }
726            } else {
727                // Backward compat: legacy flat naming — only remove if content matches
728                let legacy_name = std::path::Path::new(skill_rel)
729                    .file_name()
730                    .unwrap_or_default()
731                    .to_string_lossy()
732                    .to_string();
733                let old_prefixed_name = format!("{name}--{legacy_name}");
734                let legacy_path = skills_dir.join(&legacy_name);
735                let old_prefixed_path = skills_dir.join(&old_prefixed_name);
736                let source_path = plugin_dir.join(skill_rel);
737                let same_content = std::fs::read(&legacy_path)
738                    .ok()
739                    .zip(std::fs::read(&source_path).ok())
740                    .map(|(a, b)| a == b)
741                    .unwrap_or(false);
742                if same_content {
743                    if let Err(e) = std::fs::remove_file(&legacy_path) {
744                        eprintln!(
745                            "  {warn} Could not remove legacy companion skill {legacy_name}: {e}",
746                        );
747                    } else {
748                        println!("  {ok} Removed legacy companion skill: {legacy_name}");
749                    }
750                }
751                let old_prefixed_same_content = std::fs::read(&old_prefixed_path)
752                    .ok()
753                    .zip(std::fs::read(&source_path).ok())
754                    .map(|(a, b)| a == b)
755                    .unwrap_or(false);
756                if old_prefixed_same_content {
757                    if let Err(e) = std::fs::remove_file(&old_prefixed_path) {
758                        eprintln!(
759                            "  {warn} Could not remove legacy companion skill {old_prefixed_name}: {e}",
760                        );
761                    } else {
762                        println!("  {ok} Removed legacy companion skill: {old_prefixed_name}");
763                    }
764                }
765            }
766        }
767    }
768
769    std::fs::remove_dir_all(&plugin_dir)?;
770    println!("  {ok} Uninstalled plugin: {name}");
771    println!("  Restart the server to apply.\n");
772    Ok(())
773}
774
775// ── Toggle enable/disable ───────────────────────────────────
776
777pub async fn cmd_plugin_toggle(
778    base_url: &str,
779    name: &str,
780    enable: bool,
781) -> Result<(), Box<dyn std::error::Error>> {
782    let (ok, _action, _warn, _detail, _err_icon) = icons();
783    let action = if enable { "enable" } else { "disable" };
784    let client = super::http_client()?;
785    let resp = client
786        .put(format!("{base_url}/api/plugins/{name}/toggle"))
787        .json(&serde_json::json!({ "enabled": enable }))
788        .send()
789        .await?;
790
791    if resp.status().is_success() {
792        println!("  {ok} Plugin {name} {action}d");
793    } else {
794        eprintln!("  Failed to {action} plugin {name}: {}", resp.status());
795        return Err(format!("failed to {action} plugin {name}: HTTP {}", resp.status()).into());
796    }
797    Ok(())
798}
799
800// ── Search remote catalog ───────────────────────────────────
801
802pub async fn cmd_plugin_search(query: &str) -> Result<(), Box<dyn std::error::Error>> {
803    use crate::cli::update;
804
805    let (_dim, bold, _accent, green, yellow, _red, cyan, reset, _mono) = colors();
806    let (ok, action, _warn, _detail, _err_icon) = icons();
807
808    println!("\n  {action} Searching plugin catalog...\n");
809
810    let config_path = roboticus_core::config::resolve_config_path(None);
811    let config_str = config_path
812        .as_ref()
813        .map(|p| p.to_string_lossy().to_string())
814        .unwrap_or_default();
815    let registry_url = update::resolve_registry_url(None, &config_str);
816    let client = super::http_client()?;
817    let manifest = update::fetch_manifest(&client, &registry_url).await?;
818
819    let catalog = manifest
820        .packs
821        .plugins
822        .as_ref()
823        .ok_or("No plugin catalog available in the registry")?;
824
825    let results = catalog.search(query);
826
827    if results.is_empty() {
828        println!("  No plugins found matching \"{query}\".\n");
829        return Ok(());
830    }
831
832    println!(
833        "  {:<20} {:<10} {:<12} {}",
834        "Name", "Version", "Tier", "Description"
835    );
836    println!("  {}", "─".repeat(70));
837    for entry in &results {
838        let tier_display = match entry.tier.as_str() {
839            "official" => format!("{green}official{reset}"),
840            "community" => format!("{yellow}community{reset}"),
841            _ => entry.tier.clone(),
842        };
843        println!(
844            "  {:<20} {:<10} {:<12} {}",
845            entry.name,
846            entry.version,
847            tier_display,
848            truncate_str(&entry.description, 40)
849        );
850    }
851    println!(
852        "\n  {ok} {} plugin(s) found. Install with: {cyan}roboticus plugins install <name>{reset}\n",
853        results.len()
854    );
855    Ok(())
856}
857
858// ── Pack a plugin directory into .ic.zip ────────────────────
859
860pub fn cmd_plugin_pack(dir: &str, output: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
861    use roboticus_plugin_sdk::archive;
862
863    let (_dim, bold, _accent, green, _yellow, _red, cyan, reset, _mono) = colors();
864    let (ok, action, _warn, _detail, err_icon) = icons();
865
866    let source_path = std::path::Path::new(dir);
867    if !source_path.exists() {
868        return Err(format!("source directory not found: {dir}").into());
869    }
870
871    let manifest_path = source_path.join("plugin.toml");
872    if !manifest_path.exists() {
873        return Err(format!("no plugin.toml found in {dir}").into());
874    }
875
876    // Vet the plugin before packing
877    let manifest = PluginManifest::from_file(&manifest_path)
878        .map_err(|e| format!("Invalid plugin.toml: {e}"))?;
879
880    println!(
881        "\n  {action} Vetting {bold}{}{reset} v{green}{}{reset}...\n",
882        manifest.name, manifest.version
883    );
884
885    let report = manifest.vet(source_path);
886    let has_problems = !report.errors.is_empty() || !report.warnings.is_empty();
887    if has_problems {
888        for err in &report.errors {
889            eprintln!("    {err_icon} {err}");
890        }
891        let (_ok2, _action2, warn2, _detail2, _err2) = icons();
892        for w in &report.warnings {
893            eprintln!("    {warn2} {w}");
894        }
895        if !report.errors.is_empty() {
896            eprintln!(
897                "\n  {err_icon} Plugin failed vetting. Fix the errors above before packing.\n"
898            );
899            return Err("plugin vetting failed".into());
900        }
901        println!();
902    }
903
904    let output_dir = output
905        .map(std::path::PathBuf::from)
906        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
907
908    println!("  {action} Packing archive...");
909
910    let result = archive::pack(source_path, &output_dir)
911        .map_err(|e| format!("Failed to pack archive: {e}"))?;
912
913    println!(
914        "  {ok} Created: {bold}{}{reset}",
915        result.archive_path.display()
916    );
917    println!("  SHA-256:  {cyan}{}{reset}", result.sha256);
918    println!("  Files:    {}", result.file_count);
919    println!(
920        "  Size:     {} bytes (uncompressed)\n",
921        result.uncompressed_bytes
922    );
923    Ok(())
924}
925
926#[cfg(test)]
927mod tests {
928    use super::companion_skill_install_name;
929
930    #[test]
931    fn companion_skill_install_name_distinguishes_paths_with_same_basename() {
932        let a = companion_skill_install_name("plugin-a", "skills/core/readme.md");
933        let b = companion_skill_install_name("plugin-a", "skills/extra/readme.md");
934        assert_ne!(a, b);
935    }
936}