Skip to main content

merry_core/
usage.rs

1//! Provider-neutral model and session usage snapshots.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// Token usage reported by a model provider for one response.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
8#[serde(deny_unknown_fields)]
9pub struct ModelUsage {
10    pub input_tokens: u64,
11    pub cached_input_tokens: Option<u64>,
12    pub output_tokens: u64,
13    pub reasoning_output_tokens: Option<u64>,
14    pub total_tokens: u64,
15}
16
17impl ModelUsage {
18    /// Creates usage with no optional provider sub-counts.
19    #[must_use]
20    pub fn new(input_tokens: u64, output_tokens: u64) -> Self {
21        let total_tokens = input_tokens
22            .checked_add(output_tokens)
23            .expect("model usage total token count overflowed");
24        Self::with_details(input_tokens, None, output_tokens, None, total_tokens)
25    }
26
27    /// Creates usage from provider-reported counts.
28    #[must_use]
29    pub const fn with_details(
30        input_tokens: u64,
31        cached_input_tokens: Option<u64>,
32        output_tokens: u64,
33        reasoning_output_tokens: Option<u64>,
34        total_tokens: u64,
35    ) -> Self {
36        Self {
37            input_tokens,
38            cached_input_tokens,
39            output_tokens,
40            reasoning_output_tokens,
41            total_tokens,
42        }
43    }
44
45    /// Input token count.
46    #[must_use]
47    pub const fn input_tokens(&self) -> u64 {
48        self.input_tokens
49    }
50
51    /// Cached input token count if the provider reported it.
52    #[must_use]
53    pub const fn cached_input_tokens(&self) -> Option<u64> {
54        self.cached_input_tokens
55    }
56
57    /// Output token count.
58    #[must_use]
59    pub const fn output_tokens(&self) -> u64 {
60        self.output_tokens
61    }
62
63    /// Reasoning output token count if the provider reported it.
64    #[must_use]
65    pub const fn reasoning_output_tokens(&self) -> Option<u64> {
66        self.reasoning_output_tokens
67    }
68
69    /// Provider-reported or provider-derived total token count.
70    #[must_use]
71    pub const fn total_tokens(&self) -> u64 {
72        self.total_tokens
73    }
74
75    /// Returns the checked sum of two usage values.
76    #[must_use]
77    pub fn checked_add(self, other: Self) -> Option<Self> {
78        Some(Self {
79            input_tokens: self.input_tokens.checked_add(other.input_tokens)?,
80            cached_input_tokens: checked_add_optional(
81                self.cached_input_tokens,
82                other.cached_input_tokens,
83            )?,
84            output_tokens: self.output_tokens.checked_add(other.output_tokens)?,
85            reasoning_output_tokens: checked_add_optional(
86                self.reasoning_output_tokens,
87                other.reasoning_output_tokens,
88            )?,
89            total_tokens: self.total_tokens.checked_add(other.total_tokens)?,
90        })
91    }
92}
93
94fn checked_add_optional(left: Option<u64>, right: Option<u64>) -> Option<Option<u64>> {
95    match (left, right) {
96        (Some(left), Some(right)) => Some(Some(left.checked_add(right)?)),
97        (None, _) | (_, None) => Some(None),
98    }
99}
100
101/// Runtime-owned usage snapshot for one session.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct SessionUsage {
105    pub total: ModelUsage,
106    pub last: ModelUsage,
107    pub context: Option<UsageContextWindow>,
108    pub compaction: Option<CompactionUsageWindow>,
109    /// Cumulative token usage rolled up from managed subagents within this session.
110    ///
111    /// Included in [`SessionUsage::total`]; absent when no subagent usage has been
112    /// recorded yet.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub subagent_total: Option<ModelUsage>,
115}
116
117/// Context window snapshot used by the most recent model request that produced `last`.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
119#[serde(deny_unknown_fields)]
120pub struct UsageContextWindow {
121    pub resolved_model_window_tokens: u64,
122    pub effective_window_tokens: u64,
123    pub source: ContextWindowSource,
124}
125
126/// Compaction budget snapshot used by the most recent model request that produced `last`.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
128#[serde(deny_unknown_fields)]
129pub struct CompactionUsageWindow {
130    pub auto_compaction_enabled: bool,
131    /// Estimated dynamic-body tokens in the request that produced this usage.
132    pub dynamic_body_estimated_tokens: u64,
133    pub body_budget_tokens: u64,
134    /// Dynamic-body token count that starts automatic compaction.
135    pub compact_at_tokens: u64,
136}
137
138/// Source used to resolve a model context window.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
140#[serde(rename_all = "snake_case")]
141pub enum ContextWindowSource {
142    /// Explicit runtime or caller override.
143    ExplicitConfig,
144    /// Provider-neutral model capabilities.
145    ProviderCapabilities,
146    /// Bundled model catalog metadata.
147    BundledCatalog,
148    /// Conservative fallback when no metadata is available.
149    Fallback,
150}
151
152impl ContextWindowSource {
153    /// Stable serialized label.
154    #[must_use]
155    pub const fn as_str(self) -> &'static str {
156        match self {
157            Self::ExplicitConfig => "explicit_config",
158            Self::ProviderCapabilities => "provider_capabilities",
159            Self::BundledCatalog => "bundled_catalog",
160            Self::Fallback => "fallback",
161        }
162    }
163}