beleth 0.2.0-rc.1

Autonomous agent framework - The King commands legions
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
//! Agent implementation with ReAct-style reasoning.

use std::sync::Arc;

use futures::StreamExt;
use infernum_core::{GenerateRequest, Message, ModelId, Result, Role, SamplingParams};

use crate::memory::AgentMemory;
use crate::planner::{Planner, PlanningStrategy};
use crate::tool::{ToolCall, ToolContext, ToolRegistry};

use abaddon::InferenceEngine;

/// Source for agent persona/system prompt.
#[derive(Debug, Clone)]
pub enum PersonaSource {
    /// Inline prompt text.
    Inline(String),
    /// Reference to Grimoire persona.
    Grimoire {
        /// Persona identifier.
        persona_id: String,
        /// Optional variant.
        variant: Option<String>,
    },
}

impl PersonaSource {
    /// Creates a new inline persona source.
    #[must_use]
    pub fn inline(prompt: impl Into<String>) -> Self {
        Self::Inline(prompt.into())
    }

    /// Creates a new Grimoire persona source.
    #[must_use]
    pub fn grimoire(persona_id: impl Into<String>) -> Self {
        Self::Grimoire {
            persona_id: persona_id.into(),
            variant: None,
        }
    }

    /// Creates a new Grimoire persona source with a variant.
    #[must_use]
    pub fn grimoire_with_variant(
        persona_id: impl Into<String>,
        variant: impl Into<String>,
    ) -> Self {
        Self::Grimoire {
            persona_id: persona_id.into(),
            variant: Some(variant.into()),
        }
    }

    /// Resolves the system prompt asynchronously using GrimoireLoader.
    ///
    /// This is the preferred method as it leverages caching and proper async I/O.
    pub async fn resolve(&self) -> String {
        match self {
            Self::Inline(s) => s.clone(),
            Self::Grimoire {
                persona_id,
                variant,
            } => {
                let loader = grimoire_loader::GrimoireLoader::new();

                match loader.load(persona_id).await {
                    Ok(persona) => {
                        // If variant requested, try to get it from the persona's variants
                        if let Some(var) = variant {
                            persona.variants.get(var).cloned().unwrap_or_else(|| {
                                tracing::debug!(
                                    persona_id,
                                    variant = var,
                                    "Variant not found, using base system prompt"
                                );
                                persona.system_prompt.clone()
                            })
                        } else {
                            persona.system_prompt
                        }
                    },
                    Err(_) => {
                        // Try legacy filesystem path loading as fallback
                        Self::load_from_filesystem(persona_id, variant.as_deref())
                    },
                }
            },
        }
    }

    /// Fallback filesystem loading for backwards compatibility.
    fn load_from_filesystem(persona_id: &str, variant: Option<&str>) -> String {
        let base_path = grimoire_loader::default_grimoire_path();
        let prompt_path = if let Some(var) = variant {
            base_path.join(persona_id).join(format!("{}.md", var))
        } else {
            let dir_path = base_path.join(persona_id);
            if dir_path.is_dir() {
                dir_path.join("prompt.md")
            } else {
                base_path.join(format!("{}.md", persona_id))
            }
        };

        match std::fs::read_to_string(&prompt_path) {
            Ok(content) => content,
            Err(_) => {
                tracing::debug!(
                    persona_id,
                    path = %prompt_path.display(),
                    "Grimoire persona not found, using default prompt"
                );
                format!("You are {} - an AI assistant.", persona_id)
            },
        }
    }
}

/// Agent persona configuration.
#[derive(Debug, Clone)]
pub struct Persona {
    /// System prompt source.
    pub system: PersonaSource,
    /// Preferred model.
    pub model: Option<ModelId>,
    /// Maximum iterations.
    pub max_iterations: u32,
}

impl Default for Persona {
    fn default() -> Self {
        Self {
            system: PersonaSource::Inline("You are a helpful AI assistant.".to_string()),
            model: None,
            max_iterations: 10,
        }
    }
}

impl Persona {
    /// Creates a new persona with an inline system prompt.
    #[must_use]
    pub fn inline(prompt: impl Into<String>) -> Self {
        Self {
            system: PersonaSource::inline(prompt),
            ..Default::default()
        }
    }

    /// Creates a new persona from a Grimoire persona ID.
    #[must_use]
    pub fn from_grimoire(persona_id: impl Into<String>) -> Self {
        Self {
            system: PersonaSource::grimoire(persona_id),
            ..Default::default()
        }
    }

    /// Creates a new persona from a Grimoire persona ID with a variant.
    #[must_use]
    pub fn from_grimoire_variant(
        persona_id: impl Into<String>,
        variant: impl Into<String>,
    ) -> Self {
        Self {
            system: PersonaSource::grimoire_with_variant(persona_id, variant),
            ..Default::default()
        }
    }

    /// Sets the preferred model.
    #[must_use]
    pub fn with_model(mut self, model: impl Into<ModelId>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Sets the maximum iterations.
    #[must_use]
    pub fn with_max_iterations(mut self, max: u32) -> Self {
        self.max_iterations = max;
        self
    }

    /// Resolves the system prompt asynchronously.
    ///
    /// This is the preferred method for loading Grimoire personas as it
    /// uses proper async I/O and caching.
    pub async fn resolve_system_prompt(&self) -> String {
        self.system.resolve().await
    }
}

/// An autonomous agent with tool use and reasoning capabilities.
pub struct Agent {
    /// Agent identifier.
    pub id: String,
    /// Agent persona.
    pub persona: Persona,
    /// Available tools.
    pub tools: ToolRegistry,
    /// Agent memory.
    pub memory: AgentMemory,
    /// Planning strategy.
    pub planner: Arc<dyn Planner>,
    /// The inference engine.
    engine: Option<Arc<dyn InferenceEngine>>,
    /// Working directory for file tools (set on ToolContext automatically).
    working_dir: Option<std::path::PathBuf>,
}

impl Agent {
    /// Creates a new agent builder.
    #[must_use]
    pub fn builder() -> AgentBuilder {
        AgentBuilder::default()
    }

    /// Returns the system prompt.
    #[must_use]
    pub fn system_prompt(&self) -> String {
        match &self.persona.system {
            PersonaSource::Inline(s) => s.clone(),
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                // Try to load from Grimoire filesystem (uses INFERNUM_GRIMOIRE_PATH env or default)
                let base_path = grimoire_loader::default_grimoire_path();
                let prompt_path = if let Some(var) = variant {
                    base_path.join(persona_id).join(format!("{}.md", var))
                } else {
                    let dir_path = base_path.join(persona_id);
                    if dir_path.is_dir() {
                        dir_path.join("prompt.md")
                    } else {
                        base_path.join(format!("{}.md", persona_id))
                    }
                };

                match std::fs::read_to_string(&prompt_path) {
                    Ok(content) => content,
                    Err(_) => {
                        // Provide a helpful fallback with guidance
                        tracing::debug!(
                            persona_id,
                            path = %prompt_path.display(),
                            "Grimoire persona not found, using default prompt"
                        );
                        format!("You are {} - an AI assistant.", persona_id)
                    },
                }
            },
        }
    }

    /// Sets the inference engine.
    pub fn set_engine(&mut self, engine: Arc<dyn InferenceEngine>) {
        self.engine = Some(engine);
    }

    /// Runs the agent with the given objective using ReAct-style reasoning.
    ///
    /// # Errors
    ///
    /// Returns an error if execution fails.
    pub async fn run(&mut self, objective: &str) -> Result<String> {
        let engine = self
            .engine
            .as_ref()
            .ok_or_else(|| infernum_core::Error::internal("No engine configured for agent"))?;

        tracing::info!(objective, agent_id = %self.id, "Starting agent execution");

        // Build system prompt with tool information
        let system_prompt = self.build_system_prompt();

        // Initialize conversation with system and user objective
        let mut messages = vec![
            Message {
                role: Role::System,
                content: system_prompt,
                name: None,
                tool_calls: None,
                tool_call_id: None,
            },
            Message {
                role: Role::User,
                content: objective.to_string(),
                name: None,
                tool_calls: None,
                tool_call_id: None,
            },
        ];

        // Create tool context
        let mut ctx = ToolContext::new(&self.id);
        ctx.messages = messages.clone();
        if let Some(ref wd) = self.working_dir {
            ctx.set_state("working_dir", serde_json::json!(&*wd.to_string_lossy()));
        }

        // Context size management: prevent OOM by limiting context growth
        // For 24GB GPU with 7B model: ~14GB model in BF16, need ~10GB for activations + KV-cache
        // KV cache size = 2 * layers * context * hidden_dim * dtype_size
        // For 7B Qwen: 2 * 28 * 8192 * 3584 * 2 bytes = ~3.3GB at 8K tokens
        // Safe limit: ~8K tokens = ~32K chars to leave headroom for activations
        // Override with INFERNUM_AGENT_MAX_CONTEXT_CHARS and INFERNUM_AGENT_MAX_TOOL_OUTPUT
        let max_context_chars: usize = std::env::var("INFERNUM_AGENT_MAX_CONTEXT_CHARS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(32_000); // ~8K tokens - conservative for 7B on 24GB
        let max_tool_output_chars: usize = std::env::var("INFERNUM_AGENT_MAX_TOOL_OUTPUT")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(8_000); // Reduced to prevent large tool results from filling context

        tracing::debug!(
            max_context_chars,
            max_tool_output_chars,
            "Context budget limits"
        );

        // ReAct loop
        let mut final_answer = String::new();
        for iteration in 0..self.persona.max_iterations {
            tracing::debug!(iteration, "ReAct iteration");

            // Proactive context budget check - prevent OOM by trimming BEFORE generation
            Self::ensure_context_budget(&mut messages, max_context_chars);

            // Generate response
            let request = GenerateRequest::chat(messages.clone()).with_sampling(
                SamplingParams::default()
                    .with_max_tokens(2048)
                    .with_temperature(0.7)
                    .with_repetition_penalty(1.15),
            );

            let response = engine.generate(request).await?;
            let assistant_response = response
                .choices
                .first()
                .map_or_else(String::new, |c| c.text.clone());

            tracing::debug!(response = %assistant_response, "Agent response");

            // Add assistant response to messages
            messages.push(Message {
                role: Role::Assistant,
                content: assistant_response.clone(),
                name: None,
                tool_calls: None,
                tool_call_id: None,
            });

            // Parse the response for actions
            let action = self.parse_action(&assistant_response);

            match action {
                AgentAction::Thought(thought) => {
                    tracing::debug!(thought, "Agent thinking");
                    // Continue to next iteration
                },
                AgentAction::ToolCall(tool_call) => {
                    tracing::info!(tool = %tool_call.name, "Executing tool");

                    // Execute the tool — catch errors as observations instead of crashing
                    let observation = match self.tools.execute(&tool_call, &ctx).await {
                        Ok(result) if result.success => {
                            format!("Observation: {}", result.output)
                        },
                        Ok(result) => {
                            format!(
                                "Observation: Tool error - {}",
                                result.error.unwrap_or_default()
                            )
                        },
                        Err(e) => {
                            tracing::warn!(tool = %tool_call.name, error = %e, "Tool execution failed");
                            format!("Observation: Tool execution failed - {}", e)
                        },
                    };

                    messages.push(Message {
                        role: Role::User,
                        content: observation.clone(),
                        name: Some("system".to_string()),
                        tool_calls: None,
                        tool_call_id: None,
                    });

                    tracing::debug!(observation = %observation, "Tool result");
                },
                AgentAction::FinalAnswer(answer) => {
                    tracing::info!("Agent reached final answer");
                    final_answer = answer;
                    break;
                },
                AgentAction::Continue => {
                    // No specific action, continue
                },
            }

            // Update context
            ctx.messages = messages.clone();
        }

        // Store conversation in memory
        for msg in &messages {
            self.memory.add_message(msg.clone());
        }

        if final_answer.is_empty() {
            // If no explicit final answer, use the last assistant response
            final_answer = messages
                .iter()
                .rev()
                .find(|m| m.role == Role::Assistant)
                .map_or_else(
                    || "No response generated.".to_string(),
                    |m| m.content.clone(),
                );
        }

        Ok(final_answer)
    }

    /// Returns the model family based on the persona's model ID.
    fn model_family(&self) -> infernum_core::ModelFamily {
        self.persona
            .model
            .as_ref()
            .map(|m| infernum_core::ModelFamily::from_model_name(&m.0))
            .unwrap_or_default()
    }

    /// Builds the system prompt with tool information.
    ///
    /// Uses model-native format when the model supports it (per TOOL-CALLING-SPEC §5.6),
    /// falling back to generic Action: / Action Input: format for unknown models.
    fn build_system_prompt(&self) -> String {
        let base_prompt = self.system_prompt();

        match self.model_family() {
            infernum_core::ModelFamily::Qwen => {
                let tools_desc = self.tools.to_qwen_native_description();
                format!(
                    "{}\n\n{}\n\n\
                    When you have the final answer, respond with:\n\
                    Final Answer: <your_answer>\n\n\
                    Always think step by step.",
                    base_prompt, tools_desc
                )
            },
            _ => {
                let tools_desc = self.tools.to_prompt_description();
                format!(
                    "{}\n\n## Tools\n\n{}\n\n## Instructions\n\n\
                    When you need to use a tool, respond with:\n\
                    Action: <tool_name>\n\
                    Action Input: <json_parameters>\n\n\
                    After receiving the observation, continue reasoning.\n\n\
                    When you have the final answer, respond with:\n\
                    Final Answer: <your_answer>\n\n\
                    Always think step by step. Use Thought: to express your reasoning.",
                    base_prompt, tools_desc
                )
            },
        }
    }

    /// Parses the agent's response to extract actions.
    ///
    /// Detects both model-native `<tool_call>` tags (§5.6) and generic
    /// `Action: / Action Input:` format for backwards compatibility.
    fn parse_action(&self, response: &str) -> AgentAction {
        let response = response.trim();

        // Check for final answer
        if let Some(answer) = response.strip_prefix("Final Answer:").or_else(|| {
            response
                .lines()
                .find(|line| line.trim().starts_with("Final Answer:"))
                .and_then(|line| line.strip_prefix("Final Answer:"))
        }) {
            return AgentAction::FinalAnswer(answer.trim().to_string());
        }

        // Check for native <tool_call> tags (§5.6 — Qwen, Llama, etc.)
        if let Some(call) = self.parse_native_tool_call(response) {
            return AgentAction::ToolCall(call);
        }

        // Check for generic Action: / Action Input: format
        let mut action_name = None;
        let mut action_input = None;

        for line in response.lines() {
            let line = line.trim();
            if let Some(name) = line.strip_prefix("Action:") {
                action_name = Some(name.trim().to_string());
            } else if let Some(input) = line.strip_prefix("Action Input:") {
                action_input = Some(input.trim().to_string());
            }
        }

        // Also check for JSON block action input
        if action_input.is_none() && action_name.is_some() {
            // Look for JSON in the response
            if let Some(json_start) = response.find('{') {
                if let Some(json_end) = response.rfind('}') {
                    action_input = Some(response[json_start..=json_end].to_string());
                }
            }
        }

        if let (Some(name), Some(input)) = (action_name, action_input) {
            // Parse the JSON input
            let params = serde_json::from_str(&input).unwrap_or(serde_json::json!({}));
            return AgentAction::ToolCall(ToolCall { name, params });
        }

        // Check for thought
        if let Some(thought) = response.strip_prefix("Thought:").or_else(|| {
            response
                .lines()
                .find(|line| line.trim().starts_with("Thought:"))
                .and_then(|line| line.strip_prefix("Thought:"))
        }) {
            return AgentAction::Thought(thought.trim().to_string());
        }

        AgentAction::Continue
    }

    /// Parse a native `<tool_call>` tag from model output.
    ///
    /// Returns the first tool call found within `<tool_call></tool_call>` tags.
    /// Takes `&self` for method dispatch even though not currently needed —
    /// future model-family-specific parsing variants may use it.
    #[allow(clippy::unused_self)]
    fn parse_native_tool_call(&self, response: &str) -> Option<ToolCall> {
        let start_tag = "<tool_call>";
        let end_tag = "</tool_call>";

        let start = response.find(start_tag)?;
        let content_start = start + start_tag.len();
        let end = response[content_start..].find(end_tag)?;
        let json_str = response[content_start..content_start + end].trim();

        let parsed: serde_json::Value = serde_json::from_str(json_str).ok()?;
        let name = parsed.get("name")?.as_str()?.to_string();
        let params = parsed
            .get("arguments")
            .cloned()
            .unwrap_or(serde_json::json!({}));

        Some(ToolCall { name, params })
    }

    /// Adds a message to the agent's memory.
    pub fn add_message(&mut self, message: Message) {
        self.memory.add_message(message);
    }

    /// Clears the agent's working memory.
    pub fn clear_memory(&mut self) {
        self.memory.clear();
    }

    /// Runs the agent with a pre-generated plan.
    ///
    /// Executes each step of the plan in order, handling tool calls
    /// and collecting observations.
    ///
    /// # Errors
    ///
    /// Returns an error if execution fails.
    pub async fn run_with_plan(
        &mut self,
        mut plan: crate::planner::Plan,
    ) -> Result<PlanExecutionResult> {
        let engine = self
            .engine
            .as_ref()
            .ok_or_else(|| infernum_core::Error::internal("No engine configured for agent"))?;

        tracing::info!(
            plan_id = %plan.id,
            objective = %plan.objective,
            steps = plan.steps.len(),
            "Starting plan execution"
        );

        let mut ctx = ToolContext::new(&self.id);
        if let Some(ref wd) = self.working_dir {
            ctx.set_state("working_dir", serde_json::json!(&*wd.to_string_lossy()));
        }
        let mut step_results = Vec::new();
        let mut final_output = String::new();

        while let Some(step) = plan.next_step() {
            tracing::debug!(
                step_id = %step.id,
                description = %step.description,
                "Executing plan step"
            );

            let step_result = if let Some(tool_name) = &step.tool {
                // Execute the tool specified in the plan
                let params = step.params.clone().unwrap_or(serde_json::json!({}));
                let tool_call = ToolCall {
                    name: tool_name.clone(),
                    params,
                };

                let result = self.tools.execute(&tool_call, &ctx).await?;
                let observation = if result.success {
                    result.output.clone()
                } else {
                    format!("Error: {}", result.error.unwrap_or_default())
                };

                // Add observation to context messages
                ctx.messages.push(Message {
                    role: Role::User,
                    content: format!(
                        "Step {}: {}\nResult: {}",
                        step.id, step.description, observation
                    ),
                    name: Some("system".to_string()),
                    tool_calls: None,
                    tool_call_id: None,
                });

                PlanStepResult {
                    step_id: step.id.clone(),
                    success: result.success,
                    output: observation,
                    tool_used: Some(tool_name.clone()),
                }
            } else {
                // No tool - generate reasoning with LLM
                let messages = vec![
                    Message {
                        role: Role::System,
                        content: self.build_system_prompt(),
                        name: None,
                        tool_calls: None,
                        tool_call_id: None,
                    },
                    Message {
                        role: Role::User,
                        content: format!(
                            "Execute step {} of the plan: {}\n\nContext:\n{}",
                            step.id,
                            step.description,
                            ctx.messages
                                .iter()
                                .map(|m| m.content.as_str())
                                .collect::<Vec<_>>()
                                .join("\n---\n")
                        ),
                        name: None,
                        tool_calls: None,
                        tool_call_id: None,
                    },
                ];

                let request = GenerateRequest::chat(messages).with_sampling(
                    SamplingParams::default()
                        .with_max_tokens(1024)
                        .with_temperature(0.7),
                );

                let response = engine.generate(request).await?;
                let output = response
                    .choices
                    .first()
                    .map_or_else(String::new, |c| c.text.clone());

                ctx.messages.push(Message {
                    role: Role::Assistant,
                    content: output.clone(),
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                });

                PlanStepResult {
                    step_id: step.id.clone(),
                    success: true,
                    output,
                    tool_used: None,
                }
            };

            final_output = step_result.output.clone();
            step_results.push(step_result);
            plan.advance();
        }

        // Store in memory
        for msg in &ctx.messages {
            self.memory.add_message(msg.clone());
        }

        Ok(PlanExecutionResult {
            plan_id: plan.id,
            steps_executed: step_results.len(),
            step_results,
            final_output,
            success: plan.complete,
        })
    }

    /// Generates a plan for the given objective using the configured planner.
    ///
    /// # Errors
    ///
    /// Returns an error if planning fails.
    pub async fn generate_plan(&self, objective: &str) -> Result<crate::planner::Plan> {
        self.planner.plan(objective, &self.tools).await
    }

    /// Replans based on feedback.
    ///
    /// # Errors
    ///
    /// Returns an error if replanning fails.
    pub async fn replan(
        &self,
        plan: &crate::planner::Plan,
        feedback: &str,
    ) -> Result<crate::planner::Plan> {
        self.planner.replan(plan, feedback, &self.tools).await
    }

    /// Runs a single step of reasoning (for streaming/interactive use).
    pub async fn step(&mut self, input: &str) -> Result<StepResult> {
        let engine = self
            .engine
            .as_ref()
            .ok_or_else(|| infernum_core::Error::internal("No engine configured for agent"))?;

        // Add user input to memory
        self.memory.add_message(Message::user(input));

        // Build messages from memory
        let mut messages = vec![Message {
            role: Role::System,
            content: self.build_system_prompt(),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }];
        messages.extend(self.memory.messages().iter().cloned());

        // Generate response
        let request = GenerateRequest::chat(messages).with_sampling(
            SamplingParams::default()
                .with_max_tokens(1024)
                .with_temperature(0.7),
        );

        let response = engine.generate(request).await?;
        let assistant_response = response
            .choices
            .first()
            .map_or_else(String::new, |c| c.text.clone());

        // Add to memory
        self.memory
            .add_message(Message::assistant(&assistant_response));

        // Parse action
        let action = self.parse_action(&assistant_response);

        Ok(StepResult {
            response: assistant_response,
            action,
            usage: StepUsage {
                prompt_tokens: response.usage.prompt_tokens,
                completion_tokens: response.usage.completion_tokens,
            },
        })
    }

    /// Runs a single step with streaming output.
    pub async fn step_streaming(
        &mut self,
        input: &str,
    ) -> Result<impl futures::Stream<Item = Result<String>>> {
        let engine = self
            .engine
            .as_ref()
            .ok_or_else(|| infernum_core::Error::internal("No engine configured for agent"))?
            .clone();

        // Add user input to memory
        self.memory.add_message(Message::user(input));

        // Build messages from memory
        let mut messages = vec![Message {
            role: Role::System,
            content: self.build_system_prompt(),
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }];
        messages.extend(self.memory.messages().iter().cloned());

        // Generate streaming response
        let request = GenerateRequest::chat(messages).with_sampling(
            SamplingParams::default()
                .with_max_tokens(1024)
                .with_temperature(0.7),
        );

        let token_stream = engine.generate_stream(request).await?;

        Ok(token_stream.map(|result| {
            result.map(|chunk| {
                chunk
                    .choices
                    .first()
                    .and_then(|c| c.delta.content.clone())
                    .unwrap_or_default()
            })
        }))
    }

    /// Ensures context is within budget by compressing and trimming proactively.
    /// Call this BEFORE each LLM generation to prevent OOM.
    fn ensure_context_budget(messages: &mut Vec<Message>, max_chars: usize) {
        let total: usize = messages.iter().map(|m| m.content.len()).sum();
        let threshold = max_chars * 4 / 5; // 80% threshold for proactive trimming

        if total > threshold {
            tracing::info!(
                total_chars = total,
                threshold = threshold,
                messages_count = messages.len(),
                "Proactive context trimming triggered"
            );

            // First, compress older observations to save space
            Self::compress_old_observations(messages);

            // Check again after compression
            let total_after_compress: usize = messages.iter().map(|m| m.content.len()).sum();

            // Then remove oldest messages if still over threshold
            if total_after_compress > threshold {
                while messages.len() > 3
                    && messages.iter().map(|m| m.content.len()).sum::<usize>() > threshold
                {
                    messages.remove(1); // Remove oldest non-system message
                    tracing::debug!(
                        remaining = messages.len(),
                        "Removed oldest message during proactive trim"
                    );
                }
            }
        }
    }

    /// Compresses older observations to save context space.
    /// Keeps the last 2 observations intact, compresses older ones.
    fn compress_old_observations(messages: &mut Vec<Message>) {
        // Find all observation message indices
        let observation_indices: Vec<usize> = messages
            .iter()
            .enumerate()
            .filter(|(_, m)| m.content.starts_with("Observation:"))
            .map(|(i, _)| i)
            .collect();

        // Keep last 2 observations intact, compress older ones
        let to_compress: Vec<usize> = observation_indices
            .iter()
            .rev()
            .skip(2) // Skip the 2 most recent
            .copied()
            .collect();

        for idx in to_compress {
            if messages[idx].content.len() > 500 {
                let compressed = Self::compress_observation(&messages[idx].content);
                let saved = messages[idx].content.len() - compressed.len();
                if saved > 100 {
                    tracing::debug!(
                        idx = idx,
                        original_len = messages[idx].content.len(),
                        compressed_len = compressed.len(),
                        saved_chars = saved,
                        "Compressed old observation"
                    );
                    messages[idx].content = compressed;
                }
            }
        }
    }

    /// Compresses an observation to its key findings.
    fn compress_observation(obs: &str) -> String {
        let lines: Vec<&str> = obs.lines().collect();
        if lines.len() <= 5 {
            return obs.to_string();
        }

        // Keep first line (usually the summary header)
        let first_line = lines.first().copied().unwrap_or("");

        // Extract file paths mentioned (important context)
        let paths: Vec<&str> = lines
            .iter()
            .filter(|l| {
                l.contains('/')
                    || l.ends_with(".rs")
                    || l.ends_with(".ts")
                    || l.ends_with(".py")
                    || l.ends_with(".json")
            })
            .take(5)
            .copied()
            .collect();

        // Extract key metadata lines (lines with counts, success/error)
        let metadata: Vec<&str> = lines
            .iter()
            .filter(|l| {
                l.contains("lines")
                    || l.contains("files")
                    || l.contains("matches")
                    || l.contains("bytes")
                    || l.contains("Success")
                    || l.contains("Error")
                    || l.contains("truncated")
            })
            .take(3)
            .copied()
            .collect();

        let mut result = format!("{}\n[Compressed from {} lines]", first_line, lines.len());

        if !paths.is_empty() {
            result.push_str("\nKey files:\n");
            for path in paths.iter().take(3) {
                result.push_str("  ");
                result.push_str(path.trim());
                result.push('\n');
            }
            if paths.len() > 3 {
                result.push_str(&format!("  ... and {} more\n", paths.len() - 3));
            }
        }

        if !metadata.is_empty() {
            result.push_str("Summary: ");
            result.push_str(&metadata.join(" | "));
        }

        result
    }
}

/// Result from a single agent step.
#[derive(Debug)]
pub struct StepResult {
    /// The full response text.
    pub response: String,
    /// The parsed action.
    pub action: AgentAction,
    /// Token usage.
    pub usage: StepUsage,
}

/// Token usage for a step.
#[derive(Debug)]
pub struct StepUsage {
    /// Prompt tokens.
    pub prompt_tokens: u32,
    /// Completion tokens.
    pub completion_tokens: u32,
}

/// Action parsed from agent response.
#[derive(Debug, Clone)]
pub enum AgentAction {
    /// Agent is thinking/reasoning.
    Thought(String),
    /// Agent wants to call a tool.
    ToolCall(ToolCall),
    /// Agent has reached a final answer.
    FinalAnswer(String),
    /// No specific action, continue.
    Continue,
}

/// Result of executing a single plan step.
#[derive(Debug, Clone)]
pub struct PlanStepResult {
    /// The step ID.
    pub step_id: String,
    /// Whether the step succeeded.
    pub success: bool,
    /// Output from the step.
    pub output: String,
    /// Tool used (if any).
    pub tool_used: Option<String>,
}

/// Result of executing a complete plan.
#[derive(Debug)]
pub struct PlanExecutionResult {
    /// Plan ID that was executed.
    pub plan_id: String,
    /// Number of steps executed.
    pub steps_executed: usize,
    /// Results from each step.
    pub step_results: Vec<PlanStepResult>,
    /// Final output from the plan.
    pub final_output: String,
    /// Whether the plan completed successfully.
    pub success: bool,
}

/// Builder for creating agents.
#[derive(Default)]
pub struct AgentBuilder {
    id: Option<String>,
    persona: Option<Persona>,
    tools: Option<ToolRegistry>,
    planning_strategy: Option<PlanningStrategy>,
    engine: Option<Arc<dyn InferenceEngine>>,
    working_dir: Option<std::path::PathBuf>,
}

impl AgentBuilder {
    /// Sets the agent ID.
    #[must_use]
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Sets the persona from an inline prompt.
    #[must_use]
    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        let mut persona = self.persona.unwrap_or_default();
        persona.system = PersonaSource::Inline(prompt.into());
        self.persona = Some(persona);
        self
    }

    /// Sets the persona from a Grimoire reference.
    #[must_use]
    pub fn grimoire_persona(mut self, persona_id: impl Into<String>) -> Self {
        let mut persona = self.persona.unwrap_or_default();
        persona.system = PersonaSource::Grimoire {
            persona_id: persona_id.into(),
            variant: None,
        };
        self.persona = Some(persona);
        self
    }

    /// Sets the preferred model.
    #[must_use]
    pub fn model(mut self, model: impl Into<ModelId>) -> Self {
        let mut persona = self.persona.unwrap_or_default();
        persona.model = Some(model.into());
        self.persona = Some(persona);
        self
    }

    /// Sets the maximum iterations.
    #[must_use]
    pub fn max_iterations(mut self, max: u32) -> Self {
        let mut persona = self.persona.unwrap_or_default();
        persona.max_iterations = max;
        self.persona = Some(persona);
        self
    }

    /// Sets the tool registry.
    #[must_use]
    pub fn tools(mut self, tools: ToolRegistry) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Sets the planning strategy.
    #[must_use]
    pub fn planning_strategy(mut self, strategy: PlanningStrategy) -> Self {
        self.planning_strategy = Some(strategy);
        self
    }

    /// Sets the inference engine.
    #[must_use]
    pub fn engine(mut self, engine: Arc<dyn InferenceEngine>) -> Self {
        self.engine = Some(engine);
        self
    }

    /// Sets the working directory for file tools.
    ///
    /// This directory is set on the `ToolContext` automatically during
    /// agent execution. File tools validate that all paths stay within
    /// this boundary.
    #[must_use]
    pub fn working_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
        self.working_dir = Some(dir.into());
        self
    }

    /// Builds the agent.
    #[must_use]
    pub fn build(self) -> Agent {
        let strategy = self
            .planning_strategy
            .unwrap_or(PlanningStrategy::ReAct { max_iterations: 10 });

        Agent {
            id: self.id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
            persona: self.persona.unwrap_or_default(),
            tools: self.tools.unwrap_or_default(),
            memory: AgentMemory::new(),
            planner: Arc::new(crate::planner::DefaultPlanner::new(strategy)),
            engine: self.engine,
            working_dir: self.working_dir,
        }
    }
}

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

    #[test]
    fn test_parse_action_final_answer() {
        let agent = Agent::builder().build();
        let response = "Thought: I've calculated the result.\nFinal Answer: The answer is 42.";

        match agent.parse_action(response) {
            AgentAction::FinalAnswer(answer) => {
                assert_eq!(answer, "The answer is 42.");
            },
            _ => panic!("Expected FinalAnswer"),
        }
    }

    #[test]
    fn test_parse_action_final_answer_multiline() {
        let agent = Agent::builder().build();
        // Parser extracts content from the Final Answer: line forward
        let response = r#"Thought: After considering all factors, I can now provide the final answer.

Final Answer: The solution involves three steps"#;

        match agent.parse_action(response) {
            AgentAction::FinalAnswer(answer) => {
                assert!(answer.contains("three steps"));
            },
            _ => panic!("Expected FinalAnswer"),
        }
    }

    #[test]
    fn test_parse_action_tool_call() {
        let agent = Agent::builder().build();
        let response = "Thought: I need to calculate something.\nAction: calculator\nAction Input: {\"expression\": \"2+2\"}";

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "calculator");
                assert_eq!(call.params["expression"], "2+2");
            },
            _ => panic!("Expected ToolCall"),
        }
    }

    #[test]
    fn test_parse_action_tool_call_with_json_in_response() {
        let agent = Agent::builder().build();
        // When Action Input is empty, parser looks for JSON block in response
        let response = r#"Thought: I need to search for information.
Action: search
{"query": "Rust programming", "max_results": 5}"#;

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "search");
                assert_eq!(call.params["query"], "Rust programming");
                assert_eq!(call.params["max_results"], 5);
            },
            _ => panic!("Expected ToolCall"),
        }
    }

    #[test]
    fn test_parse_action_thought() {
        let agent = Agent::builder().build();
        let response = "Thought: Let me think about this problem.";

        match agent.parse_action(response) {
            AgentAction::Thought(thought) => {
                assert_eq!(thought, "Let me think about this problem.");
            },
            _ => panic!("Expected Thought"),
        }
    }

    #[test]
    fn test_parse_action_continue() {
        let agent = Agent::builder().build();
        let response = "I'm processing the information...";

        match agent.parse_action(response) {
            AgentAction::Continue => {},
            _ => panic!("Expected Continue"),
        }
    }

    #[test]
    fn test_agent_builder_defaults() {
        let agent = Agent::builder().build();

        assert!(!agent.id.is_empty());
        assert_eq!(agent.persona.max_iterations, 10);
    }

    #[test]
    fn test_agent_builder_custom() {
        let agent = Agent::builder()
            .id("test-agent")
            .system_prompt("You are a test agent.")
            .max_iterations(5)
            .build();

        assert_eq!(agent.id, "test-agent");
        assert_eq!(agent.persona.max_iterations, 5);
        assert_eq!(agent.system_prompt(), "You are a test agent.");
    }

    #[test]
    fn test_agent_builder_grimoire_persona() {
        let agent = Agent::builder().grimoire_persona("test-persona").build();

        match &agent.persona.system {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "test-persona");
                assert!(variant.is_none());
            },
            _ => panic!("Expected Grimoire persona"),
        }
    }

    #[test]
    fn test_build_system_prompt() {
        let agent = Agent::builder()
            .system_prompt("You are a helpful assistant.")
            .build();

        let prompt = agent.build_system_prompt();

        assert!(prompt.contains("You are a helpful assistant."));
        assert!(prompt.contains("## Tools"));
        assert!(prompt.contains("## Instructions"));
        assert!(prompt.contains("Final Answer:"));
    }

    #[test]
    fn test_agent_memory_operations() {
        let mut agent = Agent::builder().build();

        assert!(agent.memory.messages().is_empty());

        agent.add_message(Message::user("Hello"));
        assert_eq!(agent.memory.messages().len(), 1);

        agent.add_message(Message::assistant("Hi there!"));
        assert_eq!(agent.memory.messages().len(), 2);

        agent.clear_memory();
        assert!(agent.memory.messages().is_empty());
    }

    #[test]
    fn test_persona_default() {
        let persona = Persona::default();

        assert_eq!(persona.max_iterations, 10);
        assert!(persona.model.is_none());
        match persona.system {
            PersonaSource::Inline(s) => {
                assert!(s.contains("helpful AI assistant"));
            },
            _ => panic!("Expected inline persona"),
        }
    }

    #[test]
    fn test_plan_step_result() {
        let result = PlanStepResult {
            step_id: "1".to_string(),
            success: true,
            output: "Step completed".to_string(),
            tool_used: Some("calculator".to_string()),
        };

        assert!(result.success);
        assert_eq!(result.tool_used, Some("calculator".to_string()));
    }

    #[test]
    fn test_agent_action_clone() {
        let action = AgentAction::ToolCall(ToolCall {
            name: "test".to_string(),
            params: serde_json::json!({"key": "value"}),
        });

        let cloned = action.clone();
        match cloned {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "test");
            },
            _ => panic!("Expected ToolCall"),
        }
    }

    // ==========================================================================
    // PersonaSource Tests
    // ==========================================================================

    #[test]
    fn test_persona_source_inline() {
        let source = PersonaSource::Inline("Custom prompt".to_string());
        match source {
            PersonaSource::Inline(s) => assert_eq!(s, "Custom prompt"),
            _ => panic!("Expected Inline"),
        }
    }

    #[test]
    fn test_persona_source_grimoire() {
        let source = PersonaSource::Grimoire {
            persona_id: "assistant".to_string(),
            variant: Some("friendly".to_string()),
        };
        match source {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "assistant");
                assert_eq!(variant, Some("friendly".to_string()));
            },
            _ => panic!("Expected Grimoire"),
        }
    }

    #[test]
    fn test_persona_source_grimoire_no_variant() {
        let source = PersonaSource::Grimoire {
            persona_id: "default".to_string(),
            variant: None,
        };
        match source {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "default");
                assert!(variant.is_none());
            },
            _ => panic!("Expected Grimoire"),
        }
    }

    #[test]
    fn test_persona_source_debug() {
        let source = PersonaSource::Inline("test".to_string());
        let debug_str = format!("{:?}", source);
        assert!(debug_str.contains("Inline"));
    }

    #[test]
    fn test_persona_source_clone() {
        let source = PersonaSource::Grimoire {
            persona_id: "test".to_string(),
            variant: None,
        };
        let cloned = source.clone();
        match cloned {
            PersonaSource::Grimoire { persona_id, .. } => {
                assert_eq!(persona_id, "test");
            },
            _ => panic!("Expected Grimoire"),
        }
    }

    // ==========================================================================
    // Persona Tests
    // ==========================================================================

    #[test]
    fn test_persona_with_all_fields() {
        let persona = Persona {
            system: PersonaSource::Inline("Expert assistant".to_string()),
            model: Some("gpt-4".into()),
            max_iterations: 15,
        };
        assert_eq!(persona.max_iterations, 15);
        assert!(persona.model.is_some());
    }

    #[test]
    fn test_persona_debug() {
        let persona = Persona::default();
        let debug_str = format!("{:?}", persona);
        assert!(debug_str.contains("Persona"));
        assert!(debug_str.contains("max_iterations"));
    }

    #[test]
    fn test_persona_clone() {
        let persona = Persona {
            system: PersonaSource::Inline("Clone test".to_string()),
            model: None,
            max_iterations: 5,
        };
        let cloned = persona.clone();
        assert_eq!(cloned.max_iterations, 5);
    }

    // ==========================================================================
    // AgentAction Tests
    // ==========================================================================

    #[test]
    fn test_agent_action_all_variants() {
        let thought = AgentAction::Thought("thinking".to_string());
        let tool = AgentAction::ToolCall(ToolCall {
            name: "test".to_string(),
            params: serde_json::json!({}),
        });
        let answer = AgentAction::FinalAnswer("done".to_string());
        let cont = AgentAction::Continue;

        assert!(matches!(thought, AgentAction::Thought(_)));
        assert!(matches!(tool, AgentAction::ToolCall(_)));
        assert!(matches!(answer, AgentAction::FinalAnswer(_)));
        assert!(matches!(cont, AgentAction::Continue));
    }

    #[test]
    fn test_agent_action_debug() {
        let action = AgentAction::Thought("debug test".to_string());
        let debug_str = format!("{:?}", action);
        assert!(debug_str.contains("Thought"));
        assert!(debug_str.contains("debug test"));
    }

    #[test]
    fn test_agent_action_clone_final_answer() {
        let action = AgentAction::FinalAnswer("The answer".to_string());
        let cloned = action.clone();
        match cloned {
            AgentAction::FinalAnswer(s) => assert_eq!(s, "The answer"),
            _ => panic!("Expected FinalAnswer"),
        }
    }

    #[test]
    fn test_agent_action_clone_continue() {
        let action = AgentAction::Continue;
        let cloned = action.clone();
        assert!(matches!(cloned, AgentAction::Continue));
    }

    // ==========================================================================
    // PlanStepResult Tests
    // ==========================================================================

    #[test]
    fn test_plan_step_result_all_fields() {
        let result = PlanStepResult {
            step_id: "step-1".to_string(),
            success: false,
            output: "Error occurred".to_string(),
            tool_used: None,
        };
        assert_eq!(result.step_id, "step-1");
        assert!(!result.success);
        assert!(result.tool_used.is_none());
    }

    #[test]
    fn test_plan_step_result_debug() {
        let result = PlanStepResult {
            step_id: "1".to_string(),
            success: true,
            output: "done".to_string(),
            tool_used: Some("calculator".to_string()),
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("PlanStepResult"));
        assert!(debug_str.contains("calculator"));
    }

    #[test]
    fn test_plan_step_result_clone() {
        let result = PlanStepResult {
            step_id: "clone-test".to_string(),
            success: true,
            output: "output".to_string(),
            tool_used: None,
        };
        let cloned = result.clone();
        assert_eq!(cloned.step_id, "clone-test");
    }

    // ==========================================================================
    // PlanExecutionResult Tests
    // ==========================================================================

    #[test]
    fn test_plan_execution_result_creation() {
        let result = PlanExecutionResult {
            plan_id: "plan-123".to_string(),
            steps_executed: 3,
            step_results: vec![
                PlanStepResult {
                    step_id: "1".to_string(),
                    success: true,
                    output: "step 1".to_string(),
                    tool_used: None,
                },
                PlanStepResult {
                    step_id: "2".to_string(),
                    success: true,
                    output: "step 2".to_string(),
                    tool_used: Some("search".to_string()),
                },
            ],
            final_output: "Complete".to_string(),
            success: true,
        };
        assert_eq!(result.plan_id, "plan-123");
        assert_eq!(result.steps_executed, 3);
        assert_eq!(result.step_results.len(), 2);
        assert!(result.success);
    }

    #[test]
    fn test_plan_execution_result_debug() {
        let result = PlanExecutionResult {
            plan_id: "debug-plan".to_string(),
            steps_executed: 1,
            step_results: vec![],
            final_output: "done".to_string(),
            success: true,
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("PlanExecutionResult"));
        assert!(debug_str.contains("debug-plan"));
    }

    // ==========================================================================
    // StepResult Tests
    // ==========================================================================

    #[test]
    fn test_step_result_creation() {
        let result = StepResult {
            response: "Agent response".to_string(),
            action: AgentAction::Continue,
            usage: StepUsage {
                prompt_tokens: 100,
                completion_tokens: 50,
            },
        };
        assert_eq!(result.response, "Agent response");
        assert!(matches!(result.action, AgentAction::Continue));
    }

    #[test]
    fn test_step_result_debug() {
        let result = StepResult {
            response: "test".to_string(),
            action: AgentAction::FinalAnswer("answer".to_string()),
            usage: StepUsage {
                prompt_tokens: 10,
                completion_tokens: 5,
            },
        };
        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("StepResult"));
    }

    // ==========================================================================
    // StepUsage Tests
    // ==========================================================================

    #[test]
    fn test_step_usage_creation() {
        let usage = StepUsage {
            prompt_tokens: 500,
            completion_tokens: 200,
        };
        assert_eq!(usage.prompt_tokens, 500);
        assert_eq!(usage.completion_tokens, 200);
    }

    #[test]
    fn test_step_usage_debug() {
        let usage = StepUsage {
            prompt_tokens: 100,
            completion_tokens: 50,
        };
        let debug_str = format!("{:?}", usage);
        assert!(debug_str.contains("StepUsage"));
        assert!(debug_str.contains("100"));
    }

    // ==========================================================================
    // AgentBuilder Additional Tests
    // ==========================================================================

    #[test]
    fn test_agent_builder_with_tools() {
        use crate::tool::ToolRegistry;

        let registry = ToolRegistry::with_builtins();
        let agent = Agent::builder().tools(registry).build();

        assert!(agent.tools.len() >= 3);
    }

    #[test]
    fn test_agent_builder_with_planning_strategy() {
        let agent = Agent::builder()
            .planning_strategy(PlanningStrategy::Hierarchical { max_depth: 3 })
            .build();

        // Agent should be built successfully with custom strategy
        assert!(!agent.id.is_empty());
    }

    #[test]
    fn test_agent_builder_with_model() {
        let agent = Agent::builder().model("gpt-4-turbo").build();

        assert_eq!(agent.persona.model, Some("gpt-4-turbo".into()));
    }

    #[test]
    fn test_agent_builder_chain_all() {
        let agent = Agent::builder()
            .id("full-agent")
            .system_prompt("Full test agent")
            .model("claude-3")
            .max_iterations(20)
            .tools(ToolRegistry::new())
            .planning_strategy(PlanningStrategy::SingleShot)
            .build();

        assert_eq!(agent.id, "full-agent");
        assert_eq!(agent.persona.max_iterations, 20);
        assert!(agent.persona.model.is_some());
    }

    // ==========================================================================
    // Agent Additional Tests
    // ==========================================================================

    #[test]
    fn test_agent_system_prompt_inline() {
        let agent = Agent::builder()
            .system_prompt("Custom inline prompt")
            .build();

        assert_eq!(agent.system_prompt(), "Custom inline prompt");
    }

    #[test]
    fn test_agent_system_prompt_grimoire_fallback() {
        // When Grimoire persona file doesn't exist, it should use a fallback
        let agent = Agent::builder()
            .grimoire_persona("nonexistent-persona")
            .build();

        let prompt = agent.system_prompt();
        // Should contain the persona_id in the fallback message
        assert!(prompt.contains("nonexistent-persona"));
    }

    // ==========================================================================
    // parse_action Edge Cases
    // ==========================================================================

    #[test]
    fn test_parse_action_empty_response() {
        let agent = Agent::builder().build();
        let action = agent.parse_action("");

        assert!(matches!(action, AgentAction::Continue));
    }

    #[test]
    fn test_parse_action_whitespace_only() {
        let agent = Agent::builder().build();
        let action = agent.parse_action("   \n\t  ");

        assert!(matches!(action, AgentAction::Continue));
    }

    #[test]
    fn test_parse_action_final_answer_at_start() {
        let agent = Agent::builder().build();
        let response = "Final Answer: Direct answer at the start";

        match agent.parse_action(response) {
            AgentAction::FinalAnswer(answer) => {
                assert_eq!(answer, "Direct answer at the start");
            },
            _ => panic!("Expected FinalAnswer"),
        }
    }

    #[test]
    fn test_parse_action_thought_in_middle() {
        let agent = Agent::builder().build();
        let response = "Some preamble\nThought: The actual thought\nMore text";

        match agent.parse_action(response) {
            AgentAction::Thought(thought) => {
                assert_eq!(thought, "The actual thought");
            },
            _ => panic!("Expected Thought"),
        }
    }

    #[test]
    fn test_parse_action_tool_call_empty_json() {
        let agent = Agent::builder().build();
        let response = "Action: empty_tool\nAction Input: {}";

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "empty_tool");
                assert_eq!(call.params, serde_json::json!({}));
            },
            _ => panic!("Expected ToolCall"),
        }
    }

    #[test]
    fn test_parse_action_tool_call_invalid_json() {
        let agent = Agent::builder().build();
        let response = "Action: bad_json_tool\nAction Input: not valid json at all";

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "bad_json_tool");
                // Invalid JSON should result in empty object
                assert_eq!(call.params, serde_json::json!({}));
            },
            _ => panic!("Expected ToolCall"),
        }
    }

    #[test]
    fn test_parse_action_prefers_final_answer() {
        let agent = Agent::builder().build();
        // When both Final Answer and Action are present, Final Answer should take precedence
        let response = "Thought: Done\nFinal Answer: Complete\nAction: should_not_run";

        match agent.parse_action(response) {
            AgentAction::FinalAnswer(answer) => {
                assert_eq!(answer, "Complete");
            },
            _ => panic!("Expected FinalAnswer to take precedence"),
        }
    }

    // ==========================================================================
    // Agent Memory Tests
    // ==========================================================================

    #[test]
    fn test_agent_add_multiple_messages() {
        let mut agent = Agent::builder().build();

        agent.add_message(Message::user("First"));
        agent.add_message(Message::assistant("Response 1"));
        agent.add_message(Message::user("Second"));
        agent.add_message(Message::assistant("Response 2"));

        assert_eq!(agent.memory.messages().len(), 4);
    }

    #[test]
    fn test_agent_clear_memory_is_complete() {
        let mut agent = Agent::builder().build();

        agent.add_message(Message::user("Test 1"));
        agent.add_message(Message::user("Test 2"));
        assert_eq!(agent.memory.messages().len(), 2);

        agent.clear_memory();
        assert!(agent.memory.messages().is_empty());

        // Should be able to add messages after clearing
        agent.add_message(Message::user("New message"));
        assert_eq!(agent.memory.messages().len(), 1);
    }

    // ==========================================================================
    // Build System Prompt Tests
    // ==========================================================================

    #[test]
    fn test_build_system_prompt_includes_tools() {
        use crate::tool::ToolRegistry;

        let registry = ToolRegistry::with_builtins();
        let agent = Agent::builder()
            .system_prompt("Base prompt")
            .tools(registry)
            .build();

        let prompt = agent.build_system_prompt();

        assert!(prompt.contains("Base prompt"));
        assert!(prompt.contains("## Tools"));
        assert!(prompt.contains("calculator"));
    }

    #[test]
    fn test_build_system_prompt_includes_instructions() {
        let agent = Agent::builder().build();
        let prompt = agent.build_system_prompt();

        assert!(prompt.contains("Action:"));
        assert!(prompt.contains("Action Input:"));
        assert!(prompt.contains("Final Answer:"));
        assert!(prompt.contains("Thought:"));
    }

    // ==========================================================================
    // AgentBuilder Default Tests
    // ==========================================================================

    #[test]
    fn test_agent_builder_default() {
        let builder = AgentBuilder::default();
        let agent = builder.build();

        // Default agent should have auto-generated ID
        assert!(!agent.id.is_empty());
        // Default persona with 10 iterations
        assert_eq!(agent.persona.max_iterations, 10);
        // Empty tools registry
        assert!(agent.tools.is_empty());
    }

    #[test]
    fn test_agent_builder_partial() {
        let agent = Agent::builder().id("partial-agent").build();

        assert_eq!(agent.id, "partial-agent");
        // Other fields should use defaults
        assert_eq!(agent.persona.max_iterations, 10);
    }

    // ==========================================================================
    // PersonaSource Builder Tests
    // ==========================================================================

    #[test]
    fn test_persona_source_inline_builder() {
        let source = PersonaSource::inline("Custom prompt");
        match source {
            PersonaSource::Inline(s) => assert_eq!(s, "Custom prompt"),
            _ => panic!("Expected Inline"),
        }
    }

    #[test]
    fn test_persona_source_grimoire_builder() {
        let source = PersonaSource::grimoire("code-reviewer");
        match source {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "code-reviewer");
                assert!(variant.is_none());
            },
            _ => panic!("Expected Grimoire"),
        }
    }

    #[test]
    fn test_persona_source_grimoire_with_variant_builder() {
        let source = PersonaSource::grimoire_with_variant("assistant", "friendly");
        match source {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "assistant");
                assert_eq!(variant, Some("friendly".to_string()));
            },
            _ => panic!("Expected Grimoire"),
        }
    }

    #[tokio::test]
    async fn test_persona_source_resolve_inline() {
        let source = PersonaSource::inline("Test prompt for resolution");
        let resolved = source.resolve().await;
        assert_eq!(resolved, "Test prompt for resolution");
    }

    #[tokio::test]
    async fn test_persona_source_resolve_grimoire_fallback() {
        // Non-existent persona should fall back to default message
        let source = PersonaSource::grimoire("nonexistent-persona-xyz");
        let resolved = source.resolve().await;
        assert!(resolved.contains("nonexistent-persona-xyz"));
    }

    // ==========================================================================
    // Persona Builder Tests
    // ==========================================================================

    #[test]
    fn test_persona_inline_constructor() {
        let persona = Persona::inline("Expert coding assistant");
        match &persona.system {
            PersonaSource::Inline(s) => assert_eq!(s, "Expert coding assistant"),
            _ => panic!("Expected Inline source"),
        }
        assert_eq!(persona.max_iterations, 10); // default
    }

    #[test]
    fn test_persona_from_grimoire() {
        let persona = Persona::from_grimoire("code-reviewer");
        match &persona.system {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "code-reviewer");
                assert!(variant.is_none());
            },
            _ => panic!("Expected Grimoire source"),
        }
    }

    #[test]
    fn test_persona_from_grimoire_variant() {
        let persona = Persona::from_grimoire_variant("assistant", "concise");
        match &persona.system {
            PersonaSource::Grimoire {
                persona_id,
                variant,
            } => {
                assert_eq!(persona_id, "assistant");
                assert_eq!(variant.as_deref(), Some("concise"));
            },
            _ => panic!("Expected Grimoire source"),
        }
    }

    #[test]
    fn test_persona_builder_pattern() {
        let persona = Persona::from_grimoire("expert")
            .with_model("gpt-4")
            .with_max_iterations(20);

        assert_eq!(persona.model, Some("gpt-4".into()));
        assert_eq!(persona.max_iterations, 20);
    }

    #[tokio::test]
    async fn test_persona_resolve_system_prompt_inline() {
        let persona = Persona::inline("Resolved inline prompt");
        let prompt = persona.resolve_system_prompt().await;
        assert_eq!(prompt, "Resolved inline prompt");
    }

    #[tokio::test]
    async fn test_persona_resolve_system_prompt_grimoire_fallback() {
        let persona = Persona::from_grimoire("nonexistent-test-persona");
        let prompt = persona.resolve_system_prompt().await;
        // Should contain the persona_id in the fallback message
        assert!(prompt.contains("nonexistent-test-persona"));
    }

    // =========================================================================
    // Spec §5.6: Beleth Agent Native Format Tests
    //
    // These tests validate TOOL-CALLING-SPEC.md §5.6. When the agent's model
    // is Qwen, it should use native tool calling format instead of generic
    // Action: / Action Input: text protocol.
    // =========================================================================

    #[test]
    fn test_build_system_prompt_qwen_uses_native_format() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(crate::tool::CalculatorTool));

        let agent = Agent::builder()
            .model("Qwen/Qwen2.5-7B-Instruct")
            .tools(registry)
            .build();

        let prompt = agent.build_system_prompt();

        // §5.6: Qwen model must use <tools> XML tags with JSON definitions
        assert!(
            prompt.contains("<tools>"),
            "Qwen agent should use <tools> tag in system prompt"
        );
        assert!(
            prompt.contains("</tools>"),
            "Qwen agent should close <tools> tag"
        );
        assert!(
            prompt.contains("\"type\":\"function\""),
            "Qwen agent should use JSON function definitions"
        );

        // §5.6: Must use native preamble
        assert!(
            prompt.contains("You may call one or more functions"),
            "Qwen agent should use native preamble"
        );

        // §5.6: Must NOT use generic Action: format
        assert!(
            !prompt.contains("Action: <tool_name>"),
            "Qwen agent must not use generic Action: format"
        );
    }

    #[test]
    fn test_build_system_prompt_unknown_model_uses_generic_format() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(crate::tool::CalculatorTool));

        let agent = Agent::builder().tools(registry).build();

        let prompt = agent.build_system_prompt();

        // Unknown model (no model set) should fall back to generic format
        assert!(
            prompt.contains("Action: <tool_name>"),
            "Unknown model should use generic Action: format"
        );
    }

    #[test]
    fn test_parse_action_detects_native_tool_call_tags() {
        let agent = Agent::builder().model("Qwen/Qwen2.5-7B-Instruct").build();

        let response = r#"<tool_call>
{"name": "calculator", "arguments": {"expression": "2+2"}}
</tool_call>"#;

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "calculator");
                assert_eq!(call.params["expression"], "2+2");
            },
            other => panic!("Expected ToolCall from native format, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_action_detects_native_with_text_before() {
        let agent = Agent::builder().model("Qwen/Qwen2.5-7B-Instruct").build();

        let response = r#"I'll calculate that for you.
<tool_call>
{"name": "calculator", "arguments": {"expression": "15*7"}}
</tool_call>"#;

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "calculator");
                assert_eq!(call.params["expression"], "15*7");
            },
            other => panic!("Expected ToolCall, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_action_generic_still_works_with_qwen_model() {
        // §5.6: Backwards compatibility — generic format should still parse
        let agent = Agent::builder().model("Qwen/Qwen2.5-7B-Instruct").build();

        let response = "Thought: I need to calculate.\nAction: calculator\nAction Input: {\"expression\": \"3+3\"}";

        match agent.parse_action(response) {
            AgentAction::ToolCall(call) => {
                assert_eq!(call.name, "calculator");
            },
            other => panic!("Expected ToolCall from generic format, got {:?}", other),
        }
    }
}