1use std::sync::atomic::{AtomicU64, Ordering};
39use std::sync::Arc;
40
41use crate::interface::scene::TokenBudget;
42
43#[derive(
46 Debug,
47 Clone,
48 Copy,
49 PartialEq,
50 Eq,
51 Default,
52 serde::Serialize,
53 serde::Deserialize,
54 schemars::JsonSchema,
55)]
56pub struct Spend {
57 pub input_tokens: u64,
58 pub output_tokens: u64,
59 #[serde(rename = "cache_creation_input_tokens")]
61 pub cache_creation_tokens: u64,
62 #[serde(rename = "cache_read_input_tokens")]
63 pub cache_read_tokens: u64,
64}
65
66impl Spend {
67 pub fn counted_tokens(&self) -> u64 {
70 self.input_tokens
71 .saturating_add(self.cache_creation_tokens)
72 .saturating_add(self.output_tokens)
73 }
74
75 pub fn all_tokens(&self) -> u64 {
77 self.counted_tokens().saturating_add(self.cache_read_tokens)
78 }
79
80 pub fn as_usage(&self) -> crate::interface::model::Usage {
83 let narrow = |n: u64| u32::try_from(n).unwrap_or(u32::MAX);
84 crate::interface::model::Usage {
85 input_tokens: narrow(self.input_tokens),
86 output_tokens: narrow(self.output_tokens),
87 cache_creation_input_tokens: narrow(self.cache_creation_tokens),
88 cache_read_input_tokens: narrow(self.cache_read_tokens),
89 }
90 }
91
92 pub fn max(self, other: Self) -> Self {
94 Self {
95 input_tokens: self.input_tokens.max(other.input_tokens),
96 output_tokens: self.output_tokens.max(other.output_tokens),
97 cache_creation_tokens: self.cache_creation_tokens.max(other.cache_creation_tokens),
98 cache_read_tokens: self.cache_read_tokens.max(other.cache_read_tokens),
99 }
100 }
101}
102
103impl From<crate::interface::model::Usage> for Spend {
104 fn from(u: crate::interface::model::Usage) -> Self {
105 Self {
106 input_tokens: u.input_tokens as u64,
107 output_tokens: u.output_tokens as u64,
108 cache_creation_tokens: u.cache_creation_input_tokens as u64,
109 cache_read_tokens: u.cache_read_input_tokens as u64,
110 }
111 }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
116#[serde(rename_all = "snake_case")]
117pub enum Scope {
118 Turn,
119 Goal,
120 Task,
121 Session,
122}
123
124impl Scope {
125 pub fn whose(self) -> &'static str {
126 match self {
127 Self::Turn => "this turn's",
128 Self::Goal => "the goal's",
129 Self::Task => "the task's",
130 Self::Session => "this session's",
131 }
132 }
133}
134
135#[derive(Debug)]
144pub struct SpendNode {
145 scope: Scope,
146 limit: AtomicU64,
148 all: Tally,
149 delegated: Tally,
150 above: Option<Arc<SpendNode>>,
151 own_session: Option<Arc<SpendNode>>,
154}
155
156impl Default for SpendNode {
157 fn default() -> Self {
158 Self::turn(None, None)
159 }
160}
161
162impl SpendNode {
163 pub fn session(limit: Option<u64>) -> Self {
164 Self::node(Scope::Session, limit, None)
165 }
166
167 pub fn goal(limit: Option<u64>, session: Arc<SpendNode>) -> Self {
168 Self::node(Scope::Goal, limit, Some(session))
169 }
170
171 pub fn task(limit: Option<u64>, session: Arc<SpendNode>) -> Self {
174 Self::node(Scope::Task, limit, Some(session))
175 }
176
177 pub fn turn(limit: Option<u64>, above: Option<Arc<SpendNode>>) -> Self {
180 Self::node(Scope::Turn, limit, above)
181 }
182
183 fn node(scope: Scope, limit: Option<u64>, above: Option<Arc<SpendNode>>) -> Self {
184 Self {
185 scope,
186 limit: AtomicU64::new(limit.unwrap_or(0)),
187 all: Tally::default(),
188 delegated: Tally::default(),
189 above,
190 own_session: None,
191 }
192 }
193
194 pub fn counting_into(mut self, session: Arc<SpendNode>) -> Self {
196 self.own_session = Some(session);
197 self
198 }
199
200 pub fn scope(&self) -> Scope {
201 self.scope
202 }
203
204 pub fn limit(&self) -> Option<u64> {
205 Some(self.limit.load(Ordering::Relaxed)).filter(|&l| l > 0)
206 }
207
208 pub fn set_limit(&self, limit: Option<u64>) {
209 self.limit.store(limit.unwrap_or(0), Ordering::Relaxed);
210 }
211
212 pub fn add(&self, call: crate::interface::model::Usage) {
214 let call = Spend::from(call);
215 self.all.add(call);
216 if let Some(own) = &self.own_session {
217 own.all.add(call);
218 }
219 let mut delegated = self.scope == Scope::Turn;
220 let mut above = self.above.as_deref();
221 while let Some(node) = above {
222 node.all.add(call);
223 if delegated && node.scope == Scope::Turn {
224 node.delegated.add(call);
225 }
226 delegated &= node.scope == Scope::Turn;
227 above = node.above.as_deref();
228 }
229 }
230
231 pub fn read(&self) -> Spend {
233 self.all.read()
234 }
235
236 pub fn delegated(&self) -> Spend {
238 self.delegated.read()
239 }
240
241 pub fn restore(&self, spent: Spend) {
243 self.all.set(spent);
244 }
245
246 pub fn whole_turn(&self) -> Spend {
249 let mut turn = self;
250 while let Some(above) = turn.above.as_deref().filter(|a| a.scope == Scope::Turn) {
251 turn = above;
252 }
253 turn.read()
254 }
255
256 pub fn find(&self, scope: Scope) -> Option<&SpendNode> {
258 self.chain().find(|node| node.scope == scope)
259 }
260
261 fn chain(&self) -> impl Iterator<Item = &SpendNode> {
262 std::iter::successors(Some(self), |node| node.above.as_deref())
263 }
264
265 fn ceilings(&self) -> impl Iterator<Item = (Scope, u64, u64)> + '_ {
266 self.chain().filter_map(|node| {
267 let limit = node.limit()?;
268 Some((node.scope, limit, node.read().counted_tokens()))
269 })
270 }
271
272 pub fn remaining(&self) -> Option<(Scope, Remaining)> {
275 self.ceilings()
276 .map(|(scope, limit, spent)| {
277 let tokens = limit.saturating_sub(spent);
278 (scope, Remaining { tokens, limit })
279 })
280 .min_by_key(|(_, left)| left.tokens)
281 }
282
283 pub fn judge(&self) -> (Scope, Spending) {
287 let mut warned = None;
288 for (scope, limit, spent) in self.ceilings() {
289 if spent >= limit {
290 return (scope, Spending::Exhausted { limit });
291 }
292 if warned.is_none() && spent >= limit.saturating_mul(9) / 10 {
293 warned = Some((scope, limit));
294 }
295 }
296 match warned {
297 Some((scope, limit)) => (
298 scope,
299 Spending::Warn {
300 reminder: format!(
301 "<system-reminder>\n{} token budget is nearly exhausted. Keep your \
302 response concise and wrap up.\n</system-reminder>",
303 capitalized(scope.whose())
304 ),
305 limit,
306 },
307 ),
308 None => (Scope::Turn, Spending::WithinBudget),
309 }
310 }
311}
312
313fn capitalized(text: &str) -> String {
314 let mut chars = text.chars();
315 match chars.next() {
316 Some(first) => first.to_uppercase().chain(chars).collect(),
317 None => String::new(),
318 }
319}
320
321pub fn exhausted_message(scope: Scope, limit: u64) -> String {
324 format!("{} token budget of {limit} is used up", scope.whose())
325}
326
327#[derive(Debug, Default)]
328struct Tally {
329 input_tokens: AtomicU64,
330 output_tokens: AtomicU64,
331 cache_creation_tokens: AtomicU64,
332 cache_read_tokens: AtomicU64,
333}
334
335impl Tally {
336 fn add(&self, call: Spend) {
337 for (total, part) in [
338 (&self.input_tokens, call.input_tokens),
339 (&self.output_tokens, call.output_tokens),
340 (&self.cache_creation_tokens, call.cache_creation_tokens),
341 (&self.cache_read_tokens, call.cache_read_tokens),
342 ] {
343 total.fetch_add(part, Ordering::Relaxed);
344 }
345 }
346
347 fn set(&self, to: Spend) {
348 self.input_tokens.store(to.input_tokens, Ordering::Relaxed);
349 self.output_tokens
350 .store(to.output_tokens, Ordering::Relaxed);
351 self.cache_creation_tokens
352 .store(to.cache_creation_tokens, Ordering::Relaxed);
353 self.cache_read_tokens
354 .store(to.cache_read_tokens, Ordering::Relaxed);
355 }
356
357 fn read(&self) -> Spend {
358 Spend {
359 input_tokens: self.input_tokens.load(Ordering::Relaxed),
360 output_tokens: self.output_tokens.load(Ordering::Relaxed),
361 cache_creation_tokens: self.cache_creation_tokens.load(Ordering::Relaxed),
362 cache_read_tokens: self.cache_read_tokens.load(Ordering::Relaxed),
363 }
364 }
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369pub struct Remaining {
370 pub tokens: u64,
371 pub limit: u64,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum Spending {
377 WithinBudget,
378 Warn {
380 reminder: String,
381 limit: u64,
384 },
385 Exhausted {
387 limit: u64,
388 },
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub struct OutputProgress {
394 pub accumulated: u64,
396 pub target: u64,
397 pub continuations: u32,
399 pub this_delta: u64,
401 pub last_delta: u64,
403}
404
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub enum OutputTarget {
407 Reached,
409 KeepGoing { nudge: String },
411}
412
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub struct ContextBudget {
416 pub compact_threshold: usize,
418 pub compact_keep_recent: usize,
420 pub hard_cap: Option<usize>,
424}
425
426pub trait BudgetPolicy: Send + Sync {
429 fn on_usage(&self, _spend: &Spend) -> Spending {
433 Spending::WithinBudget
434 }
435
436 fn remaining(&self, _spend: &Spend) -> Option<Remaining> {
441 None
442 }
443
444 fn on_output_target(&self, _progress: &OutputProgress) -> OutputTarget {
455 OutputTarget::Reached
456 }
457
458 fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
460 ContextBudget {
461 compact_threshold: scene.compact_threshold,
462 compact_keep_recent: scene.compact_keep_recent,
463 hard_cap: None,
464 }
465 }
466}
467
468pub const MIN_CALL_TOKENS: u64 = 1024;
470
471#[derive(Default)]
474pub struct EngineBudget {
475 pub compact_threshold: Option<usize>,
478 pub compact_keep_recent: Option<usize>,
479}
480
481impl BudgetPolicy for EngineBudget {
482 fn on_output_target(&self, p: &OutputProgress) -> OutputTarget {
483 let met = (p.target as f64 * 0.9) as u64;
487 let diminishing = p.continuations >= 3 && p.this_delta < 500 && p.last_delta < 500;
488 if diminishing || p.accumulated >= met {
489 return OutputTarget::Reached;
490 }
491 let remaining = p.target.saturating_sub(p.accumulated);
492 OutputTarget::KeepGoing {
493 nudge: format!(
494 "\
495<system-reminder>
496Continue working. Used {}/{} output tokens ({} remaining).
497</system-reminder>",
498 p.accumulated, p.target, remaining
499 ),
500 }
501 }
502
503 fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
504 ContextBudget {
505 compact_threshold: self.compact_threshold.unwrap_or(scene.compact_threshold),
506 compact_keep_recent: self
507 .compact_keep_recent
508 .unwrap_or(scene.compact_keep_recent),
509 hard_cap: None,
510 }
511 }
512}
513
514pub struct Capped<P> {
522 pub inner: P,
523 pub context_hard_cap: usize,
524}
525
526impl<P: BudgetPolicy> BudgetPolicy for Capped<P> {
527 fn on_usage(&self, spend: &Spend) -> Spending {
528 self.inner.on_usage(spend)
529 }
530
531 fn remaining(&self, spend: &Spend) -> Option<Remaining> {
532 self.inner.remaining(spend)
533 }
534
535 fn on_output_target(&self, progress: &OutputProgress) -> OutputTarget {
536 self.inner.on_output_target(progress)
537 }
538
539 fn context_budget(&self, scene: &TokenBudget) -> ContextBudget {
540 ContextBudget {
541 hard_cap: Some(self.context_hard_cap),
542 ..self.inner.context_budget(scene)
543 }
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 fn engine() -> EngineBudget {
552 EngineBudget::default()
553 }
554
555 fn call(input: u32, output: u32) -> crate::interface::model::Usage {
556 crate::interface::model::Usage {
557 input_tokens: input,
558 output_tokens: output,
559 ..Default::default()
560 }
561 }
562
563 fn turn_capped(limit: u64) -> SpendNode {
564 SpendNode::turn(Some(limit), None)
565 }
566
567 #[test]
568 fn the_bill_warns_at_ninety_percent_and_stops_at_the_cap() {
569 let turn = turn_capped(1_000);
570 turn.add(call(800, 99));
571 assert_eq!(turn.judge(), (Scope::Turn, Spending::WithinBudget));
572 turn.add(call(0, 1));
573 assert!(matches!(turn.judge(), (Scope::Turn, Spending::Warn { .. })));
574 turn.add(call(0, 100));
575 assert_eq!(
576 turn.judge(),
577 (Scope::Turn, Spending::Exhausted { limit: 1_000 }),
578 "the check is `>=`; at the cap the turn is over, not one call later"
579 );
580 }
581
582 #[test]
583 fn what_remains_is_the_tightest_ceiling_up_the_chain() {
584 let session = Arc::new(SpendNode::session(Some(10_000)));
585 session.restore(Spend {
586 input_tokens: 7_000,
587 ..Default::default()
588 });
589 let goal = Arc::new(SpendNode::goal(Some(5_000), session.clone()));
590 let turn = Arc::new(SpendNode::turn(Some(4_000), Some(goal.clone())));
591 let delegate = SpendNode::turn(None, Some(turn.clone()));
592 delegate.add(call(1_000, 500));
593 assert_eq!(
594 delegate.remaining(),
595 Some((
596 Scope::Session,
597 Remaining {
598 tokens: 1_500,
599 limit: 10_000
600 }
601 ))
602 );
603 assert_eq!(goal.read().counted_tokens(), 1_500);
604 assert_eq!(turn.remaining().unwrap().1.tokens, 1_500);
605 session.set_limit(None);
606 assert_eq!(
607 delegate.remaining(),
608 Some((
609 Scope::Turn,
610 Remaining {
611 tokens: 2_500,
612 limit: 4_000
613 }
614 ))
615 );
616 assert_eq!(SpendNode::default().remaining(), None);
617 }
618
619 #[test]
620 fn a_ceiling_reached_anywhere_up_the_chain_ends_the_turn() {
621 let session = Arc::new(SpendNode::session(Some(1_000)));
622 let turn = SpendNode::turn(Some(1_000_000), Some(session.clone()));
623 turn.add(call(1_000, 0));
624 assert_eq!(
625 turn.judge(),
626 (Scope::Session, Spending::Exhausted { limit: 1_000 })
627 );
628 let next = SpendNode::turn(None, Some(session));
629 assert_eq!(next.remaining().unwrap().1.tokens, 0);
630 }
631
632 #[test]
633 fn delegates_spending_at_once_lose_nothing() {
634 let shared = Arc::new(turn_capped(40_000));
635 let usage = crate::interface::model::Usage {
636 input_tokens: 3,
637 output_tokens: 2,
638 cache_creation_input_tokens: 1,
639 cache_read_input_tokens: 7,
640 };
641 let spenders: Vec<_> = (0..8)
642 .map(|_| {
643 let shared = shared.clone();
644 std::thread::spawn(move || {
645 for _ in 0..1_000 {
646 shared.add(usage);
647 }
648 })
649 })
650 .collect();
651 for spender in spenders {
652 spender.join().unwrap();
653 }
654 assert_eq!(
655 shared.read(),
656 Spend {
657 input_tokens: 24_000,
658 output_tokens: 16_000,
659 cache_creation_tokens: 8_000,
660 cache_read_tokens: 56_000,
661 }
662 );
663 assert_eq!(shared.judge().1, Spending::Exhausted { limit: 40_000 });
664 }
665
666 #[test]
667 fn a_delegates_call_is_spent_by_every_node_above_it_once() {
668 let session = Arc::new(SpendNode::session(None));
669 let root = Arc::new(SpendNode::turn(None, Some(session.clone())));
670 let child_session = Arc::new(SpendNode::session(None));
671 let child = Arc::new(
672 SpendNode::turn(None, Some(root.clone())).counting_into(child_session.clone()),
673 );
674 let grandchild = SpendNode::turn(None, Some(child.clone()));
675 root.add(call(1, 0));
676 child.add(call(10, 0));
677 grandchild.add(call(100, 0));
678 assert_eq!(root.read().input_tokens, 111);
679 assert_eq!(root.delegated().input_tokens, 110);
680 assert_eq!(child.read().input_tokens, 110);
681 assert_eq!(child.delegated().input_tokens, 100);
682 assert_eq!(grandchild.whole_turn().input_tokens, 111);
683 assert_eq!(session.read().input_tokens, 111);
684 assert_eq!(session.delegated().input_tokens, 0);
685 assert_eq!(child_session.read().input_tokens, 10);
686 assert_eq!(
687 grandchild.find(Scope::Session).unwrap().read().input_tokens,
688 111
689 );
690 }
691
692 #[test]
693 fn a_tasks_ceiling_is_its_own_and_its_calls_are_the_sessions() {
694 let session = Arc::new(SpendNode::session(Some(10_000)));
695 let budgeted = Arc::new(SpendNode::task(Some(3_000), session.clone()));
696 let sibling = SpendNode::turn(None, Some(session.clone()));
697 let child_session = Arc::new(SpendNode::session(None));
698 let turn =
699 SpendNode::turn(None, Some(budgeted.clone())).counting_into(child_session.clone());
700 turn.add(call(2_000, 500));
701 sibling.add(call(4_000, 0));
702 assert_eq!(budgeted.read().counted_tokens(), 2_500);
703 assert_eq!(session.read().counted_tokens(), 6_500);
704 assert_eq!(child_session.read().counted_tokens(), 2_500);
705 assert_eq!(budgeted.delegated(), Spend::default());
706 assert_eq!(session.delegated(), Spend::default());
707 assert_eq!(turn.whole_turn(), turn.read());
708 assert_eq!(
709 turn.remaining(),
710 Some((
711 Scope::Task,
712 Remaining {
713 tokens: 500,
714 limit: 3_000
715 }
716 ))
717 );
718 assert_eq!(
719 sibling.remaining().map(|(scope, _)| scope),
720 Some(Scope::Session)
721 );
722 turn.add(call(500, 0));
723 assert_eq!(
724 turn.judge(),
725 (Scope::Task, Spending::Exhausted { limit: 3_000 })
726 );
727 assert_eq!(sibling.judge().1, Spending::WithinBudget);
728 session.restore(Spend {
729 input_tokens: 9_900,
730 ..Default::default()
731 });
732 let fresh = SpendNode::task(Some(3_000), session);
733 assert_eq!(
734 fresh.remaining(),
735 Some((
736 Scope::Session,
737 Remaining {
738 tokens: 100,
739 limit: 10_000
740 }
741 )),
742 "a task's ceiling loosened its session's"
743 );
744 }
745
746 #[test]
747 fn no_ceiling_configured_means_none() {
748 let turn = SpendNode::default();
749 turn.add(call(u32::MAX, 0));
750 assert_eq!(turn.judge().1, Spending::WithinBudget);
751 assert_eq!(turn.remaining(), None);
752 }
753
754 #[test]
756 fn a_cache_read_is_not_counted_and_a_cache_write_is() {
757 let spend = Spend {
758 input_tokens: 400,
759 output_tokens: 600,
760 cache_creation_tokens: 2_000,
761 cache_read_tokens: 30_000,
762 };
763 assert_eq!(spend.counted_tokens(), 3_000);
764 assert_eq!(spend.all_tokens(), 33_000);
765 }
766
767 #[test]
770 fn the_engines_ceiling_does_not_move_when_the_cache_fills() {
771 let turn = turn_capped(1_000);
772 turn.add(crate::interface::model::Usage {
773 input_tokens: 400,
774 output_tokens: 300,
775 cache_creation_input_tokens: 100,
776 cache_read_input_tokens: 90_000,
777 });
778 assert!(
779 matches!(turn.judge().1, Spending::WithinBudget),
780 "the cache moved a 1000-token ceiling that nobody asked to move"
781 );
782
783 struct CountsTheCache;
784 impl BudgetPolicy for CountsTheCache {
785 fn on_usage(&self, spend: &Spend) -> Spending {
786 if spend.all_tokens() >= 1_000 {
787 Spending::Exhausted { limit: 1_000 }
788 } else {
789 Spending::WithinBudget
790 }
791 }
792 }
793 assert_eq!(
794 CountsTheCache.on_usage(&turn.whole_turn()),
795 Spending::Exhausted { limit: 1_000 },
796 "the parts a policy needs to reach the other answer are not reachable"
797 );
798 }
799
800 #[test]
801 fn a_spend_is_written_with_the_wire_names_of_a_usage() {
802 let spend = Spend::from(crate::interface::model::Usage {
803 input_tokens: 11,
804 output_tokens: 7,
805 cache_creation_input_tokens: 5,
806 cache_read_input_tokens: 23,
807 });
808 assert_eq!(
809 serde_json::to_value(spend).unwrap(),
810 serde_json::to_value(spend.as_usage()).unwrap()
811 );
812 }
813
814 fn progress(accumulated: u64, continuations: u32, this: u64, last: u64) -> OutputProgress {
815 OutputProgress {
816 accumulated,
817 target: 100_000,
818 continuations,
819 this_delta: this,
820 last_delta: last,
821 }
822 }
823
824 #[test]
825 fn ninety_percent_of_the_output_target_counts_as_reached() {
826 let p = engine();
827 assert!(matches!(
828 p.on_output_target(&progress(89_000, 0, 1_000, 0)),
829 OutputTarget::KeepGoing { .. }
830 ));
831 assert_eq!(
832 p.on_output_target(&progress(90_000, 0, 1_000, 0)),
833 OutputTarget::Reached
834 );
835 }
836
837 #[test]
840 fn diminishing_returns_take_all_three_conditions() {
841 let p = engine();
842 assert_eq!(
843 p.on_output_target(&progress(10_000, 3, 400, 400)),
844 OutputTarget::Reached
845 );
846 assert!(matches!(
847 p.on_output_target(&progress(10_000, 2, 400, 400)),
848 OutputTarget::KeepGoing { .. },
849 ),);
850 assert!(matches!(
851 p.on_output_target(&progress(10_000, 3, 600, 400)),
852 OutputTarget::KeepGoing { .. }
853 ));
854 }
855
856 #[test]
860 fn a_long_run_of_substantial_answers_keeps_going() {
861 assert!(matches!(
862 engine().on_output_target(&progress(10_000, 20, 1_000, 1_000)),
863 OutputTarget::KeepGoing { .. }
864 ));
865 }
866
867 #[test]
868 fn the_scene_decides_the_threshold_until_a_deployment_caps_it() {
869 let scene = TokenBudget {
870 compact_threshold: 150_000,
871 compact_keep_recent: 4,
872 };
873 let engine_only = EngineBudget::default().context_budget(&scene);
874 assert_eq!(engine_only.compact_threshold, 150_000);
875 assert_eq!(
876 engine_only.hard_cap, None,
877 "the shape of the gap this fills"
878 );
879
880 let capped = Capped {
881 inner: EngineBudget::default(),
882 context_hard_cap: 120_000,
883 }
884 .context_budget(&scene);
885 assert_eq!(capped.hard_cap, Some(120_000));
886 assert_eq!(
887 capped.compact_threshold, 150_000,
888 "a ceiling is not a trigger — the scene still says when to compact"
889 );
890 }
891
892 #[test]
893 fn the_settings_compaction_numbers_override_the_scenes_when_set() {
894 let scene = TokenBudget {
895 compact_threshold: 150_000,
896 compact_keep_recent: 20,
897 };
898 let configured = EngineBudget {
899 compact_threshold: Some(60_000),
900 compact_keep_recent: Some(4),
901 }
902 .context_budget(&scene);
903 assert_eq!(
904 (configured.compact_threshold, configured.compact_keep_recent),
905 (60_000, 4)
906 );
907
908 let half = EngineBudget {
909 compact_keep_recent: Some(4),
910 ..EngineBudget::default()
911 }
912 .context_budget(&scene);
913 assert_eq!(
914 (half.compact_threshold, half.compact_keep_recent),
915 (150_000, 4)
916 );
917 }
918}