use serde_json::Value;
use std::{
collections::{HashMap, hash_map::Entry},
path::Path,
};
use crate::{
apps::normalize_model,
error::AppError,
io::load,
model::{AppKind, UsageEntry},
};
const MAX_DEPTH: usize = 5;
pub fn collect() -> Result<Vec<UsageEntry>, AppError> {
let base = load::home_dir()?.join(".kimi-code").join("sessions");
if !base.is_dir() {
return Ok(Vec::new());
}
collect_from(&base)
}
pub fn collect_from(base: &Path) -> Result<Vec<UsageEntry>, AppError> {
let mut candidates: HashMap<String, UsageEntry> = HashMap::new();
for file in load::discover_files(base, "jsonl", MAX_DEPTH) {
if file.file_name().and_then(|n| n.to_str()) != Some("wire.jsonl") {
continue;
}
parse_wire(&file, &mut candidates);
}
Ok(candidates.into_values().collect())
}
fn parse_wire(file: &Path, candidates: &mut HashMap<String, UsageEntry>) {
let Ok(records) = load::read_jsonl(file) else {
return;
};
let session_id = file.ancestors().find_map(|p| {
p.file_name()
.and_then(|n| n.to_str())
.filter(|n| n.starts_with("session_"))
.map(str::to_string)
});
for record in records {
if load::str_get(&record, &["type"]) != Some("usage.record") {
continue;
}
let scope = load::str_get(&record, &["usageScope"]);
if scope.is_some() && scope != Some("turn") {
continue;
}
let Some(usage) = record.get("usage").filter(|u| u.is_object()) else {
continue;
};
let input = load::u64_get(usage, &["inputOther"]);
let output = load::u64_get(usage, &["output"]);
let cache_read = load::u64_get(usage, &["inputCacheRead"]);
let cache_creation = load::u64_get(usage, &["inputCacheCreation"]);
if input == 0 && output == 0 && cache_read == 0 && cache_creation == 0 {
continue;
}
let model = load::str_get(&record, &["model"])
.map_or_else(|| "unknown".to_string(), normalize_model);
let created_at = record
.get("time")
.and_then(load::timestamp_to_epoch)
.unwrap_or_else(load::now_epoch);
let time_raw = record
.get("time")
.and_then(Value::as_i64)
.unwrap_or(created_at);
let agent_id = load::str_get(&record, &["agentId"]).unwrap_or("main");
let key =
format!("{agent_id}:{time_raw}:{model}:{input}:{output}:{cache_read}:{cache_creation}");
match candidates.entry(key) {
Entry::Vacant(vacant) => {
vacant.insert(UsageEntry::new(
AppKind::Kimi,
model,
session_id.clone(),
created_at,
input,
output,
cache_read,
cache_creation,
None,
));
}
Entry::Occupied(_) => {}
}
}
}
#[cfg(test)]
#[path = "tests/kimi_test.rs"]
mod tests;