Skip to main content

agentmux_srv_core/backend/
cli_download.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! AgentMux's own copy of an agent CLI that is not on npm: the pinned release
5//! file is fetched straight from the vendor's origin, checked against a
6//! SHA-256 compiled into this registry, and unpacked next to the npm installs
7//! (`<shared>/cli/<provider>/<pin>/`, same lock, same completion marker).
8//! SPEC_ISOLATED_INSTALL_FOR_NON_NPM_CLIS_2026_11_05.md.
9//!
10//! No vendor script is ever run, and a caller names only a provider id: the
11//! URL, the hash and the size all come from [`SPECS`], so the vendor's origin
12//! cannot swap the file and a request cannot point the install elsewhere.
13//! The layout is `<dir>/bin/<cli>[.exe]`; [`crate::backend::cli_install`]
14//! finds it the same way it finds an npm shim.
15
16use std::io::{Read, Write};
17use std::path::{Path, PathBuf};
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::time::Duration;
20
21use agentmux_common::DataPaths;
22use sha2::{Digest, Sha256};
23
24use crate::backend::cli_install::{self, InstallOutcome};
25
26const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
27/// No answer, or no bytes, for this long ends the download.
28const STALL_TIMEOUT: Duration = Duration::from_secs(60);
29/// The unpacked executable is far smaller than this; the cap stops an archive
30/// that claims otherwise from filling the disk.
31const MAX_EXE_BYTES: u64 = 600 * 1024 * 1024;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Archive {
35    Zip,
36    TarGz,
37    /// The download is the program itself (`exe_in_archive` is empty).
38    Raw,
39}
40
41/// One downloadable file for one platform.
42#[derive(Debug)]
43pub struct Asset {
44    /// `std::env::consts::OS`: "windows", "macos", "linux".
45    pub os: &'static str,
46    /// `std::env::consts::ARCH`: "x86_64", "aarch64".
47    pub arch: &'static str,
48    pub url: &'static str,
49    pub sha256: &'static str,
50    pub size: u64,
51    pub archive: Archive,
52    /// The executable's path inside the archive, without a leading `./`.
53    pub exe_in_archive: &'static str,
54}
55
56#[derive(Debug)]
57pub struct DownloadSpec {
58    pub provider_id: &'static str,
59    /// Equals the provider's `pinned_version`; every `url` carries it.
60    pub version: &'static str,
61    /// Every asset URL starts with this (a registry test holds it).
62    pub url_prefix: &'static str,
63    pub assets: &'static [Asset],
64}
65
66/// Grok and Muse Code are pinned below: each asset carries the hash taken for it.
67pub static SPECS: &[DownloadSpec] = &[
68// xAI publishes no checksum for Grok, so these were taken once on 2026-11-25
69// from x.ai itself and are the pin: a changed file fails the install. The Windows
70// builds are Authenticode-signed (X.AI LLC). The installer's extras
71// (`grove*` and a MinGit on Windows) are not fetched: grove falls back to the
72// git on PATH.
73DownloadSpec {
74    provider_id: "grok",
75    version: "1.0.92",
76    url_prefix: "https://x.ai/cli/grok-1.0.92-",
77    assets: &[
78        Asset {
79            os: "windows",
80            arch: "x86_64",
81            url: "https://x.ai/cli/grok-1.0.92-windows-x86_64.exe",
82            sha256: "060e51f93743b540e59c5cf9c81c0ce7b48b61c263f09235d981a6ababb1c9d7",
83            size: 187_417_232,
84            archive: Archive::Raw,
85            exe_in_archive: "",
86        },
87        Asset {
88            os: "windows",
89            arch: "aarch64",
90            url: "https://x.ai/cli/grok-1.0.92-windows-aarch64.exe",
91            sha256: "5fe563f7edb357a81d7f42022f5a23a471f43efbc62c5d595c592e0fe1c0b2f4",
92            size: 159_494_800,
93            archive: Archive::Raw,
94            exe_in_archive: "",
95        },
96        Asset {
97            os: "macos",
98            arch: "aarch64",
99            url: "https://x.ai/cli/grok-1.0.92-macos-aarch64",
100            sha256: "8b5f67b24f2cc9a4341d8e2eb7f67e3228d7d647ed04752a4f932f7133e5ab08",
101            size: 190_640_272,
102            archive: Archive::Raw,
103            exe_in_archive: "",
104        },
105        Asset {
106            os: "macos",
107            arch: "x86_64",
108            url: "https://x.ai/cli/grok-1.0.92-macos-x86_64",
109            sha256: "66b7a3ef1d647280ac649b68d89b5a3d4800b1ae9df76707c011e2d400858ea9",
110            size: 205_385_984,
111            archive: Archive::Raw,
112            exe_in_archive: "",
113        },
114        Asset {
115            os: "linux",
116            arch: "x86_64",
117            url: "https://x.ai/cli/grok-1.0.92-linux-x86_64",
118            sha256: "add4d201dbf2c0bd6077a36feb55a76939de30bae48dbb06f16b2307d38ceacb",
119            size: 208_487_936,
120            archive: Archive::Raw,
121            exe_in_archive: "",
122        },
123        Asset {
124            os: "linux",
125            arch: "aarch64",
126            url: "https://x.ai/cli/grok-1.0.92-linux-aarch64",
127            sha256: "8c74f1dc6cdc1befff6b9faada06bec4cf6759d04f2a60cdc28ece5ff696b44f",
128            size: 178_160_184,
129            archive: Archive::Raw,
130            exe_in_archive: "",
131        },
132    ],
133},
134// Meta's own manifest for this build lists a SHA-256 and size per platform; they are
135// copied here, so this is not trust on first use. The binary is the one the vendor's
136// launcher would fetch, run directly: the launcher's hourly self-update never runs,
137// and `MUSE_NO_AUTO_UPDATE=1` is set besides. The Windows build is Authenticode-signed
138// (Meta Platforms, Inc.).
139DownloadSpec {
140    provider_id: "muse",
141    version: "1.4.14-R7309.1",
142    url_prefix: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=",
143    assets: &[
144        Asset {
145            os: "windows",
146            arch: "x86_64",
147            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-x86-windows.exe",
148            sha256: "20d18c426cc26e9e4b3cc07008ec07ec97e12e466a2be8cd2797b2e0e2018382",
149            size: 435_429_624,
150            archive: Archive::Raw,
151            exe_in_archive: "",
152        },
153        Asset {
154            os: "windows",
155            arch: "aarch64",
156            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-aarch64-windows.exe",
157            sha256: "64cef76cb210de993d31478ee582ef4639bbb212df8912b74f45d40431e66e82",
158            size: 398_733_560,
159            archive: Archive::Raw,
160            exe_in_archive: "",
161        },
162        Asset {
163            os: "macos",
164            arch: "aarch64",
165            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-aarch64-macos",
166            sha256: "1c96114408acbeade9a8fb79e3b4425e5b64d50425938568aef01bdc04ce2e03",
167            size: 423_687_488,
168            archive: Archive::Raw,
169            exe_in_archive: "",
170        },
171        Asset {
172            os: "macos",
173            arch: "x86_64",
174            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-x86-macos",
175            sha256: "6da5a12d3298afba45afec929fc385b516084ed28e9504ae29354dbcdfc4089d",
176            size: 443_142_560,
177            archive: Archive::Raw,
178            exe_in_archive: "",
179        },
180        Asset {
181            os: "linux",
182            arch: "x86_64",
183            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-x86-linux",
184            sha256: "0809aac7cb58d18f5022b6d05e02aa1974683c0ec430e5f04d25b60ed17de2da",
185            size: 414_927_192,
186            archive: Archive::Raw,
187            exe_in_archive: "",
188        },
189        Asset {
190            os: "linux",
191            arch: "aarch64",
192            url: "https://lookaside.facebook.com/lookaside/muse/download/?channel=muse&version=1.4.14-R7309.1&file=muse-aarch64-linux",
193            sha256: "3dc39b8fa26f9963cc2038f2966c0932ed5a39f0f9efb39cc0266a261cbbcf76",
194            size: 371_529_960,
195            archive: Archive::Raw,
196            exe_in_archive: "",
197        },
198    ],
199},
200];
201
202/// The download install for `provider_id`, if AgentMux has one.
203pub fn download_spec(provider_id: &str) -> Option<&'static DownloadSpec> {
204    SPECS.iter().find(|s| s.provider_id == provider_id)
205}
206
207impl DownloadSpec {
208    /// The asset for this machine, or None (Grok and Muse have no build for every platform).
209    pub fn asset_for_host(&self) -> Option<&'static Asset> {
210        self.asset_for(std::env::consts::OS, std::env::consts::ARCH)
211    }
212
213    pub fn asset_for(&self, os: &str, arch: &str) -> Option<&'static Asset> {
214        self.assets.iter().find(|a| a.os == os && a.arch == arch)
215    }
216}
217
218/// `<dir>/bin/<cli>`, `.exe` on Windows.
219pub fn download_bin(dir: &Path, cli_command: &str) -> PathBuf {
220    let bin = dir.join("bin");
221    if cfg!(windows) {
222        bin.join(format!("{cli_command}.exe"))
223    } else {
224        bin.join(cli_command)
225    }
226}
227
228#[derive(Debug)]
229pub enum DownloadError {
230    Lock(std::io::Error),
231    Clear(PathBuf, std::io::Error),
232    NoSource(String),
233    NoAsset { os: &'static str, arch: &'static str },
234    Fetch(String),
235    TooLarge,
236    Short { got: u64, want: u64 },
237    HashMismatch { expected: String, actual: String },
238    Unpack(String),
239    NotRunnable(PathBuf),
240    /// A helper program (uv) failed; carries its last output lines.
241    Tool(String),
242    Mark(PathBuf, std::io::Error),
243    Cancelled,
244}
245
246impl std::fmt::Display for DownloadError {
247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248        match self {
249            DownloadError::Lock(e) => write!(f, "cannot take the CLI install lock: {e}"),
250            DownloadError::Clear(d, e) => {
251                write!(f, "cannot clear an incomplete CLI install at {}: {e}", d.display())
252            }
253            DownloadError::NoSource(p) => write!(f, "AgentMux has no download for {p}"),
254            DownloadError::NoAsset { os, arch } => {
255                write!(f, "the vendor publishes no build for {os} on {arch}")
256            }
257            DownloadError::Fetch(e) => write!(f, "download failed: {e}"),
258            DownloadError::TooLarge => write!(f, "the download is larger than the release lists it"),
259            DownloadError::Short { got, want } => {
260                write!(f, "the download stopped at {got} of {want} bytes")
261            }
262            DownloadError::HashMismatch { expected, actual } => write!(
263                f,
264                "the download does not match the checksum AgentMux expects (expected sha256 {expected}, got {actual}); nothing was installed"
265            ),
266            DownloadError::Unpack(e) => write!(f, "cannot unpack the download: {e}"),
267            DownloadError::NotRunnable(p) => {
268                write!(f, "the installed program does not run: {}", p.display())
269            }
270            DownloadError::Tool(e) => write!(f, "{e}"),
271            DownloadError::Mark(d, e) => {
272                write!(f, "cannot mark the CLI install complete at {}: {e}", d.display())
273            }
274            DownloadError::Cancelled => write!(f, "cancelled"),
275        }
276    }
277}
278
279/// Whether AgentMux installs `provider_id` itself without npm: a pinned release download.
280pub fn is_managed_install(provider_id: &str) -> bool {
281    download_spec(provider_id).is_some()
282}
283
284/// The pin a managed install of `provider_id` is keyed by.
285fn managed_version(provider_id: &str) -> Option<&'static str> {
286    download_spec(provider_id).map(|s| s.version)
287}
288
289/// Install `provider_id`'s pinned copy, **async**: take the cross-instance
290/// lock (blocking, off the runtime), reuse a finished install another instance
291/// made while this one waited, otherwise clear leftovers and install.
292/// `resolvecli`'s path; `install.start` polls the lock itself (it must stay
293/// cancellable) and calls [`install_managed_into`] once it holds it.
294pub async fn install_managed_cli(
295    paths: &DataPaths,
296    provider_id: &str,
297    on_line: &(dyn Fn(&'static str, &str) + Sync),
298    cancel: &AtomicBool,
299) -> Result<InstallOutcome, DownloadError> {
300    let version = managed_version(provider_id).ok_or_else(|| DownloadError::NoSource(provider_id.to_string()))?;
301    let provider = crate::backend::providers::get_provider(provider_id)
302        .ok_or_else(|| DownloadError::NoSource(provider_id.to_string()))?;
303    let (lock_paths, id, pin) = (paths.clone(), provider.id.to_string(), version.to_string());
304    let _guard = tokio::task::spawn_blocking(move || cli_install::lock_install(&lock_paths, &id, &pin))
305        .await
306        .map_err(|e| DownloadError::Lock(std::io::Error::other(e)))?
307        .map_err(DownloadError::Lock)?;
308    let dir = cli_install::install_dir(paths, provider.id, version);
309    if cli_install::is_valid_install(&dir, provider.cli_command) {
310        if let Some(bin) = cli_install::installed_bin(&dir, provider.cli_command) {
311            return Ok(InstallOutcome::AlreadyInstalled(bin));
312        }
313    }
314    cli_install::clear_unless_valid(&dir, provider.cli_command).map_err(|e| DownloadError::Clear(dir.clone(), e))?;
315    install_managed_into(paths, provider.id, provider.cli_command, on_line, cancel).await
316}
317
318/// Install into the install dir; the caller holds the lock and has cleared
319/// leftovers. A failure removes the partial dir, so nothing unmarked is left.
320pub async fn install_managed_into(
321    paths: &DataPaths,
322    provider_id: &str,
323    cli_command: &str,
324    on_line: &(dyn Fn(&'static str, &str) + Sync),
325    cancel: &AtomicBool,
326) -> Result<InstallOutcome, DownloadError> {
327    let spec = download_spec(provider_id).ok_or_else(|| DownloadError::NoSource(provider_id.to_string()))?;
328    install_into(paths, spec, cli_command, on_line, cancel).await
329}
330
331/// Download, verify, unpack and publish into the install dir. The caller holds
332/// the install lock and has cleared leftovers. A failure removes the partial
333/// dir, so nothing unmarked is left behind.
334pub async fn install_into(
335    paths: &DataPaths,
336    spec: &'static DownloadSpec,
337    cli_command: &str,
338    on_line: &(dyn Fn(&'static str, &str) + Sync),
339    cancel: &AtomicBool,
340) -> Result<InstallOutcome, DownloadError> {
341    let asset = spec.asset_for_host().ok_or(DownloadError::NoAsset {
342        os: std::env::consts::OS,
343        arch: std::env::consts::ARCH,
344    })?;
345    let dir = cli_install::install_dir(paths, spec.provider_id, spec.version);
346    let result = install_asset(&dir, spec, asset, cli_command, on_line, cancel).await;
347    if result.is_err() {
348        let _ = std::fs::remove_dir_all(&dir);
349    }
350    result
351}
352
353pub(crate) async fn install_asset(
354    dir: &Path,
355    spec: &DownloadSpec,
356    asset: &Asset,
357    cli_command: &str,
358    on_line: &(dyn Fn(&'static str, &str) + Sync),
359    cancel: &AtomicBool,
360) -> Result<InstallOutcome, DownloadError> {
361    let bin = download_bin(dir, cli_command);
362    std::fs::create_dir_all(bin.parent().unwrap_or(dir)).map_err(|e| DownloadError::Unpack(e.to_string()))?;
363    let archive = dir.join("download.part");
364    on_line("stdout", &format!("downloading {} {} from {}", spec.provider_id, spec.version, asset.url));
365    fetch_verified(asset, &archive, spec, on_line, cancel).await?;
366    on_line("stdout", "checksum matches; unpacking");
367    let (src, asset_exe, kind, out) = (archive.clone(), asset.exe_in_archive, asset.archive, bin.clone());
368    tokio::task::spawn_blocking(move || extract_exe(&src, kind, asset_exe, &out))
369        .await
370        .map_err(|e| DownloadError::Unpack(e.to_string()))??;
371    let _ = std::fs::remove_file(&archive);
372    let (probe, id) = (bin.clone(), spec.provider_id);
373    let version = tokio::task::spawn_blocking(move || cli_install::probe_installed(&probe, id))
374        .await
375        .ok()
376        .flatten();
377    let Some(version) = version else {
378        return Err(DownloadError::NotRunnable(bin));
379    };
380    on_line("stdout", &format!("{} {version} is installed", spec.provider_id));
381    cli_install::mark_complete(dir, spec.version).map_err(|e| DownloadError::Mark(dir.to_path_buf(), e))?;
382    Ok(InstallOutcome::Installed(bin))
383}
384
385/// Stream `asset.url` into `dest`, hashing as it arrives. Refuses more bytes
386/// than the registry lists, fewer, or a different hash.
387async fn fetch_verified(
388    asset: &Asset,
389    dest: &Path,
390    spec: &DownloadSpec,
391    on_line: &(dyn Fn(&'static str, &str) + Sync),
392    cancel: &AtomicBool,
393) -> Result<(), DownloadError> {
394    use tokio::io::AsyncWriteExt;
395    // Defence in depth: the registry's own URL must be under its own prefix.
396    if !asset.url.starts_with(spec.url_prefix) {
397        return Err(DownloadError::Fetch("the release file is outside its registered origin".into()));
398    }
399    let client = crate::http_client::builder()
400        .user_agent(format!("AgentMux/{}", env!("CARGO_PKG_VERSION")))
401        .connect_timeout(CONNECT_TIMEOUT)
402        .build()
403        .map_err(|e| DownloadError::Fetch(e.to_string()))?;
404    let mut resp = tokio::time::timeout(STALL_TIMEOUT, client.get(asset.url).send())
405        .await
406        .map_err(|_| DownloadError::Fetch("the server did not answer".into()))?
407        .and_then(|r| r.error_for_status())
408        .map_err(|e| DownloadError::Fetch(e.to_string()))?;
409    let mut out = tokio::fs::File::create(dest).await.map_err(|e| DownloadError::Fetch(e.to_string()))?;
410    let mut hasher = Sha256::new();
411    let mut got = 0u64;
412    let mut shown = 0u64;
413    loop {
414        if cancel.load(Ordering::Relaxed) {
415            return Err(DownloadError::Cancelled);
416        }
417        let chunk = tokio::time::timeout(STALL_TIMEOUT, resp.chunk())
418            .await
419            .map_err(|_| DownloadError::Fetch("the download stalled".into()))?
420            .map_err(|e| DownloadError::Fetch(e.to_string()))?;
421        let Some(chunk) = chunk else { break };
422        got += chunk.len() as u64;
423        if got > asset.size {
424            return Err(DownloadError::TooLarge);
425        }
426        hasher.update(&chunk);
427        out.write_all(&chunk).await.map_err(|e| DownloadError::Fetch(e.to_string()))?;
428        let tenth = got * 10 / asset.size.max(1);
429        if tenth > shown {
430            shown = tenth;
431            on_line("stdout", &format!("downloaded {}%", tenth * 10));
432        }
433    }
434    out.flush().await.map_err(|e| DownloadError::Fetch(e.to_string()))?;
435    drop(out);
436    verify_download(got, hasher.finalize().as_slice(), asset)
437}
438
439/// The size and the hash of what arrived against the registry's.
440fn verify_download(got: u64, digest: &[u8], asset: &Asset) -> Result<(), DownloadError> {
441    if got != asset.size {
442        return Err(DownloadError::Short { got, want: asset.size });
443    }
444    let actual = hex::encode(digest);
445    if !actual.eq_ignore_ascii_case(asset.sha256) {
446        return Err(DownloadError::HashMismatch { expected: asset.sha256.to_string(), actual });
447    }
448    Ok(())
449}
450
451/// Copy the one executable named `exe_in_archive` out of `archive` into `out`
452/// (write-then-rename). Nothing else in the archive is written, so no entry
453/// name can place a file anywhere.
454fn extract_exe(archive: &Path, kind: Archive, exe_in_archive: &str, out: &Path) -> Result<(), DownloadError> {
455    let part = out.with_extension("part");
456    let file = std::fs::File::open(archive).map_err(|e| DownloadError::Unpack(e.to_string()))?;
457    let found = match kind {
458        Archive::Zip => copy_from_zip(file, exe_in_archive, &part),
459        Archive::TarGz => copy_from_tar_gz(file, exe_in_archive, &part),
460        Archive::Raw => copy_capped(&mut { file }, &part).map(|()| true),
461    };
462    let found = found.inspect_err(|_| {
463        let _ = std::fs::remove_file(&part);
464    })?;
465    if !found {
466        let _ = std::fs::remove_file(&part);
467        return Err(DownloadError::Unpack(format!("{exe_in_archive} is not in the archive")));
468    }
469    #[cfg(unix)]
470    {
471        use std::os::unix::fs::PermissionsExt;
472        std::fs::set_permissions(&part, std::fs::Permissions::from_mode(0o755))
473            .map_err(|e| DownloadError::Unpack(e.to_string()))?;
474    }
475    std::fs::rename(&part, out).map_err(|e| DownloadError::Unpack(e.to_string()))
476}
477
478fn normalize(name: &str) -> String {
479    name.replace('\\', "/").trim_start_matches("./").to_string()
480}
481
482fn copy_capped(src: &mut dyn Read, dest: &Path) -> Result<(), DownloadError> {
483    let mut out = std::fs::File::create(dest).map_err(|e| DownloadError::Unpack(e.to_string()))?;
484    let copied = std::io::copy(&mut src.take(MAX_EXE_BYTES + 1), &mut out).map_err(|e| DownloadError::Unpack(e.to_string()))?;
485    if copied > MAX_EXE_BYTES {
486        return Err(DownloadError::Unpack("the program in the archive is larger than allowed".into()));
487    }
488    out.flush().map_err(|e| DownloadError::Unpack(e.to_string()))
489}
490
491fn copy_from_zip(file: std::fs::File, want: &str, dest: &Path) -> Result<bool, DownloadError> {
492    let mut zip = zip::ZipArchive::new(file).map_err(|e| DownloadError::Unpack(e.to_string()))?;
493    for i in 0..zip.len() {
494        let mut entry = zip.by_index(i).map_err(|e| DownloadError::Unpack(e.to_string()))?;
495        if entry.is_file() && normalize(entry.name()) == want {
496            copy_capped(&mut entry, dest)?;
497            return Ok(true);
498        }
499    }
500    Ok(false)
501}
502
503fn copy_from_tar_gz(file: std::fs::File, want: &str, dest: &Path) -> Result<bool, DownloadError> {
504    let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
505    for entry in tar.entries().map_err(|e| DownloadError::Unpack(e.to_string()))? {
506        let mut entry = entry.map_err(|e| DownloadError::Unpack(e.to_string()))?;
507        if !entry.header().entry_type().is_file() {
508            continue;
509        }
510        let name = entry.path().map_err(|e| DownloadError::Unpack(e.to_string()))?.to_string_lossy().into_owned();
511        if normalize(&name) == want {
512            copy_capped(&mut entry, dest)?;
513            return Ok(true);
514        }
515    }
516    Ok(false)
517}
518
519#[cfg(test)]
520#[path = "cli_download_tests.rs"]
521mod tests;