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::{Deserialize, Serialize};
15
16use crate::task_runner::TaskConfig;
17
18pub const SCHEMA_VERSION: u32 = 1;
19
20#[derive(Debug, Clone, Default, Serialize, Deserialize, 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, Deserialize, 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 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub base_check_passed: Option<bool>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub base_check_seconds: Option<f64>,
120}
121
122impl RunRecord {
123 fn base(config: &TaskConfig, elapsed: Duration) -> Self {
124 let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
125 let sandboxed = config.container.is_none()
126 && config.sandbox == "on"
127 && blyte_agent::sandbox::available();
128 let withheld_env = if config.container.is_some() {
129 Vec::new()
130 } else {
131 blyte_agent::shell::withheld_env()
132 };
133 let gate_left_out = config
134 .report
135 .as_deref()
136 .and_then(read_gate_left_out_from_start)
137 .unwrap_or_default();
138 Self {
139 schema_version: SCHEMA_VERSION,
140 harness_build: env!("BLYTE_BUILD").into(),
141 outcome: "error".into(),
142 error: None,
143 final_message: None,
144 model_requested: config.model.clone(),
145 model_id: None,
146 effort: None,
147 context: config.context_strategy.clone(),
148 gated,
149 gate_source: if gated { "user" } else { "none" }.into(),
150 gate_left_out,
151 container: config.container.clone(),
152 container_workdir: config.container_workdir.clone(),
153 sandboxed,
154 sandbox: sandbox_kind(config),
155 network: config.network.clone(),
156 allow_read: config
157 .allow_read
158 .iter()
159 .map(|p| p.display().to_string())
160 .collect(),
161 pass_env: config.pass_env.clone(),
162 withheld_env,
163 duration_seconds: elapsed.as_secs_f64(),
164 turns: 0,
165 empty_turns: 0,
166 truncated_turns: 0,
167 read_loop: false,
168 peak_read_repeats: 0,
169 fold_thrash: false,
170 stalled: false,
171 big_read_turns: 0,
172 tool_calls: 0,
173 gate_attempts: 0,
174 rollbacks: 0,
175 provider_retries: 0,
176 cost_usd: None,
177 max_cost_usd: config.max_cost_usd,
178 cost_capped: false,
179 fold_budget: config.fold_budget,
180 turn_usage: Vec::new(),
181 usage: UsageRecord::default(),
182 gate_ms: Vec::new(),
183 gate_turns: Vec::new(),
184 gate_wait_ms: Vec::new(),
185 gate_failures: Vec::new(),
186 tool_counts: BTreeMap::new(),
187 model_seconds: 0.0,
188 tools_seconds: 0.0,
189 gate_seconds: 0.0,
190 quote_problems: None,
191 claim_check: None,
192 claim_check_skipped: None,
193 base_check_passed: None,
194 base_check_seconds: None,
195 }
196 }
197
198 pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
200 Self {
201 error: Some(error.to_string()),
202 ..Self::base(config, elapsed)
203 }
204 }
205
206 pub fn from_run(
208 config: &TaskConfig,
209 model_id: &str,
210 outcome: &Outcome,
211 report: &RunReport,
212 state: &State,
213 elapsed: Duration,
214 ) -> Self {
215 let (outcome_name, error) = outcome_name(outcome);
216 let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
217 let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
218 let gate_ms_sum: u64 = report.gate_ms.iter().sum();
219 Self {
220 outcome: outcome_name.into(),
221 error,
222 final_message: report.final_message.clone(),
223 model_id: Some(model_id.to_string()),
224 turns: report.outcome_turns,
225 empty_turns: report.empty_turns,
226 truncated_turns: report.truncated_turns,
227 read_loop: report.read_loop,
228 peak_read_repeats: report.peak_read_repeats,
229 fold_thrash: report.fold_thrash,
230 stalled: report.stalled,
231 big_read_turns: report.big_read_turns,
232 tool_calls: report.tool_calls,
233 gate_attempts: report.gate_attempts,
234 rollbacks: state.runtime.rollbacks,
235 provider_retries: report.provider_retries,
236 cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
237 cost_capped: report.cost_capped,
238 turn_usage: report.turn_usage.clone(),
239 usage: UsageRecord {
240 input: report.usage.input,
241 cached: report.usage.cached,
242 output: report.usage.output,
243 thinking: report.usage.thinking,
244 },
245 gate_ms: report.gate_ms.clone(),
246 gate_turns: report.gate_turns.clone(),
247 gate_wait_ms: report.gate_wait_ms.clone(),
248 gate_failures: report.gate_failures.clone(),
249 tool_counts: report.tool_counts.clone(),
250 model_seconds: model_ms as f64 / 1000.0,
251 tools_seconds: tools_ms as f64 / 1000.0,
252 gate_seconds: gate_ms_sum as f64 / 1000.0,
253 quote_problems: report.quote_problems.clone(),
254 claim_check: report.claim_check.clone(),
255 claim_check_skipped: report.claim_check_skipped.clone(),
256 base_check_passed: report.base_check_passed,
257 base_check_seconds: report.base_check_seconds,
258 ..Self::base(config, elapsed)
259 }
260 }
261}
262
263pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
264 let json = serde_json::to_string_pretty(record)
265 .map_err(|e| format!("report serialisation failed: {e}"))?;
266 std::fs::write(path, json + "\n")
267 .map_err(|e| format!("cannot write report {}: {e}", path.display()))
268}
269
270fn read_gate_left_out_from_start(report_path: &Path) -> Option<Vec<String>> {
271 let file_name = report_path.file_name()?.to_str()?;
272 let id = file_name.strip_suffix(".report.json")?;
273 let start_path = report_path.with_file_name(format!("{id}.start.json"));
274 let content = std::fs::read_to_string(start_path).ok()?;
275 let val: serde_json::Value = serde_json::from_str(&content).ok()?;
276 let arr = val.get("gate_left_out")?.as_array()?;
277 let mut out = Vec::new();
278 for item in arr {
279 if let (Some(cmd), Some(reason)) = (
280 item.get("command").and_then(|v| v.as_str()),
281 item.get("reason").and_then(|v| v.as_str()),
282 ) {
283 out.push(format!("{cmd} ({reason})"));
284 } else if let Some(s) = item.as_str() {
285 out.push(s.to_string());
286 }
287 }
288 Some(out)
289}
290
291pub fn sandbox_kind(config: &TaskConfig) -> String {
293 if config.container.is_some() {
294 return "container".into();
295 }
296 if config.sandbox != "on" || !blyte_agent::sandbox::available() {
297 return "off".into();
298 }
299 match blyte_agent::sandbox::default_profile_net(
300 &config.root,
301 &config.allow_read,
302 config.network == "on",
303 ) {
304 Profile::Seatbelt(_) => "seatbelt".into(),
305 Profile::Landlock(_) => "landlock".into(),
306 Profile::LandlockOffline(_) => "landlock-offline".into(),
307 Profile::LandlockConfined { block_tcp, .. } => {
308 if block_tcp {
309 "landlock-offline".into()
310 } else {
311 "landlock".into()
312 }
313 }
314 }
315}