vv-agent 0.7.0

VectorVein agent runtime, SDK, CLI, tools, and workspace backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Instant;

use serde::{Deserialize, Serialize};

mod wire;

use crate::types::{CacheUsageStatus, TokenUsage, UsageSource};

pub const MAX_WIRE_INTEGER: u64 = (1_u64 << 53) - 1;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnavailableMetricPolicy {
    #[default]
    ContinueAndMark,
    Stop,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetDimension {
    TotalTokens,
    UncachedInputTokens,
    ToolCalls,
    ToolCallsByName,
    WallTime,
    HostCost,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetEnforcementBoundary {
    RunStart,
    CycleStart,
    LlmComplete,
    ToolBatchPreflight,
    ToolBatchComplete,
    Terminal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetExhaustionReason {
    LimitReached,
    LimitExceeded,
    MetricUnavailable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetUnavailableReason {
    UsageMissing,
    MeterMissing,
    MeterUnavailable,
    MeterError,
    UnitMismatch,
    CurrencyMismatch,
    NonMonotonic,
    IntegerOverflow,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HostCost {
    pub unit: String,
    pub currency: Option<String>,
    pub amount_microunits: u64,
}

impl HostCost {
    pub fn new(unit: impl Into<String>, amount_microunits: u64) -> Result<Self, String> {
        let cost = Self {
            unit: unit.into(),
            currency: None,
            amount_microunits,
        };
        cost.validate()?;
        Ok(cost)
    }

    pub fn with_currency(mut self, currency: impl Into<String>) -> Result<Self, String> {
        self.currency = Some(currency.into());
        self.validate()?;
        Ok(self)
    }

    fn validate(&self) -> Result<(), String> {
        validate_non_empty(&self.unit, "host cost unit")?;
        if let Some(currency) = &self.currency {
            validate_non_empty(currency, "host cost currency")?;
        }
        validate_wire_integer(self.amount_microunits, "host cost amount_microunits")
    }
}

pub trait HostCostMeter: Send + Sync {
    fn read(&self) -> Result<Option<HostCost>, String>;
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BudgetUnavailableDimension {
    pub dimension: BudgetDimension,
    pub reason: BudgetUnavailableReason,
    pub expected_unit: Option<String>,
    pub observed_unit: Option<String>,
    pub expected_currency: Option<String>,
    pub observed_currency: Option<String>,
}

impl BudgetUnavailableDimension {
    fn validate(&self) -> Result<(), String> {
        for (field, value) in [
            ("expected_unit", self.expected_unit.as_deref()),
            ("observed_unit", self.observed_unit.as_deref()),
            ("expected_currency", self.expected_currency.as_deref()),
            ("observed_currency", self.observed_currency.as_deref()),
        ] {
            if let Some(value) = value {
                validate_non_empty(value, field)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct RunBudgetLimits {
    pub max_total_tokens: Option<u64>,
    pub max_uncached_input_tokens: Option<u64>,
    pub max_tool_calls: Option<u64>,
    pub max_tool_calls_by_name: BTreeMap<String, u64>,
    pub max_wall_time_ms: Option<u64>,
    pub max_host_cost: Option<HostCost>,
    pub unavailable_metric_policy: UnavailableMetricPolicy,
}

impl RunBudgetLimits {
    pub fn builder() -> RunBudgetLimitsBuilder {
        RunBudgetLimitsBuilder::default()
    }

    pub fn has_limits(&self) -> bool {
        self.max_total_tokens.is_some()
            || self.max_uncached_input_tokens.is_some()
            || self.max_tool_calls.is_some()
            || !self.max_tool_calls_by_name.is_empty()
            || self.max_wall_time_ms.is_some()
            || self.max_host_cost.is_some()
    }

    pub fn validate(&self) -> Result<(), String> {
        for (field, value) in [
            ("max_total_tokens", self.max_total_tokens),
            ("max_uncached_input_tokens", self.max_uncached_input_tokens),
            ("max_tool_calls", self.max_tool_calls),
            ("max_wall_time_ms", self.max_wall_time_ms),
        ] {
            if let Some(value) = value {
                validate_wire_integer(value, field)?;
            }
        }
        for (name, value) in &self.max_tool_calls_by_name {
            validate_non_empty(name, "named tool budget key")?;
            validate_wire_integer(*value, &format!("max_tool_calls_by_name[{name:?}]"))?;
        }
        if let Some(cost) = &self.max_host_cost {
            cost.validate()?;
        }
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct RunBudgetLimitsBuilder {
    limits: RunBudgetLimits,
}

impl RunBudgetLimitsBuilder {
    pub fn max_total_tokens(mut self, value: u64) -> Self {
        self.limits.max_total_tokens = Some(value);
        self
    }

    pub fn max_uncached_input_tokens(mut self, value: u64) -> Self {
        self.limits.max_uncached_input_tokens = Some(value);
        self
    }

    pub fn max_tool_calls(mut self, value: u64) -> Self {
        self.limits.max_tool_calls = Some(value);
        self
    }

    pub fn max_tool_calls_by_name(
        mut self,
        values: impl IntoIterator<Item = (impl Into<String>, u64)>,
    ) -> Self {
        self.limits.max_tool_calls_by_name = values
            .into_iter()
            .map(|(name, value)| (name.into(), value))
            .collect();
        self
    }

    pub fn max_wall_time_ms(mut self, value: u64) -> Self {
        self.limits.max_wall_time_ms = Some(value);
        self
    }

    pub fn max_host_cost(mut self, value: HostCost) -> Self {
        self.limits.max_host_cost = Some(value);
        self
    }

    pub fn unavailable_metric_policy(mut self, value: UnavailableMetricPolicy) -> Self {
        self.limits.unavailable_metric_policy = value;
        self
    }

    pub fn build(self) -> Result<RunBudgetLimits, String> {
        self.limits.validate()?;
        Ok(self.limits)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BudgetUsageSnapshot {
    pub cycles: u64,
    pub total_tokens: Option<u64>,
    pub uncached_input_tokens: Option<u64>,
    pub tool_calls: u64,
    pub tool_calls_by_name: BTreeMap<String, u64>,
    pub elapsed_ms: u64,
    pub host_cost: Option<HostCost>,
    pub unavailable_dimensions: Vec<BudgetUnavailableDimension>,
}

impl Default for BudgetUsageSnapshot {
    fn default() -> Self {
        Self {
            cycles: 0,
            total_tokens: Some(0),
            uncached_input_tokens: Some(0),
            tool_calls: 0,
            tool_calls_by_name: BTreeMap::new(),
            elapsed_ms: 0,
            host_cost: None,
            unavailable_dimensions: Vec::new(),
        }
    }
}

impl BudgetUsageSnapshot {
    pub fn validate(&self) -> Result<(), String> {
        validate_wire_integer(self.cycles, "budget usage cycles")?;
        if let Some(value) = self.total_tokens {
            validate_wire_integer(value, "budget usage total_tokens")?;
        }
        if let Some(value) = self.uncached_input_tokens {
            validate_wire_integer(value, "budget usage uncached_input_tokens")?;
        }
        validate_wire_integer(self.tool_calls, "budget usage tool_calls")?;
        validate_wire_integer(self.elapsed_ms, "budget usage elapsed_ms")?;
        for (name, value) in &self.tool_calls_by_name {
            validate_non_empty(name, "budget usage tool name")?;
            validate_wire_integer(
                *value,
                &format!("budget usage tool_calls_by_name[{name:?}]"),
            )?;
        }
        if let Some(cost) = &self.host_cost {
            cost.validate()?;
        }
        let mut dimensions = self
            .unavailable_dimensions
            .iter()
            .map(|observation| observation.dimension)
            .collect::<Vec<_>>();
        dimensions.sort();
        dimensions.dedup();
        if dimensions.len() != self.unavailable_dimensions.len() {
            return Err("budget unavailable dimensions must be unique".to_string());
        }
        for observation in &self.unavailable_dimensions {
            observation.validate()?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BudgetExhaustion {
    pub dimension: BudgetDimension,
    pub tool_name: Option<String>,
    pub reason: BudgetExhaustionReason,
    pub limit: u64,
    pub observed: Option<u64>,
    pub attempted_increment: Option<u64>,
    pub overshoot: Option<u64>,
    pub unit: String,
    pub currency: Option<String>,
    pub enforcement_boundary: BudgetEnforcementBoundary,
    pub unavailable_reason: Option<BudgetUnavailableReason>,
}

impl BudgetExhaustion {
    fn validate(&self) -> Result<(), String> {
        validate_wire_integer(self.limit, "budget exhaustion limit")?;
        for (field, value) in [
            ("observed", self.observed),
            ("attempted_increment", self.attempted_increment),
            ("overshoot", self.overshoot),
        ] {
            if let Some(value) = value {
                validate_wire_integer(value, &format!("budget exhaustion {field}"))?;
            }
        }
        validate_non_empty(&self.unit, "budget exhaustion unit")?;
        if let Some(tool_name) = &self.tool_name {
            validate_non_empty(tool_name, "tool_name")?;
        }
        if let Some(currency) = &self.currency {
            validate_non_empty(currency, "currency")?;
        }
        Ok(())
    }
}

pub type MonotonicClock = Arc<dyn Fn() -> u128 + Send + Sync>;

pub struct BudgetEvaluator {
    pub limits: RunBudgetLimits,
    host_cost_meter: Option<Arc<dyn HostCostMeter>>,
    clock_ns: MonotonicClock,
    started_ns: u128,
    cycles: u64,
    total_tokens: Option<u64>,
    uncached_input_tokens: Option<u64>,
    tool_calls: u64,
    tool_calls_by_name: BTreeMap<String, u64>,
    base_elapsed_ms: u64,
    elapsed_ms: u64,
    host_cost: Option<HostCost>,
    unavailable: BTreeMap<BudgetDimension, BudgetUnavailableDimension>,
}

impl BudgetEvaluator {
    pub fn new(
        limits: RunBudgetLimits,
        host_cost_meter: Option<Arc<dyn HostCostMeter>>,
        initial_usage: Option<BudgetUsageSnapshot>,
    ) -> Result<Self, String> {
        let started = Instant::now();
        Self::with_clock(
            limits,
            host_cost_meter,
            initial_usage,
            Arc::new(move || started.elapsed().as_nanos()),
        )
    }

    pub fn with_clock(
        limits: RunBudgetLimits,
        host_cost_meter: Option<Arc<dyn HostCostMeter>>,
        initial_usage: Option<BudgetUsageSnapshot>,
        clock_ns: MonotonicClock,
    ) -> Result<Self, String> {
        limits.validate()?;
        if !limits.has_limits() {
            return Err("BudgetEvaluator requires at least one configured limit".to_string());
        }
        let usage = initial_usage.unwrap_or_default();
        usage.validate()?;
        let unavailable = usage
            .unavailable_dimensions
            .iter()
            .cloned()
            .map(|item| (item.dimension, item))
            .collect();
        let started_ns = clock_ns();
        Ok(Self {
            limits,
            host_cost_meter,
            clock_ns,
            started_ns,
            cycles: usage.cycles,
            total_tokens: usage.total_tokens,
            uncached_input_tokens: usage.uncached_input_tokens,
            tool_calls: usage.tool_calls,
            tool_calls_by_name: usage.tool_calls_by_name,
            base_elapsed_ms: usage.elapsed_ms,
            elapsed_ms: usage.elapsed_ms,
            host_cost: usage.host_cost,
            unavailable,
        })
    }

    pub fn snapshot(&self) -> BudgetUsageSnapshot {
        let mut unavailable_dimensions = self.unavailable.values().cloned().collect::<Vec<_>>();
        unavailable_dimensions.sort_by_key(|item| dimension_precedence(item.dimension));
        BudgetUsageSnapshot {
            cycles: self.cycles,
            total_tokens: self.total_tokens,
            uncached_input_tokens: self.uncached_input_tokens,
            tool_calls: self.tool_calls,
            tool_calls_by_name: self.tool_calls_by_name.clone(),
            elapsed_ms: self.elapsed_ms,
            host_cost: self.host_cost.clone(),
            unavailable_dimensions,
        }
    }

    pub fn run_start(&mut self) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::RunStart;
        self.observe_boundary();
        self.strict_unavailable(boundary).or_else(|| {
            self.check_admission_limits(
                boundary,
                &[BudgetDimension::WallTime, BudgetDimension::HostCost],
            )
        })
    }

    pub fn cycle_start(&mut self) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::CycleStart;
        self.observe_boundary();
        self.strict_unavailable(boundary).or_else(|| {
            self.check_admission_limits(
                boundary,
                &[
                    BudgetDimension::WallTime,
                    BudgetDimension::TotalTokens,
                    BudgetDimension::UncachedInputTokens,
                    BudgetDimension::HostCost,
                ],
            )
        })
    }

    pub fn llm_complete(&mut self, usage: &TokenUsage) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::LlmComplete;
        self.cycles = self.cycles.saturating_add(1);
        self.observe_token_usage(usage);
        self.observe_boundary();
        self.strict_unavailable(boundary).or_else(|| {
            self.check_exceeded_limits(
                boundary,
                &[
                    BudgetDimension::WallTime,
                    BudgetDimension::TotalTokens,
                    BudgetDimension::UncachedInputTokens,
                    BudgetDimension::HostCost,
                ],
            )
        })
    }

    pub fn preflight_tools(&mut self, tool_names: &[String]) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::ToolBatchPreflight;
        self.observe_boundary();
        if let Some(exhaustion) = self.strict_unavailable(boundary).or_else(|| {
            self.check_admission_limits(
                boundary,
                &[BudgetDimension::WallTime, BudgetDimension::HostCost],
            )
        }) {
            return Some(exhaustion);
        }

        let increment = u64::try_from(tool_names.len()).unwrap_or(u64::MAX);
        if let Some(limit) = self.limits.max_tool_calls {
            let projected = self.tool_calls.saturating_add(increment);
            if projected > limit {
                return Some(count_preflight_exhaustion(
                    BudgetDimension::ToolCalls,
                    None,
                    limit,
                    self.tool_calls,
                    increment,
                    boundary,
                ));
            }
        }

        let mut batch_by_name = BTreeMap::<String, u64>::new();
        for name in tool_names {
            *batch_by_name.entry(name.clone()).or_default() += 1;
        }
        for (name, limit) in &self.limits.max_tool_calls_by_name {
            let increment = batch_by_name.get(name).copied().unwrap_or_default();
            if increment == 0 {
                continue;
            }
            let observed = self
                .tool_calls_by_name
                .get(name)
                .copied()
                .unwrap_or_default();
            if observed.saturating_add(increment) > *limit {
                return Some(count_preflight_exhaustion(
                    BudgetDimension::ToolCallsByName,
                    Some(name.clone()),
                    *limit,
                    observed,
                    increment,
                    boundary,
                ));
            }
        }

        self.tool_calls = self.tool_calls.saturating_add(increment);
        for (name, increment) in batch_by_name {
            let value = self.tool_calls_by_name.entry(name).or_default();
            *value = value.saturating_add(increment);
        }
        None
    }

    pub fn tool_batch_complete(&mut self, operation_failed: bool) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::ToolBatchComplete;
        self.observe_boundary();
        if operation_failed {
            return None;
        }
        self.strict_unavailable(boundary).or_else(|| {
            self.check_exceeded_limits(
                boundary,
                &[BudgetDimension::WallTime, BudgetDimension::HostCost],
            )
        })
    }

    pub fn terminal(&mut self) -> Option<BudgetExhaustion> {
        let boundary = BudgetEnforcementBoundary::Terminal;
        self.observe_boundary();
        self.strict_unavailable(boundary)
            .or_else(|| self.check_exceeded_limits(boundary, &DIMENSION_PRECEDENCE))
    }

    fn observe_boundary(&mut self) {
        self.observe_elapsed();
        self.observe_host_cost();
    }

    fn observe_elapsed(&mut self) {
        if self.unavailable.contains_key(&BudgetDimension::WallTime) {
            return;
        }
        let now_ns = (self.clock_ns)();
        let delta_ns = now_ns.saturating_sub(self.started_ns);
        let elapsed_ms = u128::from(self.base_elapsed_ms).saturating_add(delta_ns / 1_000_000);
        if elapsed_ms > u128::from(MAX_WIRE_INTEGER) {
            self.latch_unavailable(
                BudgetDimension::WallTime,
                BudgetUnavailableReason::IntegerOverflow,
                Some("milliseconds"),
                None,
                None,
                None,
            );
            return;
        }
        self.elapsed_ms = self.elapsed_ms.max(elapsed_ms as u64);
    }

    fn observe_host_cost(&mut self) {
        let Some(limit) = self.limits.max_host_cost.clone() else {
            return;
        };
        if self.unavailable.contains_key(&BudgetDimension::HostCost) {
            return;
        }
        let Some(meter) = &self.host_cost_meter else {
            self.latch_host_unavailable(&limit, BudgetUnavailableReason::MeterMissing, None);
            return;
        };
        let reading = match meter.read() {
            Ok(Some(reading)) => reading,
            Ok(None) => {
                self.latch_host_unavailable(
                    &limit,
                    BudgetUnavailableReason::MeterUnavailable,
                    None,
                );
                return;
            }
            Err(_) => {
                self.latch_host_unavailable(&limit, BudgetUnavailableReason::MeterError, None);
                return;
            }
        };
        if reading.validate().is_err() {
            self.latch_host_unavailable(&limit, BudgetUnavailableReason::MeterError, None);
            return;
        }
        if reading.unit != limit.unit {
            self.latch_host_unavailable(
                &limit,
                BudgetUnavailableReason::UnitMismatch,
                Some(&reading),
            );
            return;
        }
        if reading.currency != limit.currency {
            self.latch_host_unavailable(
                &limit,
                BudgetUnavailableReason::CurrencyMismatch,
                Some(&reading),
            );
            return;
        }
        if self
            .host_cost
            .as_ref()
            .is_some_and(|previous| reading.amount_microunits < previous.amount_microunits)
        {
            self.host_cost = None;
            self.latch_host_unavailable(
                &limit,
                BudgetUnavailableReason::NonMonotonic,
                Some(&reading),
            );
            return;
        }
        self.host_cost = Some(reading);
    }

    fn observe_token_usage(&mut self, usage: &TokenUsage) {
        if !matches!(
            usage.usage_source,
            UsageSource::ProviderReported | UsageSource::Estimated
        ) {
            self.total_tokens = None;
            self.latch_unavailable(
                BudgetDimension::TotalTokens,
                BudgetUnavailableReason::UsageMissing,
                Some("tokens"),
                None,
                None,
                None,
            );
        } else if let Some(current) = self.total_tokens {
            self.total_tokens = self.safe_add_or_latch(
                BudgetDimension::TotalTokens,
                current,
                usage.total_tokens,
                "tokens",
            );
        }

        let uncached = if usage.cache_usage.status == CacheUsageStatus::ProviderReported {
            usage.cache_usage.uncached_input_tokens
        } else {
            None
        };
        if let Some(increment) = uncached {
            if let Some(current) = self.uncached_input_tokens {
                self.uncached_input_tokens = self.safe_add_or_latch(
                    BudgetDimension::UncachedInputTokens,
                    current,
                    increment,
                    "tokens",
                );
            }
        } else {
            self.uncached_input_tokens = None;
            self.latch_unavailable(
                BudgetDimension::UncachedInputTokens,
                BudgetUnavailableReason::UsageMissing,
                Some("tokens"),
                None,
                None,
                None,
            );
        }
    }

    fn safe_add_or_latch(
        &mut self,
        dimension: BudgetDimension,
        current: u64,
        increment: u64,
        expected_unit: &str,
    ) -> Option<u64> {
        match current.checked_add(increment) {
            Some(total) if total <= MAX_WIRE_INTEGER => Some(total),
            _ => {
                self.latch_unavailable(
                    dimension,
                    BudgetUnavailableReason::IntegerOverflow,
                    Some(expected_unit),
                    None,
                    None,
                    None,
                );
                None
            }
        }
    }

    fn latch_host_unavailable(
        &mut self,
        limit: &HostCost,
        reason: BudgetUnavailableReason,
        reading: Option<&HostCost>,
    ) {
        self.latch_unavailable(
            BudgetDimension::HostCost,
            reason,
            Some(&limit.unit),
            reading.map(|value| value.unit.as_str()),
            limit.currency.as_deref(),
            reading.and_then(|value| value.currency.as_deref()),
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn latch_unavailable(
        &mut self,
        dimension: BudgetDimension,
        reason: BudgetUnavailableReason,
        expected_unit: Option<&str>,
        observed_unit: Option<&str>,
        expected_currency: Option<&str>,
        observed_currency: Option<&str>,
    ) {
        self.unavailable
            .entry(dimension)
            .or_insert_with(|| BudgetUnavailableDimension {
                dimension,
                reason,
                expected_unit: expected_unit.map(str::to_string),
                observed_unit: observed_unit.map(str::to_string),
                expected_currency: expected_currency.map(str::to_string),
                observed_currency: observed_currency.map(str::to_string),
            });
    }

    fn strict_unavailable(&self, boundary: BudgetEnforcementBoundary) -> Option<BudgetExhaustion> {
        if self.limits.unavailable_metric_policy != UnavailableMetricPolicy::Stop {
            return None;
        }
        DIMENSION_PRECEDENCE.iter().find_map(|dimension| {
            let unavailable = self.unavailable.get(dimension)?;
            let (limit, unit, currency) = self.limit_descriptor(*dimension)?;
            Some(BudgetExhaustion {
                dimension: *dimension,
                tool_name: None,
                reason: BudgetExhaustionReason::MetricUnavailable,
                limit,
                observed: None,
                attempted_increment: None,
                overshoot: None,
                unit,
                currency,
                enforcement_boundary: boundary,
                unavailable_reason: Some(unavailable.reason),
            })
        })
    }

    fn check_admission_limits(
        &self,
        boundary: BudgetEnforcementBoundary,
        dimensions: &[BudgetDimension],
    ) -> Option<BudgetExhaustion> {
        DIMENSION_PRECEDENCE.iter().find_map(|dimension| {
            if !dimensions.contains(dimension) || self.unavailable.contains_key(dimension) {
                return None;
            }
            let (limit, unit, currency) = self.limit_descriptor(*dimension)?;
            let observed = self.observed_value(*dimension)?;
            (observed >= limit).then(|| BudgetExhaustion {
                dimension: *dimension,
                tool_name: None,
                reason: BudgetExhaustionReason::LimitReached,
                limit,
                observed: Some(observed),
                attempted_increment: None,
                overshoot: Some(observed.saturating_sub(limit)),
                unit,
                currency,
                enforcement_boundary: boundary,
                unavailable_reason: None,
            })
        })
    }

    fn check_exceeded_limits(
        &self,
        boundary: BudgetEnforcementBoundary,
        dimensions: &[BudgetDimension],
    ) -> Option<BudgetExhaustion> {
        DIMENSION_PRECEDENCE.iter().find_map(|dimension| {
            if !dimensions.contains(dimension) || self.unavailable.contains_key(dimension) {
                return None;
            }
            let (limit, unit, currency) = self.limit_descriptor(*dimension)?;
            let observed = self.observed_value(*dimension)?;
            (observed > limit).then(|| BudgetExhaustion {
                dimension: *dimension,
                tool_name: None,
                reason: BudgetExhaustionReason::LimitExceeded,
                limit,
                observed: Some(observed),
                attempted_increment: None,
                overshoot: Some(observed - limit),
                unit,
                currency,
                enforcement_boundary: boundary,
                unavailable_reason: None,
            })
        })
    }

    fn limit_descriptor(
        &self,
        dimension: BudgetDimension,
    ) -> Option<(u64, String, Option<String>)> {
        match dimension {
            BudgetDimension::TotalTokens => self
                .limits
                .max_total_tokens
                .map(|limit| (limit, "tokens".to_string(), None)),
            BudgetDimension::UncachedInputTokens => self
                .limits
                .max_uncached_input_tokens
                .map(|limit| (limit, "tokens".to_string(), None)),
            BudgetDimension::ToolCalls => self
                .limits
                .max_tool_calls
                .map(|limit| (limit, "calls".to_string(), None)),
            BudgetDimension::WallTime => self
                .limits
                .max_wall_time_ms
                .map(|limit| (limit, "milliseconds".to_string(), None)),
            BudgetDimension::HostCost => self.limits.max_host_cost.as_ref().map(|cost| {
                (
                    cost.amount_microunits,
                    cost.unit.clone(),
                    cost.currency.clone(),
                )
            }),
            BudgetDimension::ToolCallsByName => None,
        }
    }

    fn observed_value(&self, dimension: BudgetDimension) -> Option<u64> {
        match dimension {
            BudgetDimension::TotalTokens => self.total_tokens,
            BudgetDimension::UncachedInputTokens => self.uncached_input_tokens,
            BudgetDimension::ToolCalls => Some(self.tool_calls),
            BudgetDimension::WallTime => Some(self.elapsed_ms),
            BudgetDimension::HostCost => self.host_cost.as_ref().map(|cost| cost.amount_microunits),
            BudgetDimension::ToolCallsByName => None,
        }
    }
}

const DIMENSION_PRECEDENCE: [BudgetDimension; 6] = [
    BudgetDimension::WallTime,
    BudgetDimension::TotalTokens,
    BudgetDimension::UncachedInputTokens,
    BudgetDimension::HostCost,
    BudgetDimension::ToolCalls,
    BudgetDimension::ToolCallsByName,
];

fn dimension_precedence(dimension: BudgetDimension) -> usize {
    DIMENSION_PRECEDENCE
        .iter()
        .position(|candidate| *candidate == dimension)
        .expect("all budget dimensions have stable precedence")
}

fn count_preflight_exhaustion(
    dimension: BudgetDimension,
    tool_name: Option<String>,
    limit: u64,
    observed: u64,
    attempted_increment: u64,
    boundary: BudgetEnforcementBoundary,
) -> BudgetExhaustion {
    BudgetExhaustion {
        dimension,
        tool_name,
        reason: BudgetExhaustionReason::LimitReached,
        limit,
        observed: Some(observed),
        attempted_increment: Some(attempted_increment),
        overshoot: Some(
            observed
                .saturating_add(attempted_increment)
                .saturating_sub(limit),
        ),
        unit: "calls".to_string(),
        currency: None,
        enforcement_boundary: boundary,
        unavailable_reason: None,
    }
}

fn validate_wire_integer(value: u64, field: &str) -> Result<(), String> {
    if value <= MAX_WIRE_INTEGER {
        Ok(())
    } else {
        Err(format!("{field} must be between 0 and {MAX_WIRE_INTEGER}"))
    }
}

fn validate_non_empty(value: &str, field: &str) -> Result<(), String> {
    if value.trim().is_empty() {
        Err(format!("{field} must be a non-empty string"))
    } else {
        Ok(())
    }
}