Skip to main content

blyte_cli/
usage_log.rs

1//! Durable record of run token usage and costs.
2//!
3//! Tracks machine-wide runs across sessions and worktrees in a shared JSONL log.
4
5use serde::{Deserialize, Serialize};
6use std::ffi::OsStr;
7use std::fs::OpenOptions;
8use std::io::{BufRead, BufReader, Write};
9use std::path::{Path, PathBuf};
10
11/// Returns the default path for the usage log.
12///
13/// Priority:
14/// 1. `$BLYTE_USAGE_LOG` if set and non-empty ("off" disables logging and returns None).
15/// 2. `$XDG_STATE_HOME/blyte/usage.jsonl` if `$XDG_STATE_HOME` is set and non-empty.
16/// 3. `$HOME/.local/state/blyte/usage.jsonl` if `$HOME` is set and non-empty.
17/// 4. `None` if none of these is available.
18pub fn default_path() -> Option<PathBuf> {
19    path_from(
20        std::env::var_os("BLYTE_USAGE_LOG").as_deref(),
21        std::env::var_os("XDG_STATE_HOME").as_deref(),
22        std::env::var_os("HOME").as_deref(),
23    )
24}
25
26/// Resolves the usage log path from the given environment values.
27pub fn path_from(
28    log: Option<&OsStr>,
29    xdg: Option<&OsStr>,
30    home: Option<&OsStr>,
31) -> Option<PathBuf> {
32    if let Some(log) = log.filter(|s| !s.is_empty()) {
33        if log == "off" {
34            return None;
35        }
36        return Some(PathBuf::from(log));
37    }
38    if let Some(xdg) = xdg.filter(|s| !s.is_empty()) {
39        return Some(Path::new(xdg).join("blyte").join("usage.jsonl"));
40    }
41    if let Some(home) = home.filter(|s| !s.is_empty()) {
42        return Some(
43            Path::new(home)
44                .join(".local")
45                .join("state")
46                .join("blyte")
47                .join("usage.jsonl"),
48        );
49    }
50    None
51}
52
53/// Resolves the session identifier, falling back from `blyte` to `claude`.
54///
55/// Returns the first of the two that is `Some` and non-empty after trimming, `blyte` first; otherwise `None`.
56pub fn session_from(blyte: Option<String>, claude: Option<String>) -> Option<String> {
57    blyte
58        .filter(|s| !s.trim().is_empty())
59        .or_else(|| claude.filter(|s| !s.trim().is_empty()))
60}
61
62/// An entry in the usage log recording metadata and token consumption of a single run.
63#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
64pub struct Entry {
65    pub ts: u64,
66    pub repo: String,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub session: Option<String>,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub dispatch: Option<String>,
71    pub research: bool,
72    pub model: String,
73    pub outcome: String,
74    pub turns: u32,
75    pub input: u64,
76    pub cached: u64,
77    pub output: u64,
78    pub thinking: u64,
79    #[serde(default)]
80    pub cost_usd: Option<f64>,
81}
82
83/// Returns the repository root path as a string, stripping any `.wt` component and everything after it.
84pub fn repo_of(root: &Path) -> String {
85    let mut prefix = PathBuf::new();
86    let mut found = false;
87    for component in root.components() {
88        if component.as_os_str() == ".wt" {
89            found = true;
90            break;
91        }
92        prefix.push(component);
93    }
94    if found {
95        prefix.to_string_lossy().into_owned()
96    } else {
97        root.to_string_lossy().into_owned()
98    }
99}
100
101/// Appends a usage entry as a single JSON line to `path`.
102///
103/// Creates parent directories if needed, and writes JSON plus newline in a single `write_all`.
104pub fn append(path: &Path, entry: &Entry) -> std::io::Result<()> {
105    if let Some(parent) = path.parent() {
106        if !parent.as_os_str().is_empty() {
107            std::fs::create_dir_all(parent)?;
108        }
109    }
110    let mut file = OpenOptions::new().create(true).append(true).open(path)?;
111    let mut line = serde_json::to_vec(entry)
112        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
113    line.push(b'\n');
114    file.write_all(&line)?;
115    Ok(())
116}
117
118/// Reads all valid entries from the usage log file at `path`.
119///
120/// Skips malformed or unparseable lines. Returns an empty Vec if the file does not exist.
121pub fn read(path: &Path) -> Vec<Entry> {
122    let Ok(file) = std::fs::File::open(path) else {
123        return Vec::new();
124    };
125    let reader = BufReader::new(file);
126    let mut entries = Vec::new();
127    for line in reader.lines() {
128        let Ok(line) = line else {
129            continue;
130        };
131        let trimmed = line.trim();
132        if trimmed.is_empty() {
133            continue;
134        }
135        if let Ok(entry) = serde_json::from_str::<Entry>(trimmed) {
136            entries.push(entry);
137        }
138    }
139    entries
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use std::ffi::OsStr;
146
147    #[test]
148    fn test_path_from() {
149        // BLYTE_USAGE_LOG=/x/u.jsonl wins
150        assert_eq!(
151            path_from(
152                Some(OsStr::new("/x/u.jsonl")),
153                Some(OsStr::new("/xdg")),
154                Some(OsStr::new("/home")),
155            ),
156            Some(PathBuf::from("/x/u.jsonl"))
157        );
158
159        // off gives None
160        assert_eq!(
161            path_from(
162                Some(OsStr::new("off")),
163                Some(OsStr::new("/xdg")),
164                Some(OsStr::new("/home")),
165            ),
166            None
167        );
168
169        // XDG gives <xdg>/blyte/usage.jsonl
170        assert_eq!(
171            path_from(None, Some(OsStr::new("/xdg")), Some(OsStr::new("/home"))),
172            Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
173        );
174
175        // HOME gives <home>/.local/state/blyte/usage.jsonl
176        assert_eq!(
177            path_from(None, None, Some(OsStr::new("/home"))),
178            Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
179        );
180
181        // empty strings are treated as unset
182        assert_eq!(
183            path_from(
184                Some(OsStr::new("")),
185                Some(OsStr::new("")),
186                Some(OsStr::new("/home")),
187            ),
188            Some(PathBuf::from("/home/.local/state/blyte/usage.jsonl"))
189        );
190        assert_eq!(
191            path_from(
192                Some(OsStr::new("")),
193                Some(OsStr::new("/xdg")),
194                Some(OsStr::new("")),
195            ),
196            Some(PathBuf::from("/xdg/blyte/usage.jsonl"))
197        );
198        assert_eq!(
199            path_from(
200                Some(OsStr::new("")),
201                Some(OsStr::new("")),
202                Some(OsStr::new("")),
203            ),
204            None
205        );
206
207        // none gives None
208        assert_eq!(path_from(None, None, None), None);
209    }
210
211    #[test]
212    fn test_repo_of() {
213        assert_eq!(repo_of(Path::new("/r/.wt/T1")), "/r");
214        assert_eq!(repo_of(Path::new("/r")), "/r");
215        assert_eq!(repo_of(Path::new("/r/.wtx/a")), "/r/.wtx/a");
216    }
217
218    #[test]
219    fn test_append_twice_and_read() {
220        let tmp = tempfile::tempdir().unwrap();
221        let log_path = tmp.path().join("parent").join("sub").join("usage.jsonl");
222
223        let entry1 = Entry {
224            ts: 1700000000,
225            repo: "/repo/one".into(),
226            session: Some("sess-1".into()),
227            dispatch: Some("disp-1".into()),
228            research: false,
229            model: "claude-3-7-sonnet".into(),
230            outcome: "verified".into(),
231            turns: 3,
232            input: 1000,
233            cached: 200,
234            output: 300,
235            thinking: 50,
236            cost_usd: Some(0.015),
237        };
238
239        let entry2 = Entry {
240            ts: 1700000010,
241            repo: "/repo/two".into(),
242            session: None,
243            dispatch: None,
244            research: true,
245            model: "gemini-3.8-flash".into(),
246            outcome: "budgetexhausted".into(),
247            turns: 15,
248            input: 5000,
249            cached: 1000,
250            output: 800,
251            thinking: 0,
252            cost_usd: None,
253        };
254
255        append(&log_path, &entry1).expect("first append should succeed");
256
257        // Inject garbage line
258        {
259            let mut f = OpenOptions::new()
260                .append(true)
261                .open(&log_path)
262                .expect("open log file to inject garbage");
263            f.write_all(b"not valid json here at all\n")
264                .expect("write garbage");
265        }
266
267        append(&log_path, &entry2).expect("second append should succeed");
268
269        let entries = read(&log_path);
270        assert_eq!(entries.len(), 2);
271        assert_eq!(entries[0], entry1);
272        assert_eq!(entries[1], entry2);
273    }
274
275    #[test]
276    fn test_session_none_serialization() {
277        let entry = Entry {
278            ts: 1700000000,
279            repo: "/r".into(),
280            session: None,
281            dispatch: None,
282            research: false,
283            model: "m".into(),
284            outcome: "verified".into(),
285            turns: 1,
286            input: 10,
287            cached: 0,
288            output: 5,
289            thinking: 0,
290            cost_usd: None,
291        };
292
293        let json_str = serde_json::to_string(&entry).unwrap();
294        assert!(
295            !json_str.contains("\"session\""),
296            "session key must be omitted when None"
297        );
298        assert!(
299            !json_str.contains("\"dispatch\""),
300            "dispatch key must be omitted when None"
301        );
302
303        let parsed: Entry = serde_json::from_str(&json_str).unwrap();
304        assert_eq!(parsed, entry);
305    }
306
307    #[test]
308    fn test_session_from() {
309        assert_eq!(
310            session_from(Some("b".into()), Some("c".into())),
311            Some("b".into())
312        );
313        assert_eq!(session_from(None, Some("c".into())), Some("c".into()));
314        assert_eq!(
315            session_from(Some("".into()), Some("c".into())),
316            Some("c".into())
317        );
318        assert_eq!(session_from(Some("  ".into()), None), None);
319        assert_eq!(session_from(None, None), None);
320    }
321}