1use crate::usage_log::Entry;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
12pub struct Totals {
13 pub orchestrator_usd: f64,
14 pub implementers_usd: f64,
15 pub runs: usize,
16}
17
18impl Default for Totals {
19 fn default() -> Self {
20 Self {
21 orchestrator_usd: 0.0,
22 implementers_usd: 0.0,
23 runs: 0,
24 }
25 }
26}
27
28#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
30pub struct SessionTotals {
31 pub session: String,
32 pub first_ts: u64,
33 pub last_ts: u64,
34 pub runs: usize,
35 pub turns: usize,
36 pub model_reviews: usize,
37 pub cost_usd: f64,
38}
39
40#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
42pub struct BySessionReport {
43 pub sessions: Vec<SessionTotals>,
44 #[serde(flatten)]
45 pub totals: Totals,
46}
47
48fn matches_filters(
49 entry: &Entry,
50 session: Option<&str>,
51 since: Option<u64>,
52 repo: Option<&str>,
53) -> bool {
54 if let Some(s) = session {
55 if entry.session.as_deref() != Some(s) {
56 return false;
57 }
58 }
59 if let Some(since_ts) = since {
60 if entry.ts < since_ts {
61 return false;
62 }
63 }
64 if let Some(r) = repo {
65 if entry.repo != r {
66 return false;
67 }
68 }
69 true
70}
71
72pub fn totals(
84 entries: &[Entry],
85 session: Option<&str>,
86 since: Option<u64>,
87 repo: Option<&str>,
88) -> Totals {
89 let mut orchestrator_usd = 0.0;
90 let mut implementers_usd = 0.0;
91 let mut runs = 0;
92
93 for entry in entries {
94 if !matches_filters(entry, session, since, repo) {
95 continue;
96 }
97
98 let cost = entry.cost_usd.unwrap_or(0.0);
99 if entry.dispatch.is_some() {
100 implementers_usd += cost;
101 if entry.outcome != "turn" && entry.outcome != "model_review" {
102 runs += 1;
103 }
104 } else {
105 orchestrator_usd += cost;
106 }
107 }
108
109 Totals {
110 orchestrator_usd,
111 implementers_usd,
112 runs,
113 }
114}
115
116pub fn by_session(
120 entries: &[Entry],
121 session: Option<&str>,
122 since: Option<u64>,
123 repo: Option<&str>,
124) -> Vec<SessionTotals> {
125 let mut grouped: HashMap<&str, SessionTotals> = HashMap::new();
126
127 for entry in entries {
128 if !matches_filters(entry, session, since, repo) {
129 continue;
130 }
131
132 let key = entry
133 .session
134 .as_deref()
135 .filter(|s| !s.trim().is_empty())
136 .unwrap_or("(none)");
137
138 let row = grouped.entry(key).or_insert_with(|| SessionTotals {
139 session: key.to_string(),
140 first_ts: entry.ts,
141 last_ts: entry.ts,
142 runs: 0,
143 turns: 0,
144 model_reviews: 0,
145 cost_usd: 0.0,
146 });
147
148 row.first_ts = row.first_ts.min(entry.ts);
149 row.last_ts = row.last_ts.max(entry.ts);
150 row.cost_usd += entry.cost_usd.unwrap_or(0.0);
151
152 if entry.outcome == "model_review" {
153 row.model_reviews += 1;
154 } else {
155 row.turns += entry.turns as usize;
156 if entry.dispatch.is_some() && entry.outcome != "turn" {
157 row.runs += 1;
158 }
159 }
160 }
161
162 let mut rows: Vec<SessionTotals> = grouped.into_values().collect();
163 rows.sort_by(|a, b| {
164 a.first_ts
165 .cmp(&b.first_ts)
166 .then_with(|| a.session.cmp(&b.session))
167 });
168 rows
169}
170
171fn format_utc_ts(ts: u64) -> String {
172 let days = (ts / 86_400) as i64;
173 let secs_of_day = ts % 86_400;
174 let hour = secs_of_day / 3_600;
175 let min = (secs_of_day % 3_600) / 60;
176 let sec = secs_of_day % 60;
177
178 let z = days + 719_468;
179 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
180 let doe = (z - era * 146_097) as u64;
181 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
182 let y = yoe as i64 + era * 400;
183 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
184 let mp = (5 * doy + 2) / 153;
185 let d = doy - (153 * mp + 2) / 5 + 1;
186 let m = if mp < 10 { mp + 3 } else { mp - 9 };
187 let year = if m <= 2 { y + 1 } else { y };
188
189 format!("{year:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}Z")
190}
191
192pub fn format_by_session(rows: &[SessionTotals], totals: &Totals) -> String {
194 let mut lines = Vec::with_capacity(rows.len() + 1);
195 for row in rows {
196 lines.push(format!(
197 "{} {} .. {} {} runs, {} turns, {} model reviews ${:.2}",
198 row.session,
199 format_utc_ts(row.first_ts),
200 format_utc_ts(row.last_ts),
201 row.runs,
202 row.turns,
203 row.model_reviews,
204 row.cost_usd
205 ));
206 }
207 lines.push(format_totals(totals));
208 lines.join("\n")
209}
210
211pub fn format_totals(totals: &Totals) -> String {
214 let total = totals.orchestrator_usd + totals.implementers_usd;
215 format!(
216 "blyte ${:.2} (orchestrator ${:.2}, implementers ${:.2} in {} runs)",
217 total, totals.orchestrator_usd, totals.implementers_usd, totals.runs
218 )
219}
220
221impl std::fmt::Display for Totals {
222 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 write!(f, "{}", format_totals(self))
224 }
225}
226
227pub fn run(args: &crate::cli::CostArgs) -> i32 {
229 let entries = crate::usage_log::default_path()
230 .as_deref()
231 .map(crate::usage_log::read)
232 .unwrap_or_default();
233
234 let repo_filter = args.repo.as_ref().map(|p| {
235 if p.exists() {
236 if let Ok(c) = std::fs::canonicalize(p) {
237 return crate::usage_log::repo_of(&c);
238 }
239 }
240 crate::usage_log::repo_of(p)
241 });
242
243 let t = totals(
244 &entries,
245 args.session.as_deref(),
246 args.since,
247 repo_filter.as_deref(),
248 );
249
250 if args.by_session {
251 let sessions = by_session(
252 &entries,
253 args.session.as_deref(),
254 args.since,
255 repo_filter.as_deref(),
256 );
257 if args.json {
258 let report = BySessionReport {
259 sessions,
260 totals: t,
261 };
262 let json_str = serde_json::to_string_pretty(&report).unwrap();
263 println!("{json_str}");
264 } else {
265 println!("{}", format_by_session(&sessions, &t));
266 }
267 } else if args.json {
268 let json_str = serde_json::to_string_pretty(&t).unwrap();
269 println!("{json_str}");
270 } else {
271 println!("{}", format_totals(&t));
272 }
273
274 0
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280
281 fn make_entry(
282 ts: u64,
283 repo: &str,
284 session: Option<&str>,
285 dispatch: Option<&str>,
286 cost_usd: Option<f64>,
287 ) -> Entry {
288 Entry {
289 ts,
290 repo: repo.to_string(),
291 session: session.map(String::from),
292 dispatch: dispatch.map(String::from),
293 research: false,
294 model: "test-model".into(),
295 outcome: "verified".into(),
296 turns: 1,
297 input: 100,
298 cached: 0,
299 output: 50,
300 thinking: 0,
301 cost_usd,
302 }
303 }
304
305 #[test]
306 fn test_totals_filters_and_aggregation() {
307 let entries = vec![
314 make_entry(500, "/repo/alpha", Some("sess-1"), None, Some(0.10)),
315 make_entry(1500, "/repo/alpha", Some("sess-1"), Some("d1"), Some(0.20)),
316 make_entry(1500, "/repo/beta", Some("sess-1"), Some("d2"), None),
317 make_entry(2000, "/repo/beta", Some("sess-2"), None, Some(0.50)),
318 make_entry(2500, "/repo/beta", Some("sess-2"), Some("d3"), Some(0.40)),
319 ];
320
321 let t_all = totals(&entries, None, None, None);
323 assert!((t_all.orchestrator_usd - 0.60).abs() < 1e-6);
324 assert!((t_all.implementers_usd - 0.60).abs() < 1e-6);
325 assert_eq!(t_all.runs, 3);
326
327 let t_s1 = totals(&entries, Some("sess-1"), None, None);
329 assert!((t_s1.orchestrator_usd - 0.10).abs() < 1e-6);
330 assert!((t_s1.implementers_usd - 0.20).abs() < 1e-6);
331 assert_eq!(t_s1.runs, 2);
332
333 let t_s2 = totals(&entries, Some("sess-2"), None, None);
335 assert!((t_s2.orchestrator_usd - 0.50).abs() < 1e-6);
336 assert!((t_s2.implementers_usd - 0.40).abs() < 1e-6);
337 assert_eq!(t_s2.runs, 1);
338
339 let t_since = totals(&entries, None, Some(1000), None);
341 assert!((t_since.orchestrator_usd - 0.50).abs() < 1e-6);
342 assert!((t_since.implementers_usd - 0.60).abs() < 1e-6);
343 assert_eq!(t_since.runs, 3);
344
345 let t_alpha = totals(&entries, None, None, Some("/repo/alpha"));
347 assert!((t_alpha.orchestrator_usd - 0.10).abs() < 1e-6);
348 assert!((t_alpha.implementers_usd - 0.20).abs() < 1e-6);
349 assert_eq!(t_alpha.runs, 1);
350
351 let t_beta = totals(&entries, None, None, Some("/repo/beta"));
353 assert!((t_beta.orchestrator_usd - 0.50).abs() < 1e-6);
354 assert!((t_beta.implementers_usd - 0.40).abs() < 1e-6);
355 assert_eq!(t_beta.runs, 2);
356
357 let t_comb1 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/alpha"));
360 assert!((t_comb1.orchestrator_usd - 0.0).abs() < 1e-6);
361 assert!((t_comb1.implementers_usd - 0.20).abs() < 1e-6);
362 assert_eq!(t_comb1.runs, 1);
363
364 let t_comb2 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/beta"));
366 assert!((t_comb2.orchestrator_usd - 0.0).abs() < 1e-6);
367 assert!((t_comb2.implementers_usd - 0.0).abs() < 1e-6);
368 assert_eq!(t_comb2.runs, 1);
369
370 let t_comb3 = totals(&entries, Some("sess-2"), Some(1000), Some("/repo/beta"));
372 assert!((t_comb3.orchestrator_usd - 0.50).abs() < 1e-6);
373 assert!((t_comb3.implementers_usd - 0.40).abs() < 1e-6);
374 assert_eq!(t_comb3.runs, 1);
375
376 let t_none = totals(&entries, Some("sess-nonexistent"), None, None);
378 assert_eq!(
379 t_none,
380 Totals {
381 orchestrator_usd: 0.0,
382 implementers_usd: 0.0,
383 runs: 0,
384 }
385 );
386 }
387
388 #[test]
389 fn test_format_totals() {
390 let known = Totals {
391 orchestrator_usd: 1.25,
392 implementers_usd: 2.50,
393 runs: 3,
394 };
395 assert_eq!(
396 format_totals(&known),
397 "blyte $3.75 (orchestrator $1.25, implementers $2.50 in 3 runs)"
398 );
399 assert_eq!(
400 known.to_string(),
401 "blyte $3.75 (orchestrator $1.25, implementers $2.50 in 3 runs)"
402 );
403
404 let zero = Totals::default();
405 assert_eq!(
406 format_totals(&zero),
407 "blyte $0.00 (orchestrator $0.00, implementers $0.00 in 0 runs)"
408 );
409 }
410
411 #[test]
412 fn test_totals_json() {
413 let t = Totals {
414 orchestrator_usd: 1.25,
415 implementers_usd: 2.50,
416 runs: 3,
417 };
418 let json = serde_json::to_string(&t).unwrap();
419 let parsed: Totals = serde_json::from_str(&json).unwrap();
420 assert_eq!(parsed, t);
421 }
422
423 #[test]
424 fn test_format_utc_ts() {
425 assert_eq!(format_utc_ts(0), "1970-01-01T00:00:00Z");
426 assert_eq!(format_utc_ts(1_700_000_100), "2023-11-14T22:15:00Z");
427 assert_eq!(format_utc_ts(1_709_164_800), "2024-02-29T00:00:00Z");
428 }
429}