blyte 0.83.1

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Combined conversation model and implementer cost reporting.
//!
//! Aggregates costs from the machine-wide usage log across interactive REPL sessions
//! and dispatched worker runs.

use crate::usage_log::Entry;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Aggregated spend and run count.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Totals {
    pub conversation_usd: f64,
    pub implementers_usd: f64,
    pub runs: usize,
}

impl Default for Totals {
    fn default() -> Self {
        Self {
            conversation_usd: 0.0,
            implementers_usd: 0.0,
            runs: 0,
        }
    }
}

/// Aggregated spend and activity counts for a single session.
#[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,
}

/// JSON payload for `blyte cost --by-session --json`.
#[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
}

/// Aggregates usage log entries matching all given filters.
///
/// Filters:
/// - `session`: entries with matching session ID
/// - `since`: entries with timestamp >= `since`
/// - `repo`: entries with matching repository path
///
/// Entries with `dispatch: Some(_)` count toward `implementers_usd`, and toward `runs` unless
/// `outcome == "turn"` or `outcome == "model_review"`.
/// Entries without dispatch count toward `conversation_usd`.
/// An entry with `cost_usd: None` adds 0 to cost totals.
pub fn totals(
    entries: &[Entry],
    session: Option<&str>,
    since: Option<u64>,
    repo: Option<&str>,
) -> Totals {
    let mut conversation_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 {
            conversation_usd += cost;
        }
    }

    Totals {
        conversation_usd,
        implementers_usd,
        runs,
    }
}

/// Groups matching usage log entries by session id, ordered by first timestamp.
///
/// Entries with no session id (or an empty/whitespace session id) are grouped under `(none)`.
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")
}

/// Formats the per-session breakdown followed by the existing total line.
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")
}

/// Formats the totals into the human-readable summary line:
/// `blyte $<o+i> (conversation model $<o>, implementers $<i> in <runs> runs)`
pub fn format_totals(totals: &Totals) -> String {
    let total = totals.conversation_usd + totals.implementers_usd;
    format!(
        "blyte ${:.2} (conversation model ${:.2}, implementers ${:.2} in {} runs)",
        total, totals.conversation_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))
    }
}

/// Executes the `blyte cost` subcommand.
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),
            surface: None,
            surface_name: None,
            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() {
        // Entries mix:
        // Two sessions: "sess-1", "sess-2"
        // Dispatch and not: some Some, some None
        // One with cost_usd: None (e3)
        // Timestamps either side of since (since = 1000): e1 is 500, others >= 1000
        // Two repos: "/repo/alpha", "/repo/beta"
        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)),
        ];

        // 1. No filter: all entries included
        let t_all = totals(&entries, None, None, None);
        assert!((t_all.conversation_usd - 0.60).abs() < 1e-6);
        assert!((t_all.implementers_usd - 0.60).abs() < 1e-6);
        assert_eq!(t_all.runs, 3);

        // 2. Filter session alone: "sess-1"
        let t_s1 = totals(&entries, Some("sess-1"), None, None);
        assert!((t_s1.conversation_usd - 0.10).abs() < 1e-6);
        assert!((t_s1.implementers_usd - 0.20).abs() < 1e-6);
        assert_eq!(t_s1.runs, 2);

        // Filter session alone: "sess-2"
        let t_s2 = totals(&entries, Some("sess-2"), None, None);
        assert!((t_s2.conversation_usd - 0.50).abs() < 1e-6);
        assert!((t_s2.implementers_usd - 0.40).abs() < 1e-6);
        assert_eq!(t_s2.runs, 1);

        // 3. Filter since alone: 1000 (e1 at 500 excluded)
        let t_since = totals(&entries, None, Some(1000), None);
        assert!((t_since.conversation_usd - 0.50).abs() < 1e-6);
        assert!((t_since.implementers_usd - 0.60).abs() < 1e-6);
        assert_eq!(t_since.runs, 3);

        // 4. Filter repo alone: "/repo/alpha" (e1, e2)
        let t_alpha = totals(&entries, None, None, Some("/repo/alpha"));
        assert!((t_alpha.conversation_usd - 0.10).abs() < 1e-6);
        assert!((t_alpha.implementers_usd - 0.20).abs() < 1e-6);
        assert_eq!(t_alpha.runs, 1);

        // Filter repo alone: "/repo/beta" (e3, e4, e5)
        let t_beta = totals(&entries, None, None, Some("/repo/beta"));
        assert!((t_beta.conversation_usd - 0.50).abs() < 1e-6);
        assert!((t_beta.implementers_usd - 0.40).abs() < 1e-6);
        assert_eq!(t_beta.runs, 2);

        // 5. Combined filters
        // session="sess-1", since=1000, repo="/repo/alpha" -> only e2
        let t_comb1 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/alpha"));
        assert!((t_comb1.conversation_usd - 0.0).abs() < 1e-6);
        assert!((t_comb1.implementers_usd - 0.20).abs() < 1e-6);
        assert_eq!(t_comb1.runs, 1);

        // session="sess-1", since=1000, repo="/repo/beta" -> only e3 (cost_usd: None)
        let t_comb2 = totals(&entries, Some("sess-1"), Some(1000), Some("/repo/beta"));
        assert!((t_comb2.conversation_usd - 0.0).abs() < 1e-6);
        assert!((t_comb2.implementers_usd - 0.0).abs() < 1e-6);
        assert_eq!(t_comb2.runs, 1);

        // session="sess-2", since=1000, repo="/repo/beta" -> e4 and e5
        let t_comb3 = totals(&entries, Some("sess-2"), Some(1000), Some("/repo/beta"));
        assert!((t_comb3.conversation_usd - 0.50).abs() < 1e-6);
        assert!((t_comb3.implementers_usd - 0.40).abs() < 1e-6);
        assert_eq!(t_comb3.runs, 1);

        // Non-matching session
        let t_none = totals(&entries, Some("sess-nonexistent"), None, None);
        assert_eq!(
            t_none,
            Totals {
                conversation_usd: 0.0,
                implementers_usd: 0.0,
                runs: 0,
            }
        );
    }

    #[test]
    fn test_format_totals() {
        let known = Totals {
            conversation_usd: 1.25,
            implementers_usd: 2.50,
            runs: 3,
        };
        assert_eq!(
            format_totals(&known),
            "blyte $3.75 (conversation model $1.25, implementers $2.50 in 3 runs)"
        );
        assert_eq!(
            known.to_string(),
            "blyte $3.75 (conversation model $1.25, implementers $2.50 in 3 runs)"
        );

        let zero = Totals::default();
        assert_eq!(
            format_totals(&zero),
            "blyte $0.00 (conversation model $0.00, implementers $0.00 in 0 runs)"
        );
    }

    #[test]
    fn test_totals_json() {
        let t = Totals {
            conversation_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");
    }
}