adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
//! Run budgets: limits on model calls, tokens, cost, wall time, tool calls and units.
//!
//! A [`RunBudget`] states the limits for one run. A [`BudgetTracker`] holds the
//! shared counters for those limits. `Runner` creates one tracker per run from
//! [`RunConfig::budget`](crate::RunConfig::budget) and stores it in
//! [`RunConfig::budget_tracker`](crate::RunConfig::budget_tracker); because the
//! run configuration travels with the invocation, transfer targets, workflow
//! sub-agents and agents behind an agent tool all count against the same `Arc`.
//!
//! # Enforcement points
//!
//! | Checkpoint | Limits checked |
//! |------------|----------------|
//! | Before every model call ([`BudgetTracker::begin_model_call`]) | model calls, total tokens, cost, wall time; tool calls already over the limit |
//! | Before every tool dispatch ([`BudgetTracker::begin_tool_calls`]) | tool calls, total tokens, cost, wall time |
//! | Before every call billed in units ([`ModelCallScope::meter`](crate::ModelCallScope::meter)) | total tokens, cost, wall time; the per-unit caps of the units the call declares |
//! | After every non-partial event ([`BudgetTracker::record_event`]) | usage the call sites did not meter |
//!
//! A limit is *reached* when usage equals or exceeds it; a reached limit blocks
//! new work of that kind. Limits are checked before a call starts, so a single
//! model call can take usage past a limit; no further call starts after that.
//!
//! # Usage accounting
//!
//! Built-in tools the provider runs itself ([`UsageMetadata::builtin_tool_uses`])
//! count as tool calls when the model call's usage is recorded. They cannot be
//! reserved in advance, so a model call can take the tool-call count past its
//! limit; the next model call is then refused.
//!
//! Each model call is metered once, from the first non-partial response that
//! carries usage. Partial streaming chunks never add to the totals — Gemini
//! repeats cumulative usage on every chunk, so counting chunks would multiply
//! the spend.
//!
//! When a cost cap is set and a response has no known cost, the tracker fails
//! closed and stops the run with `cost unknown for model …`. Use
//! [`RunBudget::allow_unpriced_models`] to count such responses as zero cost.
//!
//! Calls billed in units other than tokens — images, audio, characters — are metered
//! through [`ModelCallScope::meter`](crate::ModelCallScope::meter): their cost counts
//! against the cost limit, their tokens against the token limit, and every unit is kept
//! in [`BudgetTracker::units`]. They are not model calls. A unit call with no known price
//! is refused before it is sent when a cost cap applies.
//!
//! # Per-unit caps
//!
//! [`RunBudget::max_units`] caps a unit — images, frames, pages — across the run. A call
//! billed in units declares the most it can use ([`UsageCall::with_units`](crate::UsageCall::with_units)),
//! and the tracker holds that amount before the call starts, as it reserves a model call:
//! a hold that would take a unit past its cap refuses the call with `budget.units`, before
//! any request, naming the unit and the cap. The call commits what it used and returns the
//! rest of its hold; a call that fails returns all of it. A call that declares no units is
//! not held, and its units count once it commits.
//!
//! # Example
//!
//! ```
//! use std::time::Duration;
//! use adk_core::{BudgetTracker, RunBudget, RunConfig};
//!
//! let budget = RunBudget::new()
//!     .max_model_calls(20)
//!     .max_cost_usd(50.0)
//!     .max_wall_time(Duration::from_secs(600));
//! assert_eq!(budget.max_cost_micro_usd, Some(50_000_000));
//!
//! let config = RunConfig::builder().budget(budget.clone()).build();
//! assert_eq!(config.budget, Some(budget.clone()));
//!
//! let tracker = BudgetTracker::new(budget);
//! assert!(tracker.begin_tool_calls(1).is_ok());
//! assert_eq!(tracker.usage().tool_calls, 1);
//! ```

use crate::{
    AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Event, Llm, LlmRequest, LlmResponse,
    LlmResponseStream, Result, UsageMetadata, UsageUnit, UsageVector,
};
use futures::Stream;
use std::collections::BTreeMap;
use std::fmt;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

/// Event-level `provider_metadata` key marking an event whose model usage and
/// tool calls are already counted by a [`BudgetTracker`].
///
/// Call sites that meter a model call set it on the events they emit for that
/// call, so [`BudgetTracker::record_event`] does not count the usage twice.
pub const BUDGET_RECORDED_KEY: &str = "adk.budget.recorded";

/// Event-level `provider_metadata` key naming the exhausted limit on the event
/// that explains why a run stopped. See [`budget_exceeded_event`].
pub const BUDGET_LIMIT_KEY: &str = "adk.budget.limit";

/// Resource limits for one run.
///
/// Every limit is optional; `None` leaves that resource unlimited. Build one
/// with the chained setters and attach it with
/// [`RunConfigBuilder::budget`](crate::RunConfigBuilder::budget) or
/// `RunnerConfigBuilder::budget`.
///
/// # Example
///
/// ```
/// use std::time::Duration;
/// use adk_core::RunBudget;
///
/// let budget = RunBudget::new()
///     .max_model_calls(10)
///     .max_total_tokens(200_000)
///     .max_cost_micro_usd(2_500_000)
///     .max_wall_time(Duration::from_secs(120))
///     .max_tool_calls(25);
/// assert_eq!(budget.max_tool_calls, Some(25));
/// assert!(!budget.allow_unpriced_models);
/// ```
///
/// A budget serializes in camelCase with the wall time in milliseconds and the per-unit caps
/// keyed by unit, so it travels in a durable run's input
/// (`{"runLimits": {"budget": {"maxModelCalls": 10, "maxWallTimeMs": 120000, "maxUnits": {"images": 20}}}}`).
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RunBudget {
    /// Maximum model calls started in the run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_model_calls: Option<u64>,
    /// Maximum input plus output tokens reported by the models.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_total_tokens: Option<u64>,
    /// Maximum cost in millionths of a US dollar.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_cost_micro_usd: Option<u64>,
    /// Maximum wall-clock time since the tracker was created.
    #[serde(
        rename = "maxWallTimeMs",
        with = "optional_millis",
        skip_serializing_if = "Option::is_none"
    )]
    pub max_wall_time: Option<Duration>,
    /// Maximum tool calls dispatched in the run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tool_calls: Option<u64>,
    /// Count responses with no known cost as zero cost instead of stopping.
    ///
    /// Only consulted when [`max_cost_micro_usd`](Self::max_cost_micro_usd) is
    /// set. The default `false` stops the run, because an unpriced model would
    /// otherwise spend without limit under a cost cap.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub allow_unpriced_models: bool,
    /// Maximum usage of each capped unit across the calls billed in units, such as
    /// `{images: 20}`. A unit with no entry is unlimited. See the
    /// [module documentation](self#per-unit-caps).
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub max_units: BTreeMap<UsageUnit, u64>,
}

/// `Option<Duration>` as whole milliseconds.
mod optional_millis {
    use std::time::Duration;

    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(
        value: &Option<Duration>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        match value {
            Some(duration) => {
                serializer.serialize_u64(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
            }
            None => serializer.serialize_none(),
        }
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<Duration>, D::Error> {
        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_millis))
    }
}

impl RunBudget {
    /// Creates a budget with no limits.
    pub fn new() -> Self {
        Self::default()
    }

    /// Limits the number of model calls.
    pub fn max_model_calls(mut self, max: u64) -> Self {
        self.max_model_calls = Some(max);
        self
    }

    /// Limits the input plus output tokens reported by the models.
    pub fn max_total_tokens(mut self, max: u64) -> Self {
        self.max_total_tokens = Some(max);
        self
    }

    /// Limits the cost in millionths of a US dollar.
    pub fn max_cost_micro_usd(mut self, max: u64) -> Self {
        self.max_cost_micro_usd = Some(max);
        self
    }

    /// Limits the cost in US dollars, stored as micro-USD.
    ///
    /// Negative and non-finite values become a zero cap.
    pub fn max_cost_usd(self, max: f64) -> Self {
        self.max_cost_micro_usd(usd_to_micro(max))
    }

    /// Limits the wall-clock time of the run.
    pub fn max_wall_time(mut self, max: Duration) -> Self {
        self.max_wall_time = Some(max);
        self
    }

    /// Limits the number of tool calls.
    pub fn max_tool_calls(mut self, max: u64) -> Self {
        self.max_tool_calls = Some(max);
        self
    }

    /// Counts responses with no known cost as zero cost under a cost cap.
    ///
    /// Use this for local or self-hosted models that have no per-token price.
    pub fn allow_unpriced_models(mut self) -> Self {
        self.allow_unpriced_models = true;
        self
    }

    /// Limits the usage of `unit` across the run's calls billed in units.
    ///
    /// A call that declares it would take the unit past `max` is refused with
    /// `budget.units` before it starts.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{RunBudget, UsageUnit};
    ///
    /// let budget = RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600);
    /// assert_eq!(budget.max_units.get(&UsageUnit::Images), Some(&20));
    /// assert_eq!(
    ///     serde_json::to_value(&budget).unwrap(),
    ///     serde_json::json!({ "maxUnits": { "images": 20, "frames": 600 } })
    /// );
    /// ```
    pub fn max_units(mut self, unit: UsageUnit, max: u64) -> Self {
        self.max_units.insert(unit, max);
        self
    }

    /// Returns `true` when no limit is set.
    pub fn is_unlimited(&self) -> bool {
        self.max_model_calls.is_none()
            && self.max_total_tokens.is_none()
            && self.max_cost_micro_usd.is_none()
            && self.max_wall_time.is_none()
            && self.max_tool_calls.is_none()
            && self.max_units.is_empty()
    }

    /// The stricter of `self` and `other`: each limit is the smaller of the two, a limit
    /// only one of them sets applies, and unpriced models count as free only when every
    /// budget that caps cost allows it. A budget a run's input carries narrows the runner's this way, so it can
    /// only take resources away.
    ///
    /// # Example
    ///
    /// ```
    /// use std::time::Duration;
    /// use adk_core::RunBudget;
    ///
    /// let runner = RunBudget::new().max_model_calls(50).max_wall_time(Duration::from_secs(600));
    /// let run = RunBudget::new().max_model_calls(10).max_cost_micro_usd(500_000);
    /// let narrowed = runner.narrowed(&run);
    /// assert_eq!(narrowed.max_model_calls, Some(10));
    /// assert_eq!(narrowed.max_cost_micro_usd, Some(500_000));
    /// assert_eq!(narrowed.max_wall_time, Some(Duration::from_secs(600)));
    /// ```
    #[must_use]
    pub fn narrowed(&self, other: &RunBudget) -> RunBudget {
        fn min<T: Ord + Copy>(a: Option<T>, b: Option<T>) -> Option<T> {
            match (a, b) {
                (Some(a), Some(b)) => Some(a.min(b)),
                (a, b) => a.or(b),
            }
        }
        RunBudget {
            max_model_calls: min(self.max_model_calls, other.max_model_calls),
            max_total_tokens: min(self.max_total_tokens, other.max_total_tokens),
            max_cost_micro_usd: min(self.max_cost_micro_usd, other.max_cost_micro_usd),
            max_wall_time: min(self.max_wall_time, other.max_wall_time),
            max_tool_calls: min(self.max_tool_calls, other.max_tool_calls),
            max_units: UsageUnit::ALL
                .into_iter()
                .filter_map(|unit| {
                    min(self.max_units.get(&unit).copied(), other.max_units.get(&unit).copied())
                        .map(|max| (unit, max))
                })
                .collect(),
            // The flag means something only under a cost cap, so the cap's own budget sets it.
            allow_unpriced_models: match (
                self.max_cost_micro_usd.is_some(),
                other.max_cost_micro_usd.is_some(),
            ) {
                (true, false) => self.allow_unpriced_models,
                (false, true) => other.allow_unpriced_models,
                (true, true) | (false, false) => {
                    self.allow_unpriced_models && other.allow_unpriced_models
                }
            },
        }
    }
}

/// The resource a budget check found exhausted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BudgetLimit {
    /// [`RunBudget::max_model_calls`].
    ModelCalls,
    /// [`RunBudget::max_total_tokens`], or token usage the provider did not report.
    TotalTokens,
    /// [`RunBudget::max_cost_micro_usd`], or a cost no price is known for.
    Cost,
    /// [`RunBudget::max_wall_time`].
    WallTime,
    /// [`RunBudget::max_tool_calls`].
    ToolCalls,
    /// The unit's entry in [`RunBudget::max_units`].
    Units(UsageUnit),
}

impl BudgetLimit {
    /// Stable identifier used in error details and event metadata.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ModelCalls => "model_calls",
            Self::TotalTokens => "total_tokens",
            Self::Cost => "cost_micro_usd",
            Self::WallTime => "wall_time_ms",
            Self::ToolCalls => "tool_calls",
            Self::Units(unit) => match unit {
                UsageUnit::InputTokens => "units.inputTokens",
                UsageUnit::OutputTokens => "units.outputTokens",
                UsageUnit::Images => "units.images",
                UsageUnit::AudioMillis => "units.audioMillis",
                UsageUnit::VideoMillis => "units.videoMillis",
                UsageUnit::Characters => "units.characters",
                UsageUnit::Pages => "units.pages",
                UsageUnit::Requests => "units.requests",
                UsageUnit::Frames => "units.frames",
            },
        }
    }
}

impl fmt::Display for BudgetLimit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A budget violation: which limit, how much was used, and the maximum.
///
/// Converts into an [`AdkError`] with category
/// [`ErrorCategory::ResourceExhausted`] and a `budget.*` code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BudgetExceeded {
    limit: BudgetLimit,
    used: u64,
    max: u64,
    code: &'static str,
    message: String,
}

impl BudgetExceeded {
    fn reached(limit: BudgetLimit, used: u64, max: u64) -> Self {
        let (code, message) = match limit {
            BudgetLimit::ModelCalls => (
                "budget.model_calls",
                format!("budget exhausted: {used} of {max} model calls used"),
            ),
            BudgetLimit::TotalTokens => {
                ("budget.total_tokens", format!("budget exhausted: {used} of {max} tokens used"))
            }
            BudgetLimit::Cost => (
                "budget.cost",
                format!(
                    "budget exhausted: {} of {} spent",
                    format_micro_usd(used),
                    format_micro_usd(max)
                ),
            ),
            BudgetLimit::WallTime => (
                "budget.wall_time",
                format!("budget exhausted: {used}ms of {max}ms wall time elapsed"),
            ),
            BudgetLimit::ToolCalls => {
                ("budget.tool_calls", format!("budget exhausted: {used} of {max} tool calls used"))
            }
            BudgetLimit::Units(unit) => {
                ("budget.units", format!("budget exhausted: {used} of {max} {unit} used"))
            }
        };
        Self { limit, used, max, code, message }
    }

    fn units(unit: UsageUnit, used: u64, requested: u64, max: u64) -> Self {
        Self {
            limit: BudgetLimit::Units(unit),
            used,
            max,
            code: "budget.units",
            message: format!(
                "budget exhausted: the call would bring {unit} to {}, past the run's cap of \
                 {max} {unit}, so it was not sent; raise RunBudget::max_units for {unit} or \
                 start a new run",
                used.saturating_add(requested)
            ),
        }
    }

    fn tool_batch(used: u64, requested: u64, max: u64) -> Self {
        Self {
            limit: BudgetLimit::ToolCalls,
            used,
            max,
            code: "budget.tool_calls",
            message: format!(
                "budget exhausted: {requested} tool calls requested with {used} of {max} already used"
            ),
        }
    }

    fn unpriced(model: &str, used: u64, max: u64) -> Self {
        Self {
            limit: BudgetLimit::Cost,
            used,
            max,
            code: "budget.cost_unknown",
            message: format!(
                "cost unknown for model '{model}': the budget has a cost cap of {} and no price is known for this model; set UsageMetadata::cost in the provider or opt out with RunBudget::allow_unpriced_models()",
                format_micro_usd(max)
            ),
        }
    }

    fn unpriced_units(model: &str, used: u64, max: u64) -> Self {
        Self {
            limit: BudgetLimit::Cost,
            used,
            max,
            code: "budget.cost_unknown",
            message: format!(
                "cost unknown for '{model}': the budget has a cost cap of {} and no per-unit price is known for this call, so it was not sent; add the price to the pricing catalog or opt out with RunBudget::allow_unpriced_models()",
                format_micro_usd(max)
            ),
        }
    }

    fn untokened(model: &str, used: u64, max: u64) -> Self {
        Self {
            limit: BudgetLimit::TotalTokens,
            used,
            max,
            code: "budget.tokens_unknown",
            message: format!(
                "token usage unknown for model '{model}': the provider reported no usage and the budget has a token cap of {max}"
            ),
        }
    }

    /// The exhausted limit.
    pub fn limit(&self) -> BudgetLimit {
        self.limit
    }

    /// Usage when the violation was detected, in the limit's unit.
    pub fn used(&self) -> u64 {
        self.used
    }

    /// The configured maximum, in the limit's unit.
    pub fn max(&self) -> u64 {
        self.max
    }

    /// Stable error code, for example `budget.cost` or `budget.cost_unknown`.
    pub fn code(&self) -> &'static str {
        self.code
    }

    /// Human-readable explanation.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for BudgetExceeded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for BudgetExceeded {}

impl From<BudgetExceeded> for AdkError {
    fn from(exceeded: BudgetExceeded) -> Self {
        let mut details = ErrorDetails::default();
        details.metadata.insert("limit".to_string(), exceeded.limit.as_str().into());
        details.metadata.insert("used".to_string(), exceeded.used.into());
        details.metadata.insert("max".to_string(), exceeded.max.into());
        if let BudgetLimit::Units(unit) = exceeded.limit {
            details.metadata.insert("unit".to_string(), unit.as_str().into());
        }
        AdkError::new(
            ErrorComponent::Agent,
            ErrorCategory::ResourceExhausted,
            exceeded.code,
            exceeded.message,
        )
        .with_details(details)
    }
}

/// A snapshot of the usage counted by a [`BudgetTracker`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BudgetUsage {
    /// Model calls started.
    pub model_calls: u64,
    /// Input plus output tokens reported.
    pub total_tokens: u64,
    /// Cost in millionths of a US dollar.
    pub cost_micro_usd: u64,
    /// Tool calls dispatched.
    pub tool_calls: u64,
    /// Wall-clock time since the tracker was created.
    pub elapsed: Duration,
}

/// Shared, thread-safe counters for one [`RunBudget`].
///
/// Clone the `Arc`, never the tracker: every holder of the same `Arc` counts
/// against the same limits. A tracker created with
/// [`with_parent`](Self::with_parent) also counts against its parent, so a
/// team budget nested in a run budget enforces both.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use adk_core::{BudgetLimit, BudgetTracker, RunBudget};
///
/// let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(1)));
/// let meter = tracker.begin_model_call("gemini-3.8-flash").unwrap();
/// drop(meter);
///
/// let exceeded = tracker.begin_model_call("gemini-3.8-flash").unwrap_err();
/// assert_eq!(exceeded.limit(), BudgetLimit::ModelCalls);
/// assert_eq!(tracker.usage().model_calls, 1);
/// ```
#[derive(Debug)]
pub struct BudgetTracker {
    budget: RunBudget,
    started_at: Instant,
    model_calls: AtomicU64,
    total_tokens: AtomicU64,
    cost_micro_usd: AtomicU64,
    tool_calls: AtomicU64,
    units: Mutex<UnitCounts>,
    exceeded: Mutex<Option<BudgetExceeded>>,
    parent: Option<Arc<BudgetTracker>>,
}

/// Units counted by a [`BudgetTracker`]: what calls used, and what open calls and carved
/// slices hold against the per-unit caps.
#[derive(Debug, Default)]
struct UnitCounts {
    used: UsageVector,
    held: UsageVector,
}

impl BudgetTracker {
    /// Creates a tracker for `budget` with zero usage, starting the wall clock now.
    pub fn new(budget: RunBudget) -> Self {
        Self::resume(budget, BudgetUsage::default(), None)
    }

    /// Creates a tracker that also counts against, and is limited by, `parent`.
    pub fn with_parent(budget: RunBudget, parent: Arc<BudgetTracker>) -> Self {
        Self::resume(budget, BudgetUsage::default(), Some(parent))
    }

    /// Creates a tracker that continues from previously recorded usage.
    ///
    /// The wall clock starts `usage.elapsed` in the past, so a resumed run keeps
    /// its elapsed time. Usage is not added to `parent`.
    pub fn resume(
        budget: RunBudget,
        usage: BudgetUsage,
        parent: Option<Arc<BudgetTracker>>,
    ) -> Self {
        let now = Instant::now();
        Self {
            budget,
            started_at: now.checked_sub(usage.elapsed).unwrap_or(now),
            model_calls: AtomicU64::new(usage.model_calls),
            total_tokens: AtomicU64::new(usage.total_tokens),
            cost_micro_usd: AtomicU64::new(usage.cost_micro_usd),
            tool_calls: AtomicU64::new(usage.tool_calls),
            units: Mutex::new(UnitCounts::default()),
            exceeded: Mutex::new(None),
            parent,
        }
    }

    /// The limits this tracker enforces.
    pub fn budget(&self) -> &RunBudget {
        &self.budget
    }

    /// The parent tracker, if this tracker was created with one.
    pub fn parent(&self) -> Option<&Arc<BudgetTracker>> {
        self.parent.as_ref()
    }

    /// Usage counted so far by this tracker.
    pub fn usage(&self) -> BudgetUsage {
        BudgetUsage {
            model_calls: self.model_calls.load(Ordering::SeqCst),
            total_tokens: self.total_tokens.load(Ordering::SeqCst),
            cost_micro_usd: self.cost_micro_usd.load(Ordering::SeqCst),
            tool_calls: self.tool_calls.load(Ordering::SeqCst),
            elapsed: self.started_at.elapsed(),
        }
    }

    /// Usage counted by this tracker per [`UsageUnit`]: the input and output tokens of
    /// model calls, and every unit of the calls metered through
    /// [`ModelCallScope::meter`](crate::ModelCallScope::meter).
    ///
    /// A tracker created with [`resume`](Self::resume) starts with no units, so its
    /// per-unit caps count from the resume.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use adk_core::{
    ///     BudgetTracker, LlmResponse, RunBudget, UsageMetadata, UsageUnit, UsageVector,
    /// };
    ///
    /// let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
    /// let mut meter = tracker.begin_model_call("gemini-3.8-flash").unwrap();
    /// let mut response = LlmResponse::default();
    /// response.usage_metadata = Some(UsageMetadata {
    ///     prompt_token_count: 120,
    ///     candidates_token_count: 30,
    ///     total_token_count: 150,
    ///     ..Default::default()
    /// });
    /// meter.observe(&response);
    /// assert_eq!(
    ///     tracker.units(),
    ///     UsageVector::new().with(UsageUnit::InputTokens, 120).with(UsageUnit::OutputTokens, 30)
    /// );
    /// ```
    pub fn units(&self) -> UsageVector {
        self.units.lock().unwrap_or_else(|e| e.into_inner()).used.clone()
    }

    /// The first unknown-usage violation recorded by this tracker or an ancestor.
    ///
    /// A response with no known cost under a cost cap, or no usage under a token
    /// cap, cannot be read back from the counters, so it is recorded and every
    /// later check fails with it. Limits reached by usage are recomputed at each
    /// check instead.
    pub fn exceeded(&self) -> Option<BudgetExceeded> {
        let own = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone();
        own.or_else(|| self.parent.as_ref().and_then(|parent| parent.exceeded()))
    }

    /// Checks that no token, cost or wall-time limit is reached.
    ///
    /// # Errors
    ///
    /// Returns the violation when a limit is reached in this tracker or an
    /// ancestor, or when a violation was recorded earlier.
    pub fn check(&self) -> std::result::Result<(), BudgetExceeded> {
        self.check_chain(Strictness::Reached)
    }

    /// Reserves one model call, after checking every limit that gates it.
    ///
    /// The returned [`ModelCallMeter`] records the call's usage when it sees
    /// the first non-partial response carrying usage, or when it is dropped.
    ///
    /// # Errors
    ///
    /// Returns the violation when the model-call, token, cost or wall-time
    /// limit is reached in this tracker or an ancestor.
    pub fn begin_model_call(
        self: &Arc<Self>,
        model: impl Into<String>,
    ) -> std::result::Result<ModelCallMeter, BudgetExceeded> {
        self.check()?;
        // Provider-executed built-in tools are counted after the fact, so a turn can
        // overshoot the tool-call limit; the next model call is refused instead.
        self.check_chain(Strictness::Exceeded)?;
        self.reserve(Counter::ModelCalls, 1)?;
        Ok(ModelCallMeter {
            tracker: Arc::clone(self),
            model: model.into(),
            fallback: None,
            responses_seen: false,
            settled: false,
        })
    }

    /// Checks the limits that gate a call billed in units ([`ModelCallScope::meter`](crate::ModelCallScope::meter))
    /// and holds the `units` it declares against the per-unit caps.
    ///
    /// The call is not a model call. `priced` is `false` when no price is known for the
    /// call: a cost cap that does not
    /// [`allow_unpriced_models`](RunBudget::allow_unpriced_models) then refuses it, before
    /// it is sent. Settle the hold with [`record_units`](Self::record_units) or
    /// [`release_units`](Self::release_units).
    pub(crate) fn begin_usage(
        &self,
        model: &str,
        priced: bool,
        units: &UsageVector,
    ) -> std::result::Result<(), BudgetExceeded> {
        self.check()?;
        self.check_chain(Strictness::Exceeded)?;
        if !priced {
            self.refuse_unpriced(model)?;
        }
        self.hold_units(units)
    }

    /// Holds `units` in this tracker and its ancestors, all or nothing: a unit that the hold
    /// would take past its cap anywhere in the chain refuses the whole hold.
    fn hold_units(&self, units: &UsageVector) -> std::result::Result<(), BudgetExceeded> {
        if units.is_empty() {
            return Ok(());
        }
        {
            let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
            for (unit, amount) in units.iter() {
                if let Some(&max) = self.budget.max_units.get(&unit) {
                    let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
                    if used.saturating_add(amount) > max {
                        return Err(BudgetExceeded::units(unit, used, amount, max));
                    }
                }
            }
            counts.held.merge(units);
        }
        if let Some(parent) = &self.parent
            && let Err(violation) = parent.hold_units(units)
        {
            self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(units);
            return Err(violation);
        }
        Ok(())
    }

    /// Returns `held` units of a call that did not complete, in this tracker and its
    /// ancestors.
    pub(crate) fn release_units(&self, held: &UsageVector) {
        if held.is_empty() {
            return;
        }
        self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(held);
        if let Some(parent) = &self.parent {
            parent.release_units(held);
        }
    }

    fn refuse_unpriced(&self, model: &str) -> std::result::Result<(), BudgetExceeded> {
        if let Some(max) = self.budget.max_cost_micro_usd
            && !self.budget.allow_unpriced_models
        {
            let used = self.cost_micro_usd.load(Ordering::SeqCst);
            return Err(BudgetExceeded::unpriced_units(model, used, max));
        }
        match &self.parent {
            Some(parent) => parent.refuse_unpriced(model),
            None => Ok(()),
        }
    }

    /// Counts what a call billed in units used — its cost, its tokens, and every unit — in
    /// place of the `held` units it declared.
    pub(crate) fn record_units(
        &self,
        model: &str,
        held: &UsageVector,
        units: &UsageVector,
        cost: Option<u64>,
    ) {
        self.add(Counter::TotalTokens, units.tokens());
        match cost {
            Some(cost) => self.add(Counter::Cost, cost),
            None => self.flag_unpriced(model),
        }
        self.settle_units(held, units);
    }

    /// Replaces `held` units with `used` ones, in this tracker and its ancestors, under one
    /// lock per tracker so a concurrent hold never sees both or neither.
    fn settle_units(&self, held: &UsageVector, used: &UsageVector) {
        if held.is_empty() && used.is_empty() {
            return;
        }
        {
            let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
            counts.held.subtract(held);
            counts.used.merge(used);
        }
        if let Some(parent) = &self.parent {
            parent.settle_units(held, used);
        }
    }

    /// Reserves `count` tool calls, after checking every limit that gates them.
    ///
    /// The reservation is all or nothing: a batch that does not fit in the
    /// remaining tool-call budget reserves nothing.
    ///
    /// # Errors
    ///
    /// Returns the violation when the batch does not fit, or when the token,
    /// cost or wall-time limit is reached in this tracker or an ancestor.
    pub fn begin_tool_calls(&self, count: u64) -> std::result::Result<(), BudgetExceeded> {
        self.check()?;
        if count == 0 {
            return Ok(());
        }
        self.reserve(Counter::ToolCalls, count)
    }

    /// Returns `count` reserved tool calls that did not run, in this tracker and its
    /// ancestors.
    ///
    /// An agent releases the calls it held for confirmation: a held call has not run, and
    /// it is reserved again when a later run resumes it, so it counts once.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{BudgetTracker, RunBudget};
    ///
    /// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(1));
    /// tracker.begin_tool_calls(1).unwrap();
    /// tracker.release_tool_calls(1);
    /// assert_eq!(tracker.usage().tool_calls, 0);
    /// assert!(tracker.begin_tool_calls(1).is_ok());
    /// ```
    pub fn release_tool_calls(&self, count: u64) {
        if count == 0 {
            return;
        }
        let _ = self.tool_calls.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
            Some(used.saturating_sub(count))
        });
        if let Some(parent) = &self.parent {
            parent.release_tool_calls(count);
        }
    }

    /// Tool calls left before the tool-call limit is reached, across this tracker
    /// and its ancestors. `None` when no tracker in the chain limits tool calls.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{BudgetTracker, RunBudget};
    ///
    /// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(3));
    /// tracker.begin_tool_calls(2).unwrap();
    /// assert_eq!(tracker.tool_calls_remaining(), Some(1));
    /// assert_eq!(BudgetTracker::new(RunBudget::new()).tool_calls_remaining(), None);
    /// ```
    pub fn tool_calls_remaining(&self) -> Option<u64> {
        let own = self
            .budget
            .max_tool_calls
            .map(|max| max.saturating_sub(self.tool_calls.load(Ordering::SeqCst)));
        let parent = self.parent.as_ref().and_then(|parent| parent.tool_calls_remaining());
        match (own, parent) {
            (Some(own), Some(parent)) => Some(own.min(parent)),
            (own, parent) => own.or(parent),
        }
    }

    /// What is left of each limit across this tracker and its ancestors: for every limit
    /// the chain sets, the smallest of `max − used`; `None` where no tracker limits it. A
    /// unit's units held by open calls count as used. `allow_unpriced_models` is this
    /// tracker's own.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use adk_core::{BudgetTracker, RunBudget};
    ///
    /// let run = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(10)));
    /// let team = BudgetTracker::with_parent(RunBudget::new().max_model_calls(4), run);
    /// team.begin_tool_calls(3).unwrap();
    /// let left = team.remaining();
    /// assert_eq!((left.max_tool_calls, left.max_model_calls), (Some(7), Some(4)));
    /// assert_eq!(left.max_cost_micro_usd, None);
    /// ```
    pub fn remaining(&self) -> RunBudget {
        let usage = self.usage();
        let left = |max: Option<u64>, used: u64| max.map(|max| max.saturating_sub(used));
        let own = RunBudget {
            max_model_calls: left(self.budget.max_model_calls, usage.model_calls),
            max_total_tokens: left(self.budget.max_total_tokens, usage.total_tokens),
            max_cost_micro_usd: left(self.budget.max_cost_micro_usd, usage.cost_micro_usd),
            max_wall_time: self.budget.max_wall_time.map(|max| max.saturating_sub(usage.elapsed)),
            max_tool_calls: left(self.budget.max_tool_calls, usage.tool_calls),
            allow_unpriced_models: self.budget.allow_unpriced_models,
            max_units: {
                let counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
                self.budget
                    .max_units
                    .iter()
                    .map(|(&unit, &max)| {
                        let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
                        (unit, max.saturating_sub(used))
                    })
                    .collect()
            },
        };
        match &self.parent {
            Some(parent) => {
                let mut chain = own.narrowed(&parent.remaining());
                chain.allow_unpriced_models = self.budget.allow_unpriced_models;
                chain
            }
            None => own,
        }
    }

    /// Carves a budget for work that spends on counters of its own — a background
    /// sub-agent's durable run — out of what this tracker and its ancestors have left, so
    /// the two together never spend more than the chain allows.
    ///
    /// | Limit | The slice |
    /// |-------|-----------|
    /// | Asked for and limited by the chain | The smaller of the ask and what is left |
    /// | Asked for, not limited by the chain | The ask |
    /// | Not asked for, limited by the chain | Half of what is left |
    /// | Neither | Unlimited |
    /// | Wall time | The smaller of the ask and what is left; not reserved, since it is not spent |
    ///
    /// Each unit of [`RunBudget::max_units`] is carved the same way. Model calls, tokens,
    /// cost, tool calls and units of the slice that the chain limits count as used by this
    /// tracker and its ancestors from now on, whether the work spends them or not. Unpriced models count as free in the slice only when the chain allows it under a
    /// cost cap, or when no tracker in the chain caps cost and the ask allows it.
    ///
    /// # Errors
    ///
    /// Returns the exhausted limit when the chain has nothing left of a limit it sets, or
    /// a violation was recorded; nothing is reserved then.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{BudgetTracker, RunBudget};
    ///
    /// let parent = BudgetTracker::new(RunBudget::new().max_model_calls(30).max_cost_micro_usd(1_000_000));
    /// let slice = parent.carve(&RunBudget::new().max_model_calls(10)).unwrap();
    /// assert_eq!(slice.max_model_calls, Some(10));
    /// assert_eq!(slice.max_cost_micro_usd, Some(500_000), "half of what is left");
    /// assert_eq!(parent.remaining().max_model_calls, Some(20));
    /// assert_eq!(parent.remaining().max_cost_micro_usd, Some(500_000));
    /// ```
    pub fn carve(&self, ask: &RunBudget) -> std::result::Result<RunBudget, BudgetExceeded> {
        self.check()?;
        let left = self.remaining();
        let pick = |ask: Option<u64>, left: Option<u64>| match (ask, left) {
            (Some(ask), Some(left)) => Some(ask.min(left)),
            (Some(ask), None) => Some(ask),
            (None, Some(left)) => Some(left.div_ceil(2)),
            (None, None) => None,
        };
        let capped = left.max_cost_micro_usd.is_some();
        let slice = RunBudget {
            max_model_calls: pick(ask.max_model_calls, left.max_model_calls),
            max_total_tokens: pick(ask.max_total_tokens, left.max_total_tokens),
            max_cost_micro_usd: pick(ask.max_cost_micro_usd, left.max_cost_micro_usd),
            max_wall_time: match (ask.max_wall_time, left.max_wall_time) {
                (Some(ask), Some(left)) => Some(ask.min(left)),
                (ask, left) => ask.or(left),
            },
            max_tool_calls: pick(ask.max_tool_calls, left.max_tool_calls),
            allow_unpriced_models: if capped {
                self.unpriced_allowed_in_chain()
            } else {
                ask.allow_unpriced_models
            },
            max_units: UsageUnit::ALL
                .into_iter()
                .filter_map(|unit| {
                    pick(ask.max_units.get(&unit).copied(), left.max_units.get(&unit).copied())
                        .map(|max| (unit, max))
                })
                .collect(),
        };
        let usage = self.usage();
        let exhausted = |limit: BudgetLimit, slice: Option<u64>, used: u64| {
            (slice == Some(0)).then(|| BudgetExceeded::reached(limit, used, used))
        };
        if let Some(violation) = exhausted(
            BudgetLimit::ModelCalls,
            slice.max_model_calls.filter(|_| left.max_model_calls.is_some()),
            usage.model_calls,
        )
        .or_else(|| {
            exhausted(
                BudgetLimit::TotalTokens,
                slice.max_total_tokens.filter(|_| left.max_total_tokens.is_some()),
                usage.total_tokens,
            )
        })
        .or_else(|| {
            exhausted(
                BudgetLimit::Cost,
                slice.max_cost_micro_usd.filter(|_| left.max_cost_micro_usd.is_some()),
                usage.cost_micro_usd,
            )
        })
        .or_else(|| {
            exhausted(
                BudgetLimit::ToolCalls,
                slice.max_tool_calls.filter(|_| left.max_tool_calls.is_some()),
                usage.tool_calls,
            )
        })
        .or_else(|| {
            (slice.max_wall_time == Some(Duration::ZERO)).then(|| {
                let elapsed = duration_ms(usage.elapsed);
                BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, elapsed)
            })
        })
        .or_else(|| {
            left.max_units.keys().find(|unit| slice.max_units.get(unit) == Some(&0)).map(|&unit| {
                let used = self.units().get(unit);
                BudgetExceeded::reached(BudgetLimit::Units(unit), used, used)
            })
        }) {
            return Err(violation);
        }
        // The unit hold comes first: it is the one reservation a concurrent call can refuse.
        self.hold_units(
            &slice
                .max_units
                .iter()
                .filter(|(unit, _)| left.max_units.contains_key(unit))
                .map(|(&unit, &max)| (unit, max))
                .collect(),
        )?;
        let reserve = |counter: Counter, slice: Option<u64>, limited: Option<u64>| {
            if let (Some(amount), Some(_)) = (slice, limited) {
                self.add(counter, amount);
            }
        };
        reserve(Counter::ModelCalls, slice.max_model_calls, left.max_model_calls);
        reserve(Counter::TotalTokens, slice.max_total_tokens, left.max_total_tokens);
        reserve(Counter::Cost, slice.max_cost_micro_usd, left.max_cost_micro_usd);
        reserve(Counter::ToolCalls, slice.max_tool_calls, left.max_tool_calls);
        Ok(slice)
    }

    /// Whether every tracker in the chain that caps cost counts unpriced models as free.
    fn unpriced_allowed_in_chain(&self) -> bool {
        let own = self.budget.max_cost_micro_usd.is_none() || self.budget.allow_unpriced_models;
        own && self.parent.as_ref().is_none_or(|parent| parent.unpriced_allowed_in_chain())
    }

    /// Counts usage carried by an event that no call site metered.
    ///
    /// Partial events and events already marked with [`BUDGET_RECORDED_KEY`]
    /// are skipped. Otherwise the event's usage counts as one model call and its
    /// function calls as tool calls, and the event is marked so an outer
    /// tracker does not count it again. Use this where events from agents that
    /// call models directly — custom or remote agents — pass through.
    ///
    /// # Errors
    ///
    /// Returns the violation when a recorded violation exists or when usage now
    /// exceeds a limit.
    pub fn record_event(&self, event: &mut Event) -> std::result::Result<(), BudgetExceeded> {
        if event.llm_response.partial || event.provider_metadata.contains_key(BUDGET_RECORDED_KEY) {
            return self.check_chain(Strictness::Exceeded);
        }
        let usage = event.llm_response.usage_metadata.clone();
        let tool_calls = event.tool_calls().len() as u64;
        if usage.is_none() && tool_calls == 0 {
            return self.check_chain(Strictness::Exceeded);
        }
        if let Some(usage) = usage {
            self.add(Counter::ModelCalls, 1);
            let model =
                event.llm_response.model.clone().unwrap_or_else(|| "unattributed".to_string());
            self.record_usage(&model, Some(&usage));
        }
        self.add(Counter::ToolCalls, tool_calls);
        event.provider_metadata.insert(BUDGET_RECORDED_KEY.to_string(), "true".to_string());
        self.check_chain(Strictness::Exceeded)
    }

    fn check_chain(&self, strictness: Strictness) -> std::result::Result<(), BudgetExceeded> {
        if let Some(exceeded) = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone() {
            return Err(exceeded);
        }
        if let Some(violation) = self.limit_violation(strictness) {
            return Err(violation);
        }
        match &self.parent {
            Some(parent) => parent.check_chain(strictness),
            None => Ok(()),
        }
    }

    fn limit_violation(&self, strictness: Strictness) -> Option<BudgetExceeded> {
        let usage = self.usage();
        let over = |used: u64, max: u64| match strictness {
            Strictness::Reached => used >= max,
            Strictness::Exceeded => used > max,
        };
        if let Some(max) = self.budget.max_total_tokens
            && over(usage.total_tokens, max)
        {
            return Some(BudgetExceeded::reached(
                BudgetLimit::TotalTokens,
                usage.total_tokens,
                max,
            ));
        }
        if let Some(max) = self.budget.max_cost_micro_usd
            && over(usage.cost_micro_usd, max)
        {
            return Some(BudgetExceeded::reached(BudgetLimit::Cost, usage.cost_micro_usd, max));
        }
        if let Some(max) = self.budget.max_wall_time {
            let elapsed = duration_ms(usage.elapsed);
            let max = duration_ms(max);
            if over(elapsed, max) {
                return Some(BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, max));
            }
        }
        if strictness == Strictness::Exceeded {
            if let Some(max) = self.budget.max_model_calls
                && usage.model_calls > max
            {
                return Some(BudgetExceeded::reached(
                    BudgetLimit::ModelCalls,
                    usage.model_calls,
                    max,
                ));
            }
            if let Some(max) = self.budget.max_tool_calls
                && usage.tool_calls > max
            {
                return Some(BudgetExceeded::reached(
                    BudgetLimit::ToolCalls,
                    usage.tool_calls,
                    max,
                ));
            }
        }
        None
    }

    fn remember(&self, violation: BudgetExceeded) -> BudgetExceeded {
        let mut slot = self.exceeded.lock().unwrap_or_else(|e| e.into_inner());
        slot.get_or_insert(violation).clone()
    }

    fn counter(&self, counter: Counter) -> &AtomicU64 {
        match counter {
            Counter::ModelCalls => &self.model_calls,
            Counter::ToolCalls => &self.tool_calls,
            Counter::TotalTokens => &self.total_tokens,
            Counter::Cost => &self.cost_micro_usd,
        }
    }

    fn reserve(&self, counter: Counter, count: u64) -> std::result::Result<(), BudgetExceeded> {
        let max = match counter {
            Counter::ModelCalls => self.budget.max_model_calls,
            Counter::ToolCalls => self.budget.max_tool_calls,
            Counter::TotalTokens | Counter::Cost => None,
        };
        let atomic = self.counter(counter);
        let reserved = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
            let next = used.saturating_add(count);
            match max {
                Some(max) if next > max => None,
                _ => Some(next),
            }
        });
        if let Err(used) = reserved {
            let max = max.unwrap_or_default();
            let violation = match counter {
                Counter::ToolCalls if count > 1 => BudgetExceeded::tool_batch(used, count, max),
                Counter::ToolCalls => BudgetExceeded::reached(BudgetLimit::ToolCalls, used, max),
                Counter::ModelCalls | Counter::TotalTokens | Counter::Cost => {
                    BudgetExceeded::reached(BudgetLimit::ModelCalls, used, max)
                }
            };
            return Err(violation);
        }
        if let Some(parent) = &self.parent
            && let Err(violation) = parent.reserve(counter, count)
        {
            atomic.fetch_sub(count, Ordering::SeqCst);
            return Err(violation);
        }
        Ok(())
    }

    fn add(&self, counter: Counter, amount: u64) {
        if amount == 0 {
            return;
        }
        let atomic = self.counter(counter);
        let _ = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
            Some(used.saturating_add(amount))
        });
        if let Some(parent) = &self.parent {
            parent.add(counter, amount);
        }
    }

    /// Adds one call's usage to this tracker and its ancestors.
    fn record_usage(&self, model: &str, usage: Option<&UsageMetadata>) {
        match usage {
            Some(usage) => {
                self.add(Counter::TotalTokens, u64::try_from(usage.total_token_count).unwrap_or(0));
                self.add(Counter::ToolCalls, usage.builtin_tool_use_count());
                let count = |tokens: i32| u64::try_from(tokens).unwrap_or(0);
                self.settle_units(
                    &UsageVector::new(),
                    &UsageVector::new()
                        .with(UsageUnit::InputTokens, count(usage.prompt_token_count))
                        .with(UsageUnit::OutputTokens, count(usage.candidates_token_count)),
                );
                match usage.cost {
                    Some(cost) => self.add(Counter::Cost, usd_to_micro(cost)),
                    None => self.flag_unpriced(model),
                }
            }
            None => {
                self.flag_unpriced(model);
                self.flag_untokened(model);
            }
        }
    }

    fn flag_unpriced(&self, model: &str) {
        if let Some(max) = self.budget.max_cost_micro_usd
            && !self.budget.allow_unpriced_models
        {
            let used = self.cost_micro_usd.load(Ordering::SeqCst);
            self.remember(BudgetExceeded::unpriced(model, used, max));
        }
        if let Some(parent) = &self.parent {
            parent.flag_unpriced(model);
        }
    }

    fn flag_untokened(&self, model: &str) {
        if let Some(max) = self.budget.max_total_tokens {
            let used = self.total_tokens.load(Ordering::SeqCst);
            self.remember(BudgetExceeded::untokened(model, used, max));
        }
        if let Some(parent) = &self.parent {
            parent.flag_untokened(model);
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Strictness {
    /// Usage equal to the limit fails: gates new work.
    Reached,
    /// Only usage above the limit fails: audits work that already happened.
    Exceeded,
}

#[derive(Debug, Clone, Copy)]
enum Counter {
    ModelCalls,
    ToolCalls,
    TotalTokens,
    Cost,
}

/// Records the usage of one model call into a [`BudgetTracker`].
///
/// Feed every response of the call to [`observe`](Self::observe). The meter
/// records once: at the first non-partial response that carries usage, or —
/// when the stream ends early or carries usage only on partial chunks — when
/// the meter is dropped, from the last usage it saw. Created by
/// [`BudgetTracker::begin_model_call`].
#[derive(Debug)]
pub struct ModelCallMeter {
    tracker: Arc<BudgetTracker>,
    model: String,
    fallback: Option<(String, UsageMetadata)>,
    responses_seen: bool,
    settled: bool,
}

impl ModelCallMeter {
    /// Observes one response of the call.
    pub fn observe(&mut self, response: &LlmResponse) {
        if self.settled {
            return;
        }
        self.responses_seen = true;
        let Some(usage) = &response.usage_metadata else {
            return;
        };
        let model = response.model.clone().unwrap_or_else(|| self.model.clone());
        if response.partial {
            self.fallback = Some((model, usage.clone()));
            return;
        }
        self.settled = true;
        self.tracker.record_usage(&model, Some(usage));
    }

    /// Returns `true` once the call's usage has been recorded.
    pub fn is_settled(&self) -> bool {
        self.settled
    }

    /// Records the call now, from the best usage observed so far.
    pub fn finish(mut self) {
        self.settle();
    }

    fn settle(&mut self) {
        if self.settled {
            return;
        }
        self.settled = true;
        if !self.responses_seen {
            return;
        }
        match self.fallback.take() {
            Some((model, usage)) => self.tracker.record_usage(&model, Some(&usage)),
            None => self.tracker.record_usage(&self.model, None),
        }
    }
}

impl Drop for ModelCallMeter {
    fn drop(&mut self) {
        self.settle();
    }
}

/// Wraps a model response stream so that `meter` observes every response and
/// records the call when the stream ends or is dropped.
pub fn meter_stream(stream: LlmResponseStream, meter: ModelCallMeter) -> LlmResponseStream {
    Box::pin(MeteredStream { inner: stream, meter: Some(meter) })
}

struct MeteredStream {
    inner: LlmResponseStream,
    meter: Option<ModelCallMeter>,
}

impl Stream for MeteredStream {
    type Item = Result<LlmResponse>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let item = self.inner.as_mut().poll_next(cx);
        match &item {
            Poll::Ready(Some(Ok(response))) => {
                if let Some(meter) = self.meter.as_mut() {
                    meter.observe(response);
                }
            }
            Poll::Ready(None) => {
                self.meter.take();
            }
            Poll::Ready(Some(Err(_))) | Poll::Pending => {}
        }
        item
    }
}

/// Calls `model` under `tracker`, when there is one.
///
/// Reserves the call before it starts and meters the returned stream. Agents
/// that call models directly use this so their calls count against the run
/// budget.
///
/// # Errors
///
/// Returns a [`ErrorCategory::ResourceExhausted`] error when the budget does
/// not allow another model call, or the model's own error.
///
/// # Example
///
/// ```rust,ignore
/// let tracker = ctx.run_config().budget_tracker.clone();
/// let stream = adk_core::generate_with_budget(model.as_ref(), request, false, tracker.as_ref()).await?;
/// ```
pub async fn generate_with_budget(
    model: &dyn Llm,
    request: LlmRequest,
    stream: bool,
    tracker: Option<&Arc<BudgetTracker>>,
) -> Result<LlmResponseStream> {
    let Some(tracker) = tracker else {
        return model.generate_content(request, stream).await;
    };
    let meter = tracker.begin_model_call(model.name())?;
    let responses = model.generate_content(request, stream).await?;
    Ok(meter_stream(responses, meter))
}

/// Builds the event that explains why a run stopped on a budget.
///
/// Returns `None` unless `error` has category
/// [`ErrorCategory::ResourceExhausted`]. The event is non-partial and
/// turn-complete, carries the error code and message in
/// `llm_response.error_code` / `error_message`, and names the limit under
/// [`BUDGET_LIMIT_KEY`].
///
/// # Example
///
/// ```
/// use adk_core::{AdkError, BudgetTracker, RunBudget, budget_exceeded_event};
///
/// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(0));
/// let error: AdkError = tracker.begin_tool_calls(1).unwrap_err().into();
/// let event = budget_exceeded_event("inv-1", "assistant", &error).unwrap();
/// assert_eq!(event.llm_response.error_code.as_deref(), Some("budget.tool_calls"));
/// assert_eq!(event.provider_metadata["adk.budget.limit"], "tool_calls");
/// ```
pub fn budget_exceeded_event(invocation_id: &str, author: &str, error: &AdkError) -> Option<Event> {
    if error.category != ErrorCategory::ResourceExhausted {
        return None;
    }
    let mut event = Event::new(invocation_id);
    event.author = author.to_string();
    event.llm_response.partial = false;
    event.llm_response.turn_complete = true;
    event.llm_response.finish_reason = Some(crate::FinishReason::Other);
    event.llm_response.error_code = Some(error.code.to_string());
    event.llm_response.error_message = Some(error.message.clone());
    if let Some(limit) = error.details.metadata.get("limit").and_then(|value| value.as_str()) {
        event.provider_metadata.insert(BUDGET_LIMIT_KEY.to_string(), limit.to_string());
    }
    Some(event)
}

fn usd_to_micro(usd: f64) -> u64 {
    if !usd.is_finite() || usd <= 0.0 {
        return 0;
    }
    let micro = (usd * 1_000_000.0).round();
    if micro >= u64::MAX as f64 { u64::MAX } else { micro as u64 }
}

fn duration_ms(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn format_micro_usd(micro: u64) -> String {
    format!("${}.{:06}", micro / 1_000_000, micro % 1_000_000)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Content, Part};

    fn usage(total: i32, cost: Option<f64>) -> UsageMetadata {
        UsageMetadata {
            prompt_token_count: total / 2,
            candidates_token_count: total - total / 2,
            total_token_count: total,
            cost,
            ..Default::default()
        }
    }

    fn response(partial: bool, usage: Option<UsageMetadata>) -> LlmResponse {
        LlmResponse {
            partial,
            usage_metadata: usage,
            model: Some("gemini-3.7-flash".to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn builtin_tool_uses_count_as_tool_calls_and_refuse_the_next_turn_once_over() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(2)));
        let mut searched = usage(10, Some(0.0));
        searched.builtin_tool_uses = vec![crate::BuiltinToolUse::new("web_search", 2)];
        let mut meter = tracker.begin_model_call("m").unwrap();
        meter.observe(&response(false, Some(searched.clone())));
        drop(meter);
        assert_eq!(tracker.usage().tool_calls, 2);
        assert_eq!(tracker.tool_calls_remaining(), Some(0));
        // Reaching the limit still allows a model turn that answers without tools.
        let mut meter = tracker.begin_model_call("m").unwrap();
        meter.observe(&response(false, Some(searched)));
        drop(meter);
        assert_eq!(tracker.usage().tool_calls, 4);
        let error = tracker.begin_model_call("m").unwrap_err();
        assert_eq!(error.limit(), BudgetLimit::ToolCalls);
    }

    #[test]
    fn tool_calls_remaining_takes_the_tightest_ancestor() {
        let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(1)));
        let child = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(5), parent);
        assert_eq!(child.tool_calls_remaining(), Some(1));
        child.begin_tool_calls(1).unwrap();
        assert_eq!(child.tool_calls_remaining(), Some(0));
    }

    #[test]
    fn model_call_limit_blocks_the_next_call() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
        tracker.begin_model_call("m").unwrap().finish();
        tracker.begin_model_call("m").unwrap().finish();
        let error = tracker.begin_model_call("m").unwrap_err();
        assert_eq!(error.limit(), BudgetLimit::ModelCalls);
        assert_eq!(tracker.usage().model_calls, 2);
    }

    #[test]
    fn partial_chunks_do_not_add_usage() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let mut meter = tracker.begin_model_call("gemini-3.7-flash").unwrap();
        // Gemini repeats cumulative usage on every chunk.
        meter.observe(&response(true, Some(usage(100, Some(0.001)))));
        meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
        meter.observe(&response(false, Some(usage(200, Some(0.002)))));
        meter.observe(&response(false, Some(usage(200, Some(0.002)))));
        drop(meter);
        let usage = tracker.usage();
        assert_eq!((usage.model_calls, usage.total_tokens, usage.cost_micro_usd), (1, 200, 2_000));
    }

    #[test]
    fn a_cut_stream_records_its_last_partial_usage() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let mut meter = tracker.begin_model_call("m").unwrap();
        meter.observe(&response(true, Some(usage(100, Some(0.001)))));
        meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
        drop(meter);
        assert_eq!(tracker.usage().total_tokens, 150);
        assert_eq!(tracker.usage().cost_micro_usd, 1_500);
    }

    #[test]
    fn cost_cap_stops_once_reached() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(0.003)));
        for _ in 0..3 {
            let mut meter = tracker.begin_model_call("m").unwrap();
            meter.observe(&response(false, Some(usage(10, Some(0.001)))));
        }
        let error = tracker.begin_model_call("m").unwrap_err();
        assert_eq!(error.limit(), BudgetLimit::Cost);
        assert_eq!(error.code(), "budget.cost");
        assert_eq!(error.used(), 3_000);
        assert!(tracker.begin_tool_calls(1).is_err());
    }

    #[test]
    fn unknown_cost_under_a_cap_fails_closed() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(10.0)));
        let mut meter = tracker.begin_model_call("mystery-model").unwrap();
        meter.observe(&response(false, Some(usage(10, None))));
        let error = tracker.begin_model_call("mystery-model").unwrap_err();
        assert_eq!(error.code(), "budget.cost_unknown");
        assert!(error.message().contains("cost unknown for model 'gemini-3.7-flash'"));

        let allowed = Arc::new(BudgetTracker::new(
            RunBudget::new().max_cost_usd(10.0).allow_unpriced_models(),
        ));
        let mut meter = allowed.begin_model_call("mystery-model").unwrap();
        meter.observe(&response(false, Some(usage(10, None))));
        drop(meter);
        assert!(allowed.begin_model_call("mystery-model").is_ok());
    }

    #[test]
    fn missing_usage_under_a_token_cap_fails_closed() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_total_tokens(100)));
        let mut meter = tracker.begin_model_call("silent").unwrap();
        meter.observe(&response(false, None));
        drop(meter);
        assert_eq!(tracker.check().unwrap_err().code(), "budget.tokens_unknown");
    }

    #[test]
    fn tool_batches_are_all_or_nothing() {
        let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(3));
        tracker.begin_tool_calls(2).unwrap();
        let error = tracker.begin_tool_calls(2).unwrap_err();
        assert_eq!(error.limit(), BudgetLimit::ToolCalls);
        assert_eq!(tracker.usage().tool_calls, 2);
        tracker.begin_tool_calls(1).unwrap();
        assert!(tracker.begin_tool_calls(1).is_err());
    }

    #[test]
    fn wall_time_is_checked_at_every_checkpoint() {
        let tracker = Arc::new(BudgetTracker::resume(
            RunBudget::new().max_wall_time(Duration::from_millis(50)),
            BudgetUsage { elapsed: Duration::from_millis(60), ..Default::default() },
            None,
        ));
        assert_eq!(tracker.begin_model_call("m").unwrap_err().limit(), BudgetLimit::WallTime);
        assert_eq!(tracker.begin_tool_calls(1).unwrap_err().limit(), BudgetLimit::WallTime);
    }

    #[test]
    fn child_trackers_count_against_their_parent() {
        let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
        let child = Arc::new(BudgetTracker::with_parent(
            RunBudget::new().max_model_calls(5),
            parent.clone(),
        ));
        child.begin_model_call("m").unwrap().finish();
        parent.begin_model_call("m").unwrap().finish();
        let error = child.begin_model_call("m").unwrap_err();
        assert_eq!(error.limit(), BudgetLimit::ModelCalls);
        // The failed parent reservation rolled the child back.
        assert_eq!(child.usage().model_calls, 1);
        assert_eq!(parent.usage().model_calls, 2);
    }

    #[test]
    fn record_event_counts_unmetered_events_once() {
        let tracker = BudgetTracker::new(RunBudget::new());
        let mut event = Event::new("inv");
        event.llm_response.usage_metadata = Some(usage(40, Some(0.004)));
        event.llm_response.content = Some(Content {
            role: "model".to_string(),
            parts: vec![Part::FunctionCall {
                name: "lookup".to_string(),
                args: serde_json::json!({}),
                id: None,
                thought_signature: None,
            }],
        });
        tracker.record_event(&mut event).unwrap();
        tracker.record_event(&mut event).unwrap();
        let mut partial = Event::new("inv");
        partial.llm_response.partial = true;
        partial.llm_response.usage_metadata = Some(usage(999, Some(9.0)));
        tracker.record_event(&mut partial).unwrap();
        let usage = tracker.usage();
        assert_eq!(
            (usage.model_calls, usage.total_tokens, usage.cost_micro_usd, usage.tool_calls),
            (1, 40, 4_000, 1)
        );
        assert_eq!(event.provider_metadata[BUDGET_RECORDED_KEY], "true");
    }

    #[test]
    fn violations_convert_to_resource_exhausted_errors() {
        let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(0));
        let error: AdkError = tracker.begin_tool_calls(1).unwrap_err().into();
        assert_eq!(error.category, ErrorCategory::ResourceExhausted);
        assert_eq!(error.code, "budget.tool_calls");
        assert!(!error.is_retryable());
        assert_eq!(error.details.metadata["limit"], "tool_calls");
        let event = budget_exceeded_event("inv", "agent", &error).unwrap();
        assert!(!event.llm_response.partial);
        assert_eq!(event.llm_response.error_message.as_deref(), Some(error.message.as_str()));
        assert!(budget_exceeded_event("inv", "agent", &AdkError::agent("other")).is_none());
    }

    #[tokio::test]
    async fn metered_streams_record_on_completion() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let meter = tracker.begin_model_call("m").unwrap();
        let responses: Vec<Result<LlmResponse>> = vec![
            Ok(response(true, Some(usage(5, Some(0.0005))))),
            Ok(response(false, Some(usage(10, Some(0.001))))),
        ];
        let stream = meter_stream(Box::pin(futures::stream::iter(responses)), meter);
        let collected: Vec<_> = futures::StreamExt::collect(stream).await;
        assert_eq!(collected.len(), 2);
        assert_eq!(tracker.usage().total_tokens, 10);
        assert_eq!(tracker.usage().cost_micro_usd, 1_000);
    }

    #[test]
    fn a_carved_slice_never_takes_the_chain_past_its_limits() {
        let run = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(10)));
        let team = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(6), Arc::clone(&run));
        let slice = team.carve(&RunBudget::new().max_model_calls(4).max_tool_calls(100)).unwrap();
        assert_eq!(slice.max_model_calls, Some(4));
        assert_eq!(slice.max_tool_calls, Some(6), "the team's tool limit caps the ask");
        // The slice counts in every tracker of the chain.
        assert_eq!(run.usage().model_calls, 4);
        assert_eq!(team.remaining().max_tool_calls, Some(0));
        assert_eq!(team.remaining().max_model_calls, Some(6));
        // Nothing of a limited resource left: the carve fails and reserves nothing.
        let refused = team.carve(&RunBudget::new()).unwrap_err();
        assert_eq!(refused.limit(), BudgetLimit::ToolCalls);
        assert_eq!(run.usage().model_calls, 4);
    }

    #[test]
    fn a_slice_counts_unpriced_models_as_free_only_where_the_chain_does() {
        let capped = BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000));
        let ask = RunBudget::new().allow_unpriced_models();
        assert!(!capped.carve(&ask).unwrap().allow_unpriced_models);
        let lenient =
            BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000).allow_unpriced_models());
        assert!(lenient.carve(&RunBudget::new()).unwrap().allow_unpriced_models);
        let open = BudgetTracker::new(RunBudget::new());
        assert!(open.carve(&ask).unwrap().allow_unpriced_models);
        assert_eq!(open.carve(&RunBudget::new()).unwrap(), RunBudget::new());
    }

    #[test]
    fn a_budget_round_trips_with_its_wall_time_in_milliseconds() {
        let budget =
            RunBudget::new().max_model_calls(3).max_wall_time(Duration::from_millis(1_500));
        let json = serde_json::to_value(&budget).unwrap();
        assert_eq!(json, serde_json::json!({ "maxModelCalls": 3, "maxWallTimeMs": 1500 }));
        assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), budget);
        assert_eq!(
            serde_json::from_value::<RunBudget>(serde_json::json!({})).unwrap(),
            RunBudget::new()
        );
    }

    fn images(count: u64) -> UsageVector {
        UsageVector::new().with(UsageUnit::Images, count)
    }

    #[test]
    fn a_unit_hold_past_its_cap_is_refused_naming_the_unit_and_the_cap() {
        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 2));
        tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
        tracker.record_units("sam-3.1", &images(1), &images(1), Some(2_500));
        tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
        let refused = tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err();
        assert_eq!(refused.limit(), BudgetLimit::Units(UsageUnit::Images));
        assert_eq!((refused.used(), refused.max()), (2, 2));
        assert_eq!(refused.code(), "budget.units");
        assert!(refused.message().contains("cap of 2 images"), "{}", refused.message());
        let error = AdkError::from(refused);
        assert_eq!(error.details.metadata["limit"], "units.images");
        assert_eq!(error.details.metadata["unit"], "images");
        // The open hold counts against the cap; returning it frees the room.
        tracker.release_units(&images(1));
        assert!(tracker.begin_usage("sam-3.1", true, &images(1)).is_ok());
        assert_eq!(tracker.units(), images(1), "only committed units are usage");
    }

    #[test]
    fn a_commit_replaces_the_hold_with_what_the_call_used() {
        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Frames, 100));
        let frames = |count| UsageVector::new().with(UsageUnit::Frames, count);
        tracker.begin_usage("sam-3.1", true, &frames(80)).unwrap();
        assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 20);
        tracker.record_units("sam-3.1", &frames(80), &frames(30), Some(6_000));
        assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 70);
        assert_eq!(tracker.units(), frames(30));
    }

    #[test]
    fn uncapped_units_and_undeclared_calls_are_never_held_back() {
        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 1));
        tracker
            .begin_usage("tts", true, &UsageVector::new().with(UsageUnit::Characters, 9_000))
            .unwrap();
        tracker.record_units("sam-3.1", &UsageVector::new(), &images(3), Some(0));
        // Undeclared usage still counts, so the next declaring call sees the cap reached.
        assert!(tracker.begin_usage("sam-3.1", true, &UsageVector::new()).is_ok());
        assert_eq!(
            tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err().limit(),
            BudgetLimit::Units(UsageUnit::Images)
        );
    }

    #[test]
    fn a_child_hold_is_refused_by_its_parents_cap_and_holds_nothing() {
        let run = Arc::new(BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Pages, 5)));
        let team = BudgetTracker::with_parent(
            RunBudget::new().max_units(UsageUnit::Pages, 10),
            Arc::clone(&run),
        );
        let pages = |count| UsageVector::new().with(UsageUnit::Pages, count);
        team.begin_usage("ocr", true, &pages(4)).unwrap();
        let refused = team.begin_usage("ocr", true, &pages(2)).unwrap_err();
        assert_eq!((refused.limit(), refused.max()), (BudgetLimit::Units(UsageUnit::Pages), 5));
        assert_eq!(team.remaining().max_units[&UsageUnit::Pages], 1);
        team.record_units("ocr", &pages(4), &pages(4), Some(0));
        assert_eq!((team.units(), run.units()), (pages(4), pages(4)));
    }

    #[test]
    fn unit_caps_narrow_carve_and_round_trip() {
        let runner = RunBudget::new().max_units(UsageUnit::Images, 50);
        let run =
            RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600);
        let narrowed = runner.narrowed(&run);
        assert_eq!(
            narrowed,
            RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600)
        );
        assert!(!narrowed.is_unlimited());

        let parent = BudgetTracker::new(narrowed.clone());
        let slice = parent.carve(&RunBudget::new().max_units(UsageUnit::Images, 8)).unwrap();
        assert_eq!(slice.max_units[&UsageUnit::Images], 8);
        assert_eq!(slice.max_units[&UsageUnit::Frames], 300, "half of what is left");
        assert_eq!(parent.remaining().max_units[&UsageUnit::Images], 12);
        assert_eq!(parent.units(), UsageVector::new(), "a carved slice is held, not used");
        let exhausted = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 0));
        assert_eq!(
            exhausted.carve(&RunBudget::new()).unwrap_err().limit(),
            BudgetLimit::Units(UsageUnit::Images)
        );

        let json = serde_json::to_value(&narrowed).unwrap();
        assert_eq!(json, serde_json::json!({ "maxUnits": { "images": 20, "frames": 600 } }));
        assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), narrowed);
    }
}