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>,
}
#[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 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))
}
}
}