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, MutexGuard, PoisonError};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use serde_json::Value;
use super::adapter::{self, Agent};
use super::events::{Event, Log, Tail, Text};
use super::tree::{self, SIGKILL};
use super::watch::{EXIT_LINE, GRACE};
const LINE_BYTES: usize = 8 * 1024 * 1024;
const DRAIN: Duration = Duration::from_secs(1);
const FALLBACK: Duration = Duration::from_secs(3);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
Exited(i32),
Stopped,
TimedOut,
Lost,
}
pub type Announce = Box<dyn Fn(&str) -> bool + Send>;
#[derive(Default)]
pub struct Shared {
pub text: Text,
pub log: Log,
pub last_text: Option<String>,
pub answer: Option<String>,
pub failure: Option<String>,
pub stderr: Tail,
pub session: Option<String>,
pub existed: bool,
pub end: Option<End>,
ended_at: Option<Instant>,
eof: bool,
}
impl Shared {
fn apply(&mut self, event: Event, announce: &mut Option<Announce>) {
match event {
Event::Session(session) => {
if self.session.is_none() && adapter::session_ok(&session) {
if let Some(check) = announce.take() {
self.existed = check(&session);
}
self.session = Some(session);
}
}
Event::Text(text) => {
if self.text.total() > 0 {
self.text.push("\n");
}
self.text.push(&text);
self.last_text = Some(text);
}
Event::Answer(answer) => self.answer = Some(answer),
Event::Observed(entry) => self.log.push(entry),
Event::Failure(failure) => {
self.log.push(serde_json::json!({"kind": "failure"}));
self.failure = Some(failure);
}
}
}
pub fn ended(&self) -> bool {
self.end.is_some() && (self.eof || self.ended_at.is_some_and(|at| at.elapsed() >= DRAIN))
}
pub fn final_answer(&self) -> Option<&str> {
self.answer.as_deref().or(self.last_text.as_deref())
}
}
pub fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
shared.lock().unwrap_or_else(PoisonError::into_inner)
}
pub struct Turn {
pub shared: Arc<Mutex<Shared>>,
pub before: Result<u64, String>,
pub read_text: usize,
pub read_events: usize,
stop: Arc<AtomicBool>,
supervisor: Option<JoinHandle<()>>,
}
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 {
pub fn begin(
agent: Agent,
plan: &Value,
prompt: &str,
dir: &Path,
limit: Duration,
announce: Option<Announce>,
nonce: String,
) -> io::Result<Self> {
let mut child = Command::new(std::env::current_exe()?)
.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;
}
lock(&err)
.stderr
.push(&String::from_utf8_lossy(&chunk[..n]));
}
exit_line(&mut lock(&err), &nonce);
});
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,
stop,
supervisor: Some(supervisor),
})
}
pub fn ended(&self) -> bool {
lock(&self.shared).ended()
}
pub fn ask_stop(&self) {
self.stop.store(true, Ordering::SeqCst);
}
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
}
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() {
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);
break if timed_out {
End::TimedOut
} else {
End::Stopped
};
}
thread::sleep(Duration::from_millis(25));
};
drop(control);
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());
}
}
fn exit_line(shared: &mut Shared, nonce: &str) {
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;
};
shared.stderr.replace(text[..at].trim_end());
if shared.end.is_none() {
shared.end = Some(End::Exited(code));
shared.ended_at = Some(Instant::now());
}
}
fn terminate(child: &mut Child, group: i32) {
let deadline = Instant::now() + GRACE + FALLBACK;
while Instant::now() < deadline {
if let Ok(Some(_)) = child.try_wait() {
return;
}
thread::sleep(Duration::from_millis(20));
}
tree::end_group(group, Duration::from_secs(1));
tree::signal(-group, SIGKILL);
let _ = child.wait();
}