1use std::fs;
4use std::path::Path;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::Instant;
7
8use serde::{Deserialize, Serialize};
9
10use crate::command;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Role {
16 Work,
18 Fix,
20 Judge,
22}
23
24impl Role {
25 pub fn as_str(self) -> &'static str {
27 match self {
28 Self::Work => "work",
29 Self::Fix => "fix",
30 Self::Judge => "judge",
31 }
32 }
33}
34
35#[derive(Debug)]
37#[non_exhaustive]
38pub struct AgentRequest<'a> {
39 pub role: Role,
41 pub step: &'a str,
43 pub key: &'a str,
46 pub conversation: Option<&'a str>,
49 pub cost_left: Option<f64>,
52 pub prompt: String,
54 pub agent: Option<&'a str>,
56 pub model: Option<&'a str>,
58 pub tools: Vec<&'static str>,
60 pub folder: &'a Path,
62 pub deadline: Option<Instant>,
64}
65
66#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct AgentAnswer {
70 pub text: String,
72 pub cost: Option<f64>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub conversation: Option<String>,
77}
78
79impl AgentAnswer {
80 pub fn new(text: impl Into<String>) -> Self {
82 Self {
83 text: text.into(),
84 cost: None,
85 conversation: None,
86 }
87 }
88
89 #[must_use]
91 pub fn with_cost(mut self, cost: f64) -> Self {
92 self.cost = Some(cost);
93 self
94 }
95
96 #[must_use]
98 pub fn in_conversation(mut self, conversation: &str) -> Self {
99 self.conversation = Some(conversation.to_owned());
100 self
101 }
102}
103
104pub trait Agent: Sync {
107 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String>;
113}
114
115impl<F> Agent for F
116where
117 F: Fn(&AgentRequest<'_>) -> Result<AgentAnswer, String> + Sync,
118{
119 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
120 self(request)
121 }
122}
123
124#[derive(Clone, Debug)]
133pub struct CommandAgent {
134 line: String,
135}
136
137impl CommandAgent {
138 pub fn new(line: impl Into<String>) -> Self {
140 Self { line: line.into() }
141 }
142}
143
144static ASKED: AtomicU64 = AtomicU64::new(0);
145
146impl Agent for CommandAgent {
147 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
148 let asked = ASKED.fetch_add(1, Ordering::Relaxed);
149 let file = |kind: &str| {
150 let file =
151 std::env::temp_dir().join(format!("vpf-{kind}-{}-{asked}", std::process::id()));
152 let _ = fs::remove_file(&file);
153 file
154 };
155 let (cost_file, conversation_file) = (file("cost"), file("conversation"));
156 let variables = [
157 ("VPF_ROLE", request.role.as_str().to_owned()),
158 ("VPF_STEP", request.step.to_owned()),
159 ("VPF_KEY", request.key.to_owned()),
160 (
161 "VPF_CONVERSATION",
162 request.conversation.unwrap_or_default().to_owned(),
163 ),
164 (
165 "VPF_COST_LEFT",
166 request
167 .cost_left
168 .map(|left| left.to_string())
169 .unwrap_or_default(),
170 ),
171 ("VPF_AGENT", request.agent.unwrap_or_default().to_owned()),
172 ("VPF_MODEL", request.model.unwrap_or_default().to_owned()),
173 ("VPF_TOOLS", request.tools.join(",")),
174 ("VPF_FOLDER", request.folder.display().to_string()),
175 ("VPF_COST_FILE", cost_file.display().to_string()),
176 (
177 "VPF_CONVERSATION_FILE",
178 conversation_file.display().to_string(),
179 ),
180 ];
181 let ended = command::run(
182 &self.line,
183 request.folder,
184 &variables,
185 &request.prompt,
186 request.deadline,
187 )
188 .map_err(|command::TimeOver| {
189 "the run's time was over before the agent answered".to_owned()
190 })?;
191 let cost = fs::read_to_string(&cost_file).ok().map(|text| {
192 text.lines()
193 .filter_map(|line| line.trim().parse::<f64>().ok())
194 .sum()
195 });
196 let conversation = fs::read_to_string(&conversation_file)
197 .ok()
198 .map(|text| text.trim().to_owned())
199 .filter(|text| !text.is_empty());
200 let _ = fs::remove_file(&cost_file);
201 let _ = fs::remove_file(&conversation_file);
202 if ended.passed {
203 Ok(AgentAnswer {
204 text: ended.out.trim().to_owned(),
205 cost,
206 conversation,
207 })
208 } else {
209 Err(ended.points(&self.line))
210 }
211 }
212}