1#[cfg(windows)]
9use agentmux_common::win32::NoWindow;
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15
16const CATALOG_JSON: &str = include_str!("../config/tool-catalog.json");
20
21#[derive(Debug, Clone, Deserialize)]
24pub struct ToolCatalog {
25 pub tools: Vec<ToolSpec>,
26}
27
28#[derive(Debug, Clone, Deserialize)]
29pub struct ToolSpec {
30 pub id: String,
31 pub display: String,
32 pub description: String,
33 pub tier: u8,
34 pub version: String,
35 pub check_cmd: String,
36 #[serde(default)]
39 pub version_arg: Option<String>,
40 pub platforms: HashMap<String, PlatformSpec>,
41}
42
43#[derive(Debug, Clone, Deserialize)]
44pub struct PlatformSpec {
45 pub url: String,
46 pub sha256: String,
47 pub extract: String,
49 pub bin: String,
51 pub bin_in_archive: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
58#[ts(export, export_to = "../../../frontend/types/rpc/")]
59#[serde(rename_all = "snake_case")]
60pub enum ToolStatus {
61 InstalledSystem,
62 InstalledBundled,
63 InstalledManaged,
64 Missing,
65 Unavailable,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
69#[ts(export, export_to = "../../../frontend/types/rpc/")]
70pub struct ToolStatusEntry {
71 pub id: String,
72 pub display: String,
73 pub description: String,
74 pub tier: u8,
75 pub status: ToolStatus,
76 pub version: Option<String>,
77 pub path: Option<String>,
78}
79
80pub fn bundled_tools_dir() -> Option<PathBuf> {
88 let exe = std::env::current_exe().ok()?;
89 let exe_dir = exe.parent()?;
90
91 let exe_str = exe_dir.to_string_lossy();
93 if exe_str.contains("target/debug")
94 || exe_str.contains("target/release")
95 || exe_str.contains("target\\debug")
96 || exe_str.contains("target\\release")
97 {
98 return None;
99 }
100
101 let bundled = bundled_dir_in(exe_dir);
102 Some(crate::backend::packaged_tools::runnable(bundled))
105}
106
107fn bundled_dir_in(exe_dir: &Path) -> PathBuf {
111 let tools = exe_dir.join("tools").join("bin");
112 let wrapper = if cfg!(windows) { "agentmux-bashwrap.exe" } else { "agentmux-bashwrap" };
113 if !tools.exists() && exe_dir.join(wrapper).is_file() {
114 return exe_dir.to_path_buf();
115 }
116 tools
117}
118
119pub fn user_tools_dir() -> Option<PathBuf> {
121 let home = dirs::home_dir()?;
122 Some(home.join(".agentmux").join("tools").join("bin"))
123}
124
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum UserToolsPrecedence {
131 BeforeExisting,
135 AfterExisting,
138}
139
140pub fn compose_tools_path(
144 existing: &str,
145 bundled: Option<&std::path::Path>,
146 user: Option<&std::path::Path>,
147 user_precedence: UserToolsPrecedence,
148) -> Option<String> {
149 if bundled.is_none() && user.is_none() {
150 return None;
151 }
152 let mut parts: Vec<String> = Vec::new();
153 if let Some(d) = bundled {
154 parts.push(d.to_string_lossy().into_owned());
155 }
156 if let (Some(d), UserToolsPrecedence::BeforeExisting) = (user, user_precedence) {
157 parts.push(d.to_string_lossy().into_owned());
158 }
159 if !existing.is_empty() {
160 parts.push(existing.to_string());
161 }
162 if let (Some(d), UserToolsPrecedence::AfterExisting) = (user, user_precedence) {
163 parts.push(d.to_string_lossy().into_owned());
164 }
165 let sep = if cfg!(windows) { ";" } else { ":" };
166 Some(parts.join(sep))
167}
168
169pub fn tools_path(existing: &str, user_precedence: UserToolsPrecedence) -> Option<String> {
171 let bundled = bundled_tools_dir().filter(|d| d.exists());
172 let user = user_tools_dir().filter(|d| d.exists());
173 compose_tools_path(existing, bundled.as_deref(), user.as_deref(), user_precedence)
174}
175
176pub fn prepend_agent_tools_path(env_vars: &mut HashMap<String, String>) {
181 let bundled = bundled_tools_dir().filter(|d| d.exists());
182 let user = user_tools_dir().filter(|d| d.exists());
183 prepend_tools_path_with(env_vars, bundled.as_deref(), user.as_deref());
184}
185
186fn prepend_tools_path_with(env_vars: &mut HashMap<String, String>, bundled: Option<&std::path::Path>, user: Option<&std::path::Path>) {
187 let existing = env_vars.get("PATH").cloned().or_else(|| std::env::var("PATH").ok()).unwrap_or_default();
188 if let Some(path) = compose_tools_path(&existing, bundled, user, UserToolsPrecedence::BeforeExisting) {
189 env_vars.insert("PATH".to_string(), path);
190 }
191}
192
193pub fn bashwrap_path() -> Option<PathBuf> {
199 use crate::backend::agent_tools::{find_in_tool_dirs, ToolDir};
200 find_in_tool_dirs("agentmux-bashwrap", &[ToolDir::Bundled, ToolDir::User])
201}
202
203fn downloads_dir() -> Option<PathBuf> {
205 let home = dirs::home_dir()?;
206 Some(home.join(".agentmux").join("tools").join("downloads"))
207}
208
209pub fn load_catalog() -> Result<ToolCatalog, String> {
213 serde_json::from_str(CATALOG_JSON).map_err(|e| format!("parse tool-catalog.json: {e}"))
214}
215
216pub fn current_platform() -> Result<&'static str, String> {
220 match (std::env::consts::OS, std::env::consts::ARCH) {
223 ("windows", "x86_64") => Ok("windows-x64"),
224 ("macos", "aarch64") => Ok("macos-arm64"),
225 ("macos", "x86_64") => Ok("macos-x64"),
226 ("linux", "x86_64") => Ok("linux-x64"),
227 ("linux", "aarch64") => Ok("linux-arm64"),
228 (os, arch) => Err(format!("unsupported platform: os={os} arch={arch}")),
229 }
230}
231
232fn probe_system_path(name: &str) -> bool {
236 #[cfg(windows)]
237 {
238 std::process::Command::new("where")
239 .arg(name)
240 .no_window()
241 .output()
242 .map(|o| o.status.success())
243 .unwrap_or(false)
244 }
245 #[cfg(not(windows))]
246 {
247 std::process::Command::new("which")
248 .arg(name)
249 .output()
250 .map(|o| o.status.success())
251 .unwrap_or(false)
252 }
253}
254
255fn system_path_of(name: &str) -> Option<String> {
257 #[cfg(windows)]
258 let output = {
259 std::process::Command::new("where")
260 .arg(name)
261 .no_window()
262 .output()
263 .ok()?
264 };
265 #[cfg(not(windows))]
266 let output = std::process::Command::new("which").arg(name).output().ok()?;
267
268 if output.status.success() {
269 let path = String::from_utf8_lossy(&output.stdout)
270 .lines()
271 .next()
272 .unwrap_or("")
273 .trim()
274 .to_string();
275 if !path.is_empty() {
276 return Some(path);
277 }
278 }
279 None
280}
281
282pub fn probe_version(cmd: &str, version_arg: &Option<String>) -> Option<String> {
286 probe_version_with_env(cmd, version_arg, &[])
287}
288
289pub(crate) fn probe_version_with_env(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)]) -> Option<String> {
292 probe_version_inner(cmd, version_arg, env, false)
293}
294
295pub(crate) fn probe_version_when_it_runs(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)]) -> Option<String> {
299 probe_version_inner(cmd, version_arg, env, true)
300}
301
302fn probe_version_inner(cmd: &str, version_arg: &Option<String>, env: &[(&str, &str)], must_succeed: bool) -> Option<String> {
303 let arg = version_arg.as_deref()?;
304 let mut command = std::process::Command::new(cmd);
305 crate::backend::pane_env::sanitize_external_std_command(&mut command);
309 command.arg(arg);
310 command.envs(env.iter().copied());
311 #[cfg(windows)]
312 {
313 command.no_window();
314 }
315 let output = command.output().ok()?;
316 if must_succeed && !output.status.success() {
317 return None;
318 }
319 let text = if !output.stdout.is_empty() {
321 String::from_utf8_lossy(&output.stdout).into_owned()
322 } else {
323 String::from_utf8_lossy(&output.stderr).into_owned()
324 };
325 for word in text.split_whitespace() {
327 let candidate = word.trim_matches(|c: char| !c.is_ascii_digit() && c != '.');
328 if candidate.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false)
329 && candidate.contains('.')
330 {
331 return Some(candidate.to_string());
332 }
333 }
334 None
335}
336
337pub fn get_tool_statuses() -> Vec<ToolStatusEntry> {
343 let catalog = match load_catalog() {
344 Ok(c) => c,
345 Err(e) => {
346 tracing::error!(error = %e, "failed to load tool catalog");
347 return Vec::new();
348 }
349 };
350
351 let platform = current_platform().ok();
352
353 catalog
354 .tools
355 .iter()
356 .map(|spec| {
357 let platform_key = match &platform {
359 Some(k) => *k,
360 None => {
361 return ToolStatusEntry {
362 id: spec.id.clone(),
363 display: spec.display.clone(),
364 description: spec.description.clone(),
365 tier: spec.tier,
366 status: ToolStatus::Unavailable,
367 version: None,
368 path: None,
369 };
370 }
371 };
372
373 if !spec.platforms.contains_key(platform_key) {
374 return ToolStatusEntry {
375 id: spec.id.clone(),
376 display: spec.display.clone(),
377 description: spec.description.clone(),
378 tier: spec.tier,
379 status: ToolStatus::Unavailable,
380 version: None,
381 path: None,
382 };
383 }
384
385 let bin_name = &spec.platforms[platform_key].bin;
386
387 if probe_system_path(&spec.check_cmd) {
389 let path = system_path_of(&spec.check_cmd);
390 let version = probe_version(&spec.check_cmd, &spec.version_arg);
392 return ToolStatusEntry {
393 id: spec.id.clone(),
394 display: spec.display.clone(),
395 description: spec.description.clone(),
396 tier: spec.tier,
397 status: ToolStatus::InstalledSystem,
398 version,
399 path,
400 };
401 }
402
403 if let Some(bundled) = bundled_tools_dir() {
405 let p = bundled.join(bin_name);
406 if p.exists() {
407 return ToolStatusEntry {
408 id: spec.id.clone(),
409 display: spec.display.clone(),
410 description: spec.description.clone(),
411 tier: spec.tier,
412 status: ToolStatus::InstalledBundled,
413 version: Some(spec.version.clone()),
414 path: Some(p.to_string_lossy().into_owned()),
415 };
416 }
417 }
418
419 if let Some(user_bin) = user_tools_dir() {
421 let p = user_bin.join(bin_name);
422 if p.exists() {
423 return ToolStatusEntry {
424 id: spec.id.clone(),
425 display: spec.display.clone(),
426 description: spec.description.clone(),
427 tier: spec.tier,
428 status: ToolStatus::InstalledManaged,
429 version: Some(spec.version.clone()),
430 path: Some(p.to_string_lossy().into_owned()),
431 };
432 }
433 }
434
435 ToolStatusEntry {
437 id: spec.id.clone(),
438 display: spec.display.clone(),
439 description: spec.description.clone(),
440 tier: spec.tier,
441 status: ToolStatus::Missing,
442 version: None,
443 path: None,
444 }
445 })
446 .collect()
447}
448
449pub async fn install_tool(id: &str, http_client: &reqwest::Client) -> Result<String, String> {
456 let catalog = load_catalog()?;
457 let spec = catalog
458 .tools
459 .iter()
460 .find(|t| t.id == id)
461 .ok_or_else(|| format!("tool '{id}' not found in catalog"))?;
462
463 let platform_key = current_platform()?;
464 let platform_spec = spec
465 .platforms
466 .get(platform_key)
467 .ok_or_else(|| format!("tool '{id}' has no entry for platform '{platform_key}'"))?;
468
469 let dl_dir = downloads_dir().ok_or("cannot determine downloads dir")?;
471 let bin_dir = user_tools_dir().ok_or("cannot determine user tools dir")?;
472 std::fs::create_dir_all(&dl_dir)
473 .map_err(|e| format!("create downloads dir: {e}"))?;
474 std::fs::create_dir_all(&bin_dir)
475 .map_err(|e| format!("create bin dir: {e}"))?;
476
477 let dl_path = dl_dir.join(format!("{id}-download"));
479 tracing::info!(tool = %id, url = %platform_spec.url, dest = %dl_path.display(), "downloading tool");
480
481 {
482 let bytes = http_client
483 .get(&platform_spec.url)
484 .send()
485 .await
486 .map_err(|e| format!("download '{id}': {e}"))?
487 .error_for_status()
488 .map_err(|e| format!("download '{id}' HTTP error: {e}"))?
489 .bytes()
490 .await
491 .map_err(|e| format!("read download body '{id}': {e}"))?;
492
493 std::fs::write(&dl_path, &bytes)
494 .map_err(|e| format!("write download file: {e}"))?;
495 }
496
497 {
499 let data = std::fs::read(&dl_path)
500 .map_err(|e| format!("read downloaded file for hash: {e}"))?;
501 let mut hasher = Sha256::new();
502 hasher.update(&data);
503 let digest = hex::encode(hasher.finalize());
504 if digest != platform_spec.sha256 {
505 let _ = std::fs::remove_file(&dl_path);
506 return Err(format!(
507 "SHA-256 mismatch for '{id}': expected={} got={digest}",
508 platform_spec.sha256,
509 ));
510 }
511 tracing::debug!(tool = %id, "SHA-256 verified");
512 }
513
514 let dest_path = bin_dir.join(&platform_spec.bin);
516
517 match platform_spec.extract.as_str() {
518 "none" => {
519 std::fs::copy(&dl_path, &dest_path)
520 .map_err(|e| format!("copy '{id}' to bin: {e}"))?;
521 }
522 "zip" => {
523 let archive_in = platform_spec
524 .bin_in_archive
525 .as_deref()
526 .ok_or_else(|| format!("tool '{id}': extract=zip but bin_in_archive is missing"))?;
527
528 let zip_data = std::fs::read(&dl_path)
529 .map_err(|e| format!("read zip file: {e}"))?;
530 let cursor = std::io::Cursor::new(zip_data);
531 let mut archive = zip::ZipArchive::new(cursor)
532 .map_err(|e| format!("open zip archive: {e}"))?;
533
534 let mut entry = archive
535 .by_name(archive_in)
536 .map_err(|e| format!("zip entry '{archive_in}': {e}"))?;
537
538 let mut out = std::fs::File::create(&dest_path)
539 .map_err(|e| format!("create dest file: {e}"))?;
540 std::io::copy(&mut entry, &mut out)
541 .map_err(|e| format!("extract zip entry: {e}"))?;
542 }
543 "tar_gz" => {
544 let archive_in = platform_spec
545 .bin_in_archive
546 .as_deref()
547 .ok_or_else(|| format!("tool '{id}': extract=tar_gz but bin_in_archive is missing"))?;
548
549 let gz_file = std::fs::File::open(&dl_path)
550 .map_err(|e| format!("open tar.gz: {e}"))?;
551 let gz_decoder = flate2::read::GzDecoder::new(gz_file);
552 let mut archive = tar::Archive::new(gz_decoder);
553
554 let mut found = false;
555 for entry in archive.entries().map_err(|e| format!("tar entries: {e}"))? {
556 let mut entry = entry.map_err(|e| format!("tar entry: {e}"))?;
557 let path = entry.path().map_err(|e| format!("tar entry path: {e}"))?;
558 if path.to_string_lossy() == archive_in {
559 entry
560 .unpack(&dest_path)
561 .map_err(|e| format!("unpack tar entry: {e}"))?;
562 found = true;
563 break;
564 }
565 }
566 if !found {
567 return Err(format!(
568 "tar archive does not contain expected entry '{archive_in}'"
569 ));
570 }
571 }
572 other => {
573 return Err(format!("unknown extract mode '{other}' for tool '{id}'"));
574 }
575 }
576
577 #[cfg(unix)]
579 {
580 use std::os::unix::fs::PermissionsExt as _;
581 let mut perms = std::fs::metadata(&dest_path)
582 .map_err(|e| format!("stat installed binary: {e}"))?
583 .permissions();
584 let mode = perms.mode();
585 perms.set_mode(mode | 0o111);
586 std::fs::set_permissions(&dest_path, perms)
587 .map_err(|e| format!("set executable bit: {e}"))?;
588 }
589
590 let _ = std::fs::remove_file(&dl_path);
592
593 let dest_str = dest_path.to_string_lossy().into_owned();
594 tracing::info!(tool = %id, path = %dest_str, "tool installed successfully");
595 Ok(dest_str)
596}
597
598#[cfg(test)]
599mod tool_status_wire_tests {
600 use super::*;
601 use serde_json::json;
602
603 #[test]
609 fn a_tool_entry_always_carries_version_and_path() {
610 let v = serde_json::to_value(ToolStatusEntry {
611 id: "rg".to_string(),
612 display: "ripgrep".to_string(),
613 description: "search".to_string(),
614 tier: 1,
615 status: ToolStatus::Missing,
616 version: None,
617 path: None,
618 })
619 .expect("serializable");
620 let obj = v.as_object().expect("object");
621 assert!(obj.contains_key("version") && obj.contains_key("path"));
622 assert_eq!(v["version"], json!(null));
623 assert_eq!(v["path"], json!(null));
624 }
625
626 #[test]
630 fn tool_status_serializes_to_the_expected_snake_case_tags() {
631 for (variant, tag) in [
632 (ToolStatus::InstalledSystem, "installed_system"),
633 (ToolStatus::InstalledBundled, "installed_bundled"),
634 (ToolStatus::InstalledManaged, "installed_managed"),
635 (ToolStatus::Missing, "missing"),
636 (ToolStatus::Unavailable, "unavailable"),
637 ] {
638 assert_eq!(serde_json::to_value(variant).unwrap(), json!(tag));
639 }
640 }
641}
642
643#[cfg(test)]
644mod tools_path_tests {
645 use super::{compose_tools_path, prepend_tools_path_with, UserToolsPrecedence};
646 use std::path::Path;
647
648 const SEP: &str = if cfg!(windows) { ";" } else { ":" };
649
650 fn join(parts: &[&str]) -> String {
651 parts.join(SEP)
652 }
653
654 #[test]
655 fn bundled_always_leads_and_user_follows_the_requested_precedence() {
656 let (b, u) = (Path::new("B"), Path::new("U"));
657 assert_eq!(
658 compose_tools_path("SYS", Some(b), Some(u), UserToolsPrecedence::BeforeExisting),
659 Some(join(&["B", "U", "SYS"]))
660 );
661 assert_eq!(
662 compose_tools_path("SYS", Some(b), Some(u), UserToolsPrecedence::AfterExisting),
663 Some(join(&["B", "SYS", "U"]))
664 );
665 }
666
667 #[test]
668 fn no_tool_dirs_leaves_path_untouched() {
669 assert_eq!(compose_tools_path("SYS", None, None, UserToolsPrecedence::BeforeExisting), None);
670 }
671
672 #[test]
673 fn an_agents_own_path_gets_the_tool_dirs_in_front_and_none_means_no_change() {
674 let sep = if cfg!(windows) { ";" } else { ":" };
675 let mut env = std::collections::HashMap::from([("PATH".to_string(), "SYS".to_string())]);
676 prepend_tools_path_with(&mut env, Some(Path::new("B")), Some(Path::new("U")));
677 assert_eq!(env["PATH"], format!("B{sep}U{sep}SYS"), "the user dir (build-slot shims) is ahead of the system PATH");
678 let mut untouched = std::collections::HashMap::from([("PATH".to_string(), "SYS".to_string())]);
679 prepend_tools_path_with(&mut untouched, None, None);
680 assert_eq!(untouched["PATH"], "SYS");
681 let mut none = std::collections::HashMap::new();
682 prepend_tools_path_with(&mut none, None, Some(Path::new("U")));
683 assert!(none["PATH"].starts_with(&format!("U{sep}")) || none["PATH"] == "U", "no PATH in the env: the process's own follows the user dir");
684 }
685
686 #[test]
687 fn an_empty_inherited_path_adds_no_empty_entry() {
688 assert_eq!(
690 compose_tools_path("", None, Some(Path::new("U")), UserToolsPrecedence::BeforeExisting),
691 Some("U".to_string())
692 );
693 assert_eq!(
694 compose_tools_path("", Some(Path::new("B")), None, UserToolsPrecedence::AfterExisting),
695 Some("B".to_string())
696 );
697 }
698}
699
700#[cfg(test)]
701mod bundled_dir_tests {
702 use super::bundled_dir_in;
703
704 fn wrapper() -> &'static str {
705 if cfg!(windows) { "agentmux-bashwrap.exe" } else { "agentmux-bashwrap" }
706 }
707
708 #[test]
709 fn the_desktop_keeps_its_tools_below_the_server() {
710 let dir = tempfile::tempdir().unwrap();
711 std::fs::create_dir_all(dir.path().join("tools").join("bin")).unwrap();
712 std::fs::write(dir.path().join(wrapper()), b"x").unwrap();
713 assert_eq!(bundled_dir_in(dir.path()), dir.path().join("tools").join("bin"), "tools/bin wins where it exists");
714 }
715
716 #[test]
717 fn the_server_package_keeps_its_helpers_beside_the_server() {
718 let dir = tempfile::tempdir().unwrap();
719 std::fs::write(dir.path().join(wrapper()), b"x").unwrap();
720 assert_eq!(bundled_dir_in(dir.path()), dir.path());
721 }
722
723 #[test]
724 fn a_folder_with_neither_is_still_the_tools_folder_that_is_missing() {
725 let dir = tempfile::tempdir().unwrap();
726 assert_eq!(bundled_dir_in(dir.path()), dir.path().join("tools").join("bin"));
727 }
728}