1#[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
20pub fn estimate_tool_definition_tokens(tools: &[ToolDefinition]) -> u64 {
29 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 approx_eq(estimate.raw_usd, 1_000.0 * 0.01 + 100.0 * 0.02);
166 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 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 assert_eq!(budget.record(0.5), BudgetStatus::Ok);
245 assert_eq!(budget.record(0.3), BudgetStatus::Warning { spent: 0.8, max: 1.0 });
247 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 assert_eq!(BudgetStatus::classify(999.0, None, 0.75), BudgetStatus::Ok);
264 assert_eq!(BudgetStatus::classify(0.5, Some(1.0), 0.75), BudgetStatus::Ok);
266 assert_eq!(BudgetStatus::classify(0.8, Some(1.0), 0.75), BudgetStatus::Warning { spent: 0.8, max: 1.0 });
268 assert!(!BudgetStatus::classify(1.0, Some(1.0), 0.75).is_exceeded());
270 assert!(BudgetStatus::classify(1.01, Some(1.0), 0.75).is_exceeded());
272 assert_eq!(BudgetStatus::classify(0.6, Some(1.0), 0.5), BudgetStatus::Warning { spent: 0.6, max: 1.0 });
274 }
275}
276
277pub const DEFAULT_BUDGET_WARNING_RATIO: f64 = 0.75;
282
283#[derive(Debug, Clone, Copy, PartialEq)]
290pub enum BudgetStatus {
291 Ok,
293 Warning {
295 spent: f64,
297 max: f64,
299 },
300 Exceeded {
302 spent: f64,
304 max: f64,
306 },
307}
308
309impl BudgetStatus {
310 #[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 #[must_use]
334 pub fn is_exceeded(&self) -> bool {
335 matches!(self, BudgetStatus::Exceeded { .. })
336 }
337}
338
339#[derive(Debug, Clone)]
348pub struct SessionBudget {
349 max_usd: Option<f64>,
350 warning_threshold: f64,
351 spent_usd: f64,
352}
353
354impl SessionBudget {
355 #[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 #[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 pub fn record(&mut self, raw_usd: f64) -> BudgetStatus {
371 self.spent_usd += raw_usd.max(0.0);
372 self.status()
373 }
374
375 #[must_use]
377 pub fn status(&self) -> BudgetStatus {
378 BudgetStatus::classify(self.spent_usd, self.max_usd, self.warning_threshold)
379 }
380
381 #[must_use]
383 pub fn spent_usd(&self) -> f64 {
384 self.spent_usd
385 }
386
387 #[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}