use std::path::PathBuf;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct UsageCheckpoint {
pub folder: PathBuf,
pub totals: String,
}
impl UsageCheckpoint {
pub fn new(folder: impl Into<PathBuf>, totals: impl Into<String>) -> Self {
Self {
folder: folder.into(),
totals: totals.into(),
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum UsagePurpose {
Turn,
Title,
CommitAssist,
Review,
Rebase,
Other,
}
impl UsagePurpose {
pub fn as_str(self) -> &'static str {
match self {
Self::Turn => "turn",
Self::Title => "title",
Self::CommitAssist => "commit_assist",
Self::Review => "review",
Self::Rebase => "rebase",
Self::Other => "other",
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CostBasis {
ListPrice,
HostPrice,
AgentReported,
Mixed,
}
impl CostBasis {
pub fn as_str(self) -> &'static str {
match self {
Self::ListPrice => "list",
Self::HostPrice => "host",
Self::AgentReported => "agent_reported",
Self::Mixed => "mixed",
}
}
#[must_use]
pub fn combine(self, other: Self) -> Self {
if self == other { self } else { Self::Mixed }
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PlanLogin {
ChatGpt,
Claude,
}
impl PlanLogin {
pub fn as_str(self) -> &'static str {
match self {
Self::ChatGpt => "chatgpt",
Self::Claude => "claude",
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PricedCost {
pub basis: CostBasis,
pub micro_usd: u64,
pub upper_bound: bool,
}
impl PricedCost {
pub fn new(basis: CostBasis, micro_usd: u64) -> Self {
Self {
basis,
micro_usd,
upper_bound: false,
}
}
#[must_use]
pub fn saturating_add(self, other: Self) -> Self {
Self {
basis: self.basis.combine(other.basis),
micro_usd: self.micro_usd.saturating_add(other.micro_usd),
upper_bound: self.upper_bound || other.upper_bound,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ApiEquivalentCost {
pub cost: PricedCost,
pub login: Option<PlanLogin>,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CostEstimate(CostParts);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum CostParts {
Charged(PricedCost),
ApiEquivalent(ApiEquivalentCost),
Both(PricedCost, ApiEquivalentCost),
}
impl CostEstimate {
pub fn new(basis: CostBasis, micro_usd: u64) -> Self {
Self::charged(PricedCost::new(basis, micro_usd))
}
pub fn charged(cost: PricedCost) -> Self {
Self(CostParts::Charged(cost))
}
pub fn plan_billed(equivalent: ApiEquivalentCost) -> Self {
Self(CostParts::ApiEquivalent(equivalent))
}
pub fn charge(self) -> Option<PricedCost> {
match self.0 {
CostParts::Charged(charged) | CostParts::Both(charged, _) => Some(charged),
CostParts::ApiEquivalent(_) => None,
}
}
pub fn api_equivalent(self) -> Option<ApiEquivalentCost> {
match self.0 {
CostParts::ApiEquivalent(equivalent) | CostParts::Both(_, equivalent) => {
Some(equivalent)
}
CostParts::Charged(_) => None,
}
}
#[must_use]
pub fn billed_to(self, login: PlanLogin) -> Self {
let cost = match self.0 {
CostParts::Charged(cost) | CostParts::ApiEquivalent(ApiEquivalentCost { cost, .. }) => {
cost
}
CostParts::Both(charged, equivalent) => charged.saturating_add(equivalent.cost),
};
Self::plan_billed(ApiEquivalentCost {
cost,
login: Some(login),
})
}
#[must_use]
pub fn saturating_add(self, other: Self) -> Self {
let charged = match (self.charge(), other.charge()) {
(Some(charged), Some(next)) => Some(charged.saturating_add(next)),
(charged, next) => charged.or(next),
};
let api_equivalent = match (self.api_equivalent(), other.api_equivalent()) {
(Some(equivalent), Some(next)) => Some(ApiEquivalentCost {
cost: equivalent.cost.saturating_add(next.cost),
login: equivalent.login.filter(|login| next.login == Some(*login)),
}),
(equivalent, next) => equivalent.or(next),
};
Self::from_parts(charged, api_equivalent).unwrap_or(self)
}
fn from_parts(
charged: Option<PricedCost>,
api_equivalent: Option<ApiEquivalentCost>,
) -> Option<Self> {
match (charged, api_equivalent) {
(Some(charged), Some(equivalent)) => Some(Self(CostParts::Both(charged, equivalent))),
(Some(charged), None) => Some(Self::charged(charged)),
(None, Some(equivalent)) => Some(Self::plan_billed(equivalent)),
(None, None) => None,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ContextFill {
pub last_input_tokens: u64,
pub peak_input_tokens: u64,
pub window_tokens: Option<u64>,
}
impl ContextFill {
pub fn of_request(input_tokens: u64, window_tokens: Option<u64>) -> Self {
Self {
last_input_tokens: input_tokens,
peak_input_tokens: input_tokens,
window_tokens,
}
}
#[must_use]
pub fn then(self, next: Self) -> Self {
Self {
last_input_tokens: next.last_input_tokens,
peak_input_tokens: self.peak_input_tokens.max(next.peak_input_tokens),
window_tokens: next.window_tokens.or(self.window_tokens),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ModelUsage {
pub cache_read_tokens: Option<u64>,
pub cache_write_tokens: Option<u64>,
pub context: Option<ContextFill>,
pub cost: Option<CostEstimate>,
pub input_tokens: u64,
pub model: String,
pub output_tokens: u64,
pub reasoning_tokens: Option<u64>,
pub requests: u32,
pub unreported_requests: u32,
}
impl ModelUsage {
pub fn new(model: impl Into<String>) -> Self {
Self {
cache_read_tokens: None,
cache_write_tokens: None,
context: None,
cost: None,
input_tokens: 0,
model: model.into(),
output_tokens: 0,
reasoning_tokens: None,
requests: 0,
unreported_requests: 0,
}
}
pub fn unreported(model: impl Into<String>, requests: u32) -> Self {
Self {
requests,
unreported_requests: requests,
..Self::new(model)
}
}
pub fn add(&mut self, next: &Self) {
let both = |total: Option<u64>, tokens: Option<u64>| {
total
.zip(tokens)
.map(|(total, tokens)| total.saturating_add(tokens))
};
self.cache_read_tokens = both(self.cache_read_tokens, next.cache_read_tokens);
self.cache_write_tokens = both(self.cache_write_tokens, next.cache_write_tokens);
self.context = match (self.context, next.context) {
(Some(context), Some(next_context)) => Some(context.then(next_context)),
(context, next_context) => next_context.or(context),
};
self.cost = self
.cost
.zip(next.cost)
.map(|(cost, next_cost)| cost.saturating_add(next_cost));
self.input_tokens = self.input_tokens.saturating_add(next.input_tokens);
self.output_tokens = self.output_tokens.saturating_add(next.output_tokens);
self.reasoning_tokens = both(self.reasoning_tokens, next.reasoning_tokens);
self.requests = self.requests.saturating_add(next.requests);
self.unreported_requests = self
.unreported_requests
.saturating_add(next.unreported_requests);
}
pub fn is_empty(&self) -> bool {
self.input_tokens == 0 && self.output_tokens == 0 && self.unreported_requests == 0
}
}
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct TurnUsage {
pub checkpoint: Option<UsageCheckpoint>,
pub models: Vec<ModelUsage>,
}
impl TurnUsage {
pub fn single(usage: ModelUsage) -> Self {
Self {
checkpoint: None,
models: vec![usage],
}
}
pub fn record(&mut self, next: &ModelUsage) {
let entry = match self
.models
.iter()
.position(|usage| usage.model == next.model)
{
Some(index) => {
let mut entry = self.models.remove(index);
entry.add(next);
entry
}
None => next.clone(),
};
self.models.push(entry);
}
pub fn merge(&mut self, next: &Self) {
for usage in &next.models {
self.record(usage);
}
if next.checkpoint.is_some() {
self.checkpoint.clone_from(&next.checkpoint);
}
}
pub fn total(&self) -> Option<ModelUsage> {
self.models.iter().cloned().reduce(|mut total, next| {
total.add(&next);
total
})
}
pub fn context(&self) -> Option<ContextFill> {
self.models.iter().rev().find_map(|usage| usage.context)
}
pub fn input_tokens(&self) -> u64 {
self.models
.iter()
.fold(0, |total, usage| total.saturating_add(usage.input_tokens))
}
pub fn output_tokens(&self) -> u64 {
self.models
.iter()
.fold(0, |total, usage| total.saturating_add(usage.output_tokens))
}
}
#[cfg(test)]
#[path = "usage_test.rs"]
mod tests;