blyte 0.78.3

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use blyte_agent::sandbox::validate_surface_id;
use serde::{Deserialize, Serialize};

use crate::surface_dir::{probe, validate_surface_name, Liveness};

static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SurfaceState {
    Idle,
    Working,
    Approval,
    Replied,
}

impl SurfaceState {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Working => "working",
            Self::Approval => "approval",
            Self::Replied => "replied",
        }
    }

    pub fn display_label(&self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Working => "working",
            Self::Approval => "waiting on you (approval)",
            Self::Replied => "waiting on you (replied)",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegistryEntry {
    pub id: String,
    pub name: String,
    pub root: PathBuf,
    pub branch: Option<String>,
    pub pid: u32,
    pub port: u16,
    pub started_at: u64,
    pub doing: String,
    pub state: SurfaceState,
}

pub fn state_dir() -> Result<PathBuf, String> {
    crate::registry::state_dir().ok_or_else(|| {
        "cannot find the blyte state directory: set BLYTE_STATE_DIR, XDG_STATE_HOME or HOME"
            .to_string()
    })
}

pub fn registry_dir() -> Result<PathBuf, String> {
    state_dir().map(|dir| dir.join("surfaces"))
}

pub fn entry_path(dir: &Path, id: &str) -> PathBuf {
    dir.join(format!("{id}.json"))
}

pub fn write_entry(dir: &Path, entry: &RegistryEntry) -> Result<(), String> {
    validate_surface_id(&entry.id)?;
    validate_surface_name(&entry.name)?;
    std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
    let dest = entry_path(dir, &entry.id);
    let mut json = serde_json::to_string_pretty(entry)
        .map_err(|e| format!("failed to serialize {}: {e}", dest.display()))?;
    json.push('\n');
    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let tmp = dir.join(format!(".{}.tmp.{}.{seq}", entry.id, std::process::id()));
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut file = opts
        .open(&tmp)
        .map_err(|e| format!("failed to create {}: {e}", tmp.display()))?;
    if let Err(e) = file.write_all(json.as_bytes()) {
        drop(file);
        let _ = std::fs::remove_file(&tmp);
        return Err(format!("failed to write {}: {e}", tmp.display()));
    }
    drop(file);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)) {
            let _ = std::fs::remove_file(&tmp);
            return Err(format!(
                "failed to set permissions on {}: {e}",
                tmp.display()
            ));
        }
    }
    if let Err(e) = std::fs::rename(&tmp, &dest) {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!(
            "failed to rename {} to {}: {e}",
            tmp.display(),
            dest.display()
        ));
    }
    Ok(())
}

pub fn remove_entry(dir: &Path, id: &str) -> Result<(), String> {
    let path = entry_path(dir, id);
    match std::fs::remove_file(&path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(format!("failed to remove {}: {e}", path.display())),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnreadableRecord {
    pub path: PathBuf,
    pub reason: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RegistryEntries {
    pub entries: Vec<RegistryEntry>,
    pub unreadable: Vec<UnreadableRecord>,
}

pub fn report_unreadable(unreadable: &[UnreadableRecord], err: &mut dyn Write) {
    for record in unreadable {
        let _ = writeln!(
            err,
            "blyte: skipped surface record {}: {}",
            record.path.display(),
            record.reason
        );
    }
    if !unreadable.is_empty() {
        let _ = err.flush();
    }
}

pub fn read_entries(dir: &Path) -> Result<RegistryEntries, String> {
    let read_dir = match std::fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RegistryEntries::default()),
        Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
    };
    let mut entries = Vec::new();
    let mut unreadable = Vec::new();
    for item in read_dir {
        let item = item.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
        let path = item.path();
        let file_name = item.file_name();
        let lossy = file_name.to_string_lossy();
        if !lossy.ends_with(".json") {
            continue;
        }
        let Some(name_str) = file_name.to_str() else {
            return Err(format!("invalid registry entry path: {}", path.display()));
        };
        let Some(stem) = name_str.strip_suffix(".json") else {
            continue;
        };
        // A surface removes its entry when it exits, which can happen between the listing above
        // and this read: that surface is no longer running, so it is not in the result.
        let bytes = match std::fs::read(&path) {
            Ok(bytes) => bytes,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
        };
        let entry: RegistryEntry = match serde_json::from_slice(&bytes) {
            Ok(entry) => entry,
            Err(e) => {
                unreadable.push(UnreadableRecord {
                    path,
                    reason: e.to_string(),
                });
                continue;
            }
        };
        if entry.id != stem {
            unreadable.push(UnreadableRecord {
                path,
                reason: format!("has id {}, expected {stem}", entry.id),
            });
            continue;
        }
        entries.push(entry);
    }
    entries.sort_by(|a, b| {
        a.started_at
            .cmp(&b.started_at)
            .then_with(|| a.id.cmp(&b.id))
    });
    unreadable.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(RegistryEntries {
        entries,
        unreadable,
    })
}

pub fn live_entries(dir: &Path) -> Result<RegistryEntries, String> {
    let read = read_entries(dir)?;
    let mut live = Vec::with_capacity(read.entries.len());
    for entry in read.entries {
        match probe(entry.pid, entry.port, &entry.id) {
            Liveness::Running | Liveness::Unknown => live.push(entry),
            Liveness::NotRunning => remove_entry(dir, &entry.id)?,
        }
    }
    Ok(RegistryEntries {
        entries: live,
        unreadable: read.unreadable,
    })
}

pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
    let listing = live_entries(dir)?;
    let mut matches: Vec<RegistryEntry> = listing
        .entries
        .into_iter()
        .filter(|entry| entry.name == name || entry.id == name)
        .collect();
    match matches.len() {
        0 => {
            if listing.unreadable.is_empty() {
                Err(format!("no running surface named {name}"))
            } else {
                let paths: Vec<String> = listing
                    .unreadable
                    .iter()
                    .map(|record| record.path.display().to_string())
                    .collect();
                let label = if paths.len() == 1 {
                    "skipped unreadable surface record"
                } else {
                    "skipped unreadable surface records"
                };
                Err(format!(
                    "no running surface named {name} ({label}: {})",
                    paths.join(", ")
                ))
            }
        }
        1 => Ok(matches.remove(0)),
        _ => {
            let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
            Err(format!(
                "more than one running surface is named {name}; use an id: {}",
                ids.join(", ")
            ))
        }
    }
}

pub fn first_line(text: &str) -> String {
    for line in text.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty() {
            return trimmed.chars().take(120).collect();
        }
    }
    String::new()
}