onerig_core/adapter/
mod.rs1use 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
88pub(crate) fn append_schema_instruction(prompt: &mut String, schema: &str) {
89 prompt.push_str("\n\nAnswer with ONLY a JSON object matching this JSON Schema:\n");
90 prompt.push_str(schema);
91}
92
93pub(crate) fn structured_or_done(harness: &str, job: &Job, text: String) -> Outcome {
94 if job.schema.is_none() {
95 return Outcome::Done {
96 text,
97 structured: None,
98 };
99 }
100 match extract_json_object(&text) {
101 Some(value) => Outcome::Done {
102 text,
103 structured: Some(value),
104 },
105 None => Outcome::failed(
106 FailureKind::Unknown,
107 format!("{harness} gave no structured answer"),
108 ),
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Default)]
114pub struct Spawn {
115 pub program: PathBuf,
116 pub args: Vec<String>,
117 pub env_set: Vec<(String, String)>,
118 pub env_remove: Vec<String>,
120 pub stdin: Option<String>,
121 pub files: Vec<(PathBuf, String)>,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Default)]
127pub struct Output {
128 pub exit_code: Option<i32>,
129 pub stdout: Vec<String>,
130 pub stderr_tail: String,
131}
132
133pub trait Adapter: Send {
136 fn probe_spawns(&self) -> Vec<Spawn>;
137 fn probe_result(&self, outputs: &[Output]) -> Result<Probe, ProbeError>;
138 fn quota_spawn(&self) -> Option<Spawn>;
139 fn quota_result(&self, output: &Output) -> Option<QuotaReport>;
140 fn spawn(&self, job: &Job) -> Spawn;
141 fn parse(&self, line: &str) -> Vec<HarnessEvent>;
143 fn outcome(&self, job: &Job, output: &Output) -> Outcome;
145}
146
147pub mod agy;
148pub mod claude;
149pub mod codex;
150pub mod opencode;
151
152pub fn extract_json_object(text: &str) -> Option<serde_json::Value> {
154 let trimmed = text.trim();
155 if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed)
156 && value.is_object()
157 {
158 return Some(value);
159 }
160 trimmed.match_indices('{').find_map(|(start, _)| {
161 serde_json::Deserializer::from_str(&trimmed[start..])
162 .into_iter::<serde_json::Value>()
163 .next()?
164 .ok()
165 .filter(serde_json::Value::is_object)
166 })
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use serde_json::json;
173
174 #[test]
175 fn extract_json_object_handles_raw_fenced_and_prose_wrapped_objects() {
176 assert_eq!(
177 extract_json_object(r#" {"a": 1} "#),
178 Some(json!({ "a": 1 }))
179 );
180 assert_eq!(
181 extract_json_object("Here is the plan:\n```json\n{\"tasks\": []}\n```\nDone {note}."),
182 Some(json!({ "tasks": [] }))
183 );
184 assert_eq!(extract_json_object("[1, 2, 3]"), None);
185 assert_eq!(extract_json_object("no json here {broken}"), None);
186 }
187}