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
//! Metering for every model call made on behalf of a run.
//!
//! `LlmAgent` and `CodeActAgent` turns, context compaction summaries, MCP sampling
//! and LLM routing all go through a [`ModelCallScope`], which applies the run's
//! [`BudgetTracker`] and spend ledger as two gates:
//!
//! | Step | Budget ([`RunConfig::budget_tracker`]) | Spend ledger ([`RunConfig::spend_ledger`]) |
//! |------|----------------------------------------|--------------------------------------------|
//! | Before the call | [`BudgetTracker::begin_model_call`] refuses a call over the limit | [`SpendLedger::reserve`] holds the call's upper-bound cost ([`Llm::max_cost_micro_usd`]) or refuses the call |
//! | After the call | the call's usage and cost are counted once | the reported cost is committed under `LlmResponse::provider` |
//! | Call failed | — | the hold is released |
//!
//! A refused call is never sent to the provider.
//!
//! # Hard caps
//!
//! The hold is an upper bound on the call's cost, so the committed cost never exceeds it
//! and a spend cap is never overshot. A call the model cannot bound (an unpriced model)
//! reserves [`UNBOUNDED_HOLD_MICRO_USD`]: any cap that covers the call refuses it, so it
//! runs only where no cap applies, and commits its reported cost or the
//! [`LlmSpendEstimate`] when it reports none.
//!
//! # Reaching the scope
//!
//! - [`ModelCallScope::generate`] meters one call explicitly.
//! - [`ModelCallScope::within`] makes the scope current for a future; inside it,
//!   [`generate_metered`] and [`MeteredLlm`] meter against it. The runner wraps
//!   its compaction calls this way, the MCP client wraps sampling requests, and
//!   `LlmAgent`, `CodeActAgent` and the realtime runtimes wrap every tool call in the
//!   run's scope ([`ModelCallScope::within_tool`]).
//!
//! # Calls billed in units
//!
//! Image generation, transcription and speech synthesis are billed per image, per second
//! of audio or per character, not per token. [`ModelCallScope::meter`] (or
//! [`meter_usage`], against the current scope) applies the same two gates to them:
//!
//! | Step | Budget | Spend ledger |
//! |------|--------|--------------|
//! | Before the call | refuses when a limit is reached, when the call has no known price under a cost cap, or when [`UsageCall::units`] would take a unit past its cap ([`RunBudget::max_units`](crate::RunBudget::max_units)); otherwise holds those units | reserves [`UsageCall::max_cost_micro_usd`], or [`UNBOUNDED_HOLD_MICRO_USD`] without a price |
//! | After the call | counts its cost, tokens and [`UsageVector`] in place of the units it held | commits [`MeteredUsage::cost_micro_usd`] |
//! | Call failed | returns the units it held | the hold is released |
//!
//! Units are counted in the budget ([`BudgetTracker::units`]) and never in the ledger,
//! whose amounts are micro-USD only. A unit call is not a model call.
//!
//! # Example
//!
//! ```
//! use std::sync::Arc;
//! use adk_core::{BudgetTracker, InMemorySpendLedger, ModelCallScope, RunBudget, RunConfig};
//!
//! let config = RunConfig::builder()
//!     .spend_ledger(Arc::new(InMemorySpendLedger::default()))
//!     .build();
//! let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(10)));
//! let scope = ModelCallScope::for_run(&config, "my-app", "assistant").with_budget(tracker);
//! assert!(!scope.is_unmetered());
//! assert_eq!(scope.spend_key("gemini-3.8-flash").unwrap().vendor.as_deref(), Some("gemini"));
//! ```

use std::fmt;
use std::future::Future;
use std::sync::Arc;

use async_trait::async_trait;
use futures::StreamExt;

use crate::{
    BudgetTracker, GovernanceControl, Llm, LlmRequest, LlmResponse, LlmResponseStream,
    ReservationId, Result, RunConfig, SpendKey, SpendLedger, ToolContext, UsageVector,
    budget::meter_stream, schema_adapter::SchemaAdapter, usd_to_micro_usd,
};

/// Hold reserved for a model call whose cost cannot be bounded.
///
/// It exceeds every cap, so a ledger refuses it wherever a limit covers the call, and it
/// fits the signed 64-bit storage of the SQL ledgers.
pub const UNBOUNDED_HOLD_MICRO_USD: u64 = i64::MAX as u64;

/// What an unbounded model call commits when its response reports no cost.
///
/// Calls with a cost bound ([`Llm::max_cost_micro_usd`]) reserve and, when no cost is
/// reported, commit that bound. A call without one reserves [`UNBOUNDED_HOLD_MICRO_USD`],
/// which only an uncapped key accepts, and commits this estimate when its response
/// reports no cost: `max_output_tokens × price` when the request caps output tokens and an
/// output price is set, otherwise `per_call_micro_usd`.
///
/// # Example
///
/// ```rust
/// use adk_core::{LlmRequest, LlmSpendEstimate};
///
/// let estimate = LlmSpendEstimate::per_call(20_000).with_output_price(10_000_000);
/// let mut request = LlmRequest::new("gemini-3.8-flash", vec![]);
/// assert_eq!(estimate.estimate(&request), 20_000);
///
/// request.config = Some(adk_core::GenerateContentConfig {
///     max_output_tokens: Some(4_096),
///     ..Default::default()
/// });
/// assert_eq!(estimate.estimate(&request), 40_960);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LlmSpendEstimate {
    /// Reserved when the request has no output cap or no output price is set.
    pub per_call_micro_usd: u64,
    /// Output price in micro-USD per million tokens, applied to `max_output_tokens`.
    pub output_micro_usd_per_million_tokens: Option<u64>,
}

impl LlmSpendEstimate {
    /// Default per-call hold: 0.05 USD.
    pub const DEFAULT_PER_CALL_MICRO_USD: u64 = 50_000;

    /// Reserves a fixed amount before every call.
    pub fn per_call(micro_usd: u64) -> Self {
        Self { per_call_micro_usd: micro_usd, output_micro_usd_per_million_tokens: None }
    }

    /// Sizes the hold from the request's `max_output_tokens` at this output price.
    pub fn with_output_price(mut self, micro_usd_per_million_tokens: u64) -> Self {
        self.output_micro_usd_per_million_tokens = Some(micro_usd_per_million_tokens);
        self
    }

    /// Returns the amount to reserve for `request`.
    pub fn estimate(&self, request: &LlmRequest) -> u64 {
        let max_output_tokens = request
            .config
            .as_ref()
            .and_then(|config| config.max_output_tokens)
            .and_then(|tokens| u64::try_from(tokens).ok());
        match (max_output_tokens, self.output_micro_usd_per_million_tokens) {
            (Some(tokens), Some(price)) => tokens.saturating_mul(price).div_ceil(1_000_000),
            _ => self.per_call_micro_usd,
        }
    }
}

impl Default for LlmSpendEstimate {
    fn default() -> Self {
        Self::per_call(Self::DEFAULT_PER_CALL_MICRO_USD)
    }
}

/// Vendor a model call is reserved under, read from the model id's family prefix.
///
/// The vendor must be known before the call so a vendor cap can refuse it. Ids routed
/// through an aggregator name the model's maker, not the aggregator; the committed cost
/// moves to the provider the response reports.
///
/// # Example
///
/// ```
/// use adk_core::vendor_for_model;
///
/// assert_eq!(vendor_for_model("models/gemini-3.8-flash"), "gemini");
/// assert_eq!(vendor_for_model("grok-4.6"), "xai");
/// assert_eq!(vendor_for_model("muse-spark-1.3"), "muse");
/// assert_eq!(vendor_for_model("my-fine-tune"), "unknown");
/// ```
pub fn vendor_for_model(model: &str) -> &'static str {
    let name = model.rsplit('/').next().unwrap_or(model).to_ascii_lowercase();
    let starts = |prefixes: &[&str]| prefixes.iter().any(|prefix| name.starts_with(prefix));
    if starts(&["gemini"]) {
        "gemini"
    } else if starts(&["claude"]) {
        "anthropic"
    } else if starts(&["gpt-", "chatgpt", "o1", "o3", "o4", "codex"]) {
        "openai"
    } else if starts(&["deepseek"]) {
        "deepseek"
    } else if starts(&["grok"]) {
        "xai"
    } else if starts(&["mistral", "magistral", "codestral", "devstral", "ministral", "pixtral"]) {
        "mistral"
    } else if starts(&["muse-"]) {
        "muse"
    } else {
        "unknown"
    }
}

/// A spend-ledger hold for one model call, settled from the responses it observes.
///
/// | What the hold observed | Ledger action on [`settle`](Self::settle) |
/// |------------------------|--------------------------------------------|
/// | A response reporting `usage_metadata.cost` | Commit that cost |
/// | Responses, but no cost | Commit the estimate and log a warning |
/// | No response (the call failed) | Release |
///
/// When a response names a provider other than the reserved vendor (for example `bedrock`
/// serving a Claude model), the cost is committed under that provider. If a limit refuses
/// even a zero-amount reservation under the reported provider, the cost is committed under
/// the reserved vendor instead and a warning is logged.
///
/// A hold dropped unsettled settles on the current Tokio runtime; outside a runtime it
/// expires by the ledger's reservation TTL.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use adk_core::{InMemorySpendLedger, LlmResponse, ModelSpendHold, SpendKey, SpendLedger, SpendPeriod, UsageMetadata};
///
/// # async fn demo() -> adk_core::Result<()> {
/// let ledger = Arc::new(InMemorySpendLedger::default());
/// let key = SpendKey::org("acme").with_vendor("gemini");
/// let mut hold = ModelSpendHold::reserve(ledger.clone(), key, 50_000).await?;
///
/// let mut response = LlmResponse::default();
/// response.usage_metadata = Some(UsageMetadata { cost: Some(0.002), ..Default::default() });
/// hold.observe(&response);
/// hold.settle().await;
/// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 2_000);
/// # Ok(())
/// # }
/// ```
pub struct ModelSpendHold {
    inner: Option<HoldState>,
}

struct HoldState {
    ledger: Arc<dyn SpendLedger>,
    reservation: ReservationId,
    key: SpendKey,
    estimate: u64,
    saw_response: bool,
    cost_micro_usd: Option<u64>,
    provider: Option<String>,
}

impl fmt::Debug for ModelSpendHold {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("ModelSpendHold");
        if let Some(state) = &self.inner {
            debug
                .field("reservation", &state.reservation)
                .field("key", &state.key)
                .field("estimate", &state.estimate)
                .field("cost_micro_usd", &state.cost_micro_usd);
        }
        debug.finish_non_exhaustive()
    }
}

impl ModelSpendHold {
    /// Reserves `estimate_micro_usd` under `key`.
    ///
    /// # Errors
    ///
    /// Returns the ledger's error, such as [`SPEND_LIMIT_EXCEEDED_CODE`](crate::SPEND_LIMIT_EXCEEDED_CODE),
    /// when the reservation is refused.
    pub async fn reserve(
        ledger: Arc<dyn SpendLedger>,
        key: SpendKey,
        estimate_micro_usd: u64,
    ) -> Result<Self> {
        let reservation = ledger.reserve(&key, estimate_micro_usd).await.inspect_err(|error| {
            tracing::warn!(error = %error, spend.key = %key, "model call refused by spend ledger");
        })?;
        Ok(Self {
            inner: Some(HoldState {
                ledger,
                reservation,
                key,
                estimate: estimate_micro_usd,
                saw_response: false,
                cost_micro_usd: None,
                provider: None,
            }),
        })
    }

    /// Commits `micro_usd`, instead of the reserved amount, when no response reports a cost.
    pub fn with_unpriced_commit(mut self, micro_usd: u64) -> Self {
        if let Some(state) = self.inner.as_mut() {
            state.estimate = micro_usd;
        }
        self
    }

    /// The key the hold was reserved under.
    pub fn key(&self) -> Option<&SpendKey> {
        self.inner.as_ref().map(|state| &state.key)
    }

    /// Records the cost and provider a response reports.
    pub fn observe(&mut self, response: &LlmResponse) {
        let Some(state) = self.inner.as_mut() else {
            return;
        };
        state.saw_response = true;
        if let Some(cost) = response.usage_metadata.as_ref().and_then(|usage| usage.cost) {
            state.cost_micro_usd = usd_to_micro_usd(cost);
        }
        if let Some(provider) = &response.provider {
            state.provider = Some(provider.clone());
        }
    }

    /// Records that the call completed at `cost_micro_usd`, or at an unknown cost.
    ///
    /// For calls that report no [`LlmResponse`], such as the unit-billed calls of
    /// [`ModelCallScope::meter`].
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use adk_core::{InMemorySpendLedger, ModelSpendHold, SpendKey, SpendLedger, SpendPeriod};
    ///
    /// # async fn demo() -> adk_core::Result<()> {
    /// let ledger = Arc::new(InMemorySpendLedger::default());
    /// let mut hold = ModelSpendHold::reserve(ledger.clone(), SpendKey::org("acme"), 20_000).await?;
    /// hold.observe_cost(Some(10_000));
    /// hold.settle().await;
    /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 10_000);
    /// # Ok(())
    /// # }
    /// ```
    pub fn observe_cost(&mut self, cost_micro_usd: Option<u64>) {
        let Some(state) = self.inner.as_mut() else {
            return;
        };
        state.saw_response = true;
        if cost_micro_usd.is_some() {
            state.cost_micro_usd = cost_micro_usd;
        }
    }

    /// Commits the observed cost, or releases the hold when no response arrived.
    ///
    /// Returns the provider the cost was reported under when it differs from the reserved
    /// vendor, so a caller can reserve later calls of the same model under it.
    pub async fn settle(mut self) -> Option<String> {
        let state = self.inner.take()?;
        state.settle().await
    }
}

impl HoldState {
    async fn settle(self) -> Option<String> {
        let Self { ledger, reservation, key, estimate, saw_response, cost_micro_usd, provider } =
            self;
        if !saw_response {
            if let Err(error) = ledger.release(reservation).await {
                tracing::warn!(error = %error, spend.key = %key, "failed to release model spend reservation");
            }
            return None;
        }
        let amount = match cost_micro_usd {
            Some(amount) => amount,
            // A model that bounds its cost at zero, such as local inference, reports none.
            None if estimate == 0 => {
                tracing::debug!(
                    spend.key = %key,
                    "model response reported no cost; committing its zero bound"
                );
                0
            }
            None => {
                tracing::warn!(
                    spend.key = %key,
                    spend.estimate_micro_usd = estimate,
                    "model response reported no cost; committing the reserved bound or estimate"
                );
                estimate
            }
        };
        let reported = provider.filter(|provider| key.vendor.as_deref() != Some(provider));
        if let Some(provider) = &reported {
            let corrected = key.clone().with_vendor(provider.clone());
            // A zero hold places the committed cost under the reported provider; the
            // estimate's hold is released only once the cost is recorded there.
            match ledger.reserve(&corrected, 0).await {
                Ok(corrected_reservation) => {
                    match ledger.commit(corrected_reservation, amount).await {
                        Ok(()) => {
                            if let Err(error) = ledger.release(reservation).await {
                                tracing::warn!(error = %error, spend.key = %key, "failed to release model spend reservation");
                            }
                            return reported;
                        }
                        Err(error) => tracing::warn!(
                            error = %error,
                            spend.key = %corrected,
                            "failed to commit model spend under the reported provider; committing under the reserved vendor"
                        ),
                    }
                }
                Err(error) => tracing::warn!(
                    error = %error,
                    spend.key = %corrected,
                    "spend ledger refused the reported provider; committing under the reserved vendor"
                ),
            }
        }
        if let Err(error) = ledger.commit(reservation, amount).await {
            tracing::error!(
                error = %error,
                spend.key = %key,
                spend.amount_micro_usd = amount,
                "failed to commit model spend"
            );
        }
        reported
    }
}

impl Drop for ModelSpendHold {
    fn drop(&mut self) {
        let Some(state) = self.inner.take() else {
            return;
        };
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                handle.spawn(async move {
                    state.settle().await;
                });
            }
            Err(_) => tracing::warn!(
                spend.key = %state.key,
                "model spend hold dropped outside a tokio runtime; it expires by TTL"
            ),
        }
    }
}

/// Spend attribution for the model calls of a [`ModelCallScope`].
#[derive(Clone)]
struct SpendScope {
    ledger: Arc<dyn SpendLedger>,
    org: String,
    agent: Option<String>,
    estimate: LlmSpendEstimate,
}

/// The budget and spend ledger that model calls made on behalf of a run count against.
///
/// Built from a run's [`RunConfig`] with [`for_run`](Self::for_run), or assembled
/// explicitly for calls made outside any run. An empty scope meters nothing.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use adk_core::{BudgetTracker, InMemorySpendLedger, ModelCallScope, RunBudget};
///
/// let scope = ModelCallScope::new()
///     .with_budget(Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(1.0))))
///     .with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme")
///     .with_agent("mcp-sampling");
/// assert_eq!(scope.spend_key("claude-haiku-4-5").unwrap().agent.as_deref(), Some("mcp-sampling"));
/// ```
#[derive(Clone, Default)]
pub struct ModelCallScope {
    budget: Option<Arc<BudgetTracker>>,
    spend: Option<SpendScope>,
    governance: Vec<GovernanceControl>,
}

impl fmt::Debug for ModelCallScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ModelCallScope")
            .field("budget", &self.budget.as_ref().map(|tracker| tracker.budget()))
            .field("spend_org", &self.spend.as_ref().map(|spend| spend.org.as_str()))
            .field("spend_agent", &self.spend.as_ref().and_then(|spend| spend.agent.as_deref()))
            .field("governance", &self.governance.len())
            .finish()
    }
}

tokio::task_local! {
    static CURRENT_SCOPE: ModelCallScope;
}

impl ModelCallScope {
    /// Creates a scope that meters nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates the scope for calls made on behalf of a run.
    ///
    /// Uses the run's [`budget_tracker`](RunConfig::budget_tracker), its
    /// [`spend_ledger`](RunConfig::spend_ledger),
    /// [`llm_spend_estimate`](RunConfig::llm_spend_estimate) and kill switches
    /// ([`governance`](RunConfig::governance)). Spend is attributed to
    /// `org` (the runner passes its app name) and the [`AgentId`](crate::AgentId) the
    /// agent named `agent_name` acts as
    /// ([`ActingConfig::principal_for`](crate::ActingConfig::principal_for): the
    /// configured principal, or `urn:adk:agent:{org}/{agent_name}`).
    pub fn for_run(config: &RunConfig, org: &str, agent_name: &str) -> Self {
        Self {
            budget: config.budget_tracker.clone(),
            spend: config.spend_ledger.clone().map(|ledger| SpendScope {
                ledger,
                org: org.to_string(),
                agent: Some(config.acting.principal_for(org, agent_name).id.into()),
                estimate: config.llm_spend_estimate.unwrap_or_default(),
            }),
            governance: config.governance.clone(),
        }
    }

    /// Refuses every call while `control` is frozen.
    ///
    /// The scope checks its kill switches before each call it meters, so a call that
    /// makes several provider calls, such as a [fallback chain](Llm::generate_content_metered),
    /// stops at the next one once a switch is frozen.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{GOVERNANCE_FROZEN_CODE, GovernanceControl, ModelCallScope};
    ///
    /// let control = GovernanceControl::new();
    /// let scope = ModelCallScope::new().with_governance(control.clone());
    /// assert!(scope.check_governance().is_ok());
    /// control.freeze("incident");
    /// assert_eq!(scope.check_governance().unwrap_err().code, GOVERNANCE_FROZEN_CODE);
    /// ```
    pub fn with_governance(mut self, control: GovernanceControl) -> Self {
        if !self.governance.iter().any(|existing| existing.same_as(&control)) {
            self.governance.push(control);
        }
        self
    }

    /// Returns the error of the first frozen kill switch, if any.
    ///
    /// # Errors
    ///
    /// Returns the frozen control's `governance.frozen` error
    /// ([`GovernanceControl::check`]).
    pub fn check_governance(&self) -> Result<()> {
        self.governance.iter().try_for_each(GovernanceControl::check)
    }

    /// Counts calls against `tracker`.
    pub fn with_budget(mut self, tracker: Arc<BudgetTracker>) -> Self {
        self.budget = Some(tracker);
        self
    }

    /// Reserves and commits call spend in `ledger`, attributed to `org`.
    pub fn with_spend_ledger(
        mut self,
        ledger: Arc<dyn SpendLedger>,
        org: impl Into<String>,
    ) -> Self {
        self.spend = Some(SpendScope {
            ledger,
            org: org.into(),
            agent: self.spend.as_ref().and_then(|spend| spend.agent.clone()),
            estimate: self.spend.as_ref().map(|spend| spend.estimate).unwrap_or_default(),
        });
        self
    }

    /// Attributes spend to `agent`. Has no effect without a spend ledger.
    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
        if let Some(spend) = self.spend.as_mut() {
            spend.agent = Some(agent.into());
        }
        self
    }

    /// Sets the hold reserved before each call. Has no effect without a spend ledger.
    pub fn with_spend_estimate(mut self, estimate: LlmSpendEstimate) -> Self {
        if let Some(spend) = self.spend.as_mut() {
            spend.estimate = estimate;
        }
        self
    }

    /// The budget tracker calls count against.
    pub fn budget(&self) -> Option<&Arc<BudgetTracker>> {
        self.budget.as_ref()
    }

    /// Returns `true` when the scope has neither a budget nor a spend ledger.
    pub fn is_unmetered(&self) -> bool {
        self.budget.is_none() && self.spend.is_none()
    }

    /// The key a call to `model` reserves under, when the scope has a spend ledger.
    pub fn spend_key(&self, model: &str) -> Option<SpendKey> {
        self.vendor_spend_key(vendor_for_model(model))
    }

    /// The key a call billed by `vendor` reserves under, when the scope has a spend ledger.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use adk_core::{InMemorySpendLedger, ModelCallScope};
    ///
    /// let scope = ModelCallScope::new().with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme");
    /// assert_eq!(scope.vendor_spend_key("muse").unwrap().vendor.as_deref(), Some("muse"));
    /// assert!(ModelCallScope::new().vendor_spend_key("muse").is_none());
    /// ```
    pub fn vendor_spend_key(&self, vendor: &str) -> Option<SpendKey> {
        let spend = self.spend.as_ref()?;
        let key = SpendKey::org(&spend.org).with_vendor(vendor);
        Some(match &spend.agent {
            Some(agent) => key.with_agent(agent.clone()),
            None => key,
        })
    }

    /// The scope of the run a tool call belongs to, when the tool's runtime exposes the
    /// run's [`RunConfig`] ([`ToolContext::run_config`]).
    ///
    /// Spend is attributed to the context's app and the agent making the call, as
    /// [`for_run`](Self::for_run) attributes it.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let scope = adk_core::ModelCallScope::for_tool(ctx.as_ref());
    /// ```
    pub fn for_tool(ctx: &dyn ToolContext) -> Option<Self> {
        ctx.run_config().map(|config| Self::for_run(config, ctx.app_name(), ctx.agent_name()))
    }

    /// Runs a tool call with the scope of the run it belongs to current
    /// ([`for_tool`](Self::for_tool)), so the media and model calls the tool makes through
    /// [`meter_usage`] and [`generate_metered`] count against the run. Without a run
    /// configuration on `ctx`, `future` runs as is.
    ///
    /// Agents call this around every tool execution.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await;
    /// ```
    pub fn within_tool<F: Future>(
        ctx: &dyn ToolContext,
        future: F,
    ) -> impl Future<Output = F::Output> + use<F> {
        let scope = Self::for_tool(ctx);
        async move {
            match scope {
                Some(scope) => scope.within(future).await,
                None => future.await,
            }
        }
    }

    /// Returns `true` when both scopes count against the same budget and ledger.
    pub fn same_as(&self, other: &Self) -> bool {
        let budget = match (&self.budget, &other.budget) {
            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
            (None, None) => true,
            _ => false,
        };
        let spend = match (&self.spend, &other.spend) {
            (Some(a), Some(b)) => {
                Arc::ptr_eq(&a.ledger, &b.ledger) && a.org == b.org && a.agent == b.agent
            }
            (None, None) => true,
            _ => false,
        };
        budget && spend
    }

    /// The scope made current by an enclosing [`within`](Self::within), if any.
    pub fn current() -> Option<Self> {
        CURRENT_SCOPE.try_with(Clone::clone).ok()
    }

    /// Runs `future` with this scope current, so [`generate_metered`] and [`MeteredLlm`]
    /// inside it meter against this scope.
    ///
    /// The scope does not follow work spawned onto other tasks.
    pub async fn within<F: Future>(self, future: F) -> F::Output {
        CURRENT_SCOPE.scope(self, future).await
    }

    /// Calls `model` under this scope.
    ///
    /// Refuses the call while one of the scope's kill switches is frozen
    /// ([`with_governance`](Self::with_governance)), then hands it to
    /// [`Llm::generate_content_metered`], which meters it as one model call
    /// ([`generate_one_call`](Self::generate_one_call)) unless the model sends the request
    /// to several providers and meters each of their calls itself.
    ///
    /// # Errors
    ///
    /// Returns the frozen control's `governance.frozen` error, the ledger's error when the
    /// reservation is refused, a [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted)
    /// error when the budget does not allow another call, or the model's own error.
    pub async fn generate(
        &self,
        model: &dyn Llm,
        request: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        self.check_governance()?;
        if self.is_unmetered() && self.governance.is_empty() {
            return model.generate_content(request, stream).await;
        }
        model.generate_content_metered(self, request, stream).await
    }

    /// Meters one call to `model` as one model call.
    ///
    /// Reserves the call's upper-bound cost ([`Llm::max_cost_micro_usd`], or
    /// [`UNBOUNDED_HOLD_MICRO_USD`] when there is none), then the budget's model call,
    /// before the request is sent; a refusal from either stops the call. The returned
    /// stream counts the call's usage once and commits its cost at the turn-complete
    /// response, or when the stream ends or is dropped. The spend is reserved under the
    /// vendor of `request.model` ([`vendor_for_model`]) and committed under the provider
    /// the response reports.
    ///
    /// This is what [`Llm::generate_content_metered`] does unless a model overrides it.
    ///
    /// # Errors
    ///
    /// Returns the ledger's error when the reservation is refused, a
    /// [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted) error when the
    /// budget does not allow another call, or the model's own error.
    pub async fn generate_one_call<M: Llm + ?Sized>(
        &self,
        model: &M,
        request: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        if self.is_unmetered() {
            return model.generate_content(request, stream).await;
        }
        let hold = match (&self.spend, self.spend_key(&request.model)) {
            (Some(spend), Some(key)) => Some(match model.max_cost_micro_usd(&request) {
                Some(bound) => ModelSpendHold::reserve(spend.ledger.clone(), key, bound).await?,
                None => {
                    ModelSpendHold::reserve(spend.ledger.clone(), key, UNBOUNDED_HOLD_MICRO_USD)
                        .await?
                        .with_unpriced_commit(spend.estimate.estimate(&request))
                }
            }),
            _ => None,
        };
        let meter = match self.budget.as_ref().map(|tracker| tracker.begin_model_call(model.name()))
        {
            Some(Ok(meter)) => Some(meter),
            Some(Err(exceeded)) => {
                // A hold that saw no response is released.
                if let Some(hold) = hold {
                    hold.settle().await;
                }
                return Err(exceeded.into());
            }
            None => None,
        };
        let responses = match model.generate_content(request, stream).await {
            Ok(responses) => responses,
            Err(error) => {
                if let Some(hold) = hold {
                    hold.settle().await;
                }
                return Err(error);
            }
        };
        let responses = match meter {
            Some(meter) => meter_stream(responses, meter),
            None => responses,
        };
        Ok(match hold {
            Some(hold) => commit_on_completion(responses, hold),
            None => responses,
        })
    }
}

impl ModelCallScope {
    /// Checks the budget and reserves the spend for one call billed in units.
    ///
    /// Reserves [`UsageCall::max_cost_micro_usd`] in the spend ledger — or
    /// [`UNBOUNDED_HOLD_MICRO_USD`] when the call has no known price, which every covering
    /// cap refuses — then checks the run budget, which refuses a call with no known price
    /// under a cost cap, and holds [`UsageCall::units`] against its per-unit caps. Settle
    /// the returned hold with [`UsageHold::commit`] once the call completes; a hold released
    /// or dropped unsettled records nothing and returns the units it held.
    ///
    /// # Errors
    ///
    /// Returns the frozen control's `governance.frozen` error while a kill switch is frozen,
    /// the ledger's error when the reservation is refused, or a
    /// [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted) error when the
    /// budget refuses the call — `budget.units`, naming the unit and its cap, when a
    /// declared unit does not fit. Nothing has been sent when any of them refuses.
    pub async fn begin_usage(&self, call: &UsageCall) -> Result<UsageHold> {
        self.check_governance()?;
        let spend = match (&self.spend, self.vendor_spend_key(&call.vendor)) {
            (Some(spend), Some(key)) => Some(match call.max_cost_micro_usd {
                Some(bound) => ModelSpendHold::reserve(spend.ledger.clone(), key, bound).await?,
                None => {
                    ModelSpendHold::reserve(spend.ledger.clone(), key, UNBOUNDED_HOLD_MICRO_USD)
                        .await?
                        .with_unpriced_commit(spend.estimate.per_call_micro_usd)
                }
            }),
            _ => None,
        };
        if let Some(tracker) = &self.budget
            && let Err(exceeded) =
                tracker.begin_usage(&call.model, call.max_cost_micro_usd.is_some(), &call.units)
        {
            if let Some(hold) = spend {
                hold.settle().await;
            }
            return Err(exceeded.into());
        }
        Ok(UsageHold {
            spend,
            budget: self.budget.clone(),
            model: call.model.clone(),
            held: call.units.clone(),
        })
    }

    /// Runs one call billed in units under this scope.
    ///
    /// `future` is the call: it returns its value with the [`MeteredUsage`] it incurred.
    /// The budget is checked and the spend reserved before `future` is polled
    /// ([`begin_usage`](Self::begin_usage)), the usage is committed when it succeeds, and
    /// the hold is released when it fails. An unmetered scope runs `future` as is.
    ///
    /// # Errors
    ///
    /// A refusal from [`begin_usage`](Self::begin_usage), in which case `future` never
    /// runs, or the error `future` returns.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use adk_core::{
    ///     InMemorySpendLedger, MeteredUsage, ModelCallScope, SpendKey, SpendLedger, SpendLimits,
    ///     SpendPeriod, UsageCall, UsageUnit, UsageVector,
    /// };
    ///
    /// # async fn demo() -> adk_core::Result<()> {
    /// let limits = SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), 1_000_000);
    /// let ledger = Arc::new(InMemorySpendLedger::new(limits));
    /// let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
    ///
    /// let call = UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(10_000);
    /// let image = scope
    ///     .meter(call, async {
    ///         let usage = MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, 1))
    ///             .with_cost_micro_usd(10_000);
    ///         Ok(("image bytes", usage))
    ///     })
    ///     .await?;
    /// assert_eq!(image, "image bytes");
    /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 10_000);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn meter<T, F>(&self, call: UsageCall, future: F) -> Result<T>
    where
        F: Future<Output = Result<(T, MeteredUsage)>>,
    {
        if self.is_unmetered() {
            self.check_governance()?;
            return future.await.map(|(value, _)| value);
        }
        let hold = self.begin_usage(&call).await?;
        match future.await {
            Ok((value, usage)) => {
                hold.commit(usage).await;
                Ok(value)
            }
            Err(error) => {
                hold.release().await;
                Err(error)
            }
        }
    }
}

/// One call billed in units: the vendor and model it is billed under, the most it can
/// cost, and the most it can use of each unit.
///
/// # Example
///
/// ```
/// use adk_core::{UsageCall, UsageUnit, UsageVector};
///
/// let call = UsageCall::new("muse", "muse-image-1.0")
///     .with_max_cost_micro_usd(40_000)
///     .with_units(UsageVector::new().with(UsageUnit::Images, 4));
/// assert_eq!(call.max_cost_micro_usd, Some(40_000));
/// assert_eq!(call.units.get(UsageUnit::Images), 4);
/// assert_eq!(UsageCall::new("deepgram", "nova-3").max_cost_micro_usd, None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UsageCall {
    /// The spend key vendor the call is reserved and committed under, such as `muse`.
    pub vendor: String,
    /// The model or service called, named in budget errors and logs.
    pub model: String,
    /// Upper bound on the call's cost, or `None` when no price is known.
    pub max_cost_micro_usd: Option<u64>,
    /// The most the call can use of each unit, held against the run budget's per-unit caps
    /// ([`RunBudget::max_units`](crate::RunBudget::max_units)) before the call starts. Empty
    /// when the call declares none, in which case no cap holds it back.
    pub units: UsageVector,
}

impl UsageCall {
    /// A call to `model`, billed by `vendor`, with no known price and no declared units.
    pub fn new(vendor: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            vendor: vendor.into(),
            model: model.into(),
            max_cost_micro_usd: None,
            units: UsageVector::new(),
        }
    }

    /// Sets the most the call can cost.
    pub fn with_max_cost_micro_usd(mut self, max_cost_micro_usd: u64) -> Self {
        self.max_cost_micro_usd = Some(max_cost_micro_usd);
        self
    }

    /// Declares the most the call can use of each unit. The run budget holds these before
    /// the call starts and refuses the call when a unit would pass its cap.
    pub fn with_units(mut self, units: UsageVector) -> Self {
        self.units = units;
        self
    }
}

/// What one call billed in units used, and what it cost when the price is known.
///
/// # Example
///
/// ```
/// use adk_core::{MeteredUsage, UsageUnit, UsageVector};
///
/// let usage = MeteredUsage::new(UsageVector::new().with(UsageUnit::AudioMillis, 90_000))
///     .with_cost_micro_usd(4_500);
/// assert_eq!(usage.units.get(UsageUnit::AudioMillis), 90_000);
/// assert_eq!(usage.cost_micro_usd, Some(4_500));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MeteredUsage {
    /// Usage per unit.
    pub units: UsageVector,
    /// Cost in micro-USD, or `None` when no price is known.
    pub cost_micro_usd: Option<u64>,
}

impl MeteredUsage {
    /// Usage of `units` at an unknown cost.
    pub fn new(units: UsageVector) -> Self {
        Self { units, cost_micro_usd: None }
    }

    /// Sets the cost.
    pub fn with_cost_micro_usd(mut self, cost_micro_usd: u64) -> Self {
        self.cost_micro_usd = Some(cost_micro_usd);
        self
    }
}

/// The open budget check and spend hold of one call billed in units, from
/// [`ModelCallScope::begin_usage`].
///
/// | Settled with | Spend ledger | Budget |
/// |--------------|--------------|--------|
/// | [`commit`](Self::commit) | the reported cost, or the reserved bound (the scope's per-call estimate for an unpriced call) when none is reported | cost, tokens and units counted in place of the units held; an unknown cost under a cost cap stops the run |
/// | [`release`](Self::release), or dropped | hold released | nothing counted; the units held are returned |
#[must_use = "an unsettled usage hold records nothing"]
pub struct UsageHold {
    spend: Option<ModelSpendHold>,
    budget: Option<Arc<BudgetTracker>>,
    model: String,
    held: UsageVector,
}

impl fmt::Debug for UsageHold {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UsageHold")
            .field("spend", &self.spend)
            .field("model", &self.model)
            .field("held", &self.held)
            .finish_non_exhaustive()
    }
}

impl UsageHold {
    /// Records what the call used, in place of the units it held.
    pub async fn commit(mut self, usage: MeteredUsage) {
        if let Some(tracker) = self.budget.take() {
            tracker.record_units(&self.model, &self.held, &usage.units, usage.cost_micro_usd);
        }
        if let Some(mut hold) = self.spend.take() {
            hold.observe_cost(usage.cost_micro_usd);
            hold.settle().await;
        }
    }

    /// Releases the hold of a call that failed, recording nothing and returning the units
    /// it held.
    pub async fn release(mut self) {
        if let Some(tracker) = self.budget.take() {
            tracker.release_units(&self.held);
        }
        if let Some(hold) = self.spend.take() {
            hold.settle().await;
        }
    }
}

impl Drop for UsageHold {
    fn drop(&mut self) {
        // An abandoned call — its future dropped mid-flight — returns the units it held.
        if let Some(tracker) = self.budget.take() {
            tracker.release_units(&self.held);
        }
    }
}

/// Runs one call billed in units under the [current](ModelCallScope::current) scope, or
/// unmetered when there is none. See [`ModelCallScope::meter`].
///
/// Media clients call this so a call made inside a tool counts against the run the tool
/// belongs to.
///
/// # Errors
///
/// See [`ModelCallScope::meter`].
///
/// # Example
///
/// ```
/// use adk_core::{MeteredUsage, UsageCall, UsageUnit, UsageVector, meter_usage};
///
/// # async fn demo() -> adk_core::Result<()> {
/// let call = UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(10_000);
/// let images = meter_usage(call, async {
///     Ok((1, MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, 1))))
/// })
/// .await?;
/// assert_eq!(images, 1);
/// # Ok(())
/// # }
/// ```
pub async fn meter_usage<T, F>(call: UsageCall, future: F) -> Result<T>
where
    F: Future<Output = Result<(T, MeteredUsage)>>,
{
    match ModelCallScope::current() {
        Some(scope) => scope.meter(call, future).await,
        None => future.await.map(|(value, _)| value),
    }
}

/// Settles `hold` from the responses of `responses` once the stream ends.
fn commit_on_completion(responses: LlmResponseStream, hold: ModelSpendHold) -> LlmResponseStream {
    // Dropping the stream early drops the hold, which settles it on the runtime.
    Box::pin(futures::stream::unfold(Some((responses, Some(hold))), |state| async move {
        let (mut responses, mut hold) = state?;
        match responses.next().await {
            Some(item) => {
                if let (Ok(response), Some(open)) = (&item, hold.as_mut()) {
                    open.observe(response);
                    // Committed before the caller sees the final response, so the next
                    // call's reservation already counts this one's cost.
                    if response.turn_complete
                        && !response.partial
                        && let Some(open) = hold.take()
                    {
                        open.settle().await;
                    }
                }
                Some((item, Some((responses, hold))))
            }
            None => {
                if let Some(open) = hold {
                    open.settle().await;
                }
                None
            }
        }
    }))
}

/// Calls `model` under the [current](ModelCallScope::current) scope, or unmetered when
/// there is none.
///
/// Built-in compaction summarizers and the MCP sampling handler call models through this
/// function; use it in a custom [`BaseEventsSummarizer`](crate::BaseEventsSummarizer) or
/// sampling handler so its calls count against the run.
///
/// # Errors
///
/// See [`ModelCallScope::generate`].
///
/// # Example
///
/// ```rust,ignore
/// let stream = adk_core::generate_metered(model.as_ref(), request, false).await?;
/// ```
pub async fn generate_metered(
    model: &dyn Llm,
    request: LlmRequest,
    stream: bool,
) -> Result<LlmResponseStream> {
    match ModelCallScope::current() {
        Some(scope) => scope.generate(model, request, stream).await,
        None => model.generate_content(request, stream).await,
    }
}

/// An [`Llm`] that meters every call against a [`ModelCallScope`].
///
/// With an explicit scope ([`with_scope`](Self::with_scope)) every call counts against
/// it; otherwise calls count against the [current](ModelCallScope::current) scope and run
/// unmetered outside one. Wrap the model of a custom summarizer or judge with it; do not
/// wrap an agent's own model, whose calls the agent already meters.
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use adk_core::{MeteredLlm, ModelCallScope};
///
/// let judge_model = Arc::new(MeteredLlm::new(model).with_scope(scope));
/// ```
pub struct MeteredLlm {
    inner: Arc<dyn Llm>,
    scope: Option<ModelCallScope>,
}

impl MeteredLlm {
    /// Wraps `inner`, metering against the current scope.
    pub fn new(inner: Arc<dyn Llm>) -> Self {
        Self { inner, scope: None }
    }

    /// Meters every call against `scope`, whether or not another scope is current.
    pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
        self.scope = Some(scope);
        self
    }
}

#[async_trait]
impl Llm for MeteredLlm {
    fn name(&self) -> &str {
        self.inner.name()
    }

    async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream> {
        match self.scope.clone().or_else(ModelCallScope::current) {
            Some(scope) => scope.generate(self.inner.as_ref(), req, stream).await,
            None => self.inner.generate_content(req, stream).await,
        }
    }

    fn schema_adapter(&self) -> &dyn SchemaAdapter {
        self.inner.schema_adapter()
    }

    fn uses_interactions_api(&self) -> bool {
        self.inner.uses_interactions_api()
    }

    fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
        self.inner.max_cost_micro_usd(request)
    }

    fn context_window(&self) -> Option<u64> {
        self.inner.context_window()
    }

    fn data_locality(&self) -> crate::DataLocality {
        self.inner.data_locality()
    }

    fn data_destinations(&self) -> Vec<crate::DataDestination> {
        self.inner.data_destinations()
    }

    fn native_web_search(&self) -> Option<crate::NativeWebSearch> {
        self.inner.native_web_search()
    }

    fn native_compaction(&self) -> Option<crate::NativeCompaction> {
        self.inner.native_compaction()
    }

    async fn prewarm(&self) -> Result<()> {
        self.inner.prewarm().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{InMemorySpendLedger, RunBudget, SpendLimits, SpendPeriod, UsageUnit};
    use std::sync::atomic::{AtomicBool, Ordering};

    fn image_call(images: u64) -> UsageCall {
        UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(images * 10_000)
    }

    fn images(count: u64) -> MeteredUsage {
        MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, count))
            .with_cost_micro_usd(count * 10_000)
    }

    fn capped(micro_usd: u64) -> Arc<InMemorySpendLedger> {
        Arc::new(InMemorySpendLedger::new(
            SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), micro_usd),
        ))
    }

    #[tokio::test]
    async fn a_unit_call_over_the_cap_is_refused_before_it_is_sent() {
        let ledger = capped(5_000);
        let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
        let sent = AtomicBool::new(false);
        let refused = scope
            .meter(image_call(1), async {
                sent.store(true, Ordering::SeqCst);
                Ok(((), images(1)))
            })
            .await
            .unwrap_err();
        assert_eq!(refused.code, crate::SPEND_LIMIT_EXCEEDED_CODE);
        assert!(!sent.load(Ordering::SeqCst));
        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 0);
    }

    #[tokio::test]
    async fn a_unit_call_commits_its_cost_to_the_ledger_and_the_budget() {
        let ledger = capped(1_000_000);
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(1.0)));
        let scope = ModelCallScope::new()
            .with_budget(tracker.clone())
            .with_spend_ledger(ledger.clone(), "acme");
        scope.meter(image_call(2), async { Ok(((), images(2))) }).await.unwrap();

        let key = SpendKey::org("acme").with_vendor("muse");
        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 20_000);
        assert_eq!(tracker.usage().cost_micro_usd, 20_000);
        assert_eq!(tracker.usage().model_calls, 0);
        assert_eq!(tracker.units(), UsageVector::new().with(UsageUnit::Images, 2));
    }

    #[tokio::test]
    async fn a_failed_unit_call_releases_its_hold_and_counts_nothing() {
        let ledger = capped(10_000);
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let scope = ModelCallScope::new()
            .with_budget(tracker.clone())
            .with_spend_ledger(ledger.clone(), "acme");
        let failed = scope
            .meter(image_call(1), async {
                Err::<((), MeteredUsage), _>(crate::AdkError::model("down"))
            })
            .await
            .unwrap_err();
        assert_eq!(failed.message, "down");
        assert_eq!(tracker.units(), UsageVector::new());
        // The released hold leaves the whole cap for the next call.
        scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 10_000);
    }

    #[tokio::test]
    async fn an_unpriced_unit_call_is_refused_under_a_ledger_cap() {
        let scope = ModelCallScope::new().with_spend_ledger(capped(1_000_000), "acme");
        let sent = AtomicBool::new(false);
        let refused = scope
            .meter(UsageCall::new("deepgram", "nova-3"), async {
                sent.store(true, Ordering::SeqCst);
                Ok(((), MeteredUsage::default()))
            })
            .await
            .unwrap_err();
        assert_eq!(refused.code, crate::SPEND_LIMIT_EXCEEDED_CODE);
        assert!(!sent.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn an_unpriced_unit_call_is_refused_under_a_budget_cost_cap() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(5.0)));
        let scope = ModelCallScope::new().with_budget(tracker.clone());
        let sent = AtomicBool::new(false);
        let refused = scope
            .meter(UsageCall::new("deepgram", "nova-3"), async {
                sent.store(true, Ordering::SeqCst);
                Ok(((), MeteredUsage::default()))
            })
            .await
            .unwrap_err();
        assert_eq!(refused.code, "budget.cost_unknown");
        assert!(!sent.load(Ordering::SeqCst));
        // Nothing ran, so nothing is recorded against later calls.
        assert!(tracker.check().is_ok());

        let opted_out = Arc::new(BudgetTracker::new(
            RunBudget::new().max_cost_usd(5.0).allow_unpriced_models(),
        ));
        let scope = ModelCallScope::new().with_budget(opted_out.clone());
        scope
            .meter(UsageCall::new("deepgram", "nova-3"), async {
                Ok(((), MeteredUsage::new(UsageVector::new().with(UsageUnit::AudioMillis, 800))))
            })
            .await
            .unwrap();
        assert_eq!(opted_out.units(), UsageVector::new().with(UsageUnit::AudioMillis, 800));
    }

    #[tokio::test]
    async fn an_unpriced_unit_call_without_a_cap_commits_the_estimate() {
        let ledger = Arc::new(InMemorySpendLedger::default());
        let scope = ModelCallScope::new()
            .with_spend_ledger(ledger.clone(), "acme")
            .with_spend_estimate(LlmSpendEstimate::per_call(7_000));
        scope
            .meter(UsageCall::new("deepgram", "nova-3"), async {
                Ok(((), MeteredUsage::default()))
            })
            .await
            .unwrap();
        let key = SpendKey::org("acme").with_vendor("deepgram");
        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 7_000);
    }

    /// The messages of the warnings logged while it is the default subscriber.
    #[derive(Clone, Default)]
    struct Warnings(Arc<std::sync::Mutex<Vec<String>>>);

    impl tracing::Subscriber for Warnings {
        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
            true
        }
        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
            tracing::span::Id::from_u64(1)
        }
        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
        fn event(&self, event: &tracing::Event<'_>) {
            struct Message(String);
            impl tracing::field::Visit for Message {
                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
                    if field.name() == "message" {
                        self.0 = format!("{value:?}");
                    }
                }
            }
            if *event.metadata().level() == tracing::Level::WARN {
                let mut message = Message(String::new());
                event.record(&mut message);
                self.0.lock().unwrap().push(message.0);
            }
        }
        fn enter(&self, _: &tracing::span::Id) {}
        fn exit(&self, _: &tracing::span::Id) {}
    }

    #[tokio::test]
    async fn a_response_without_a_cost_warns_only_when_its_bound_is_positive() {
        let warnings = Warnings::default();
        let _default = tracing::subscriber::set_default(warnings.clone());
        let ledger = Arc::new(InMemorySpendLedger::default());
        // A local model bounds its cost at zero; a cloud model at a positive amount.
        for bound in [0, 7_000] {
            let mut hold = ModelSpendHold::reserve(ledger.clone(), SpendKey::org("acme"), bound)
                .await
                .unwrap();
            hold.observe_cost(None);
            hold.settle().await;
        }
        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 7_000);
        assert_eq!(
            *warnings.0.lock().unwrap(),
            ["model response reported no cost; committing the reserved bound or estimate"]
        );
    }

    #[tokio::test]
    async fn a_unit_call_is_refused_once_the_budget_is_spent() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_micro_usd(10_000)));
        let scope = ModelCallScope::new().with_budget(tracker.clone());
        scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
        let refused = scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap_err();
        assert_eq!(refused.code, "budget.cost");
    }

    #[tokio::test]
    async fn the_free_function_meters_against_the_current_scope() {
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let scope = ModelCallScope::new().with_budget(tracker.clone());
        scope.within(meter_usage(image_call(1), async { Ok(((), images(1))) })).await.unwrap();
        assert_eq!(tracker.usage().cost_micro_usd, 10_000);
        // Outside any scope the call runs unmetered.
        meter_usage(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
        assert_eq!(tracker.usage().cost_micro_usd, 10_000);
    }

    #[test]
    fn vendor_is_read_from_the_model_family() {
        assert_eq!(vendor_for_model("gemini-3.7-flash"), "gemini");
        assert_eq!(vendor_for_model("models/gemini-3.1-pro-preview"), "gemini");
        assert_eq!(vendor_for_model("claude-opus-4-8"), "anthropic");
        assert_eq!(vendor_for_model("gpt-5.2"), "openai");
        assert_eq!(vendor_for_model("o3-mini"), "openai");
        assert_eq!(vendor_for_model("deepseek-v4"), "deepseek");
        assert_eq!(vendor_for_model("muse-image-1.0"), "muse");
        assert_eq!(vendor_for_model("llama-4-scout"), "unknown");
    }

    #[test]
    fn the_estimate_without_an_output_price_is_the_per_call_amount() {
        let mut request = LlmRequest::new("gemini-3.7-flash", vec![]);
        request.config = Some(crate::GenerateContentConfig {
            max_output_tokens: Some(1_000),
            ..Default::default()
        });
        assert_eq!(LlmSpendEstimate::per_call(7).estimate(&request), 7);
        assert_eq!(LlmSpendEstimate::default().estimate(&request), 50_000);
    }

    struct Searching;

    #[async_trait]
    impl Llm for Searching {
        fn name(&self) -> &str {
            "searching"
        }

        async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
            Ok(Box::pin(futures::stream::empty()))
        }

        fn native_web_search(&self) -> Option<crate::NativeWebSearch> {
            Some(crate::NativeWebSearch::new(
                "gemini",
                crate::NativeWebSearchTool::GoogleSearch,
                false,
            ))
        }
    }

    #[test]
    fn the_metered_wrapper_reports_the_native_search_of_the_model_it_wraps() {
        let metered = MeteredLlm::new(Arc::new(Searching));
        assert_eq!(
            metered.native_web_search(),
            Some(crate::NativeWebSearch::new(
                "gemini",
                crate::NativeWebSearchTool::GoogleSearch,
                false
            ))
        );
    }

    /// Answers every call with one complete response reporting `cost`, served by `provider`.
    struct Priced {
        name: &'static str,
        provider: &'static str,
        cost: f64,
        sent: std::sync::atomic::AtomicUsize,
    }

    impl Priced {
        fn new(name: &'static str, provider: &'static str, cost: f64) -> Self {
            Self { name, provider, cost, sent: std::sync::atomic::AtomicUsize::new(0) }
        }
    }

    #[async_trait]
    impl Llm for Priced {
        fn name(&self) -> &str {
            self.name
        }

        async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
            self.sent.fetch_add(1, Ordering::SeqCst);
            let mut response = LlmResponse::new(crate::Content::new("model").with_text("ok"));
            response.provider = Some(self.provider.to_string());
            response.model = Some(self.name.to_string());
            response.usage_metadata = Some(crate::UsageMetadata {
                prompt_token_count: 10,
                candidates_token_count: 5,
                total_token_count: 15,
                cost: Some(self.cost),
                ..Default::default()
            });
            Ok(Box::pin(futures::stream::iter([Ok(response)])))
        }

        fn max_cost_micro_usd(&self, _: &LlmRequest) -> Option<u64> {
            Some(50_000)
        }
    }

    /// Sends every request to both of its models and answers with the second one's stream.
    struct BothModels {
        first: Arc<Priced>,
        second: Arc<Priced>,
    }

    #[async_trait]
    impl Llm for BothModels {
        fn name(&self) -> &str {
            "both"
        }

        async fn generate_content(
            &self,
            req: LlmRequest,
            stream: bool,
        ) -> Result<LlmResponseStream> {
            self.second.generate_content(req, stream).await
        }

        async fn generate_content_metered(
            &self,
            scope: &ModelCallScope,
            req: LlmRequest,
            stream: bool,
        ) -> Result<LlmResponseStream> {
            let mut first = req.clone();
            first.model = self.first.name.to_string();
            let mut drained = scope.generate(self.first.as_ref(), first, stream).await?;
            while drained.next().await.is_some() {}
            let mut second = req;
            second.model = self.second.name.to_string();
            scope.generate(self.second.as_ref(), second, stream).await
        }
    }

    #[tokio::test]
    async fn a_model_that_meters_its_own_calls_records_each_under_its_provider() {
        let ledger = capped(1_000_000);
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let scope = ModelCallScope::new()
            .with_budget(tracker.clone())
            .with_spend_ledger(ledger.clone(), "acme");
        let model = BothModels {
            first: Arc::new(Priced::new("gpt-6.1-sol", "openai", 0.001)),
            second: Arc::new(Priced::new("claude-haiku-5-5", "anthropic", 0.002)),
        };

        let mut responses =
            scope.generate(&model, LlmRequest::new("both", vec![]), false).await.unwrap();
        while responses.next().await.is_some() {}

        let spent = |vendor: &'static str| {
            let ledger = ledger.clone();
            async move {
                ledger
                    .spent(&SpendKey::org("acme").with_vendor(vendor), SpendPeriod::Day)
                    .await
                    .unwrap()
            }
        };
        assert_eq!(spent("openai").await, 1_000);
        assert_eq!(spent("anthropic").await, 2_000);
        assert_eq!(tracker.usage().model_calls, 2);
        assert_eq!(tracker.usage().total_tokens, 30);
        assert_eq!(tracker.usage().cost_micro_usd, 3_000);
    }

    #[tokio::test]
    async fn a_model_with_the_default_is_metered_as_one_call() {
        let ledger = capped(1_000_000);
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let scope = ModelCallScope::new()
            .with_budget(tracker.clone())
            .with_spend_ledger(ledger.clone(), "acme");
        let model = Priced::new("claude-haiku-5-5", "anthropic", 0.002);

        let mut responses = scope
            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
            .await
            .unwrap();
        while responses.next().await.is_some() {}

        let key = SpendKey::org("acme").with_vendor("anthropic");
        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 2_000);
        assert_eq!(tracker.usage().model_calls, 1);
    }

    #[tokio::test]
    async fn a_frozen_scope_refuses_a_call_before_it_is_reserved_or_sent() {
        let ledger = capped(1_000_000);
        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
        let control = crate::GovernanceControl::new();
        let scope = ModelCallScope::new()
            .with_budget(tracker.clone())
            .with_spend_ledger(ledger.clone(), "acme")
            .with_governance(control.clone());
        let model = Priced::new("claude-haiku-5-5", "anthropic", 0.002);
        control.freeze("incident");

        let refused = scope
            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
            .await
            .err()
            .unwrap();
        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
        assert_eq!(model.sent.load(Ordering::SeqCst), 0);
        assert_eq!(tracker.usage().model_calls, 0);

        let unmetered = ModelCallScope::new().with_governance(control.clone());
        let refused = unmetered
            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
            .await
            .err()
            .unwrap();
        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
        let refused =
            unmetered.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap_err();
        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
        assert_eq!(model.sent.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn a_run_scope_carries_the_run_kill_switches() {
        let control = crate::GovernanceControl::new();
        let config = RunConfig::builder().governance(control.clone()).build();
        let scope = ModelCallScope::for_run(&config, "acme", "assistant");
        assert!(scope.check_governance().is_ok());
        control.freeze("incident");
        assert_eq!(scope.check_governance().unwrap_err().code, crate::GOVERNANCE_FROZEN_CODE);
    }
}