Skip to main content

onerig_core/adapter/
mod.rs

1//! Harness adapters. An adapter knows one harness's command line and output
2//! format. Every method is pure: it starts nothing and reads nothing, so an
3//! adapter is tested with captured output alone.
4
5use std::path::PathBuf;
6
7use serde_json::Value;
8
9use crate::prompt::{PLANNER_ROLE, REVIEWER_ROLE};
10use crate::runner::{
11    FailureKind, HarnessEvent, Job, Outcome, Probe, ProbeError, QuotaReport, Role,
12};
13
14pub(crate) fn role_prompt(role: Role) -> Option<&'static str> {
15    match role {
16        Role::Planner => Some(PLANNER_ROLE),
17        Role::Reviewer => Some(REVIEWER_ROLE),
18        Role::Worker => None,
19    }
20}
21
22pub(crate) fn prepend_role(role: Role, prompt: &str) -> String {
23    match role_prompt(role) {
24        Some(prefix) => format!("{prefix}\n\n{prompt}"),
25        None => prompt.to_string(),
26    }
27}
28
29pub(crate) fn json_lines(stdout: &[String]) -> Vec<Value> {
30    stdout
31        .iter()
32        .filter_map(|line| serde_json::from_str(line).ok())
33        .collect()
34}
35
36pub(crate) struct TagParser {
37    pub tag_key: &'static str,
38    pub start_tag: &'static str,
39    pub step_tag: &'static str,
40    pub step_payload_key: &'static str,
41    pub parse_step: fn(&Value) -> Option<HarnessEvent>,
42}
43
44impl TagParser {
45    pub fn parse(&self, model: &str, line: &str) -> Vec<HarnessEvent> {
46        let Ok(value) = serde_json::from_str::<Value>(line) else {
47            return Vec::new();
48        };
49        let event = match value[self.tag_key].as_str() {
50            Some(tag) if tag == self.start_tag => Some(HarnessEvent::Started {
51                model: Some(model.to_string()),
52            }),
53            Some(tag) if tag == self.step_tag => (self.parse_step)(&value[self.step_payload_key]),
54            _ => None,
55        };
56        event.into_iter().collect()
57    }
58}
59
60pub(crate) fn exit_message(prefix: &str, output: &Output) -> String {
61    let exit = output
62        .exit_code
63        .map_or("a signal".to_string(), |code| format!("exit code {code}"));
64    let tail = output.stderr_tail.trim();
65    if tail.is_empty() {
66        format!("{prefix} ({exit})")
67    } else {
68        format!("{prefix} ({exit}): {tail}")
69    }
70}
71
72pub(crate) fn classify_error_text(
73    quota_signs: &[&str],
74    auth_signs: &[&str],
75    message: String,
76) -> Outcome {
77    let lower = message.to_lowercase();
78    let kind = if quota_signs.iter().any(|sign| lower.contains(sign)) {
79        FailureKind::Quota
80    } else if auth_signs.iter().any(|sign| lower.contains(sign)) {
81        FailureKind::Auth
82    } else {
83        FailureKind::Unknown
84    };
85    Outcome::failed(kind, message)
86}
87
88/// A subprocess call, described but not started.
89#[derive(Debug, Clone, PartialEq, Eq, Default)]
90pub struct Spawn {
91    pub program: PathBuf,
92    pub args: Vec<String>,
93    pub env_set: Vec<(String, String)>,
94    /// Variable names to remove; a trailing `*` removes every variable with that prefix.
95    pub env_remove: Vec<String>,
96    pub stdin: Option<String>,
97    /// Files the driver writes before it starts the process.
98    pub files: Vec<(PathBuf, String)>,
99}
100
101/// Everything a finished process produced.
102#[derive(Debug, Clone, PartialEq, Eq, Default)]
103pub struct Output {
104    pub exit_code: Option<i32>,
105    pub stdout: Vec<String>,
106    pub stderr_tail: String,
107}
108
109/// One value per lane, built from that lane's configuration.
110/// `Send` so a runner holding adapters can work on a background thread.
111pub trait Adapter: Send {
112    fn probe_spawns(&self) -> Vec<Spawn>;
113    fn probe_result(&self, outputs: &[Output]) -> Result<Probe, ProbeError>;
114    fn quota_spawn(&self) -> Option<Spawn>;
115    fn quota_result(&self, output: &Output) -> Option<QuotaReport>;
116    fn spawn(&self, job: &Job) -> Spawn;
117    /// One stdout line to zero or more events. Unknown lines yield nothing.
118    fn parse(&self, line: &str) -> Vec<HarnessEvent>;
119    /// The outcome of a job that ended by itself.
120    fn outcome(&self, job: &Job, output: &Output) -> Outcome;
121}
122
123pub mod agy;
124pub mod claude;
125pub mod codex;
126
127/// Extracts a JSON object from raw or fenced/prose-wrapped model output.
128pub fn extract_json_object(text: &str) -> Option<serde_json::Value> {
129    let trimmed = text.trim();
130    if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed)
131        && value.is_object()
132    {
133        return Some(value);
134    }
135    trimmed.match_indices('{').find_map(|(start, _)| {
136        serde_json::Deserializer::from_str(&trimmed[start..])
137            .into_iter::<serde_json::Value>()
138            .next()?
139            .ok()
140            .filter(serde_json::Value::is_object)
141    })
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use serde_json::json;
148
149    #[test]
150    fn extract_json_object_handles_raw_fenced_and_prose_wrapped_objects() {
151        assert_eq!(
152            extract_json_object(r#" {"a": 1} "#),
153            Some(json!({ "a": 1 }))
154        );
155        assert_eq!(
156            extract_json_object("Here is the plan:\n```json\n{\"tasks\": []}\n```\nDone {note}."),
157            Some(json!({ "tasks": [] }))
158        );
159        assert_eq!(extract_json_object("[1, 2, 3]"), None);
160        assert_eq!(extract_json_object("no json here {broken}"), None);
161    }
162}