Skip to main content

Crate tokenusage

Crate tokenusage 

Source
Expand description

§tokenusage

Fast, zero-config token usage tracker for Codex, Claude Code, and Antigravity. Parses local log files produced by AI coding assistants and computes per-model, per-day, and per-session token counts with estimated USD costs.

This crate is dual-use:

Use caseFeatureWhat you get
CLI binary (tu)cli (default)Full terminal UI, TUI dashboard, image export, GUI
Library dependencyno default featuresProgrammatic access to parsed usage data

§Quick start (library)

Add tokenusage as a dependency without the default cli feature so you only pull in the lightweight parsing core:

[dependencies]
tokenusage = { version = "1.5", default-features = false }

§Fetch a full usage snapshot

use tokenusage::{Config, ReportPeriod};

let config = Config::default();
let snapshot = tokenusage::usage_snapshot(config).await?;
for event in &snapshot.events {
    println!("{}: {} ({} tokens)",
        event.timestamp, event.model, event.usage.total_tokens());
}

§Generate a daily cost report

use tokenusage::{Config, ReportPeriod};

let report = tokenusage::daily_report(
    Config::default(),
    ReportPeriod::Daily,
    false,   // instances (per-session breakdown)
    None,    // project filter
).await?;

for row in &report.daily {
    println!("{}: {} total tokens, ${:.4}",
        row.date, row.totals.total_tokens, row.totals.cost_usd);
}
println!("Grand total: ${:.4}", report.totals.cost_usd);

§Filter by date range

use tokenusage::Config;

let config = Config {
    since: Some("2025-06-01".into()),
    until: Some("2025-06-30".into()),
    ..Config::default()
};
let events = tokenusage::load_events(config).await?;
println!("June events: {}", events.len());

§Architecture overview

 Log files on disk
   (Claude ~/.claude/projects/*/,  Codex ~/.codex/sessions/*)
        |
        v
 +--------------+     +--------------+     +---------------+
 |  Discovery   | --> |   Parsing    | --> |  Aggregation  |
 |  (sources)   |     | (rayon par.) |     | (reports/snap)|
 +--------------+     +--------------+     +---------------+
        |                    |                     |
   SourceConfig         UsageEvent           DailyReport
   DiscoveredFile       ParseStats          UsageSnapshot
  1. Discovery — Scans configured root directories for JSONL log files.
  2. Parsing — Parallel (rayon) extraction of UsageEvents with incremental caching for repeated runs.
  3. Aggregation — Groups events into DailyReport rows or returns a raw UsageSnapshot.

§Feature flags

FeatureDefaultDescription
cliyesEnables the tu binary and all terminal/GUI dependencies (clap, ratatui, iced, etc.)

When cli is disabled the crate compiles with only the core parsing and reporting logic — no terminal, no GUI, no image export dependencies.

Re-exports§

pub use api::Config;
pub use api::SortOrder;
pub use api::WeekStart;
pub use api::daily_report;
pub use api::daily_report_with_week_start;
pub use api::load_events;
pub use api::parse_stats;
pub use api::usage_snapshot;

Modules§

api
Public library API for programmatic access to token usage data.

Structs§

ActivitySummary
Coding activity summary derived from heartbeat data.
DailyReport
Complete usage report with per-period rows and grand totals.
DailyRow
A single row in a daily/weekly/monthly usage report.
DateFilter
Inclusive date range filter.
ParseStats
Parsing diagnostics — how many files/lines were processed and why some were skipped.
PricingRate
Per-model pricing rates in USD per million tokens.
PricingTable
Model pricing lookup table with exact-match and prefix-match entries.
TokenCounts
Immutable token count snapshot with pre-computed total.
UsageAccumulator
Running accumulator for token counts and estimated cost.
UsageEvent
A single parsed token usage event from a log file.
UsageSnapshot
Complete snapshot of parsed token usage data.

Enums§

ReportPeriod
Time granularity for report grouping.
SourceKind
Which AI coding assistant produced a log entry.
TimeZoneMode
Timezone strategy for date grouping.