mahbot 0.10.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
//! Install and update the Bot API server binary. The binary is the product's own build of
//! `tdlib/telegram-bot-api`, published in a release stream of its own: prereleases tagged
//! `tgapi-v<version>` in the product's repository. Prereleases are what keeps the product's updater
//! untouched — it reads `releases/latest` and `version.txt`, which never point at one — while
//! release assets stay downloadable by a plain HTTP client with no credentials. Everything after
//! the download is the shared managed-binary machinery Bun and chrome-use already use: SHA-256 from
//! the release's `SHA256SUMS`, a streamed verified download, one file extracted out of the archive,
//! an atomic swap into place. The owner never fetches, unpacks or replaces anything by hand. Taking
//! the install away — the way back to the cloud — is the whole server root
//! ([`super::server::remove_state`]), binary included.

use std::path::PathBuf;

use semver::Version;

const TAG_PREFIX: &str = "tgapi-v";

/// Test hook: a releases listing that answers in GitHub's shape instead of the real one. The
/// product's own update channel is a different contract and is never read or written here.
const RELEASES_URL_ENV: &str = "MAHBOT_TGAPI_RELEASES_URL";

fn releases_url() -> String {
    format!(
        "https://api.github.com/repos/{}/releases",
        crate::util::managed_bin::release_repo()
    )
}

const fn file_name() -> &'static str {
    if cfg!(windows) {
        "telegram-bot-api.exe"
    } else {
        "telegram-bot-api"
    }
}

/// Where the binary lives: beside the server's own state, inside the product's configuration
/// directory — never in the daemon's temp root, which is swept.
pub(super) fn binary_path() -> Option<PathBuf> {
    Some(
        crate::config::default_config_dir()
            .ok()?
            .join("telegram-bot-api")
            .join("bin")
            .join(file_name()),
    )
}

pub(super) fn present() -> bool {
    binary_path().is_some_and(|path| crate::util::is_executable(&path))
}

pub(super) struct Release {
    tag: String,
    pub(super) version: Version,
    archive_url: String,
    sums_url: Option<String>,
}

/// This host's asset tag (`telegram-bot-api-<version>-<os>-<arch>`), or the platform it is not
/// published for.
///
/// Windows has one artifact: x64. Windows 11 on ARM emulates x64 user-mode processes — file, socket
/// and child-process behaviour included — so the same artifact serves both architectures and there
/// is no unsupported state.
fn asset_platform() -> Result<(&'static str, &'static str), String> {
    let (os, arch) = crate::util::managed_bin::host_os_arch()?;
    let arch = if os == "windows" && arch == "aarch64" {
        "x86_64"
    } else {
        arch
    };
    Ok((os, arch))
}

/// The newest release on offer for this host.
///
/// Pages are read until one carries a server build. The listing is ordered by creation date, so the
/// newest build is on the earliest page that holds one.
pub(super) async fn latest() -> Result<Release, String> {
    let (os, arch) = asset_platform()?;
    let base = std::env::var(RELEASES_URL_ENV).unwrap_or_else(|_| releases_url());
    for page in 1..=crate::util::managed_bin::LISTING_PAGES {
        // A body that is not a listing offers this stream nothing, exactly as an empty page does.
        let listing =
            crate::util::managed_bin::release_page(&base, page, "the newest server release")
                .await?
                .unwrap_or_default();
        if let Some(release) = newest_for(&listing, os, arch) {
            return Ok(release);
        }
        if listing.len() < crate::util::managed_bin::LISTING_PAGE_SIZE {
            break;
        }
    }
    Err(format!("no server release is published for {os}-{arch}"))
}

fn parse_version(text: &str) -> Option<Version> {
    crate::util::managed_bin::parse_short_version(text.strip_prefix(TAG_PREFIX)?)
}

fn newest_for(listing: &[serde_json::Value], os: &str, arch: &str) -> Option<Release> {
    let extension = if os == "windows" { "zip" } else { "tar.gz" };
    listing
        .iter()
        .filter_map(|release| {
            let tag = release["tag_name"].as_str()?;
            let version = parse_version(tag)?;
            let assets = release["assets"].as_array()?;
            let asset = |suffix: &str| {
                assets.iter().find_map(|asset| {
                    let name = asset["name"].as_str()?;
                    name.ends_with(suffix)
                        .then(|| asset["browser_download_url"].as_str().map(String::from))
                        .flatten()
                })
            };
            let archive_url = asset(&format!("-{os}-{arch}.{extension}"))?;
            Some(Release {
                tag: tag.to_string(),
                version,
                archive_url,
                sums_url: asset("SHA256SUMS"),
            })
        })
        .max_by(|a, b| a.version.cmp(&b.version))
}

/// Download, verify, extract and atomically place `release`'s archive. Returns the release version
/// now installed. Every failure names the operation and a reason with no local path and no URL,
/// because it is recorded and shown verbatim.
pub(super) async fn install(release: Release) -> Result<Version, String> {
    use crate::util::http::{DownloadSizeCheck, download_verified};

    let dest = binary_path().ok_or_else(|| "the install directory is unavailable".to_string())?;
    let file = file_name();
    let client = crate::util::managed_bin::download_client()?;
    let hash = match &release.sums_url {
        Some(url) => {
            let body =
                crate::util::managed_bin::fetch_sha256_sums(url, "the checksum list").await?;
            let asset = release.archive_url.rsplit('/').next().unwrap_or_default();
            crate::util::managed_bin::sha256_for(&body, asset)
                .ok_or_else(|| "the release publishes no checksum for this artifact".to_string())?
        }
        None => return Err("the release publishes no checksum list".to_string()),
    };

    let work = tempfile::tempdir().map_err(|e| {
        format!(
            "the download's temporary directory could not be created ({})",
            e.kind()
        )
    })?;
    let archive = work
        .path()
        .join(release.archive_url.rsplit('/').next().unwrap_or("server"));
    download_verified(
        client,
        &release.archive_url,
        &archive,
        &hash,
        None,
        DownloadSizeCheck::None,
        |_, _| {},
    )
    .await
    .map_err(|e| {
        format!(
            "the server release could not be downloaded: {}",
            crate::util::managed_bin::download_reason(&e)
        )
    })?;

    let fresh = if archive.extension().and_then(|e| e.to_str()) == Some("zip") {
        crate::util::managed_bin::extract_single_file_zip(&archive, work.path(), file)?
    } else {
        crate::util::managed_bin::extract_single_file_tar_gz(&archive, work.path(), file)?
    };
    // Proven before it replaces a working copy: a checksum-valid artifact can still be unable to
    // run (a missing library, the wrong runtime), and placing it would leave nothing but a copy
    // that fails every attempt — with no version to compare, the update check would never repair it
    // either.
    if super::server::reported_version_at(&fresh).await.is_none() {
        return Err("the downloaded server binary could not run".to_string());
    }
    crate::util::managed_bin::place_extracted(&fresh, &dest)?;
    tracing::info!(
        version = %release.version,
        tag = %release.tag,
        "telegram-bot-api: installed"
    );
    Ok(release.version)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn listing() -> Vec<serde_json::Value> {
        serde_json::json!([
            {
                "tag_name": "tgapi-v10.1",
                "assets": [
                    {"name": "telegram-bot-api-10.1-linux-x86_64.tar.gz",
                     "browser_download_url": "https://example.test/10.1/linux"},
                    {"name": "SHA256SUMS", "browser_download_url": "https://example.test/10.1/sums"}
                ]
            },
            {
                "tag_name": "tgapi-v10.3",
                "assets": [
                    {"name": "telegram-bot-api-10.3-linux-x86_64.tar.gz",
                     "browser_download_url": "https://example.test/10.3/linux"},
                    {"name": "SHA256SUMS", "browser_download_url": "https://example.test/10.3/sums"}
                ]
            },
            {
                "tag_name": "tgapi-v10.4",
                "assets": [
                    {"name": "telegram-bot-api-10.4-windows-x86_64.zip",
                     "browser_download_url": "https://example.test/10.4/windows"},
                    {"name": "SHA256SUMS", "browser_download_url": "https://example.test/10.4/sums"}
                ]
            },
            {
                "tag_name": "v0.8.0",
                "assets": [
                    {"name": "mahbot-0.8.0-linux-x86_64.tar.gz",
                     "browser_download_url": "https://example.test/mahbot/linux"}
                ]
            }
        ])
        .as_array()
        .expect("the listing is an array")
        .clone()
    }

    #[test]
    fn the_newest_release_for_the_host_wins_and_the_product_channel_is_ignored() {
        let release = newest_for(&listing(), "linux", "x86_64").expect("a release");
        assert_eq!(release.version, Version::new(10, 3, 0));
        assert_eq!(release.archive_url, "https://example.test/10.3/linux");
        assert_eq!(
            release.sums_url.as_deref(),
            Some("https://example.test/10.3/sums")
        );
    }

    #[test]
    fn a_platform_without_an_artifact_is_not_served_by_another_one() {
        assert!(newest_for(&listing(), "macos", "aarch64").is_none());
        assert!(newest_for(&[], "linux", "x86_64").is_none());
    }
}