neosian 3.0.2

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! The watcher's run of the harness (split from `watch.rs`): the harness
//! started under the turn's launch with the prompt on its standard input,
//! its output relayed to the server and captured for the record, the stop
//! read from the watcher's own standard input, then the filing, the status
//! and the leftovers ended.

use std::io::{self, Read, Write};
use std::path::Path;
use std::process::Stdio;
use std::sync::{Arc, Mutex, PoisonError, mpsc};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use super::adapter::Agent;
use super::capture::Capture;
use super::ending::{self, ignore_sigterm};
use super::filing;
use super::plan::Checked;
use super::sandbox::Launch;

/// The turn's record while it runs; the filing takes it out at the end.
type Recording = Arc<Mutex<Option<Capture>>>;

/// Copy the harness's stream to the watcher's own descriptor `fd` (1 or
/// 2) as it arrives, written through the descriptor number itself: the
/// command door holds the standard streams' locks for the watcher's whole
/// run, and a second descriptor would keep the server's pipe open after the
/// watcher points 1 and 2 at /dev/null. Standard output also reaches the
/// turn's record, whole, after it is relayed (X4a).
fn relay(
    mut from: impl Read + Send + 'static,
    fd: i32,
    record: Option<Recording>,
) -> JoinHandle<bool> {
    thread::spawn(move || {
        let mut to = ending::raw(fd);
        let mut chunk = [0u8; 8192];
        loop {
            let n = match from.read(&mut chunk) {
                Ok(0) => return true,
                Ok(n) => n,
                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                Err(_) => return false,
            };
            if to.write_all(&chunk[..n]).is_err() {
                return false;
            }
            if let Some(record) = &record
                && let Some(capture) = record
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .as_mut()
            {
                capture.push(&chunk[..n]);
            }
        }
    })
}

pub(super) fn drive(
    plan: &Checked,
    launch: &Launch,
    program: &Path,
    (argv, env): (&[String], &[(String, String)]),
    prompt: Vec<u8>,
) -> io::Result<u8> {
    // Muse reads its prompt only from a regular file: an anonymous one (X6b).
    let fed = match plan.agent {
        Agent::Muse => Stdio::from(super::muse::prompt_file(&prompt)?),
        _ => Stdio::piped(),
    };
    let mut harness = launch
        .command(program, &argv[1..], env)
        .current_dir(&plan.directory)
        .stdin(fed)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    // Only now, so the harness keeps the default disposition: the group's
    // SIGTERM is for everyone but the watcher, which sends it.
    ignore_sigterm();
    let asked = prompt.clone();
    if let Some(mut stdin) = harness.stdin.take() {
        thread::spawn(move || {
            let _ = stdin.write_all(&prompt);
        });
    }
    let record: Recording = Arc::new(Mutex::new(Some(Capture::new(plan.agent))));
    let relays = [
        relay(
            harness.stdout.take().expect("piped"),
            1,
            Some(Arc::clone(&record)),
        ),
        relay(harness.stderr.take().expect("piped"), 2, None),
    ];
    let (ended, closed) = mpsc::channel::<()>();
    thread::spawn(move || {
        let mut sink = [0u8; 256];
        let mut input = io::stdin();
        while matches!(input.read(&mut sink), Ok(n) if n > 0) {}
        let _ = ended.send(());
    });
    let own = std::process::id() as i32;
    let status = loop {
        if let Some(status) = harness.try_wait()? {
            break Some(status);
        }
        match closed.recv_timeout(Duration::from_millis(20)) {
            Err(mpsc::RecvTimeoutError::Timeout) => continue,
            Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break None,
        }
    };
    let Some(status) = status else {
        ending::end_tree(&mut harness, own);
        return Ok(1);
    };
    let drained = Instant::now() + Duration::from_millis(500);
    for handle in &relays {
        while !handle.is_finished() && Instant::now() < drained {
            thread::sleep(Duration::from_millis(10));
        }
    }
    // The output reached its end, not the drain deadline (X6c U7).
    let [out, _] = relays;
    let eof = out.is_finished() && out.join().unwrap_or(false);
    let code = ending::code(status);
    // The turn is filed before the answer, so the parent reads it at once,
    // or is told it waits for its destination (X4a).
    let captured = record
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .take()
        .map(|capture| capture.finish(eof));
    // A stop that reached the watcher before filing begins prevents it;
    // once the server is told filing began, the turn is recorded (X4e P6).
    let filed = if matches!(closed.try_recv(), Err(mpsc::TryRecvError::Empty)) {
        filing::begun(&plan.nonce);
        filing::file(plan, &asked, captured, code)
    } else {
        serde_json::json!({"disposition": "stopped"})
    };
    filing::report(&plan.nonce, &filed);
    // The result first: the exit line, then the server's pipes closed, so
    // the answer does not wait for what the harness left behind (#431).
    ending::report(&plan.nonce, code);
    ending::leftovers(own, &closed);
    Ok(code)
}