1use crate::core::central_repo;
2use crate::core::git_credentials;
3use crate::core::skill_metadata;
4mod cache_cleanup;
5mod cache_lock;
6use anyhow::{bail, Context, Result};
7pub use cache_cleanup::clear_repository_cache;
8use cache_lock::{lock_repo_cache, RepoCacheLock};
9use git2::{Direction, Repository};
10use sha2::{Digest, Sha256};
11use std::io::{BufReader, Read};
12use std::path::{Path, PathBuf};
13use std::process::{ChildStderr, Command, Stdio};
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18const CLONE_TIMEOUT_SECS: u64 = 300;
19
20pub const CLONE_TEMP_PREFIX: &str = "agent-hub-clone-";
23
24pub type ProgressCallback = Box<dyn Fn(&str) + Send>;
26
27fn git_command() -> Command {
29 #[allow(unused_mut)]
30 let mut cmd = Command::new("git");
31 #[cfg(target_os = "windows")]
32 {
33 use std::os::windows::process::CommandExt;
34 cmd.creation_flags(0x08000000); }
36 cmd
37}
38
39#[derive(Debug, Clone)]
40pub struct ParsedGitSource {
41 pub original_url: String,
42 pub clone_url: String,
43 pub branch: Option<String>,
44 pub subpath: Option<String>,
45}
46
47pub fn parse_git_source(url: &str) -> ParsedGitSource {
48 let trimmed = url.trim().to_string();
49 let (clone_url, branch, subpath) = normalize_url(&trimmed);
50
51 ParsedGitSource {
52 original_url: trimmed,
53 clone_url,
54 branch,
55 subpath,
56 }
57}
58
59pub fn validate_git_url(url: &str) -> Result<()> {
64 let trimmed = url.trim();
65 let lower = trimmed.to_lowercase();
66
67 if lower.starts_with("https://")
69 || lower.starts_with("http://")
70 || lower.starts_with("ssh://")
71 || lower.starts_with("git@")
72 {
73 return Ok(());
74 }
75
76 if !trimmed.contains("://")
78 && !trimmed.contains('\\')
79 && !trimmed.starts_with('/')
80 && !trimmed.starts_with('.')
81 && !trimmed.starts_with('~')
82 && trimmed.contains('/')
83 {
84 let bytes = trimmed.as_bytes();
85 let is_windows_path =
86 bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
87 if !is_windows_path {
88 return Ok(());
89 }
90 }
91
92 anyhow::bail!("URL scheme not allowed: only https, http, ssh, and git@ are permitted");
93}
94
95fn canonicalize_clone_url(url: &str) -> String {
104 let trimmed = url.trim().trim_end_matches('/');
105 trimmed.strip_suffix(".git").unwrap_or(trimmed).to_string()
106}
107
108fn repo_cache_dir(url: &str) -> PathBuf {
112 repo_cache_dir_for(url, false)
113}
114
115fn repo_cache_dir_for(url: &str, sparse: bool) -> PathBuf {
122 let canonical = canonicalize_clone_url(url);
123 let mut hasher = Sha256::new();
124 hasher.update(canonical.as_bytes());
125 let hash = format!("{:x}", hasher.finalize());
126 let short = &hash[..16];
127 let name = if sparse {
128 format!("{short}-sparse")
129 } else {
130 short.to_string()
131 };
132 central_repo::cache_dir().join("repos").join(name)
133}
134
135const REPO_CACHE_LIMIT_BYTES: u64 = 1024 * 1024 * 1024;
142
143fn prune_repo_cache(keep: &Path) {
156 prune_cache_root(
157 ¢ral_repo::cache_dir().join("repos"),
158 keep,
159 REPO_CACHE_LIMIT_BYTES,
160 )
161}
162
163fn prune_cache_root(root: &Path, keep: &Path, limit: u64) {
167 let Ok(entries) = std::fs::read_dir(root) else {
168 return;
169 };
170
171 let mut slots: Vec<(PathBuf, u64, std::time::SystemTime)> = Vec::new();
172 let mut total: u64 = 0;
173 for entry in entries.flatten() {
174 let path = entry.path();
175 if !path.is_dir() {
176 continue;
177 }
178 let (size, used) = slot_stats(&path);
179 total = total.saturating_add(size);
180 slots.push((path, size, used));
181 }
182
183 slots.sort_by_key(|(_, _, used)| *used);
184 for (path, size, _) in slots {
185 if total <= limit {
186 break;
187 }
188 if path == keep {
189 continue;
190 }
191 let Ok(_lock) = RepoCacheLock::try_acquire(&path) else {
192 continue;
193 };
194 if std::fs::remove_dir_all(&path).is_ok() {
195 log::info!("pruned repo cache slot {}", path.display());
196 total = total.saturating_sub(size);
197 }
198 }
199}
200
201fn slot_stats(dir: &Path) -> (u64, std::time::SystemTime) {
210 let mut size = 0u64;
211 let mut newest = std::time::UNIX_EPOCH;
212 for entry in walkdir::WalkDir::new(dir).into_iter().flatten() {
213 let Ok(meta) = entry.metadata() else {
214 continue;
215 };
216 if !meta.is_file() {
217 continue;
218 }
219 size = size.saturating_add(meta.len());
220 if let Ok(modified) = meta.modified() {
221 newest = newest.max(modified);
222 }
223 }
224 (size, newest)
225}
226
227fn materialize_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
228 let temp_dir =
229 std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));
230
231 let child = git_command()
235 .arg("clone")
236 .arg("--local")
237 .arg(cached)
238 .arg(&temp_dir)
239 .stdout(Stdio::null())
240 .stderr(Stdio::piped())
241 .spawn();
242
243 let mut system_git_stderr: Option<String> = None;
244 if let Ok(mut child) = child {
245 let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
246 loop {
247 if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
248 let _ = child.kill();
249 let _ = child.wait();
250 let _ = std::fs::remove_dir_all(&temp_dir);
251 anyhow::bail!("Installation cancelled");
252 }
253 match child.try_wait() {
254 Ok(Some(status)) => {
255 if status.success() {
256 return Ok(temp_dir);
257 }
258 let mut stderr_buf = String::new();
259 if let Some(mut stderr) = child.stderr.take() {
260 let _ = stderr.read_to_string(&mut stderr_buf);
261 }
262 let _ = std::fs::remove_dir_all(&temp_dir);
263 system_git_stderr = Some(stderr_buf);
264 break;
265 }
266 Ok(None) => {
267 if Instant::now() > deadline {
268 let _ = child.kill();
269 let _ = child.wait();
270 let _ = std::fs::remove_dir_all(&temp_dir);
271 anyhow::bail!(
272 "Local clone from cache timed out after {}s",
273 CLONE_TIMEOUT_SECS
274 );
275 }
276 std::thread::sleep(Duration::from_millis(100));
277 }
278 Err(_) => {
279 let _ = std::fs::remove_dir_all(&temp_dir);
280 break;
281 }
282 }
283 }
284 }
285
286 let source = cached
287 .to_str()
288 .ok_or_else(|| anyhow::anyhow!("Cached repo path is not valid UTF-8"))?;
289 match git2::build::RepoBuilder::new().clone(source, &temp_dir) {
290 Ok(_) => Ok(temp_dir),
291 Err(err) => {
292 let _ = std::fs::remove_dir_all(&temp_dir);
293 let detail = system_git_stderr
294 .filter(|s| !s.trim().is_empty())
295 .map(|s| format!(" (system git: {})", s.trim()))
296 .unwrap_or_default();
297 anyhow::bail!(
298 "Failed to create install checkout from cache: {}{}",
299 err,
300 detail
301 )
302 }
303 }
304}
305
306fn try_update_cached_repo(
309 cached: &Path,
310 url: &str,
311 branch: Option<&str>,
312 proxy_url: Option<&str>,
313 cancel: Option<&Arc<AtomicBool>>,
314 on_progress: &Option<ProgressCallback>,
315) -> Result<bool> {
316 if !cached.join(".git").exists() {
317 return Ok(false);
318 }
319
320 let current_remote = {
322 let mut cmd = git_command();
323 cmd.arg("-C")
324 .arg(cached)
325 .args(["remote", "get-url", "origin"]);
326 let output = cmd.output().ok();
327 output
328 .filter(|o| o.status.success())
329 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
330 };
331 let remote_matches = current_remote
332 .as_deref()
333 .is_some_and(|r| canonicalize_clone_url(r) == canonicalize_clone_url(url));
334 if !remote_matches {
335 let _ = std::fs::remove_dir_all(cached);
337 return Ok(false);
338 }
339
340 if let Some(cb) = on_progress {
341 cb("Updating cached repository…");
342 }
343
344 let mut fetch_cmd = git_command();
350 fetch_cmd.arg("-C").arg(cached);
351 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
352 fetch_cmd.arg("-c").arg(format!("http.proxy={proxy}"));
353 fetch_cmd.arg("-c").arg(format!("https.proxy={proxy}"));
354 }
355 fetch_cmd.arg("fetch").arg("--depth").arg("1");
356 fetch_cmd.arg("origin");
357 if let Some(branch) = branch {
358 fetch_cmd.arg(branch);
359 }
360 fetch_cmd.stdout(Stdio::null()).stderr(Stdio::null());
361
362 let child = fetch_cmd.spawn();
363 if let Ok(mut child) = child {
364 let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
365 loop {
366 if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
367 let _ = child.kill();
368 let _ = child.wait();
369 anyhow::bail!("Installation cancelled");
370 }
371 match child.try_wait() {
372 Ok(Some(status)) => {
373 if !status.success() {
374 let _ = std::fs::remove_dir_all(cached);
376 return Ok(false);
377 }
378 break;
379 }
380 Ok(None) => {
381 if Instant::now() > deadline {
382 let _ = child.kill();
383 let _ = child.wait();
384 let _ = std::fs::remove_dir_all(cached);
385 return Ok(false);
386 }
387 std::thread::sleep(Duration::from_millis(200));
388 }
389 Err(_) => {
390 let _ = std::fs::remove_dir_all(cached);
391 return Ok(false);
392 }
393 }
394 }
395 } else {
396 let _ = std::fs::remove_dir_all(cached);
397 return Ok(false);
398 }
399
400 let targets: Vec<String> = match branch {
405 Some(b) => vec![format!("origin/{b}"), "FETCH_HEAD".to_string()],
406 None => vec!["origin/HEAD".to_string()],
407 };
408 let mut cancelled = false;
413 let reset_ok = targets.iter().any(|target| {
414 match run_git_watched_at(
415 cached,
416 &["reset", "--hard", target],
417 proxy_url,
418 cancel,
419 &None,
420 ) {
421 Ok(()) => true,
422 Err(e) => {
423 cancelled |= is_cancellation(&e);
424 false
425 }
426 }
427 });
428 if cancelled {
433 bail!("Installation cancelled");
434 }
435 match reset_ok {
436 true => Ok(true),
437 false => {
438 let _ = std::fs::remove_dir_all(cached);
439 Ok(false)
440 }
441 }
442}
443
444fn is_ssh_warning(line: &str) -> bool {
446 let trimmed = line.trim().trim_start_matches("** ");
447 trimmed.starts_with("WARNING:")
448 || trimmed.starts_with("This session may")
449 || trimmed.starts_with("The server may")
450 || trimmed.starts_with("See https://openssh.com")
451}
452
453fn spawn_stderr_collector(
454 stderr: Option<ChildStderr>,
455 forward_progress: bool,
456) -> (
457 std::sync::mpsc::Receiver<String>,
458 std::thread::JoinHandle<String>,
459) {
460 let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
461 let stderr_thread = std::thread::spawn(move || {
462 let mut collected = String::new();
463 let Some(stderr) = stderr else {
464 return collected;
465 };
466
467 let mut reader = BufReader::new(stderr);
468 let mut line = Vec::new();
469 let mut byte = [0u8; 1];
470
471 loop {
472 match reader.read(&mut byte) {
473 Ok(0) => {
474 if !line.is_empty() {
475 emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
476 }
477 break;
478 }
479 Ok(_) if byte[0] == b'\n' || byte[0] == b'\r' => {
480 if !line.is_empty() {
481 emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
482 line.clear();
483 }
484 }
485 Ok(_) => line.push(byte[0]),
486 Err(_) => break,
487 }
488 }
489
490 collected
491 });
492
493 (stderr_rx, stderr_thread)
494}
495
496fn emit_stderr_line(
497 line: &[u8],
498 forward_progress: bool,
499 stderr_tx: &std::sync::mpsc::Sender<String>,
500 collected: &mut String,
501) {
502 let line = String::from_utf8_lossy(line).to_string();
503 if !is_ssh_warning(&line) {
504 collected.push_str(&line);
505 collected.push('\n');
506 }
507 if forward_progress {
508 let _ = stderr_tx.send(line);
509 }
510}
511
512pub fn clone_repo_ref(
513 url: &str,
514 branch: Option<&str>,
515 cancel: Option<&Arc<AtomicBool>>,
516 proxy_url: Option<&str>,
517) -> Result<PathBuf> {
518 clone_repo_ref_with_progress(url, branch, cancel, proxy_url, None)
519}
520
521pub fn clone_repo_ref_with_progress(
522 url: &str,
523 branch: Option<&str>,
524 cancel: Option<&Arc<AtomicBool>>,
525 proxy_url: Option<&str>,
526 on_progress: Option<ProgressCallback>,
527) -> Result<PathBuf> {
528 clone_repo_ref_scoped(url, branch, None, cancel, proxy_url, on_progress)
529}
530
531pub fn clone_repo_ref_scoped(
545 url: &str,
546 branch: Option<&str>,
547 subpath: Option<&str>,
548 cancel: Option<&Arc<AtomicBool>>,
549 proxy_url: Option<&str>,
550 on_progress: Option<ProgressCallback>,
551) -> Result<PathBuf> {
552 if let Some(subpath) = sparse_pattern(subpath) {
553 match clone_repo_sparse(url, branch, &subpath, cancel, proxy_url, &on_progress) {
554 Ok(dir) => return Ok(dir),
555 Err(e) if is_cancellation(&e) => return Err(e),
556 Err(e) => {
557 log::info!(
558 "narrow clone of '{subpath}' from {url} unavailable, using a full checkout: {e}"
559 );
560 }
561 }
562 }
563
564 clone_repo_full(url, branch, cancel, proxy_url, on_progress)
565}
566
567fn is_cancellation(err: &anyhow::Error) -> bool {
570 let message = err.to_string();
571 message.contains("cancelled") || message.contains("canceled")
572}
573
574fn sparse_pattern(subpath: Option<&str>) -> Option<String> {
589 let raw = subpath?;
590 #[cfg(windows)]
591 let raw = &raw.replace('\\', "/");
592
593 if raw.is_empty()
594 || raw != raw.trim()
595 || raw.starts_with('/')
596 || raw.ends_with('/')
597 || raw.contains('\\')
598 {
599 return None;
600 }
601 if raw
602 .split('/')
603 .any(|segment| segment.is_empty() || segment == "." || segment == "..")
604 {
605 return None;
606 }
607 Some(raw.to_string())
608}
609
610fn clone_repo_sparse(
612 url: &str,
613 branch: Option<&str>,
614 subpath: &str,
615 cancel: Option<&Arc<AtomicBool>>,
616 proxy_url: Option<&str>,
617 on_progress: &Option<ProgressCallback>,
618) -> Result<PathBuf> {
619 let cached_dir = repo_cache_dir_for(url, true);
620 let _cache_lock = lock_repo_cache(&cached_dir, on_progress)?;
621
622 let reusable = cached_dir.exists()
626 && try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, on_progress)?;
627
628 if !reusable {
629 let _ = std::fs::remove_dir_all(&cached_dir);
630 prune_repo_cache(&cached_dir);
631 sparse_clone_into(&cached_dir, url, branch, cancel, proxy_url, on_progress).inspect_err(
632 |_| {
633 let _ = std::fs::remove_dir_all(&cached_dir);
634 },
635 )?;
636 }
637
638 set_sparse_scope(&cached_dir, subpath, cancel, proxy_url, on_progress)?;
639
640 if !sparse_checkout_holds_a_skill(&cached_dir, subpath) {
644 bail!("'{subpath}' is not a skill directory in the narrow checkout of {url}");
645 }
646
647 copy_cached_repo(&cached_dir, cancel)
648}
649
650fn sparse_clone_into(
651 dest: &Path,
652 url: &str,
653 branch: Option<&str>,
654 cancel: Option<&Arc<AtomicBool>>,
655 proxy_url: Option<&str>,
656 on_progress: &Option<ProgressCallback>,
657) -> Result<()> {
658 if let Some(cb) = on_progress {
659 cb("Fetching only the requested skill directory…");
660 }
661 if let Some(parent) = dest.parent() {
662 std::fs::create_dir_all(parent)?;
663 }
664
665 let mut command = git_command();
666 command
667 .arg("clone")
668 .arg("--filter=blob:none")
669 .arg("--no-checkout")
670 .arg("--sparse")
671 .arg("--depth")
672 .arg("1");
673 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
676 command.arg("-c").arg(format!("http.proxy={proxy}"));
677 command.arg("-c").arg(format!("https.proxy={proxy}"));
678 }
679 if let Some(branch) = branch {
680 command.arg("--branch").arg(branch);
681 }
682 command.arg("--progress").arg(url).arg(dest);
683 run_git_watched(command, cancel, on_progress)
684}
685
686fn set_sparse_scope(
691 cached: &Path,
692 subpath: &str,
693 cancel: Option<&Arc<AtomicBool>>,
694 proxy_url: Option<&str>,
695 on_progress: &Option<ProgressCallback>,
696) -> Result<()> {
697 run_git_watched_at(
701 cached,
702 &["sparse-checkout", "set", "--cone", subpath],
703 proxy_url,
704 cancel,
705 on_progress,
706 )?;
707 run_git_watched_at(cached, &["checkout"], proxy_url, cancel, on_progress)
708}
709
710fn sparse_checkout_holds_a_skill(cached: &Path, subpath: &str) -> bool {
721 skill_metadata::is_valid_skill_dir(&cached.join(subpath))
722}
723
724fn copy_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
732 let temp_dir =
733 std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));
734 if let Err(e) = copy_dir_contents(cached, &temp_dir, cancel) {
735 let _ = std::fs::remove_dir_all(&temp_dir);
736 return Err(e);
737 }
738 detach_from_promisor(&temp_dir);
739 Ok(temp_dir)
740}
741
742fn detach_from_promisor(repo_dir: &Path) {
761 for key in [
767 "remote.origin.promisor",
768 "remote.origin.partialclonefilter",
769 "extensions.partialClone",
770 ] {
771 let _ = git_command()
772 .arg("-C")
773 .arg(repo_dir)
774 .args(["config", "--unset", key])
775 .stdout(Stdio::null())
776 .stderr(Stdio::null())
777 .status();
778 }
779}
780
781fn copy_dir_contents(src: &Path, dst: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<()> {
785 if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
786 bail!("Installation cancelled");
787 }
788 std::fs::create_dir_all(dst).with_context(|| format!("Failed to create {}", dst.display()))?;
789 for entry in std::fs::read_dir(src)? {
790 let entry = entry?;
791 let file_type = entry.file_type()?;
792 if file_type.is_symlink() {
793 continue;
794 }
795 let target = dst.join(entry.file_name());
796 if file_type.is_dir() {
797 copy_dir_contents(&entry.path(), &target, cancel)?;
798 } else {
799 std::fs::copy(entry.path(), &target).with_context(|| {
800 format!(
801 "Failed to copy {} to {}",
802 entry.path().display(),
803 target.display()
804 )
805 })?;
806 }
807 }
808 Ok(())
809}
810
811fn run_git_watched_at(
823 dir: &Path,
824 args: &[&str],
825 proxy_url: Option<&str>,
826 cancel: Option<&Arc<AtomicBool>>,
827 on_progress: &Option<ProgressCallback>,
828) -> Result<()> {
829 let mut command = git_command();
830 command.arg("-C").arg(dir);
831 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
832 command.arg("-c").arg(format!("http.proxy={proxy}"));
833 command.arg("-c").arg(format!("https.proxy={proxy}"));
834 }
835 command.args(args);
836 run_git_watched(command, cancel, on_progress)
837}
838
839fn run_git_watched(
846 mut command: Command,
847 cancel: Option<&Arc<AtomicBool>>,
848 on_progress: &Option<ProgressCallback>,
849) -> Result<()> {
850 let mut child = command
851 .stdout(Stdio::null())
852 .stderr(Stdio::piped())
853 .spawn()
854 .context("Failed to start git")?;
855
856 let (stderr_rx, stderr_thread) =
857 spawn_stderr_collector(child.stderr.take(), on_progress.is_some());
858 let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
859
860 loop {
861 if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
862 let _ = child.kill();
863 let _ = child.wait();
864 bail!("Installation cancelled");
865 }
866
867 if let Some(ref cb) = on_progress {
868 while let Ok(line) = stderr_rx.try_recv() {
869 if !is_ssh_warning(&line) && !line.trim().is_empty() {
870 cb(&line);
871 }
872 }
873 }
874
875 match child.try_wait() {
876 Ok(Some(status)) => {
877 let collected = stderr_thread.join().unwrap_or_default();
878 if status.success() {
879 return Ok(());
880 }
881 bail!("git exited with {}: {}", status, collected.trim());
882 }
883 Ok(None) => {
884 if Instant::now() > deadline {
885 let _ = child.kill();
886 let _ = child.wait();
887 bail!("git timed out after {}s", CLONE_TIMEOUT_SECS);
888 }
889 std::thread::sleep(Duration::from_millis(100));
890 }
891 Err(e) => {
892 let _ = child.kill();
893 let _ = child.wait();
894 bail!("Failed to wait for git: {e}")
895 }
896 }
897 }
898}
899
900fn clone_repo_full(
901 url: &str,
902 branch: Option<&str>,
903 cancel: Option<&Arc<AtomicBool>>,
904 proxy_url: Option<&str>,
905 on_progress: Option<ProgressCallback>,
906) -> Result<PathBuf> {
907 let cached_dir = repo_cache_dir(url);
908 let _cache_lock = lock_repo_cache(&cached_dir, &on_progress)?;
909
910 if cached_dir.exists() {
912 match try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, &on_progress) {
913 Ok(true) => return materialize_cached_repo(&cached_dir, cancel),
914 Ok(false) => { }
915 Err(e) => {
916 if e.to_string().contains("cancelled") || e.to_string().contains("canceled") {
918 return Err(e);
919 }
920 }
922 }
923 }
924
925 let _ = std::fs::remove_dir_all(&cached_dir);
927 prune_repo_cache(&cached_dir);
928
929 let timeout = Duration::from_secs(CLONE_TIMEOUT_SECS);
930 let mut system_git_stderr: Option<String> = None;
931
932 let mut command = git_command();
934 command.arg("clone").arg("--depth").arg("1");
935 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
936 command.arg("-c").arg(format!("http.proxy={proxy}"));
937 command.arg("-c").arg(format!("https.proxy={proxy}"));
938 }
939 if let Some(branch) = branch {
940 command.arg("--branch").arg(branch);
941 }
942 command.arg("--progress"); let child = command
944 .arg(url)
945 .arg(&cached_dir)
946 .stdout(Stdio::null())
947 .stderr(Stdio::piped())
948 .spawn();
949
950 if let Ok(mut child) = child {
951 let (stderr_rx, stderr_thread) =
952 spawn_stderr_collector(child.stderr.take(), on_progress.is_some());
953
954 let deadline = Instant::now() + timeout;
955 loop {
956 if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
957 let _ = child.kill();
958 let _ = child.wait();
959 let _ = std::fs::remove_dir_all(&cached_dir);
960 anyhow::bail!("Installation cancelled");
961 }
962
963 if let Some(ref cb) = on_progress {
965 while let Ok(line) = stderr_rx.try_recv() {
966 if !is_ssh_warning(&line) && !line.trim().is_empty() {
967 cb(&line);
968 }
969 }
970 }
971
972 match child.try_wait() {
973 Ok(Some(status)) => {
974 let collected = stderr_thread.join().unwrap_or_default();
975 if status.success() {
976 return materialize_cached_repo(&cached_dir, cancel);
977 }
978 system_git_stderr = Some(collected);
979 let _ = std::fs::remove_dir_all(&cached_dir);
981 break; }
983 Ok(None) => {
984 if Instant::now() > deadline {
985 let _ = child.kill();
986 let _ = child.wait();
987 let _ = std::fs::remove_dir_all(&cached_dir);
988 anyhow::bail!(
989 "Git clone timed out after {}s — check your network connection",
990 CLONE_TIMEOUT_SECS
991 );
992 }
993 std::thread::sleep(Duration::from_millis(200));
994 }
995 Err(_) => {
996 let _ = std::fs::remove_dir_all(&cached_dir);
997 break;
998 }
999 }
1000 }
1001 }
1002
1003 if let Some(ref cb) = on_progress {
1005 cb("Trying alternative clone method…");
1006 }
1007
1008 let mut builder = git2::build::RepoBuilder::new();
1009 if let Some(branch) = branch {
1010 builder.branch(branch);
1011 }
1012
1013 let cancel_clone = cancel.cloned();
1014 let clone_deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
1015 let mut callbacks = git2::RemoteCallbacks::new();
1016
1017 let progress_for_cb: Option<Arc<std::sync::Mutex<ProgressCallback>>> =
1018 on_progress.map(|cb| Arc::new(std::sync::Mutex::new(cb)));
1019 let progress_for_transfer = progress_for_cb.clone();
1020
1021 callbacks.transfer_progress(move |stats| {
1022 if let Some(ref c) = cancel_clone {
1023 if c.load(Ordering::SeqCst) {
1024 return false;
1025 }
1026 }
1027 if Instant::now() > clone_deadline {
1028 return false;
1029 }
1030 if let Some(ref cb) = progress_for_transfer {
1031 if let Ok(cb) = cb.lock() {
1032 let msg = format!(
1033 "Receiving objects: {}/{} ({:.1} KB)",
1034 stats.received_objects(),
1035 stats.total_objects(),
1036 stats.received_bytes() as f64 / 1024.0
1037 );
1038 cb(&msg);
1039 }
1040 }
1041 true
1042 });
1043
1044 git_credentials::install_git2_credentials(&mut callbacks, url);
1045 let mut fetch_opts = git2::FetchOptions::new();
1046 fetch_opts.remote_callbacks(callbacks);
1047 fetch_opts.depth(1);
1048 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1049 let mut proxy_opts = git2::ProxyOptions::new();
1050 proxy_opts.url(proxy);
1051 fetch_opts.proxy_options(proxy_opts);
1052 }
1053 builder.fetch_options(fetch_opts);
1054
1055 match builder.clone(url, &cached_dir) {
1056 Ok(_) => materialize_cached_repo(&cached_dir, cancel),
1057 Err(git2_err) => {
1058 if let Some(pinned) = branch {
1061 if clone_tag_with_git2(url, pinned, &cached_dir, cancel, proxy_url).is_ok() {
1062 return materialize_cached_repo(&cached_dir, cancel);
1063 }
1064 }
1065 let _ = std::fs::remove_dir_all(&cached_dir);
1066 let detail = system_git_stderr
1068 .filter(|s| !s.trim().is_empty())
1069 .map(|s| format!(" (system git: {})", s.trim()))
1070 .unwrap_or_default();
1071 anyhow::bail!("Failed to clone {}: {}{}", url, git2_err, detail)
1072 }
1073 }
1074}
1075
1076fn clone_tag_with_git2(
1089 url: &str,
1090 tag: &str,
1091 cached_dir: &Path,
1092 cancel: Option<&Arc<AtomicBool>>,
1093 proxy_url: Option<&str>,
1094) -> Result<()> {
1095 let _ = std::fs::remove_dir_all(cached_dir);
1096 let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
1097 let fetch_opts = || {
1098 let cancel = cancel.cloned();
1099 let mut callbacks = git2::RemoteCallbacks::new();
1100 callbacks.transfer_progress(move |_| {
1101 if cancel.as_ref().is_some_and(|c| c.load(Ordering::SeqCst)) {
1102 return false;
1103 }
1104 Instant::now() <= deadline
1105 });
1106 git_credentials::install_git2_credentials(&mut callbacks, url);
1107 let mut opts = git2::FetchOptions::new();
1108 opts.remote_callbacks(callbacks);
1109 opts.depth(1);
1110 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1111 let mut proxy_opts = git2::ProxyOptions::new();
1112 proxy_opts.url(proxy);
1113 opts.proxy_options(proxy_opts);
1114 }
1115 opts
1116 };
1117
1118 let repo = git2::Repository::init(cached_dir)?;
1119 {
1120 let mut remote = repo.remote("origin", url)?;
1123 let refspec = format!("+refs/tags/{tag}:refs/tags/{tag}");
1124 remote.fetch(&[refspec.as_str()], Some(&mut fetch_opts()), None)?;
1125 }
1126 let commit = repo.revparse_single(&format!("refs/tags/{tag}^{{commit}}"))?;
1127 repo.set_head_detached(commit.id())?;
1128 repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
1129 Ok(())
1130}
1131
1132pub fn get_head_revision(repo_dir: &Path) -> Result<String> {
1133 let output = git_command()
1134 .arg("-C")
1135 .arg(repo_dir)
1136 .args(["rev-parse", "HEAD"])
1137 .output();
1138
1139 if let Ok(output) = output {
1140 if output.status.success() {
1141 return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string());
1142 }
1143 }
1144
1145 let repo = Repository::open(repo_dir)?;
1146 let head = repo.head()?.peel_to_commit()?;
1147 Ok(head.id().to_string())
1148}
1149
1150pub fn resolve_remote_revision(
1151 url: &str,
1152 branch: Option<&str>,
1153 proxy_url: Option<&str>,
1154) -> Result<String> {
1155 if let Ok(revision) = resolve_remote_revision_with_git(url, branch, proxy_url) {
1156 return Ok(revision);
1157 }
1158
1159 let repo = Repository::init_bare(
1160 std::env::temp_dir().join(format!("agent-hub-remote-{}", uuid::Uuid::new_v4())),
1161 )?;
1162 let mut remote = repo.remote_anonymous(url)?;
1163 let mut proxy_opts = git2::ProxyOptions::new();
1164 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1165 proxy_opts.url(proxy);
1166 }
1167 let mut callbacks = git2::RemoteCallbacks::new();
1168 git_credentials::install_git2_credentials(&mut callbacks, url);
1169 remote.connect_auth(Direction::Fetch, Some(callbacks), Some(proxy_opts))?;
1170 let refs = remote.list()?;
1171
1172 for wanted in candidate_ref_names(branch) {
1173 if let Some(head) = refs.iter().find(|head| head.name() == wanted) {
1174 return Ok(head.oid().to_string());
1175 }
1176 }
1177
1178 anyhow::bail!("Unable to resolve remote revision for {}", url)
1179}
1180
1181pub fn checkout_revision(repo_dir: &Path, revision: &str) -> Result<()> {
1182 let status = git_command()
1183 .arg("-C")
1184 .arg(repo_dir)
1185 .args(["checkout", "--detach", revision])
1186 .stdout(std::process::Stdio::null())
1187 .stderr(std::process::Stdio::null())
1188 .status();
1189
1190 if let Ok(status) = status {
1191 if status.success() {
1192 return Ok(());
1193 }
1194 }
1195
1196 let repo = Repository::open(repo_dir)?;
1197 let oid = git2::Oid::from_str(revision)?;
1198 repo.set_head_detached(oid)?;
1199 repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
1200 Ok(())
1201}
1202
1203pub fn relative_subpath(repo_dir: &Path, skill_dir: &Path) -> Option<String> {
1204 let relative = skill_dir.strip_prefix(repo_dir).ok()?;
1205 if relative.as_os_str().is_empty() {
1206 None
1207 } else {
1208 Some(relative.to_string_lossy().to_string())
1209 }
1210}
1211
1212fn normalize_url(url: &str) -> (String, Option<String>, Option<String>) {
1213 let trimmed = url.trim();
1214
1215 if trimmed.starts_with("http://")
1217 || trimmed.starts_with("https://")
1218 || trimmed.starts_with("ssh://")
1219 || trimmed.starts_with("git@")
1220 {
1221 if let Some((clone_url, branch, subpath)) = parse_github_tree_url(trimmed) {
1222 return (clone_url, Some(branch), subpath);
1223 }
1224 return (trimmed.to_string(), None, None);
1225 }
1226
1227 if trimmed.contains('/') && !trimmed.contains(' ') {
1229 return (format!("https://github.com/{}.git", trimmed), None, None);
1230 }
1231
1232 (trimmed.to_string(), None, None)
1233}
1234
1235pub fn find_skill_dir(repo_dir: &Path, skill_id: Option<&str>) -> Result<PathBuf> {
1236 if let Some(id) = skill_id {
1241 let direct = repo_dir.join(id);
1242 if skill_metadata::is_valid_skill_dir(&direct) {
1243 return Ok(direct);
1244 }
1245
1246 let in_skills = repo_dir.join("skills").join(id);
1247 if skill_metadata::is_valid_skill_dir(&in_skills) {
1248 return Ok(in_skills);
1249 }
1250
1251 let in_agents = repo_dir.join(".agents").join("skills").join(id);
1258 if skill_metadata::is_valid_skill_dir(&in_agents) {
1259 return Ok(in_agents);
1260 }
1261
1262 let mut name_match: Option<PathBuf> = None;
1266 for e in walkdir::WalkDir::new(repo_dir)
1267 .max_depth(6)
1268 .into_iter()
1269 .flatten()
1270 {
1271 if e.file_type().is_dir() {
1272 if e.file_name().to_string_lossy() == id
1273 && skill_metadata::is_valid_skill_dir(e.path())
1274 {
1275 return Ok(e.path().to_path_buf());
1276 }
1277 if name_match.is_none() {
1278 let meta = skill_metadata::parse_skill_md(e.path());
1279 if meta.name.as_deref() == Some(id) {
1280 name_match = Some(e.path().to_path_buf());
1281 }
1282 }
1283 }
1284 }
1285 if let Some(path) = name_match {
1286 return Ok(path);
1287 }
1288
1289 bail!("Skill '{}' not found in {}", id, repo_dir.display());
1294 }
1295
1296 let has_skill_md = ["SKILL.md", "skill.md"]
1301 .iter()
1302 .any(|f| repo_dir.join(f).exists());
1303 if has_skill_md {
1304 return Ok(repo_dir.to_path_buf());
1305 }
1306
1307 let skills_subdir = repo_dir.join("skills");
1309 if skills_subdir.is_dir() {
1310 return Ok(skills_subdir);
1311 }
1312
1313 let skill_subdir = repo_dir.join("skill");
1314 if skill_subdir.is_dir() {
1315 return Ok(skill_subdir);
1316 }
1317
1318 Ok(repo_dir.to_path_buf())
1320}
1321
1322pub fn cleanup_temp(path: &Path) {
1323 let _ = std::fs::remove_dir_all(path);
1324}
1325
1326fn parse_github_tree_url(url: &str) -> Option<(String, String, Option<String>)> {
1327 let (clone_url, path) = parse_github_tree_url_path(url)?;
1328 let (branch, subpath) = split_tree_branch_path(&path, &[]);
1329 Some((clone_url, branch, subpath))
1330}
1331
1332fn parse_github_tree_url_path(url: &str) -> Option<(String, String)> {
1336 let re = regex::Regex::new(r"^(https://github\.com/[^/]+/[^/]+?)(?:\.git)?/tree/(.+)$").ok()?;
1337 let caps = re.captures(url)?;
1338 let clone_url = format!("{}.git", caps.get(1)?.as_str());
1339 let path = caps.get(2)?.as_str().to_string();
1340 Some((clone_url, path))
1341}
1342
1343fn split_tree_path_with_known_refs(path: &str, known: &RemoteRefNames) -> (String, Option<String>) {
1350 match_known_ref(path, &known.heads)
1351 .or_else(|| match_known_ref(path, &known.tags))
1352 .unwrap_or_else(|| split_tree_branch_path(path, &[]))
1353}
1354
1355fn match_known_ref(path: &str, known: &[String]) -> Option<(String, Option<String>)> {
1362 let mut best: Option<&str> = None;
1363 for name in known {
1364 if name.is_empty() {
1365 continue;
1366 }
1367 let matches = path == name.as_str()
1368 || path
1369 .strip_prefix(name.as_str())
1370 .is_some_and(|rest| rest.starts_with('/'));
1371 if matches && best.map_or(true, |b: &str| name.len() > b.len()) {
1372 best = Some(name);
1373 }
1374 }
1375 best.map(|name| {
1376 let subpath = path
1377 .strip_prefix(name)
1378 .and_then(|rest| rest.strip_prefix('/'))
1379 .filter(|s| !s.is_empty())
1380 .map(|s| s.to_string());
1381 (name.to_string(), subpath)
1382 })
1383}
1384
1385fn split_tree_branch_path(path: &str, known_branches: &[String]) -> (String, Option<String>) {
1394 if let Some(hit) = match_known_ref(path, known_branches) {
1395 return hit;
1396 }
1397
1398 let mut parts = path.splitn(2, '/');
1399 let branch = parts.next().unwrap_or("").to_string();
1400 let subpath = parts
1401 .next()
1402 .filter(|s| !s.is_empty())
1403 .map(|s| s.to_string());
1404 (branch, subpath)
1405}
1406
1407pub fn parse_git_source_resolved(url: &str, proxy_url: Option<&str>) -> ParsedGitSource {
1412 let mut parsed = parse_git_source(url);
1413 let original_url = parsed.original_url.clone();
1414
1415 let Some((clone_url, path)) = parse_github_tree_url_path(&original_url) else {
1416 return parsed;
1417 };
1418 if !path.contains('/') {
1420 return parsed;
1421 }
1422
1423 let known = match list_remote_ref_names(&clone_url, proxy_url) {
1424 Ok(refs) if !refs.is_empty() => refs,
1425 Ok(_) => {
1426 log::warn!(
1427 "ls-remote returned no refs for {}; using optimistic tree-URL parse",
1428 clone_url
1429 );
1430 return parsed;
1431 }
1432 Err(e) => {
1433 log::warn!(
1434 "ls-remote failed for {}: {} — using optimistic tree-URL parse (slash-ref URLs may parse incorrectly)",
1435 clone_url,
1436 e
1437 );
1438 return parsed;
1439 }
1440 };
1441 let (branch, subpath) = split_tree_path_with_known_refs(&path, &known);
1442 parsed.branch = Some(branch);
1443 parsed.subpath = subpath;
1444 parsed
1445}
1446
1447#[derive(Debug, Default, PartialEq)]
1454struct RemoteRefNames {
1455 heads: Vec<String>,
1456 tags: Vec<String>,
1457}
1458
1459impl RemoteRefNames {
1460 fn is_empty(&self) -> bool {
1461 self.heads.is_empty() && self.tags.is_empty()
1462 }
1463}
1464
1465fn list_remote_ref_names(url: &str, proxy_url: Option<&str>) -> Result<RemoteRefNames> {
1466 let mut cmd = git_command();
1467 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1468 cmd.arg("-c").arg(format!("http.proxy={proxy}"));
1469 cmd.arg("-c").arg(format!("https.proxy={proxy}"));
1470 }
1471 let output = cmd
1472 .args(["ls-remote", "--heads", "--tags", url])
1473 .output()
1474 .with_context(|| format!("Failed to list remote refs for {}", url))?;
1475
1476 if !output.status.success() {
1477 anyhow::bail!("git ls-remote exited with {}", output.status);
1478 }
1479
1480 let stdout = String::from_utf8_lossy(&output.stdout);
1481 Ok(parse_remote_ref_names(&stdout))
1482}
1483
1484fn parse_remote_ref_names(stdout: &str) -> RemoteRefNames {
1485 let mut refs = RemoteRefNames::default();
1486 for line in stdout.lines() {
1487 let mut parts = line.split_whitespace();
1488 let Some(_sha) = parts.next() else { continue };
1489 let Some(refname) = parts.next() else {
1490 continue;
1491 };
1492 if refname.ends_with("^{}") {
1494 continue;
1495 }
1496 if let Some(name) = refname.strip_prefix("refs/heads/") {
1497 refs.heads.push(name.to_string());
1498 } else if let Some(name) = refname.strip_prefix("refs/tags/") {
1499 refs.tags.push(name.to_string());
1500 }
1501 }
1502 refs
1503}
1504
1505fn candidate_ref_names(source_ref: Option<&str>) -> Vec<String> {
1513 match source_ref {
1514 Some(name) => vec![
1515 format!("refs/heads/{name}"),
1516 format!("refs/tags/{name}^{{}}"),
1517 format!("refs/tags/{name}"),
1518 ],
1519 None => vec!["HEAD".to_string()],
1520 }
1521}
1522
1523fn select_remote_revision(stdout: &str, candidates: &[String]) -> Option<String> {
1528 let refs: Vec<(&str, &str)> = stdout
1529 .lines()
1530 .filter_map(|line| {
1531 let mut parts = line.split_whitespace();
1532 let sha = parts.next()?;
1533 let name = parts.next()?;
1534 (!sha.is_empty()).then_some((name, sha))
1535 })
1536 .collect();
1537
1538 candidates.iter().find_map(|wanted| {
1539 refs.iter()
1540 .find(|(name, _)| *name == wanted.as_str())
1541 .map(|(_, sha)| sha.to_string())
1542 })
1543}
1544
1545fn resolve_remote_revision_with_git(
1546 url: &str,
1547 branch: Option<&str>,
1548 proxy_url: Option<&str>,
1549) -> Result<String> {
1550 let candidates = candidate_ref_names(branch);
1551 let mut cmd = git_command();
1552 if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1553 cmd.arg("-c").arg(format!("http.proxy={proxy}"));
1554 cmd.arg("-c").arg(format!("https.proxy={proxy}"));
1555 }
1556 cmd.args(["ls-remote", url]);
1557 cmd.args(&candidates);
1558 let output = cmd
1559 .output()
1560 .with_context(|| format!("Failed to query remote {}", url))?;
1561
1562 if !output.status.success() {
1563 anyhow::bail!("git ls-remote exited with {}", output.status);
1564 }
1565
1566 let stdout = String::from_utf8_lossy(&output.stdout);
1567 select_remote_revision(&stdout, &candidates)
1568 .ok_or_else(|| anyhow::anyhow!("No remote revision found"))
1569}
1570
1571#[cfg(test)]
1572mod tests;
1573
1574#[cfg(test)]
1575#[path = "git_fetcher/tag_tests.rs"]
1576mod tag_tests;