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 pub container: Option<String>,
56 pub container_workdir: String,
57 pub sandboxed: bool,
59 pub sandbox: String,
61 pub network: String,
63 pub allow_read: Vec<String>,
65 pub pass_env: Vec<String>,
67 pub withheld_env: Vec<String>,
69 pub duration_seconds: f64,
70 pub turns: u32,
71 pub empty_turns: u32,
72 pub tool_calls: u32,
73 pub gate_attempts: u32,
74 pub rollbacks: u32,
75 pub provider_retries: u32,
76 pub cost_usd: Option<f64>,
78 pub max_cost_usd: Option<f64>,
80 pub cost_capped: bool,
82 pub fold_budget: Option<usize>,
84 pub turn_usage: Vec<blyte_agent::run::TurnUsage>,
86 pub usage: UsageRecord,
87 pub gate_ms: Vec<u64>,
88 #[serde(default)]
89 pub gate_turns: Vec<u32>,
90 pub gate_wait_ms: Vec<u64>,
91 pub gate_failures: Vec<String>,
92 pub tool_counts: BTreeMap<String, u32>,
93 pub model_seconds: f64,
94 pub tools_seconds: f64,
95 pub gate_seconds: f64,
96}
97
98impl RunRecord {
99 fn base(config: &TaskConfig, elapsed: Duration) -> Self {
100 let gated = config.gate.as_deref().is_some_and(|g| !g.trim().is_empty());
101 let sandboxed = config.container.is_none()
102 && config.sandbox == "on"
103 && blyte_agent::sandbox::available();
104 let withheld_env = if config.container.is_some() {
105 Vec::new()
106 } else {
107 blyte_agent::shell::withheld_env()
108 };
109 Self {
110 schema_version: SCHEMA_VERSION,
111 harness_build: env!("BLYTE_BUILD").into(),
112 outcome: "error".into(),
113 error: None,
114 final_message: None,
115 model_requested: config.model.clone(),
116 model_id: None,
117 effort: None,
118 context: config.context_strategy.clone(),
119 gated,
120 gate_source: if gated { "user" } else { "none" }.into(),
121 container: config.container.clone(),
122 container_workdir: config.container_workdir.clone(),
123 sandboxed,
124 sandbox: sandbox_kind(config),
125 network: config.network.clone(),
126 allow_read: config
127 .allow_read
128 .iter()
129 .map(|p| p.display().to_string())
130 .collect(),
131 pass_env: config.pass_env.clone(),
132 withheld_env,
133 duration_seconds: elapsed.as_secs_f64(),
134 turns: 0,
135 empty_turns: 0,
136 tool_calls: 0,
137 gate_attempts: 0,
138 rollbacks: 0,
139 provider_retries: 0,
140 cost_usd: None,
141 max_cost_usd: config.max_cost_usd,
142 cost_capped: false,
143 fold_budget: config.fold_budget,
144 turn_usage: Vec::new(),
145 usage: UsageRecord::default(),
146 gate_ms: Vec::new(),
147 gate_turns: Vec::new(),
148 gate_wait_ms: Vec::new(),
149 gate_failures: Vec::new(),
150 tool_counts: BTreeMap::new(),
151 model_seconds: 0.0,
152 tools_seconds: 0.0,
153 gate_seconds: 0.0,
154 }
155 }
156
157 pub fn from_error(config: &TaskConfig, error: &str, elapsed: Duration) -> Self {
159 Self {
160 error: Some(error.to_string()),
161 ..Self::base(config, elapsed)
162 }
163 }
164
165 pub fn from_run(
167 config: &TaskConfig,
168 model_id: &str,
169 outcome: &Outcome,
170 report: &RunReport,
171 state: &State,
172 elapsed: Duration,
173 ) -> Self {
174 let (outcome_name, error) = outcome_name(outcome);
175 let model_ms: u64 = report.turn_usage.iter().map(|t| t.model_ms).sum();
176 let tools_ms: u64 = report.turn_usage.iter().map(|t| t.tools_ms).sum();
177 let gate_ms_sum: u64 = report.gate_ms.iter().sum();
178 Self {
179 outcome: outcome_name.into(),
180 error,
181 final_message: report.final_message.clone(),
182 model_id: Some(model_id.to_string()),
183 turns: report.outcome_turns,
184 empty_turns: report.empty_turns,
185 tool_calls: report.tool_calls,
186 gate_attempts: report.gate_attempts,
187 rollbacks: state.runtime.rollbacks,
188 provider_retries: report.provider_retries,
189 cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(&report.usage)),
190 cost_capped: report.cost_capped,
191 turn_usage: report.turn_usage.clone(),
192 usage: UsageRecord {
193 input: report.usage.input,
194 cached: report.usage.cached,
195 output: report.usage.output,
196 thinking: report.usage.thinking,
197 },
198 gate_ms: report.gate_ms.clone(),
199 gate_turns: report.gate_turns.clone(),
200 gate_wait_ms: report.gate_wait_ms.clone(),
201 gate_failures: report.gate_failures.clone(),
202 tool_counts: report.tool_counts.clone(),
203 model_seconds: model_ms as f64 / 1000.0,
204 tools_seconds: tools_ms as f64 / 1000.0,
205 gate_seconds: gate_ms_sum as f64 / 1000.0,
206 ..Self::base(config, elapsed)
207 }
208 }
209}
210
211pub fn write(path: &Path, record: &RunRecord) -> Result<(), String> {
212 let json = serde_json::to_string_pretty(record)
213 .map_err(|e| format!("report serialisation failed: {e}"))?;
214 std::fs::write(path, json + "\n")
215 .map_err(|e| format!("cannot write report {}: {e}", path.display()))
216}
217
218pub fn sandbox_kind(config: &TaskConfig) -> String {
220 if config.container.is_some() {
221 return "container".into();
222 }
223 if config.sandbox != "on" || !blyte_agent::sandbox::available() {
224 return "off".into();
225 }
226 match blyte_agent::sandbox::default_profile_net(
227 &config.root,
228 &config.allow_read,
229 config.network == "on",
230 ) {
231 Profile::Seatbelt(_) => "seatbelt".into(),
232 Profile::Landlock(_) => "landlock".into(),
233 Profile::LandlockOffline(_) => "landlock-offline".into(),
234 Profile::LandlockConfined { block_tcp, .. } => {
235 if block_tcp {
236 "landlock-offline".into()
237 } else {
238 "landlock".into()
239 }
240 }
241 }
242}