anda_core 0.13.3

Core types and traits for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
//! Core data models shared by agents, tools, and model adapters.
//!
//! The types in this module form the data contract between Anda runtimes,
//! model providers, agents, tools, and clients. They cover:
//! - agent and tool inputs/outputs ([`AgentInput`], [`AgentOutput`], [`ToolInput`], [`ToolOutput`]);
//! - chat messages and multimodal content ([`Message`], [`ContentPart`]);
//! - function-call metadata ([`FunctionDefinition`], [`ToolCall`]);
//! - request metadata and usage accounting ([`RequestMeta`], [`Usage`]);
//! - prompt documents and completion requests ([`Document`], [`Documents`], [`CompletionRequest`]).

use candid::Principal;
use encoding_rs::{Encoding, UTF_8};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Map, json};
use std::{
    borrow::Cow,
    collections::{BTreeMap, HashMap},
    str::FromStr,
};

use crate::{Json, json::normalize_strict_schema};
pub use ic_auth_types::{ByteArrayB64, ByteBufB64, Xid};

mod completion;
mod resource;

pub use completion::*;
pub use resource::*;

/// Request sent to an agent for processing.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct AgentInput {
    /// Agent name. When empty, the runtime selects its default agent.
    pub name: String,

    /// User prompt or task message for the agent.
    pub prompt: String,

    /// The resources to process by the agent.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub resources: Vec<Resource>,

    /// The topics for the agent request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topics: Option<Vec<String>>,

    /// Metadata for the agent request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<RequestMeta>,
}

impl AgentInput {
    /// Creates a new agent input with the given name and prompt.
    pub fn new(name: String, prompt: String) -> Self {
        Self {
            name,
            prompt,
            resources: Vec::new(),
            topics: None,
            meta: None,
        }
    }
}

/// Parsed command prefix from an agent prompt.
///
/// Empty prompts and `/ping` are treated as lightweight health checks. Prompts
/// without a leading slash are plain user prompts. Other slash-prefixed prompts
/// keep the original prompt while exposing the lowercase command name.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum PromptCommand {
    /// Empty prompt or `/ping`.
    #[default]
    Ping,
    /// Prompt text without a command prefix.
    Plain {
        /// Original prompt text.
        prompt: String,
    },
    /// Slash-prefixed command and the original prompt text.
    Command {
        /// Lowercase command name without the leading slash.
        command: String,
        /// Original prompt text.
        prompt: String,
    },
}

impl From<String> for PromptCommand {
    fn from(prompt: String) -> Self {
        let trimmed = prompt.trim();
        if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("/ping") {
            return Self::Ping;
        }

        let Some(stripped) = trimmed.strip_prefix('/') else {
            return Self::Plain { prompt };
        };
        let command_end = stripped.find(char::is_whitespace).unwrap_or(stripped.len());
        let command = &stripped[..command_end];

        Self::Command {
            command: command.to_lowercase(),
            prompt,
        }
    }
}

impl PromptCommand {
    /// Returns the argument text after the slash command prefix.
    ///
    /// If this command was built manually with a prompt that does not contain a matching slash
    /// prefix, the trimmed prompt is treated as the argument.
    pub fn command_argument(&self) -> Option<&str> {
        let Self::Command { command, prompt } = self else {
            return None;
        };

        let trimmed = prompt.trim();
        let Some(stripped) = trimmed.strip_prefix('/') else {
            return Some(trimmed);
        };

        let command_end = stripped.find(char::is_whitespace).unwrap_or(stripped.len());
        if !stripped[..command_end].eq_ignore_ascii_case(command) {
            return Some(trimmed);
        }

        Some(stripped[command_end..].trim())
    }
}

/// Output produced by an agent execution.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct AgentOutput {
    /// Final visible content from the agent. It may be empty.
    pub content: String,

    /// Optional intermediate reasoning text returned by providers that expose it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thoughts: Option<String>,

    /// The usage statistics for the agent execution.
    pub usage: Usage,

    /// The usage statistics for each tool called by the agent.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub tools_usage: HashMap<String, Usage>,

    /// Failure reason if execution failed. `None` indicates success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failed_reason: Option<String>,

    /// Tool calls returned by the LLM function calling.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCall>,

    /// The history of the conversation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub chat_history: Vec<Message>,

    /// Provider-specific conversation history used internally by model adapters.
    ///
    /// This is included in completion responses for follow-up calls, but should
    /// not be exposed as a stable engine API response.
    #[serde(skip)]
    pub raw_history: Vec<Json>,

    /// A collection of artifacts generated by the agent during the execution of the task.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub artifacts: Vec<Resource>,

    /// The conversation ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversation: Option<u64>,

    /// The session ID for the agent execution, if applicable.
    /// This is used to correlate related conversations or executions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,

    /// The model used by the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Partial agent output serialized when metadata must be preserved.
///
/// This compact shape is used when an [`AgentOutput`] is converted into a tool
/// output and cannot be represented as just the final content string or JSON
/// value.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct PartialAgentOutput {
    /// Final visible content from the agent.
    pub content: String,

    /// Optional intermediate reasoning text returned by the provider.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thoughts: Option<String>,

    /// Failure reason if execution failed. `None` indicates success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failed_reason: Option<String>,

    /// The conversation ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversation: Option<u64>,

    /// The session ID for the agent execution, if applicable.
    /// This is used to correlate related conversations or executions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,

    /// The model used by the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

impl AgentOutput {
    /// Converts an agent result into a JSON tool output.
    ///
    /// If the agent produced metadata such as thoughts, failure information,
    /// conversation IDs, or model labels, the output is wrapped as
    /// [`PartialAgentOutput`]. Otherwise the final content is parsed as JSON
    /// when possible and falls back to a JSON string.
    pub fn into_tool_output(self) -> ToolOutput<Json> {
        let AgentOutput {
            content,
            thoughts,
            usage,
            tools_usage,
            failed_reason,
            artifacts,
            conversation,
            session,
            model,
            ..
        } = self;
        let has_metadata = thoughts.is_some()
            || failed_reason.is_some()
            || conversation.is_some()
            || session.is_some()
            || model.is_some();

        let is_error = failed_reason
            .as_ref()
            .map(|reason| !reason.trim().is_empty());
        let output = if has_metadata {
            json!(PartialAgentOutput {
                content,
                thoughts,
                failed_reason,
                conversation,
                session,
                model,
            })
        } else {
            serde_json::from_str::<Json>(&content).unwrap_or(Json::String(content))
        };

        ToolOutput {
            output,
            is_error,
            artifacts,
            usage,
            tools_usage,
        }
    }
}

fn deserialize_content<'de, D>(deserializer: D) -> Result<Vec<ContentPart>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Json::deserialize(deserializer)?;
    match value {
        Json::Null => Ok(Vec::new()),
        Json::String(s) => Ok(vec![ContentPart::Text { text: s }]),
        Json::Array(_) => Vec::<ContentPart>::deserialize(value).map_err(serde::de::Error::custom),
        _ => Err(serde::de::Error::custom(
            "expected a string or array for content",
        )),
    }
}

/// Chat message sent to or returned by an LLM provider.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Message {
    /// Message role: "system", "user", "assistant", "tool".
    pub role: String,

    /// Message content parts.
    #[serde(default, deserialize_with = "deserialize_content")]
    pub content: Vec<ContentPart>,

    /// An optional name for the participant. Provides the model information to differentiate between participants of the same role.
    /// This field is not used by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// The user ID of the message sender.
    /// This field is not used by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<Principal>,

    /// The timestamp of the message.
    /// This field is not used by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<u64>,
}

impl Message {
    /// Returns all text content parts joined with blank lines.
    pub fn text(&self) -> Option<String> {
        let mut texts: Vec<&str> = Vec::new();
        for part in &self.content {
            if let ContentPart::Text { text } = part {
                texts.push(text);
            }
        }
        if texts.is_empty() {
            return None;
        }
        Some(texts.join("\n\n"))
    }

    /// Returns all reasoning content parts joined with blank lines.
    pub fn thoughts(&self) -> Option<String> {
        let mut thoughts: Vec<&str> = Vec::new();
        for part in &self.content {
            if let ContentPart::Reasoning { text } = part {
                thoughts.push(text);
            }
        }
        if thoughts.is_empty() {
            return None;
        }
        Some(thoughts.join("\n\n"))
    }

    /// Extracts tool calls from this message.
    pub fn tool_calls(&self) -> Vec<ToolCall> {
        let mut tool_calls: Vec<ToolCall> = Vec::new();
        for part in &self.content {
            if let ContentPart::ToolCall {
                name,
                args,
                call_id,
            } = part
            {
                tool_calls.push(ToolCall {
                    name: name.clone(),
                    args: args.clone(),
                    call_id: call_id.clone(),
                    result: None,
                    remote_id: None,
                });
            }
        }
        tool_calls
    }

    /// Removes non-visible content parts and appends a short pruning notice.
    pub fn prune_content(&mut self) -> usize {
        let original_len = self.content.len();
        self.content.retain(|part| {
            matches!(
                part,
                ContentPart::Text { .. }
                    | ContentPart::Reasoning { .. }
                    | ContentPart::Action { .. }
            )
        });
        let pruned = original_len - self.content.len();
        if pruned > 0 {
            self.content.push(ContentPart::Text {
                text: format!(
                    "[{} items (tool calls or files) pruned due to limits]",
                    pruned
                ),
            });
        }
        pruned
    }
}

/// A single content item inside a chat message.
///
/// The enum supports Anda's normalized content types while preserving unknown
/// provider-specific JSON payloads in [`ContentPart::Any`].
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all_fields = "camelCase")]
pub enum ContentPart {
    /// Visible text content.
    Text {
        /// Text body.
        text: String,
    },
    /// Provider reasoning or thinking text.
    Reasoning {
        /// Reasoning text body.
        text: String,
    },
    /// File content referenced by URI.
    FileData {
        /// URI pointing to the file data.
        file_uri: String,

        /// MIME type if known.
        #[serde(skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
    },
    /// Inline binary data with an explicit MIME type.
    InlineData {
        /// MIME type for the inline bytes.
        mime_type: String,
        /// Base64-encoded binary payload.
        data: ByteBufB64,
    },
    /// Tool call requested by a model.
    ToolCall {
        /// Tool function name.
        name: String,
        /// JSON arguments for the tool call.
        args: Json,

        /// Provider call identifier used to correlate tool outputs.
        #[serde(skip_serializing_if = "Option::is_none")]
        call_id: Option<String>,
    },
    /// Tool output returned to a model.
    ToolOutput {
        /// Tool function name.
        name: String,
        /// JSON output payload.
        output: Json,

        /// Whether the tool output represents an error.
        #[serde(skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,

        /// Provider call identifier this output answers.
        #[serde(skip_serializing_if = "Option::is_none")]
        call_id: Option<String>,

        /// Remote engine principal when the tool call was delegated.
        #[serde(skip_serializing_if = "Option::is_none")]
        remote_id: Option<Principal>,
    },
    /// Signed action payload emitted by an agent.
    Action {
        /// Action name.
        name: String,
        /// Action-specific payload.
        payload: Json,

        /// Principals that should receive the action.
        #[serde(skip_serializing_if = "Option::is_none")]
        recipients: Option<Vec<Principal>>,

        /// Optional signature over the action payload.
        #[serde(skip_serializing_if = "Option::is_none")]
        signature: Option<ByteBufB64>,
    },
    /// Provider-specific content part preserved as raw JSON.
    #[serde(untagged)]
    Any(Json),
}

impl ContentPart {
    /// Creates a content part of type `Any` with the given type tag and value.
    ///
    /// The type tag is only added when `val` serializes to a JSON object.
    pub fn any_from<T>(ty: &str, val: T) -> Self
    where
        T: Serialize,
    {
        let mut val = json!(val);
        if let Some(map) = val.as_object_mut() {
            map.insert("type".to_string(), ty.into());
        }
        ContentPart::Any(val)
    }

    /// Attempts to convert this content part of type `Any` into the specified type if the type tag matches.
    pub fn any_into<T>(self, ty: &str) -> Result<T, Box<Self>>
    where
        T: DeserializeOwned,
    {
        if let ContentPart::Any(val) = &self
            && let Some(t) = val.get("type").and_then(|x| x.as_str())
            && t == ty
        {
            T::deserialize(val).map_err(|_| Box::new(self))
        } else {
            Err(Box::new(self))
        }
    }
}

/// Converts a content part with inline data to a data URL string.
///
/// See <https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data>.
pub fn part_to_data_url(data: &ByteBufB64, mime_type: Option<&String>) -> String {
    format!(
        "data:{};base64,{}",
        mime_type.map(|m| m.as_str()).unwrap_or(""),
        data.to_base64()
    )
}

/// Parses a data URL string and extracts the inline data and MIME type, if applicable.
///
/// When the data URL omits the media type (e.g. `data:;base64,...`), the MIME
/// type is inferred from the decoded bytes, falling back to
/// `application/octet-stream` for base64 payloads and `text/plain` for
/// percent-encoded payloads.
pub fn inline_data_from_data_url(data_url: &str) -> Option<(ByteBufB64, String)> {
    if let Some(stripped) = data_url.strip_prefix("data:") {
        let (meta, data_part) = stripped.split_once(",")?;

        if let Some(mime_part) = meta.strip_suffix(";base64") {
            if let Ok(data) = ByteBufB64::from_str(data_part) {
                let mime_type = if mime_part.is_empty() {
                    infer2::get(&data)
                        .map(|t| t.mime_type().to_string())
                        .unwrap_or_else(|| "application/octet-stream".to_string())
                } else {
                    mime_part.to_string()
                };
                Some((data, mime_type))
            } else {
                None
            }
        } else {
            let data = decode_percent_encoded_bytes(data_part)?;
            let mime_type = if meta.is_empty() {
                infer2::get(&data)
                    .map(|t| t.mime_type().to_string())
                    .unwrap_or_else(|| "text/plain".to_string())
            } else {
                meta.to_string()
            };
            Some((data, mime_type))
        }
    } else if let Ok(data) = ByteBufB64::from_str(data_url) {
        let mime_type = infer2::get(&data).map(|t| t.mime_type().to_string());
        Some((
            data,
            mime_type.unwrap_or_else(|| "application/octet-stream".to_string()),
        ))
    } else {
        None
    }
}

impl<'de> Deserialize<'de> for ContentPart {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = Json::deserialize(deserializer)?;
        match &value {
            Json::String(s) => Ok(ContentPart::Text { text: s.clone() }),
            Json::Object(map)
                if matches!(
                    map.get("type").and_then(|t| t.as_str()),
                    Some(
                        "Text"
                            | "Reasoning"
                            | "FileData"
                            | "InlineData"
                            | "ToolCall"
                            | "ToolOutput"
                            | "Action"
                    )
                ) =>
            {
                #[derive(Deserialize)]
                #[serde(tag = "type", rename_all_fields = "camelCase")]
                enum Helper {
                    Text {
                        text: String,
                    },
                    Reasoning {
                        text: String,
                    },
                    FileData {
                        file_uri: String,
                        mime_type: Option<String>,
                    },
                    InlineData {
                        mime_type: String,
                        data: ByteBufB64,
                    },
                    ToolCall {
                        name: String,
                        args: Json,
                        call_id: Option<String>,
                    },
                    ToolOutput {
                        name: String,
                        output: Json,
                        is_error: Option<bool>,
                        call_id: Option<String>,
                        remote_id: Option<Principal>,
                    },
                    Action {
                        name: String,
                        payload: Json,
                        recipients: Option<Vec<Principal>>,
                        signature: Option<ByteBufB64>,
                    },
                }

                match serde_json::from_value::<Helper>(value) {
                    Ok(h) => Ok(match h {
                        Helper::Text { text } => ContentPart::Text { text },
                        Helper::Reasoning { text } => ContentPart::Reasoning { text },
                        Helper::FileData {
                            file_uri,
                            mime_type,
                        } => ContentPart::FileData {
                            file_uri,
                            mime_type,
                        },
                        Helper::InlineData { mime_type, data } => {
                            ContentPart::InlineData { mime_type, data }
                        }
                        Helper::ToolCall {
                            name,
                            args,
                            call_id,
                        } => ContentPart::ToolCall {
                            name,
                            args,
                            call_id,
                        },
                        Helper::ToolOutput {
                            name,
                            output,
                            is_error,
                            call_id,
                            remote_id,
                        } => ContentPart::ToolOutput {
                            name,
                            output,
                            is_error,
                            call_id,
                            remote_id,
                        },
                        Helper::Action {
                            name,
                            payload,
                            recipients,
                            signature,
                        } => ContentPart::Action {
                            name,
                            payload,
                            recipients,
                            signature,
                        },
                    }),
                    Err(err) => Err(serde::de::Error::custom(format!(
                        "invalid ContentPart: {err}"
                    ))),
                }
            }
            _ => Ok(ContentPart::Any(value)),
        }
    }
}

impl From<String> for ContentPart {
    fn from(text: String) -> Self {
        Self::Text { text }
    }
}

impl From<Json> for ContentPart {
    fn from(val: Json) -> Self {
        if let Json::Object(map) = &val
            && let Some(t) = map.get("type").and_then(|x| x.as_str())
        {
            match t {
                "Text" | "Reasoning" | "FileData" | "InlineData" | "ToolCall" | "ToolOutput"
                | "Action" | "Any" => {
                    if let Ok(part) = serde_json::from_value::<ContentPart>(val.clone()) {
                        return part;
                    }
                }
                _ => {}
            }
        }

        ContentPart::Any(val)
    }
}

impl TryFrom<Resource> for ContentPart {
    type Error = Resource;
    fn try_from(res: Resource) -> Result<Self, Self::Error> {
        if res.blob.as_ref().map(|v| !v.0.is_empty()).unwrap_or(false)
            && let Some(data) = res.blob
        {
            match resource_text_from_bytes(&data.0, res.mime_type.as_deref()) {
                Some(text) => Ok(ContentPart::Text {
                    text: text.into_owned(),
                }),
                None => {
                    let data: ByteBufB64 = data.0.into();
                    let mime_type = res.mime_type.unwrap_or_else(|| {
                        infer2::get(&data)
                            .map(|t| t.mime_type())
                            .unwrap_or("application/octet-stream")
                            .to_string()
                    });
                    Ok(ContentPart::InlineData { mime_type, data })
                }
            }
        } else if res
            .uri
            .as_ref()
            .map(|v| !v.trim().is_empty())
            .unwrap_or(false)
            && let Some(file_uri) = res.uri
        {
            Ok(ContentPart::FileData {
                file_uri,
                mime_type: res.mime_type,
            })
        } else {
            Err(res)
        }
    }
}

/// Request sent to a tool for processing.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolInput<T> {
    /// Tool name.
    pub name: String,

    /// Tool arguments.
    pub args: T,

    /// The resources to process by the tool.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub resources: Vec<Resource>,

    /// The metadata for the tool request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<RequestMeta>,
}

impl<T> ToolInput<T> {
    /// Creates a new tool input with the given name and arguments.
    pub fn new(name: String, args: T) -> Self {
        Self {
            name,
            args,
            resources: Vec::new(),
            meta: None,
        }
    }
}

/// Output produced by a tool execution.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolOutput<T> {
    /// The output from the tool.
    pub output: T,

    /// Indicates if the tool execution resulted in an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,

    /// A collection of artifacts generated by the tool execution.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub artifacts: Vec<Resource>,

    /// The usage statistics for the tool execution.
    pub usage: Usage,

    /// The usage statistics for each tool called by the agent.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub tools_usage: HashMap<String, Usage>,
}

impl<T> ToolOutput<T> {
    /// Creates a new tool output with the given output value.
    pub fn new(output: T) -> Self {
        Self {
            output,
            is_error: None,
            artifacts: Vec::new(),
            usage: Usage::default(),
            tools_usage: HashMap::new(),
        }
    }
}

/// Metadata attached to an agent or tool request.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct RequestMeta {
    /// The target engine principal for the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub engine: Option<Principal>,

    /// User identifier supplied by the request context.
    /// Note: This is not verified and should not be used as a trusted identifier.
    /// For example, if triggered by a bot of X platform, this might be the username
    /// of the user interacting with the bot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// Extra metadata key-value pairs.
    #[serde(flatten)]
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub extra: Map<String, Json>,
}

impl RequestMeta {
    /// Gets an extra metadata value by key and deserializes it to the specified type.
    pub fn get_extra_as<T>(&self, key: &str) -> Option<T>
    where
        T: DeserializeOwned,
    {
        self.extra
            .get(key)
            .and_then(|value| serde_json::from_value(value.clone()).ok())
    }
}

/// Usage statistics for an agent, model, or tool execution.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Usage {
    /// Input tokens sent to the LLM.
    pub input_tokens: u64,

    /// Output tokens received from the LLM.
    pub output_tokens: u64,

    /// cached tokens used in the execution.
    #[serde(default)]
    pub cached_tokens: u64,

    /// Number of requests made to models, agents, or tools.
    pub requests: u64,
}

impl Usage {
    /// Accumulates the usage statistics from another usage object.
    pub fn accumulate(&mut self, other: &Usage) {
        self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
        self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
        self.cached_tokens = self.cached_tokens.saturating_add(other.cached_tokens);
        self.requests = self.requests.saturating_add(other.requests);
    }
}

/// Tool call requested by an LLM or returned by a tool execution pipeline.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolCall {
    /// Tool function name.
    pub name: String,

    /// Tool function arguments.
    pub args: Json,

    /// Tool result populated by the agent runtime when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<ToolOutput<Json>>,

    /// Provider-specific tool call ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_id: Option<String>,

    /// Remote engine principal that executed the tool, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_id: Option<Principal>,
}

/// Represents a function definition with its metadata.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Function {
    /// Definition of the function.
    pub definition: FunctionDefinition,

    /// Resource tags supported by this function.
    pub supported_resource_tags: Vec<String>,
}

/// Defines a callable function with its metadata and schema.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct FunctionDefinition {
    /// Name of the function.
    pub name: String,

    /// Description of what the function does.
    pub description: String,

    /// JSON schema defining the function's parameters.
    pub parameters: Json,

    /// Whether the model should strictly follow the parameter schema when calling the function.
    ///
    /// Provider support and the accepted JSON Schema subset vary by model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strict: Option<bool>,
}

impl FunctionDefinition {
    /// Modifies the function name with a prefix.
    pub fn name_with_prefix(mut self, prefix: &str) -> Self {
        self.name = format!("{}{}", prefix, self.name);
        self
    }

    /// Normalizes strict parameter schemas before sending them to providers.
    pub fn normalize_strict_parameters(mut self) -> Self {
        if self.strict.unwrap_or_default() {
            self.parameters = normalize_strict_schema(self.parameters);
        }
        self
    }
}

/// Estimates token count using a small, provider-independent heuristic.
pub fn estimate_tokens(content: &str) -> usize {
    content.len() / 3
}

/// A document with metadata and content.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Document {
    /// The metadata of the document.
    pub metadata: BTreeMap<String, Json>,

    /// The content of the document.
    pub content: Json,
}

impl Document {
    /// Creates a new text document with the given ID and text content.
    pub fn from_text(id: &str, text: &str) -> Self {
        Self {
            metadata: BTreeMap::from([
                ("id".to_string(), id.into()),
                ("type".to_string(), "Text".into()),
            ]),
            content: text.into(),
        }
    }
}

impl From<&Resource> for Document {
    fn from(res: &Resource) -> Self {
        let mut metadata = BTreeMap::from([
            ("id".to_string(), res._id.into()),
            ("type".to_string(), "Resource".into()),
        ]);

        let mut rr = ResourceRef::from(res);
        rr.blob = None; // blob content is not included in metadata
        if let Json::Object(val) = json!(rr) {
            metadata.extend(val);
        };

        let content = match res
            .blob
            .as_ref()
            .and_then(|b| resource_text_from_bytes(&b.0, res.mime_type.as_deref()))
        {
            Some(text) => text.into_owned().into(),
            None => Json::Null,
        };

        Self { metadata, content }
    }
}

/// Collection of documents that can be injected into a completion prompt.
#[derive(Clone, Debug)]
pub struct Documents {
    /// The tag of the document collection. Defaults to "documents".
    tag: String,
    /// The documents in the collection.
    docs: Vec<Document>,
}

impl Default for Documents {
    fn default() -> Self {
        Self {
            tag: "documents".to_string(),
            docs: Vec::new(),
        }
    }
}

impl Documents {
    /// Creates a new document collection.
    pub fn new(tag: String, docs: Vec<Document>) -> Self {
        Self { tag, docs }
    }

    /// Sets the tag of the document collection.
    pub fn with_tag(self, tag: String) -> Self {
        Self { tag, ..self }
    }

    /// Returns the tag of the document collection.
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Converts the document collection into a system-style user message.
    pub fn to_message(&self, rfc3339_datetime: &str) -> Option<Message> {
        if self.docs.is_empty() {
            return None;
        }

        Some(Message {
            role: "user".into(),
            content: vec![
                format!("Current Datetime: {}\n\n---\n\n{}", rfc3339_datetime, self).into(),
            ],
            name: Some("$system".into()),
            ..Default::default()
        })
    }

    /// Appends a document to the collection.
    pub fn append(&mut self, doc: Document) {
        self.docs.push(doc);
    }
}

impl From<Vec<String>> for Documents {
    fn from(texts: Vec<String>) -> Self {
        let mut docs = Vec::new();
        for (i, text) in texts.into_iter().enumerate() {
            docs.push(Document {
                content: text.into(),
                metadata: BTreeMap::from([
                    ("_id".to_string(), i.into()),
                    ("type".to_string(), "Text".into()),
                ]),
            });
        }
        Self {
            docs,
            ..Default::default()
        }
    }
}

impl From<Vec<Document>> for Documents {
    fn from(docs: Vec<Document>) -> Self {
        Self {
            docs,
            ..Default::default()
        }
    }
}

impl std::ops::Deref for Documents {
    type Target = Vec<Document>;

    fn deref(&self) -> &Self::Target {
        &self.docs
    }
}

impl std::ops::DerefMut for Documents {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.docs
    }
}

impl AsRef<Vec<Document>> for Documents {
    fn as_ref(&self) -> &Vec<Document> {
        &self.docs
    }
}

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

impl std::fmt::Display for Documents {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.docs.is_empty() {
            return Ok(());
        }
        writeln!(f, "<{}>", self.tag)?;
        for doc in &self.docs {
            writeln!(f, "{}", doc)?;
        }
        write!(f, "</{}>", self.tag)
    }
}

/// Appends text resources to the prompt as an `<attachments>` document block.
///
/// Resources tagged `text` or `md` are removed from `resources` (see
/// [`text_resource_documents`]); other resources are left untouched.
pub fn prompt_with_resources(prompt: String, resources: &mut Vec<Resource>) -> String {
    let user_resources = text_resource_documents(resources);
    if user_resources.is_empty() {
        prompt
    } else {
        format!(
            "{prompt}\n\n{}",
            Documents::new("attachments".to_string(), user_resources)
        )
    }
}

/// Removes resources tagged `text` or `md` and converts them into documents.
///
/// Removed resources whose blob cannot be decoded as text are discarded
/// without producing a document.
pub fn text_resource_documents(resources: &mut Vec<Resource>) -> Vec<Document> {
    let res = select_resources(resources, &["text".to_string(), "md".to_string()]);
    let mut user_resources: Vec<Document> = Vec::with_capacity(res.len());
    for resource in &res {
        let doc = Document::from(resource);
        if doc.content != Json::Null {
            user_resources.push(doc);
        }
    }

    user_resources
}

fn decode_percent_encoded_bytes(input: &str) -> Option<ByteBufB64> {
    fn decode_hex(byte: u8) -> Option<u8> {
        match byte {
            b'0'..=b'9' => Some(byte - b'0'),
            b'a'..=b'f' => Some(byte - b'a' + 10),
            b'A'..=b'F' => Some(byte - b'A' + 10),
            _ => None,
        }
    }

    let bytes = input.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'%' => {
                let hi = *bytes.get(index + 1)?;
                let lo = *bytes.get(index + 2)?;
                decoded.push((decode_hex(hi)? << 4) | decode_hex(lo)?);
                index += 3;
            }
            byte => {
                decoded.push(byte);
                index += 1;
            }
        }
    }

    Some(decoded.into())
}

/// Attempts to decode the given byte slice as UTF-8 text and checks if it looks like text content.
pub fn utf8_text_from_bytes(data: &[u8]) -> Option<&str> {
    let text = std::str::from_utf8(data).ok()?;
    looks_like_text(text).then_some(text)
}

/// Attempts to decode the given byte vector as UTF-8 text and checks if it looks like text content.
pub fn utf8_text_from(data: Vec<u8>) -> Option<String> {
    let text = String::from_utf8(data).ok()?;
    looks_like_text(&text).then_some(text)
}

/// Attempts to decode bytes as text and checks if it looks like text content.
///
/// UTF-8 is always preferred. On Windows, non-UTF-8 bytes fall back to the
/// system ANSI code page used by many legacy text files.
pub fn text_from_bytes(data: &[u8]) -> Option<Cow<'_, str>> {
    text_from_bytes_with_encoding(data, platform_text_encoding())
}

/// Attempts to decode the given byte vector as text and checks if it looks like text content.
pub fn text_from(data: Vec<u8>) -> Option<String> {
    text_from_bytes(&data).map(Cow::into_owned)
}

/// Attempts to decode bytes as text using UTF-8 first and an explicit fallback encoding second.
pub fn text_from_bytes_with_encoding<'a>(
    data: &'a [u8],
    fallback_encoding: Option<&'static Encoding>,
) -> Option<Cow<'a, str>> {
    if let Some(text) = utf8_text_from_bytes(data) {
        return Some(Cow::Borrowed(text));
    }

    let encoding = fallback_encoding?;
    if encoding.name() == UTF_8.name() {
        return None;
    }

    let (text, _, had_errors) = encoding.decode(data);
    // `Encoding::decode` sniffs UTF-16 BOMs even when the requested fallback is
    // a legacy code page. A BOM-only non-empty byte slice decodes to an empty
    // string and should not become an empty prompt document.
    if had_errors || (!data.is_empty() && text.is_empty()) || !looks_like_text(&text) {
        return None;
    }

    Some(Cow::Owned(text.into_owned()))
}

/// Resolves a text encoding label, accepting both `utf8` and standard Encoding Standard labels.
pub fn text_encoding_for_label(label: &str) -> Option<&'static Encoding> {
    let label = label.trim();
    if label.eq_ignore_ascii_case("utf8") {
        return Some(UTF_8);
    }
    Encoding::for_label(label.as_bytes())
}

/// Returns the normalized label used by Anda for a decoded text encoding.
pub fn text_encoding_label(encoding: &'static Encoding) -> String {
    if encoding.name() == UTF_8.name() {
        "utf8".to_string()
    } else {
        encoding.name().to_ascii_lowercase()
    }
}

/// Returns the platform-local text encoding used for legacy text files.
///
/// On Windows this is the ANSI code page returned by `GetACP`; on other
/// platforms there is no legacy fallback and UTF-8 remains the only implicit
/// text encoding.
pub fn platform_text_encoding() -> Option<&'static Encoding> {
    #[cfg(target_os = "windows")]
    {
        windows_code_page_encoding(windows_file_code_page())
    }
    #[cfg(not(target_os = "windows"))]
    {
        None
    }
}

/// Maps a Windows code page number to an Encoding Standard decoder when supported.
pub fn windows_code_page_encoding(code_page: u32) -> Option<&'static Encoding> {
    match code_page {
        65001 => Some(UTF_8),
        936 => Some(encoding_rs::GBK),
        950 => Some(encoding_rs::BIG5),
        932 => Some(encoding_rs::SHIFT_JIS),
        949 => Some(encoding_rs::EUC_KR),
        1250 => Some(encoding_rs::WINDOWS_1250),
        1251 => Some(encoding_rs::WINDOWS_1251),
        1252 => Some(encoding_rs::WINDOWS_1252),
        1253 => Some(encoding_rs::WINDOWS_1253),
        1254 => Some(encoding_rs::WINDOWS_1254),
        1255 => Some(encoding_rs::WINDOWS_1255),
        1256 => Some(encoding_rs::WINDOWS_1256),
        1257 => Some(encoding_rs::WINDOWS_1257),
        1258 => Some(encoding_rs::WINDOWS_1258),
        _ => {
            let windows_label = format!("windows-{code_page}");
            Encoding::for_label(windows_label.as_bytes()).or_else(|| {
                let cp_label = format!("cp{code_page}");
                Encoding::for_label(cp_label.as_bytes())
            })
        }
    }
}

fn resource_text_from_bytes<'a>(data: &'a [u8], mime_type: Option<&str>) -> Option<Cow<'a, str>> {
    resource_text_from_bytes_with_encoding(data, mime_type, platform_text_encoding())
}

fn resource_text_from_bytes_with_encoding<'a>(
    data: &'a [u8],
    mime_type: Option<&str>,
    fallback_encoding: Option<&'static Encoding>,
) -> Option<Cow<'a, str>> {
    if let Some(text) = utf8_text_from_bytes(data) {
        return Some(Cow::Borrowed(text));
    }

    if let Some(mime_type) = mime_type
        && !mime_type_allows_text_fallback(mime_type)
    {
        return None;
    }

    text_from_bytes_with_encoding(data, fallback_encoding)
}

fn mime_type_allows_text_fallback(mime_type: &str) -> bool {
    let essence = mime_type
        .split(';')
        .next()
        .unwrap_or(mime_type)
        .trim()
        .to_ascii_lowercase();

    essence.is_empty()
        || essence.starts_with("text/")
        || essence.ends_with("+json")
        || essence.ends_with("+xml")
        || matches!(
            essence.as_str(),
            "application/json"
                | "application/xml"
                | "application/javascript"
                | "application/x-javascript"
                | "application/x-ndjson"
                | "application/yaml"
                | "application/x-yaml"
                | "application/toml"
                | "application/x-www-form-urlencoded"
        )
}

#[cfg(target_os = "windows")]
fn windows_file_code_page() -> u32 {
    // Legacy Windows text files commonly use the ANSI code page rather than the
    // OEM console code page used by `cmd.exe` output.
    unsafe { windows_sys::Win32::Globalization::GetACP() }
}

fn looks_like_text(text: &str) -> bool {
    let mut sampled = 0usize;
    let mut suspicious = 0usize;
    for ch in text.chars().take(4096) {
        sampled += 1;
        if ch.is_control() && !matches!(ch, '\n' | '\r' | '\t') {
            suspicious += 1;
        }
    }

    sampled == 0 || suspicious * 100 / sampled <= 5
}

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

    fn resource(id: u64, tags: &[&str]) -> Resource {
        Resource {
            _id: id,
            name: format!("resource-{id}"),
            tags: tags.iter().map(|tag| tag.to_string()).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn test_agent_and_tool_constructors_default_optional_fields() {
        let agent = AgentInput::new("planner".into(), "summarize this".into());
        assert_eq!(agent.name, "planner");
        assert_eq!(agent.prompt, "summarize this");
        assert!(agent.resources.is_empty());
        assert!(agent.topics.is_none());
        assert!(agent.meta.is_none());

        let tool = ToolInput::new("sum".into(), json!({"x": 1, "y": 2}));
        assert_eq!(tool.name, "sum");
        assert_eq!(tool.args, json!({"x": 1, "y": 2}));
        assert!(tool.resources.is_empty());
        assert!(tool.meta.is_none());

        let output = ToolOutput::new(json!("ok"));
        assert_eq!(output.output, json!("ok"));
        assert!(output.artifacts.is_empty());
        assert_eq!(output.usage.requests, 0);
        assert!(output.tools_usage.is_empty());
    }

    #[test]
    fn test_prompt_command_from_string_variants() {
        assert_eq!(PromptCommand::from("".to_string()), PromptCommand::Ping);
        assert_eq!(
            PromptCommand::from("  /PING  ".to_string()),
            PromptCommand::Ping
        );
        assert_eq!(
            PromptCommand::from("hello".to_string()),
            PromptCommand::Plain {
                prompt: "hello".into(),
            }
        );
        assert_eq!(
            PromptCommand::from("/Status  show details".to_string()),
            PromptCommand::Command {
                command: "status".into(),
                prompt: "/Status  show details".into(),
            }
        );
        assert_eq!(
            PromptCommand::from("/help".to_string()),
            PromptCommand::Command {
                command: "help".into(),
                prompt: "/help".into(),
            }
        );

        let stop = PromptCommand::from("/stop  停止当前任务,保留会话".to_string());
        assert_eq!(stop.command_argument(), Some("停止当前任务,保留会话"));

        let manual = PromptCommand::Command {
            command: "cancel".into(),
            prompt: "取消当前任务".into(),
        };
        assert_eq!(manual.command_argument(), Some("取消当前任务"));

        assert_eq!(PromptCommand::Ping.command_argument(), None);
    }

    #[test]
    fn test_agent_output_into_tool_output_handles_json_plain_text_and_metadata() {
        let mut tools_usage = HashMap::new();
        tools_usage.insert(
            "sum".into(),
            Usage {
                requests: 1,
                ..Default::default()
            },
        );

        let output = AgentOutput {
            content: r#"{"ok":true}"#.into(),
            usage: Usage {
                input_tokens: 2,
                output_tokens: 1,
                requests: 1,
                ..Default::default()
            },
            tools_usage: tools_usage.clone(),
            artifacts: vec![resource(7, &["text"])],
            ..Default::default()
        }
        .into_tool_output();
        assert_eq!(output.output, json!({"ok": true}));
        assert_eq!(output.artifacts.len(), 1);
        assert_eq!(output.artifacts[0]._id, 7);
        assert_eq!(output.usage.input_tokens, 2);
        assert_eq!(output.tools_usage.get("sum").unwrap().requests, 1);

        let output = AgentOutput {
            content: "not-json".into(),
            thoughts: Some("thinking".into()),
            session: Some("session-1".into()),
            model: Some("test-model".into()),
            ..Default::default()
        }
        .into_tool_output();
        assert_eq!(
            output.output,
            json!({
                "content": "not-json",
                "thoughts": "thinking",
                "session": "session-1",
                "model": "test-model"
            })
        );

        let output = AgentOutput {
            content: "still-not-json".into(),
            ..Default::default()
        }
        .into_tool_output();
        assert_eq!(output.output, json!("still-not-json"));
    }

    #[test]
    fn test_data_url_helpers_round_trip_and_invalid_inputs() {
        let data: ByteBufB64 = b"hello".to_vec().into();
        let mime_type = "text/plain".to_string();

        let data_url = part_to_data_url(&data, Some(&mime_type));
        assert_eq!(data_url, "data:text/plain;base64,aGVsbG8=");

        let (decoded, decoded_mime_type) = inline_data_from_data_url(&data_url).unwrap();
        assert_eq!(decoded, data);
        assert_eq!(decoded_mime_type, "text/plain");

        let (decoded, _) = inline_data_from_data_url("aGVsbG8=").unwrap();
        assert_eq!(decoded, data);

        let html_url = "data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E";
        let (decoded, decoded_mime_type) = inline_data_from_data_url(html_url).unwrap();
        let expected_html: ByteBufB64 = b"<h1>Hello, World!</h1>".to_vec().into();
        assert_eq!(decoded, expected_html);
        assert_eq!(decoded_mime_type, "text/html");

        let (decoded, decoded_mime_type) =
            inline_data_from_data_url("data:text/plain,hello").unwrap();
        let expected_text: ByteBufB64 = b"hello".to_vec().into();
        assert_eq!(decoded, expected_text);
        assert_eq!(decoded_mime_type, "text/plain");

        assert!(inline_data_from_data_url("data:text/plain,%GG").is_none());
        assert!(inline_data_from_data_url("not-base64%%%").is_none());
    }

    #[test]
    fn test_inline_data_from_data_url_infers_missing_mime_type() {
        // base64 data URL without media type: infer from magic bytes
        let jpeg_header: ByteBufB64 = vec![0xff, 0xd8, 0xff, 0xe0].into();
        let data_url = format!("data:;base64,{}", jpeg_header.to_base64());
        let (decoded, mime_type) = inline_data_from_data_url(&data_url).unwrap();
        assert_eq!(decoded, jpeg_header);
        assert_eq!(mime_type, "image/jpeg");

        // base64 data URL without media type and no recognizable magic bytes
        let (decoded, mime_type) = inline_data_from_data_url("data:;base64,aGVsbG8=").unwrap();
        assert_eq!(decoded, ByteBufB64::from(b"hello".to_vec()));
        assert_eq!(mime_type, "application/octet-stream");

        // percent-encoded data URL without media type defaults to text/plain
        let (decoded, mime_type) = inline_data_from_data_url("data:,Hello%20World").unwrap();
        assert_eq!(decoded, ByteBufB64::from(b"Hello World".to_vec()));
        assert_eq!(mime_type, "text/plain");
    }

    #[test]
    fn test_content_part_try_from_resource_variants() {
        let text = Resource {
            blob: Some(b"hello".to_vec().into()),
            ..resource(1, &["text"])
        };
        assert_eq!(
            ContentPart::try_from(text).unwrap(),
            ContentPart::Text {
                text: "hello".into(),
            }
        );

        let binary = Resource {
            blob: Some(vec![0xff, 0xd8, 0xff].into()),
            mime_type: Some("image/jpeg".into()),
            ..resource(2, &["image"])
        };
        assert_eq!(
            ContentPart::try_from(binary).unwrap(),
            ContentPart::InlineData {
                mime_type: "image/jpeg".into(),
                data: vec![0xff, 0xd8, 0xff].into(),
            }
        );

        let file = Resource {
            uri: Some("file:///tmp/a.txt".into()),
            mime_type: Some("text/plain".into()),
            ..resource(3, &["text"])
        };
        assert_eq!(
            ContentPart::try_from(file).unwrap(),
            ContentPart::FileData {
                file_uri: "file:///tmp/a.txt".into(),
                mime_type: Some("text/plain".into()),
            }
        );

        let empty_blob = Resource {
            blob: Some(Vec::<u8>::new().into()),
            ..resource(4, &["text"])
        };
        assert!(ContentPart::try_from(empty_blob).is_err());

        let empty_uri = Resource {
            uri: Some("   ".into()),
            ..resource(5, &["text"])
        };
        assert!(ContentPart::try_from(empty_uri).is_err());
    }

    #[test]
    fn test_text_from_bytes_decodes_utf8_and_legacy_fallback() {
        let decoded =
            text_from_bytes_with_encoding("中文.txt".as_bytes(), Some(encoding_rs::GBK)).unwrap();
        assert!(matches!(&decoded, Cow::Borrowed(_)));
        assert_eq!(decoded.as_ref(), "中文.txt");

        let (gbk, _, had_errors) = encoding_rs::GBK.encode("中文.txt");
        assert!(!had_errors);
        let decoded = text_from_bytes_with_encoding(&gbk, Some(encoding_rs::GBK)).unwrap();
        assert!(matches!(&decoded, Cow::Owned(_)));
        assert_eq!(decoded.as_ref(), "中文.txt");

        assert!(text_from_bytes_with_encoding(&gbk, Some(UTF_8)).is_none());
        assert!(text_from_bytes_with_encoding(&[0x81, 0x30], Some(encoding_rs::GBK)).is_none());
        assert!(
            resource_text_from_bytes_with_encoding(
                &[0xff, 0xfe],
                None,
                Some(encoding_rs::WINDOWS_1252),
            )
            .is_none()
        );
    }

    #[test]
    fn test_resource_text_fallback_respects_binary_mime_type() {
        let binary_header = [0xff, 0xd8, 0xff];
        assert!(
            resource_text_from_bytes_with_encoding(
                &binary_header,
                Some("image/jpeg"),
                Some(encoding_rs::WINDOWS_1252),
            )
            .is_none()
        );

        let (legacy_text, _, had_errors) = encoding_rs::WINDOWS_1252.encode("café");
        assert!(!had_errors);
        let decoded = resource_text_from_bytes_with_encoding(
            &legacy_text,
            Some("text/plain; charset=windows-1252"),
            Some(encoding_rs::WINDOWS_1252),
        )
        .unwrap();
        assert_eq!(decoded.as_ref(), "café");
    }

    #[test]
    fn test_request_meta_get_extra_as_and_usage_accumulate() {
        let mut extra = Map::new();
        extra.insert("numbers".into(), json!([1, 2, 3]));
        extra.insert("flag".into(), json!(true));
        let meta = RequestMeta {
            extra,
            ..Default::default()
        };

        assert_eq!(
            meta.get_extra_as::<Vec<u64>>("numbers"),
            Some(vec![1, 2, 3])
        );
        assert_eq!(meta.get_extra_as::<bool>("flag"), Some(true));
        assert_eq!(meta.get_extra_as::<String>("missing"), None);

        let mut usage = Usage {
            input_tokens: u64::MAX - 1,
            output_tokens: 2,
            cached_tokens: 3,
            requests: u64::MAX,
        };
        let other = Usage {
            input_tokens: 10,
            output_tokens: 5,
            cached_tokens: u64::MAX,
            requests: 1,
        };
        usage.accumulate(&other);

        assert_eq!(usage.input_tokens, u64::MAX);
        assert_eq!(usage.output_tokens, 7);
        assert_eq!(usage.cached_tokens, u64::MAX);
        assert_eq!(usage.requests, u64::MAX);
    }

    #[test]
    fn test_function_definition_and_document_helpers() {
        let definition = FunctionDefinition {
            name: "search".into(),
            description: "Find documents".into(),
            parameters: json!({
                "type": "object",
                "properties": {},
                "required": [],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
        .name_with_prefix("tool_");
        assert_eq!(definition.name, "tool_search");
        assert_eq!(definition.description, "Find documents");
        assert_eq!(estimate_tokens("abcdef"), 2);
        assert_eq!(estimate_tokens(""), 0);

        let text_doc = Document::from_text("doc-1", "hello");
        assert_eq!(text_doc.metadata.get("id"), Some(&json!("doc-1")));
        assert_eq!(text_doc.metadata.get("type"), Some(&json!("Text")));
        assert_eq!(text_doc.content, json!("hello"));

        let resource = Resource {
            _id: 9,
            name: "note".into(),
            tags: vec!["text".into()],
            uri: Some("file:///tmp/note.txt".into()),
            blob: Some(b"hello".to_vec().into()),
            mime_type: Some("text/plain".into()),
            ..Default::default()
        };
        let doc = Document::from(&resource);
        assert_eq!(doc.metadata.get("id"), Some(&json!(9)));
        assert_eq!(doc.metadata.get("type"), Some(&json!("Resource")));
        assert_eq!(doc.metadata.get("_id"), Some(&json!(9)));
        assert_eq!(doc.metadata.get("name"), Some(&json!("note")));
        assert_eq!(doc.metadata.get("tags"), Some(&json!(["text"])));
        assert_eq!(
            doc.metadata.get("uri"),
            Some(&json!("file:///tmp/note.txt"))
        );
        assert!(!doc.metadata.contains_key("blob"));
        assert_eq!(doc.content, json!("hello"));
    }

    #[test]
    fn test_documents_and_resource_prompt_helpers() {
        let mut docs = Documents::new(
            "attachments".into(),
            vec![Document::from_text("1", "alpha")],
        );
        assert_eq!(docs.tag(), "attachments");
        docs.append(Document::from_text("2", "beta"));
        assert_eq!(docs.len(), 2);

        let message = docs.to_message("2026-05-16T00:00:00Z").unwrap();
        assert_eq!(message.role, "user");
        assert_eq!(message.name.as_deref(), Some("$system"));
        let text = message.text().unwrap();
        assert!(text.contains("Current Datetime: 2026-05-16T00:00:00Z"));
        assert!(text.contains("<attachments>"));
        assert!(text.contains("alpha"));
        assert!(text.contains("beta"));

        assert!(
            Documents::default()
                .to_message("2026-05-16T00:00:00Z")
                .is_none()
        );

        let from_strings: Documents = vec!["alpha".to_string(), "beta".to_string()].into();
        assert_eq!(
            from_strings[0],
            Document {
                metadata: BTreeMap::from([
                    ("_id".to_string(), json!(0)),
                    ("type".to_string(), json!("Text")),
                ]),
                content: json!("alpha"),
            }
        );
        assert_eq!(
            from_strings[1],
            Document {
                metadata: BTreeMap::from([
                    ("_id".to_string(), json!(1)),
                    ("type".to_string(), json!("Text")),
                ]),
                content: json!("beta"),
            }
        );

        let mut resources = vec![
            Resource {
                blob: Some(b"alpha".to_vec().into()),
                ..resource(1, &["text"])
            },
            Resource {
                blob: Some(vec![0xff, 0xfe].into()),
                ..resource(2, &["md"])
            },
            Resource {
                uri: Some("file:///tmp/image.png".into()),
                ..resource(3, &["image"])
            },
        ];

        let docs = text_resource_documents(&mut resources);
        assert_eq!(
            docs,
            vec![Document {
                metadata: BTreeMap::from([
                    ("_id".to_string(), json!(1)),
                    ("id".to_string(), json!(1)),
                    ("name".to_string(), json!("resource-1")),
                    ("tags".to_string(), json!(["text"])),
                    ("type".to_string(), json!("Resource")),
                ]),
                content: json!("alpha"),
            }]
        );
        assert_eq!(resources.len(), 1);
        assert_eq!(resources[0]._id, 3);

        let mut prompt_resources = vec![Resource {
            blob: Some(b"beta".to_vec().into()),
            ..resource(4, &["text"])
        }];
        let prompt = prompt_with_resources("Base prompt".into(), &mut prompt_resources);
        assert!(prompt.starts_with("Base prompt\n\n<attachments>"));
        assert!(prompt.contains("beta"));
        assert!(prompt_resources.is_empty());

        let mut untouched_resources = vec![Resource {
            uri: Some("file:///tmp/only-image.png".into()),
            ..resource(5, &["image"])
        }];
        let prompt = prompt_with_resources("Base prompt".into(), &mut untouched_resources);
        assert_eq!(prompt, "Base prompt");
        assert_eq!(untouched_resources.len(), 1);
        assert_eq!(untouched_resources[0]._id, 5);
    }

    #[test]
    fn test_message_content_deserialize_rejects_non_string_non_array() {
        assert!(
            serde_json::from_value::<Message>(json!({
                "role": "user",
                "content": 123,
            }))
            .is_err()
        );
    }

    #[test]
    fn test_prompt() {
        let documents: Documents = vec![
            Document {
                metadata: BTreeMap::from([("_id".to_string(), 1.into())]),
                content: "Test document 1.".into(),
            },
            Document {
                metadata: BTreeMap::from([
                    ("_id".to_string(), 2.into()),
                    ("key".to_string(), "value".into()),
                    ("a".to_string(), "b".into()),
                ]),
                content: "Test document 2.".into(),
            },
        ]
        .into();
        // println!("{}", documents);

        let s = documents.to_string();
        let lines: Vec<&str> = s.lines().collect();
        assert_eq!(lines[0], "<documents>");
        assert_eq!(lines[3], "</documents>");

        let doc1: Json = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(doc1.get("content").unwrap(), "Test document 1.");
        assert_eq!(doc1.get("metadata").unwrap().get("_id").unwrap(), 1);

        let doc2: Json = serde_json::from_str(lines[2]).unwrap();
        assert_eq!(doc2.get("content").unwrap(), "Test document 2.");
        assert_eq!(doc2.get("metadata").unwrap().get("_id").unwrap(), 2);
        assert_eq!(doc2.get("metadata").unwrap().get("key").unwrap(), "value");
        assert_eq!(doc2.get("metadata").unwrap().get("a").unwrap(), "b");

        let documents = documents.with_tag("my_docs".to_string());
        let s = documents.to_string();
        let lines: Vec<&str> = s.lines().collect();
        assert_eq!(lines[0], "<my_docs>");
        assert_eq!(lines[3], "</my_docs>");

        let doc1: Json = serde_json::from_str(lines[1]).unwrap();
        assert_eq!(doc1.get("content").unwrap(), "Test document 1.");
        assert_eq!(doc1.get("metadata").unwrap().get("_id").unwrap(), 1);

        let doc2: Json = serde_json::from_str(lines[2]).unwrap();
        assert_eq!(doc2.get("content").unwrap(), "Test document 2.");
        assert_eq!(doc2.get("metadata").unwrap().get("_id").unwrap(), 2);
        assert_eq!(doc2.get("metadata").unwrap().get("key").unwrap(), "value");
        assert_eq!(doc2.get("metadata").unwrap().get("a").unwrap(), "b");
    }

    #[test]
    fn test_content_part_text_serde_and_from() {
        let part: ContentPart = "hello".to_string().into();
        assert_eq!(
            part,
            ContentPart::Text {
                text: "hello".into()
            }
        );

        // serde round-trip
        let v = serde_json::to_value(&part).unwrap();
        assert_eq!(v.get("type").unwrap(), "Text");
        assert_eq!(v.get("text").unwrap(), "hello");

        let back: ContentPart = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(back, part);
        let back: ContentPart = v.into();
        assert_eq!(back, part);

        let part: Vec<ContentPart> = serde_json::from_str(
            r#"
            [
                "hello",
                {
                    "type": "Text",
                    "text": "world"
                }
            ]
            "#,
        )
        .unwrap();
        assert_eq!(
            part,
            vec![
                ContentPart::Text {
                    text: "hello".into()
                },
                ContentPart::Text {
                    text: "world".into()
                }
            ]
        );
    }

    #[test]
    fn test_content_part_filedata_serde_optional() {
        // mime_type = None -> 不序列化
        let part = ContentPart::FileData {
            file_uri: "gs://bucket/file".into(),
            mime_type: None,
        };
        let v = serde_json::to_value(&part).unwrap();
        assert_eq!(v.get("type").unwrap(), "FileData");
        // 字段采用 camelCase
        assert_eq!(v.get("fileUri").unwrap(), "gs://bucket/file");
        assert!(v.get("mimeType").is_none());

        // mime_type = Some -> 出现
        let part2 = ContentPart::FileData {
            file_uri: "gs://bucket/file2".into(),
            mime_type: Some("image/png".into()),
        };
        let v2 = serde_json::to_value(&part2).unwrap();
        assert_eq!(v2.get("type").unwrap(), "FileData");
        assert_eq!(v2.get("fileUri").unwrap(), "gs://bucket/file2");
        assert_eq!(v2.get("mimeType").unwrap(), "image/png");

        // 反序列化校验
        let back: ContentPart = serde_json::from_value(v2.clone()).unwrap();
        assert_eq!(back, part2);
        let back: ContentPart = v2.into();
        assert_eq!(back, part2);
    }

    #[test]
    fn test_content_part_inlinedata_serde() {
        let part = ContentPart::InlineData {
            mime_type: "text/plain".into(),
            data: b"hello".to_vec().into(),
        };
        let v = serde_json::to_value(&part).unwrap();
        assert_eq!(v.get("type").unwrap(), "InlineData");
        assert_eq!(v.get("mimeType").unwrap(), "text/plain");
        assert_eq!(v.get("data").unwrap(), "aGVsbG8=");

        let back: ContentPart = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(back, part);
        let back: ContentPart = v.into();
        assert_eq!(back, part);
    }

    #[test]
    fn test_content_part_any_serde() {
        let v = json!({
            "type": "text/plain",
            "data": "aGVsbG8=",
        });
        let part: ContentPart = v.clone().into();
        assert_eq!(part, ContentPart::Any(v));
        let v2 = serde_json::to_value(&part).unwrap();
        assert_eq!(v2.get("type").unwrap(), "text/plain");
        assert_eq!(v2.get("data").unwrap(), "aGVsbG8=");

        let part = ContentPart::Any(json!({
            "data": "aGVsbG8=",
        }));
        let v2 = serde_json::to_value(&part).unwrap();
        assert!(v2.get("type").is_none());
        assert_eq!(v2.get("data").unwrap(), "aGVsbG8=");
    }

    #[test]
    fn test_content_part_any_supports_resource_serde() {
        let mut metadata = Map::new();
        metadata.insert("source".into(), json!("upload"));
        metadata.insert("priority".into(), json!(3));

        let resource = Resource {
            _id: 42,
            name: "note.txt".into(),
            tags: vec!["text".into(), "note".into()],
            description: Some("A note resource".into()),
            uri: Some("file:///tmp/note.txt".into()),
            mime_type: Some("text/plain".into()),
            blob: Some(b"hello world".to_vec().into()),
            size: Some(11),
            metadata: Some(metadata),
            ..Default::default()
        };

        let resource_json = json!(resource);
        let part: ContentPart = resource_json.clone().into();
        assert_eq!(part, ContentPart::Any(resource_json.clone()));

        let serialized = serde_json::to_value(&part).unwrap();
        assert_eq!(serialized, resource_json);

        let back: ContentPart = serde_json::from_value(serialized.clone()).unwrap();
        assert_eq!(back, ContentPart::Any(resource_json));

        let resource_back: Resource = serde_json::from_value(serialized).unwrap();
        assert_eq!(resource_back._id, 42);
        assert_eq!(resource_back.name, "note.txt");
        assert_eq!(resource_back.tags, vec!["text", "note"]);
        assert_eq!(
            resource_back.description.as_deref(),
            Some("A note resource")
        );
        assert_eq!(resource_back.uri.as_deref(), Some("file:///tmp/note.txt"));
        assert_eq!(resource_back.mime_type.as_deref(), Some("text/plain"));
        assert_eq!(resource_back.blob, Some(b"hello world".to_vec().into()));
        assert_eq!(resource_back.size, Some(11));
        assert_eq!(
            resource_back
                .metadata
                .as_ref()
                .and_then(|meta| meta.get("source")),
            Some(&json!("upload"))
        );
        assert_eq!(
            resource_back
                .metadata
                .as_ref()
                .and_then(|meta| meta.get("priority")),
            Some(&json!(3))
        );
    }

    #[test]
    fn test_content_part_any_from_and_any_into_resource() {
        let mut metadata = Map::new();
        metadata.insert("source".into(), json!("upload"));
        metadata.insert("priority".into(), json!(3));

        let resource = Resource {
            _id: 42,
            name: "note.txt".into(),
            tags: vec!["text".into(), "note".into()],
            description: Some("A note resource".into()),
            uri: Some("file:///tmp/note.txt".into()),
            mime_type: Some("text/plain".into()),
            blob: Some(b"hello world".to_vec().into()),
            size: Some(11),
            metadata: Some(metadata),
            ..Default::default()
        };

        let part = ContentPart::any_from("Resource", &resource);
        let expected = json!({
            "type": "Resource",
            "_id": 42,
            "name": "note.txt",
            "tags": ["text", "note"],
            "description": "A note resource",
            "uri": "file:///tmp/note.txt",
            "mime_type": "text/plain",
            "blob": "aGVsbG8gd29ybGQ=",
            "size": 11,
            "metadata": {
                "source": "upload",
                "priority": 3
            }
        });
        assert_eq!(part, ContentPart::Any(expected));

        let resource_back = part.clone().any_into::<Resource>("Resource").unwrap();
        assert_eq!(resource_back._id, resource._id);
        assert_eq!(resource_back.name, resource.name);
        assert_eq!(resource_back.tags, resource.tags);
        assert_eq!(resource_back.description, resource.description);
        assert_eq!(resource_back.uri, resource.uri);
        assert_eq!(resource_back.mime_type, resource.mime_type);
        assert_eq!(resource_back.blob, resource.blob);
        assert_eq!(resource_back.size, resource.size);
        assert_eq!(resource_back.metadata, resource.metadata);

        assert_eq!(
            part.clone().any_into::<Resource>("OtherType"),
            Err(Box::new(part.clone()))
        );

        let invalid = ContentPart::any_from("Resource", "plain-text");
        assert_eq!(
            invalid.clone().any_into::<Resource>("Resource"),
            Err(Box::new(invalid))
        );
    }

    #[test]
    fn test_content_part_toolcall_and_tooloutput_serde() {
        let call = ContentPart::ToolCall {
            name: "sum".into(),
            args: serde_json::json!({"x":1, "y":2}),
            call_id: None,
        };
        let v_call = serde_json::to_value(&call).unwrap();
        assert_eq!(v_call.get("type").unwrap(), "ToolCall");
        assert_eq!(v_call.get("name").unwrap(), "sum");
        assert_eq!(
            v_call.get("args").unwrap(),
            &serde_json::json!({"x":1, "y":2})
        );
        // callId 省略
        assert!(v_call.get("callId").is_none());
        let back_call: ContentPart = serde_json::from_value(v_call.clone()).unwrap();
        assert_eq!(back_call, call);
        let back: ContentPart = v_call.into();
        assert_eq!(back, call);

        let out = ContentPart::ToolOutput {
            name: "sum".into(),
            output: serde_json::json!({"result":3}),
            is_error: None,
            call_id: Some("c1".into()),
            remote_id: None,
        };
        let v_out = serde_json::to_value(&out).unwrap();
        assert_eq!(v_out.get("type").unwrap(), "ToolOutput");
        assert_eq!(v_out.get("name").unwrap(), "sum");
        assert_eq!(
            v_out.get("output").unwrap(),
            &serde_json::json!({"result":3})
        );
        // callId 存在
        assert_eq!(v_out.get("callId").unwrap(), "c1");
        let back_out: ContentPart = serde_json::from_value(v_out.clone()).unwrap();
        assert_eq!(back_out, out);
        let back: ContentPart = v_out.into();
        assert_eq!(back, out);
    }

    #[test]
    fn test_message_text_collects_only_text_parts_in_order() {
        let msg = Message {
            role: "assistant".into(),
            content: vec![
                ContentPart::Reasoning {
                    text: "first thought".into(),
                },
                ContentPart::Text {
                    text: "first text".into(),
                },
                ContentPart::ToolCall {
                    name: "sum".into(),
                    args: serde_json::json!({"x":1, "y":2}),
                    call_id: Some("call_1".into()),
                },
                ContentPart::Text {
                    text: "second text".into(),
                },
                ContentPart::Action {
                    name: "notify".into(),
                    payload: serde_json::json!({"ok": true}),
                    recipients: None,
                    signature: None,
                },
            ],
            ..Default::default()
        };

        assert_eq!(msg.text().as_deref(), Some("first text\n\nsecond text"));

        let no_text = Message {
            role: "assistant".into(),
            content: vec![ContentPart::Reasoning {
                text: "thought only".into(),
            }],
            ..Default::default()
        };
        assert_eq!(no_text.text(), None);
    }

    #[test]
    fn test_message_thoughts_collects_only_reasoning_parts_in_order() {
        let msg = Message {
            role: "assistant".into(),
            content: vec![
                ContentPart::Text {
                    text: "visible text".into(),
                },
                ContentPart::Reasoning {
                    text: "first thought".into(),
                },
                ContentPart::ToolOutput {
                    name: "sum".into(),
                    output: serde_json::json!({"result": 3}),
                    is_error: None,
                    call_id: Some("call_1".into()),
                    remote_id: None,
                },
                ContentPart::Reasoning {
                    text: "second thought".into(),
                },
            ],
            ..Default::default()
        };

        assert_eq!(
            msg.thoughts().as_deref(),
            Some("first thought\n\nsecond thought")
        );

        let no_reasoning = Message {
            role: "assistant".into(),
            content: vec![ContentPart::Text {
                text: "text only".into(),
            }],
            ..Default::default()
        };
        assert_eq!(no_reasoning.thoughts(), None);
    }

    #[test]
    fn test_message_tool_calls_extract_from_content_parts() {
        let parts = vec![
            ContentPart::Text {
                text: "hello".into(),
            },
            ContentPart::ToolCall {
                name: "sum".into(),
                args: serde_json::json!({"x":1, "y": 2}),
                call_id: Some("abc".into()),
            },
            ContentPart::ToolCall {
                name: "echo".into(),
                args: serde_json::json!({"text":"hi"}),
                call_id: None,
            },
            ContentPart::ToolOutput {
                name: "sum".into(),
                output: serde_json::json!({"result": 3}),
                is_error: None,
                call_id: Some("abc".into()),
                remote_id: None,
            },
        ];
        let msg = Message {
            role: "assistant".into(),
            content: parts,
            ..Default::default()
        };

        let calls = msg.tool_calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].name, "sum");
        assert_eq!(calls[0].args, serde_json::json!({"x":1, "y":2}));
        assert_eq!(calls[0].call_id.as_deref(), Some("abc"));
        assert!(calls[0].result.is_none());
        assert!(calls[0].remote_id.is_none());
        assert_eq!(calls[1].name, "echo");
        assert_eq!(calls[1].args, serde_json::json!({"text":"hi"}));
        assert!(calls[1].call_id.is_none());
        assert!(calls[1].result.is_none());
        assert!(calls[1].remote_id.is_none());
    }

    #[test]
    fn test_message_prune_content_keeps_visible_parts_and_is_idempotent() {
        let action = ContentPart::Action {
            name: "delegate".into(),
            payload: serde_json::json!({"agent": "planner"}),
            recipients: None,
            signature: None,
        };
        let mut msg = Message {
            role: "assistant".into(),
            content: vec![
                ContentPart::Text {
                    text: "visible text".into(),
                },
                ContentPart::ToolCall {
                    name: "sum".into(),
                    args: serde_json::json!({"x":1, "y":2}),
                    call_id: Some("call_1".into()),
                },
                ContentPart::Reasoning {
                    text: "visible thought".into(),
                },
                ContentPart::FileData {
                    file_uri: "file:///tmp/a.txt".into(),
                    mime_type: None,
                },
                action.clone(),
                ContentPart::ToolOutput {
                    name: "sum".into(),
                    output: serde_json::json!({"result": 3}),
                    is_error: None,
                    call_id: Some("call_1".into()),
                    remote_id: None,
                },
            ],
            ..Default::default()
        };

        assert_eq!(msg.prune_content(), 3);
        assert_eq!(
            msg.content,
            vec![
                ContentPart::Text {
                    text: "visible text".into(),
                },
                ContentPart::Reasoning {
                    text: "visible thought".into(),
                },
                action,
                ContentPart::Text {
                    text: "[3 items (tool calls or files) pruned due to limits]".into(),
                },
            ]
        );

        let pruned = msg.content.clone();
        assert_eq!(msg.prune_content(), 0);
        assert_eq!(msg.content, pruned);
    }

    #[test]
    fn test_message_content_deserialize_from_string() {
        // content as a plain string
        let msg: Message = serde_json::from_value(serde_json::json!({
            "role": "user",
            "content": "hello world"
        }))
        .unwrap();
        assert_eq!(msg.role, "user");
        assert_eq!(msg.content.len(), 1);
        assert_eq!(
            msg.content[0],
            ContentPart::Text {
                text: "hello world".into()
            }
        );

        // content as an array still works
        let msg2: Message = serde_json::from_value(serde_json::json!({
            "role": "assistant",
            "content": [{"type": "Text", "text": "hi"}]
        }))
        .unwrap();
        assert_eq!(msg2.content.len(), 1);
        assert_eq!(msg2.content[0], ContentPart::Text { text: "hi".into() });

        // missing content defaults to empty vec
        let msg3: Message = serde_json::from_value(serde_json::json!({
            "role": "system"
        }))
        .unwrap();
        assert!(msg3.content.is_empty());

        // null content is treated as empty content for provider compatibility
        let msg4: Message = serde_json::from_value(serde_json::json!({
            "role": "assistant",
            "content": null
        }))
        .unwrap();
        assert!(msg4.content.is_empty());
    }

    #[test]
    fn test_request_meta_extra_flatten_serde() {
        // empty extra should not serialize
        let meta = RequestMeta {
            engine: None,
            user: None,
            extra: Map::new(),
        };
        let v = serde_json::to_value(&meta).unwrap();
        assert_eq!(v, serde_json::json!({}));

        // extra should be flattened into the top-level object
        let mut extra = Map::new();
        extra.insert("foo".into(), serde_json::json!("bar"));
        extra.insert("n".into(), serde_json::json!(1));
        extra.insert("obj".into(), serde_json::json!({"x": true}));

        let meta2 = RequestMeta {
            engine: Some(Principal::from_text("aaaaa-aa").unwrap()),
            user: Some("alice".into()),
            extra,
        };

        let v2 = serde_json::to_value(&meta2).unwrap();
        assert_eq!(v2.get("engine").unwrap(), "aaaaa-aa");
        assert_eq!(v2.get("user").unwrap(), "alice");
        assert_eq!(v2.get("foo").unwrap(), "bar");
        assert_eq!(v2.get("n").unwrap(), 1);
        assert_eq!(v2.get("obj").unwrap(), &serde_json::json!({"x": true}));
        assert!(v2.get("extra").is_none());

        // deserialization: unknown fields go into extra
        let input = serde_json::json!({
            "engine": "aaaaa-aa",
            "user": "bob",
            "k1": "v1",
            "k2": 2,
            "nested": {"a": 1}
        });
        let back: RequestMeta = serde_json::from_value(input).unwrap();
        assert_eq!(back.engine.unwrap().to_text(), "aaaaa-aa");
        assert_eq!(back.user.as_deref(), Some("bob"));
        assert_eq!(back.extra.get("k1").unwrap(), "v1");
        assert_eq!(back.extra.get("k2").unwrap(), 2);
        assert_eq!(
            back.extra.get("nested").unwrap(),
            &serde_json::json!({"a": 1})
        );

        // round-trip (field-by-field)
        let back2: RequestMeta = serde_json::from_value(v2).unwrap();
        assert_eq!(back2.engine.unwrap().to_text(), "aaaaa-aa");
        assert_eq!(back2.user.as_deref(), Some("alice"));
        assert_eq!(back2.extra.get("foo").unwrap(), "bar");
        assert_eq!(back2.extra.get("n").unwrap(), 1);
        assert_eq!(
            back2.extra.get("obj").unwrap(),
            &serde_json::json!({"x": true})
        );
    }
}