use crate::usage_log::Entry;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Totals {
pub orchestrator_usd: f64,
pub implementers_usd: f64,
pub runs: usize,
}
impl Default for Totals {
fn default() -> Self {
Self {
orchestrator_usd: 0.0,
implementers_usd: 0.0,
runs: 0,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SessionTotals {
pub session: String,
pub first_ts: u64,
pub last_ts: u64,
pub runs: usize,
pub turns: usize,
pub model_reviews: usize,
pub cost_usd: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct BySessionReport {
pub sessions: Vec<SessionTotals>,
#[serde(flatten)]
pub totals: Totals,
}
fn matches_filters(
entry: &Entry,
session: Option<&str>,
since: Option<u64>,
repo: Option<&str>,
) -> bool {
if let Some(s) = session {
if entry.session.as_deref() != Some(s) {
return false;
}
}
if let Some(since_ts) = since {
if entry.ts < since_ts {
return false;
}
}
if let Some(r) = repo {
if entry.repo != r {
return false;
}
}
true
}
pub fn totals(
entries: &[Entry],
session: Option<&str>,
since: Option<u64>,
repo: Option<&str>,
) -> Totals {
let mut orchestrator_usd = 0.0;
let mut implementers_usd = 0.0;
let mut runs = 0;
for entry in entries {
if !matches_filters(entry, session, since, repo) {
continue;
}
let cost = entry.cost_usd.unwrap_or(0.0);
if entry.dispatch.is_some() {
implementers_usd += cost;
if entry.outcome != "turn" && entry.outcome != "model_review" {
runs += 1;
}
} else {
orchestrator_usd += cost;
}
}
Totals {
orchestrator_usd,
implementers_usd,
runs,
}
}
pub fn by_session(
entries: &[Entry],
session: Option<&str>,
since: Option<u64>,
repo: Option<&str>,
) -> Vec<SessionTotals> {
let mut grouped: HashMap<&str, SessionTotals> = HashMap::new();
for entry in entries {
if !matches_filters(entry, session, since, repo) {
continue;
}
let key = entry
.session
.as_deref()
.filter(|s| !s.trim().is_empty())
.unwrap_or("(none)");
let row = grouped.entry(key).or_insert_with(|| SessionTotals {
session: key.to_string(),
first_ts: entry.ts,
last_ts: entry.ts,
runs: 0,
turns: 0,
model_reviews: 0,
cost_usd: 0.0,
});
row.first_ts = row.first_ts.min(entry.ts);
row.last_ts = row.last_ts.max(entry.ts);
row.cost_usd += entry.cost_usd.unwrap_or(0.0);
if entry.outcome == "model_review" {
row.model_reviews += 1;
} else {
row.turns += entry.turns as usize;
if entry.dispatch.is_some() && entry.outcome != "turn" {
row.runs += 1;
}
}
}
let mut rows: Vec<SessionTotals> = grouped.into_values().collect();
rows.sort_by(|a, b| {
a.first_ts
.cmp(&b.first_ts)
.then_with(|| a.session.cmp(&b.session))
});
rows
}
fn format_utc_ts(ts: u64) -> String {
let days = (ts / 86_400) as i64;
let secs_of_day = ts % 86_400;
let hour = secs_of_day / 3_600;
let min = (secs_of_day % 3_600) / 60;
let sec = secs_of_day % 60;
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if m <= 2 { y + 1 } else { y };
format!("{year:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}Z")
}
pub fn format_by_session(rows: &[SessionTotals], totals: &Totals) -> String {
let mut lines = Vec::with_capacity(rows.len() + 1);
for row in rows {
lines.push(format!(
"{} {} .. {} {} runs, {} turns, {} model reviews ${:.2}",
row.session,
format_utc_ts(row.first_ts),
format_utc_ts(row.last_ts),
row.runs,
row.turns,
row.model_reviews,
row.cost_usd
));
}
lines.push(format_totals(totals));
lines.join("\n")
}
pub fn format_totals(totals: &Totals) -> String {
let total = totals.orchestrator_usd + totals.implementers_usd;
format!(
"blyte ${:.2} (orchestrator ${:.2}, implementers ${:.2} in {} runs)",
total, totals.orchestrator_usd, totals.implementers_usd, totals.runs
)
}
impl std::fmt::Display for Totals {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", format_totals(self))
}
}
pub fn run(args: &crate::cli::CostArgs) -> i32 {
let entries = crate::usage_log::default_path()
.as_deref()
.map(crate::usage_log::read)
.unwrap_or_default();
let repo_filter = args.repo.as_ref().map(|p| {
if p.exists() {
if let Ok(c) = std::fs::canonicalize(p) {
return crate::usage_log::repo_of(&c);
}
}
crate::usage_log::repo_of(p)
});
let t = totals(
&entries,
args.session.as_deref(),
args.since,
repo_filter.as_deref(),
);
if args.by_session {
let sessions = by_session(
&entries,
args.session.as_deref(),
args.since,
repo_filter.as_deref(),
);
if args.json {
let report = BySessionReport {
sessions,
totals: t,
};
let json_str = serde_json::to_string_pretty(&report).unwrap();
println!("{json_str}");
} else {
println!("{}", format_by_session(&sessions, &t));
}
} else if args.json {
let json_str = serde_json::to_string_pretty(&t).unwrap();
println!("{json_str}");
} else {
println!("{}", format_totals(&t));
}
0
}
#[cfg(test)]
mod tests {
use super::*;
fn make_entry(
ts: u64,
repo: &str,
session: Option<&str>,
dispatch: Option<&str>,
cost_usd: Option<f64>,
) -> Entry {
Entry {
ts,
repo: repo.to_string(),
session: session.map(String::from),
dispatch: dispatch.map(String::from),
research: false,
model: "test-model".into(),
outcome: "verified".into(),
turns: 1,
input: 100,
cached: 0,
output: 50,
thinking: 0,
cost_usd,
}
}
#[test]
fn test_totals_filters_and_aggregation() {
let entries = vec![
make_entry(500, "/repo/alpha", Some("sess-1"), None, Some(0.10)),
make_entry(1500, "/repo/alpha", Some("sess-1"), Some("d1"), Some(0.20)),
make_entry(1500, "/repo/beta", Some("sess-1"), Some("d2"), None),
make_entry(2000, "/repo/beta", Some("sess-2"), None, Some(0.50)),
make_entry(2500, "/repo/beta", Some("sess-2"), Some("d3"), Some(0.40)),
];
let t_all = totals(&entries, None, None, None);
assert!((t_all.orchestrator_usd - 0.60).abs() < 1e-6);
assert!((t_all.implementers_usd - 0.60).abs() < 1e-6);
assert_eq!(t_all.runs, 3);
let t_s1 = totals(&entries, Some("sess-1"), None, None);
assert!((t_s1.orchestrator_usd - 0.10).abs() < 1e-6);
assert!((t_s1.implementers_usd - 0.20).abs() < 1e-6);
assert_eq!(t_s1.runs, 2);
let t_s2 = totals(&entries, Some("sess-2"), None, None);
assert!((t_s2.orchestrator_usd - 0.50).abs() < 1e-6);
assert!((t_s2.implementers_usd - 0.40).abs() < 1e-6);
assert_eq!(t_s2.runs, 1);
let t_since = totals(&entries, None, Some(1000), None);
assert!((t_since.orchestrator_usd - 0.50).abs() < 1e-6);
assert!((t_since.implementers_usd - 0.60).abs() < 1e-6);
assert_eq!(t_since.runs, 3);
let t_alpha = totals(&entries, None, None, Some("/repo/alpha"));
assert!((t_alpha.orchestrator_usd - 0.10).abs() < 1e-6);
assert!((t_alpha.implementers_usd - 0.20).abs() < 1e-6);
assert_eq!(t_alpha.runs, 1);
let t_beta = totals(&entries, None, None, Some("/repo/beta"));
assert!((t_beta.orchestrator_usd - 0.50).abs() < 1e-6);
assert!((t_beta.implementers_usd - 0.40).abs() < 1e-6);
assert_eq!(t_beta.runs, 2);
let t_comb1 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/alpha"));
assert!((t_comb1.orchestrator_usd - 0.0).abs() < 1e-6);
assert!((t_comb1.implementers_usd - 0.20).abs() < 1e-6);
assert_eq!(t_comb1.runs, 1);
let t_comb2 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/beta"));
assert!((t_comb2.orchestrator_usd - 0.0).abs() < 1e-6);
assert!((t_comb2.implementers_usd - 0.0).abs() < 1e-6);
assert_eq!(t_comb2.runs, 1);
let t_comb3 = totals(&entries, Some("sess-2"), Some(1000), Some("/repo/beta"));
assert!((t_comb3.orchestrator_usd - 0.50).abs() < 1e-6);
assert!((t_comb3.implementers_usd - 0.40).abs() < 1e-6);
assert_eq!(t_comb3.runs, 1);
let t_none = totals(&entries, Some("sess-nonexistent"), None, None);
assert_eq!(
t_none,
Totals {
orchestrator_usd: 0.0,
implementers_usd: 0.0,
runs: 0,
}
);
}
#[test]
fn test_format_totals() {
let known = Totals {
orchestrator_usd: 1.25,
implementers_usd: 2.50,
runs: 3,
};
assert_eq!(
format_totals(&known),
"blyte $3.75 (orchestrator $1.25, implementers $2.50 in 3 runs)"
);
assert_eq!(
known.to_string(),
"blyte $3.75 (orchestrator $1.25, implementers $2.50 in 3 runs)"
);
let zero = Totals::default();
assert_eq!(
format_totals(&zero),
"blyte $0.00 (orchestrator $0.00, implementers $0.00 in 0 runs)"
);
}
#[test]
fn test_totals_json() {
let t = Totals {
orchestrator_usd: 1.25,
implementers_usd: 2.50,
runs: 3,
};
let json = serde_json::to_string(&t).unwrap();
let parsed: Totals = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, t);
}
#[test]
fn test_format_utc_ts() {
assert_eq!(format_utc_ts(0), "1970-01-01T00:00:00Z");
assert_eq!(format_utc_ts(1_700_000_100), "2023-11-14T22:15:00Z");
assert_eq!(format_utc_ts(1_709_164_800), "2024-02-29T00:00:00Z");
}
}