lean-ctx 3.12.13

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx computer diag`: the fixed menu a grantee reaches over SSH on a
//! `weave_host` computer (sshd `ForceCommand`, and the forced `command=` of
//! every key). The request comes from `SSH_ORIGINAL_COMMAND` (or the
//! arguments when run locally) and is matched word for word: no shell, no
//! free-form argument, nothing secret printed.

use std::path::Path;

use super::{STATUS_FILE, UNIT};

const MENU: &str = "This cloud computer: diagnostics\n\n\
Usage: ssh <user>@<computer> <command>\n\n\
  status   The service, the meter, the users, disk and memory\n\
  help     This menu\n";

/// Run the menu; the exit code of the process.
pub(crate) fn run(args: &[String]) -> i32 {
    let request = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_else(|_| args.join(" "));
    let words: Vec<&str> = request.split_whitespace().collect();
    match words.as_slice() {
        [] | ["status"] => {
            print!("{}", status_text());
            0
        }
        ["help" | "--help" | "-h"] => {
            print!("{MENU}");
            0
        }
        _ => {
            eprint!("Unknown diagnostic command.\n\n{MENU}");
            2
        }
    }
}

fn status_text() -> String {
    let mut out = String::from("This cloud computer\n");
    out.push_str(&format!("  service    {}\n", service_state()));
    let owner = super::service_uid();
    match owner.and_then(|uid| read_status(Path::new(STATUS_FILE), uid)) {
        Some(status) => out.push_str(&status),
        None => out.push_str("  status     not written yet (service starting or stopped)\n"),
    }
    if let Some(disk) = disk_line() {
        out.push_str(&disk);
    }
    if let Some(memory) = memory_line() {
        out.push_str(&memory);
    }
    out
}

fn service_state() -> String {
    let out = std::process::Command::new("/usr/bin/systemctl")
        .args(["is-active", UNIT])
        .env_clear()
        .stdin(std::process::Stdio::null())
        .output();
    match out {
        Ok(out) => {
            let word: String = String::from_utf8_lossy(&out.stdout)
                .trim()
                .chars()
                .filter(char::is_ascii_alphabetic)
                .take(20)
                .collect();
            if word.is_empty() {
                "unknown".into()
            } else {
                word
            }
        }
        Err(_) => "unknown".into(),
    }
}

/// The lines of the status file the agent writes (owned by its service
/// user, not writable by others, no secrets).
fn read_status(path: &Path, owner: u32) -> Option<String> {
    let bytes = super::secret_file::read_checked(
        path,
        owner,
        super::secret_file::Exposure::Readable,
        16 * 1024,
    )
    .ok()?;
    let status: super::Status = serde_json::from_slice(&bytes).ok()?;
    Some(status.lines())
}

#[cfg(unix)]
fn disk_line() -> Option<String> {
    let root = std::ffi::CString::new("/").ok()?;
    // SAFETY: a zeroed statvfs is a valid out-parameter.
    let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
    // SAFETY: `root` is NUL-terminated and `st` a valid pointer.
    if unsafe { libc::statvfs(root.as_ptr(), &raw mut st) } != 0 {
        return None;
    }
    // The field widths differ between platforms.
    #[allow(clippy::unnecessary_cast, clippy::cast_lossless)]
    let (block, blocks, avail) = (st.f_frsize as u64, st.f_blocks as u64, st.f_bavail as u64);
    let (total, free) = (
        blocks.saturating_mul(block.max(1)),
        avail.saturating_mul(block.max(1)),
    );
    Some(format!(
        "  disk       {} free of {}\n",
        gib(free),
        gib(total)
    ))
}

#[cfg(not(unix))]
fn disk_line() -> Option<String> {
    None
}

fn memory_line() -> Option<String> {
    let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
    let field = |name: &str| {
        meminfo.lines().find_map(|l| {
            l.strip_prefix(name)?
                .trim()
                .trim_end_matches("kB")
                .trim()
                .parse::<u64>()
                .ok()
        })
    };
    let total = field("MemTotal:")?;
    let available = field("MemAvailable:")?;
    Some(format!(
        "  memory     {} available of {}\n",
        gib(available * 1024),
        gib(total * 1024)
    ))
}

fn gib(bytes: u64) -> String {
    #[allow(clippy::cast_precision_loss)]
    let gib = bytes as f64 / (1024.0 * 1024.0 * 1024.0);
    format!("{gib:.1} GiB")
}

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

    #[test]
    fn sizes_read_in_gib() {
        assert_eq!(gib(0), "0.0 GiB");
        assert_eq!(gib(3 * 1024 * 1024 * 1024 / 2), "1.5 GiB");
    }
}