use crate::cli::TimeRange;
use crate::constants::{FastHashMap, capacity};
use crate::models::{
CodeAnalysis, ExtensionType, PerProviderUsage, Provider, ProviderActiveDays, UsageResult,
};
use crate::pricing::{ModelPricingMap, calculate_cost};
use crate::session::{ParseMode, parse_session_file_as, read_cursor_usage, read_opencode_usage};
use crate::utils::{
COPILOT_SESSION_MAX_DEPTH, TokenCounts, collect_files_with_max_depth, is_claude_session_file,
is_codex_session_file, is_copilot_session_file, is_gemini_session_file, resolve_paths,
};
use anyhow::Result;
use rayon::prelude::*;
use serde_json::{Value, json};
use std::collections::HashSet;
use std::path::Path;
pub struct UsageData {
pub models: UsageResult,
pub per_provider: PerProviderUsage,
pub provider_days: ProviderActiveDays,
pub stored_costs: StoredCosts,
}
#[derive(Debug, Default, Clone)]
pub struct StoredCosts {
pub opencode: FastHashMap<String, f64>,
pub cursor: FastHashMap<String, f64>,
}
fn extract_conversation_usage_from_analysis(analysis: &CodeAnalysis) -> FastHashMap<String, Value> {
let mut conversation_usage = FastHashMap::with_capacity(capacity::MODELS_PER_SESSION);
let mut merge_into = |model: &String, usage: &Value| {
conversation_usage
.entry(model.clone())
.and_modify(|existing_usage| merge_usage_values(existing_usage, usage))
.or_insert_with(|| usage.clone());
};
for record in &analysis.records {
for (model, usage) in &record.conversation_usage {
merge_into(model, usage);
}
for (model, usage) in &record.advisor_usage {
merge_into(model, usage);
}
}
conversation_usage
}
pub fn get_usage_from_directories(time_range: TimeRange) -> Result<UsageData> {
let paths = resolve_paths()?;
let mut result = FastHashMap::with_capacity(capacity::MODEL_COMBINATIONS);
let mut per_provider = PerProviderUsage::default();
let mut stored_costs = StoredCosts::default();
let mut claude_dates: HashSet<String> = HashSet::new();
let mut codex_dates: HashSet<String> = HashSet::new();
let mut copilot_dates: HashSet<String> = HashSet::new();
let mut gemini_dates: HashSet<String> = HashSet::new();
let mut opencode_dates: HashSet<String> = HashSet::new();
let mut cursor_dates: HashSet<String> = HashSet::new();
if paths.claude_session_dir.exists() {
process_usage_directory(
&paths.claude_session_dir,
ExtensionType::ClaudeCode,
&mut result,
&mut per_provider.claude,
&mut claude_dates,
is_claude_session_file,
time_range,
None,
)?;
}
if paths.codex_session_dir.exists() {
process_usage_directory(
&paths.codex_session_dir,
ExtensionType::Codex,
&mut result,
&mut per_provider.codex,
&mut codex_dates,
is_codex_session_file,
time_range,
None,
)?;
}
if paths.copilot_session_dir.exists() {
process_usage_directory(
&paths.copilot_session_dir,
ExtensionType::Copilot,
&mut result,
&mut per_provider.copilot,
&mut copilot_dates,
is_copilot_session_file,
time_range,
Some(COPILOT_SESSION_MAX_DEPTH),
)?;
}
if paths.gemini_session_dir.exists() {
process_usage_directory(
&paths.gemini_session_dir,
ExtensionType::Gemini,
&mut result,
&mut per_provider.gemini,
&mut gemini_dates,
is_gemini_session_file,
time_range,
None,
)?;
}
if paths.opencode_db.exists()
&& let Err(err) = process_opencode_usage(
&paths.opencode_db,
&mut result,
&mut per_provider.opencode,
&mut stored_costs.opencode,
&mut opencode_dates,
time_range,
)
{
eprintln!(
"Warning: Failed to read OpenCode DB {}: {err}",
paths.opencode_db.display()
);
}
if (paths.cursor_chats_dir.exists() || paths.cursor_dir.join("auth.json").exists())
&& let Err(err) = process_cursor_usage(
&paths.cursor_chats_dir,
&paths.cursor_tracking_db,
&mut result,
&mut per_provider.cursor,
&mut stored_costs.cursor,
&mut cursor_dates,
time_range,
)
{
eprintln!("Warning: Failed to read Cursor usage: {err}");
}
let mut all_dates: HashSet<&String> = HashSet::new();
all_dates.extend(claude_dates.iter());
all_dates.extend(codex_dates.iter());
all_dates.extend(copilot_dates.iter());
all_dates.extend(gemini_dates.iter());
all_dates.extend(opencode_dates.iter());
all_dates.extend(cursor_dates.iter());
let provider_days = ProviderActiveDays {
claude: claude_dates.len(),
codex: codex_dates.len(),
copilot: copilot_dates.len(),
gemini: gemini_dates.len(),
opencode: opencode_dates.len(),
cursor: cursor_dates.len(),
total: all_dates.len(),
};
Ok(UsageData {
models: result,
per_provider,
provider_days,
stored_costs,
})
}
#[allow(clippy::too_many_arguments)] fn process_usage_directory<P, F>(
dir: P,
provider: ExtensionType,
global_result: &mut UsageResult,
provider_result: &mut UsageResult,
unique_dates: &mut HashSet<String>,
filter_fn: F,
time_range: TimeRange,
max_depth: Option<usize>,
) -> Result<()>
where
P: AsRef<Path>,
F: Copy + Fn(&Path) -> bool + Sync + Send,
{
let dir = dir.as_ref();
let files = collect_files_with_max_depth(dir, filter_fn, time_range, max_depth)?;
let file_results: Vec<(String, FastHashMap<String, Value>)> = files
.par_iter()
.filter_map(|file_info| {
match parse_session_file_as(&file_info.path, provider, ParseMode::UsageOnly) {
Ok(analysis) => {
let conversation_usage = extract_conversation_usage_from_analysis(&analysis);
Some((file_info.modified_date.clone(), conversation_usage))
}
Err(e) => {
eprintln!(
"Warning: Failed to analyze {}: {}",
file_info.path.display(),
e
);
None
}
}
})
.collect();
for (date, conversation_usage) in file_results {
unique_dates.insert(date);
for (model, usage_value) in conversation_usage {
provider_result
.entry(model.clone())
.and_modify(|existing| merge_usage_values(existing, &usage_value))
.or_insert_with(|| usage_value.clone());
global_result
.entry(model)
.and_modify(|existing| merge_usage_values(existing, &usage_value))
.or_insert(usage_value);
}
}
Ok(())
}
fn process_opencode_usage(
db_path: &Path,
global_result: &mut UsageResult,
provider_result: &mut UsageResult,
stored_costs: &mut FastHashMap<String, f64>,
unique_dates: &mut HashSet<String>,
time_range: TimeRange,
) -> Result<()> {
let sessions = read_opencode_usage(db_path, time_range)?;
fold_stored_cost_sessions(
sessions,
global_result,
provider_result,
stored_costs,
unique_dates,
);
Ok(())
}
fn process_cursor_usage(
chats_dir: &Path,
tracking_db: &Path,
global_result: &mut UsageResult,
provider_result: &mut UsageResult,
stored_costs: &mut FastHashMap<String, f64>,
unique_dates: &mut HashSet<String>,
time_range: TimeRange,
) -> Result<()> {
let sessions = read_cursor_usage(chats_dir, tracking_db, time_range)?;
fold_stored_cost_sessions(
sessions,
global_result,
provider_result,
stored_costs,
unique_dates,
);
Ok(())
}
fn fold_stored_cost_sessions(
sessions: Vec<(String, CodeAnalysis, f64)>,
global_result: &mut UsageResult,
provider_result: &mut UsageResult,
stored_costs: &mut FastHashMap<String, f64>,
unique_dates: &mut HashSet<String>,
) {
for (date, analysis, session_cost) in sessions {
unique_dates.insert(date);
let conversation_usage = extract_conversation_usage_from_analysis(&analysis);
for (model, usage_value) in conversation_usage {
*stored_costs.entry(model.clone()).or_insert(0.0) += session_cost;
provider_result
.entry(model.clone())
.and_modify(|existing| merge_usage_values(existing, &usage_value))
.or_insert_with(|| usage_value.clone());
global_result
.entry(model)
.and_modify(|existing| merge_usage_values(existing, &usage_value))
.or_insert(usage_value);
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum CostSource {
Litellm,
OpenCodeStored(f64),
CursorStored(f64),
}
pub fn resolve_model_cost(
model: &str,
counts: &TokenCounts,
pricing_map: &ModelPricingMap,
source: CostSource,
) -> (f64, Option<String>) {
let priced = |pricing: &crate::pricing::ModelPricing| {
let token_cost = calculate_cost(
counts.input_tokens,
counts.output_tokens,
counts.reasoning_tokens,
counts.cache_read,
counts.cache_creation_5m,
counts.cache_creation_1h,
pricing,
);
token_cost + counts.web_search_requests as f64 * pricing.web_search_cost_per_query
};
match source {
CostSource::CursorStored(stored) => (stored, None),
CostSource::OpenCodeStored(stored) => match pricing_map.get_exact(model) {
Some(pricing) => (priced(&pricing), None),
None => (stored, None),
},
CostSource::Litellm => {
let result = pricing_map.get(model);
(priced(&result.pricing), result.matched_model)
}
}
}
impl UsageData {
pub fn provider_usage(&self, provider: Provider) -> Option<&UsageResult> {
self.per_provider.get(provider)
}
}
fn merge_usage_values(existing: &mut Value, new: &Value) {
use crate::utils::{accumulate_i64_fields, accumulate_nested_object, extract_token_counts};
let (Some(existing_ro), Some(new_ro)) = (existing.as_object(), new.as_object()) else {
return;
};
let existing_flat = existing_ro.contains_key("input_tokens");
let existing_codex = existing_ro.contains_key("total_token_usage");
let new_flat = new_ro.contains_key("input_tokens");
let new_codex = new_ro.contains_key("total_token_usage");
if (existing_flat && new_codex) || (existing_codex && new_flat) {
let merged = add_token_counts(&extract_token_counts(existing), &extract_token_counts(new));
*existing = token_counts_to_flat_value(&merged);
return;
}
if let (Some(existing_obj), Some(new_obj)) = (existing.as_object_mut(), new.as_object()) {
if existing_obj.contains_key("input_tokens") {
accumulate_i64_fields(
existing_obj,
new_obj,
&[
"input_tokens",
"cache_creation_input_tokens",
"cache_read_input_tokens",
"output_tokens",
"thoughts_tokens",
"reasoning_output_tokens",
"tool_tokens",
"total_tokens",
],
);
if let Some(new_cache) = new_obj.get("cache_creation").and_then(|v| v.as_object()) {
accumulate_nested_object(existing_obj, "cache_creation", new_cache);
}
if let Some(new_stu) = new_obj.get("server_tool_use").and_then(|v| v.as_object()) {
accumulate_nested_object(existing_obj, "server_tool_use", new_stu);
}
}
else if existing_obj.contains_key("total_token_usage")
&& let Some(new_total) = new_obj.get("total_token_usage").and_then(|v| v.as_object())
{
accumulate_nested_object(existing_obj, "total_token_usage", new_total);
}
}
}
fn add_token_counts(a: &TokenCounts, b: &TokenCounts) -> TokenCounts {
TokenCounts {
input_tokens: a.input_tokens + b.input_tokens,
output_tokens: a.output_tokens + b.output_tokens,
reasoning_tokens: a.reasoning_tokens + b.reasoning_tokens,
cache_read: a.cache_read + b.cache_read,
cache_creation: a.cache_creation + b.cache_creation,
cache_creation_5m: a.cache_creation_5m + b.cache_creation_5m,
cache_creation_1h: a.cache_creation_1h + b.cache_creation_1h,
web_search_requests: a.web_search_requests + b.web_search_requests,
total: a.total + b.total,
}
}
fn token_counts_to_flat_value(c: &TokenCounts) -> Value {
let mut obj = serde_json::Map::new();
obj.insert("input_tokens".into(), json!(c.input_tokens));
obj.insert("output_tokens".into(), json!(c.output_tokens));
obj.insert("reasoning_output_tokens".into(), json!(c.reasoning_tokens));
obj.insert("cache_read_input_tokens".into(), json!(c.cache_read));
obj.insert(
"cache_creation_input_tokens".into(),
json!(c.cache_creation),
);
if c.cache_creation_5m != 0 || c.cache_creation_1h != 0 {
obj.insert(
"cache_creation".into(),
json!({
"ephemeral_5m_input_tokens": c.cache_creation_5m,
"ephemeral_1h_input_tokens": c.cache_creation_1h,
}),
);
}
if c.web_search_requests != 0 {
obj.insert(
"server_tool_use".into(),
json!({ "web_search_requests": c.web_search_requests }),
);
}
Value::Object(obj)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pricing::{ModelPricing, clear_pricing_cache};
use std::collections::HashMap;
fn map_with_gpt4() -> ModelPricingMap {
let mut raw = HashMap::new();
raw.insert(
"gpt-4".to_string(),
ModelPricing {
input_cost_per_token: 1e-5,
..Default::default()
},
);
ModelPricingMap::new(raw)
}
fn counts(input: i64) -> TokenCounts {
TokenCounts {
input_tokens: input,
total: input,
..Default::default()
}
}
#[test]
fn test_opencode_exact_match_computes_from_tokens() {
clear_pricing_cache();
let map = map_with_gpt4();
let (cost, matched) = resolve_model_cost(
"gpt-4",
&counts(1_000_000),
&map,
CostSource::OpenCodeStored(99.0),
);
assert!((cost - 10.0).abs() < 1e-6); assert!(matched.is_none());
}
#[test]
fn test_opencode_no_exact_match_uses_stored_cost() {
clear_pricing_cache();
let map = map_with_gpt4();
let (cost, matched) = resolve_model_cost(
"deepseek-v4-pro",
&counts(1_000_000),
&map,
CostSource::OpenCodeStored(99.0),
);
assert!((cost - 99.0).abs() < 1e-9);
assert!(matched.is_none());
}
#[test]
fn test_cursor_stored_cost_ignores_exact_match() {
clear_pricing_cache();
let map = map_with_gpt4();
let (cost, matched) = resolve_model_cost(
"gpt-4",
&counts(1_000_000),
&map,
CostSource::CursorStored(3.5),
);
assert!((cost - 3.5).abs() < 1e-9);
assert!(matched.is_none());
}
#[test]
fn test_non_opencode_keeps_existing_lookup() {
clear_pricing_cache();
let map = map_with_gpt4();
let (cost, matched) =
resolve_model_cost("gpt-4", &counts(1_000_000), &map, CostSource::Litellm);
assert!((cost - 10.0).abs() < 1e-6);
assert!(matched.is_none());
}
#[test]
fn merge_preserves_tokens_across_mixed_shapes() {
use crate::utils::extract_token_counts;
let codex = json!({
"total_token_usage": {
"input_tokens": 1000,
"cached_input_tokens": 200,
"output_tokens": 500,
"total_tokens": 1500
}
});
let flat = json!({
"input_tokens": 100,
"output_tokens": 20,
"cache_read_input_tokens": 50,
"cache_creation_input_tokens": 10
});
let expect = |c: TokenCounts| {
assert_eq!(c.input_tokens, 800 + 100);
assert_eq!(c.output_tokens, 500 + 20);
assert_eq!(c.cache_read, 200 + 50);
assert_eq!(c.cache_creation, 10);
assert_eq!(c.total, 1680);
};
let mut existing = codex.clone();
merge_usage_values(&mut existing, &flat);
expect(extract_token_counts(&existing));
let mut existing = flat.clone();
merge_usage_values(&mut existing, &codex);
expect(extract_token_counts(&existing));
}
}