troupekit-kit 0.4.0

Ergonomic API for the Troupekit LLM agent framework: one builder or one macro per agent, tool and graph.
Documentation
use crate::error::KitError;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use troupekit_trace::{trace, Trace};

const MAX_LAW_FILE_BYTES: u64 = 1024 * 1024;
const MAX_INLINE_LAW_BYTES: usize = 64 * 1024;
const MAX_LAWS: usize = 64;

/// The laws attached to an agent or graph, checked at `build`.
/// 0.2 stores and validates them; no run proves them yet. `auto` asks
/// the verifier to also derive laws from the code, and defaults to `true`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Laws {
    paths: Vec<PathBuf>,
    inline: Vec<String>,
    auto: bool,
}

impl Laws {
    /// Returns the law files, as absolute paths resolved at `build`.
    /// Each is an existing `.bend` file of at most 1 MiB of UTF-8. Paths
    /// are trusted host input: symlinks and any directory are allowed.
    pub fn paths(&self) -> &[PathBuf] {
        &self.paths
    }

    /// Returns the inline laws in the order they were added.
    /// Each is non-blank, at most 64 KiB and free of NUL bytes.
    /// The text is kept exactly as given.
    pub fn inline(&self) -> &[String] {
        &self.inline
    }

    /// Reports whether laws derived from the code are wanted.
    /// Set with `.auto_laws(..)`; `true` unless turned off.
    /// 0.2 records the choice only.
    pub fn auto(&self) -> bool {
        self.auto
    }

    pub(crate) fn check(
        owner: &str,
        paths: &[PathBuf],
        inline: &[String],
        auto: bool,
    ) -> Result<Laws, KitError> {
        let fail = |m: String| KitError::config(owner, m);
        let total = paths.len() + inline.len();
        if total > MAX_LAWS {
            return Err(fail(format!("takes at most {MAX_LAWS} laws, got {total}")));
        }
        let mut resolved = Vec::with_capacity(paths.len());
        for path in paths {
            resolved.push(
                read_checked(path, "bend", MAX_LAW_FILE_BYTES)
                    .map(|(absolute, _)| absolute)
                    .map_err(|m| fail(format!("law file `{}` {m}", path.display())))?,
            );
        }
        for (i, law) in inline.iter().enumerate() {
            let n = i + 1;
            if law.trim().is_empty() {
                return Err(fail(format!("inline law {n} is blank")));
            }
            if law.len() > MAX_INLINE_LAW_BYTES {
                return Err(fail(format!("inline law {n} is over 64 KiB")));
            }
            if law.contains('\0') {
                return Err(fail(format!("inline law {n} contains a NUL byte")));
            }
        }
        assert_eq!(resolved.len(), paths.len());
        for path in &resolved {
            let shown = path.display().to_string();
            trace!(
                Trace::Laws,
                "law.load",
                owner = owner,
                source = "file",
                path = shown,
                auto = auto,
            );
        }
        for law in inline {
            trace!(
                Trace::Laws,
                "law.load",
                owner = owner,
                source = "inline",
                bytes = law.len(),
                auto = auto,
            );
        }
        Ok(Laws {
            paths: resolved,
            inline: inline.to_vec(),
            auto,
        })
    }
}

impl Default for Laws {
    fn default() -> Self {
        Laws {
            paths: Vec::new(),
            inline: Vec::new(),
            auto: true,
        }
    }
}

/// `O_NONBLOCK` on the BSD family, so opening a FIFO returns at once.
#[cfg(any(
    target_os = "macos",
    target_os = "ios",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly"
))]
const O_NONBLOCK: i32 = 0x0004;
/// `O_NONBLOCK` on Linux and Android for every architecture except the
/// MIPS, SPARC, Alpha and PA-RISC families, which number it differently.
#[cfg(all(
    any(target_os = "linux", target_os = "android"),
    any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "arm",
        target_arch = "aarch64",
        target_arch = "riscv64",
        target_arch = "powerpc",
        target_arch = "powerpc64",
        target_arch = "s390x",
        target_arch = "loongarch64"
    )
))]
const O_NONBLOCK: i32 = 0o4000;
/// No known `O_NONBLOCK` value for this target, so open stays blocking;
/// the opened handle is still checked to be a regular file.
#[cfg(all(
    unix,
    not(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    )),
    not(all(
        any(target_os = "linux", target_os = "android"),
        any(
            target_arch = "x86",
            target_arch = "x86_64",
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "riscv64",
            target_arch = "powerpc",
            target_arch = "powerpc64",
            target_arch = "s390x",
            target_arch = "loongarch64"
        )
    ))
))]
const O_NONBLOCK: i32 = 0;

/// Opens a law file for reading without waiting on a FIFO, as the context
/// loader does; the caller then checks the handle is a regular file.
/// Input: the absolute path. Output: the file or the I/O error.
fn open_nonblocking(path: &Path) -> std::io::Result<std::fs::File> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
    options.open(path)
}

/// Checks and reads one user-named file: non-empty path, no `..`, the
/// given extension, a regular file of at most `max_bytes`, valid UTF-8.
/// Returns the absolute path and the text, or the reason it was refused.
/// `max_bytes` must be a whole number of MiB.
pub(crate) fn read_checked(
    path: &Path,
    extension: &str,
    max_bytes: u64,
) -> Result<(PathBuf, String), String> {
    assert!(max_bytes > 0 && max_bytes.is_multiple_of(1024 * 1024));
    let too_big = || format!("is over {} MiB", max_bytes / (1024 * 1024));
    if path.as_os_str().is_empty() {
        return Err("is empty".into());
    }
    if path.components().any(|c| c == Component::ParentDir) {
        return Err("must not contain `..`".into());
    }
    if path.extension().is_none_or(|e| e != extension) {
        return Err(format!("must be a .{extension} file"));
    }
    let absolute = std::path::absolute(path).map_err(|e| format!("cannot be resolved: {e}"))?;
    assert!(absolute.is_absolute(), "std::path::absolute returns an absolute path");
    let file = match open_nonblocking(&absolute) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err("does not exist".into()),
        Err(e) => return Err(format!("cannot be read: {e}")),
    };
    let meta = file.metadata().map_err(|e| format!("cannot be read: {e}"))?;
    if !meta.is_file() {
        return Err("is not a regular file".into());
    }
    if meta.len() > max_bytes {
        return Err(too_big());
    }
    let bytes = read_bounded(file, max_bytes).map_err(|e| e.unwrap_or_else(too_big))?;
    let text = String::from_utf8(bytes).map_err(|_| "is not valid UTF-8".to_string())?;
    Ok((absolute, text))
}

/// Reads at most `max_bytes` plus one byte, so a file that grew after its
/// size check is refused without reading it all. Input: the opened file
/// and the cap. Output: the bytes, `Err(None)` past the cap, or the I/O
/// failure as text.
fn read_bounded(file: impl Read, max_bytes: u64) -> Result<Vec<u8>, Option<String>> {
    let mut bytes = Vec::new();
    file.take(max_bytes + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| Some(format!("cannot be read: {e}")))?;
    if bytes.len() as u64 > max_bytes {
        return Err(None);
    }
    Ok(bytes)
}

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

    #[test]
    fn read_stops_one_byte_past_the_cap() {
        assert_eq!(read_bounded(std::io::repeat(b'a'), MAX_LAW_FILE_BYTES).unwrap_err(), None);
        let exact = vec![b'a'; MAX_LAW_FILE_BYTES as usize];
        assert_eq!(read_bounded(exact.as_slice(), MAX_LAW_FILE_BYTES).unwrap().len(), exact.len());
    }

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        all(
            any(target_os = "linux", target_os = "android"),
            any(
                target_arch = "x86",
                target_arch = "x86_64",
                target_arch = "arm",
                target_arch = "aarch64",
                target_arch = "riscv64",
                target_arch = "powerpc",
                target_arch = "powerpc64",
                target_arch = "s390x",
                target_arch = "loongarch64"
            )
        )
    ))]
    #[test]
    fn a_named_pipe_law_file_is_refused_without_blocking() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = dir.path().join("rules.bend");
        let made = std::process::Command::new("mkfifo").arg(&fifo).status().unwrap();
        assert!(made.success());
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || tx.send(read_checked(&fifo, "bend", MAX_LAW_FILE_BYTES).map(|(p, _)| p)).unwrap());
        let result = rx
            .recv_timeout(std::time::Duration::from_secs(10))
            .expect("read_checked blocked on a named pipe");
        assert_eq!(result, Err("is not a regular file".to_string()));
    }

    #[cfg(windows)]
    #[test]
    fn drive_relative_path_resolves_to_an_absolute_one() {
        let dir = tempfile::tempdir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        std::fs::write(dir.path().join("rules.bend"), "law").unwrap();
        let drive = dir.path().components().next().unwrap().as_os_str().to_owned();
        let mut relative = std::ffi::OsString::from(drive);
        relative.push("rules.bend");
        let (resolved, _) = read_checked(&PathBuf::from(relative), "bend", MAX_LAW_FILE_BYTES).unwrap();
        assert!(resolved.is_absolute(), "{}", resolved.display());
        assert!(resolved.ends_with("rules.bend"), "{}", resolved.display());
    }
}