Skip to main content

vpf_runner/
agent.rs

1//! Agents: who does a step by `agent`, fixes a command's way, or proves another agent's work.
2
3use 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/// Why an agent is asked.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Role {
16    /// To do a step's work.
17    Work,
18    /// To fix what stands in a command's way.
19    Fix,
20    /// To prove another agent's work, only reading.
21    Judge,
22}
23
24impl Role {
25    /// The role's name: `work`, `fix` or `judge`.
26    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/// What an agent is asked.
36#[derive(Debug)]
37#[non_exhaustive]
38pub struct AgentRequest<'a> {
39    /// Why it is asked.
40    pub role: Role,
41    /// The id of the step it is asked for.
42    pub step: &'a str,
43    /// Where in the run it is asked: its answer is kept under this key in the record's journal. A host may show
44    /// what the agent does meanwhile under it.
45    pub key: &'a str,
46    /// The conversation the step's work was done in before, when that work was refused and is asked again, so the
47    /// agent may go on in it.
48    pub conversation: Option<&'a str>,
49    /// What the run may still spend, when its plan has a cost limit and what it spent so far is known. Agents
50    /// working at the same time are each told the same.
51    pub cost_left: Option<f64>,
52    /// Everything it is told, in words.
53    pub prompt: String,
54    /// The named agent, when the plan names one.
55    pub agent: Option<&'a str>,
56    /// The model, when the plan names one.
57    pub model: Option<&'a str>,
58    /// The only kinds of tools it may use.
59    pub tools: Vec<&'static str>,
60    /// The folder it works in.
61    pub folder: &'a Path,
62    /// When the run's time is over, when it has a limit.
63    pub deadline: Option<Instant>,
64    /// A folder kept with the run, the same each time this key is asked, where the agent may keep what lets it be
65    /// found again should the run stop while it works: asked again, it may wait for the work still going on and
66    /// give its answer instead of starting over. Only for a run kept in the folder; it goes when the run ends.
67    pub keep: Option<&'a Path>,
68}
69
70/// What an agent answered.
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
72#[non_exhaustive]
73pub struct AgentAnswer {
74    /// Its answer, in words.
75    pub text: String,
76    /// What the answer cost, when the agent says.
77    pub cost: Option<f64>,
78    /// The conversation the work was done in, when the agent says: it is told again if the work comes back.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub conversation: Option<String>,
81}
82
83impl AgentAnswer {
84    /// An answer in these words, with nothing said of its cost or conversation.
85    pub fn new(text: impl Into<String>) -> Self {
86        Self {
87            text: text.into(),
88            cost: None,
89            conversation: None,
90        }
91    }
92
93    /// The answer, and what it cost.
94    #[must_use]
95    pub fn with_cost(mut self, cost: f64) -> Self {
96        self.cost = Some(cost);
97        self
98    }
99
100    /// The answer, and the conversation it was given in.
101    #[must_use]
102    pub fn in_conversation(mut self, conversation: &str) -> Self {
103        self.conversation = Some(conversation.to_owned());
104        self
105    }
106}
107
108/// Who answers when an agent is asked. Steps that wait for none of each other ask at the same time, from more
109/// than one thread.
110pub trait Agent: Sync {
111    /// Asks the agent.
112    ///
113    /// # Errors
114    ///
115    /// Why the agent could not answer: the work it was asked for is refused with it, and the rest of the run goes on.
116    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/// An agent reached through a command line.
129///
130/// The command runs in the folder with the prompt on its input, and its output is the answer. It is told
131/// `VPF_ROLE` (`work`, `fix` or `judge`), `VPF_STEP`, `VPF_KEY`, `VPF_AGENT`, `VPF_MODEL`, `VPF_TOOLS` (the kinds
132/// of tools it may use, joined by commas), `VPF_FOLDER`, `VPF_CONVERSATION` (the conversation of the step's
133/// refused work, or nothing), `VPF_COST_LEFT` (what the run may still spend, or nothing), `VPF_COST_FILE`, a file
134/// where it may write what each answer cost, one number per line, and `VPF_CONVERSATION_FILE`, a file where it may
135/// write the id of the conversation it worked in.
136///
137/// For a run kept in the folder, the command's process, output and end are kept in the request's
138/// [`keep`](AgentRequest::keep) folder, and a run that stopped while it worked waits for it and takes its answer
139/// instead of asking again.
140#[derive(Clone, Debug)]
141pub struct CommandAgent {
142    line: String,
143}
144
145impl CommandAgent {
146    /// An agent reached through this command line.
147    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    /// How the command ended: the one still working or ended from before the run stopped, or a new one.
156    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
178/// What the command is told.
179fn 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}