neosian 3.0.0

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The inputs a plan is built from, held to their grammar: where a harness
//! is found, where a child may work, and the model, session and prompt it
//! is given.

use std::path::{Path, PathBuf};

/// The harness executable on `path`, absolute PATH entries only: a
/// relative entry would resolve against the child's directory.
pub fn which(program: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
    let path = path?;
    std::env::split_paths(path)
        .filter(|entry| entry.is_absolute())
        .flat_map(|entry| {
            let plain = entry.join(program);
            let windows = ["exe", "cmd", "bat"].map(|ext| plain.with_extension(ext));
            std::iter::once(plain).chain(windows)
        })
        .find(|candidate| executable(candidate))
}

pub fn executable(path: &Path) -> bool {
    if !path.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        path.metadata()
            .is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Why a child may not work in a directory.
#[derive(Debug, PartialEq, Eq)]
pub enum Placed {
    /// The given directory does not exist.
    Missing,
    /// The directory is neither this server's own nor listed.
    NotAllowed(PathBuf),
    /// This server's directory is not strictly below the home directory,
    /// or there is no home: a directory must be listed and named.
    NeedListed,
}

/// Where a child may work (§40.50, amended by #430 and #431): the server's
/// own directory when it lies strictly below the home directory, or one the
/// person listed, compared canonically. Anywhere else, or with no home, a
/// listed directory must be named. `given` is resolved against the
/// server's directory.
pub fn place(
    given: Option<&str>,
    server: &Path,
    home: Option<&Path>,
    listed: &[PathBuf],
) -> Result<PathBuf, Placed> {
    let canonical = |path: &Path| path.canonicalize().ok().filter(|path| path.is_dir());
    let own = canonical(server);
    let home = home
        .filter(|home| !home.as_os_str().is_empty())
        .and_then(canonical);
    let own_ok = own.as_ref().filter(|own| {
        home.as_ref()
            .is_some_and(|home| own.starts_with(home) && *own != home)
    });
    let Some(given) = given else {
        return own_ok.cloned().ok_or(Placed::NeedListed);
    };
    let path = canonical(&server.join(given)).ok_or(Placed::Missing)?;
    if own_ok == Some(&path) || listed.contains(&path) {
        return Ok(path);
    }
    Err(Placed::NotAllowed(path))
}

/// The home directory from `HOME`, None when unset or empty.
pub fn home() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .filter(|home| !home.is_empty())
        .map(PathBuf::from)
}

/// A Codex server name an override can address as a bare TOML key.
pub fn bare_key(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_-".contains(c))
}

/// A model name in a conservative character set (§40.50 item 8), never
/// one a harness's parser could take for an option.
pub fn model_ok(model: &str) -> bool {
    (1..=128).contains(&model.len())
        && model.starts_with(|c: char| c.is_ascii_alphanumeric())
        && model
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "._:/@#+-".contains(c))
}

/// A harness session ID neosian will put on a command line: the
/// conversation-ID grammar, starting with a letter or digit.
pub fn session_ok(session: &str) -> bool {
    crate::conversation::ids::parse_conversation_id(session).is_ok()
        && session.starts_with(|c: char| c.is_ascii_alphanumeric())
}

pub const PROMPT_BYTES: usize = 256 * 1024;

pub fn prompt_ok(prompt: &str) -> bool {
    (1..=PROMPT_BYTES).contains(&prompt.len())
}