1use std::collections::BTreeMap;
8use std::path::Path;
9use std::time::Duration;
10
11use blyte_agent::run::{Outcome, RunReport};
12use blyte_agent::sandbox::Profile;
13use blyte_agent::state::State;
14use serde::Serialize;
15
16use crate::task_runner::TaskConfig;
17
18pub const SCHEMA_VERSION: u32 = 1;
19
20#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
21pub struct UsageRecord {
22 pub input: u64,
23 pub cached: u64,
24 pub output: u64,
25 pub thinking: u64,
26}
27
28fn outcome_name(outcome: &Outcome) -> (&'static str, Option<String>) {
30 match outcome {
31 Outcome::Verified => ("verified", None),
32 Outcome::Finished => ("finished", None),
33 Outcome::BudgetExhausted => ("budget_exhausted", None),
34 Outcome::GateFailed => ("gate_failed", None),
35 Outcome::Blocked(why) => ("blocked", Some(why.clone())),
36 Outcome::Error(e) => ("error", Some(e.clone())),
37 }
38}
39
40#[derive(Debug, Clone, Default, Serialize, PartialEq)]
41pub struct RunRecord {
42 pub schema_version: u32,
43 pub harness_build: String,
45 pub outcome: String,
46 pub error: Option<String>,
47 pub final_message: Option<String>,
48 pub model_requested: Option<String>,
49 pub model_id: Option<String>,
50 pub effort: Option<String>,
51 pub context: String,
52 pub gated: bool,
53 pub gate_source: String,
55 #[serde(default)]
56 pub gate_left_out: Vec<String>,
57 pub container: Option<String>,
58 pub container_workdir: String,
59 pub sandboxed: bool,
61 pub sandbox: String,
63 pub network: String,
65 pub allow_read: Vec<String>,
67 pub pass_env: Vec<String>,
69 pub withheld_env: Vec<String>,
71 pub duration_seconds: f64,
72 pub turns: u32,
73 pub empty_turns: u32,
74 #[serde(default)]
75 pub truncated_turns: u32,
76 #[serde(default)]
77 pub read_loop: bool,
78 #[serde(default)]
79 pub peak_read_repeats: u32,
80 #[serde(default)]
81 pub fold_thrash: bool,
82 #[serde(default)]
83 pub stalled: bool,
84 #[serde(default)]
85 pub big_read_turns: u32,
86 pub tool_calls: u32,
87 pub gate_attempts: u32,
88 pub rollbacks: u32,
89 pub provider_retries: u32,
90 pub cost_usd: Option<f64>,
92 pub max_cost_usd: Option<f64>,
94 pub cost_capped: bool,
96 pub fold_budget: Option<usize>,
98 pub turn_usage: Vec<blyte_agent::run::TurnUsage>,
100 pub usage: UsageRecord,
101 pub gate_ms: Vec<u64>,
102 #[serde(default)]
103 pub gate_turns: Vec<u32>,
104 pub gate_wait_ms: Vec<u64>,
105 pub gate_failures: Vec<String>,
106 pub tool_counts: BTreeMap<String, u32>,
107 pub model_seconds: f64,
108 pub tools_seconds: f64,
109 pub gate_seconds: f64,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub quote_problems: Option<Vec<String>>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub claim_check_skipped: Option<String>,
116}
117
118impl RunRecord {
119 fn base(config: &TaskConfig, elapsed: Duration) -> Self {
120 let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
121 let sandboxed = config.container.is_none()
122 && config.sandbox == "on"
123 && blyte_agent::sandbox::available();
124 let withheld_env = if config.container.is_some() {
125 Vec::new()
126 } else {
127 blyte_agent::shell::withheld_env()
128 };
129 let gate_left_out = config
130 .report
131 .as_deref()
132 .and_then(read_gate_left_out_from_start)
133 .unwrap_or_default();
134 Self {
135 schema_version: SCHEMA_VERSION,
136 harness_build: env!("BLYTE_BUILD").into(),
137 outcome: "error".into(),
138 error: None,
139 final_message: None,
140 model_requested: config.model.clone(),
141 model_id: None,
142 effort: None,
143 context: config.context_strategy.clone(),
144 gated,
145 gate_source: if gated { "user" } else { "none" }.into(),
146 gate_left_out,
147 container: config.container.clone(),
148 container_workdir: config.container_workdir.clone(),
149 sandboxed,
150 sandbox: sandbox_kind(config),
151 network: config.network.clone(),
152 allow_read: config
153 .allow_read
154 .iter()
155 .map(|p| p.display().to_string())
156 .collect(),
157 pass_env: config.pass_env.clone(),
158 withheld_env,
159 duration_seconds: elapsed.as_secs_f64(),
160 turns: 0,
161 empty_turns: 0,
162 truncated_turns: 0,
163 read_loop: false,
164 peak_read_repeats: 0,
165 fold_thrash: false,
166 stalled: false,
167 big_read_turns: 0,
168 tool_calls: 0,
169 gate_attempts: 0,
170 rollbacks: 0,
171 provider_retries: 0,
172 cost_usd: None,
173 max_cost_usd: config.max_cost_usd,
174 cost_capped: false,
175 fold_budget: config.fold_budget,
176 turn_usage: Vec::new(),
177 usage: UsageRecord::default(),
178 gate_ms: Vec::new(),
179 gate_turns: Vec::new(),
180 gate_wait_ms: Vec::new(),
181 gate_failures: Vec::new(),
182 tool_counts: BTreeMap::new(),
183 model_seconds: 0.0,
184 tools_seconds: 0.0,
185 gate_seconds: 0.0,
186 quote_problems: None,
187 claim_check: None,
188 claim_check_skipped: None,
189 }
190 }
191
192 pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
194 Self {
195 error: Some(error.to_string()),
196 ..Self::base(config, elapsed)
197 }
198 }
199
200 pub fn from_run(
202 config: &TaskConfig,
203 model_id: &str,
204 outcome: &Outcome,
205 report: &RunReport,
206 state: &State,
207 elapsed: Duration,
208 ) -> Self {
209 let (outcome_name, error) = outcome_name(outcome);
210 let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
211 let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
212 let gate_ms_sum: u64 = report.gate_ms.iter().sum();
213 Self {
214 outcome: outcome_name.into(),
215 error,
216 final_message: report.final_message.clone(),
217 model_id: Some(model_id.to_string()),
218 turns: report.outcome_turns,
219 empty_turns: report.empty_turns,
220 truncated_turns: report.truncated_turns,
221 read_loop: report.read_loop,
222 peak_read_repeats: report.peak_read_repeats,
223 fold_thrash: report.fold_thrash,
224 stalled: report.stalled,
225 big_read_turns: report.big_read_turns,
226 tool_calls: report.tool_calls,
227 gate_attempts: report.gate_attempts,
228 rollbacks: state.runtime.rollbacks,
229 provider_retries: report.provider_retries,
230 cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
231 cost_capped: report.cost_capped,
232 turn_usage: report.turn_usage.clone(),
233 usage: UsageRecord {
234 input: report.usage.input,
235 cached: report.usage.cached,
236 output: report.usage.output,
237 thinking: report.usage.thinking,
238 },
239 gate_ms: report.gate_ms.clone(),
240 gate_turns: report.gate_turns.clone(),
241 gate_wait_ms: report.gate_wait_ms.clone(),
242 gate_failures: report.gate_failures.clone(),
243 tool_counts: report.tool_counts.clone(),
244 model_seconds: model_ms as f64 / 1000.0,
245 tools_seconds: tools_ms as f64 / 1000.0,
246 gate_seconds: gate_ms_sum as f64 / 1000.0,
247 quote_problems: report.quote_problems.clone(),
248 claim_check: report.claim_check.clone(),
249 claim_check_skipped: report.claim_check_skipped.clone(),
250 ..Self::base(config, elapsed)
251 }
252 }
253}
254
255pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
256 let json = serde_json::to_string_pretty(record)
257 .map_err(|e| format!("report serialisation failed: {e}"))?;
258 std::fs::write(path, json + "\n")
259 .map_err(|e| format!("cannot write report {}: {e}", path.display()))
260}
261
262fn read_gate_left_out_from_start(report_path: &Path) -> Option<Vec<String>> {
263 let file_name = report_path.file_name()?.to_str()?;
264 let id = file_name.strip_suffix(".report.json")?;
265 let start_path = report_path.with_file_name(format!("{id}.start.json"));
266 let content = std::fs::read_to_string(start_path).ok()?;
267 let val: serde_json::Value = serde_json::from_str(&content).ok()?;
268 let arr = val.get("gate_left_out")?.as_array()?;
269 let mut out = Vec::new();
270 for item in arr {
271 if let (Some(cmd), Some(reason)) = (
272 item.get("command").and_then(|v| v.as_str()),
273 item.get("reason").and_then(|v| v.as_str()),
274 ) {
275 out.push(format!("{cmd} ({reason})"));
276 } else if let Some(s) = item.as_str() {
277 out.push(s.to_string());
278 }
279 }
280 Some(out)
281}
282
283pub fn sandbox_kind(config: &TaskConfig) -> String {
285 if config.container.is_some() {
286 return "container".into();
287 }
288 if config.sandbox != "on" || !blyte_agent::sandbox::available() {
289 return "off".into();
290 }
291 match blyte_agent::sandbox::default_profile_net(
292 &config.root,
293 &config.allow_read,
294 config.network == "on",
295 ) {
296 Profile::Seatbelt(_) => "seatbelt".into(),
297 Profile::Landlock(_) => "landlock".into(),
298 Profile::LandlockOffline(_) => "landlock-offline".into(),
299 Profile::LandlockConfined { block_tcp, .. } => {
300 if block_tcp {
301 "landlock-offline".into()
302 } else {
303 "landlock".into()
304 }
305 }
306 }
307}