blyte-agent 0.82.0

The blyte agent loop: tools, context, persistent shell sessions, search and the command sandbox.
Documentation
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;

use blyte_provider::{Message, Request, UserPart};

use crate::shell;

pub const MIN_SECRET_BYTES: usize = 8;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redactor {
    pairs: Vec<(String, String)>,
}

enum Piece<'a> {
    Raw(&'a str),
    Redacted(&'a str),
}

impl Redactor {
    pub fn from_pairs(pairs: Vec<(String, String)>) -> Redactor {
        let mut filtered: Vec<(String, String)> = pairs
            .into_iter()
            .filter(|(_, value)| value.len() >= MIN_SECRET_BYTES)
            .collect();
        filtered.sort_by(|a, b| {
            b.1.len()
                .cmp(&a.1.len())
                .then_with(|| a.1.cmp(&b.1))
                .then_with(|| a.0.cmp(&b.0))
        });
        filtered.dedup_by(|a, b| a.1 == b.1);
        Redactor { pairs: filtered }
    }

    pub fn for_root(root: &Path) -> Result<Redactor, String> {
        let main_checkout = resolve_main_checkout(root)?;
        let mut pairs = Vec::new();
        for &name in shell::HARNESS_ENV {
            if let Some(value) = std::env::var_os(name) {
                pairs.push((name.to_string(), value.to_string_lossy().into_owned()));
            }
        }
        for name in shell::withheld_env() {
            if let Some(value) = std::env::var_os(&name) {
                pairs.push((name, value.to_string_lossy().into_owned()));
            }
        }
        read_env_file(&root.join(".env"), &mut pairs)?;
        if let Some(main_root) = main_checkout.as_deref() {
            if !same_path(main_root, root) {
                read_env_file(&main_root.join(".env"), &mut pairs)?;
            }
        }
        Ok(Redactor::from_pairs(pairs))
    }

    pub fn redact_request(&self, req: &Request) -> Request {
        if self.pairs.is_empty() {
            return req.clone();
        }
        Request {
            system: self.apply(&req.system),
            messages: req
                .messages
                .iter()
                .map(|m| self.redact_message(m))
                .collect(),
            tools: req.tools.clone(),
            max_output_tokens: req.max_output_tokens,
            timeout: req.timeout,
        }
    }

    fn redact_message(&self, msg: &Message) -> Message {
        match msg {
            Message::User(text) => Message::User(self.apply(text)),
            Message::UserParts(parts) => Message::UserParts(
                parts
                    .iter()
                    .map(|p| match p {
                        UserPart::Text(t) => UserPart::Text(self.apply(t)),
                        UserPart::Image { mime_type, data } => UserPart::Image {
                            mime_type: mime_type.clone(),
                            data: data.clone(),
                        },
                    })
                    .collect(),
            ),
            Message::Assistant(text) => Message::Assistant(self.apply(text)),
            Message::ToolCall {
                id,
                name,
                arguments,
                signature,
            } => Message::ToolCall {
                id: id.clone(),
                name: name.clone(),
                arguments: self.redact_json(arguments),
                signature: signature.clone(),
            },
            Message::ToolResult {
                id,
                name,
                content,
                is_error,
            } => Message::ToolResult {
                id: id.clone(),
                name: name.clone(),
                content: self.apply(content),
                is_error: *is_error,
            },
        }
    }

    fn redact_json(&self, val: &serde_json::Value) -> serde_json::Value {
        match val {
            serde_json::Value::String(s) => serde_json::Value::String(self.apply(s)),
            serde_json::Value::Array(items) => {
                serde_json::Value::Array(items.iter().map(|v| self.redact_json(v)).collect())
            }
            serde_json::Value::Object(map) => serde_json::Value::Object(
                map.iter()
                    .map(|(k, v)| (k.clone(), self.redact_json(v)))
                    .collect(),
            ),
            other => other.clone(),
        }
    }

    pub fn apply(&self, text: &str) -> String {
        if self.pairs.is_empty() || text.is_empty() {
            return text.to_string();
        }
        let mut pieces = vec![Piece::Raw(text)];
        for (name, value) in &self.pairs {
            if !pieces
                .iter()
                .any(|p| matches!(p, Piece::Raw(s) if s.contains(value.as_str())))
            {
                continue;
            }
            let mut next = Vec::with_capacity(pieces.len() + 2);
            for piece in pieces {
                match piece {
                    Piece::Redacted(n) => next.push(Piece::Redacted(n)),
                    Piece::Raw(s) => {
                        if !s.contains(value.as_str()) {
                            next.push(Piece::Raw(s));
                            continue;
                        }
                        let mut first = true;
                        for part in s.split(value.as_str()) {
                            if !first {
                                next.push(Piece::Redacted(name.as_str()));
                            }
                            first = false;
                            if !part.is_empty() {
                                next.push(Piece::Raw(part));
                            }
                        }
                    }
                }
            }
            pieces = next;
        }
        let mut out = String::with_capacity(text.len());
        for piece in pieces {
            match piece {
                Piece::Raw(s) => out.push_str(s),
                Piece::Redacted(name) => {
                    out.push_str("[redacted ");
                    out.push_str(name);
                    out.push(']');
                }
            }
        }
        out
    }
}

fn in_git_tree(root: &Path) -> Result<bool, String> {
    if std::env::var_os("GIT_DIR").is_some() {
        return Ok(true);
    }
    let abs_root =
        std::path::absolute(root).map_err(|e| format!("cannot resolve {}: {e}", root.display()))?;
    Ok(abs_root
        .ancestors()
        .any(|dir| std::fs::symlink_metadata(dir.join(".git")).is_ok()))
}

fn resolve_main_checkout(root: &Path) -> Result<Option<PathBuf>, String> {
    if !in_git_tree(root)? {
        return Ok(None);
    }
    let output = Command::new("git")
        .args(["-C"])
        .arg(root)
        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .output()
        .map_err(|e| format!("cannot run git rev-parse in {}: {e}", root.display()))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("not a git repository (or any") {
            return Ok(None);
        }
        return Err(format!(
            "git rev-parse --git-common-dir failed in {}: {}",
            root.display(),
            stderr.trim()
        ));
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let line = text
        .lines()
        .map(str::trim)
        .find(|s| !s.is_empty())
        .ok_or_else(|| {
            format!(
                "git rev-parse --git-common-dir returned empty output in {}",
                root.display()
            )
        })?;
    let common_dir = Path::new(line);
    if common_dir.file_name() == Some(OsStr::new(".git")) {
        if let Some(main_root) = common_dir.parent() {
            return Ok(Some(main_root.to_path_buf()));
        }
    }
    Ok(None)
}

fn read_env_file(env_path: &Path, pairs: &mut Vec<(String, String)>) -> Result<(), String> {
    match std::fs::read_to_string(env_path) {
        Ok(text) => {
            for (name, value) in parse_env_file(&text) {
                if shell::credential_like(&name, &value) {
                    pairs.push((name, value));
                }
            }
            Ok(())
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            if std::fs::symlink_metadata(env_path).is_ok() {
                return Err(format!("cannot read {}: {e}", env_path.display()));
            }
            Ok(())
        }
        Err(e) => Err(format!("cannot read {}: {e}", env_path.display())),
    }
}

fn same_path(a: &Path, b: &Path) -> bool {
    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
        (Ok(ca), Ok(cb)) => ca == cb,
        _ => a == b,
    }
}

pub fn parse_env_file(text: &str) -> Vec<(String, String)> {
    let mut pairs = Vec::new();
    for raw_line in text.lines() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = if let Some(rest) = line.strip_prefix("export ") {
            rest.trim_start()
        } else if let Some(rest) = line.strip_prefix("export\t") {
            rest.trim_start()
        } else {
            line
        };
        let Some((raw_name, raw_val)) = line.split_once('=') else {
            continue;
        };
        let name = raw_name.trim();
        if name.is_empty() {
            continue;
        }
        let val = raw_val.trim();
        let unquoted = if val.len() >= 2
            && ((val.starts_with('"') && val.ends_with('"'))
                || (val.starts_with('\'') && val.ends_with('\'')))
        {
            &val[1..val.len() - 1]
        } else {
            val
        };
        pairs.push((name.to_string(), unquoted.to_string()));
    }
    pairs
}