Skip to main content

onerig_core/
runner.rs

1//! The interface the run state machine uses to run jobs, and the data that
2//! crosses it. The real runner combines an adapter with the process driver;
3//! tests use a scripted one.
4
5use std::path::PathBuf;
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum Role {
12    Planner,
13    Worker,
14    Reviewer,
15}
16
17/// One subprocess call of a harness.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Job {
20    pub role: Role,
21    pub prompt: String,
22    /// The run's worktree.
23    pub cwd: PathBuf,
24    /// Where files a harness call needs are written.
25    pub run_dir: PathBuf,
26    /// Where the raw output of a failed job is kept.
27    pub raw_log: PathBuf,
28    /// JSON Schema text, when a structured result is wanted.
29    pub schema: Option<&'static str>,
30}
31
32/// What a harness reports while a job runs, reduced to what onerig shows.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(tag = "type", rename_all = "snake_case")]
35pub enum HarnessEvent {
36    Started { model: Option<String> },
37    Text { text: String },
38    Tool { name: String, detail: String },
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42#[serde(tag = "type", rename_all = "snake_case")]
43pub enum Outcome {
44    Done {
45        text: String,
46        structured: Option<serde_json::Value>,
47    },
48    Failed {
49        kind: FailureKind,
50        message: String,
51        /// Unix milliseconds.
52        reset_at: Option<u64>,
53    },
54}
55
56impl Outcome {
57    /// A failure with no known reset time.
58    pub fn failed(kind: FailureKind, message: impl Into<String>) -> Outcome {
59        Outcome::Failed {
60            kind,
61            message: message.into(),
62            reset_at: None,
63        }
64    }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum FailureKind {
70    /// The account's allowance is used up, or the provider refuses for load or balance.
71    Quota,
72    /// The harness says the user is not logged in.
73    Auth,
74    /// The driver killed the job.
75    Timeout,
76    /// Anything else, including a result the adapter does not recognise.
77    Unknown,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct Probe {
82    pub version: String,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
86#[serde(tag = "type", content = "message", rename_all = "snake_case")]
87pub enum ProbeError {
88    #[error("{0}")]
89    Missing(String),
90    #[error("{0}")]
91    Unsupported(String),
92    #[error("{0}")]
93    NotLoggedIn(String),
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
97pub struct QuotaReport {
98    pub remaining_fraction: f64,
99    /// Unix milliseconds.
100    pub reset_at: Option<u64>,
101}
102
103pub trait Runner {
104    /// Check that a lane can run. Makes no model call.
105    fn preflight(&mut self, lane: &str) -> Result<Probe, ProbeError>;
106    /// Remaining quota of a lane, when its harness can report it for free.
107    fn quota(&mut self, lane: &str) -> Option<QuotaReport>;
108    /// Run one job to its end. `on_spawn` receives the process group of a
109    /// harness process when it starts; `on_event` each event as it arrives.
110    fn run(
111        &mut self,
112        lane: &str,
113        job: &Job,
114        on_spawn: &mut dyn FnMut(i32),
115        on_event: &mut dyn FnMut(HarnessEvent),
116    ) -> Outcome;
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use serde_json::json;
123
124    // The run log and the test scripts both depend on these exact shapes.
125    #[test]
126    fn a_failed_outcome_is_written_the_way_the_log_documents_it() {
127        let outcome = Outcome::Failed {
128            kind: FailureKind::Quota,
129            message: "balance is empty".into(),
130            reset_at: None,
131        };
132
133        assert_eq!(
134            serde_json::to_value(&outcome).unwrap(),
135            json!({ "type": "failed", "kind": "quota", "message": "balance is empty", "reset_at": null })
136        );
137    }
138
139    #[test]
140    fn harness_events_are_tagged_with_a_snake_case_type() {
141        let tool = HarnessEvent::Tool {
142            name: "edit".into(),
143            detail: "src/http.rs".into(),
144        };
145        let text: HarnessEvent =
146            serde_json::from_value(json!({ "type": "text", "text": "hi" })).unwrap();
147
148        assert_eq!(
149            serde_json::to_value(&tool).unwrap(),
150            json!({ "type": "tool", "name": "edit", "detail": "src/http.rs" })
151        );
152        assert_eq!(text, HarnessEvent::Text { text: "hi".into() });
153    }
154}