ag_contracts/usage.rs
1//! Provider-neutral token, cost, and context-fill usage that every agent
2//! backend reports for a turn or isolated prompt.
3//!
4//! Counts a backend does not report stay `None` rather than zero, so totals
5//! never present an unknown figure as a known one.
6
7use std::path::PathBuf;
8
9/// Cumulative usage totals an agent reported for the most recent
10/// conversation in `folder`, which a later run there continues.
11#[derive(Clone, Debug, Eq, Hash, PartialEq)]
12pub struct UsageCheckpoint {
13 /// Working directory whose most recent conversation the totals cover.
14 pub folder: PathBuf,
15 /// Opaque totals that only the reporting agent interprets.
16 pub totals: String,
17}
18
19impl UsageCheckpoint {
20 /// Returns the checkpoint of `totals` reported in `folder`.
21 pub fn new(folder: impl Into<PathBuf>, totals: impl Into<String>) -> Self {
22 Self {
23 folder: folder.into(),
24 totals: totals.into(),
25 }
26 }
27}
28
29/// Work an invocation's usage is recorded under, so utility work stays
30/// distinguishable from session turns.
31#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
32pub enum UsagePurpose {
33 /// A session turn, including its compaction and summary requests.
34 Turn,
35 /// Generation of a session title.
36 Title,
37 /// Generation of a commit message.
38 CommitAssist,
39 /// A focused review of session changes.
40 Review,
41 /// Conflict resolution while rebasing a session branch.
42 Rebase,
43 /// Any other utility prompt.
44 Other,
45}
46
47impl UsagePurpose {
48 /// Returns the stable persisted label of this purpose.
49 pub fn as_str(self) -> &'static str {
50 match self {
51 Self::Turn => "turn",
52 Self::Title => "title",
53 Self::CommitAssist => "commit_assist",
54 Self::Review => "review",
55 Self::Rebase => "rebase",
56 Self::Other => "other",
57 }
58 }
59}
60
61/// Where the prices of a [`PricedCost`] came from.
62#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
63pub enum CostBasis {
64 /// Provider list prices from the built-in model catalog.
65 ListPrice,
66 /// Prices the host supplied, such as a negotiated rate.
67 HostPrice,
68 /// The agent's own estimate, such as Claude Code's per-model `costUSD`.
69 AgentReported,
70 /// A sum of amounts priced from more than one basis.
71 Mixed,
72}
73
74impl CostBasis {
75 /// Returns the stable persisted label of this basis.
76 pub fn as_str(self) -> &'static str {
77 match self {
78 Self::ListPrice => "list",
79 Self::HostPrice => "host",
80 Self::AgentReported => "agent_reported",
81 Self::Mixed => "mixed",
82 }
83 }
84
85 /// Returns the basis of a sum of amounts priced on `self` and `other`:
86 /// their shared basis, or [`Self::Mixed`] when they differ.
87 #[must_use]
88 pub fn combine(self, other: Self) -> Self {
89 if self == other { self } else { Self::Mixed }
90 }
91}
92
93/// Subscription login that bills usage a flat fee, whose priced figure is
94/// therefore only an API equivalent.
95#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
96pub enum PlanLogin {
97 /// A `ChatGPT` plan, through the harness or Codex.
98 ChatGpt,
99 /// A Claude subscription through Claude Code.
100 Claude,
101}
102
103impl PlanLogin {
104 /// Returns the stable persisted label of this login.
105 pub fn as_str(self) -> &'static str {
106 match self {
107 Self::ChatGpt => "chatgpt",
108 Self::Claude => "claude",
109 }
110 }
111}
112
113/// One priced amount in integer micro-USD, one millionth of a US dollar.
114#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
115pub struct PricedCost {
116 /// Where the prices came from.
117 pub basis: CostBasis,
118 /// Amount in micro-USD.
119 pub micro_usd: u64,
120 /// Whether the amount is an upper bound because cache reads were priced
121 /// at the input price, their price being undeclared.
122 pub upper_bound: bool,
123}
124
125impl PricedCost {
126 /// Returns an exact amount of `micro_usd` priced on `basis`.
127 pub fn new(basis: CostBasis, micro_usd: u64) -> Self {
128 Self {
129 basis,
130 micro_usd,
131 upper_bound: false,
132 }
133 }
134
135 /// Adds `other`, saturating; the bases combine as
136 /// [`CostBasis::combine`] describes, and the sum is an upper bound when
137 /// either side is.
138 #[must_use]
139 pub fn saturating_add(self, other: Self) -> Self {
140 Self {
141 basis: self.basis.combine(other.basis),
142 micro_usd: self.micro_usd.saturating_add(other.micro_usd),
143 upper_bound: self.upper_bound || other.upper_bound,
144 }
145 }
146}
147
148/// What usage billed to a subscription plan would cost at the provider's
149/// API list prices. It is no charge: the plan bills a flat fee.
150#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
151pub struct ApiEquivalentCost {
152 /// Amount at API list prices.
153 pub cost: PricedCost,
154 /// Login whose plan billed the usage, or `None` for a sum over several
155 /// logins.
156 pub login: Option<PlanLogin>,
157}
158
159/// Estimated cost of some usage: the charge of metered usage and the API
160/// equivalent of plan-billed usage, kept apart so an API equivalent is
161/// never summed into a charge. An estimate always holds at least one of
162/// them; usage with no price has no estimate. Provider bills stay
163/// authoritative.
164#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
165pub struct CostEstimate(CostParts);
166
167/// The amounts a [`CostEstimate`] holds.
168#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
169enum CostParts {
170 /// Only metered usage.
171 Charged(PricedCost),
172 /// Only plan-billed usage.
173 ApiEquivalent(ApiEquivalentCost),
174 /// Both, kept apart.
175 Both(PricedCost, ApiEquivalentCost),
176}
177
178impl CostEstimate {
179 /// Returns an exact charge of `micro_usd` priced on `basis`.
180 pub fn new(basis: CostBasis, micro_usd: u64) -> Self {
181 Self::charged(PricedCost::new(basis, micro_usd))
182 }
183
184 /// Returns the estimate of metered usage charged `cost`.
185 pub fn charged(cost: PricedCost) -> Self {
186 Self(CostParts::Charged(cost))
187 }
188
189 /// Returns the estimate of plan-billed usage whose API equivalent is
190 /// `equivalent`.
191 pub fn plan_billed(equivalent: ApiEquivalentCost) -> Self {
192 Self(CostParts::ApiEquivalent(equivalent))
193 }
194
195 /// Returns the estimated charge of the metered usage, or `None` when
196 /// none was metered.
197 pub fn charge(self) -> Option<PricedCost> {
198 match self.0 {
199 CostParts::Charged(charged) | CostParts::Both(charged, _) => Some(charged),
200 CostParts::ApiEquivalent(_) => None,
201 }
202 }
203
204 /// Returns the API equivalent of the plan-billed usage, or `None` when
205 /// none was plan-billed.
206 pub fn api_equivalent(self) -> Option<ApiEquivalentCost> {
207 match self.0 {
208 CostParts::ApiEquivalent(equivalent) | CostParts::Both(_, equivalent) => {
209 Some(equivalent)
210 }
211 CostParts::Charged(_) => None,
212 }
213 }
214
215 /// Returns this estimate as plan-billed usage of `login`: every amount
216 /// becomes its API equivalent.
217 #[must_use]
218 pub fn billed_to(self, login: PlanLogin) -> Self {
219 let cost = match self.0 {
220 CostParts::Charged(cost) | CostParts::ApiEquivalent(ApiEquivalentCost { cost, .. }) => {
221 cost
222 }
223 CostParts::Both(charged, equivalent) => charged.saturating_add(equivalent.cost),
224 };
225
226 Self::plan_billed(ApiEquivalentCost {
227 cost,
228 login: Some(login),
229 })
230 }
231
232 /// Adds `other`, saturating, part by part: charges to charges and API
233 /// equivalents to API equivalents. API equivalents of different logins
234 /// sum to an equivalent of no single login.
235 #[must_use]
236 pub fn saturating_add(self, other: Self) -> Self {
237 let charged = match (self.charge(), other.charge()) {
238 (Some(charged), Some(next)) => Some(charged.saturating_add(next)),
239 (charged, next) => charged.or(next),
240 };
241 let api_equivalent = match (self.api_equivalent(), other.api_equivalent()) {
242 (Some(equivalent), Some(next)) => Some(ApiEquivalentCost {
243 cost: equivalent.cost.saturating_add(next.cost),
244 login: equivalent.login.filter(|login| next.login == Some(*login)),
245 }),
246 (equivalent, next) => equivalent.or(next),
247 };
248
249 Self::from_parts(charged, api_equivalent).unwrap_or(self)
250 }
251
252 /// Returns the estimate holding `charged` and `api_equivalent`, or
253 /// `None` when it would hold neither.
254 fn from_parts(
255 charged: Option<PricedCost>,
256 api_equivalent: Option<ApiEquivalentCost>,
257 ) -> Option<Self> {
258 match (charged, api_equivalent) {
259 (Some(charged), Some(equivalent)) => Some(Self(CostParts::Both(charged, equivalent))),
260 (Some(charged), None) => Some(Self::charged(charged)),
261 (None, Some(equivalent)) => Some(Self::plan_billed(equivalent)),
262 (None, None) => None,
263 }
264 }
265}
266
267/// How full a model's context window was, measured by the reported input
268/// tokens of its requests, cache included.
269#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
270pub struct ContextFill {
271 /// Input tokens of the latest request: what the model last saw.
272 pub last_input_tokens: u64,
273 /// Largest request input observed.
274 pub peak_input_tokens: u64,
275 /// Context window of the model, or `None` when unknown.
276 pub window_tokens: Option<u64>,
277}
278
279impl ContextFill {
280 /// Returns the fill of one request with `input_tokens` of input.
281 pub fn of_request(input_tokens: u64, window_tokens: Option<u64>) -> Self {
282 Self {
283 last_input_tokens: input_tokens,
284 peak_input_tokens: input_tokens,
285 window_tokens,
286 }
287 }
288
289 /// Folds the later fill `next` into this one: the latest request comes
290 /// from `next`, the peak is the larger of both.
291 #[must_use]
292 pub fn then(self, next: Self) -> Self {
293 Self {
294 last_input_tokens: next.last_input_tokens,
295 peak_input_tokens: self.peak_input_tokens.max(next.peak_input_tokens),
296 window_tokens: next.window_tokens.or(self.window_tokens),
297 }
298 }
299}
300
301/// Tokens and estimated charge of one model within one turn or isolated
302/// prompt.
303///
304/// The counts overlap: `cache_read_tokens` and `cache_write_tokens` are part
305/// of `input_tokens`, and `reasoning_tokens` is part of `output_tokens`.
306/// A request whose backend reported no input or output count is counted in
307/// `unreported_requests`, which makes the token totals lower bounds.
308#[derive(Clone, Debug, Eq, Hash, PartialEq)]
309pub struct ModelUsage {
310 /// Input tokens served from the provider's prompt cache, or `None` when
311 /// the backend does not report them.
312 pub cache_read_tokens: Option<u64>,
313 /// Input tokens written to the provider's prompt cache, or `None` when
314 /// the backend does not report them.
315 pub cache_write_tokens: Option<u64>,
316 /// Context fill of this model's requests, or `None` when no request
317 /// reported its input.
318 pub context: Option<ContextFill>,
319 /// Estimated charge, or `None` when no price is known for every request.
320 pub cost: Option<CostEstimate>,
321 /// All input tokens, cache included.
322 pub input_tokens: u64,
323 /// Model identifier, as sessions record it.
324 pub model: String,
325 /// Output tokens, reasoning included.
326 pub output_tokens: u64,
327 /// Reasoning tokens, or `None` when the backend does not report them.
328 pub reasoning_tokens: Option<u64>,
329 /// Provider requests counted, including unreported ones.
330 pub requests: u32,
331 /// Requests whose backend reported no input or output count.
332 pub unreported_requests: u32,
333}
334
335impl ModelUsage {
336 /// Returns usage of `model` with no requests and every detail unknown.
337 pub fn new(model: impl Into<String>) -> Self {
338 Self {
339 cache_read_tokens: None,
340 cache_write_tokens: None,
341 context: None,
342 cost: None,
343 input_tokens: 0,
344 model: model.into(),
345 output_tokens: 0,
346 reasoning_tokens: None,
347 requests: 0,
348 unreported_requests: 0,
349 }
350 }
351
352 /// Returns usage of `model` for requests whose backend reported nothing.
353 pub fn unreported(model: impl Into<String>, requests: u32) -> Self {
354 Self {
355 requests,
356 unreported_requests: requests,
357 ..Self::new(model)
358 }
359 }
360
361 /// Adds the later usage `next` of the same model, saturating. A detail
362 /// stays known only when both sides know it.
363 pub fn add(&mut self, next: &Self) {
364 let both = |total: Option<u64>, tokens: Option<u64>| {
365 total
366 .zip(tokens)
367 .map(|(total, tokens)| total.saturating_add(tokens))
368 };
369 self.cache_read_tokens = both(self.cache_read_tokens, next.cache_read_tokens);
370 self.cache_write_tokens = both(self.cache_write_tokens, next.cache_write_tokens);
371 self.context = match (self.context, next.context) {
372 (Some(context), Some(next_context)) => Some(context.then(next_context)),
373 (context, next_context) => next_context.or(context),
374 };
375 self.cost = self
376 .cost
377 .zip(next.cost)
378 .map(|(cost, next_cost)| cost.saturating_add(next_cost));
379 self.input_tokens = self.input_tokens.saturating_add(next.input_tokens);
380 self.output_tokens = self.output_tokens.saturating_add(next.output_tokens);
381 self.reasoning_tokens = both(self.reasoning_tokens, next.reasoning_tokens);
382 self.requests = self.requests.saturating_add(next.requests);
383 self.unreported_requests = self
384 .unreported_requests
385 .saturating_add(next.unreported_requests);
386 }
387
388 /// Returns whether this usage records nothing worth persisting: no
389 /// tokens and no unreported request.
390 pub fn is_empty(&self) -> bool {
391 self.input_tokens == 0 && self.output_tokens == 0 && self.unreported_requests == 0
392 }
393}
394
395/// Usage of every model one turn or isolated prompt used.
396///
397/// Entries are ordered by their latest request, so the last entry with a
398/// context fill describes what the most recent request saw.
399#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
400pub struct TurnUsage {
401 /// Cumulative totals an agent reported for the conversation it left,
402 /// which the host stores and passes back through
403 /// [`crate::TurnContinuation::with_usage_checkpoint`] so the next turn
404 /// continuing that conversation can derive its own share; `None` for
405 /// agents and runs that report per-turn usage.
406 pub checkpoint: Option<UsageCheckpoint>,
407 /// One entry per model.
408 pub models: Vec<ModelUsage>,
409}
410
411impl TurnUsage {
412 /// Returns the usage of one model.
413 pub fn single(usage: ModelUsage) -> Self {
414 Self {
415 checkpoint: None,
416 models: vec![usage],
417 }
418 }
419
420 /// Folds the later usage `next` of one model into its entry, which
421 /// moves last, or appends it for a model not seen yet.
422 pub fn record(&mut self, next: &ModelUsage) {
423 let entry = match self
424 .models
425 .iter()
426 .position(|usage| usage.model == next.model)
427 {
428 Some(index) => {
429 let mut entry = self.models.remove(index);
430 entry.add(next);
431
432 entry
433 }
434 None => next.clone(),
435 };
436 self.models.push(entry);
437 }
438
439 /// Folds every entry of the later usage `next` into this one; a later
440 /// checkpoint replaces this one.
441 pub fn merge(&mut self, next: &Self) {
442 for usage in &next.models {
443 self.record(usage);
444 }
445 if next.checkpoint.is_some() {
446 self.checkpoint.clone_from(&next.checkpoint);
447 }
448 }
449
450 /// Returns the usage of every model summed into one entry named after
451 /// the first, as [`ModelUsage::add`] sums them, or `None` without any
452 /// model.
453 pub fn total(&self) -> Option<ModelUsage> {
454 self.models.iter().cloned().reduce(|mut total, next| {
455 total.add(&next);
456
457 total
458 })
459 }
460
461 /// Returns the context fill of the most recent request that reported
462 /// its input.
463 pub fn context(&self) -> Option<ContextFill> {
464 self.models.iter().rev().find_map(|usage| usage.context)
465 }
466
467 /// Returns the input tokens of every model, cache included.
468 pub fn input_tokens(&self) -> u64 {
469 self.models
470 .iter()
471 .fold(0, |total, usage| total.saturating_add(usage.input_tokens))
472 }
473
474 /// Returns the output tokens of every model, reasoning included.
475 pub fn output_tokens(&self) -> u64 {
476 self.models
477 .iter()
478 .fold(0, |total, usage| total.saturating_add(usage.output_tokens))
479 }
480}
481
482#[cfg(test)]
483#[path = "usage_test.rs"]
484mod tests;