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 pub keep: Option<&'a Path>,
68}
69
70#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
72#[non_exhaustive]
73pub struct AgentAnswer {
74 pub text: String,
76 pub cost: Option<f64>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub conversation: Option<String>,
81}
82
83impl AgentAnswer {
84 pub fn new(text: impl Into<String>) -> Self {
86 Self {
87 text: text.into(),
88 cost: None,
89 conversation: None,
90 }
91 }
92
93 #[must_use]
95 pub fn with_cost(mut self, cost: f64) -> Self {
96 self.cost = Some(cost);
97 self
98 }
99
100 #[must_use]
102 pub fn in_conversation(mut self, conversation: &str) -> Self {
103 self.conversation = Some(conversation.to_owned());
104 self
105 }
106}
107
108pub trait Agent: Sync {
111 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String>;
117}
118
119impl<F> Agent for F
120where
121 F: Fn(&AgentRequest<'_>) -> Result<AgentAnswer, String> + Sync,
122{
123 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
124 self(request)
125 }
126}
127
128#[derive(Clone, Debug)]
141pub struct CommandAgent {
142 line: String,
143}
144
145impl CommandAgent {
146 pub fn new(line: impl Into<String>) -> Self {
148 Self { line: line.into() }
149 }
150}
151
152static ASKED: AtomicU64 = AtomicU64::new(0);
153
154impl CommandAgent {
155 fn ended(
157 &self,
158 request: &AgentRequest<'_>,
159 cost_file: &Path,
160 conversation_file: &Path,
161 ) -> Result<command::Ended, command::TimeOver> {
162 if let Some(ended) = request
163 .keep
164 .and_then(|keep| command::rejoin(keep, request.deadline))
165 {
166 return ended;
167 }
168 let variables = variables(request, cost_file, conversation_file);
169 let (line, folder, input) = (&self.line, request.folder, &request.prompt);
170 if let Some(keep) = request.keep {
171 let _ = fs::remove_dir_all(keep);
172 return command::run_kept(line, folder, &variables, input, keep, request.deadline);
173 }
174 command::run(line, folder, &variables, input, request.deadline)
175 }
176}
177
178fn variables(
180 request: &AgentRequest<'_>,
181 cost_file: &Path,
182 conversation_file: &Path,
183) -> [(&'static str, String); 11] {
184 [
185 ("VPF_ROLE", request.role.as_str().to_owned()),
186 ("VPF_STEP", request.step.to_owned()),
187 ("VPF_KEY", request.key.to_owned()),
188 (
189 "VPF_CONVERSATION",
190 request.conversation.unwrap_or_default().to_owned(),
191 ),
192 (
193 "VPF_COST_LEFT",
194 request
195 .cost_left
196 .map(|left| left.to_string())
197 .unwrap_or_default(),
198 ),
199 ("VPF_AGENT", request.agent.unwrap_or_default().to_owned()),
200 ("VPF_MODEL", request.model.unwrap_or_default().to_owned()),
201 ("VPF_TOOLS", request.tools.join(",")),
202 ("VPF_FOLDER", request.folder.display().to_string()),
203 ("VPF_COST_FILE", cost_file.display().to_string()),
204 (
205 "VPF_CONVERSATION_FILE",
206 conversation_file.display().to_string(),
207 ),
208 ]
209}
210
211impl Agent for CommandAgent {
212 fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
213 let asked = ASKED.fetch_add(1, Ordering::Relaxed);
214 let file = |kind: &str| {
215 request.keep.map_or_else(
216 || {
217 let file = std::env::temp_dir()
218 .join(format!("vpf-{kind}-{}-{asked}", std::process::id()));
219 let _ = fs::remove_file(&file);
220 file
221 },
222 |keep| keep.join(kind),
223 )
224 };
225 let (cost_file, conversation_file) = (file("cost"), file("conversation"));
226 let ended = self
227 .ended(request, &cost_file, &conversation_file)
228 .map_err(|command::TimeOver| {
229 "the run's time was over before the agent answered".to_owned()
230 })?;
231 let cost = fs::read_to_string(&cost_file).ok().map(|text| {
232 text.lines()
233 .filter_map(|line| line.trim().parse::<f64>().ok())
234 .sum()
235 });
236 let conversation = fs::read_to_string(&conversation_file)
237 .ok()
238 .map(|text| text.trim().to_owned())
239 .filter(|text| !text.is_empty());
240 if request.keep.is_none() {
241 let _ = fs::remove_file(&cost_file);
242 let _ = fs::remove_file(&conversation_file);
243 }
244 if ended.passed {
245 Ok(AgentAnswer {
246 text: ended.out.trim().to_owned(),
247 cost,
248 conversation,
249 })
250 } else {
251 Err(ended.points(&self.line))
252 }
253 }
254}