| @@ -0,0 +1,1086 @@ |
| 1 | + //! What the agents have used: tokens and cost read from Claude Code's and |
| 2 | + //! Pi's session logs and from usage hubs, and the plan limits Claude reports. |
| 3 | + //! Everything here blocks, so run it on a background executor. |
| 4 | + |
| 5 | + use std::{ |
| 6 | + collections::{BTreeSet, HashMap}, |
| 7 | + fs::File, |
| 8 | + io::{BufRead as _, BufReader}, |
| 9 | + path::{Path, PathBuf}, |
| 10 | + time::{Duration, SystemTime}, |
| 11 | + }; |
| 12 | + |
| 13 | + use chrono::{DateTime, Local, NaiveDate, NaiveDateTime, TimeDelta, Timelike as _, Utc}; |
| 14 | + use serde::Deserialize; |
| 15 | + use serde_json::Value; |
| 16 | + |
| 17 | + use crate::settings::UsageHub; |
| 18 | + |
| 19 | + /// Where usage is read from. Each directory comes with the label it's shown |
| 20 | + /// under, which is also its provider in the report. |
| 21 | + #[derive(Clone, Debug, Default)] |
| 22 | + pub struct UsageSources { |
| 23 | + /// Claude config directories, such as `~/.claude`. |
| 24 | + pub claude_dirs: Vec<(String, PathBuf)>, |
| 25 | + /// Pi agent directories, such as `~/.pi/agent`. |
| 26 | + pub pi_dirs: Vec<(String, PathBuf)>, |
| 27 | + pub hubs: Vec<UsageHub>, |
| 28 | + } |
| 29 | + |
| 30 | + /// Token counts, split the way the APIs bill them. |
| 31 | + #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 32 | + pub struct Tokens { |
| 33 | + /// Uncached input. |
| 34 | + pub input: u64, |
| 35 | + pub output: u64, |
| 36 | + pub cache_write: u64, |
| 37 | + pub cache_read: u64, |
| 38 | + } |
| 39 | + |
| 40 | + impl Tokens { |
| 41 | + pub fn total(&self) -> u64 { |
| 42 | + self.input + self.output + self.cache_write + self.cache_read |
| 43 | + } |
| 44 | + |
| 45 | + fn add(&mut self, other: &Tokens) { |
| 46 | + self.input += other.input; |
| 47 | + self.output += other.output; |
| 48 | + self.cache_write += other.cache_write; |
| 49 | + self.cache_read += other.cache_read; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /// Dollars, split like [`Tokens`]. |
| 54 | + #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 55 | + pub struct Costs { |
| 56 | + pub input: f64, |
| 57 | + pub output: f64, |
| 58 | + pub cache_write: f64, |
| 59 | + pub cache_read: f64, |
| 60 | + } |
| 61 | + |
| 62 | + impl Costs { |
| 63 | + pub fn total(&self) -> f64 { |
| 64 | + self.input + self.output + self.cache_write + self.cache_read |
| 65 | + } |
| 66 | + |
| 67 | + fn add(&mut self, other: &Costs) { |
| 68 | + self.input += other.input; |
| 69 | + self.output += other.output; |
| 70 | + self.cache_write += other.cache_write; |
| 71 | + self.cache_read += other.cache_read; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + /// One provider's use of one model in one local hour. |
| 76 | + #[derive(Clone, Debug)] |
| 77 | + pub struct Bucket { |
| 78 | + pub provider: String, |
| 79 | + pub model: String, |
| 80 | + /// The local hour it started in. |
| 81 | + pub hour: NaiveDateTime, |
| 82 | + pub tokens: Tokens, |
| 83 | + /// `None` when the model has no known price. |
| 84 | + pub cost: Option<Costs>, |
| 85 | + /// What the cache reads saved over paying full input price. |
| 86 | + pub savings: f64, |
| 87 | + /// The sessions it came from, numbered across the report. |
| 88 | + pub sessions: BTreeSet<u32>, |
| 89 | + } |
| 90 | + |
| 91 | + impl Bucket { |
| 92 | + pub fn day(&self) -> NaiveDate { |
| 93 | + self.hour.date() |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + #[derive(Clone, Debug, Default)] |
| 98 | + pub struct UsageReport { |
| 99 | + pub buckets: Vec<Bucket>, |
| 100 | + /// Hubs that couldn't be read, and the like. Shown, never fatal. |
| 101 | + pub errors: Vec<String>, |
| 102 | + pub collected_at: Option<DateTime<Local>>, |
| 103 | + } |
| 104 | + |
| 105 | + impl UsageReport { |
| 106 | + /// The provider labels that show up in the report, in the order sources were given. |
| 107 | + pub fn providers(&self) -> Vec<String> { |
| 108 | + let mut labels: Vec<String> = Vec::new(); |
| 109 | + for bucket in &self.buckets { |
| 110 | + if !labels.contains(&bucket.provider) { |
| 111 | + labels.push(bucket.provider.clone()); |
| 112 | + } |
| 113 | + } |
| 114 | + labels |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// One normalized usage record, before it's folded into a bucket. |
| 119 | + struct Row { |
| 120 | + provider: String, |
| 121 | + model: String, |
| 122 | + at: DateTime<Utc>, |
| 123 | + session: Option<String>, |
| 124 | + tokens: Tokens, |
| 125 | + /// A cost the source worked out itself, such as Pi's. |
| 126 | + cost: Option<Costs>, |
| 127 | + } |
| 128 | + |
| 129 | + /// Reads every source for usage since `since`. |
| 130 | + pub fn collect(sources: &UsageSources, since: SystemTime) -> UsageReport { |
| 131 | + let since: DateTime<Utc> = since.into(); |
| 132 | + let mut errors = Vec::new(); |
| 133 | + let mut rows = Vec::new(); |
| 134 | + |
| 135 | + for (label, dir) in &sources.claude_dirs { |
| 136 | + let files = jsonl_files(&dir.join("projects"), since); |
| 137 | + rows.extend(dedup_claude(parse_parallel(files, |path| read_claude_file(path, label, since)))); |
| 138 | + } |
| 139 | + for (label, dir) in &sources.pi_dirs { |
| 140 | + let files = jsonl_files(&dir.join("sessions"), since); |
| 141 | + rows.extend(parse_parallel(files, |path| read_pi_file(path, label, since))); |
| 142 | + } |
| 143 | + for hub in &sources.hubs { |
| 144 | + match read_hub(hub, since) { |
| 145 | + Ok(hub_rows) => rows.extend(hub_rows), |
| 146 | + Err(err) => errors.push(format!("{}: {err}", hub_label(hub))), |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + let mut report = fold(rows); |
| 151 | + report.errors = errors; |
| 152 | + report.collected_at = Some(Local::now()); |
| 153 | + report |
| 154 | + } |
| 155 | + |
| 156 | + fn hub_label(hub: &UsageHub) -> String { |
| 157 | + if hub.name.trim().is_empty() { hub.url.clone() } else { hub.name.clone() } |
| 158 | + } |
| 159 | + |
| 160 | + /// Folds rows into hourly buckets per provider and model. |
| 161 | + fn fold(rows: Vec<Row>) -> UsageReport { |
| 162 | + let mut session_ix: HashMap<(String, String), u32> = HashMap::new(); |
| 163 | + let mut buckets: HashMap<(String, String, NaiveDateTime), Bucket> = HashMap::new(); |
| 164 | + |
| 165 | + for row in rows { |
| 166 | + let Some(hour) = local_hour(row.at) else { continue }; |
| 167 | + let price = price(&row.model); |
| 168 | + let cost = row.cost.or_else(|| price.map(|price| price.cost(&row.tokens))); |
| 169 | + let savings = price.map(|price| price.savings(row.tokens.cache_read)).unwrap_or(0.); |
| 170 | + let bucket = buckets |
| 171 | + .entry((row.provider.clone(), row.model.clone(), hour)) |
| 172 | + .or_insert_with(|| Bucket { |
| 173 | + provider: row.provider.clone(), |
| 174 | + model: row.model.clone(), |
| 175 | + hour, |
| 176 | + tokens: Tokens::default(), |
| 177 | + cost: None, |
| 178 | + savings: 0., |
| 179 | + sessions: BTreeSet::new(), |
| 180 | + }); |
| 181 | + bucket.tokens.add(&row.tokens); |
| 182 | + if let Some(cost) = cost { |
| 183 | + bucket.cost.get_or_insert_with(Costs::default).add(&cost); |
| 184 | + } |
| 185 | + bucket.savings += savings; |
| 186 | + if let Some(session) = row.session { |
| 187 | + let next = session_ix.len() as u32; |
| 188 | + let ix = *session_ix.entry((row.provider, session)).or_insert(next); |
| 189 | + bucket.sessions.insert(ix); |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + let mut buckets: Vec<Bucket> = buckets.into_values().collect(); |
| 194 | + buckets.sort_by(|a, b| (a.hour, &a.provider, &a.model).cmp(&(b.hour, &b.provider, &b.model))); |
| 195 | + UsageReport { buckets, errors: Vec::new(), collected_at: None } |
| 196 | + } |
| 197 | + |
| 198 | + fn local_hour(at: DateTime<Utc>) -> Option<NaiveDateTime> { |
| 199 | + let local = at.with_timezone(&Local).naive_local(); |
| 200 | + local.with_minute(0)?.with_second(0)?.with_nanosecond(0) |
| 201 | + } |
| 202 | + |
| 203 | + /// Every `.jsonl` file under `dir` changed since `since`. |
| 204 | + fn jsonl_files(dir: &Path, since: DateTime<Utc>) -> Vec<PathBuf> { |
| 205 | + let since: SystemTime = since.into(); |
| 206 | + let mut files = Vec::new(); |
| 207 | + let mut stack = vec![dir.to_path_buf()]; |
| 208 | + while let Some(dir) = stack.pop() { |
| 209 | + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; |
| 210 | + for entry in entries.flatten() { |
| 211 | + let Ok(kind) = entry.file_type() else { continue }; |
| 212 | + let path = entry.path(); |
| 213 | + if kind.is_dir() { |
| 214 | + stack.push(path); |
| 215 | + } else if path.extension().is_some_and(|ext| ext == "jsonl") |
| 216 | + && entry.metadata().and_then(|meta| meta.modified()).is_ok_and(|modified| modified >= since) |
| 217 | + { |
| 218 | + files.push(path); |
| 219 | + } |
| 220 | + } |
| 221 | + } |
| 222 | + files |
| 223 | + } |
| 224 | + |
| 225 | + /// Runs `read` over the files on a few threads. |
| 226 | + fn parse_parallel<T: Send>(files: Vec<PathBuf>, read: impl Fn(&Path) -> Vec<T> + Sync) -> Vec<T> { |
| 227 | + let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(8); |
| 228 | + let chunk = files.len().div_ceil(threads).max(1); |
| 229 | + std::thread::scope(|scope| { |
| 230 | + let handles: Vec<_> = files |
| 231 | + .chunks(chunk) |
| 232 | + .map(|chunk| scope.spawn(|| chunk.iter().flat_map(|path| read(path)).collect::<Vec<T>>())) |
| 233 | + .collect(); |
| 234 | + handles.into_iter().flat_map(|handle| handle.join().unwrap_or_default()).collect() |
| 235 | + }) |
| 236 | + } |
| 237 | + |
| 238 | + /// Calls `line` for each line of a file that contains every one of `needles`. |
| 239 | + fn scan_lines(path: &Path, needles: &[&str], mut line: impl FnMut(&str)) { |
| 240 | + let Ok(file) = File::open(path) else { return }; |
| 241 | + let mut reader = BufReader::with_capacity(256 * 1024, file); |
| 242 | + let mut buf = Vec::new(); |
| 243 | + loop { |
| 244 | + buf.clear(); |
| 245 | + match reader.read_until(b'\n', &mut buf) { |
| 246 | + Ok(0) | Err(_) => break, |
| 247 | + Ok(_) => {} |
| 248 | + } |
| 249 | + let Ok(text) = std::str::from_utf8(&buf) else { continue }; |
| 250 | + if needles.iter().all(|needle| text.contains(needle)) { |
| 251 | + line(text); |
| 252 | + } |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + fn parse_time(value: &Value) -> Option<DateTime<Utc>> { |
| 257 | + match value { |
| 258 | + Value::String(text) => DateTime::parse_from_rfc3339(text).ok().map(|at| at.with_timezone(&Utc)), |
| 259 | + Value::Number(millis) => DateTime::from_timestamp_millis(millis.as_i64()?), |
| 260 | + _ => None, |
| 261 | + } |
| 262 | + } |
| 263 | + |
| 264 | + // ---- Claude Code --------------------------------------------------------------- |
| 265 | + |
| 266 | + #[derive(Deserialize)] |
| 267 | + struct ClaudeLine { |
| 268 | + #[serde(rename = "type")] |
| 269 | + kind: Option<String>, |
| 270 | + timestamp: Option<Value>, |
| 271 | + #[serde(rename = "sessionId")] |
| 272 | + session_id: Option<String>, |
| 273 | + #[serde(rename = "requestId")] |
| 274 | + request_id: Option<String>, |
| 275 | + message: Option<ClaudeMessage>, |
| 276 | + } |
| 277 | + |
| 278 | + #[derive(Deserialize)] |
| 279 | + struct ClaudeMessage { |
| 280 | + id: Option<String>, |
| 281 | + model: Option<String>, |
| 282 | + usage: Option<ClaudeUsage>, |
| 283 | + } |
| 284 | + |
| 285 | + #[derive(Deserialize)] |
| 286 | + struct ClaudeUsage { |
| 287 | + input_tokens: Option<u64>, |
| 288 | + output_tokens: Option<u64>, |
| 289 | + cache_creation_input_tokens: Option<u64>, |
| 290 | + cache_read_input_tokens: Option<u64>, |
| 291 | + } |
| 292 | + |
| 293 | + /// A Claude row with its (message id, request id), for deduplication. |
| 294 | + type KeyedRow = (Option<(String, String)>, Row); |
| 295 | + |
| 296 | + fn read_claude_file(path: &Path, label: &str, since: DateTime<Utc>) -> Vec<KeyedRow> { |
| 297 | + let mut rows = Vec::new(); |
| 298 | + scan_lines(path, &["\"usage\"", "\"assistant\""], |text| { |
| 299 | + let Ok(line) = serde_json::from_str::<ClaudeLine>(text) else { return }; |
| 300 | + if line.kind.as_deref() != Some("assistant") { |
| 301 | + return; |
| 302 | + } |
| 303 | + let Some(message) = line.message else { return }; |
| 304 | + let Some(usage) = message.usage else { return }; |
| 305 | + let Some(at) = line.timestamp.as_ref().and_then(parse_time).filter(|at| *at >= since) else { return }; |
| 306 | + let tokens = Tokens { |
| 307 | + input: usage.input_tokens.unwrap_or(0), |
| 308 | + output: usage.output_tokens.unwrap_or(0), |
| 309 | + cache_write: usage.cache_creation_input_tokens.unwrap_or(0), |
| 310 | + cache_read: usage.cache_read_input_tokens.unwrap_or(0), |
| 311 | + }; |
| 312 | + let model = message.model.unwrap_or_default(); |
| 313 | + // Claude Code writes `<synthetic>` for messages it made up itself. |
| 314 | + if tokens.total() == 0 || model.is_empty() { |
| 315 | + return; |
| 316 | + } |
| 317 | + let key = message.id.zip(line.request_id); |
| 318 | + rows.push(( |
| 319 | + key, |
| 320 | + Row { provider: label.to_string(), model, at, session: line.session_id, tokens, cost: None }, |
| 321 | + )); |
| 322 | + }); |
| 323 | + rows |
| 324 | + } |
| 325 | + |
| 326 | + /// Claude Code writes the same response on several lines, one per content |
| 327 | + /// block. Keeps one row per response: the one with the most output, since |
| 328 | + /// early lines can be written before the output count is final. |
| 329 | + fn dedup_claude(rows: Vec<KeyedRow>) -> Vec<Row> { |
| 330 | + let mut seen: HashMap<(String, String), usize> = HashMap::new(); |
| 331 | + let mut kept: Vec<Row> = Vec::with_capacity(rows.len()); |
| 332 | + for (key, row) in rows { |
| 333 | + match key { |
| 334 | + Some(key) => match seen.get(&key) { |
| 335 | + Some(&ix) => { |
| 336 | + if row.tokens.output > kept[ix].tokens.output { |
| 337 | + kept[ix] = row; |
| 338 | + } |
| 339 | + } |
| 340 | + None => { |
| 341 | + seen.insert(key, kept.len()); |
| 342 | + kept.push(row); |
| 343 | + } |
| 344 | + }, |
| 345 | + None => kept.push(row), |
| 346 | + } |
| 347 | + } |
| 348 | + kept |
| 349 | + } |
| 350 | + |
| 351 | + // ---- Pi -------------------------------------------------------------------------- |
| 352 | + |
| 353 | + fn read_pi_file(path: &Path, label: &str, since: DateTime<Utc>) -> Vec<Row> { |
| 354 | + // Pi names its session files after the session. |
| 355 | + let session = path.file_stem().map(|stem| stem.to_string_lossy().into_owned()); |
| 356 | + let mut rows = Vec::new(); |
| 357 | + scan_lines(path, &["\"usage\"", "\"assistant\""], |text| { |
| 358 | + let Ok(line) = serde_json::from_str::<Value>(text) else { return }; |
| 359 | + if let Some(row) = pi_row(&line, label, session.clone()).filter(|row| row.at >= since) { |
| 360 | + rows.push(row); |
| 361 | + } |
| 362 | + }); |
| 363 | + rows |
| 364 | + } |
| 365 | + |
| 366 | + fn pi_row(line: &Value, label: &str, session: Option<String>) -> Option<Row> { |
| 367 | + if line.get("type")?.as_str()? != "message" { |
| 368 | + return None; |
| 369 | + } |
| 370 | + let message = line.get("message")?; |
| 371 | + if message.get("role")?.as_str()? != "assistant" { |
| 372 | + return None; |
| 373 | + } |
| 374 | + let usage = message.get("usage")?; |
| 375 | + let count = |key: &str| usage.get(key).and_then(Value::as_u64).unwrap_or(0); |
| 376 | + let tokens = Tokens { |
| 377 | + input: count("input"), |
| 378 | + output: count("output"), |
| 379 | + cache_write: count("cacheWrite"), |
| 380 | + cache_read: count("cacheRead"), |
| 381 | + }; |
| 382 | + if tokens.total() == 0 { |
| 383 | + return None; |
| 384 | + } |
| 385 | + let at = line.get("timestamp").and_then(parse_time).or_else(|| message.get("timestamp").and_then(parse_time))?; |
| 386 | + let cost = usage.get("cost").and_then(|cost| { |
| 387 | + let part = |key: &str| cost.get(key).and_then(Value::as_f64); |
| 388 | + let total = part("total")?; |
| 389 | + Some(match (part("input"), part("output"), part("cacheWrite"), part("cacheRead")) { |
| 390 | + (Some(input), Some(output), cache_write, cache_read) => Costs { |
| 391 | + input, |
| 392 | + output, |
| 393 | + cache_write: cache_write.unwrap_or(0.), |
| 394 | + cache_read: cache_read.unwrap_or(0.), |
| 395 | + }, |
| 396 | + _ => Costs { input: total, ..Costs::default() }, |
| 397 | + }) |
| 398 | + }); |
| 399 | + let model = message.get("model").and_then(Value::as_str).unwrap_or("unknown").to_string(); |
| 400 | + Some(Row { provider: label.to_string(), model, at, session, tokens, cost }) |
| 401 | + } |
| 402 | + |
| 403 | + // ---- usage hubs ------------------------------------------------------------------ |
| 404 | + |
| 405 | + fn read_hub(hub: &UsageHub, since: DateTime<Utc>) -> anyhow::Result<Vec<Row>> { |
| 406 | + let base = hub.url.trim().trim_end_matches('/'); |
| 407 | + if base.is_empty() { |
| 408 | + anyhow::bail!("no URL"); |
| 409 | + } |
| 410 | + let base = if base.contains("://") { base.to_string() } else { format!("http://{base}") }; |
| 411 | + let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(10)).build(); |
| 412 | + let response = agent |
| 413 | + .get(&format!("{base}/v0/management/usage")) |
| 414 | + .set("Authorization", &format!("Bearer {}", hub.key.trim())) |
| 415 | + .call()?; |
| 416 | + // Read it whole: the reply lists every request, past ureq's 10 MB string cap. |
| 417 | + let reply: Value = serde_json::from_reader(response.into_reader())?; |
| 418 | + Ok(hub_rows(&reply, &hub_label(hub), since)) |
| 419 | + } |
| 420 | + |
| 421 | + /// Reads CLIProxyAPI's `/v0/management/usage` reply, ignoring anything unexpected. |
| 422 | + fn hub_rows(reply: &Value, label: &str, since: DateTime<Utc>) -> Vec<Row> { |
| 423 | + let mut rows = Vec::new(); |
| 424 | + let apis = reply.pointer("/usage/apis").and_then(Value::as_object); |
| 425 | + for api in apis.into_iter().flat_map(|apis| apis.values()) { |
| 426 | + let models = api.get("models").and_then(Value::as_object); |
| 427 | + for (model, entry) in models.into_iter().flatten() { |
| 428 | + let details = entry.get("details").and_then(Value::as_array); |
| 429 | + for detail in details.into_iter().flatten() { |
| 430 | + let Some(at) = detail.get("timestamp").and_then(parse_time).filter(|at| *at >= since) else { |
| 431 | + continue; |
| 432 | + }; |
| 433 | + let Some(counts) = detail.get("tokens") else { continue }; |
| 434 | + let count = |key: &str| counts.get(key).and_then(Value::as_u64).unwrap_or(0); |
| 435 | + // Cached tokens are part of the input count, as in OpenAI's usage. |
| 436 | + let cached = count("cached_tokens"); |
| 437 | + let input = count("input_tokens"); |
| 438 | + let mut output = count("output_tokens"); |
| 439 | + let reasoning = count("reasoning_tokens"); |
| 440 | + if reasoning > 0 && input + output + reasoning <= count("total_tokens") { |
| 441 | + output += reasoning; |
| 442 | + } |
| 443 | + let tokens = |
| 444 | + Tokens { input: input.saturating_sub(cached), output, cache_write: 0, cache_read: cached }; |
| 445 | + if tokens.total() == 0 { |
| 446 | + continue; |
| 447 | + } |
| 448 | + rows.push(Row { |
| 449 | + provider: label.to_string(), |
| 450 | + model: model.clone(), |
| 451 | + at, |
| 452 | + session: None, |
| 453 | + tokens, |
| 454 | + cost: None, |
| 455 | + }); |
| 456 | + } |
| 457 | + } |
| 458 | + } |
| 459 | + rows |
| 460 | + } |
| 461 | + |
| 462 | + // ---- pricing ----------------------------------------------------------------------- |
| 463 | + |
| 464 | + /// USD per million tokens. |
| 465 | + #[derive(Clone, Copy, Debug, PartialEq)] |
| 466 | + pub struct Price { |
| 467 | + pub input: f64, |
| 468 | + pub output: f64, |
| 469 | + pub cache_read: f64, |
| 470 | + /// Five-minute cache writes: 1.25 × input. |
| 471 | + pub cache_write: f64, |
| 472 | + } |
| 473 | + |
| 474 | + impl Price { |
| 475 | + const fn new(input: f64, output: f64, cache_read: f64) -> Self { |
| 476 | + Self { input, output, cache_read, cache_write: input * 1.25 } |
| 477 | + } |
| 478 | + |
| 479 | + pub fn cost(&self, tokens: &Tokens) -> Costs { |
| 480 | + let dollars = |count: u64, rate: f64| count as f64 * rate / 1_000_000.; |
| 481 | + Costs { |
| 482 | + input: dollars(tokens.input, self.input), |
| 483 | + output: dollars(tokens.output, self.output), |
| 484 | + cache_write: dollars(tokens.cache_write, self.cache_write), |
| 485 | + cache_read: dollars(tokens.cache_read, self.cache_read), |
| 486 | + } |
| 487 | + } |
| 488 | + |
| 489 | + /// What `cache_read` tokens would have cost at full input price, minus what they cost. |
| 490 | + pub fn savings(&self, cache_read: u64) -> f64 { |
| 491 | + cache_read as f64 * (self.input - self.cache_read) / 1_000_000. |
| 492 | + } |
| 493 | + } |
| 494 | + |
| 495 | + /// Claude's prices by model id prefix. Longer prefixes come first. |
| 496 | + const PRICES: &[(&str, Price)] = &[ |
| 497 | + ("claude-fable-5-1", Price::new(10., 50., 0.25)), |
| 498 | + ("claude-fable-5", Price::new(10., 50., 1.)), |
| 499 | + ("claude-mythos", Price::new(10., 50., 1.)), |
| 500 | + ("claude-opus-5-5", Price::new(4., 20., 0.2)), |
| 501 | + ("claude-opus-5", Price::new(5., 25., 0.5)), |
| 502 | + ("claude-opus-4-8", Price::new(5., 25., 0.5)), |
| 503 | + ("claude-opus-4-7", Price::new(5., 25., 0.5)), |
| 504 | + ("claude-opus-4-6", Price::new(5., 25., 0.5)), |
| 505 | + ("claude-opus-4-5", Price::new(5., 25., 0.5)), |
| 506 | + ("claude-opus-4-1", Price::new(15., 75., 1.5)), |
| 507 | + ("claude-opus-4", Price::new(15., 75., 1.5)), |
| 508 | + ("claude-sonnet-5-5", Price::new(2., 10., 0.2)), |
| 509 | + ("claude-sonnet-5", Price::new(2., 10., 0.2)), |
| 510 | + ("claude-sonnet-4-6", Price::new(3., 15., 0.3)), |
| 511 | + ("claude-sonnet-4-5", Price::new(3., 15., 0.3)), |
| 512 | + ("claude-sonnet-4", Price::new(3., 15., 0.3)), |
| 513 | + ("claude-3-7-sonnet", Price::new(3., 15., 0.3)), |
| 514 | + ("claude-haiku-5-5", Price::new(0.1, 0.5, 0.01)), |
| 515 | + ("claude-haiku-4-5", Price::new(1., 5., 0.1)), |
| 516 | + ("claude-3-5-haiku", Price::new(0.8, 4., 0.08)), |
| 517 | + ]; |
| 518 | + |
| 519 | + /// The price of a Claude model, from ids like `claude-opus-5-5`, |
| 520 | + /// `claude-haiku-4-5-20251001`, `anthropic/claude-sonnet-5` or |
| 521 | + /// `us.anthropic.claude-opus-4-1-v1:0`. `None` for anything else. |
| 522 | + pub fn price(model: &str) -> Option<Price> { |
| 523 | + let start = model.find("claude-")?; |
| 524 | + let mut id = &model[start..]; |
| 525 | + if let Some(cut) = id.find(['[', ':', '@']) { |
| 526 | + id = &id[..cut]; |
| 527 | + } |
| 528 | + let id = strip_date(id); |
| 529 | + PRICES |
| 530 | + .iter() |
| 531 | + .find(|(prefix, _)| id.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('-'))) |
| 532 | + .map(|(_, price)| *price) |
| 533 | + } |
| 534 | + |
| 535 | + /// Drops a release date suffix: `claude-haiku-4-5-20251001` → `claude-haiku-4-5`. |
| 536 | + fn strip_date(id: &str) -> &str { |
| 537 | + match id.rsplit_once('-') { |
| 538 | + Some((base, date)) if date.len() == 8 && date.bytes().all(|b| b.is_ascii_digit()) => base, |
| 539 | + _ => id, |
| 540 | + } |
| 541 | + } |
| 542 | + |
| 543 | + // ---- summaries --------------------------------------------------------------------- |
| 544 | + |
| 545 | + /// The time ranges the Usage page offers. |
| 546 | + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 547 | + pub enum Span { |
| 548 | + Day, |
| 549 | + Week, |
| 550 | + Month, |
| 551 | + Quarter, |
| 552 | + } |
| 553 | + |
| 554 | + impl Span { |
| 555 | + pub const ALL: [Span; 4] = [Span::Day, Span::Week, Span::Month, Span::Quarter]; |
| 556 | + |
| 557 | + pub fn label(self) -> &'static str { |
| 558 | + match self { |
| 559 | + Span::Day => "Past 24h", |
| 560 | + Span::Week => "7 days", |
| 561 | + Span::Month => "30 days", |
| 562 | + Span::Quarter => "90 days", |
| 563 | + } |
| 564 | + } |
| 565 | + |
| 566 | + pub fn days(self) -> i64 { |
| 567 | + match self { |
| 568 | + Span::Day => 1, |
| 569 | + Span::Week => 7, |
| 570 | + Span::Month => 30, |
| 571 | + Span::Quarter => 90, |
| 572 | + } |
| 573 | + } |
| 574 | + |
| 575 | + /// The past 24 hours chart by the hour, the rest by the day. |
| 576 | + pub fn hourly(self) -> bool { |
| 577 | + self == Span::Day |
| 578 | + } |
| 579 | + |
| 580 | + /// When the range starts, as a moment to collect from. |
| 581 | + pub fn since(self, now: DateTime<Local>) -> SystemTime { |
| 582 | + let start = self.first_slot(now.naive_local()); |
| 583 | + start.and_local_timezone(Local).earliest().map(SystemTime::from).unwrap_or_else(|| { |
| 584 | + SystemTime::from(now) - Duration::from_secs(self.days() as u64 * 86_400) |
| 585 | + }) |
| 586 | + } |
| 587 | + |
| 588 | + fn first_slot(self, now: NaiveDateTime) -> NaiveDateTime { |
| 589 | + if self.hourly() { |
| 590 | + let hour = now.with_minute(0).and_then(|t| t.with_second(0)).and_then(|t| t.with_nanosecond(0)); |
| 591 | + hour.unwrap_or(now) - TimeDelta::hours(23) |
| 592 | + } else { |
| 593 | + (now.date() - TimeDelta::days(self.days() - 1)).and_hms_opt(0, 0, 0).unwrap_or(now) |
| 594 | + } |
| 595 | + } |
| 596 | + } |
| 597 | + |
| 598 | + /// Totals for one provider. |
| 599 | + #[derive(Clone, Debug, Default)] |
| 600 | + pub struct ProviderTotal { |
| 601 | + pub label: String, |
| 602 | + pub sessions: usize, |
| 603 | + pub tokens: u64, |
| 604 | + pub cost: f64, |
| 605 | + } |
| 606 | + |
| 607 | + /// One point of the chart: an hour or a day. |
| 608 | + #[derive(Clone, Debug)] |
| 609 | + pub struct Point { |
| 610 | + /// The axis label: `14:00` or `Oct 9`. |
| 611 | + pub label: String, |
| 612 | + /// The tooltip's title: `Thu, Oct 9, 14:00` or `Thu, Oct 9`. |
| 613 | + pub title: String, |
| 614 | + pub tokens: u64, |
| 615 | + pub cost: f64, |
| 616 | + } |
| 617 | + |
| 618 | + /// One row of the breakdown table. |
| 619 | + #[derive(Clone, Debug)] |
| 620 | + pub struct Line { |
| 621 | + pub label: String, |
| 622 | + pub tokens: u64, |
| 623 | + /// `None` when none of it has a price. |
| 624 | + pub cost: Option<f64>, |
| 625 | + } |
| 626 | + |
| 627 | + /// The report narrowed to a range and maybe one provider, in the shapes the page shows. |
| 628 | + #[derive(Clone, Debug, Default)] |
| 629 | + pub struct Summary { |
| 630 | + pub tokens: Tokens, |
| 631 | + pub cost: Costs, |
| 632 | + pub savings: f64, |
| 633 | + /// Tokens of models without a known price. |
| 634 | + pub unpriced: u64, |
| 635 | + pub sessions: usize, |
| 636 | + pub providers: Vec<ProviderTotal>, |
| 637 | + /// Every hour or day in the range, oldest first, zeros included. |
| 638 | + pub series: Vec<Point>, |
| 639 | + /// Most tokens first. |
| 640 | + pub models: Vec<Line>, |
| 641 | + /// Newest first, days with use only. |
| 642 | + pub days: Vec<Line>, |
| 643 | + } |
| 644 | + |
| 645 | + pub fn summarize(report: &UsageReport, span: Span, provider: Option<&str>, now: NaiveDateTime) -> Summary { |
| 646 | + let start = span.first_slot(now); |
| 647 | + let mut summary = Summary::default(); |
| 648 | + let mut providers: Vec<(ProviderTotal, BTreeSet<u32>)> = Vec::new(); |
| 649 | + let mut all_sessions = BTreeSet::new(); |
| 650 | + let mut models: Vec<Line> = Vec::new(); |
| 651 | + let mut days: Vec<(NaiveDate, Line)> = Vec::new(); |
| 652 | + |
| 653 | + let slots: Vec<NaiveDateTime> = if span.hourly() { |
| 654 | + (0..24).map(|ix| start + TimeDelta::hours(ix)).collect() |
| 655 | + } else { |
| 656 | + (0..span.days()).map(|ix| start + TimeDelta::days(ix)).collect() |
| 657 | + }; |
| 658 | + summary.series = slots |
| 659 | + .iter() |
| 660 | + .map(|slot| { |
| 661 | + let (label, title) = if span.hourly() { |
| 662 | + (slot.format("%H:%M").to_string(), slot.format("%a, %b %-d, %H:%M").to_string()) |
| 663 | + } else { |
| 664 | + (slot.format("%b %-d").to_string(), slot.format("%a, %b %-d").to_string()) |
| 665 | + }; |
| 666 | + Point { label, title, tokens: 0, cost: 0. } |
| 667 | + }) |
| 668 | + .collect(); |
| 669 | + |
| 670 | + for bucket in &report.buckets { |
| 671 | + if bucket.hour < start || provider.is_some_and(|provider| provider != bucket.provider) { |
| 672 | + continue; |
| 673 | + } |
| 674 | + let tokens = bucket.tokens.total(); |
| 675 | + let cost = bucket.cost.map(|cost| cost.total()); |
| 676 | + summary.tokens.add(&bucket.tokens); |
| 677 | + if let Some(costs) = &bucket.cost { |
| 678 | + summary.cost.add(costs); |
| 679 | + } else { |
| 680 | + summary.unpriced += tokens; |
| 681 | + } |
| 682 | + summary.savings += bucket.savings; |
| 683 | + all_sessions.extend(bucket.sessions.iter().copied()); |
| 684 | + |
| 685 | + let ix = match providers.iter().position(|(total, _)| total.label == bucket.provider) { |
| 686 | + Some(ix) => ix, |
| 687 | + None => { |
| 688 | + let total = ProviderTotal { label: bucket.provider.clone(), ..ProviderTotal::default() }; |
| 689 | + providers.push((total, BTreeSet::new())); |
| 690 | + providers.len() - 1 |
| 691 | + } |
| 692 | + }; |
| 693 | + let (total, sessions) = &mut providers[ix]; |
| 694 | + total.tokens += tokens; |
| 695 | + total.cost += cost.unwrap_or(0.); |
| 696 | + sessions.extend(bucket.sessions.iter().copied()); |
| 697 | + |
| 698 | + add_line(&mut models, |line| line.label == bucket.model, &bucket.model, tokens, cost); |
| 699 | + let day = bucket.day(); |
| 700 | + match days.iter_mut().find(|(date, _)| *date == day) { |
| 701 | + Some((_, line)) => add_to(line, tokens, cost), |
| 702 | + None => days.push((day, Line { label: day.format("%a, %b %-d").to_string(), tokens, cost })), |
| 703 | + } |
| 704 | + |
| 705 | + let slot = if span.hourly() { |
| 706 | + (bucket.hour - start).num_hours() |
| 707 | + } else { |
| 708 | + (bucket.day() - start.date()).num_days() |
| 709 | + }; |
| 710 | + if let Some(point) = usize::try_from(slot).ok().and_then(|slot| summary.series.get_mut(slot)) { |
| 711 | + point.tokens += tokens; |
| 712 | + point.cost += cost.unwrap_or(0.); |
| 713 | + } |
| 714 | + } |
| 715 | + |
| 716 | + summary.sessions = all_sessions.len(); |
| 717 | + summary.providers = providers |
| 718 | + .into_iter() |
| 719 | + .map(|(mut total, sessions)| { |
| 720 | + total.sessions = sessions.len(); |
| 721 | + total |
| 722 | + }) |
| 723 | + .collect(); |
| 724 | + summary.providers.sort_by(|a, b| b.tokens.cmp(&a.tokens)); |
| 725 | + models.sort_by(|a, b| b.tokens.cmp(&a.tokens)); |
| 726 | + summary.models = models; |
| 727 | + days.sort_by(|a, b| b.0.cmp(&a.0)); |
| 728 | + summary.days = days.into_iter().map(|(_, line)| line).collect(); |
| 729 | + summary |
| 730 | + } |
| 731 | + |
| 732 | + fn add_line(lines: &mut Vec<Line>, is: impl Fn(&Line) -> bool, label: &str, tokens: u64, cost: Option<f64>) { |
| 733 | + match lines.iter_mut().find(|line| is(line)) { |
| 734 | + Some(line) => add_to(line, tokens, cost), |
| 735 | + None => lines.push(Line { label: label.to_string(), tokens, cost }), |
| 736 | + } |
| 737 | + } |
| 738 | + |
| 739 | + fn add_to(line: &mut Line, tokens: u64, cost: Option<f64>) { |
| 740 | + line.tokens += tokens; |
| 741 | + if let Some(cost) = cost { |
| 742 | + *line.cost.get_or_insert(0.) += cost; |
| 743 | + } |
| 744 | + } |
| 745 | + |
| 746 | + // ---- formatting -------------------------------------------------------------------- |
| 747 | + |
| 748 | + /// Token counts the way T3 Code writes them: `532`, `14.2K`, `4.63M`, `1.08B`. |
| 749 | + pub fn format_tokens(count: u64) -> String { |
| 750 | + let count = count as f64; |
| 751 | + let (value, unit) = if count >= 1e9 { |
| 752 | + (count / 1e9, "B") |
| 753 | + } else if count >= 1e6 { |
| 754 | + (count / 1e6, "M") |
| 755 | + } else if count >= 1e3 { |
| 756 | + (count / 1e3, "K") |
| 757 | + } else { |
| 758 | + return format!("{count}"); |
| 759 | + }; |
| 760 | + let digits = if value >= 100. { 0 } else if value >= 10. { 1 } else { 2 }; |
| 761 | + format!("{value:.digits$}{unit}") |
| 762 | + } |
| 763 | + |
| 764 | + /// Dollars with cents and thousands separators: `$1,405.02`. |
| 765 | + pub fn format_cost(dollars: f64) -> String { |
| 766 | + if dollars > 0. && dollars < 0.01 { |
| 767 | + return "<$0.01".to_string(); |
| 768 | + } |
| 769 | + let cents = (dollars * 100.).round() as u64; |
| 770 | + let whole = (cents / 100).to_string(); |
| 771 | + let mut grouped = String::new(); |
| 772 | + for (ix, digit) in whole.chars().enumerate() { |
| 773 | + if ix > 0 && (whole.len() - ix).is_multiple_of(3) { |
| 774 | + grouped.push(','); |
| 775 | + } |
| 776 | + grouped.push(digit); |
| 777 | + } |
| 778 | + format!("${grouped}.{:02}", cents % 100) |
| 779 | + } |
| 780 | + |
| 781 | + // ---- plan limits ------------------------------------------------------------------- |
| 782 | + |
| 783 | + /// One plan limit, such as Claude's five-hour session window. |
| 784 | + #[derive(Clone, Debug, PartialEq)] |
| 785 | + pub struct Limit { |
| 786 | + pub label: String, |
| 787 | + /// How much of it is used, 0–100. |
| 788 | + pub percent: f64, |
| 789 | + pub resets_at: Option<DateTime<Local>>, |
| 790 | + /// `normal`, `warning` or `critical`, as Claude reports it. |
| 791 | + pub severity: String, |
| 792 | + /// Whether this is the limit currently holding the account back the most. |
| 793 | + pub active: bool, |
| 794 | + } |
| 795 | + |
| 796 | + /// Reads the limits from the reply to the Claude CLI's `get_usage` control request. |
| 797 | + pub fn limits_from_claude(reply: &Value) -> Vec<Limit> { |
| 798 | + let rate_limits = reply.get("rate_limits").unwrap_or(reply); |
| 799 | + if let Some(limits) = rate_limits.get("limits").and_then(Value::as_array) { |
| 800 | + return limits.iter().filter_map(claude_limit).collect(); |
| 801 | + } |
| 802 | + // Older replies only have the named windows. |
| 803 | + const WINDOWS: [(&str, &str); 4] = [ |
| 804 | + ("five_hour", "Current session"), |
| 805 | + ("seven_day", "Weekly · all models"), |
| 806 | + ("seven_day_opus", "Weekly · Opus"), |
| 807 | + ("seven_day_sonnet", "Weekly · Sonnet"), |
| 808 | + ]; |
| 809 | + let Some(windows) = rate_limits.as_object() else { return Vec::new() }; |
| 810 | + WINDOWS |
| 811 | + .iter() |
| 812 | + .filter_map(|(key, label)| { |
| 813 | + let window = windows.get(*key)?; |
| 814 | + let percent = window.get("utilization").and_then(Value::as_f64)?; |
| 815 | + Some(Limit { |
| 816 | + label: label.to_string(), |
| 817 | + percent, |
| 818 | + resets_at: window.get("resets_at").and_then(parse_time).map(|at| at.with_timezone(&Local)), |
| 819 | + severity: severity_of(percent).to_string(), |
| 820 | + active: false, |
| 821 | + }) |
| 822 | + }) |
| 823 | + .collect() |
| 824 | + } |
| 825 | + |
| 826 | + fn claude_limit(limit: &Value) -> Option<Limit> { |
| 827 | + let percent = limit.get("percent").and_then(Value::as_f64)?; |
| 828 | + let kind = limit.get("kind").and_then(Value::as_str).unwrap_or_default(); |
| 829 | + let scoped_to = limit |
| 830 | + .pointer("/scope/model/display_name") |
| 831 | + .and_then(Value::as_str) |
| 832 | + .or_else(|| limit.pointer("/scope/surface").and_then(Value::as_str)); |
| 833 | + let label = match (kind, scoped_to) { |
| 834 | + ("session", _) => "Current session".to_string(), |
| 835 | + ("weekly_all", _) => "Weekly · all models".to_string(), |
| 836 | + (_, Some(scope)) if kind.starts_with("weekly") => format!("Weekly · {scope}"), |
| 837 | + (_, Some(scope)) => format!("{} · {scope}", humanize(kind)), |
| 838 | + _ => humanize(kind), |
| 839 | + }; |
| 840 | + Some(Limit { |
| 841 | + label, |
| 842 | + percent, |
| 843 | + resets_at: limit.get("resets_at").and_then(parse_time).map(|at| at.with_timezone(&Local)), |
| 844 | + severity: limit |
| 845 | + .get("severity") |
| 846 | + .and_then(Value::as_str) |
| 847 | + .map(str::to_string) |
| 848 | + .unwrap_or_else(|| severity_of(percent).to_string()), |
| 849 | + active: limit.get("is_active").and_then(Value::as_bool).unwrap_or(false), |
| 850 | + }) |
| 851 | + } |
| 852 | + |
| 853 | + fn severity_of(percent: f64) -> &'static str { |
| 854 | + if percent >= 90. { |
| 855 | + "critical" |
| 856 | + } else if percent >= 75. { |
| 857 | + "warning" |
| 858 | + } else { |
| 859 | + "normal" |
| 860 | + } |
| 861 | + } |
| 862 | + |
| 863 | + /// `weekly_scoped` → `Weekly scoped`. |
| 864 | + fn humanize(key: &str) -> String { |
| 865 | + let words = key.replace('_', " "); |
| 866 | + let mut chars = words.chars(); |
| 867 | + match chars.next() { |
| 868 | + Some(first) => first.to_uppercase().chain(chars).collect(), |
| 869 | + None => "Limit".to_string(), |
| 870 | + } |
| 871 | + } |
| 872 | + |
| 873 | + #[cfg(test)] |
| 874 | + mod tests { |
| 875 | + use super::*; |
| 876 | + use serde_json::json; |
| 877 | + |
| 878 | + #[test] |
| 879 | + fn prices_by_prefix() { |
| 880 | + assert_eq!(price("claude-opus-5-5"), Some(Price::new(4., 20., 0.2))); |
| 881 | + assert_eq!(price("claude-haiku-4-5-20251001"), Some(Price::new(1., 5., 0.1))); |
| 882 | + assert_eq!(price("claude-opus-4-20250514"), Some(Price::new(15., 75., 1.5))); |
| 883 | + assert_eq!(price("claude-opus-4-1-20250805"), Some(Price::new(15., 75., 1.5))); |
| 884 | + assert_eq!(price("claude-opus-4-6"), Some(Price::new(5., 25., 0.5))); |
| 885 | + assert_eq!(price("claude-fable-5-1"), Some(Price::new(10., 50., 0.25))); |
| 886 | + assert_eq!(price("claude-fable-5"), Some(Price::new(10., 50., 1.))); |
| 887 | + assert_eq!(price("claude-mythos-1"), Some(Price::new(10., 50., 1.))); |
| 888 | + assert_eq!(price("anthropic/claude-sonnet-5"), Some(Price::new(2., 10., 0.2))); |
| 889 | + assert_eq!(price("claude-opus-5-5[1m]"), Some(Price::new(4., 20., 0.2))); |
| 890 | + assert_eq!(price("claude-3-5-haiku-20241022"), Some(Price::new(0.8, 4., 0.08))); |
| 891 | + assert_eq!(price("<synthetic>"), None); |
| 892 | + assert_eq!(price("gpt-5"), None); |
| 893 | + assert_eq!(Price::new(4., 20., 0.2).cache_write, 5.); |
| 894 | + } |
| 895 | + |
| 896 | + #[test] |
| 897 | + fn opus_5_5_month_costs_about_405() { |
| 898 | + let tokens = Tokens { input: 0, output: 4_600_000, cache_write: 20_600_000, cache_read: 1_050_000_000 }; |
| 899 | + let cost = price("claude-opus-5-5").unwrap().cost(&tokens).total(); |
| 900 | + assert!((cost - 405.).abs() < 1., "{cost}"); |
| 901 | + assert!((price("claude-opus-5-5").unwrap().savings(1_000_000) - 3.8).abs() < 1e-9); |
| 902 | + } |
| 903 | + |
| 904 | + #[test] |
| 905 | + fn formats_like_t3() { |
| 906 | + assert_eq!(format_tokens(1_080_000_000), "1.08B"); |
| 907 | + assert_eq!(format_tokens(4_630_000), "4.63M"); |
| 908 | + assert_eq!(format_tokens(14_200), "14.2K"); |
| 909 | + assert_eq!(format_tokens(532), "532"); |
| 910 | + assert_eq!(format_cost(405.019), "$405.02"); |
| 911 | + assert_eq!(format_cost(1405.5), "$1,405.50"); |
| 912 | + assert_eq!(format_cost(0.), "$0.00"); |
| 913 | + } |
| 914 | + |
| 915 | + #[test] |
| 916 | + fn claude_lines_dedup_by_response() { |
| 917 | + let line = |output: u64| { |
| 918 | + json!({ |
| 919 | + "type": "assistant", "timestamp": "2026-10-01T10:00:00.000Z", "sessionId": "s1", |
| 920 | + "requestId": "req_1", |
| 921 | + "message": {"id": "msg_1", "model": "claude-opus-5-5", "usage": { |
| 922 | + "input_tokens": 2, "output_tokens": output, |
| 923 | + "cache_creation_input_tokens": 100, "cache_read_input_tokens": 1000}} |
| 924 | + }) |
| 925 | + .to_string() |
| 926 | + }; |
| 927 | + let dir = std::env::temp_dir().join(format!("vectrum-usage-test-{}", std::process::id())); |
| 928 | + let file = dir.join("projects/p/s1.jsonl"); |
| 929 | + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); |
| 930 | + std::fs::write(&file, format!("{}\n{}\n{{\"type\":\"user\"}}\n", line(5), line(40))).unwrap(); |
| 931 | + let sources = UsageSources { claude_dirs: vec![("Claude Code".into(), dir.clone())], ..Default::default() }; |
| 932 | + let report = collect(&sources, SystemTime::UNIX_EPOCH); |
| 933 | + std::fs::remove_dir_all(&dir).ok(); |
| 934 | + assert_eq!(report.buckets.len(), 1); |
| 935 | + assert_eq!(report.buckets[0].tokens, Tokens { input: 2, output: 40, cache_write: 100, cache_read: 1000 }); |
| 936 | + assert_eq!(report.buckets[0].sessions.len(), 1); |
| 937 | + } |
| 938 | + |
| 939 | + #[test] |
| 940 | + fn pi_rows_use_pis_cost() { |
| 941 | + let line = json!({ |
| 942 | + "type": "message", "timestamp": "2026-10-01T10:00:00.000Z", |
| 943 | + "message": {"role": "assistant", "model": "gpt-5", "provider": "openai", "usage": { |
| 944 | + "input": 10, "output": 5, "cacheRead": 0, "cacheWrite": 0, |
| 945 | + "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}}} |
| 946 | + }); |
| 947 | + let row = pi_row(&line, "Pi", Some("s".into())).unwrap(); |
| 948 | + assert_eq!(row.tokens.total(), 15); |
| 949 | + assert!((row.cost.unwrap().total() - 0.03).abs() < 1e-9); |
| 950 | + } |
| 951 | + |
| 952 | + #[test] |
| 953 | + fn hub_rows_split_cached_input() { |
| 954 | + let reply = json!({"usage": {"apis": {"key": {"models": {"claude-sonnet-5": {"details": [ |
| 955 | + {"timestamp": "2026-10-01T10:00:00Z", "failed": false, "tokens": { |
| 956 | + "input_tokens": 100, "output_tokens": 10, "reasoning_tokens": 0, |
| 957 | + "cached_tokens": 60, "total_tokens": 110}} |
| 958 | + ]}}}}}}); |
| 959 | + let rows = hub_rows(&reply, "Hub", DateTime::<Utc>::UNIX_EPOCH); |
| 960 | + assert_eq!(rows.len(), 1); |
| 961 | + assert_eq!(rows[0].tokens, Tokens { input: 40, output: 10, cache_write: 0, cache_read: 60 }); |
| 962 | + } |
| 963 | + |
| 964 | + #[test] |
| 965 | + fn summary_fills_missing_days() { |
| 966 | + let now = NaiveDate::from_ymd_opt(2026, 10, 9).unwrap().and_hms_opt(12, 30, 0).unwrap(); |
| 967 | + let bucket = |day: u32, model: &str, output: u64| Bucket { |
| 968 | + provider: "Claude Code".into(), |
| 969 | + model: model.into(), |
| 970 | + hour: NaiveDate::from_ymd_opt(2026, 10, day).unwrap().and_hms_opt(9, 0, 0).unwrap(), |
| 971 | + tokens: Tokens { output, ..Tokens::default() }, |
| 972 | + cost: price(model).map(|price| price.cost(&Tokens { output, ..Tokens::default() })), |
| 973 | + savings: 0., |
| 974 | + sessions: BTreeSet::from([day]), |
| 975 | + }; |
| 976 | + let report = UsageReport { |
| 977 | + buckets: vec![bucket(1, "claude-opus-5-5", 1_000_000), bucket(8, "mystery", 500), bucket(9, "claude-opus-5-5", 10)], |
| 978 | + ..UsageReport::default() |
| 979 | + }; |
| 980 | + let week = summarize(&report, Span::Week, None, now); |
| 981 | + assert_eq!(week.series.len(), 7); |
| 982 | + assert_eq!(week.series[0].label, "Oct 3"); |
| 983 | + assert_eq!(week.series[5].tokens, 500); |
| 984 | + assert_eq!(week.series[6].tokens, 10); |
| 985 | + assert_eq!(week.tokens.total(), 510); |
| 986 | + assert_eq!(week.unpriced, 500); |
| 987 | + assert_eq!(week.sessions, 2); |
| 988 | + assert_eq!(week.models[0].label, "mystery"); |
| 989 | + assert_eq!(week.models[0].cost, None); |
| 990 | + assert_eq!(week.days.len(), 2); |
| 991 | + |
| 992 | + let month = summarize(&report, Span::Month, Some("Claude Code"), now); |
| 993 | + assert_eq!(month.series.len(), 30); |
| 994 | + assert!((month.cost.total() - 20.0002).abs() < 1e-6); |
| 995 | + assert_eq!(month.providers[0].sessions, 3); |
| 996 | + |
| 997 | + let day = summarize(&report, Span::Day, None, now); |
| 998 | + assert_eq!(day.series.len(), 24); |
| 999 | + assert_eq!(day.series.last().unwrap().label, "12:00"); |
| 1000 | + assert_eq!(day.tokens.total(), 10); |
| 1001 | + } |
| 1002 | + |
| 1003 | + #[test] |
| 1004 | + fn limits_from_the_limits_list() { |
| 1005 | + let reply = json!({ |
| 1006 | + "subscription_type": "team", |
| 1007 | + "rate_limits_available": true, |
| 1008 | + "rate_limits": { |
| 1009 | + "five_hour": {"utilization": 7, "resets_at": "2026-10-10T01:40:00.386310+00:00"}, |
| 1010 | + "seven_day": {"utilization": 22, "resets_at": "2026-10-12T17:00:00.386332+00:00"}, |
| 1011 | + "seven_day_opus": null, |
| 1012 | + "extra_usage": {"is_enabled": false}, |
| 1013 | + "limits": [ |
| 1014 | + {"kind": "session", "group": "session", "percent": 7, "severity": "normal", |
| 1015 | + "resets_at": "2026-10-10T01:40:00.386310+00:00", "scope": null, "is_active": false}, |
| 1016 | + {"kind": "weekly_all", "group": "weekly", "percent": 22, "severity": "normal", |
| 1017 | + "resets_at": "2026-10-12T17:00:00.386332+00:00", "scope": null, "is_active": true}, |
| 1018 | + {"kind": "weekly_scoped", "group": "weekly", "percent": 6, "severity": "normal", |
| 1019 | + "resets_at": "2026-10-12T17:00:00.386332+00:00", |
| 1020 | + "scope": {"model": {"id": null, "display_name": "Fable"}, "surface": null}, "is_active": false} |
| 1021 | + ] |
| 1022 | + } |
| 1023 | + }); |
| 1024 | + let limits = limits_from_claude(&reply); |
| 1025 | + let labels: Vec<&str> = limits.iter().map(|limit| limit.label.as_str()).collect(); |
| 1026 | + assert_eq!(labels, ["Current session", "Weekly · all models", "Weekly · Fable"]); |
| 1027 | + assert_eq!(limits[1].percent, 22.); |
| 1028 | + assert!(limits[1].active); |
| 1029 | + assert!(!limits[0].active); |
| 1030 | + assert_eq!( |
| 1031 | + limits[0].resets_at.map(|at| at.with_timezone(&Utc).to_rfc3339()), |
| 1032 | + Some("2026-10-10T01:40:00.386310+00:00".to_string()) |
| 1033 | + ); |
| 1034 | + } |
| 1035 | + |
| 1036 | + #[test] |
| 1037 | + fn limits_from_named_windows() { |
| 1038 | + let reply = json!({"rate_limits": { |
| 1039 | + "five_hour": {"utilization": 95, "resets_at": "2026-10-10T01:40:00+00:00"}, |
| 1040 | + "seven_day": {"utilization": 22, "resets_at": null}, |
| 1041 | + "seven_day_opus": null |
| 1042 | + }}); |
| 1043 | + let limits = limits_from_claude(&reply); |
| 1044 | + assert_eq!(limits.len(), 2); |
| 1045 | + assert_eq!(limits[0].label, "Current session"); |
| 1046 | + assert_eq!(limits[0].severity, "critical"); |
| 1047 | + assert_eq!(limits[1].label, "Weekly · all models"); |
| 1048 | + assert_eq!(limits[1].resets_at, None); |
| 1049 | + assert!(limits_from_claude(&json!({})).is_empty()); |
| 1050 | + } |
| 1051 | + |
| 1052 | + /// Prints the last 30 days of this machine's Claude Code usage by model: |
| 1053 | + /// `cargo test real_claude_usage -- --ignored --nocapture`. |
| 1054 | + #[test] |
| 1055 | + #[ignore] |
| 1056 | + fn real_claude_usage() { |
| 1057 | + let home = PathBuf::from(std::env::var_os("HOME").unwrap()); |
| 1058 | + let sources = UsageSources { |
| 1059 | + claude_dirs: vec![("Claude Code".into(), home.join(".claude"))], |
| 1060 | + pi_dirs: vec![("Pi".into(), home.join(".pi/agent"))], |
| 1061 | + hubs: Vec::new(), |
| 1062 | + }; |
| 1063 | + let started = std::time::Instant::now(); |
| 1064 | + let report = collect(&sources, Span::Month.since(Local::now())); |
| 1065 | + let elapsed = started.elapsed(); |
| 1066 | + let summary = summarize(&report, Span::Month, None, Local::now().naive_local()); |
| 1067 | + println!("collected in {elapsed:?}, {} buckets", report.buckets.len()); |
| 1068 | + for line in &summary.models { |
| 1069 | + let cost = line.cost.map(format_cost).unwrap_or_else(|| "unpriced".into()); |
| 1070 | + println!("{:<28} {:>8} {:>12}", line.label, format_tokens(line.tokens), cost); |
| 1071 | + } |
| 1072 | + let t = summary.tokens; |
| 1073 | + println!( |
| 1074 | + "total {} ({} sessions) {} · input {} output {} cache write {} cache read {} · savings {}", |
| 1075 | + format_tokens(t.total()), |
| 1076 | + summary.sessions, |
| 1077 | + format_cost(summary.cost.total()), |
| 1078 | + format_tokens(t.input), |
| 1079 | + format_tokens(t.output), |
| 1080 | + format_tokens(t.cache_write), |
| 1081 | + format_tokens(t.cache_read), |
| 1082 | + format_cost(summary.savings), |
| 1083 | + ); |
| 1084 | + println!("errors: {:?}", report.errors); |
| 1085 | + } |
| 1086 | + } |