use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use serde::{Deserialize, Serialize};
use crate::command;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Work,
Fix,
Judge,
}
impl Role {
pub fn as_str(self) -> &'static str {
match self {
Self::Work => "work",
Self::Fix => "fix",
Self::Judge => "judge",
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct AgentRequest<'a> {
pub role: Role,
pub step: &'a str,
pub key: &'a str,
pub conversation: Option<&'a str>,
pub cost_left: Option<f64>,
pub prompt: String,
pub agent: Option<&'a str>,
pub model: Option<&'a str>,
pub tools: Vec<&'static str>,
pub folder: &'a Path,
pub deadline: Option<Instant>,
pub keep: Option<&'a Path>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AgentAnswer {
pub text: String,
pub cost: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation: Option<String>,
}
impl AgentAnswer {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
cost: None,
conversation: None,
}
}
#[must_use]
pub fn with_cost(mut self, cost: f64) -> Self {
self.cost = Some(cost);
self
}
#[must_use]
pub fn in_conversation(mut self, conversation: &str) -> Self {
self.conversation = Some(conversation.to_owned());
self
}
}
pub trait Agent: Sync {
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)
}
}
#[derive(Clone, Debug)]
pub struct CommandAgent {
line: String,
}
impl CommandAgent {
pub fn new(line: impl Into<String>) -> Self {
Self { line: line.into() }
}
}
static ASKED: AtomicU64 = AtomicU64::new(0);
impl CommandAgent {
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)
}
}
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))
}
}
}