Skip to main content

vtcode_core/llm/
usage_cost.rs

1//! Provider-normalized usage accumulation and cache-aware session cost estimation.
2//!
3//! Different providers report `prompt_tokens` with different cache semantics:
4//! Anthropic and Minimax report `prompt_tokens` *exclusive* of cache-read and
5//! cache-creation tokens, while every other supported provider (OpenAI, Gemini,
6//! etc.) reports `prompt_tokens` as a total that already includes cached
7//! tokens. This module normalizes per-turn provider usage into the canonical
8//! harness `Usage` shape, where `input_tokens` always means the total prompt
9//! tokens (uncached + cached + cache-creation), and provides a shared cost
10//! estimator used by both the interactive and headless runloops.
11
12#[cfg(test)]
13use vtcode_config::models::ModelPricing;
14
15use crate::llm::provider::ToolDefinition;
16#[cfg(test)]
17use crate::llm::provider::Usage as ProviderUsage;
18use vtcode_commons::tokens::heuristic_tokens_from_byte_len_u64;
19
20/// Estimate the token overhead of sending `tools` in the request payload.
21///
22/// Serializes each tool definition to JSON (the wire format sent to
23/// providers), sums the byte length, and converts to an approximate token
24/// count using the same "~4 bytes per token" heuristic used elsewhere in the
25/// codebase (see `system.rs` and `progress.rs`). A tool whose definition
26/// fails to serialize contributes zero bytes rather than failing the whole
27/// estimate, since this is an advisory figure, not a billing-accurate count.
28pub fn estimate_tool_definition_tokens(tools: &[ToolDefinition]) -> u64 {
29    // Reuse a single buffer across all tools instead of allocating a fresh
30    // `String` per definition. The buffer grows once to the largest serialized
31    // tool and stays there for the rest of the call.
32    let mut buf = Vec::new();
33    let total_bytes: u64 = tools
34        .iter()
35        .map(|tool| {
36            buf.clear();
37            serde_json::to_writer(&mut buf, tool).map(|_| buf.len() as u64).unwrap_or(0)
38        })
39        .sum();
40    heuristic_tokens_from_byte_len_u64(total_bytes)
41}
42
43pub use vtcode_llm::usage_cost::{
44    SessionCostAccumulator, SessionCostEstimate, estimate_decisions_cost, estimate_session_costs,
45    estimate_session_costs_with_pricing, normalized_turn_usage, provider_reports_exclusive_input,
46    require_budget_pricing,
47};
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use serde_json::json;
53
54    fn approx_eq(a: f64, b: f64) {
55        assert!((a - b).abs() < 1e-12, "expected {a} to approx-equal {b}");
56    }
57
58    #[test]
59    fn estimate_tool_definition_tokens_is_zero_for_empty_slice() {
60        assert_eq!(estimate_tool_definition_tokens(&[]), 0);
61    }
62
63    #[test]
64    fn estimate_tool_definition_tokens_matches_serialized_byte_length() {
65        let tool = ToolDefinition::function(
66            "read_file".to_string(),
67            "Read the contents of a file from the workspace.".to_string(),
68            json!({
69                "type": "object",
70                "properties": {
71                    "path": { "type": "string" }
72                },
73                "required": ["path"],
74            }),
75        );
76
77        let expected_bytes = serde_json::to_string(&tool).expect("tool serializes").len() as u64;
78        let expected_tokens = expected_bytes.div_ceil(4);
79
80        assert_eq!(estimate_tool_definition_tokens(&[tool]), expected_tokens);
81    }
82
83    #[test]
84    fn normalized_turn_usage_adds_cache_tokens_for_anthropic() {
85        let usage = ProviderUsage {
86            prompt_tokens: 100,
87            completion_tokens: 20,
88            total_tokens: 120,
89            cached_prompt_tokens: None,
90            cache_creation_tokens: Some(50),
91            cache_read_tokens: Some(400),
92            iterations: None,
93        };
94
95        let normalized = normalized_turn_usage("anthropic", &usage);
96        assert_eq!(normalized.input_tokens, 550);
97        assert_eq!(normalized.cached_input_tokens, 400);
98        assert_eq!(normalized.cache_creation_tokens, 50);
99        assert_eq!(normalized.output_tokens, 20);
100    }
101
102    #[test]
103    fn normalized_turn_usage_treats_minimax_like_anthropic() {
104        let usage = ProviderUsage {
105            prompt_tokens: 100,
106            completion_tokens: 20,
107            total_tokens: 120,
108            cached_prompt_tokens: None,
109            cache_creation_tokens: Some(50),
110            cache_read_tokens: Some(400),
111            iterations: None,
112        };
113
114        let normalized = normalized_turn_usage("minimax", &usage);
115        assert_eq!(normalized.input_tokens, 550);
116        assert_eq!(normalized.cached_input_tokens, 400);
117        assert_eq!(normalized.cache_creation_tokens, 50);
118        assert_eq!(normalized.output_tokens, 20);
119    }
120
121    #[test]
122    fn normalized_turn_usage_keeps_openai_prompt_tokens_as_total() {
123        let usage = ProviderUsage {
124            prompt_tokens: 500,
125            completion_tokens: 30,
126            total_tokens: 530,
127            cached_prompt_tokens: Some(400),
128            cache_creation_tokens: None,
129            cache_read_tokens: None,
130            iterations: None,
131        };
132
133        let normalized = normalized_turn_usage("openai", &usage);
134        assert_eq!(normalized.input_tokens, 500);
135        assert_eq!(normalized.cached_input_tokens, 400);
136        assert_eq!(normalized.cache_creation_tokens, 0);
137    }
138
139    #[test]
140    fn provider_reports_exclusive_input_is_case_insensitive() {
141        assert!(provider_reports_exclusive_input("Anthropic"));
142        assert!(provider_reports_exclusive_input("ANTHROPIC"));
143        assert!(!provider_reports_exclusive_input("OpenAI"));
144        assert!(!provider_reports_exclusive_input("openai"));
145    }
146
147    #[test]
148    fn estimate_session_costs_with_pricing_discounts_cache_reads() {
149        let pricing = ModelPricing {
150            input: Some(0.01),
151            output: Some(0.02),
152            cache_read: Some(0.001),
153            cache_write: Some(0.0125),
154        };
155        let usage = vtcode_exec_events::Usage {
156            input_tokens: 1_000,
157            cached_input_tokens: 800,
158            cache_creation_tokens: 0,
159            output_tokens: 100,
160        };
161
162        let estimate = estimate_session_costs_with_pricing(pricing, &usage).expect("estimate");
163
164        // raw: all 1000 input tokens at full rate + output.
165        approx_eq(estimate.raw_usd, 1_000.0 * 0.01 + 100.0 * 0.02);
166        // effective: 200 uncached @ input rate + 800 cached @ read rate + output.
167        approx_eq(estimate.effective_usd, 200.0 * 0.01 + 800.0 * 0.001 + 100.0 * 0.02);
168        assert!(estimate.effective_usd < estimate.raw_usd);
169    }
170
171    #[test]
172    fn estimate_session_costs_with_pricing_matches_raw_when_no_cache_activity() {
173        let pricing = ModelPricing {
174            input: Some(0.01),
175            output: Some(0.02),
176            cache_read: Some(0.001),
177            cache_write: Some(0.0125),
178        };
179        let usage = vtcode_exec_events::Usage {
180            input_tokens: 1_000,
181            cached_input_tokens: 0,
182            cache_creation_tokens: 0,
183            output_tokens: 100,
184        };
185
186        let estimate = estimate_session_costs_with_pricing(pricing, &usage).expect("estimate");
187        approx_eq(estimate.raw_usd, estimate.effective_usd);
188    }
189
190    #[test]
191    fn estimate_session_costs_with_pricing_uses_heuristic_fallback_rates() {
192        let pricing = ModelPricing {
193            input: Some(0.01),
194            output: Some(0.02),
195            cache_read: None,
196            cache_write: None,
197        };
198        let usage = vtcode_exec_events::Usage {
199            input_tokens: 1_000,
200            cached_input_tokens: 50,
201            cache_creation_tokens: 500,
202            output_tokens: 50,
203        };
204
205        let estimate = estimate_session_costs_with_pricing(pricing, &usage).expect("estimate");
206
207        let read_rate = 0.01 * 0.10;
208        let write_rate = 0.01 * 1.25;
209        let uncached = 1_000.0 - 50.0 - 500.0;
210        let expected_effective = uncached * 0.01 + 50.0 * read_rate + 500.0 * write_rate + 50.0 * 0.02;
211        approx_eq(estimate.effective_usd, expected_effective);
212        approx_eq(estimate.raw_usd, 1_000.0 * 0.01 + 50.0 * 0.02);
213        // Cache-creation tokens dominate here (500 vs. 50 cache-read tokens),
214        // so the write-rate premium outweighs the read-rate discount and
215        // pushes effective above raw.
216        assert!(estimate.effective_usd > estimate.raw_usd);
217    }
218
219    #[test]
220    fn estimate_session_costs_with_pricing_returns_none_without_full_pricing() {
221        let missing_input = ModelPricing {
222            input: None,
223            output: Some(0.02),
224            cache_read: None,
225            cache_write: None,
226        };
227        let missing_output = ModelPricing {
228            input: Some(0.01),
229            output: None,
230            cache_read: None,
231            cache_write: None,
232        };
233        let usage = vtcode_exec_events::Usage::default();
234
235        assert!(estimate_session_costs_with_pricing(missing_input, &usage).is_none());
236        assert!(estimate_session_costs_with_pricing(missing_output, &usage).is_none());
237    }
238
239    #[test]
240    fn session_budget_tracks_spend_and_thresholds() {
241        let mut budget = SessionBudget::new(Some(1.0));
242        assert_eq!(budget.status(), BudgetStatus::Ok);
243        // 0.5 -> Ok
244        assert_eq!(budget.record(0.5), BudgetStatus::Ok);
245        // 0.3 -> 0.8 >= 0.75 cap -> Warning
246        assert_eq!(budget.record(0.3), BudgetStatus::Warning { spent: 0.8, max: 1.0 });
247        // 0.3 -> 1.1 >= cap -> Exceeded
248        assert_eq!(budget.record(0.3), BudgetStatus::Exceeded { spent: 1.1, max: 1.0 });
249        assert!((budget.spent_usd() - 1.1).abs() < 1e-9);
250        assert!((budget.remaining_usd().unwrap() - 0.0).abs() < 1e-9);
251    }
252
253    #[test]
254    fn session_budget_unlimited_is_always_ok() {
255        let mut budget = SessionBudget::new(None);
256        assert_eq!(budget.record(1000.0), BudgetStatus::Ok);
257        assert_eq!(budget.remaining_usd(), None);
258    }
259
260    #[test]
261    fn budget_status_classify_matches_harness_semantics() {
262        // Unlimited.
263        assert_eq!(BudgetStatus::classify(999.0, None, 0.75), BudgetStatus::Ok);
264        // Under warning.
265        assert_eq!(BudgetStatus::classify(0.5, Some(1.0), 0.75), BudgetStatus::Ok);
266        // At/above warning, within cap.
267        assert_eq!(BudgetStatus::classify(0.8, Some(1.0), 0.75), BudgetStatus::Warning { spent: 0.8, max: 1.0 });
268        // Exactly at cap is NOT exceeded (strict `>`), matching runner semantics.
269        assert!(!BudgetStatus::classify(1.0, Some(1.0), 0.75).is_exceeded());
270        // Over cap.
271        assert!(BudgetStatus::classify(1.01, Some(1.0), 0.75).is_exceeded());
272        // Configurable threshold.
273        assert_eq!(BudgetStatus::classify(0.6, Some(1.0), 0.5), BudgetStatus::Warning { spent: 0.6, max: 1.0 });
274    }
275}
276
277/// Default fraction of the budget at which the harness warns before hard
278/// exhaustion. Mirrors `agent.harness.budget_warning_threshold`'s default so a
279/// [`SessionBudget`] built without an explicit threshold behaves like the
280/// harness default.
281pub const DEFAULT_BUDGET_WARNING_RATIO: f64 = 0.75;
282
283/// Outcome of classifying cumulative spend against a budget cap.
284///
285/// This is the single source of truth for the harness budget decision. Both the
286/// `vtcode-core` runner ([`crate::core::agent::runner`]) and the binary crate's
287/// turn loop classify spend through [`BudgetStatus::classify`] rather than
288/// re-deriving the `> max` / `>= threshold * max` comparisons inline.
289#[derive(Debug, Clone, Copy, PartialEq)]
290pub enum BudgetStatus {
291    /// Under the warning threshold.
292    Ok,
293    /// At or above the warning ratio but still within the cap.
294    Warning {
295        /// Cumulative spend so far (USD).
296        spent: f64,
297        /// Configured cap (USD).
298        max: f64,
299    },
300    /// Over the cap — the run should stop or escalate.
301    Exceeded {
302        /// Cumulative spend so far (USD).
303        spent: f64,
304        /// Configured cap (USD).
305        max: f64,
306    },
307}
308
309impl BudgetStatus {
310    /// Classify `spent_usd` against an optional `max_usd` cap and a
311    /// `warning_threshold` fraction (`0.0..=1.0`).
312    ///
313    /// - `max_usd == None` → always [`BudgetStatus::Ok`] (unlimited).
314    /// - `spent_usd > max` → [`BudgetStatus::Exceeded`] (strict, matching the
315    ///   harness "stop after reaching the budget limit" semantics).
316    /// - `spent_usd >= warning_threshold * max` → [`BudgetStatus::Warning`].
317    /// - otherwise → [`BudgetStatus::Ok`].
318    #[must_use]
319    pub fn classify(spent_usd: f64, max_usd: Option<f64>, warning_threshold: f64) -> Self {
320        let Some(max) = max_usd else {
321            return BudgetStatus::Ok;
322        };
323        if spent_usd > max {
324            BudgetStatus::Exceeded { spent: spent_usd, max }
325        } else if spent_usd >= warning_threshold * max {
326            BudgetStatus::Warning { spent: spent_usd, max }
327        } else {
328            BudgetStatus::Ok
329        }
330    }
331
332    /// Whether the cap has been exceeded (the run should stop/escalate).
333    #[must_use]
334    pub fn is_exceeded(&self) -> bool {
335        matches!(self, BudgetStatus::Exceeded { .. })
336    }
337}
338
339/// Durable per-session cost budget for long-running (full-auto) sessions.
340///
341/// Long-horizon tasks accrue cost continuously; the harness should pause or
342/// escalate at thresholds rather than burning unbounded spend. `SessionBudget`
343/// accumulates the conservative `raw_usd` figure (see [`SessionCostEstimate`])
344/// and reports a [`BudgetStatus`] on each recorded turn. It delegates the
345/// decision to [`BudgetStatus::classify`] so callers that instead recompute the
346/// running total each turn (like the harness) share identical semantics.
347#[derive(Debug, Clone)]
348pub struct SessionBudget {
349    max_usd: Option<f64>,
350    warning_threshold: f64,
351    spent_usd: f64,
352}
353
354impl SessionBudget {
355    /// Create a budget with the default warning ratio. `None` max means
356    /// unlimited (status is always `Ok`).
357    #[must_use]
358    pub fn new(max_usd: Option<f64>) -> Self {
359        Self::with_warning_threshold(max_usd, DEFAULT_BUDGET_WARNING_RATIO)
360    }
361
362    /// Create a budget with an explicit warning threshold (e.g. from
363    /// `agent.harness.budget_warning_threshold`).
364    #[must_use]
365    pub fn with_warning_threshold(max_usd: Option<f64>, warning_threshold: f64) -> Self {
366        Self { max_usd, warning_threshold, spent_usd: 0.0 }
367    }
368
369    /// Record a turn's spend and return the resulting status.
370    pub fn record(&mut self, raw_usd: f64) -> BudgetStatus {
371        self.spent_usd += raw_usd.max(0.0);
372        self.status()
373    }
374
375    /// Current status given accumulated spend.
376    #[must_use]
377    pub fn status(&self) -> BudgetStatus {
378        BudgetStatus::classify(self.spent_usd, self.max_usd, self.warning_threshold)
379    }
380
381    /// Cumulative spend so far (USD).
382    #[must_use]
383    pub fn spent_usd(&self) -> f64 {
384        self.spent_usd
385    }
386
387    /// Remaining budget, or `None` when unlimited.
388    #[must_use]
389    pub fn remaining_usd(&self) -> Option<f64> {
390        self.max_usd.map(|m| (m - self.spent_usd).max(0.0))
391    }
392}