blyte 0.86.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
use std::collections::VecDeque;
use std::io::{BufRead, Write};
use std::sync::mpsc::{self, TryRecvError};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::session::{AnswerError, ApprovalAnswer, Entry, EntryBody, Session};

const POLL_WAIT: Duration = Duration::from_millis(100);
const APPROVAL_PROMPT: &str = "Approve once? [y/N] ";

pub struct TerminalOptions {
    pub input_is_terminal: bool,
    pub settle: Duration,
    pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
    pub runs_working: Arc<dyn Fn() -> Result<usize, String> + Send + Sync>,
}

pub fn render_entry(entry: &Entry) -> Option<String> {
    match &entry.body {
        EntryBody::UserMessage { text, .. } => Some(format!("> {text}")),
        EntryBody::Turn { text, .. } => {
            if text.is_empty() {
                None
            } else {
                Some(text.clone())
            }
        }
        EntryBody::ToolStarted { name, input } => {
            let first_line = input.lines().next().unwrap_or("");
            let truncated: String = first_line.chars().take(100).collect();
            Some(format!("  {name}: {truncated}"))
        }
        EntryBody::ToolFinished {
            name,
            summary,
            is_error,
        } => {
            if *is_error {
                Some(format!("  {name} failed: {summary}"))
            } else {
                None
            }
        }
        EntryBody::Retry {
            attempt,
            max,
            wait_ms,
            reason,
        } => Some(format!("  retry {attempt}/{max} in {wait_ms} ms: {reason}")),
        EntryBody::Error { message } => Some(format!("error: {message}")),
        EntryBody::Idle {
            turns,
            cost_usd,
            seconds,
            ..
        } => {
            let cost = match cost_usd {
                Some(c) => format!("USD {c:.4}"),
                None => "cost unknown".to_string(),
            };
            let time = match seconds {
                Some(s) => format!("{s:.1} s"),
                None => "time unknown".to_string(),
            };
            Some(format!("[{turns} turn(s), {cost}, {time}]"))
        }
        EntryBody::ModelChanged { model } => Some(format!("model: {model}")),
        EntryBody::EffortChanged { effort } => match effort {
            Some(e) => Some(format!("effort: {e}")),
            None => Some("effort: default".to_string()),
        },
        EntryBody::Decision { run, action, note } => match note {
            Some(n) if !n.is_empty() => Some(format!("  decision on {run}: {action} ({n})")),
            _ => Some(format!("  decision on {run}: {action}")),
        },
        EntryBody::PeerMessage {
            from_name,
            from_repository,
            text,
            ..
        } => Some(format!("[from {from_name} ({from_repository})] {text}")),
        EntryBody::ApprovalRequested {
            command, reason, ..
        } => Some(format!("RUN OUTSIDE THE SANDBOX\n{command}\n{reason}")),
        EntryBody::PublishApprovalRequested { publish, .. } => {
            let short_commit: String = publish.commit.chars().take(12).collect();
            Some(format!(
                "OPEN PULL REQUEST\n{}\n{} -> {}, commit {}\n{}",
                publish.title, publish.branch, publish.base, short_commit, publish.remote_url
            ))
        }
        EntryBody::LandApprovalRequested { land, .. } => {
            let short_commit: String = land.commit.chars().take(12).collect();
            Some(format!(
                "MERGE PULL REQUEST #{}\n{}\n{}\n{} -> {}, commit {}\nLanding check passed: {}",
                land.number,
                land.title,
                land.pull_request_url,
                land.branch,
                land.base,
                short_commit,
                land.check_command
            ))
        }
        EntryBody::ApprovalAnswered {
            answer, command, ..
        } => Some(format!("approval {answer}: {command}")),
    }
}

enum InputEvent {
    Line(String),
    Eof,
    Error(std::io::Error),
}

fn spawn_input_reader(mut input: Box<dyn BufRead + Send>) -> mpsc::Receiver<InputEvent> {
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let mut buf = String::new();
        loop {
            buf.clear();
            match input.read_line(&mut buf) {
                Ok(0) => {
                    let _ = tx.send(InputEvent::Eof);
                    break;
                }
                Ok(_) => {
                    let without_lf = buf.strip_suffix('\n').unwrap_or(&buf);
                    let trimmed = without_lf.strip_suffix('\r').unwrap_or(without_lf);
                    if tx.send(InputEvent::Line(trimmed.to_string())).is_err() {
                        break;
                    }
                }
                Err(e) => {
                    let _ = tx.send(InputEvent::Error(e));
                    break;
                }
            }
        }
    });
    rx
}

fn format_answer_error(err: AnswerError) -> &'static str {
    match err {
        AnswerError::NotFound => "not found",
        AnswerError::AlreadyAnswered => "already answered",
    }
}

fn parse_approval_answer(line: &str) -> ApprovalAnswer {
    match line.trim().to_ascii_lowercase().as_str() {
        "y" | "yes" => ApprovalAnswer::Yes,
        _ => ApprovalAnswer::No,
    }
}

fn approval_request_id(body: &EntryBody) -> Option<&str> {
    match body {
        EntryBody::ApprovalRequested { id, .. }
        | EntryBody::PublishApprovalRequested { id, .. }
        | EntryBody::LandApprovalRequested { id, .. } => Some(id.as_str()),
        _ => None,
    }
}

fn write_line_breaking_prompt(out: &mut dyn Write, prompt_shown: &mut bool, text: &str) {
    if *prompt_shown {
        let _ = writeln!(out);
        *prompt_shown = false;
    }
    let _ = writeln!(out, "{text}");
}

fn show_approval_prompt(out: &mut dyn Write, prompt_shown: &mut bool) {
    let _ = write!(out, "{APPROVAL_PROMPT}");
    *prompt_shown = true;
}

pub fn run_terminal_front(
    session: &Session,
    input: Box<dyn BufRead + Send>,
    out: &mut dyn Write,
    options: TerminalOptions,
) -> i32 {
    let mut after = session.info().last_seq;
    let rx = spawn_input_reader(input);
    let mut waiting_approvals: VecDeque<String> = VecDeque::new();
    let mut prompt_shown = false;
    let mut saw_error = false;
    let mut input_closed = false;
    let mut quiet_since: Option<Instant> = None;

    loop {
        let entries = session.entries_after(after, POLL_WAIT);
        if !entries.is_empty() {
            quiet_since = None;
            for entry in entries {
                after = entry.seq;
                if matches!(entry.body, EntryBody::Error { .. }) {
                    saw_error = true;
                }
                if let Some(rendered) = render_entry(&entry) {
                    write_line_breaking_prompt(out, &mut prompt_shown, &rendered);
                }
                if let Some(id) = approval_request_id(&entry.body) {
                    if options.input_is_terminal {
                        let was_empty = waiting_approvals.is_empty();
                        waiting_approvals.push_back(id.to_string());
                        if was_empty {
                            show_approval_prompt(out, &mut prompt_shown);
                        }
                    } else {
                        let _ = session.answer_approval(id, ApprovalAnswer::No);
                        write_line_breaking_prompt(
                            out,
                            &mut prompt_shown,
                            "approval needs a terminal: standard input is not one",
                        );
                    }
                } else if let EntryBody::ApprovalAnswered { id, .. } = &entry.body {
                    if let Some(pos) = waiting_approvals.iter().position(|w| w == id) {
                        waiting_approvals.remove(pos);
                        write_line_breaking_prompt(out, &mut prompt_shown, "answered on the page");
                        if pos == 0 && !waiting_approvals.is_empty() {
                            show_approval_prompt(out, &mut prompt_shown);
                        }
                    }
                }
            }
            let _ = out.flush();
        }

        loop {
            match rx.try_recv() {
                Ok(InputEvent::Line(line)) => {
                    quiet_since = None;
                    if let Some(id) = waiting_approvals.pop_front() {
                        prompt_shown = false;
                        let answer = parse_approval_answer(&line);
                        if let Err(err) = session.answer_approval(&id, answer) {
                            let _ = writeln!(
                                out,
                                "approval not recorded: {}",
                                format_answer_error(err)
                            );
                        }
                        if !waiting_approvals.is_empty() {
                            show_approval_prompt(out, &mut prompt_shown);
                        }
                        let _ = out.flush();
                    } else {
                        let trimmed = line.trim();
                        if trimmed.is_empty() {
                            continue;
                        }
                        if trimmed == "/exit" {
                            return 0;
                        }
                        if trimmed == "/help" {
                            let _ = writeln!(out, "/help  show available commands");
                            let _ = writeln!(out, "/exit  exit the terminal");
                            let _ = out.flush();
                        } else if trimmed.starts_with('/') {
                            let _ = writeln!(out, "unknown command: {trimmed} (try /help)");
                            let _ = out.flush();
                        } else if let Err(e) = session.submit(&line, Vec::new()) {
                            let _ = writeln!(out, "error: {e}");
                            let _ = out.flush();
                        }
                    }
                }
                Ok(InputEvent::Eof) => {
                    if options.input_is_terminal {
                        if session.info().busy {
                            session.stop_run();
                        }
                        return 0;
                    }
                    input_closed = true;
                }
                Ok(InputEvent::Error(e)) => {
                    write_line_breaking_prompt(
                        out,
                        &mut prompt_shown,
                        &format!("error: cannot read input: {e}"),
                    );
                    let _ = out.flush();
                    return 1;
                }
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => {
                    if !input_closed {
                        if options.input_is_terminal {
                            if session.info().busy {
                                session.stop_run();
                            }
                            return 0;
                        }
                        input_closed = true;
                    }
                    break;
                }
            }
        }

        if (options.take_interrupt)() {
            if session.info().busy {
                session.stop_run();
                write_line_breaking_prompt(out, &mut prompt_shown, "stopping the current turn");
                let _ = out.flush();
                quiet_since = None;
            } else {
                return 0;
            }
        }

        if input_closed {
            let info = session.info();
            if !info.busy && info.queued == 0 && info.last_seq <= after {
                match (options.runs_working)() {
                    Ok(0) => {
                        let since = *quiet_since.get_or_insert_with(Instant::now);
                        if since.elapsed() >= options.settle {
                            return if saw_error { 1 } else { 0 };
                        }
                    }
                    Ok(_) => {
                        quiet_since = None;
                    }
                    Err(e) => {
                        write_line_breaking_prompt(
                            out,
                            &mut prompt_shown,
                            &format!("error: cannot tell whether runs are working: {e}"),
                        );
                        let _ = out.flush();
                        return 1;
                    }
                }
            } else {
                quiet_since = None;
            }
        }
    }
}