vpf-runner 0.4.0

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>,
}

/// 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.
#[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 Agent for CommandAgent {
    fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
        let asked = ASKED.fetch_add(1, Ordering::Relaxed);
        let file = |kind: &str| {
            let file =
                std::env::temp_dir().join(format!("vpf-{kind}-{}-{asked}", std::process::id()));
            let _ = fs::remove_file(&file);
            file
        };
        let (cost_file, conversation_file) = (file("cost"), file("conversation"));
        let variables = [
            ("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(),
            ),
        ];
        let ended = command::run(
            &self.line,
            request.folder,
            &variables,
            &request.prompt,
            request.deadline,
        )
        .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());
        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))
        }
    }
}