neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The capture's spool of tool calls: a private file with no name, made in
//! the temporary directory and unlinked at once, read back from its start
//! when the turn is filed.

use std::fs::File;
use std::io::{self, BufWriter, Seek, Write};

use serde_json::{Value, json};

/// A private file with no name.
pub fn unnamed() -> io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;
    let path = std::env::temp_dir().join(format!(
        "neosian-capture-{}-{}",
        std::process::id(),
        uuid::Uuid::new_v4().simple()
    ));
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(&path)?;
    std::fs::remove_file(&path)?;
    Ok(file)
}

/// The spool flushed and read from its start, or why it cannot be.
pub fn rewound(spool: Option<BufWriter<File>>) -> Result<Option<File>, String> {
    match spool.map(BufWriter::into_inner) {
        Some(Ok(mut file)) => file
            .rewind()
            .map(|()| Some(file))
            .map_err(|e| e.to_string()),
        Some(Err(error)) => Err(error.error().to_string()),
        None => Ok(None),
    }
}

/// What one held call takes: its id, its name and its input as JSON text.
pub fn size(id: &str, name: &str, input: &Value) -> u64 {
    (id.len() + name.len() + input.to_string().len()) as u64
}

impl super::Capture {
    /// One completed tool call, spooled as the PostToolUse payload the
    /// child's hook would have sent; a call seen before is not repeated.
    pub(super) fn tool(&mut self, id: Option<String>, name: String, input: Value, response: Value) {
        if self.over || self.error.is_some() {
            return;
        }
        if let Some(id) = &id
            && !self.seen.insert(id.clone())
        {
            return;
        }
        let payload = json!({
            "hook_event_name": crate::record::payload::TOOL_EVENT,
            "tool_name": name,
            "tool_input": input,
            "tool_use_id": id,
            "tool_response": response,
        });
        let mut line = payload.to_string();
        line.push('\n');
        self.spooled += line.len() as u64;
        self.check();
        if self.over {
            return;
        }
        let written = match self.spool.as_mut() {
            Some(spool) => spool.write_all(line.as_bytes()),
            None => unnamed().and_then(|file| {
                let spool = self.spool.insert(BufWriter::new(file));
                spool.write_all(line.as_bytes())
            }),
        };
        if let Err(error) = written {
            self.error = Some(error.to_string());
        }
    }
}