Skip to main content

blyte_cli/
cost.rs

1//! Combined conversation model and implementer cost reporting.
2//!
3//! Aggregates costs from the machine-wide usage log across interactive REPL sessions
4//! and dispatched worker runs.
5
6use crate::usage_log::Entry;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10/// Aggregated spend and run count.
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
12pub struct Totals {
13    pub conversation_usd: f64,
14    pub implementers_usd: f64,
15    pub runs: usize,
16}
17
18impl Default for Totals {
19    fn default() -> Self {
20        Self {
21            conversation_usd: 0.0,
22            implementers_usd: 0.0,
23            runs: 0,
24        }
25    }
26}
27
28/// Aggregated spend and activity counts for a single session.
29#[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/// JSON payload for `blyte cost --by-session --json`.
41#[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
72/// Aggregates usage log entries matching all given filters.
73///
74/// Filters:
75/// - `session`: entries with matching session ID
76/// - `since`: entries with timestamp >= `since`
77/// - `repo`: entries with matching repository path
78///
79/// Entries with `dispatch: Some(_)` count toward `implementers_usd`, and toward `runs` unless
80/// `outcome == "turn"` or `outcome == "model_review"`.
81/// Entries without dispatch count toward `conversation_usd`.
82/// An entry with `cost_usd: None` adds 0 to cost totals.
83pub fn totals(
84    entries: &[Entry],
85    session: Option<&str>,
86    since: Option<u64>,
87    repo: Option<&str>,
88) -> Totals {
89    let mut conversation_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            conversation_usd += cost;
106        }
107    }
108
109    Totals {
110        conversation_usd,
111        implementers_usd,
112        runs,
113    }
114}
115
116/// Groups matching usage log entries by session id, ordered by first timestamp.
117///
118/// Entries with no session id (or an empty/whitespace session id) are grouped under `(none)`.
119pub 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
192/// Formats the per-session breakdown followed by the existing total line.
193pub 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
211/// Formats the totals into the human-readable summary line:
212/// `blyte $<o+i> (conversation model $<o>, implementers $<i> in <runs> runs)`
213pub fn format_totals(totals: &Totals) -> String {
214    let total = totals.conversation_usd + totals.implementers_usd;
215    format!(
216        "blyte ${:.2} (conversation model ${:.2}, implementers ${:.2} in {} runs)",
217        total, totals.conversation_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
227/// Executes the `blyte cost` subcommand.
228pub 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            surface: None,
293            surface_name: None,
294            dispatch: dispatch.map(String::from),
295            research: false,
296            model: "test-model".into(),
297            outcome: "verified".into(),
298            turns: 1,
299            input: 100,
300            cached: 0,
301            output: 50,
302            thinking: 0,
303            cost_usd,
304        }
305    }
306
307    #[test]
308    fn test_totals_filters_and_aggregation() {
309        // Entries mix:
310        // Two sessions: "sess-1", "sess-2"
311        // Dispatch and not: some Some, some None
312        // One with cost_usd: None (e3)
313        // Timestamps either side of since (since = 1000): e1 is 500, others >= 1000
314        // Two repos: "/repo/alpha", "/repo/beta"
315        let entries = vec![
316            make_entry(500, "/repo/alpha", Some("sess-1"), None, Some(0.10)),
317            make_entry(1500, "/repo/alpha", Some("sess-1"), Some("d1"), Some(0.20)),
318            make_entry(1500, "/repo/beta", Some("sess-1"), Some("d2"), None),
319            make_entry(2000, "/repo/beta", Some("sess-2"), None, Some(0.50)),
320            make_entry(2500, "/repo/beta", Some("sess-2"), Some("d3"), Some(0.40)),
321        ];
322
323        // 1. No filter: all entries included
324        let t_all = totals(&entries, None, None, None);
325        assert!((t_all.conversation_usd - 0.60).abs() < 1e-6);
326        assert!((t_all.implementers_usd - 0.60).abs() < 1e-6);
327        assert_eq!(t_all.runs, 3);
328
329        // 2. Filter session alone: "sess-1"
330        let t_s1 = totals(&entries, Some("sess-1"), None, None);
331        assert!((t_s1.conversation_usd - 0.10).abs() < 1e-6);
332        assert!((t_s1.implementers_usd - 0.20).abs() < 1e-6);
333        assert_eq!(t_s1.runs, 2);
334
335        // Filter session alone: "sess-2"
336        let t_s2 = totals(&entries, Some("sess-2"), None, None);
337        assert!((t_s2.conversation_usd - 0.50).abs() < 1e-6);
338        assert!((t_s2.implementers_usd - 0.40).abs() < 1e-6);
339        assert_eq!(t_s2.runs, 1);
340
341        // 3. Filter since alone: 1000 (e1 at 500 excluded)
342        let t_since = totals(&entries, None, Some(1000), None);
343        assert!((t_since.conversation_usd - 0.50).abs() < 1e-6);
344        assert!((t_since.implementers_usd - 0.60).abs() < 1e-6);
345        assert_eq!(t_since.runs, 3);
346
347        // 4. Filter repo alone: "/repo/alpha" (e1, e2)
348        let t_alpha = totals(&entries, None, None, Some("/repo/alpha"));
349        assert!((t_alpha.conversation_usd - 0.10).abs() < 1e-6);
350        assert!((t_alpha.implementers_usd - 0.20).abs() < 1e-6);
351        assert_eq!(t_alpha.runs, 1);
352
353        // Filter repo alone: "/repo/beta" (e3, e4, e5)
354        let t_beta = totals(&entries, None, None, Some("/repo/beta"));
355        assert!((t_beta.conversation_usd - 0.50).abs() < 1e-6);
356        assert!((t_beta.implementers_usd - 0.40).abs() < 1e-6);
357        assert_eq!(t_beta.runs, 2);
358
359        // 5. Combined filters
360        // session="sess-1", since=1000, repo="/repo/alpha" -> only e2
361        let t_comb1 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/alpha"));
362        assert!((t_comb1.conversation_usd - 0.0).abs() < 1e-6);
363        assert!((t_comb1.implementers_usd - 0.20).abs() < 1e-6);
364        assert_eq!(t_comb1.runs, 1);
365
366        // session="sess-1", since=1000, repo="/repo/beta" -> only e3 (cost_usd: None)
367        let t_comb2 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/beta"));
368        assert!((t_comb2.conversation_usd - 0.0).abs() < 1e-6);
369        assert!((t_comb2.implementers_usd - 0.0).abs() < 1e-6);
370        assert_eq!(t_comb2.runs, 1);
371
372        // session="sess-2", since=1000, repo="/repo/beta" -> e4 and e5
373        let t_comb3 = totals(&entries, Some("sess-2"), Some(1000), Some("/repo/beta"));
374        assert!((t_comb3.conversation_usd - 0.50).abs() < 1e-6);
375        assert!((t_comb3.implementers_usd - 0.40).abs() < 1e-6);
376        assert_eq!(t_comb3.runs, 1);
377
378        // Non-matching session
379        let t_none = totals(&entries, Some("sess-nonexistent"), None, None);
380        assert_eq!(
381            t_none,
382            Totals {
383                conversation_usd: 0.0,
384                implementers_usd: 0.0,
385                runs: 0,
386            }
387        );
388    }
389
390    #[test]
391    fn test_format_totals() {
392        let known = Totals {
393            conversation_usd: 1.25,
394            implementers_usd: 2.50,
395            runs: 3,
396        };
397        assert_eq!(
398            format_totals(&known),
399            "blyte $3.75 (conversation model $1.25, implementers $2.50 in 3 runs)"
400        );
401        assert_eq!(
402            known.to_string(),
403            "blyte $3.75 (conversation model $1.25, implementers $2.50 in 3 runs)"
404        );
405
406        let zero = Totals::default();
407        assert_eq!(
408            format_totals(&zero),
409            "blyte $0.00 (conversation model $0.00, implementers $0.00 in 0 runs)"
410        );
411    }
412
413    #[test]
414    fn test_totals_json() {
415        let t = Totals {
416            conversation_usd: 1.25,
417            implementers_usd: 2.50,
418            runs: 3,
419        };
420        let json = serde_json::to_string(&t).unwrap();
421        let parsed: Totals = serde_json::from_str(&json).unwrap();
422        assert_eq!(parsed, t);
423    }
424
425    #[test]
426    fn test_format_utc_ts() {
427        assert_eq!(format_utc_ts(0), "1970-01-01T00:00:00Z");
428        assert_eq!(format_utc_ts(1_700_000_100), "2023-11-14T22:15:00Z");
429        assert_eq!(format_utc_ts(1_709_164_800), "2024-02-29T00:00:00Z");
430    }
431}