neosian 3.0.3

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! Pi's state for one child (X5a). Pi keeps its sign-in, settings and
//! sessions in one agent directory, `PI_CODING_AGENT_DIR` or `~/.pi/agent`,
//! which the policy keeps unwritable like every client's own directory.
//! Each child gets a session directory of its own, made by the watcher from
//! trusted paths before launch: `neosian-harness/<session>` below the
//! agent directory's `sessions`, or below `PI_CODING_AGENT_SESSION_DIR`
//! when that names a place strictly below the home directory. That
//! directory is the child's only writable Pi state, in both modes; Pi
//! writes its session file there as `<timestamp>_<session>.jsonl` (its
//! `SessionManager`, 1.7.0). A turn that continues the session opens that
//! exact file, which must be the only one naming the session, a regular
//! file with one link, whose header names the session and the child's
//! directory: Pi would otherwise create a new session at an absent path.
//! Pi also takes a lock on its credential store, `auth.json.lock`, to read
//! it; that directory is the one other name it may make (X7a), and only
//! while `auth.json` is no link and the lock's name holds nothing but a
//! real directory; otherwise the child is refused (X7c Y5).

use std::ffi::OsString;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};

use serde_json::Value;

use super::super::adapter::Agent;
use super::super::pi::Paths;
use super::super::text::say;
use super::policy::{Rule, resolve, text};
use super::state;

/// The variable that moves Pi's session storage.
pub const SESSION_VAR: &str = "PI_CODING_AGENT_SESSION_DIR";
/// The directory below the session base that holds the children's sessions.
const CHILDREN: &str = "neosian-harness";
/// The longest session header read.
const HEADER_BYTES: u64 = 64 * 1024;

fn outside(path: &Path) -> String {
    say(
        "sandbox_state",
        &[("agent", "pi"), ("path", &path.display().to_string())],
    )
}

/// Pi's agent directory, as the turn names it to Pi.
pub fn agent_dir(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
    state::root(Agent::Pi, home, var).ok()
}

/// Where Pi's sessions go: the moved base when the variable names an
/// absolute place strictly below `home` (canonical), else `sessions` in the
/// agent directory. A moved base elsewhere refuses the child.
pub fn base(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
    let moved = var(SESSION_VAR)
        .map(PathBuf::from)
        .filter(|value| value.is_absolute());
    let Some(moved) = moved else {
        return Ok(state::root(Agent::Pi, home, var)?.join("sessions"));
    };
    resolve(&moved)
        .filter(|base| base.starts_with(home) && base != home)
        .ok_or_else(|| outside(&moved))
}

/// The moved session base, as one of the places no child writes beyond its
/// own state.
pub fn moved(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
    var(SESSION_VAR)?;
    base(home, var).ok()
}

/// The child's session directory, which must be where its name says: no
/// link on the way leads elsewhere.
pub fn session_dir(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    session: &str,
) -> Result<PathBuf, String> {
    let wanted = base(home, var)?.join(CHILDREN).join(session);
    let ok = uuid::Uuid::parse_str(session).is_ok();
    resolve(&wanted)
        .filter(|found| ok && *found == wanted)
        .ok_or_else(|| outside(&wanted))
}

/// The policy's allowance for the child's Pi state.
pub fn rules(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    session: Option<&str>,
) -> Result<Vec<Rule>, String> {
    let session = session.ok_or_else(|| outside(home))?;
    let own = Rule::Subpath(text(&session_dir(home, var, session)?)?);
    Ok(vec![own, Rule::Literal(text(&auth_lock(home, var)?)?)])
}

/// The lock Pi takes on its credential store even to read it (X7a, seen
/// live: "Credential store read failed ... EPERM ... mkdir
/// '<agent>/auth.json.lock'"): a directory beside `auth.json`, named after
/// the file it resolves to, made and removed again. The file itself stays
/// unwritable. Exactly `auth.json.lock` in the validated agent directory is
/// allowed (X7c Y5): a credential file that is a link (whose lock Pi would
/// name after its target), or a file or link at the lock's name, refuses
/// the child, which would otherwise fail on Pi's own EPERM.
fn auth_lock(home: &Path, var: &dyn Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
    let agent = state::root(Agent::Pi, home, var)?;
    let (file, lock) = (agent.join("auth.json"), agent.join("auth.json.lock"));
    if file
        .symlink_metadata()
        .is_ok_and(|found| found.file_type().is_symlink())
    {
        return Err(say(
            "pi_auth_lock",
            &[("path", &file.display().to_string())],
        ));
    }
    match lock.symlink_metadata() {
        Ok(found) if !found.is_dir() => Err(say(
            "pi_auth_lock",
            &[("path", &lock.display().to_string())],
        )),
        _ => Ok(lock),
    }
}

/// The paths a Pi turn runs with, made ready by the watcher: a new
/// session's directory made, empty and its own; a continued session's file
/// found exactly.
pub fn prepare(
    home: &Path,
    var: &dyn Fn(&str) -> Option<OsString>,
    session: &str,
    resume: bool,
    directory: &Path,
) -> Result<Paths, String> {
    let agent_dir = state::root(Agent::Pi, home, var)?;
    let session_dir = session_dir(home, var, session)?;
    if text(&agent_dir).and(text(&session_dir)).is_err() {
        return Err(outside(&session_dir));
    }
    let file = if resume {
        Some(session_file(&session_dir, session, directory)?)
    } else {
        make(&session_dir)?;
        None
    };
    Ok(Paths {
        agent_dir,
        session_dir,
        file,
    })
}

/// The session directory made new, mode 0700, its parents made as needed;
/// none of them may be a link.
fn make(dir: &Path) -> Result<(), String> {
    use std::os::unix::fs::DirBuilderExt;
    let shown = dir.display().to_string();
    let failed = |error: std::io::Error| {
        say(
            "pi_session_dir",
            &[("directory", &shown), ("error", &error.to_string())],
        )
    };
    let parent = dir.parent().ok_or_else(|| outside(dir))?;
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(parent)
        .map_err(failed)?;
    // Made by neosian from canonical parts; a link put there since is refused.
    if resolve(parent).as_deref() != Some(parent) {
        return Err(outside(dir));
    }
    std::fs::DirBuilder::new()
        .mode(0o700)
        .create(dir)
        .map_err(failed)
}

/// What a session file's first line says, when it is a header.
fn header(path: &Path) -> Option<Value> {
    let file = std::fs::File::open(path).ok()?;
    let mut line = Vec::new();
    BufReader::new(file.take(HEADER_BYTES))
        .read_until(b'\n', &mut line)
        .ok()?;
    serde_json::from_slice::<Value>(&line)
        .ok()
        .filter(|header| header["type"] == "session")
}

/// The one file in `dir` that holds the session, checked as Pi wrote it.
pub fn session_file(dir: &Path, session: &str, directory: &Path) -> Result<PathBuf, String> {
    use std::os::unix::fs::MetadataExt;
    let shown = dir.display().to_string();
    let said = |key: &str, file: &Path| {
        let file = file.display().to_string();
        say(
            key,
            &[("session", session), ("directory", &shown), ("file", &file)],
        )
    };
    let real = dir.symlink_metadata().is_ok_and(|m| m.is_dir());
    let entries = std::fs::read_dir(dir)
        .ok()
        .filter(|_| real)
        .ok_or_else(|| said("pi_session_absent", dir))?;
    let suffix = format!("_{session}.jsonl");
    let mut found = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str().filter(|name| name.ends_with(".jsonl")) else {
            continue;
        };
        let path = dir.join(name);
        let regular = path.symlink_metadata().is_ok_and(|m| m.is_file());
        let header = regular.then(|| header(&path)).flatten();
        let names = header.as_ref().is_some_and(|h| h["id"] == session);
        if name.ends_with(&suffix) || names {
            found.push((path, header));
        }
    }
    let (path, header) = match found.len() {
        0 => return Err(said("pi_session_absent", dir)),
        1 => found.remove(0),
        _ => return Err(said("pi_session_ambiguous", dir)),
    };
    let one = path
        .symlink_metadata()
        .is_ok_and(|m| m.is_file() && m.nlink() == 1);
    let named = path.to_str().is_some_and(|p| p.ends_with(&suffix));
    let cwd = header
        .as_ref()
        .and_then(|h| h["cwd"].as_str())
        .and_then(|cwd| Path::new(cwd).canonicalize().ok());
    let matches = header.as_ref().is_some_and(|h| h["id"] == session);
    if !(one && named && matches && cwd.as_deref() == Some(directory)) {
        return Err(said("pi_session_replaced", &path));
    }
    Ok(path)
}