vpf-runner 0.4.1

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! Agents: who does a step by `agent`, fixes a command's way, or proves another agent's work.

use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;

use serde::{Deserialize, Serialize};

use crate::command;

/// Why an agent is asked.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    /// To do a step's work.
    Work,
    /// To fix what stands in a command's way.
    Fix,
    /// To prove another agent's work, only reading.
    Judge,
}

impl Role {
    /// The role's name: `work`, `fix` or `judge`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Work => "work",
            Self::Fix => "fix",
            Self::Judge => "judge",
        }
    }
}

/// What an agent is asked.
#[derive(Debug)]
#[non_exhaustive]
pub struct AgentRequest<'a> {
    /// Why it is asked.
    pub role: Role,
    /// The id of the step it is asked for.
    pub step: &'a str,
    /// Where in the run it is asked: its answer is kept under this key in the record's journal. A host may show
    /// what the agent does meanwhile under it.
    pub key: &'a str,
    /// The conversation the step's work was done in before, when that work was refused and is asked again, so the
    /// agent may go on in it.
    pub conversation: Option<&'a str>,
    /// What the run may still spend, when its plan has a cost limit and what it spent so far is known. Agents
    /// working at the same time are each told the same.
    pub cost_left: Option<f64>,
    /// Everything it is told, in words.
    pub prompt: String,
    /// The named agent, when the plan names one.
    pub agent: Option<&'a str>,
    /// The model, when the plan names one.
    pub model: Option<&'a str>,
    /// The only kinds of tools it may use.
    pub tools: Vec<&'static str>,
    /// The folder it works in.
    pub folder: &'a Path,
    /// When the run's time is over, when it has a limit.
    pub deadline: Option<Instant>,
    /// A folder kept with the run, the same each time this key is asked, where the agent may keep what lets it be
    /// found again should the run stop while it works: asked again, it may wait for the work still going on and
    /// give its answer instead of starting over. Only for a run kept in the folder; it goes when the run ends.
    pub keep: Option<&'a Path>,
}

/// What an agent answered.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AgentAnswer {
    /// Its answer, in words.
    pub text: String,
    /// What the answer cost, when the agent says.
    pub cost: Option<f64>,
    /// The conversation the work was done in, when the agent says: it is told again if the work comes back.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conversation: Option<String>,
}

impl AgentAnswer {
    /// An answer in these words, with nothing said of its cost or conversation.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            cost: None,
            conversation: None,
        }
    }

    /// The answer, and what it cost.
    #[must_use]
    pub fn with_cost(mut self, cost: f64) -> Self {
        self.cost = Some(cost);
        self
    }

    /// The answer, and the conversation it was given in.
    #[must_use]
    pub fn in_conversation(mut self, conversation: &str) -> Self {
        self.conversation = Some(conversation.to_owned());
        self
    }
}

/// Who answers when an agent is asked. Steps that wait for none of each other ask at the same time, from more
/// than one thread.
pub trait Agent: Sync {
    /// Asks the agent.
    ///
    /// # Errors
    ///
    /// Why the agent could not answer: the work it was asked for is refused with it, and the rest of the run goes on.
    fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String>;
}

impl<F> Agent for F
where
    F: Fn(&AgentRequest<'_>) -> Result<AgentAnswer, String> + Sync,
{
    fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
        self(request)
    }
}

/// An agent reached through a command line.
///
/// The command runs in the folder with the prompt on its input, and its output is the answer. It is told
/// `VPF_ROLE` (`work`, `fix` or `judge`), `VPF_STEP`, `VPF_KEY`, `VPF_AGENT`, `VPF_MODEL`, `VPF_TOOLS` (the kinds
/// of tools it may use, joined by commas), `VPF_FOLDER`, `VPF_CONVERSATION` (the conversation of the step's
/// refused work, or nothing), `VPF_COST_LEFT` (what the run may still spend, or nothing), `VPF_COST_FILE`, a file
/// where it may write what each answer cost, one number per line, and `VPF_CONVERSATION_FILE`, a file where it may
/// write the id of the conversation it worked in.
///
/// For a run kept in the folder, the command's process, output and end are kept in the request's
/// [`keep`](AgentRequest::keep) folder, and a run that stopped while it worked waits for it and takes its answer
/// instead of asking again.
#[derive(Clone, Debug)]
pub struct CommandAgent {
    line: String,
}

impl CommandAgent {
    /// An agent reached through this command line.
    pub fn new(line: impl Into<String>) -> Self {
        Self { line: line.into() }
    }
}

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

impl CommandAgent {
    /// How the command ended: the one still working or ended from before the run stopped, or a new one.
    fn ended(
        &self,
        request: &AgentRequest<'_>,
        cost_file: &Path,
        conversation_file: &Path,
    ) -> Result<command::Ended, command::TimeOver> {
        if let Some(ended) = request
            .keep
            .and_then(|keep| command::rejoin(keep, request.deadline))
        {
            return ended;
        }
        let variables = variables(request, cost_file, conversation_file);
        let (line, folder, input) = (&self.line, request.folder, &request.prompt);
        if let Some(keep) = request.keep {
            let _ = fs::remove_dir_all(keep);
            return command::run_kept(line, folder, &variables, input, keep, request.deadline);
        }
        command::run(line, folder, &variables, input, request.deadline)
    }
}

/// What the command is told.
fn variables(
    request: &AgentRequest<'_>,
    cost_file: &Path,
    conversation_file: &Path,
) -> [(&'static str, String); 11] {
    [
        ("VPF_ROLE", request.role.as_str().to_owned()),
        ("VPF_STEP", request.step.to_owned()),
        ("VPF_KEY", request.key.to_owned()),
        (
            "VPF_CONVERSATION",
            request.conversation.unwrap_or_default().to_owned(),
        ),
        (
            "VPF_COST_LEFT",
            request
                .cost_left
                .map(|left| left.to_string())
                .unwrap_or_default(),
        ),
        ("VPF_AGENT", request.agent.unwrap_or_default().to_owned()),
        ("VPF_MODEL", request.model.unwrap_or_default().to_owned()),
        ("VPF_TOOLS", request.tools.join(",")),
        ("VPF_FOLDER", request.folder.display().to_string()),
        ("VPF_COST_FILE", cost_file.display().to_string()),
        (
            "VPF_CONVERSATION_FILE",
            conversation_file.display().to_string(),
        ),
    ]
}

impl Agent for CommandAgent {
    fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
        let asked = ASKED.fetch_add(1, Ordering::Relaxed);
        let file = |kind: &str| {
            request.keep.map_or_else(
                || {
                    let file = std::env::temp_dir()
                        .join(format!("vpf-{kind}-{}-{asked}", std::process::id()));
                    let _ = fs::remove_file(&file);
                    file
                },
                |keep| keep.join(kind),
            )
        };
        let (cost_file, conversation_file) = (file("cost"), file("conversation"));
        let ended = self
            .ended(request, &cost_file, &conversation_file)
            .map_err(|command::TimeOver| {
                "the run's time was over before the agent answered".to_owned()
            })?;
        let cost = fs::read_to_string(&cost_file).ok().map(|text| {
            text.lines()
                .filter_map(|line| line.trim().parse::<f64>().ok())
                .sum()
        });
        let conversation = fs::read_to_string(&conversation_file)
            .ok()
            .map(|text| text.trim().to_owned())
            .filter(|text| !text.is_empty());
        if request.keep.is_none() {
            let _ = fs::remove_file(&cost_file);
            let _ = fs::remove_file(&conversation_file);
        }
        if ended.passed {
            Ok(AgentAnswer {
                text: ended.out.trim().to_owned(),
                cost,
                conversation,
            })
        } else {
            Err(ended.points(&self.line))
        }
    }
}