| 1 | use std::collections::BTreeMap; |
| 2 | |
| 3 | use codewhale_command_contract::facets::{ |
| 4 | DebugCostProjection, ReceiptCost, ReceiptCostState, ReceiptTokens, ReceiptUsage, |
| 5 | }; |
| 6 | use codewhale_command_contract::types::CommandCurrency; |
| 7 | use codewhale_commands::debug::tokens::{ |
| 8 | SUBSCRIPTION_ONLY_COST_NOTE, cost_is_subscription_only, cost_report, |
| 9 | }; |
| 10 | |
| 11 | use super::Receipt; |
| 12 | use crate::cost_status::UsageSourceContribution; |
| 13 | use crate::diagnostics_messages::EnglishDiagnostics; |
| 14 | use crate::llm_client::ProviderUsageCoverage; |
| 15 | use crate::session_manager::{SessionCostSnapshot, SessionMetadata}; |
| 16 | |
| 17 | const TURN_SCOPE_NOTE: &str = "Usage: token counts and cost are kept for the whole session, not per turn, so a single-turn receipt leaves them out."; |
| 18 | const NO_TOKENS_NOTE: &str = "Tokens: the session saved no provider token counts, so none are shown; that is not zero usage."; |
| 19 | const THREAD_COST_NOTE: &str = "Cost: a Runtime thread receipt carries token counts only; GET /v1/threads/{id}/usage reports the thread's cost and what it covers."; |
| 20 | |
| 21 | fn sanitize(amount: f64) -> f64 { |
| 22 | if amount.is_finite() && amount >= 0.0 { |
| 23 | amount |
| 24 | } else { |
| 25 | 0.0 |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | pub fn cost_projection_from_snapshot(cost: &SessionCostSnapshot) -> DebugCostProjection { |
| 30 | let cny = cost.cny_priced_turns > 0 && cost.priced_turns == 0; |
| 31 | let (parent, auxiliary, high_water, priced, unpriced, reasons) = if cny { |
| 32 | ( |
| 33 | cost.session_cost_cny, |
| 34 | cost.subagent_cost_cny, |
| 35 | cost.displayed_cost_high_water_cny, |
| 36 | cost.cny_priced_turns, |
| 37 | cost.cny_unpriced_turns, |
| 38 | &cost.cny_unpriced_reasons, |
| 39 | ) |
| 40 | } else { |
| 41 | ( |
| 42 | cost.session_cost_usd, |
| 43 | cost.subagent_cost_usd, |
| 44 | cost.displayed_cost_high_water_usd, |
| 45 | cost.priced_turns, |
| 46 | cost.unpriced_turns, |
| 47 | &cost.unpriced_reasons, |
| 48 | ) |
| 49 | }; |
| 50 | let parent_turns = sanitize(parent); |
| 51 | let subagents = sanitize(auxiliary); |
| 52 | let current = parent_turns + subagents; |
| 53 | let total = current.max(sanitize(high_water)); |
| 54 | DebugCostProjection { |
| 55 | currency: if cny { |
| 56 | CommandCurrency::Cny |
| 57 | } else { |
| 58 | CommandCurrency::Usd |
| 59 | }, |
| 60 | total, |
| 61 | parent_turns, |
| 62 | subagents, |
| 63 | display_floor: (total - current).max(0.0), |
| 64 | priced_turns: priced, |
| 65 | unpriced_turns: unpriced, |
| 66 | legacy_coverage_unknown: cost.coverage_is_legacy_unknown(), |
| 67 | user_declared_estimates: cost.pricing_provenances.contains("user_override"), |
| 68 | itemized_turns: 0, |
| 69 | route_amounts: Vec::new(), |
| 70 | turn_history_capacity: 0, |
| 71 | unpriced_reason_labels: reasons.iter().cloned().collect(), |
| 72 | unpriced_classes: cost.unpriced_classes.iter().cloned().collect(), |
| 73 | pricing_provenances: cost.pricing_provenances.iter().cloned().collect(), |
| 74 | live_pricing_defects: cost.live_pricing_defects.iter().cloned().collect(), |
| 75 | unusable_pricing_defects: cost.live_pricing_unusable_defects.iter().cloned().collect(), |
| 76 | route_receipts: cost.route_receipts.iter().cloned().collect(), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub fn receipt_cost(projection: &DebugCostProjection) -> ReceiptCost { |
| 81 | let has_amount = projection.priced_turns > 0 |
| 82 | || (projection.legacy_coverage_unknown && projection.total > 0.0); |
| 83 | let state = if !has_amount { |
| 84 | ReceiptCostState::Unknown |
| 85 | } else if projection.unpriced_turns > 0 || projection.legacy_coverage_unknown { |
| 86 | ReceiptCostState::Partial |
| 87 | } else { |
| 88 | ReceiptCostState::Priced |
| 89 | }; |
| 90 | let report = if cost_is_subscription_only(projection) { |
| 91 | SUBSCRIPTION_ONLY_COST_NOTE.to_string() |
| 92 | } else { |
| 93 | cost_report(projection, &EnglishDiagnostics) |
| 94 | .unwrap_or_else(|error| format!("The cost report is unavailable: {error}")) |
| 95 | }; |
| 96 | ReceiptCost { |
| 97 | state, |
| 98 | amount: has_amount.then_some(projection.total), |
| 99 | currency: match projection.currency { |
| 100 | CommandCurrency::Usd => "USD", |
| 101 | CommandCurrency::Cny => "CNY", |
| 102 | }, |
| 103 | priced_turns: projection.priced_turns, |
| 104 | unpriced_turns: projection.unpriced_turns, |
| 105 | report, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn add(total: &mut Option<u64>, value: Option<u32>) { |
| 110 | if let Some(value) = value { |
| 111 | *total = Some(total.unwrap_or(0).saturating_add(u64::from(value))); |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | pub fn tokens_from_sources( |
| 116 | sources: &BTreeMap<String, UsageSourceContribution>, |
| 117 | saved_total: u64, |
| 118 | ) -> Option<ReceiptTokens> { |
| 119 | let mut tokens = ReceiptTokens::default(); |
| 120 | let (mut input, mut output, mut calls) = (0u64, 0u64, 0usize); |
| 121 | for contribution in sources.values() { |
| 122 | let record = &contribution.record; |
| 123 | let reported = record.settlement.as_ref().map_or_else( |
| 124 | || record.usage.usage != Default::default(), |
| 125 | |revision| { |
| 126 | matches!( |
| 127 | revision.coverage, |
| 128 | ProviderUsageCoverage::Reported | ProviderUsageCoverage::Incomplete |
| 129 | ) |
| 130 | }, |
| 131 | ); |
| 132 | if !reported { |
| 133 | continue; |
| 134 | } |
| 135 | let usage = &record.usage.usage; |
| 136 | input = input.saturating_add(u64::from(usage.input_tokens)); |
| 137 | output = output.saturating_add(u64::from(usage.output_tokens)); |
| 138 | add(&mut tokens.cache_read, usage.prompt_cache_hit_tokens); |
| 139 | add(&mut tokens.cache_write, usage.prompt_cache_write_tokens); |
| 140 | add(&mut tokens.reasoning, usage.reasoning_tokens); |
| 141 | calls += 1; |
| 142 | } |
| 143 | if calls > 0 { |
| 144 | tokens.input = Some(input); |
| 145 | tokens.output = Some(output); |
| 146 | tokens.total = input.saturating_add(output); |
| 147 | tokens.calls = Some(calls); |
| 148 | Some(tokens) |
| 149 | } else if saved_total > 0 { |
| 150 | tokens.total = saved_total; |
| 151 | Some(tokens) |
| 152 | } else { |
| 153 | None |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | pub fn session_usage( |
| 158 | projection: &DebugCostProjection, |
| 159 | sources: &BTreeMap<String, UsageSourceContribution>, |
| 160 | saved_total_tokens: u64, |
| 161 | ) -> ReceiptUsage { |
| 162 | ReceiptUsage { |
| 163 | tokens: tokens_from_sources(sources, saved_total_tokens), |
| 164 | cost: Some(receipt_cost(projection)), |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | pub fn saved_session_usage(metadata: &SessionMetadata) -> ReceiptUsage { |
| 169 | session_usage( |
| 170 | &cost_projection_from_snapshot(&metadata.cost), |
| 171 | &metadata.cost.accounted_usage_sources, |
| 172 | metadata.total_tokens, |
| 173 | ) |
| 174 | } |
| 175 | |
| 176 | #[must_use] |
| 177 | pub fn with_usage(mut receipt: Receipt, usage: ReceiptUsage) -> Receipt { |
| 178 | if receipt.turn.is_some() { |
| 179 | receipt.not_recorded.push(TURN_SCOPE_NOTE.to_string()); |
| 180 | return receipt; |
| 181 | } |
| 182 | if usage.tokens.is_none() { |
| 183 | receipt.not_recorded.push(NO_TOKENS_NOTE.to_string()); |
| 184 | } |
| 185 | receipt.usage = Some(usage); |
| 186 | receipt |
| 187 | } |
| 188 | |
| 189 | pub fn thread_tokens(turns: &[&crate::runtime_threads::TurnRecord]) -> Option<ReceiptTokens> { |
| 190 | let mut tokens = ReceiptTokens::default(); |
| 191 | let (mut input, mut output, mut turns_with_usage) = (0u64, 0u64, 0usize); |
| 192 | for usage in turns.iter().filter_map(|turn| turn.usage.as_ref()) { |
| 193 | input = input.saturating_add(u64::from(usage.input_tokens)); |
| 194 | output = output.saturating_add(u64::from(usage.output_tokens)); |
| 195 | add(&mut tokens.cache_read, usage.prompt_cache_hit_tokens); |
| 196 | add(&mut tokens.cache_write, usage.prompt_cache_write_tokens); |
| 197 | add(&mut tokens.reasoning, usage.reasoning_tokens); |
| 198 | turns_with_usage += 1; |
| 199 | } |
| 200 | (turns_with_usage > 0).then(|| { |
| 201 | tokens.input = Some(input); |
| 202 | tokens.output = Some(output); |
| 203 | tokens.total = input.saturating_add(output); |
| 204 | tokens |
| 205 | }) |
| 206 | } |
| 207 | |
| 208 | pub fn thread_cost_note() -> &'static str { |
| 209 | THREAD_COST_NOTE |
| 210 | } |
| 211 |