1use super::*;
2
3use roboticus_plugin_sdk::manifest::PluginManifest;
4use sha2::{Digest, Sha256};
5
6enum InstallSource {
9 Directory(std::path::PathBuf),
11 Archive(std::path::PathBuf),
13 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 InstallSource::Archive(path.to_path_buf())
25 } else if has_path_sep || path.exists() {
26 InstallSource::Directory(path.to_path_buf())
28 } else {
29 InstallSource::Catalog(source.to_string())
31 }
32}
33
34pub 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
84pub 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
169fn 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 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 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
351pub 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
361fn 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 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 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 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
419fn 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 let staging_dir = roboticus_core::home_dir().join(".roboticus").join("staging");
435 std::fs::create_dir_all(&staging_dir)?;
436
437 let result = archive::unpack(archive_path, &staging_dir)
438 .map_err(|e| format!("Failed to unpack archive: {e}"))?;
439
440 println!(
441 " {ok} Unpacked {bold}{}{reset} v{green}{}{reset} ({} files)",
442 result.manifest.name, result.manifest.version, result.file_count
443 );
444 println!(" {ok} SHA-256: {cyan}{}{reset}", &result.sha256[..16]);
445
446 if !check_requirements(&result.manifest) {
448 let _ = std::fs::remove_dir_all(&result.dest_dir);
450 return Err("missing required plugin dependencies".into());
451 }
452
453 let dest = match check_not_installed(&result.manifest.name) {
455 Ok(d) => d,
456 Err(()) => {
457 let _ = std::fs::remove_dir_all(&result.dest_dir);
459 return Err(format!("plugin '{}' already installed", result.manifest.name).into());
460 }
461 };
462
463 if !prompt_yes_no(&format!(
465 "Install {} v{}?",
466 result.manifest.name, result.manifest.version
467 )) {
468 println!(" Cancelled.");
469 let _ = std::fs::remove_dir_all(&result.dest_dir);
470 return Ok(());
471 }
472
473 std::fs::create_dir_all(dest.parent().unwrap_or(&dest))?;
475 std::fs::rename(&result.dest_dir, &dest).or_else(|_| {
476 if let Err(e) = copy_dir_recursive(&result.dest_dir, &dest) {
478 let _ = std::fs::remove_dir_all(&dest);
479 return Err(e);
480 }
481 std::fs::remove_dir_all(&result.dest_dir)
482 })?;
483
484 if let Err(e) = deploy_companion_skills(&result.manifest, &dest) {
485 if let Err(clean_err) = std::fs::remove_dir_all(&dest) {
487 eprintln!(
488 " {err_icon} Companion skill deployment failed and rollback also failed: {clean_err}"
489 );
490 }
491 return Err(e);
492 }
493 print_plugin_summary(
494 &result.manifest,
495 &format!("archive: {}", archive_path.display()),
496 );
497 Ok(())
498}
499
500async fn install_from_catalog(name: &str) -> Result<(), Box<dyn std::error::Error>> {
503 use crate::cli::update;
504 use roboticus_plugin_sdk::archive;
505
506 let (_dim, bold, _accent, green, _yellow, red, cyan, reset, _mono) = colors();
507 let (ok, action, _warn, _detail, err_icon) = icons();
508
509 println!("\n {action} Searching catalog for {bold}{name}{reset}...");
510
511 let config_path = roboticus_core::config::resolve_config_path(None);
513 let config_str = config_path
514 .as_ref()
515 .map(|p| p.to_string_lossy().to_string())
516 .unwrap_or_default();
517 let registry_url = update::resolve_registry_url(None, &config_str);
518 let client = super::http_client()?;
519 let manifest = update::fetch_manifest(&client, ®istry_url).await?;
520
521 let catalog = manifest
522 .packs
523 .plugins
524 .as_ref()
525 .ok_or("No plugin catalog available in the registry")?;
526
527 let entry = catalog
528 .find(name)
529 .ok_or_else(|| format!("Plugin '{name}' not found in catalog"))?;
530
531 println!(
532 " {ok} Found: {bold}{}{reset} v{green}{}{reset}",
533 entry.name, entry.version
534 );
535 println!(" {}", truncate_str(&entry.description, 72));
536 println!(" Author: {}", entry.author);
537 println!(" Tier: {}", entry.tier);
538
539 if check_not_installed(&entry.name).is_err() {
541 return Err(format!("plugin '{}' already installed", entry.name).into());
542 }
543
544 if !prompt_yes_no(&format!(
546 "Download and install {} v{}?",
547 entry.name, entry.version
548 )) {
549 println!(" Cancelled.");
550 return Ok(());
551 }
552
553 let base_url = update::registry_base_url(®istry_url);
555 let archive_url = format!("{base_url}/{}", entry.path);
556
557 println!(" {action} Downloading from {cyan}{archive_url}{reset}...");
558
559 let client = super::http_client()?;
560 let resp = client.get(&archive_url).send().await?;
561
562 if !resp.status().is_success() {
563 return Err(format!("download failed: HTTP {}", resp.status()).into());
564 }
565
566 let bytes = resp.bytes().await?;
567 println!(" {ok} Downloaded {} bytes", bytes.len());
568
569 println!(" {action} Verifying SHA-256...");
571 archive::verify_bytes_checksum(&bytes, &entry.sha256)
572 .map_err(|e| format!("Checksum verification failed: {e}"))?;
573 println!(
574 " {ok} Checksum verified: {cyan}{}{reset}",
575 &entry.sha256[..16]
576 );
577
578 let staging_dir = roboticus_core::home_dir().join(".roboticus").join("staging");
580 std::fs::create_dir_all(&staging_dir)?;
581
582 let result = archive::unpack_bytes(&bytes, &staging_dir, entry.sha256.clone())
583 .map_err(|e| format!("Failed to unpack archive: {e}"))?;
584
585 if result.manifest.name != entry.name {
587 let _ = std::fs::remove_dir_all(&result.dest_dir);
588 return Err(format!(
589 "identity mismatch: catalog says '{}' but archive contains '{}'",
590 entry.name, result.manifest.name
591 )
592 .into());
593 }
594
595 if check_not_installed(&result.manifest.name).is_err() {
597 let _ = std::fs::remove_dir_all(&result.dest_dir);
598 return Err(format!("plugin '{}' already installed", result.manifest.name).into());
599 }
600
601 if !check_requirements(&result.manifest) {
603 let _ = std::fs::remove_dir_all(&result.dest_dir);
604 return Err("missing required plugin dependencies".into());
605 }
606
607 let dest = roboticus_core::home_dir()
609 .join(".roboticus")
610 .join("plugins")
611 .join(&result.manifest.name);
612 std::fs::create_dir_all(dest.parent().unwrap_or(&dest))?;
613 std::fs::rename(&result.dest_dir, &dest).or_else(|_| {
614 if let Err(e) = copy_dir_recursive(&result.dest_dir, &dest) {
615 let _ = std::fs::remove_dir_all(&dest);
616 return Err(e);
617 }
618 std::fs::remove_dir_all(&result.dest_dir)
619 })?;
620
621 if let Err(e) = deploy_companion_skills(&result.manifest, &dest) {
622 if let Err(clean_err) = std::fs::remove_dir_all(&dest) {
624 eprintln!(
625 " {err_icon} Companion skill deployment failed and rollback also failed: {clean_err}"
626 );
627 }
628 return Err(e);
629 }
630 print_plugin_summary(&result.manifest, &format!("catalog: {name}"));
631 Ok(())
632}
633
634pub fn cmd_plugin_uninstall(name: &str) -> Result<(), Box<dyn std::error::Error>> {
637 let (_dim, _bold, _accent, _green, _yellow, _red, _cyan, _reset, _mono) = colors();
638 let (ok, _action, warn, _detail, _err_icon) = icons();
639 let roboticus_dir = roboticus_core::home_dir().join(".roboticus");
640 let plugin_dir = roboticus_dir.join("plugins").join(name);
641
642 if !plugin_dir.exists() {
643 eprintln!(" Plugin not found: {name}");
644 return Err(format!("plugin not found: {name}").into());
645 }
646
647 let manifest_path = plugin_dir.join("plugin.toml");
649 if manifest_path.exists()
650 && let Ok(manifest) = PluginManifest::from_file(&manifest_path)
651 {
652 let skills_dir = roboticus_dir.join("skills");
653 for skill_rel in &manifest.companion_skills {
654 let installed_name = companion_skill_install_name(name, skill_rel);
655 let skill_path = skills_dir.join(&installed_name);
656 if skill_path.exists() {
657 if let Err(e) = std::fs::remove_file(&skill_path) {
658 eprintln!(" {warn} Could not remove companion skill {installed_name}: {e}",);
659 } else {
660 println!(" {ok} Removed companion skill: {installed_name}");
661 }
662 } else {
663 let legacy_name = std::path::Path::new(skill_rel)
665 .file_name()
666 .unwrap_or_default()
667 .to_string_lossy()
668 .to_string();
669 let old_prefixed_name = format!("{name}--{legacy_name}");
670 let legacy_path = skills_dir.join(&legacy_name);
671 let old_prefixed_path = skills_dir.join(&old_prefixed_name);
672 let source_path = plugin_dir.join(skill_rel);
673 let same_content = std::fs::read(&legacy_path)
674 .ok()
675 .zip(std::fs::read(&source_path).ok())
676 .map(|(a, b)| a == b)
677 .unwrap_or(false);
678 if same_content {
679 if let Err(e) = std::fs::remove_file(&legacy_path) {
680 eprintln!(
681 " {warn} Could not remove legacy companion skill {legacy_name}: {e}",
682 );
683 } else {
684 println!(" {ok} Removed legacy companion skill: {legacy_name}");
685 }
686 }
687 let old_prefixed_same_content = std::fs::read(&old_prefixed_path)
688 .ok()
689 .zip(std::fs::read(&source_path).ok())
690 .map(|(a, b)| a == b)
691 .unwrap_or(false);
692 if old_prefixed_same_content {
693 if let Err(e) = std::fs::remove_file(&old_prefixed_path) {
694 eprintln!(
695 " {warn} Could not remove legacy companion skill {old_prefixed_name}: {e}",
696 );
697 } else {
698 println!(" {ok} Removed legacy companion skill: {old_prefixed_name}");
699 }
700 }
701 }
702 }
703 }
704
705 let manifest_path = plugin_dir.join("plugin.toml");
707 if manifest_path.exists()
708 && let Ok(manifest) = PluginManifest::from_file(&manifest_path)
709 {
710 let skills_dir = roboticus_dir.join("skills");
711 for skill_rel in &manifest.companion_skills {
712 let installed_name = companion_skill_install_name(name, skill_rel);
713 let skill_path = skills_dir.join(&installed_name);
714 if skill_path.exists() {
715 if let Err(e) = std::fs::remove_file(&skill_path) {
716 eprintln!(" {warn} Could not remove companion skill {installed_name}: {e}",);
717 } else {
718 println!(" {ok} Removed companion skill: {installed_name}");
719 }
720 } else {
721 let legacy_name = std::path::Path::new(skill_rel)
723 .file_name()
724 .unwrap_or_default()
725 .to_string_lossy()
726 .to_string();
727 let old_prefixed_name = format!("{name}--{legacy_name}");
728 let legacy_path = skills_dir.join(&legacy_name);
729 let old_prefixed_path = skills_dir.join(&old_prefixed_name);
730 let source_path = plugin_dir.join(skill_rel);
731 let same_content = std::fs::read(&legacy_path)
732 .ok()
733 .zip(std::fs::read(&source_path).ok())
734 .map(|(a, b)| a == b)
735 .unwrap_or(false);
736 if same_content {
737 if let Err(e) = std::fs::remove_file(&legacy_path) {
738 eprintln!(
739 " {warn} Could not remove legacy companion skill {legacy_name}: {e}",
740 );
741 } else {
742 println!(" {ok} Removed legacy companion skill: {legacy_name}");
743 }
744 }
745 let old_prefixed_same_content = std::fs::read(&old_prefixed_path)
746 .ok()
747 .zip(std::fs::read(&source_path).ok())
748 .map(|(a, b)| a == b)
749 .unwrap_or(false);
750 if old_prefixed_same_content {
751 if let Err(e) = std::fs::remove_file(&old_prefixed_path) {
752 eprintln!(
753 " {warn} Could not remove legacy companion skill {old_prefixed_name}: {e}",
754 );
755 } else {
756 println!(" {ok} Removed legacy companion skill: {old_prefixed_name}");
757 }
758 }
759 }
760 }
761 }
762
763 std::fs::remove_dir_all(&plugin_dir)?;
764 println!(" {ok} Uninstalled plugin: {name}");
765 println!(" Restart the server to apply.\n");
766 Ok(())
767}
768
769pub async fn cmd_plugin_toggle(
772 base_url: &str,
773 name: &str,
774 enable: bool,
775) -> Result<(), Box<dyn std::error::Error>> {
776 let (ok, _action, _warn, _detail, _err_icon) = icons();
777 let action = if enable { "enable" } else { "disable" };
778 let client = super::http_client()?;
779 let resp = client
780 .put(format!("{base_url}/api/plugins/{name}/toggle"))
781 .json(&serde_json::json!({ "enabled": enable }))
782 .send()
783 .await?;
784
785 if resp.status().is_success() {
786 println!(" {ok} Plugin {name} {action}d");
787 } else {
788 eprintln!(" Failed to {action} plugin {name}: {}", resp.status());
789 return Err(format!("failed to {action} plugin {name}: HTTP {}", resp.status()).into());
790 }
791 Ok(())
792}
793
794pub async fn cmd_plugin_search(query: &str) -> Result<(), Box<dyn std::error::Error>> {
797 use crate::cli::update;
798
799 let (_dim, bold, _accent, green, yellow, _red, cyan, reset, _mono) = colors();
800 let (ok, action, _warn, _detail, _err_icon) = icons();
801
802 println!("\n {action} Searching plugin catalog...\n");
803
804 let config_path = roboticus_core::config::resolve_config_path(None);
805 let config_str = config_path
806 .as_ref()
807 .map(|p| p.to_string_lossy().to_string())
808 .unwrap_or_default();
809 let registry_url = update::resolve_registry_url(None, &config_str);
810 let client = super::http_client()?;
811 let manifest = update::fetch_manifest(&client, ®istry_url).await?;
812
813 let catalog = manifest
814 .packs
815 .plugins
816 .as_ref()
817 .ok_or("No plugin catalog available in the registry")?;
818
819 let results = catalog.search(query);
820
821 if results.is_empty() {
822 println!(" No plugins found matching \"{query}\".\n");
823 return Ok(());
824 }
825
826 println!(
827 " {:<20} {:<10} {:<12} {}",
828 "Name", "Version", "Tier", "Description"
829 );
830 println!(" {}", "─".repeat(70));
831 for entry in &results {
832 let tier_display = match entry.tier.as_str() {
833 "official" => format!("{green}official{reset}"),
834 "community" => format!("{yellow}community{reset}"),
835 _ => entry.tier.clone(),
836 };
837 println!(
838 " {:<20} {:<10} {:<12} {}",
839 entry.name,
840 entry.version,
841 tier_display,
842 truncate_str(&entry.description, 40)
843 );
844 }
845 println!(
846 "\n {ok} {} plugin(s) found. Install with: {cyan}roboticus plugins install <name>{reset}\n",
847 results.len()
848 );
849 Ok(())
850}
851
852pub fn cmd_plugin_pack(dir: &str, output: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
855 use roboticus_plugin_sdk::archive;
856
857 let (_dim, bold, _accent, green, _yellow, _red, cyan, reset, _mono) = colors();
858 let (ok, action, _warn, _detail, err_icon) = icons();
859
860 let source_path = std::path::Path::new(dir);
861 if !source_path.exists() {
862 return Err(format!("source directory not found: {dir}").into());
863 }
864
865 let manifest_path = source_path.join("plugin.toml");
866 if !manifest_path.exists() {
867 return Err(format!("no plugin.toml found in {dir}").into());
868 }
869
870 let manifest = PluginManifest::from_file(&manifest_path)
872 .map_err(|e| format!("Invalid plugin.toml: {e}"))?;
873
874 println!(
875 "\n {action} Vetting {bold}{}{reset} v{green}{}{reset}...\n",
876 manifest.name, manifest.version
877 );
878
879 let report = manifest.vet(source_path);
880 let has_problems = !report.errors.is_empty() || !report.warnings.is_empty();
881 if has_problems {
882 for err in &report.errors {
883 eprintln!(" {err_icon} {err}");
884 }
885 let (_ok2, _action2, warn2, _detail2, _err2) = icons();
886 for w in &report.warnings {
887 eprintln!(" {warn2} {w}");
888 }
889 if !report.errors.is_empty() {
890 eprintln!(
891 "\n {err_icon} Plugin failed vetting. Fix the errors above before packing.\n"
892 );
893 return Err("plugin vetting failed".into());
894 }
895 println!();
896 }
897
898 let output_dir = output
899 .map(std::path::PathBuf::from)
900 .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
901
902 println!(" {action} Packing archive...");
903
904 let result = archive::pack(source_path, &output_dir)
905 .map_err(|e| format!("Failed to pack archive: {e}"))?;
906
907 println!(
908 " {ok} Created: {bold}{}{reset}",
909 result.archive_path.display()
910 );
911 println!(" SHA-256: {cyan}{}{reset}", result.sha256);
912 println!(" Files: {}", result.file_count);
913 println!(
914 " Size: {} bytes (uncompressed)\n",
915 result.uncompressed_bytes
916 );
917 Ok(())
918}
919
920#[cfg(test)]
921mod tests {
922 use super::companion_skill_install_name;
923
924 #[test]
925 fn companion_skill_install_name_distinguishes_paths_with_same_basename() {
926 let a = companion_skill_install_name("plugin-a", "skills/core/readme.md");
927 let b = companion_skill_install_name("plugin-a", "skills/extra/readme.md");
928 assert_ne!(a, b);
929 }
930}