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) fn exit_message(prefix: &str, output: &Output) -> String {
37    let exit = output
38        .exit_code
39        .map_or("a signal".to_string(), |code| format!("exit code {code}"));
40    let tail = output.stderr_tail.trim();
41    if tail.is_empty() {
42        format!("{prefix} ({exit})")
43    } else {
44        format!("{prefix} ({exit}): {tail}")
45    }
46}
47
48pub(crate) fn classify_error_text(
49    quota_signs: &[&str],
50    auth_signs: &[&str],
51    message: String,
52) -> Outcome {
53    let lower = message.to_lowercase();
54    let kind = if quota_signs.iter().any(|sign| lower.contains(sign)) {
55        FailureKind::Quota
56    } else if auth_signs.iter().any(|sign| lower.contains(sign)) {
57        FailureKind::Auth
58    } else {
59        FailureKind::Unknown
60    };
61    Outcome::failed(kind, message)
62}
63
64/// A subprocess call, described but not started.
65#[derive(Debug, Clone, PartialEq, Eq, Default)]
66pub struct Spawn {
67    pub program: PathBuf,
68    pub args: Vec<String>,
69    pub env_set: Vec<(String, String)>,
70    /// Variable names to remove; a trailing `*` removes every variable with that prefix.
71    pub env_remove: Vec<String>,
72    pub stdin: Option<String>,
73    /// Files the driver writes before it starts the process.
74    pub files: Vec<(PathBuf, String)>,
75}
76
77/// Everything a finished process produced.
78#[derive(Debug, Clone, PartialEq, Eq, Default)]
79pub struct Output {
80    pub exit_code: Option<i32>,
81    pub stdout: Vec<String>,
82    pub stderr_tail: String,
83}
84
85/// One value per lane, built from that lane's configuration.
86/// `Send` so a runner holding adapters can work on a background thread.
87pub trait Adapter: Send {
88    fn probe_spawns(&self) -> Vec<Spawn>;
89    fn probe_result(&self, outputs: &[Output]) -> Result<Probe, ProbeError>;
90    fn quota_spawn(&self) -> Option<Spawn>;
91    fn quota_result(&self, output: &Output) -> Option<QuotaReport>;
92    fn spawn(&self, job: &Job) -> Spawn;
93    /// One stdout line to zero or more events. Unknown lines yield nothing.
94    fn parse(&self, line: &str) -> Vec<HarnessEvent>;
95    /// The outcome of a job that ended by itself.
96    fn outcome(&self, job: &Job, output: &Output) -> Outcome;
97}
98
99pub mod agy;
100pub mod claude;
101pub mod codex;
102
103/// Extracts a JSON object from raw or fenced/prose-wrapped model output.
104pub fn extract_json_object(text: &str) -> Option<serde_json::Value> {
105    let trimmed = text.trim();
106    if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed)
107        && value.is_object()
108    {
109        return Some(value);
110    }
111    trimmed.match_indices('{').find_map(|(start, _)| {
112        serde_json::Deserializer::from_str(&trimmed[start..])
113            .into_iter::<serde_json::Value>()
114            .next()?
115            .ok()
116            .filter(serde_json::Value::is_object)
117    })
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use serde_json::json;
124
125    #[test]
126    fn extract_json_object_handles_raw_fenced_and_prose_wrapped_objects() {
127        assert_eq!(
128            extract_json_object(r#" {"a": 1} "#),
129            Some(json!({ "a": 1 }))
130        );
131        assert_eq!(
132            extract_json_object("Here is the plan:\n```json\n{\"tasks\": []}\n```\nDone {note}."),
133            Some(json!({ "tasks": [] }))
134        );
135        assert_eq!(extract_json_object("[1, 2, 3]"), None);
136        assert_eq!(extract_json_object("no json here {broken}"), None);
137    }
138}