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
use crate::schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
use crate::{Result, types::Content};
use async_trait::async_trait;
use futures::stream::Stream;
use serde::{Deserialize, Serialize};
use std::pin::Pin;

/// A pinned, boxed stream of [`LlmResponse`] results from a model.
pub type LlmResponseStream = Pin<Box<dyn Stream<Item = Result<LlmResponse>> + Send>>;

/// The core trait for all LLM providers.
///
/// Implementations wrap a specific model API (Gemini, OpenAI, Anthropic, etc.)
/// and produce a stream of responses for a given request.
#[async_trait]
pub trait Llm: Send + Sync {
    /// Returns the model identifier (e.g., "gemini-3.8-flash").
    fn name(&self) -> &str;
    /// Generates content from the given request, optionally streaming.
    async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream>;

    /// Generates content with every provider call it makes metered against `scope`.
    ///
    /// [`ModelCallScope::generate`](crate::ModelCallScope::generate) calls this for every
    /// metered call, after checking the scope's kill switches. The default meters the call as
    /// one model call ([`ModelCallScope::generate_one_call`](crate::ModelCallScope::generate_one_call)):
    /// one hold in the spend ledger, reserved under the vendor of `req.model`, and one model
    /// call in the run budget.
    ///
    /// A model that sends one request to several providers, such as a fallback chain,
    /// overrides it to call each of them through `scope.generate`, so every provider call is
    /// reserved, counted and committed under the provider and model that served it. A
    /// wrapper that only changes the request or the stream keeps the default and is metered
    /// as one call.
    ///
    /// # Errors
    ///
    /// Returns what [`ModelCallScope::generate`](crate::ModelCallScope::generate) returns.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_core::{
    ///     InMemorySpendLedger, Llm, LlmRequest, LlmResponseStream, ModelCallScope, SpendKey,
    ///     SpendLedger, SpendPeriod,
    /// };
    ///
    /// struct Local;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Local {
    ///     fn name(&self) -> &str {
    ///         "gemini-local"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         Ok(Box::pin(futures::stream::empty()))
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async {
    /// let ledger = Arc::new(InMemorySpendLedger::default());
    /// let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
    /// // The default meters the call as one; a call with no response commits nothing.
    /// let request = LlmRequest::new("gemini-local", vec![]);
    /// let _ = Local.generate_content_metered(&scope, request, false).await?;
    /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 0);
    /// # Ok::<(), adk_core::AdkError>(())
    /// # }).unwrap();
    /// ```
    async fn generate_content_metered(
        &self,
        scope: &crate::ModelCallScope,
        req: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        scope.generate_one_call(self, req, stream).await
    }

    /// Returns the schema adapter for this provider.
    ///
    /// The schema adapter normalizes raw JSON Schema from MCP tools into the
    /// format accepted by this provider's function-calling API.
    ///
    /// Default implementation returns [`GenericSchemaAdapter`], which applies
    /// safe transforms suitable for most providers. Override this method to
    /// return a provider-specific adapter (e.g., `GeminiSchemaAdapter`,
    /// `OpenAiStrictSchemaAdapter`).
    fn schema_adapter(&self) -> &dyn SchemaAdapter {
        &GenericSchemaAdapter
    }

    /// Returns `true` if this model is configured to use a server-managed
    /// environment (e.g., Gemini Interactions API) where the provider owns
    /// the tool-calling loop and filesystem.
    ///
    /// This is used at agent build time to detect conflicts with client-side
    /// sandbox tools that would produce competing filesystems.
    ///
    /// Default implementation returns `false`. Override in providers that
    /// support server-managed environments.
    fn uses_interactions_api(&self) -> bool {
        false
    }

    /// Returns an upper bound, in micro-USD, on what `request` can cost on this model.
    ///
    /// The spend ledger reserves this amount before the call, so the call's committed
    /// cost never exceeds its reservation and a hard cap is never overshot. Providers
    /// derive it from the request's size, its output cap (or the model's maximum output),
    /// and the highest per-token rate that can apply. `None` means the call cannot be
    /// bounded — an unpriced model, or a request whose size is unknown; see
    /// [`ModelCallScope`](crate::ModelCallScope) for how such calls are reserved.
    ///
    /// The default returns `None`. Wrappers forward to the model they wrap.
    fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
        let _ = request;
        None
    }

    /// The most tokens a request to this model may carry, as its provider documents it, if
    /// known.
    ///
    /// Auto-compaction ([`IntraCompactionConfig`](crate::IntraCompactionConfig)) compacts an
    /// agent's history before it nears this window. `adk-model` providers read it from the
    /// pricing catalog, which records each vendor's published figure.
    ///
    /// The default returns `None`, which compacts at
    /// [`DEFAULT_TOKEN_THRESHOLD`](crate::intra_compaction::DEFAULT_TOKEN_THRESHOLD).
    /// Wrappers forward to the model they wrap.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Llm, LlmRequest, LlmResponseStream};
    ///
    /// struct Local;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Local {
    ///     fn name(&self) -> &str {
    ///         "local-8k"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         unimplemented!()
    ///     }
    ///     fn context_window(&self) -> Option<u64> {
    ///         Some(8_192)
    ///     }
    /// }
    ///
    /// assert_eq!(Local.context_window(), Some(8_192));
    /// ```
    fn context_window(&self) -> Option<u64> {
        None
    }

    /// The provider-executed web search this model's transport serves, if any (spec 3.1
    /// §7.20 "Provider-native search and fetch").
    ///
    /// Read from the client, never from the model's output: an agent that wants the
    /// provider's search declares the built-in tool this names, and a model that returns
    /// `None` gets web search only through a tool the application runs itself.
    ///
    /// The default returns `None`. Wrappers forward to the model they wrap.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Llm, LlmRequest, LlmResponseStream, NativeWebSearch, NativeWebSearchTool};
    ///
    /// struct Hosted;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Hosted {
    ///     fn name(&self) -> &str {
    ///         "hosted"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         unimplemented!()
    ///     }
    ///     fn native_web_search(&self) -> Option<NativeWebSearch> {
    ///         Some(NativeWebSearch::new("anthropic", NativeWebSearchTool::AnthropicWebSearch, true))
    ///     }
    /// }
    ///
    /// assert_eq!(Hosted.native_web_search().unwrap().provider, "anthropic");
    /// ```
    fn native_web_search(&self) -> Option<NativeWebSearch> {
        None
    }

    /// The conversation compaction this model's provider performs itself, if any.
    ///
    /// The runner's auto-compaction asks such a model for the summary
    /// ([`NativeCompactionRequest`](crate::intra_compaction::NativeCompactionRequest)) in place
    /// of writing one with its own summarizer, and keeps the provider's signed result in the
    /// history so the provider reads it back
    /// ([`is_native_compaction`](crate::intra_compaction::is_native_compaction)).
    ///
    /// The default returns `None`. Wrappers forward to the model they wrap.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Llm, LlmRequest, LlmResponseStream, NativeCompaction};
    ///
    /// struct Hosted;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Hosted {
    ///     fn name(&self) -> &str {
    ///         "hosted"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         unimplemented!()
    ///     }
    ///     fn native_compaction(&self) -> Option<NativeCompaction> {
    ///         Some(NativeCompaction::new("anthropic").keeping_thinking())
    ///     }
    /// }
    ///
    /// assert!(Hosted.native_compaction().unwrap().keeps_thinking);
    /// ```
    fn native_compaction(&self) -> Option<NativeCompaction> {
        None
    }

    /// Opens what the first call to this model would otherwise open, such as the pooled
    /// TLS connection to the provider, so a turn that follows soon after starts on it.
    ///
    /// It sends no prompt and spends no tokens. What it opens lasts as long as the client
    /// keeps an idle connection (90 seconds for `adk-anthropic`); call it again after that.
    /// The default does nothing. Wrappers forward to the model they wrap.
    ///
    /// # Errors
    ///
    /// Returns the provider's error when it cannot be reached; a turn would meet the same
    /// error, so a caller may log it and carry on.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{Llm, LlmRequest, LlmResponseStream};
    ///
    /// struct Local;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Local {
    ///     fn name(&self) -> &str {
    ///         "local"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         Ok(Box::pin(futures::stream::empty()))
    ///     }
    /// }
    ///
    /// # futures::executor::block_on(async {
    /// Local.prewarm().await?;
    /// # Ok::<(), adk_core::AdkError>(())
    /// # }).unwrap();
    /// ```
    async fn prewarm(&self) -> Result<()> {
        Ok(())
    }

    /// Where a call's request data goes: into another machine ([`DataLocality::Remote`]),
    /// to a server on this machine ([`DataLocality::Loopback`]), or nowhere outside this
    /// process ([`DataLocality::InProcess`]).
    ///
    /// The image privacy guardrail reads it to tell which model calls leave the machine.
    /// The default is `Remote`, so a model that does not say is treated as remote. Wrappers
    /// forward the wrapped model's locality; a wrapper over several models answers the
    /// least local of them ([`DataLocality::least_local`]).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{DataLocality, Llm, LlmRequest, LlmResponseStream};
    ///
    /// struct OnDevice;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for OnDevice {
    ///     fn name(&self) -> &str {
    ///         "qwen3-vl-2b"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         Ok(Box::pin(futures::stream::empty()))
    ///     }
    ///     fn data_locality(&self) -> DataLocality {
    ///         DataLocality::InProcess
    ///     }
    /// }
    ///
    /// assert_eq!(OnDevice.data_locality(), DataLocality::InProcess);
    /// assert!(!OnDevice.data_locality().leaves_machine());
    /// ```
    fn data_locality(&self) -> DataLocality {
        DataLocality::Remote
    }

    /// Where a call's request data is sent: each provider the model may call, by the id its
    /// responses carry in [`LlmResponse::provider`], with the hosts its client connects to.
    ///
    /// `adk-model` providers answer from their configured endpoint, so a custom base URL, a
    /// Vertex or Bedrock region, or an Azure resource names its own host. A loopback server
    /// names its loopback host; [`data_locality`](Self::data_locality) says whether the data
    /// leaves the machine. Image egress rules and the privacy guardrail read it to name the
    /// hosts a remote model's images go to.
    ///
    /// The default returns none, meaning the destination is unknown. Wrappers forward to the
    /// model they wrap; a wrapper over several models answers every model's destinations, or
    /// none when any of them is unknown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{DataDestination, Llm, LlmRequest, LlmResponseStream};
    ///
    /// struct Hosted;
    ///
    /// #[async_trait::async_trait]
    /// impl Llm for Hosted {
    ///     fn name(&self) -> &str {
    ///         "claude-sonnet-5-5"
    ///     }
    ///     async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
    ///         unimplemented!()
    ///     }
    ///     fn data_destinations(&self) -> Vec<DataDestination> {
    ///         vec![DataDestination::of_url("anthropic", "https://api.anthropic.com/v1")]
    ///     }
    /// }
    ///
    /// let destinations = Hosted.data_destinations();
    /// assert_eq!(destinations[0].provider, "anthropic");
    /// assert_eq!(destinations[0].hosts, ["api.anthropic.com"]);
    /// ```
    fn data_destinations(&self) -> Vec<DataDestination> {
        Vec::new()
    }
}

/// One provider a model sends request data to, and the hosts its client connects to.
///
/// Read from the client's configuration, never from a response: [`Llm::data_destinations`]
/// returns one per provider a model may call.
///
/// # Example
///
/// ```rust
/// use adk_core::DataDestination;
///
/// let vertex = DataDestination::of_url("gemini", "https://europe-west4-aiplatform.googleapis.com/v1");
/// assert_eq!(vertex.hosts, ["europe-west4-aiplatform.googleapis.com"]);
///
/// let ollama = DataDestination::of_url("ollama", "http://localhost:11434");
/// assert_eq!(ollama.hosts, ["localhost:11434"]);
///
/// assert!(DataDestination::of_url("openai", "not a url").hosts.is_empty());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DataDestination {
    /// The provider's id, as its responses carry it in [`LlmResponse::provider`]:
    /// `anthropic`, `gemini`, `openai`, `bedrock`, or the name an OpenAI-compatible client
    /// is configured with.
    pub provider: String,
    /// The hosts request data is sent to, each as `host`, or `host:port` when the port is
    /// not 443.
    pub hosts: Vec<String>,
}

impl DataDestination {
    /// A destination at `hosts`, each `host` or `host:port`.
    pub fn new(
        provider: impl Into<String>,
        hosts: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self { provider: provider.into(), hosts: hosts.into_iter().map(Into::into).collect() }
    }

    /// The destination of a client whose endpoint is `url`: its host, with the port when
    /// it is not 443. A URL that does not parse, or names no host, gives no host.
    pub fn of_url(provider: impl Into<String>, url: &str) -> Self {
        let host = url::Url::parse(url.trim()).ok().and_then(|parsed| {
            let host = parsed.host_str()?.trim_end_matches('.').to_ascii_lowercase();
            Some(match parsed.port_or_known_default() {
                Some(443) | None => host,
                Some(port) => format!("{host}:{port}"),
            })
        });
        Self { provider: provider.into(), hosts: host.into_iter().collect() }
    }

    /// Every destination's hosts, in order and without repeats.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::DataDestination;
    ///
    /// let both = [
    ///     DataDestination::new("anthropic", ["api.anthropic.com"]),
    ///     DataDestination::new("gemini", ["generativelanguage.googleapis.com", "api.anthropic.com"]),
    /// ];
    /// assert_eq!(
    ///     DataDestination::all_hosts(&both),
    ///     ["api.anthropic.com", "generativelanguage.googleapis.com"]
    /// );
    /// ```
    pub fn all_hosts(destinations: &[DataDestination]) -> Vec<String> {
        let mut hosts: Vec<String> = Vec::new();
        for host in destinations.iter().flat_map(|d| d.hosts.iter()) {
            if !hosts.contains(host) {
                hosts.push(host.clone());
            }
        }
        hosts
    }
}

/// Where a model call's request data goes, from most to least local.
///
/// Ordered by how far data travels, so the greater of two localities is the less local one.
///
/// | Locality | Request data | Example |
/// |----------|--------------|---------|
/// | [`InProcess`](Self::InProcess) | Stays in this process | `adk-mistralrs` models |
/// | [`Loopback`](Self::Loopback) | Leaves the process for a server on this machine | Ollama or an OpenAI-compatible server at `localhost` |
/// | [`Remote`](Self::Remote) | Leaves the machine | Every hosted provider |
///
/// A loopback server can itself forward a request elsewhere; `Loopback` says only that the
/// framework sends it no further than this machine.
///
/// # Example
///
/// ```rust
/// use adk_core::DataLocality;
///
/// assert_eq!(DataLocality::of_url("http://localhost:11434"), DataLocality::Loopback);
/// assert_eq!(DataLocality::of_url("http://[::1]:8000/v1"), DataLocality::Loopback);
/// assert_eq!(DataLocality::of_url("https://api.openai.com/v1"), DataLocality::Remote);
/// assert_eq!(
///     DataLocality::least_local([DataLocality::InProcess, DataLocality::Loopback]),
///     DataLocality::Loopback
/// );
/// assert_eq!(serde_json::to_value(DataLocality::InProcess).unwrap(), "inProcess");
/// ```
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum DataLocality {
    /// The model runs in this process; request data never leaves it.
    InProcess,
    /// The model is served on this machine over the loopback interface.
    Loopback,
    /// The model is served by another machine; request data leaves this one.
    #[default]
    Remote,
}

impl DataLocality {
    /// The locality of a server at `url`: [`Loopback`](Self::Loopback) when its host is
    /// `localhost` or a loopback address (`127.0.0.0/8`, `::1`), otherwise
    /// [`Remote`](Self::Remote). A URL that does not parse is `Remote`.
    pub fn of_url(url: &str) -> Self {
        let Ok(parsed) = url::Url::parse(url.trim()) else {
            return Self::Remote;
        };
        let loopback = match parsed.host() {
            Some(url::Host::Domain(domain)) => {
                let domain = domain.trim_end_matches('.').to_ascii_lowercase();
                domain == "localhost" || domain.ends_with(".localhost")
            }
            Some(url::Host::Ipv4(address)) => address.is_loopback(),
            Some(url::Host::Ipv6(address)) => {
                address.is_loopback()
                    || address.to_ipv4_mapped().is_some_and(|mapped| mapped.is_loopback())
            }
            None => false,
        };
        if loopback { Self::Loopback } else { Self::Remote }
    }

    /// The least local of `localities`: where the data of a call that may go to any of
    /// them can end up. [`Remote`](Self::Remote) when there are none.
    pub fn least_local(localities: impl IntoIterator<Item = DataLocality>) -> Self {
        localities.into_iter().max().unwrap_or(Self::Remote)
    }

    /// Whether request data leaves this machine.
    pub fn leaves_machine(self) -> bool {
        self == Self::Remote
    }

    /// Whether request data leaves this process.
    pub fn leaves_process(self) -> bool {
        self != Self::InProcess
    }
}

/// Tool declarations keyed by tool name, in the order the agent declares them.
///
/// Providers send the tools in this order, so a request is the same on every run, as in
/// adk-python and adk-go. Inserting a name already present replaces its declaration in place.
///
/// ```rust
/// use adk_core::ToolDeclarations;
/// use serde_json::json;
///
/// let mut tools = ToolDeclarations::new();
/// tools.insert("search".into(), json!({"name": "search"}));
/// tools.insert("add".into(), json!({"name": "add"}));
/// tools.insert("search".into(), json!({"name": "search", "description": "Find pages"}));
///
/// let names: Vec<&str> = tools.keys().map(String::as_str).collect();
/// assert_eq!(names, ["search", "add"]);
/// assert_eq!(tools["search"]["description"], "Find pages");
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ToolDeclarations {
    entries: Vec<(String, serde_json::Value)>,
}

impl ToolDeclarations {
    /// No declarations.
    pub fn new() -> Self {
        Self::default()
    }

    /// The number of declarations.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether there are no declarations.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Declares `name`, at the end, or in its place when it is already declared. Returns the
    /// declaration it replaced.
    pub fn insert(
        &mut self,
        name: String,
        declaration: serde_json::Value,
    ) -> Option<serde_json::Value> {
        match self.entries.iter_mut().find(|(existing, _)| *existing == name) {
            Some((_, slot)) => Some(std::mem::replace(slot, declaration)),
            None => {
                self.entries.push((name, declaration));
                None
            }
        }
    }

    /// The declaration of `name`.
    pub fn get(&self, name: &str) -> Option<&serde_json::Value> {
        self.entries.iter().find(|(existing, _)| existing == name).map(|(_, value)| value)
    }

    /// The declaration of `name`, to change.
    pub fn get_mut(&mut self, name: &str) -> Option<&mut serde_json::Value> {
        self.entries.iter_mut().find(|(existing, _)| existing == name).map(|(_, value)| value)
    }

    /// Whether `name` is declared.
    pub fn contains_key(&self, name: &str) -> bool {
        self.get(name).is_some()
    }

    /// Removes `name`, keeping the order of the rest. Returns its declaration.
    pub fn remove(&mut self, name: &str) -> Option<serde_json::Value> {
        let index = self.entries.iter().position(|(existing, _)| existing == name)?;
        Some(self.entries.remove(index).1)
    }

    /// Keeps the declarations `keep` accepts, in order.
    pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut serde_json::Value) -> bool) {
        self.entries.retain_mut(|(name, value)| keep(name, value));
    }

    /// Names and declarations, in declaration order.
    pub fn iter(&self) -> ToolDeclarationsIter<'_> {
        self.entries.iter().map(|(name, value)| (name, value))
    }

    /// Names, in declaration order.
    pub fn keys(&self) -> ToolDeclarationsKeys<'_> {
        ToolDeclarationsKeys { entries: self.entries.iter() }
    }

    /// Declarations, in declaration order.
    pub fn values(&self) -> ToolDeclarationsValues<'_> {
        ToolDeclarationsValues { entries: self.entries.iter() }
    }
}

/// The names in [`ToolDeclarations`], in declaration order. Prints as a list of the names,
/// as a `HashMap`'s keys do.
#[derive(Clone)]
pub struct ToolDeclarationsKeys<'a> {
    entries: std::slice::Iter<'a, (String, serde_json::Value)>,
}

impl<'a> Iterator for ToolDeclarationsKeys<'a> {
    type Item = &'a String;

    fn next(&mut self) -> Option<&'a String> {
        self.entries.next().map(|(name, _)| name)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.entries.size_hint()
    }
}

impl DoubleEndedIterator for ToolDeclarationsKeys<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.entries.next_back().map(|(name, _)| name)
    }
}

impl ExactSizeIterator for ToolDeclarationsKeys<'_> {}

impl std::fmt::Debug for ToolDeclarationsKeys<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// The declarations in [`ToolDeclarations`], in declaration order. Prints as a list of the
/// declarations, as a `HashMap`'s values do.
#[derive(Clone)]
pub struct ToolDeclarationsValues<'a> {
    entries: std::slice::Iter<'a, (String, serde_json::Value)>,
}

impl<'a> Iterator for ToolDeclarationsValues<'a> {
    type Item = &'a serde_json::Value;

    fn next(&mut self) -> Option<&'a serde_json::Value> {
        self.entries.next().map(|(_, value)| value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.entries.size_hint()
    }
}

impl DoubleEndedIterator for ToolDeclarationsValues<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.entries.next_back().map(|(_, value)| value)
    }
}

impl ExactSizeIterator for ToolDeclarationsValues<'_> {}

impl std::fmt::Debug for ToolDeclarationsValues<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// An iterator over [`ToolDeclarations`], in declaration order.
pub type ToolDeclarationsIter<'a> = std::iter::Map<
    std::slice::Iter<'a, (String, serde_json::Value)>,
    fn(&'a (String, serde_json::Value)) -> (&'a String, &'a serde_json::Value),
>;

impl std::ops::Index<&str> for ToolDeclarations {
    type Output = serde_json::Value;

    /// The declaration of `name`; panics when it is not declared.
    fn index(&self, name: &str) -> &serde_json::Value {
        self.get(name).unwrap_or_else(|| panic!("tool {name} is not declared"))
    }
}

impl<'a> IntoIterator for &'a ToolDeclarations {
    type Item = (&'a String, &'a serde_json::Value);
    type IntoIter = ToolDeclarationsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for ToolDeclarations {
    type Item = (String, serde_json::Value);
    type IntoIter = std::vec::IntoIter<(String, serde_json::Value)>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl<K: Into<String>> FromIterator<(K, serde_json::Value)> for ToolDeclarations {
    fn from_iter<I: IntoIterator<Item = (K, serde_json::Value)>>(iter: I) -> Self {
        let mut tools = Self::new();
        tools.extend(iter);
        tools
    }
}

impl<K: Into<String>> Extend<(K, serde_json::Value)> for ToolDeclarations {
    fn extend<I: IntoIterator<Item = (K, serde_json::Value)>>(&mut self, iter: I) {
        for (name, declaration) in iter {
            self.insert(name.into(), declaration);
        }
    }
}

/// A request to an LLM provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmRequest {
    /// The model identifier to use for generation.
    pub model: String,
    /// The conversation contents (system, user, model messages).
    pub contents: Vec<Content>,
    /// Optional generation configuration (temperature, tokens, etc.).
    pub config: Option<GenerateContentConfig>,
    /// Tool declarations keyed by tool name, in declaration order.
    #[serde(skip)]
    pub tools: ToolDeclarations,
    /// Provider-neutral identifier of the previous response to continue from.
    /// The agent populates this from the most recent event's `interaction_id`.
    /// Maps to `previous_interaction_id` for the Gemini Interactions transport;
    /// ignored by transports that do not support response chaining.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub previous_response_id: Option<String>,
}

/// How much reasoning effort a model spends (spec 3.1 §7.23, §10 C4).
///
/// Each provider maps a level to its own control: Anthropic `output_config.effort` with
/// adaptive thinking, OpenAI `reasoning_effort`, Gemini `thinking_level`. Levels above
/// `High` (`xhigh`, `max`) and below `Low` (`minimal`, `none`) are reachable only through a
/// provider's own configuration.
///
/// # Example
///
/// ```rust
/// use adk_core::Effort;
///
/// assert_eq!("high".parse::<Effort>(), Ok(Effort::High));
/// assert_eq!(Effort::Low.to_string(), "low");
/// assert!(Effort::Low < Effort::High);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
    /// The least reasoning a provider offers short of none.
    Low,
    /// Balanced reasoning.
    Medium,
    /// Thorough reasoning.
    High,
}

impl Effort {
    /// Every level, lowest first.
    pub const ALL: [Effort; 3] = [Effort::Low, Effort::Medium, Effort::High];

    /// The level's name as flags and configuration files spell it.
    pub const fn as_str(self) -> &'static str {
        match self {
            Effort::Low => "low",
            Effort::Medium => "medium",
            Effort::High => "high",
        }
    }
}

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

impl std::str::FromStr for Effort {
    type Err = String;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "low" => Ok(Effort::Low),
            "medium" => Ok(Effort::Medium),
            "high" => Ok(Effort::High),
            other => Err(format!("unknown effort '{other}'; use low, medium or high")),
        }
    }
}

/// Configuration for LLM content generation.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GenerateContentConfig {
    /// Sampling temperature (0.0 = deterministic, higher = more random).
    pub temperature: Option<f32>,
    /// Nucleus sampling threshold.
    pub top_p: Option<f32>,
    /// Top-k sampling parameter.
    pub top_k: Option<i32>,
    /// Frequency penalty to reduce repetition.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub frequency_penalty: Option<f32>,
    /// Presence penalty to encourage topic diversity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub presence_penalty: Option<f32>,
    /// Maximum number of output tokens to generate.
    pub max_output_tokens: Option<i32>,
    /// Random seed for reproducible generation.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub seed: Option<i64>,
    /// Number of top log probabilities to return per token.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub top_logprobs: Option<u8>,
    /// Sequences that stop generation when encountered.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stop_sequences: Vec<String>,
    /// JSON Schema for structured output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_schema: Option<serde_json::Value>,

    /// Output modalities requested from Gemini, such as `["TEXT", "IMAGE"]`.
    /// Other clients reject this field rather than silently dropping it.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::GenerateContentConfig;
    /// let config = GenerateContentConfig {
    ///     response_modalities: Some(vec!["TEXT".into(), "IMAGE".into()]),
    ///     ..Default::default()
    /// };
    /// assert_eq!(config.response_modalities.as_ref().unwrap().len(), 2);
    /// ```
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub response_modalities: Option<Vec<String>>,

    /// Optional cached content name for Gemini provider.
    /// When set, the Gemini provider attaches this to the generation request.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cached_content: Option<String>,

    /// The reasoning effort of this call (spec 3.1 §7.23, §10 C4).
    ///
    /// A set value wins over the effort the client was built with: Anthropic sends it as
    /// `output_config.effort` with adaptive thinking, OpenAI as `reasoning_effort` (Chat
    /// Completions) or `reasoning.effort` (Responses), Gemini as `thinking_level`, and
    /// OpenRouter and DeepSeek as their reasoning effort. A provider or model with no effort
    /// control ignores it and logs at debug level. `None` keeps the client's own
    /// configuration.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{Effort, GenerateContentConfig};
    ///
    /// let config = GenerateContentConfig { effort: Some(Effort::High), ..Default::default() };
    /// assert_eq!(serde_json::to_value(&config).unwrap()["effort"], "high");
    /// assert!(serde_json::to_value(GenerateContentConfig::default()).unwrap().get("effort").is_none());
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effort: Option<Effort>,

    /// Provider-specific request options keyed by provider namespace.
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extensions: serde_json::Map<String, serde_json::Value>,
}

/// A response from an LLM provider.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LlmResponse {
    /// The generated content (text, function calls, etc.).
    pub content: Option<Content>,
    /// Token usage statistics.
    pub usage_metadata: Option<UsageMetadata>,
    /// Reason the model stopped generating.
    pub finish_reason: Option<FinishReason>,
    /// Citation sources referenced in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub citation_metadata: Option<CitationMetadata>,
    /// Whether this is a partial streaming chunk.
    pub partial: bool,
    /// Whether the model has finished its turn.
    pub turn_complete: bool,
    /// Whether the response was interrupted.
    pub interrupted: bool,
    /// Error code from the provider, if any.
    pub error_code: Option<String>,
    /// Error message from the provider, if any.
    pub error_message: Option<String>,
    /// Provider-specific metadata (e.g., response IDs, routing info).
    ///
    /// `LlmAgent` recognizes two optional boolean fields: `content_complete`
    /// on a non-partial response replaces accumulated deltas with authoritative
    /// content; `continue_turn` requests another bounded model iteration for
    /// a provider-native tool pause without a client function call.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub provider_metadata: Option<serde_json::Value>,
    /// Interactions API: the server-assigned interaction id for this turn, used
    /// to continue the conversation via `previous_interaction_id`. `None` for
    /// the generateContent transport and non-Gemini providers.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub interaction_id: Option<String>,
    /// Model that produced this response: the version the provider reports when
    /// it reports one, otherwise the identifier the request was sent to.
    ///
    /// Set by every `adk-model` provider. Budgets and pricing read it to
    /// attribute usage and cost; `None` means the producer did not attribute it.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub model: Option<String>,
    /// Provider that served this response, such as `"gemini"`, `"openai"`,
    /// `"anthropic"` or `"bedrock"`.
    ///
    /// Set by every `adk-model` provider; `None` means the producer did not
    /// attribute it.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub provider: Option<String>,
}

/// Trait for LLM providers that support prompt caching.
///
/// Providers implementing this trait can create and delete cached content
/// resources, enabling automatic prompt caching lifecycle management by the
/// runner. The runner stores an `Option<Arc<dyn CacheCapable>>` alongside the
/// primary `Arc<dyn Llm>` and calls these methods when [`ContextCacheConfig`]
/// is active.
///
/// # Example
///
/// ```rust,ignore
/// use adk_core::CacheCapable;
///
/// let cache_name = model
///     .create_cache("You are a helpful assistant.", &tools, 600)
///     .await?;
/// // ... use cache_name in generation requests ...
/// model.delete_cache(&cache_name).await?;
/// ```
#[async_trait]
pub trait CacheCapable: Send + Sync {
    /// Create a cached content resource from the given system instruction,
    /// tool definitions, and TTL.
    ///
    /// Returns the provider-specific cache name (e.g. `"cachedContents/abc123"`
    /// for Gemini) that can be attached to subsequent generation requests via
    /// [`GenerateContentConfig::cached_content`].
    async fn create_cache(
        &self,
        system_instruction: &str,
        tools: &ToolDeclarations,
        ttl_seconds: u32,
    ) -> Result<String>;

    /// Delete a previously created cached content resource by name.
    async fn delete_cache(&self, name: &str) -> Result<()>;
}

/// Configuration for automatic prompt caching lifecycle management.
///
/// When set on runner configuration, the runner will automatically create and manage
/// cached content resources for supported providers (currently Gemini).
///
/// # Example
///
/// ```rust
/// use adk_core::ContextCacheConfig;
///
/// let config = ContextCacheConfig {
///     min_tokens: 4096,
///     ttl_seconds: 600,
///     cache_intervals: 3,
/// };
/// assert_eq!(config.min_tokens, 4096);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextCacheConfig {
    /// Minimum system instruction + tool token count to trigger caching.
    /// Set to 0 to disable caching.
    pub min_tokens: u32,

    /// Cache time-to-live in seconds.
    /// Set to 0 to disable caching.
    pub ttl_seconds: u32,

    /// Maximum number of LLM invocations before cache refresh.
    /// After this many invocations, the runner creates a new cache
    /// and deletes the old one.
    pub cache_intervals: u32,
}

impl Default for ContextCacheConfig {
    fn default() -> Self {
        Self { min_tokens: 4096, ttl_seconds: 600, cache_intervals: 3 }
    }
}

/// Token usage statistics from an LLM response.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UsageMetadata {
    /// Number of tokens in the prompt.
    pub prompt_token_count: i32,
    /// Number of tokens in the generated response.
    pub candidates_token_count: i32,
    /// Total tokens (prompt + response).
    pub total_token_count: i32,

    /// Tokens read from cache (Gemini/Anthropic).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cache_read_input_token_count: Option<i32>,

    /// Tokens written to cache during this request.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cache_creation_input_token_count: Option<i32>,

    /// Tokens used for thinking/reasoning (thinking models).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub thinking_token_count: Option<i32>,

    /// Audio input tokens (multimodal models).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub audio_input_token_count: Option<i32>,

    /// Audio output tokens (multimodal models).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub audio_output_token_count: Option<i32>,

    /// Estimated cost in USD for this request.
    ///
    /// `adk-model` providers fill this from the provider's own report when it
    /// sends one (OpenRouter), otherwise from `adk_model::pricing::PricingCatalog`.
    /// `None` means the cost is unknown, never that the request was free.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cost: Option<f64>,

    /// Whether this request used a bring-your-own-key provider.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub is_byok: Option<bool>,

    /// Provider-native usage data retained when available, including fields
    /// that are not yet projected into the normalized counters above.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub provider_usage: Option<serde_json::Value>,

    /// Provider-executed built-in tool uses the provider reported for this request.
    ///
    /// Each use counts as one tool call against a
    /// [`RunBudget`](crate::RunBudget), and priced kinds add their per-use fee to
    /// [`cost`](Self::cost). See [`BuiltinToolUse`] for the kinds providers report.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub builtin_tool_uses: Vec<BuiltinToolUse>,
}

impl UsageMetadata {
    /// Total number of provider-executed built-in tool uses across all kinds.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::{BuiltinToolUse, UsageMetadata};
    ///
    /// let usage = UsageMetadata {
    ///     builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 2), BuiltinToolUse::new("web_fetch", 1)],
    ///     ..Default::default()
    /// };
    /// assert_eq!(usage.builtin_tool_use_count(), 3);
    /// ```
    pub fn builtin_tool_use_count(&self) -> u64 {
        self.builtin_tool_uses.iter().map(|used| u64::from(used.count)).sum()
    }
}

/// Deserializes a token count that a provider may report as `null`, reading `null` as zero.
///
/// Pair it with `#[serde(default)]` so that a missing count is zero too. Compatible endpoints
/// report a count they did not compute as `null` or leave it out, and that must not fail the
/// model turn the usage belongs to. Fields typed `Option<_>` need no helper: serde already
/// reads `null` there as `None`.
///
/// # Example
///
/// ```
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Usage {
///     #[serde(default, deserialize_with = "adk_core::nullable_count")]
///     input_tokens: u32,
/// }
///
/// let usage: Usage = serde_json::from_str(r#"{"input_tokens": null}"#).unwrap();
/// assert_eq!(usage.input_tokens, 0);
/// let usage: Usage = serde_json::from_str("{}").unwrap();
/// assert_eq!(usage.input_tokens, 0);
/// let usage: Usage = serde_json::from_str(r#"{"input_tokens": 12}"#).unwrap();
/// assert_eq!(usage.input_tokens, 12);
/// ```
///
/// # Errors
///
/// Returns the deserializer's error when the value is neither `null` nor a `T`.
pub fn nullable_count<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}

/// How many times the provider ran one kind of built-in tool for a request.
///
/// Kinds are provider-neutral names:
///
/// | Kind | Reported by |
/// |------|-------------|
/// | `web_search` | Anthropic `usage.server_tool_use.web_search_requests`, OpenAI `web_search_call` items |
/// | `web_fetch` | Anthropic `usage.server_tool_use.web_fetch_requests` |
/// | `code_execution` | Anthropic `usage.server_tool_use.code_execution_requests`, OpenAI `code_interpreter_call` items, Gemini `executableCode` parts |
/// | `file_search` | OpenAI `file_search_call` items |
/// | `image_generation` | OpenAI `image_generation_call` items |
/// | `mcp` | OpenAI `mcp_call` items |
/// | `google_search` | Gemini `groundingMetadata.webSearchQueries` (one per query) |
/// | `google_maps` | Gemini grounding chunks with a `maps` source (one per grounded response) |
///
/// # Example
///
/// ```
/// use adk_core::BuiltinToolUse;
///
/// let used = BuiltinToolUse::new("web_search", 3);
/// assert_eq!(used.kind, "web_search");
/// assert_eq!(used.count, 3);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuiltinToolUse {
    /// Provider-neutral tool kind, such as `web_search`.
    pub kind: String,
    /// Number of uses the provider reported.
    pub count: u32,
}

impl BuiltinToolUse {
    /// Creates a record of `count` uses of `kind`.
    pub fn new(kind: impl Into<String>, count: u32) -> Self {
        Self { kind: kind.into(), count }
    }
}

/// The wire form of a provider-executed web search tool (spec 3.1 §7.20).
///
/// Each variant names the `adk-tool` built-in that declares it.
///
/// | Variant | Built-in | Request entry |
/// |---------|----------|---------------|
/// | `GoogleSearch` | `GoogleSearchTool` | Gemini `tools[].google_search` |
/// | `AnthropicWebSearch` | `WebSearchTool` | Messages `web_search_20250305` server tool |
/// | `OpenAiWebSearch` | `OpenAIWebSearchTool` | Responses `{"type": "web_search"}` |
/// | `DeepSeekWebSearch` | `DeepSeekWebSearchTool` | DeepSeek Responses `{"type": "web_search"}` |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NativeWebSearchTool {
    /// Gemini `google_search` grounding.
    GoogleSearch,
    /// The Anthropic Messages `web_search` server tool.
    AnthropicWebSearch,
    /// The OpenAI Responses `web_search` tool.
    OpenAiWebSearch,
    /// The `web_search` tool of DeepSeek's Responses endpoint.
    DeepSeekWebSearch,
}

/// The provider-executed web search a model's transport serves (spec 3.1 §7.20), as
/// [`Llm::native_web_search`] reports it.
///
/// # Example
///
/// ```rust
/// use adk_core::{NativeWebSearch, NativeWebSearchTool};
///
/// let search = NativeWebSearch::new("gemini", NativeWebSearchTool::GoogleSearch, false);
/// assert_eq!(search.provider, "gemini");
/// assert!(!search.allowed_domains, "google_search takes no domain allowlist");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct NativeWebSearch {
    /// Provider that runs the search, such as `"gemini"`, `"anthropic"`, `"openai"` or
    /// `"deepseek"`.
    pub provider: &'static str,
    /// The tool the request declares.
    pub tool: NativeWebSearchTool,
    /// Whether the provider honours a domain allowlist on the tool.
    pub allowed_domains: bool,
}

impl NativeWebSearch {
    /// Describes the search `provider` runs through `tool`, with or without a domain
    /// allowlist.
    pub fn new(provider: &'static str, tool: NativeWebSearchTool, allowed_domains: bool) -> Self {
        Self { provider, tool, allowed_domains }
    }
}

/// The conversation compaction a model's provider performs itself, as
/// [`Llm::native_compaction`] reports it.
///
/// # Example
///
/// ```rust
/// use adk_core::NativeCompaction;
///
/// let compaction = NativeCompaction::new("anthropic").keeping_thinking();
/// assert_eq!(compaction.provider, "anthropic");
/// assert!(compaction.keeps_thinking);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct NativeCompaction {
    /// Provider that writes the summary, such as `"anthropic"`.
    pub provider: &'static str,
    /// Whether the turns kept after the summary keep their thinking: the provider accepts
    /// thinking that was produced before the summary replaced the turns it followed.
    pub keeps_thinking: bool,
}

impl NativeCompaction {
    /// The compaction `provider` performs; the kept turns lose their thinking.
    pub fn new(provider: &'static str) -> Self {
        Self { provider, keeps_thinking: false }
    }

    /// The kept turns keep their thinking after the summary.
    pub fn keeping_thinking(mut self) -> Self {
        self.keeps_thinking = true;
        self
    }
}

/// Citation metadata emitted by model providers for source attribution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationMetadata {
    /// The list of citation sources in this response.
    #[serde(default)]
    pub citation_sources: Vec<CitationSource>,
}

/// One citation source with optional offsets.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationSource {
    /// URI of the cited source.
    pub uri: Option<String>,
    /// Title of the cited source.
    pub title: Option<String>,
    /// Start character index in the response text.
    pub start_index: Option<i32>,
    /// End character index in the response text.
    pub end_index: Option<i32>,
    /// License of the cited source.
    pub license: Option<String>,
    /// Publication date of the cited source.
    pub publication_date: Option<String>,
}

/// Reason the model stopped generating content.
///
/// The enum is `#[non_exhaustive]`: providers add stop reasons, so a `match` outside
/// `adk-core` needs a wildcard arm. Each variant serializes as its name (`"Stop"`,
/// `"Refusal"`, ...), and a name this version does not know deserializes as
/// [`Other`](Self::Other), so an event written by a newer release still loads.
///
/// `LlmAgent` and `CodeActAgent` end the run with an error on [`Refusal`](Self::Refusal)
/// (`model.refusal`) and [`MalformedToolCall`](Self::MalformedToolCall)
/// (`model.malformed_tool_call`); the other reasons leave the outcome to the content.
///
/// # Example
///
/// ```
/// use adk_core::FinishReason;
///
/// fn succeeded(reason: Option<FinishReason>) -> bool {
///     match reason {
///         Some(FinishReason::Stop) | None => true,
///         Some(FinishReason::Refusal | FinishReason::MalformedToolCall) => false,
///         Some(_) => false,
///     }
/// }
///
/// assert!(!succeeded(Some(FinishReason::Refusal)));
/// assert_eq!(serde_json::to_string(&FinishReason::Refusal).unwrap(), "\"Refusal\"");
/// assert_eq!(
///     serde_json::from_str::<FinishReason>("\"SomeLaterReason\"").unwrap(),
///     FinishReason::Other
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum FinishReason {
    /// Natural stop (end of response).
    Stop,
    /// Hit the maximum token limit.
    MaxTokens,
    /// A content filter blocked or cut the response, such as Gemini `SAFETY`, OpenAI
    /// `content_filter`, or a Bedrock guardrail.
    Safety,
    /// Content blocked due to recitation/copyright.
    Recitation,
    /// The model declined the request: Anthropic `stop_reason: "refusal"`, an OpenAI Chat
    /// Completions `refusal`, or a Responses `refusal` content part. The response's text, when
    /// present, is the refusal, not an answer.
    Refusal,
    /// The provider reports a tool call the model generated as invalid: Gemini
    /// `MALFORMED_FUNCTION_CALL` or `UNEXPECTED_TOOL_CALL`, Bedrock `malformed_tool_use`.
    MalformedToolCall,
    /// Other/unknown reason, including a name a newer release wrote.
    #[serde(other)]
    Other,
}

impl LlmRequest {
    /// Creates a new request with the given model and contents.
    pub fn new(model: impl Into<String>, contents: Vec<Content>) -> Self {
        Self {
            model: model.into(),
            contents,
            config: None,
            tools: ToolDeclarations::new(),
            previous_response_id: None,
        }
    }

    /// Set the response schema for structured output.
    pub fn with_response_schema(mut self, schema: serde_json::Value) -> Self {
        let config = self.config.get_or_insert(GenerateContentConfig::default());
        config.response_schema = Some(schema);
        self
    }

    /// Set the generation config.
    pub fn with_config(mut self, config: GenerateContentConfig) -> Self {
        self.config = Some(config);
        self
    }
}

impl LlmResponse {
    /// Creates a complete (non-streaming) response with the given content.
    pub fn new(content: Content) -> Self {
        Self {
            content: Some(content),
            usage_metadata: None,
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: None,
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
            model: None,
            provider: None,
        }
    }
}

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

    #[test]
    fn a_loopback_host_is_loopback_and_every_other_host_remote() {
        for url in [
            "http://localhost:11434",
            "http://LOCALHOST.:8000/v1",
            "http://vllm.localhost/v1",
            "http://127.0.0.1:1234/v1",
            "http://127.8.9.10",
            "http://[::1]:8080",
            "http://[::ffff:127.0.0.1]:8080",
            " https://localhost/v1/ ",
        ] {
            assert_eq!(DataLocality::of_url(url), DataLocality::Loopback, "{url}");
        }
        for url in [
            "https://api.openai.com/v1",
            "http://localhost.example.com",
            "http://0.0.0.0:11434",
            "http://10.0.0.5:11434",
            "http://[::2]",
            "localhost:11434",
            "not a url",
            "",
        ] {
            assert_eq!(DataLocality::of_url(url), DataLocality::Remote, "{url}");
        }
    }

    #[test]
    fn the_least_local_of_several_localities_wins() {
        use DataLocality::{InProcess, Loopback, Remote};
        assert_eq!(DataLocality::least_local([InProcess, InProcess]), InProcess);
        assert_eq!(DataLocality::least_local([InProcess, Loopback]), Loopback);
        assert_eq!(DataLocality::least_local([Loopback, Remote, InProcess]), Remote);
        assert_eq!(DataLocality::least_local([]), Remote);
        assert_eq!(DataLocality::default(), Remote);
        assert!(Remote.leaves_machine() && Remote.leaves_process());
        assert!(!Loopback.leaves_machine() && Loopback.leaves_process());
        assert!(!InProcess.leaves_machine() && !InProcess.leaves_process());
        for locality in [InProcess, Loopback, Remote] {
            let wire = serde_json::to_value(locality).unwrap();
            assert_eq!(serde_json::from_value::<DataLocality>(wire).unwrap(), locality);
        }
    }

    #[test]
    fn a_metered_model_reports_the_wrapped_models_locality() {
        struct Local;

        #[async_trait]
        impl Llm for Local {
            fn name(&self) -> &str {
                "local"
            }
            async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
                Ok(Box::pin(futures::stream::empty()))
            }
            fn data_locality(&self) -> DataLocality {
                DataLocality::InProcess
            }
            fn data_destinations(&self) -> Vec<DataDestination> {
                vec![DataDestination::new("local", ["127.0.0.1:8080"])]
            }
        }

        let metered = crate::MeteredLlm::new(std::sync::Arc::new(Local));
        assert_eq!(metered.data_locality(), DataLocality::InProcess);
        assert_eq!(
            metered.data_destinations(),
            vec![DataDestination::new("local", ["127.0.0.1:8080"])]
        );
    }

    #[test]
    fn a_destination_names_the_endpoint_host_and_any_port_but_443() {
        for (url, host) in [
            ("https://api.anthropic.com", "api.anthropic.com"),
            ("https://API.OpenAI.com./v1", "api.openai.com"),
            (
                "https://bedrock-runtime.eu-west-1.amazonaws.com:443/x",
                "bedrock-runtime.eu-west-1.amazonaws.com",
            ),
            ("http://localhost:11434", "localhost:11434"),
            ("http://gpu-box/v1", "gpu-box:80"),
            ("https://nim.internal:8443/v1", "nim.internal:8443"),
            ("http://[::1]:8000/v1", "[::1]:8000"),
        ] {
            assert_eq!(
                DataDestination::of_url("p", url),
                DataDestination::new("p", [host]),
                "{url}"
            );
        }
        for url in ["not a url", "", "data:text/plain,x"] {
            assert!(DataDestination::of_url("p", url).hosts.is_empty(), "{url}");
        }
    }

    #[test]
    fn a_model_that_does_not_say_has_no_destination() {
        struct Silent;

        #[async_trait]
        impl Llm for Silent {
            fn name(&self) -> &str {
                "silent"
            }
            async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
                Ok(Box::pin(futures::stream::empty()))
            }
        }

        assert!(Silent.data_destinations().is_empty());
    }

    #[test]
    fn tool_names_and_declarations_print_as_lists() {
        let tools: ToolDeclarations = [
            ("search", serde_json::json!({"name": "search"})),
            ("add", serde_json::json!({"name": "add"})),
        ]
        .into_iter()
        .collect();
        assert_eq!(format!("{:?}", tools.keys()), r#"["search", "add"]"#);
        assert_eq!(
            format!("{:?}", tools.values()),
            r#"[Object {"name": String("search")}, Object {"name": String("add")}]"#
        );
        assert_eq!(tools.keys().len(), 2);
        assert_eq!(tools.keys().next_back().map(String::as_str), Some("add"));
    }

    #[test]
    fn test_llm_request_creation() {
        let req = LlmRequest::new("test-model", vec![]);
        assert_eq!(req.model, "test-model");
        assert!(req.contents.is_empty());
    }

    #[test]
    fn test_llm_request_with_response_schema() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            }
        });
        let req = LlmRequest::new("test-model", vec![]).with_response_schema(schema.clone());

        assert!(req.config.is_some());
        let config = req.config.unwrap();
        assert!(config.response_schema.is_some());
        assert_eq!(config.response_schema.unwrap(), schema);
    }

    #[test]
    fn test_llm_request_with_config() {
        let config = GenerateContentConfig {
            temperature: Some(0.7),
            top_p: Some(0.9),
            top_k: Some(40),
            frequency_penalty: Some(0.2),
            presence_penalty: Some(-0.3),
            max_output_tokens: Some(1024),
            seed: Some(42),
            top_logprobs: Some(5),
            stop_sequences: vec!["END".to_string()],
            ..Default::default()
        };
        let req = LlmRequest::new("test-model", vec![]).with_config(config);

        assert!(req.config.is_some());
        let config = req.config.unwrap();
        assert_eq!(config.temperature, Some(0.7));
        assert_eq!(config.max_output_tokens, Some(1024));
        assert_eq!(config.frequency_penalty, Some(0.2));
        assert_eq!(config.presence_penalty, Some(-0.3));
        assert_eq!(config.seed, Some(42));
        assert_eq!(config.top_logprobs, Some(5));
        assert_eq!(config.stop_sequences, vec!["END"]);
    }

    #[test]
    fn test_llm_response_creation() {
        let content = Content::new("assistant");
        let resp = LlmResponse::new(content);
        assert!(resp.content.is_some());
        assert!(resp.turn_complete);
        assert!(!resp.partial);
        assert_eq!(resp.finish_reason, Some(FinishReason::Stop));
        assert!(resp.citation_metadata.is_none());
        assert!(resp.provider_metadata.is_none());
    }

    #[test]
    fn test_llm_response_deserialize_without_citations() {
        let json = serde_json::json!({
            "content": {
                "role": "model",
                "parts": [{"text": "hello"}]
            },
            "partial": false,
            "turn_complete": true,
            "interrupted": false
        });

        let response: LlmResponse = serde_json::from_value(json).expect("should deserialize");
        assert!(response.citation_metadata.is_none());
    }

    #[test]
    fn test_llm_response_roundtrip_with_citations() {
        let response = LlmResponse {
            content: Some(Content::new("model").with_text("hello")),
            usage_metadata: None,
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: Some(CitationMetadata {
                citation_sources: vec![CitationSource {
                    uri: Some("https://example.com".to_string()),
                    title: Some("Example".to_string()),
                    start_index: Some(0),
                    end_index: Some(5),
                    license: None,
                    publication_date: Some("2026-01-01T00:00:00Z".to_string()),
                }],
            }),
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: None,
            interaction_id: None,
            model: None,
            provider: None,
        };

        let encoded = serde_json::to_string(&response).expect("serialize");
        let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");
        assert_eq!(decoded.citation_metadata, response.citation_metadata);
    }

    #[test]
    fn test_generate_content_config_roundtrip_with_extensions() {
        let mut extensions = serde_json::Map::new();
        extensions.insert(
            "openrouter".to_string(),
            serde_json::json!({
                "provider": {
                    "zdr": true,
                    "order": ["openai", "anthropic"]
                },
                "plugins": [
                    { "id": "web", "enabled": true }
                ]
            }),
        );

        let config = GenerateContentConfig {
            temperature: Some(0.4),
            top_p: Some(0.8),
            top_k: Some(12),
            frequency_penalty: Some(0.1),
            presence_penalty: Some(0.2),
            max_output_tokens: Some(512),
            seed: Some(7),
            top_logprobs: Some(3),
            stop_sequences: vec!["STOP".to_string(), "DONE".to_string()],
            response_schema: Some(serde_json::json!({
                "type": "object",
                "properties": { "answer": { "type": "string" } },
                "required": ["answer"]
            })),
            response_modalities: Some(vec!["TEXT".to_string(), "IMAGE".to_string()]),
            cached_content: Some("cachedContents/abc123".to_string()),
            effort: Some(Effort::Medium),
            extensions,
        };

        let encoded = serde_json::to_string(&config).expect("serialize");
        let decoded: GenerateContentConfig = serde_json::from_str(&encoded).expect("deserialize");

        assert_eq!(decoded.temperature, config.temperature);
        assert_eq!(decoded.top_p, config.top_p);
        assert_eq!(decoded.top_k, config.top_k);
        assert_eq!(decoded.frequency_penalty, config.frequency_penalty);
        assert_eq!(decoded.presence_penalty, config.presence_penalty);
        assert_eq!(decoded.max_output_tokens, config.max_output_tokens);
        assert_eq!(decoded.seed, config.seed);
        assert_eq!(decoded.top_logprobs, config.top_logprobs);
        assert_eq!(decoded.stop_sequences, config.stop_sequences);
        assert_eq!(decoded.response_schema, config.response_schema);
        assert_eq!(decoded.cached_content, config.cached_content);
        assert_eq!(decoded.extensions, config.extensions);
        assert_eq!(decoded.response_modalities, config.response_modalities);
        assert_eq!(decoded.effort, config.effort);
    }

    #[test]
    fn a_config_without_effort_reads_and_writes_as_before() {
        let legacy: GenerateContentConfig =
            serde_json::from_value(serde_json::json!({ "temperature": 0.2 })).unwrap();
        assert_eq!(legacy.effort, None);
        assert_eq!(serde_json::to_value(&legacy).unwrap().get("effort"), None);
        let set: GenerateContentConfig =
            serde_json::from_value(serde_json::json!({ "effort": "low" })).unwrap();
        assert_eq!(set.effort, Some(Effort::Low));
    }

    #[test]
    fn test_llm_response_and_usage_roundtrip_with_provider_metadata() {
        let response = LlmResponse {
            content: Some(Content::new("model").with_text("hello")),
            usage_metadata: Some(UsageMetadata {
                prompt_token_count: 10,
                candidates_token_count: 20,
                total_token_count: 30,
                cache_read_input_token_count: Some(5),
                cache_creation_input_token_count: Some(2),
                thinking_token_count: Some(3),
                audio_input_token_count: Some(4),
                audio_output_token_count: Some(6),
                cost: Some(0.0125),
                is_byok: Some(true),
                provider_usage: Some(serde_json::json!({
                    "server_tool_use": {
                        "web_search_requests": 1
                    },
                    "prompt_tokens_details": {
                        "video_tokens": 8
                    }
                })),
                builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 1)],
            }),
            finish_reason: Some(FinishReason::Stop),
            citation_metadata: None,
            partial: false,
            turn_complete: true,
            interrupted: false,
            error_code: None,
            error_message: None,
            provider_metadata: Some(serde_json::json!({
                "openrouter": {
                    "responseId": "resp_123",
                    "outputItems": 2
                }
            })),
            interaction_id: None,
            model: None,
            provider: None,
        };

        let encoded = serde_json::to_string(&response).expect("serialize");
        let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");

        assert_eq!(decoded.provider_metadata, response.provider_metadata);
        assert_eq!(
            decoded.usage_metadata.as_ref().and_then(|u| u.cost),
            response.usage_metadata.as_ref().and_then(|u| u.cost),
        );
        assert_eq!(
            decoded.usage_metadata.as_ref().and_then(|u| u.is_byok),
            response.usage_metadata.as_ref().and_then(|u| u.is_byok),
        );
        assert_eq!(
            decoded.usage_metadata.as_ref().map(|u| u.builtin_tool_uses.clone()),
            Some(vec![BuiltinToolUse::new("web_search", 1)]),
        );
        assert_eq!(
            decoded.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
            response.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
        );
    }

    #[test]
    fn test_finish_reason() {
        assert_eq!(FinishReason::Stop, FinishReason::Stop);
        assert_ne!(FinishReason::Stop, FinishReason::MaxTokens);
    }

    /// Events and sessions store the finish reason by name, so the names are a wire format.
    #[test]
    fn finish_reason_wire_names_are_stable() {
        let names = [
            (FinishReason::Stop, "Stop"),
            (FinishReason::MaxTokens, "MaxTokens"),
            (FinishReason::Safety, "Safety"),
            (FinishReason::Recitation, "Recitation"),
            (FinishReason::Refusal, "Refusal"),
            (FinishReason::MalformedToolCall, "MalformedToolCall"),
            (FinishReason::Other, "Other"),
        ];
        for (reason, name) in names {
            assert_eq!(serde_json::to_value(reason).unwrap(), serde_json::json!(name));
            assert_eq!(
                serde_json::from_value::<FinishReason>(serde_json::json!(name)).unwrap(),
                reason
            );
        }
        assert_eq!(
            serde_json::from_value::<FinishReason>(serde_json::json!("ReasonFromALaterRelease"))
                .unwrap(),
            FinishReason::Other
        );
    }

    /// A response persisted before 3.0 still loads.
    #[test]
    fn a_persisted_response_still_loads() {
        let stored = serde_json::json!({
            "content": null,
            "usage_metadata": null,
            "finish_reason": "Safety",
            "partial": false,
            "turn_complete": true,
            "interrupted": false,
            "error_code": null,
            "error_message": null
        });
        let response: LlmResponse = serde_json::from_value(stored).unwrap();
        assert_eq!(response.finish_reason, Some(FinishReason::Safety));
    }
}