1use std::sync::Arc;
7
8use crate::interface::budget_policy::{OutputProgress, SpendNode};
9
10#[derive(Debug, Clone)]
11pub struct SessionLedger {
12 pub spent: Arc<SpendNode>,
16 pub goal_spent: Option<GoalSpend>,
18 pub spent_recorded: Option<SpendRecord>,
20 pub calls: SessionCalls,
21 pub token_target: TokenTarget,
22 pub invoked_skills: Vec<String>,
24 pub nested_repos: std::collections::BTreeMap<std::path::PathBuf, u64>,
27 pub nested_repos_at_start: Option<std::collections::BTreeMap<std::path::PathBuf, u64>>,
31}
32
33impl Default for SessionLedger {
34 fn default() -> Self {
35 Self {
36 spent: Arc::new(SpendNode::session(None)),
37 goal_spent: None,
38 spent_recorded: None,
39 calls: SessionCalls::default(),
40 token_target: TokenTarget::default(),
41 invoked_skills: Vec::new(),
42 nested_repos: Default::default(),
43 nested_repos_at_start: None,
44 }
45 }
46}
47
48impl SessionLedger {
49 pub fn spend_unrecorded(&self) -> Option<SpendRecord> {
52 let record = self.spend_record();
53 let recorded = self.spent_recorded.clone().unwrap_or_default();
54 (record != recorded).then_some(record)
55 }
56
57 pub fn spend_record(&self) -> SpendRecord {
59 SpendRecord {
60 session: self.spent.read(),
61 goal: self.goal_spent.as_ref().map(|goal| GoalSpendRecord {
62 id: goal.goal_id.clone(),
63 spent: goal.node.read(),
64 }),
65 }
66 }
67
68 pub fn open_goal(
71 &mut self,
72 goal_id: &str,
73 limit: Option<u64>,
74 spent: crate::interface::budget_policy::Spend,
75 ) -> Arc<SpendNode> {
76 let node = Arc::new(SpendNode::goal(limit, self.spent.clone()));
77 node.restore(spent);
78 self.goal_spent = Some(GoalSpend {
79 goal_id: goal_id.to_string(),
80 node: node.clone(),
81 });
82 node
83 }
84
85 pub fn note_skills<'a>(&mut self, names: impl IntoIterator<Item = &'a str>) {
86 for name in names {
87 if !self.invoked_skills.iter().any(|s| s == name) {
88 self.invoked_skills.push(name.to_string());
89 }
90 }
91 }
92}
93
94#[derive(Debug, Clone, Copy, Default)]
97pub struct SessionCalls {
98 pub api_calls: u32,
99 pub tool_calls: u32,
100}
101
102#[derive(Debug, Clone)]
104pub struct GoalSpend {
105 pub goal_id: String,
106 pub node: Arc<SpendNode>,
107}
108
109pub const SPEND_NS: &str = "agix.spend";
111pub const SPEND_EVENT: &str = "total";
112
113#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
116pub struct SpendRecord {
117 pub session: crate::interface::budget_policy::Spend,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub goal: Option<GoalSpendRecord>,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
123pub struct GoalSpendRecord {
124 pub id: String,
125 pub spent: crate::interface::budget_policy::Spend,
126}
127
128impl SpendRecord {
129 pub fn latest(records: impl IntoIterator<Item = SpendRecord>) -> Option<SpendRecord> {
134 records.into_iter().reduce(|seen, next| {
135 let goal = match (seen.goal, next.goal) {
136 (Some(a), Some(b)) if a.id == b.id => Some(GoalSpendRecord {
137 id: a.id,
138 spent: a.spent.max(b.spent),
139 }),
140 (a, b) => b.or(a),
141 };
142 SpendRecord {
143 session: seen.session.max(next.session),
144 goal,
145 }
146 })
147 }
148}
149
150#[derive(Debug, Clone, Copy, Default)]
153pub struct TokenTarget {
154 pub target: Option<u64>,
155 pub unannounced: bool,
157 pub accumulated: u64,
158 pub continuations: u32,
159 pub last_delta: u64,
160}
161
162impl TokenTarget {
163 pub fn clear(&mut self) {
165 *self = Self::default();
166 }
167
168 pub fn aim(&mut self, target: u64) {
170 *self = Self {
171 target: Some(target),
172 unannounced: true,
173 ..Self::default()
174 };
175 }
176
177 pub fn take_unannounced(&mut self) -> Option<u64> {
179 std::mem::take(&mut self.unannounced)
180 .then_some(self.target)
181 .flatten()
182 }
183
184 pub fn add_output(&mut self, target: u64, this_delta: u64) -> OutputProgress {
186 self.accumulated = self.accumulated.saturating_add(this_delta);
187 OutputProgress {
188 accumulated: self.accumulated,
189 target,
190 continuations: self.continuations,
191 this_delta,
192 last_delta: self.last_delta,
193 }
194 }
195
196 pub fn continued(&mut self, this_delta: u64) -> u32 {
199 self.continuations += 1;
200 self.last_delta = this_delta;
201 self.continuations
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::TokenTarget;
208
209 #[test]
210 fn a_new_aim_carries_nothing_over_from_the_last_target() {
211 let mut target = TokenTarget::default();
212 target.aim(5_000);
213 target.add_output(5_000, 700);
214 target.continued(700);
215 target.take_unannounced();
216
217 target.aim(9_000);
218 let progress = target.add_output(9_000, 10);
219 assert_eq!(
220 (
221 target.unannounced,
222 progress.accumulated,
223 progress.continuations,
224 progress.last_delta
225 ),
226 (true, 10, 0, 0)
227 );
228 }
229}