Skip to main content

base/context/
ledger.rs

1//! What a session has spent and asked for over its turns — kept on its
2//! `SessionState` (in `session-state`), so it outlives the engine that ran
3//! them. Its token total is also in the session log (`agix.spend`), so it
4//! outlives the process.
5
6use std::sync::Arc;
7
8use crate::interface::budget_policy::{OutputProgress, SpendNode};
9
10#[derive(Debug, Clone)]
11pub struct SessionLedger {
12    /// The session's node: every call of its turns spends into it as it is
13    /// made, their delegates' and those made on their side included, and
14    /// `session.token_budget` is its ceiling.
15    pub spent: Arc<SpendNode>,
16    /// The goal's node, under the session's, that its rounds spend into.
17    pub goal_spent: Option<GoalSpend>,
18    /// What the session log last recorded of the two.
19    pub spent_recorded: Option<SpendRecord>,
20    pub calls: SessionCalls,
21    pub token_target: TokenTarget,
22    /// Skills invoked or announced so far, re-injected after compaction.
23    pub invoked_skills: Vec<String>,
24    /// Repositories nested in the project the session has already reported
25    /// or been told to keep, with a digest of their configuration then.
26    pub nested_repos: std::collections::BTreeMap<std::path::PathBuf, u64>,
27    /// The repositories nested in the project before the session's first
28    /// tool call ran, with a digest of their configuration then; `None`
29    /// until that call.
30    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    /// [`Self::spend_record`] when the log does not have it yet; a session
50    /// that has spent nothing has nothing to record.
51    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    /// What the session and its goal have spent, as the log records it.
58    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    /// A node for goal `goal_id` under the session's, holding `limit`, that
69    /// has spent `spent` already.
70    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/// The model calls and tool calls of a session's own agent, summed over the
95/// turns it ran since it was loaded.
96#[derive(Debug, Clone, Copy, Default)]
97pub struct SessionCalls {
98    pub api_calls: u32,
99    pub tool_calls: u32,
100}
101
102/// The node of the goal whose rounds spend into it.
103#[derive(Debug, Clone)]
104pub struct GoalSpend {
105    pub goal_id: String,
106    pub node: Arc<SpendNode>,
107}
108
109/// Log namespace and event under which a [`SpendRecord`] is written.
110pub const SPEND_NS: &str = "agix.spend";
111pub const SPEND_EVENT: &str = "total";
112
113/// What a session has spent since it was created, and its goal since it was
114/// set, as the session log records them.
115#[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    /// The latest of `records`, a session log's in order. Two writers record
130    /// them — the engine and the session pool — and what was spent only
131    /// grows, so each figure is the largest recorded, whichever landed last;
132    /// a goal's, the largest recorded under its id.
133    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/// An output token target, kept until it is met, given up on, or cleared —
151/// a turn that ends otherwise leaves it running into the next.
152#[derive(Debug, Clone, Copy, Default)]
153pub struct TokenTarget {
154    pub target: Option<u64>,
155    /// Set by the message that set the target; the model has not been told yet.
156    pub unannounced: bool,
157    pub accumulated: u64,
158    pub continuations: u32,
159    pub last_delta: u64,
160}
161
162impl TokenTarget {
163    /// No target, nothing counted toward one.
164    pub fn clear(&mut self) {
165        *self = Self::default();
166    }
167
168    /// Aim at `target` from nothing, for the model to be told of it.
169    pub fn aim(&mut self, target: u64) {
170        *self = Self {
171            target: Some(target),
172            unannounced: true,
173            ..Self::default()
174        };
175    }
176
177    /// The target the model has not been told of yet, now told.
178    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    /// Count `this_delta` output tokens toward `target`.
185    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    /// Record that the model was asked to keep going after `this_delta`
197    /// output tokens; how many times it has been, now.
198    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}