neosian 3.0.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
//! One turn of a child (ยง40.50 items 3, 4, 8, amended by #430): the
//! watcher process and the threads that follow it. The supervisor thread
//! writes the plan and the prompt to the watcher, holds its standard input
//! open for the turn's life, and closes it to stop the turn. The watcher is
//! the only writer of the pipes the readers read, so they reach the end
//! when it exits, whatever else still holds the harness's own pipes. When
//! the watcher is gone, the server ends its process group itself.

use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use serde_json::Value;

use super::adapter::Agent;
use super::signin;
use super::tree::{self, SIGKILL};
use super::watch::{EXIT_LINE, GRACE};

mod shared;
pub use shared::{Announce, End, Shared, lock};

/// The longest line of harness output read; the rest of a longer one is skipped.
const LINE_BYTES: usize = 8 * 1024 * 1024;
/// After the watcher exits, how long the readers may take to reach the end.
const DRAIN: Duration = Duration::from_secs(1);
/// After the pipe closes, how long the server waits before ending the group itself.
const FALLBACK: Duration = Duration::from_secs(3);
/// How long a stopped turn whose filing has begun may take to finish it.
const FILING: Duration = Duration::from_secs(300);

pub struct Turn {
    pub shared: Arc<Mutex<Shared>>,
    /// The newest turn number of the child's conversation when it began,
    /// or why it could not be read.
    pub before: Result<u64, String>,
    /// How much of the text and how many entries the parent has read.
    pub read_text: usize,
    pub read_events: usize,
    /// Notes the turn's answers carry, such as an unread sign-in status.
    pub notes: Vec<String>,
    stop: Arc<AtomicBool>,
    supervisor: Option<JoinHandle<()>>,
}

/// Read one line of at most `LINE_BYTES`; false at the end of the stream.
fn bounded_line(reader: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<bool> {
    line.clear();
    let mut seen = false;
    loop {
        let buffer = reader.fill_buf()?;
        if buffer.is_empty() {
            return Ok(seen);
        }
        seen = true;
        let (chunk, done) = match buffer.iter().position(|b| *b == b'\n') {
            Some(at) => (&buffer[..at], at + 1),
            None => (buffer, buffer.len()),
        };
        if line.len() < LINE_BYTES {
            let room = LINE_BYTES - line.len();
            line.extend_from_slice(&chunk[..chunk.len().min(room)]);
        }
        let newline = done > chunk.len();
        reader.consume(done);
        if newline {
            return Ok(true);
        }
    }
}

impl Turn {
    /// Start the watcher in `dir` and hand it `plan` and the prompt.
    pub fn begin(
        agent: Agent,
        plan: &Value,
        prompt: &str,
        dir: &Path,
        limit: Duration,
        announce: Option<Announce>,
        nonce: String,
    ) -> io::Result<Self> {
        let mut command = Command::new(std::env::current_exe()?);
        // The server's home made absolute, whatever directory the watcher,
        // its recorder and the child run in (X4f Q1).
        if let Some(home) = super::selection::home() {
            command.env(crate::home::HOME_ENV, home);
        }
        let mut child = command
            .arg("harness-watch")
            .current_dir(dir)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0)
            .spawn()?;
        let mut message = plan.to_string().into_bytes();
        message.push(b'\n');
        message.extend_from_slice(prompt.as_bytes());
        let shared = Arc::new(Mutex::new(Shared::default()));
        let stdout = child.stdout.take().expect("piped");
        let stderr = child.stderr.take().expect("piped");
        let out = Arc::clone(&shared);
        thread::spawn(move || {
            let mut announce = announce;
            let mut reader = BufReader::new(stdout);
            let mut line = Vec::new();
            while let Ok(true) = bounded_line(&mut reader, &mut line) {
                let events = agent.read(&String::from_utf8_lossy(&line));
                let mut shared = lock(&out);
                for event in events {
                    shared.apply(event, &mut announce);
                }
            }
            lock(&out).eof = true;
        });
        let err = Arc::clone(&shared);
        thread::spawn(move || {
            let mut stderr = stderr;
            let mut chunk = [0u8; 4096];
            while let Ok(n) = stderr.read(&mut chunk) {
                if n == 0 {
                    break;
                }
                let mut shared = lock(&err);
                shared.stderr.push(&String::from_utf8_lossy(&chunk[..n]));
                // Filing progress as it arrives, not at the end (X4f Q4).
                began(&mut shared, &nonce);
            }
            exit_line(&mut lock(&err), &nonce, agent);
        });
        let stop = Arc::new(AtomicBool::new(false));
        let asked = Arc::clone(&stop);
        let state = Arc::clone(&shared);
        let supervisor = thread::spawn(move || supervise(child, message, &asked, &state, limit));
        Ok(Self {
            shared,
            before: Ok(0),
            read_text: 0,
            read_events: 0,
            notes: Vec::new(),
            stop,
            supervisor: Some(supervisor),
        })
    }

    pub fn ended(&self) -> bool {
        lock(&self.shared).ended()
    }

    /// Ask the supervisor to end the turn; it returns at once.
    pub fn ask_stop(&self) {
        self.stop.store(true, Ordering::SeqCst);
    }

    /// Wait for the supervisor, at most `bound`; true once it has finished.
    pub fn join(&mut self, bound: Duration) -> bool {
        let deadline = Instant::now() + bound;
        while self
            .supervisor
            .as_ref()
            .is_some_and(|handle| !handle.is_finished())
        {
            if Instant::now() >= deadline {
                return false;
            }
            thread::sleep(Duration::from_millis(10));
        }
        if let Some(handle) = self.supervisor.take() {
            let _ = handle.join();
        }
        true
    }

    /// How long a stop may take: the watcher's grace, the fallback, a margin.
    pub fn stop_bound() -> Duration {
        GRACE + FALLBACK + GRACE + Duration::from_secs(1)
    }
}

fn supervise(
    mut child: Child,
    message: Vec<u8>,
    asked: &AtomicBool,
    shared: &Mutex<Shared>,
    limit: Duration,
) {
    let mut control = child.stdin.take();
    if let Some(stdin) = control.as_mut() {
        // A watcher that refused has exited; its stderr says why.
        let _ = stdin.write_all(&message).and_then(|()| stdin.flush());
    }
    let group = child.id() as i32;
    let deadline = Instant::now() + limit;
    let end = loop {
        match child.try_wait() {
            Ok(Some(status)) if status.signal().is_some() => break End::Lost,
            Ok(Some(status)) => break End::Exited(status.code().unwrap_or(1)),
            Ok(None) => {}
            Err(_) => break End::Lost,
        }
        let timed_out = Instant::now() >= deadline;
        if timed_out || asked.load(Ordering::SeqCst) {
            drop(control.take());
            terminate(&mut child, group, shared);
            break if timed_out {
                End::TimedOut
            } else {
                End::Stopped
            };
        }
        thread::sleep(Duration::from_millis(25));
    };
    drop(control);
    // A watcher gone by a signal left its group behind; a finished one
    // left nothing, and this finds nothing.
    tree::end_group(group, GRACE);
    let mut shared = lock(shared);
    if shared.end.is_none() {
        shared.end = Some(end);
        shared.ended_at = Some(Instant::now());
    }
}

/// The watcher's own last line on stderr, `EXIT_LINE <nonce> <status>`,
/// which ends the turn before the watcher has finished cleaning up (#431).
/// Only the turn's nonce counts, so a harness cannot write it. A sign-in
/// failure the harness reported only on stderr is read here (Pi, X5a).
fn exit_line(shared: &mut Shared, nonce: &str, agent: Agent) {
    began(shared, nonce);
    let text = shared.stderr.text().to_string();
    let marker = format!("{EXIT_LINE} {nonce} ");
    let Some(at) = text.rfind(&marker) else {
        return;
    };
    let Ok(code) = text[at + marker.len()..].trim().parse::<i32>() else {
        return;
    };
    let (kept, filed) = super::filing::taken(&text[..at], nonce);
    if signin::stderr_said(agent, code, &kept) {
        shared.apply(signin::failed_after(agent, &kept), &mut None);
    }
    shared.filed = filed;
    shared.stderr.replace(kept.trim_end());
    if shared.end.is_none() {
        shared.end = Some(End::Exited(code));
        shared.ended_at = Some(Instant::now());
    }
}

/// The watcher's line that filing began, taken out of the stderr text.
fn began(shared: &mut Shared, nonce: &str) {
    if let Some(kept) = super::filing::began(shared.stderr.text(), nonce) {
        shared.filing = true;
        shared.stderr.replace(&kept);
    }
}

/// After the pipe closed: wait for the watcher to end the turn; if it has
/// not after its grace and the fallback, end its group from here. A turn
/// whose filing has begun is recorded, never cut: the watcher is waited for
/// within `FILING` (X4e P6).
fn terminate(child: &mut Child, group: i32, shared: &Mutex<Shared>) {
    let mut deadline = Instant::now() + GRACE + FALLBACK;
    let mut filing = false;
    while Instant::now() < deadline {
        if let Ok(Some(_)) = child.try_wait() {
            return;
        }
        if !filing && lock(shared).filing {
            filing = true;
            deadline = Instant::now() + FILING;
        }
        thread::sleep(Duration::from_millis(20));
    }
    // Not reaped yet, so the group's ID cannot have been reused.
    tree::end_group(group, Duration::from_secs(1));
    tree::signal(-group, SIGKILL);
    let _ = child.wait();
}