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}
65
66/// What an agent answered.
67#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct AgentAnswer {
70    /// Its answer, in words.
71    pub text: String,
72    /// What the answer cost, when the agent says.
73    pub cost: Option<f64>,
74    /// The conversation the work was done in, when the agent says: it is told again if the work comes back.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub conversation: Option<String>,
77}
78
79impl AgentAnswer {
80    /// An answer in these words, with nothing said of its cost or conversation.
81    pub fn new(text: impl Into<String>) -> Self {
82        Self {
83            text: text.into(),
84            cost: None,
85            conversation: None,
86        }
87    }
88
89    /// The answer, and what it cost.
90    #[must_use]
91    pub fn with_cost(mut self, cost: f64) -> Self {
92        self.cost = Some(cost);
93        self
94    }
95
96    /// The answer, and the conversation it was given in.
97    #[must_use]
98    pub fn in_conversation(mut self, conversation: &str) -> Self {
99        self.conversation = Some(conversation.to_owned());
100        self
101    }
102}
103
104/// Who answers when an agent is asked. Steps that wait for none of each other ask at the same time, from more
105/// than one thread.
106pub trait Agent: Sync {
107    /// Asks the agent.
108    ///
109    /// # Errors
110    ///
111    /// Why the agent could not answer: the work it was asked for is refused with it, and the rest of the run goes on.
112    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/// An agent reached through a command line.
125///
126/// The command runs in the folder with the prompt on its input, and its output is the answer. It is told
127/// `VPF_ROLE` (`work`, `fix` or `judge`), `VPF_STEP`, `VPF_KEY`, `VPF_AGENT`, `VPF_MODEL`, `VPF_TOOLS` (the kinds
128/// of tools it may use, joined by commas), `VPF_FOLDER`, `VPF_CONVERSATION` (the conversation of the step's
129/// refused work, or nothing), `VPF_COST_LEFT` (what the run may still spend, or nothing), `VPF_COST_FILE`, a file
130/// where it may write what each answer cost, one number per line, and `VPF_CONVERSATION_FILE`, a file where it may
131/// write the id of the conversation it worked in.
132#[derive(Clone, Debug)]
133pub struct CommandAgent {
134    line: String,
135}
136
137impl CommandAgent {
138    /// An agent reached through this command line.
139    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}