juncture 0.1.0

Typed state machine framework for LLM agents - Rust implementation of LangGraph
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
//! `ToolNode`: executes tools from AI message `tool_calls`

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use juncture_core::state::State;
use juncture_core::state::messages::{Message, Role, ToolCall};
use juncture_core::stream::ToolsEvent;
use juncture_tracing::spans::attrs;
use tokio::task::JoinSet;

use crate::tools::error::ToolError;
use crate::tools::interceptor::{NopToolInterceptor, ToolInterceptor};
use crate::tools::runtime::ToolRuntime;
use crate::tools::trait_::{StatefulTool, Tool, ToolDefinition};
use crate::tools::transformer::ToolCallTransformer;

/// Type alias for the tools condition function to reduce type complexity
type ToolsConditionFn = Arc<dyn Fn(&Message) -> bool + Send + Sync>;

/// Configuration for `ToolNode`
///
/// Controls tool execution behavior including error handling,
/// validation, and interception.
pub struct ToolNodeConfig<S: State> {
    /// Available tools for execution
    pub tools: Vec<ToolEntry<S>>,

    /// Whether to handle errors as tool result messages
    ///
    /// If true, errors are returned as tool result messages so the LLM can retry.
    /// If false, errors are propagated immediately.
    pub handle_errors: bool,

    /// Whether to validate tool input against schema
    pub validate_input: bool,

    /// Optional transformer for tool call arguments
    pub call_transformer: Option<Box<dyn ToolCallTransformer>>,

    /// Optional interceptor for pre/post execution hooks
    pub interceptor: Option<Arc<dyn ToolInterceptor>>,

    /// Optional condition function to determine if tools should be executed
    ///
    /// If set, this function is called with the AI message containing tool calls.
    /// Returns true to execute tools, false to skip tool execution.
    /// Used for implementing `tools_condition` routing pattern.
    pub tools_condition: Option<ToolsConditionFn>,
}

/// A wrapper that can hold either a stateless or stateful tool.
///
/// This enum enables `ToolNode` to store and dispatch to both types of tools:
/// - Stateless tools implement only `Tool` trait
/// - Stateful tools implement `StatefulTool<S>` and can access graph state
#[derive(Clone)]
pub enum ToolEntry<S: State> {
    /// A stateless tool that implements only `Tool`
    Stateless(Arc<dyn Tool>),

    /// A stateful tool that implements `StatefulTool<S>` with runtime access
    Stateful(Arc<dyn StatefulTool<S>>),
}

impl<S: State> std::fmt::Debug for ToolEntry<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Stateless(_) => f.debug_tuple("Stateless").field(&self.name()).finish(),
            Self::Stateful(_) => f.debug_tuple("Stateful").field(&self.name()).finish(),
        }
    }
}

impl<S: State> ToolEntry<S> {
    /// Get the tool name
    pub fn name(&self) -> &str {
        match self {
            Self::Stateless(tool) => tool.name(),
            Self::Stateful(tool) => tool.name(),
        }
    }

    /// Get the tool description
    pub fn description(&self) -> &str {
        match self {
            Self::Stateless(tool) => tool.description(),
            Self::Stateful(tool) => tool.description(),
        }
    }

    /// Get the tool's JSON schema
    pub fn schema(&self) -> serde_json::Value {
        match self {
            Self::Stateless(tool) => tool.schema(),
            Self::Stateful(tool) => tool.schema(),
        }
    }

    /// Get the tool definition
    pub fn definition(&self) -> ToolDefinition {
        match self {
            Self::Stateless(tool) => tool.definition(),
            Self::Stateful(tool) => tool.definition(),
        }
    }

    /// Create a stateless tool entry from a boxed Tool
    #[must_use]
    pub fn from_stateless(tool: Box<dyn Tool>) -> Self {
        Self::Stateless(Arc::from(tool))
    }

    /// Create a stateful tool entry from an Arc<StatefulTool>
    #[must_use]
    pub fn from_stateful(tool: Arc<dyn StatefulTool<S>>) -> Self {
        Self::Stateful(tool)
    }
}

impl<S: State> Default for ToolNodeConfig<S> {
    fn default() -> Self {
        Self {
            tools: Vec::new(),
            handle_errors: true,
            validate_input: true,
            call_transformer: None,
            interceptor: None,
            tools_condition: None,
        }
    }
}

impl<S: State> std::fmt::Debug for ToolNodeConfig<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolNodeConfig")
            .field("tools_count", &self.tools.len())
            .field("handle_errors", &self.handle_errors)
            .field("validate_input", &self.validate_input)
            .field("call_transformer", &self.call_transformer.is_some())
            .field("interceptor", &self.interceptor.is_some())
            .field("tools_condition", &self.tools_condition.is_some())
            .finish()
    }
}

/// Tool execution trace for observability
///
/// Records execution metadata for each tool call, useful for
/// debugging, monitoring, and audit trails.
#[derive(Clone, Debug)]
pub struct ToolExecutionTrace {
    /// Name of the tool that was executed
    pub tool_name: String,

    /// Tool call ID from the AI message
    pub tool_call_id: String,

    /// Attempt number (for retry logic)
    pub attempt: usize,

    /// Unix timestamp of first attempt
    pub first_attempt_time: f64,

    /// Execution duration in milliseconds
    pub duration_ms: u64,

    /// Whether the execution succeeded
    pub success: bool,

    /// Tool input arguments at time of execution
    pub input: serde_json::Value,

    /// Tool output on success
    pub output: Option<String>,

    /// Error message on failure
    pub error: Option<String>,
}

impl ToolExecutionTrace {
    /// Create a new tool execution trace
    #[must_use]
    pub fn new(
        tool_name: String,
        tool_call_id: String,
        attempt: usize,
        input: serde_json::Value,
    ) -> Self {
        Self {
            tool_name,
            tool_call_id,
            attempt,
            first_attempt_time: Self::now(),
            duration_ms: 0,
            success: false,
            input,
            output: None,
            error: None,
        }
    }

    /// Mark the trace as completed with duration, success status, and optional output/error
    pub fn complete(
        &mut self,
        duration_ms: u64,
        success: bool,
        output: Option<String>,
        error: Option<String>,
    ) {
        self.duration_ms = duration_ms;
        self.success = success;
        self.output = output;
        self.error = error;
    }

    /// Get current Unix timestamp
    fn now() -> f64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0.0, |d| d.as_secs_f64())
    }
}

/// `ToolNode`: executes tools from AI message `tool_calls`
///
/// This is the standard tool execution node in `ReAct` agent patterns.
/// It extracts `tool_calls` from the last AI message, looks up the corresponding
/// Tool implementations, executes them concurrently, and returns tool result messages.
///
/// # Type Parameters
///
/// * `S` - The state type (must implement [`State`])
///
/// # Execution Flow
///
/// 1. Extract `tool_calls` from the last AI message in the conversation
/// 2. For each `tool_call`:
///    - Apply `pre_execute` interceptor hook
///    - Transform the tool call arguments
///    - Execute the tool concurrently (with state access for stateful tools)
///    - Apply `post_execute` interceptor hook
/// 3. Return tool result messages
///
/// # Example
///
/// ```ignore
/// use juncture::tools::{ToolNode, Tool};
/// use juncture_core::state::messages::{Message, ToolCall};
/// use serde_json::json;
///
/// // Create tools
/// let tools = vec![Box::new(MySearchTool::new())];
///
/// // Create ToolNode
/// let tool_node = ToolNode::new(tools);
///
/// // Execute tool calls from AI message
/// let messages = vec![
///     Message::human("Search for rust programming"),
///     Message::ai_with_tool_calls("", vec![
///         ToolCall {
///             id: "call_123".to_string(),
///             name: "search".to_string(),
///             arguments: json!({"query": "rust programming"}),
///         },
///     ]),
/// ];
///
/// let results = tool_node.execute(&messages).await?;
/// // results contains tool result messages
/// ```
pub struct ToolNode<S: State> {
    /// Registered tools indexed by name
    tools: HashMap<String, ToolEntry<S>>,

    /// Whether to handle errors as tool result messages
    handle_errors: bool,

    /// Whether to validate tool input against schema
    validate_input: bool,

    /// Optional transformer for tool call arguments
    call_transformer: Option<Arc<dyn ToolCallTransformer>>,

    /// Optional interceptor for pre/post execution hooks
    interceptor: Option<Arc<dyn ToolInterceptor>>,

    /// Optional condition function to determine if tools should be executed
    ///
    /// If set, this function is called with the AI message containing tool calls.
    /// Returns true to execute tools, false to skip tool execution.
    tools_condition: Option<ToolsConditionFn>,

    /// Optional sender for tool lifecycle streaming events.
    ///
    /// When set, [`ToolStarted`](ToolsEvent::ToolStarted) and
    /// [`ToolFinished`](ToolsEvent::ToolFinished) events are emitted
    /// during tool execution.
    tools_event_tx: Option<tokio::sync::mpsc::UnboundedSender<ToolsEvent>>,
}

impl<S: State> std::fmt::Debug for ToolNode<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolNode")
            .field("tools", &self.tools.len())
            .field("handle_errors", &self.handle_errors)
            .field("validate_input", &self.validate_input)
            .field("call_transformer", &self.call_transformer.is_some())
            .field("interceptor", &self.interceptor.is_some())
            .field("tools_condition", &self.tools_condition.is_some())
            .field("tools_event_tx", &self.tools_event_tx.is_some())
            .finish()
    }
}

// Generic implementation for any State type
impl<S: State> ToolNode<S> {
    /// Create a new `ToolNode` with stateless tools (backward compatible)
    ///
    /// Uses default configuration: error handling enabled, validation enabled.
    ///
    /// This method accepts stateless tools for backward compatibility.
    /// For stateful tools, use [`ToolNode::with_stateful_tools`] instead.
    #[must_use]
    pub fn new(tools: Vec<Box<dyn Tool>>) -> Self {
        let mut tools_map = HashMap::new();
        for tool in tools {
            let tool_arc: Arc<dyn Tool> = Arc::from(tool);
            tools_map.insert(tool_arc.name().to_string(), ToolEntry::Stateless(tool_arc));
        }

        Self {
            tools: tools_map,
            handle_errors: true,
            validate_input: true,
            call_transformer: None,
            interceptor: None,
            tools_condition: None,
            tools_event_tx: None,
        }
    }

    /// Create a new `ToolNode` with stateful tools
    ///
    /// Uses default configuration: error handling enabled, validation enabled.
    ///
    /// This method accepts both stateless and stateful tools.
    #[must_use]
    pub fn with_stateful_tools(tools: Vec<ToolEntry<S>>) -> Self {
        let mut tools_map = HashMap::new();
        for tool in tools {
            tools_map.insert(tool.name().to_string(), tool);
        }

        Self {
            tools: tools_map,
            handle_errors: true,
            validate_input: true,
            call_transformer: None,
            interceptor: None,
            tools_condition: None,
            tools_event_tx: None,
        }
    }

    /// Create a `ToolNode` with custom configuration
    #[must_use]
    pub fn with_config(config: ToolNodeConfig<S>) -> Self {
        let mut tools_map = HashMap::new();
        for tool in config.tools {
            tools_map.insert(tool.name().to_string(), tool);
        }

        Self {
            tools: tools_map,
            handle_errors: config.handle_errors,
            validate_input: config.validate_input,
            call_transformer: config.call_transformer.map(Arc::from),
            interceptor: config.interceptor,
            tools_condition: config.tools_condition,
            tools_event_tx: None,
        }
    }

    /// Set error handling mode
    ///
    /// If true, errors are returned as tool result messages.
    /// If false, errors are propagated immediately.
    #[must_use]
    pub const fn with_error_handling(mut self, handle: bool) -> Self {
        self.handle_errors = handle;
        self
    }

    /// Enable or disable input validation
    #[must_use]
    pub const fn with_validation(mut self, validate: bool) -> Self {
        self.validate_input = validate;
        self
    }

    /// Set a tool call transformer
    #[must_use]
    pub fn with_transformer(mut self, transformer: Box<dyn ToolCallTransformer>) -> Self {
        self.call_transformer = Some(Arc::from(transformer));
        self
    }

    /// Set a tool execution interceptor
    #[must_use]
    pub fn with_interceptor(mut self, interceptor: Arc<dyn ToolInterceptor>) -> Self {
        self.interceptor = Some(interceptor);
        self
    }

    /// Set a tools condition function for conditional tool execution
    ///
    /// If set, this function is called with the AI message containing tool calls.
    /// When the function returns false, tool execution is skipped and an empty
    /// result is returned.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use juncture::tools::{ToolNode, Tool};
    /// use juncture_core::state::messages::Message;
    /// use std::sync::Arc;
    ///
    /// let tools = vec![Box::new(MySearchTool::new())];
    /// let tool_node = ToolNode::new(tools)
    ///     .with_tools_condition(Arc::new(|msg| {
    ///         // Only execute tools if message contains specific keyword
    ///         msg.content_text().contains("search")
    ///     }));
    /// ```
    #[must_use]
    pub fn with_tools_condition(mut self, condition: ToolsConditionFn) -> Self {
        self.tools_condition = Some(condition);
        self
    }

    /// Attach a tool event sender for streaming lifecycle events.
    ///
    /// When set, [`ToolStarted`](ToolsEvent::ToolStarted) and
    /// [`ToolFinished`](ToolsEvent::ToolFinished) events are emitted
    /// during tool execution.
    #[must_use]
    pub fn with_tools_event_tx(
        mut self,
        tx: tokio::sync::mpsc::UnboundedSender<ToolsEvent>,
    ) -> Self {
        self.tools_event_tx = Some(tx);
        self
    }

    /// Execute tools from the last AI message's `tool_calls`
    ///
    /// This is the main execution method that:
    /// 1. Finds the last AI message in the conversation
    /// 2. Extracts `tool_calls` from it
    /// 3. Executes each tool concurrently
    /// 4. Returns tool result messages
    ///
    /// # Errors
    ///
    /// Returns [`ToolError`] if:
    /// - No AI message with tool calls is found
    /// - Tool execution fails and error handling is disabled
    /// - Required tool is not found and error handling is disabled
    pub async fn execute(&self, messages: &[Message]) -> Result<Vec<Message>, ToolError> {
        self.execute_with_state(messages, None).await
    }

    /// Execute tools with state access for stateful tools
    ///
    /// This method provides the current state to stateful tools via `ToolRuntime`.
    /// For stateless tools, the state parameter is ignored.
    ///
    /// # Errors
    ///
    /// Returns [`ToolError`] if:
    /// - No AI message with tool calls is found
    /// - Tool execution fails and error handling is disabled
    /// - Required tool is not found and error handling is disabled
    #[allow(
        clippy::too_many_lines,
        reason = "execute_with_state requires: message validation, tools_condition check, tool iteration, concurrent spawning, transformer application, validation, interceptor hooks, and result collection. The complexity is necessary for comprehensive tool execution with state support and conditional execution."
    )]
    pub async fn execute_with_state(
        &self,
        messages: &[Message],
        state: Option<&S>,
    ) -> Result<Vec<Message>, ToolError> {
        // Find the last AI message with tool calls
        let last_ai = messages
            .iter()
            .rev()
            .find(|m| m.role == Role::Ai && m.has_tool_calls())
            .ok_or_else(|| {
                ToolError::validation_failed(vec![
                    "No AI message with tool calls found".to_string(),
                ])
            })?;

        if last_ai.tool_calls.is_empty() {
            return Ok(Vec::new());
        }

        // Check tools_condition if set
        if let Some(ref condition) = self.tools_condition
            && !condition(last_ai)
        {
            // Condition returned false, skip tool execution
            return Ok(Vec::new());
        }

        // Collect tool results
        // Execute all tool calls concurrently
        let mut results = JoinSet::new();
        let mut tool_messages: Vec<Message> = Vec::new();
        let interceptor = self
            .interceptor
            .as_ref()
            .map_or_else(|| Arc::new(NopToolInterceptor), Arc::clone);

        for tool_call in &last_ai.tool_calls {
            let tool = if let Some(t) = self.tools.get(&tool_call.name) {
                t.clone()
            } else {
                let error = ToolError::tool_not_found(&tool_call.name);
                if self.handle_errors {
                    // Add error as a tool result
                    tool_messages.push(Message::tool_result(
                        tool_call.id.clone(),
                        format!("Error: {error}"),
                    ));
                    continue;
                }
                return Err(error);
            };

            let mut tool_call = tool_call.clone();

            // Apply transformer if configured
            if let Some(ref transformer) = self.call_transformer
                && let Err(e) = transformer.transform(&mut tool_call)
            {
                if self.handle_errors {
                    tool_messages.push(Message::tool_result(
                        tool_call.id.clone(),
                        format!("Error: {e}"),
                    ));
                    continue;
                }
                return Err(e);
            }

            // Validate input against the tool's JSON schema if enabled
            if self.validate_input
                && let Err(e) = self.validate_tool_call(&tool_call)
            {
                if self.handle_errors {
                    tool_messages.push(Message::tool_result(
                        tool_call.id.clone(),
                        format!("Error: {e}"),
                    ));
                    continue;
                }
                return Err(e);
            }

            let interceptor = Arc::clone(&interceptor);
            let tools_event_tx = self.tools_event_tx.clone();

            // Clone state for stateful tool execution
            let state_clone = state.cloned();

            results.spawn(async move {
                Self::execute_single_tool(
                    &tool_call,
                    &tool,
                    &interceptor,
                    tools_event_tx,
                    state_clone,
                )
                .await
            });
        }

        // Collect results
        while let Some(result) = results.join_next().await {
            match result {
                Ok(Ok((tool_call_id, output))) => {
                    tool_messages.push(Message::tool_result(tool_call_id, output));
                }
                Ok(Err(e)) => {
                    if self.handle_errors {
                        // Return error as tool result for LLM to retry
                        tool_messages.push(Message::tool_result("unknown", format!("Error: {e}")));
                    } else {
                        return Err(e);
                    }
                }
                Err(join_err) => {
                    let msg = format!("Tool execution panicked: {join_err}");
                    if self.handle_errors {
                        tool_messages.push(Message::tool_result("unknown".to_string(), msg));
                    } else {
                        return Err(ToolError::execution_failed(msg));
                    }
                }
            }
        }

        Ok(tool_messages)
    }

    /// Execute a single tool call
    #[allow(
        clippy::cognitive_complexity,
        clippy::too_many_lines,
        reason = "execute_single_tool requires: span creation, interceptor hooks, tool invocation (stateless or stateful), error handling, metrics emission, result transformation, and streaming event emission. The complexity is justified by the comprehensive tool execution with observability."
    )]
    async fn execute_single_tool(
        tool_call: &ToolCall,
        tool: &ToolEntry<S>,
        interceptor: &Arc<dyn ToolInterceptor>,
        tools_event_tx: Option<tokio::sync::mpsc::UnboundedSender<ToolsEvent>>,
        state: Option<S>,
    ) -> Result<(String, String), ToolError> {
        let span = tracing::info_span!(
            "juncture.tool.call",
            "juncture.tool.name" = %tool.name(),
            "juncture.tool.duration_ms" = tracing::field::Empty,
            "juncture.tool.error" = tracing::field::Empty,
        );
        let _enter = span.enter();

        // Emit ToolStarted event before execution
        if let Some(ref tx) = tools_event_tx {
            let input = tool_call.arguments.clone();
            let event = ToolsEvent::ToolStarted {
                tool_name: tool.name().to_string(),
                tool_call_id: tool_call.id.clone(),
                node: "tools".to_string(),
                input,
                timestamp: chrono::Utc::now(),
            };
            let _ = tx.send(event);
        }

        let state_json = serde_json::Value::Null;

        // Pre-execute hook
        interceptor.pre_execute(tool_call, &state_json).await?;

        // Create execution trace capturing the tool input at time of execution
        let mut trace = ToolExecutionTrace::new(
            tool.name().to_string(),
            tool_call.id.clone(),
            1,
            tool_call.arguments.clone(),
        );

        // Execute the tool - dispatch based on tool type
        #[cfg(not(target_family = "wasm"))]
        let start = std::time::Instant::now();
        let result = match tool {
            ToolEntry::Stateless(stateless_tool) => {
                // Stateless tool execution
                stateless_tool.invoke(tool_call.arguments.clone()).await
            }
            ToolEntry::Stateful(stateful_tool) => {
                // Stateful tool execution with ToolRuntime
                if let Some(ref state_data) = state {
                    let runtime = ToolRuntime::new(
                        state_data.clone(),
                        tool_call.id.clone(),
                        juncture_core::config::RunnableConfig::default(),
                        None, // Store is not available in this context
                    );
                    stateful_tool
                        .invoke_with_runtime(tool_call.arguments.clone(), &runtime)
                        .await
                } else {
                    // Stateful tool called without state - this is an error
                    return Err(ToolError::execution_failed(format!(
                        "Stateful tool '{}' called without state context",
                        tool.name()
                    )));
                }
            }
        };
        #[cfg(not(target_family = "wasm"))]
        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
        #[cfg(target_family = "wasm")]
        let duration_ms: u64 = 0;

        // Record duration
        tracing::Span::current().record(attrs::TOOL_DURATION_MS, duration_ms);

        // Emit metrics for tool execution
        tracing::debug!(
            name: "juncture.tool.calls",
            tool_name = %tool.name(),
        );

        tracing::debug!(
            name: "juncture.tool.duration_ms",
            duration_ms = duration_ms,
            tool_name = %tool.name(),
        );

        // Report tool call and duration metrics
        let _ = juncture_core::pregel::try_report_tool_call();
        let _ = juncture_core::pregel::try_report_tool_duration(duration_ms);

        // Post-execute hook
        let output = match interceptor.post_execute(tool_call, &result).await {
            Ok(out) => {
                // Complete trace with success details
                trace.complete(duration_ms, true, Some(out.clone()), None);

                // Emit ToolFinished event with output
                if let Some(ref tx) = tools_event_tx {
                    let output_json = serde_json::json!({"result": out});
                    let event = ToolsEvent::ToolFinished {
                        tool_call_id: tool_call.id.clone(),
                        output: output_json,
                        duration_ms,
                        success: true,
                    };
                    let _ = tx.send(event);
                }

                out
            }
            Err(e) => {
                // Complete trace with failure details
                trace.complete(duration_ms, false, None, Some(e.to_string()));

                // Emit ToolFinished event with error
                if let Some(ref tx) = tools_event_tx {
                    let event = ToolsEvent::ToolFinished {
                        tool_call_id: tool_call.id.clone(),
                        output: serde_json::json!({"error": e.to_string()}),
                        duration_ms,
                        success: false,
                    };
                    let _ = tx.send(event);
                }

                // Log execution trace before returning error
                tracing::debug!(
                    name: "juncture.tool.trace",
                    tool_name = %trace.tool_name,
                    tool_call_id = %trace.tool_call_id,
                    attempt = trace.attempt,
                    duration_ms = trace.duration_ms,
                    success = trace.success,
                );

                // Record error attribute
                tracing::Span::current().record(attrs::TOOL_ERROR, e.to_string());

                // Emit error metric
                tracing::debug!(
                    name: "juncture.tool.errors",
                    tool_name = %tool.name(),
                );

                // Report tool error metric
                let _ = juncture_core::pregel::try_report_tool_error();

                return Err(e);
            }
        };

        // Log execution trace for successful execution
        tracing::debug!(
            name: "juncture.tool.trace",
            tool_name = %trace.tool_name,
            tool_call_id = %trace.tool_call_id,
            attempt = trace.attempt,
            duration_ms = trace.duration_ms,
            success = trace.success,
        );

        Ok((tool_call.id.clone(), output))
    }

    /// Get a list of registered tool names
    #[must_use]
    pub fn tool_names(&self) -> Vec<&str> {
        self.tools.keys().map(std::string::String::as_str).collect()
    }

    /// Check if a tool is registered
    #[must_use]
    pub fn has_tool(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Get the number of registered tools
    #[must_use]
    pub fn tool_count(&self) -> usize {
        self.tools.len()
    }

    /// Validate tool call arguments against the registered tool's JSON schema
    ///
    /// Checks that the tool exists and that the arguments conform to its schema.
    ///
    /// # Errors
    ///
    /// Returns [`ToolError::ValidationFailed`] if:
    /// - The tool is not registered
    /// - The arguments do not match the tool's JSON schema
    fn validate_tool_call(&self, tool_call: &ToolCall) -> Result<(), ToolError> {
        let tool = self.tools.get(&tool_call.name).ok_or_else(|| {
            ToolError::validation_failed(vec![format!(
                "Tool '{}' not found in registered tools",
                tool_call.name
            )])
        })?;
        Self::validate_arguments_against_schema(&tool_call.arguments, &tool.schema())
    }

    /// Validate JSON arguments against a JSON Schema
    ///
    /// Performs basic structural validation:
    /// - Type checking (object, array, string, number, boolean)
    /// - Required property verification for object schemas
    /// - Property type matching
    fn validate_arguments_against_schema(
        arguments: &serde_json::Value,
        schema: &serde_json::Value,
    ) -> Result<(), ToolError> {
        let Some(schema_obj) = schema.as_object() else {
            return Ok(());
        };

        if schema_obj.is_empty() {
            return Ok(());
        }

        // Check the schema-level type
        let Some(schema_type) = schema.get("type").and_then(serde_json::Value::as_str) else {
            return Ok(());
        };

        match schema_type {
            "object" => Self::validate_object_arguments(arguments, schema)?,
            "array" => {
                if !arguments.is_array() {
                    return Err(ToolError::validation_failed(vec![format!(
                        "Expected array arguments, got '{}'",
                        Self::value_type_name(arguments)
                    )]));
                }
            }
            "string" => {
                if !arguments.is_string() {
                    return Err(ToolError::validation_failed(vec![format!(
                        "Expected string arguments, got '{}'",
                        Self::value_type_name(arguments)
                    )]));
                }
            }
            "number" | "integer" => {
                if !arguments.is_number() {
                    return Err(ToolError::validation_failed(vec![format!(
                        "Expected number arguments, got '{}'",
                        Self::value_type_name(arguments)
                    )]));
                }
            }
            "boolean" => {
                if !arguments.is_boolean() {
                    return Err(ToolError::validation_failed(vec![format!(
                        "Expected boolean arguments, got '{}'",
                        Self::value_type_name(arguments)
                    )]));
                }
            }
            _ => {} // Unknown type, skip validation
        }

        Ok(())
    }

    /// Validate object-type arguments against an object schema
    fn validate_object_arguments(
        arguments: &serde_json::Value,
        schema: &serde_json::Value,
    ) -> Result<(), ToolError> {
        if !arguments.is_object() {
            return Err(ToolError::validation_failed(vec![format!(
                "Expected object arguments, got '{}'",
                Self::value_type_name(arguments)
            )]));
        }

        // Check required fields exist
        if let Some(required) = schema.get("required").and_then(|r| r.as_array()) {
            let obj = arguments.as_object().expect("already checked is_object");
            for field in required {
                let field_name = field.as_str().ok_or_else(|| {
                    ToolError::validation_failed(vec![
                        "Invalid schema: required field name is not a string".to_string(),
                    ])
                })?;
                if !obj.contains_key(field_name) {
                    return Err(ToolError::validation_failed(vec![format!(
                        "Missing required field: '{field_name}'"
                    )]));
                }
            }
        }

        // Validate property types if schema defines them
        if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
            let obj = arguments.as_object().expect("already checked is_object");
            for (prop_name, prop_schema) in properties {
                if let Some(arg_val) = obj.get(prop_name) {
                    Self::validate_property_type(arg_val, prop_schema, prop_name)?;
                }
            }
        }

        Ok(())
    }

    /// Validate a single property value against its JSON Schema type definition
    fn validate_property_type(
        value: &serde_json::Value,
        prop_schema: &serde_json::Value,
        prop_name: &str,
    ) -> Result<(), ToolError> {
        let Some(expected_type) = prop_schema.get("type").and_then(serde_json::Value::as_str)
        else {
            return Ok(());
        };

        let matches = match expected_type {
            "object" => value.is_object(),
            "array" => value.is_array(),
            "string" => value.is_string(),
            "number" => value.is_number(),
            "integer" => value.is_i64() || value.is_u64(),
            "boolean" => value.is_boolean(),
            "null" => value.is_null(),
            _ => true, // Unknown schema type, accept
        };

        if !matches {
            return Err(ToolError::validation_failed(vec![format!(
                "Field '{prop_name}' expected type '{expected_type}', got '{}'",
                Self::value_type_name(value)
            )]));
        }

        Ok(())
    }

    /// Get a human-readable name for a JSON value type
    const fn value_type_name(value: &serde_json::Value) -> &'static str {
        match value {
            serde_json::Value::Null => "null",
            serde_json::Value::Bool(_) => "boolean",
            serde_json::Value::Number(_) => "number",
            serde_json::Value::String(_) => "string",
            serde_json::Value::Array(_) => "array",
            serde_json::Value::Object(_) => "object",
        }
    }
}

impl ToolError {
    /// Get the tool call ID associated with this error
    #[must_use]
    pub const fn tool_call_id(&self) -> Option<&str> {
        None
    }
}

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

    // Type alias for tests using a simple state type
    type TestToolNode = ToolNode<juncture_core::state::messages::MessagesState>;

    /// Simple test tool that echoes its input
    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &'static str {
            "echo"
        }

        fn description(&self) -> &'static str {
            "Echoes the input"
        }

        fn schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "message": {"type": "string"}
                },
                "required": ["message"]
            })
        }

        async fn invoke(&self, input: serde_json::Value) -> Result<String, ToolError> {
            input["message"]
                .as_str()
                .map(std::string::ToString::to_string)
                .ok_or_else(|| ToolError::invalid_input("Missing 'message' field".to_string()))
        }
    }

    /// Test tool that always fails
    struct FailTool;

    #[async_trait]
    impl Tool for FailTool {
        fn name(&self) -> &'static str {
            "fail"
        }

        fn description(&self) -> &'static str {
            "Always fails"
        }

        fn schema(&self) -> serde_json::Value {
            json!({"type": "object"})
        }

        async fn invoke(&self, _input: serde_json::Value) -> Result<String, ToolError> {
            Err(ToolError::execution_failed(
                "Intentional failure".to_string(),
            ))
        }
    }

    #[tokio::test]
    async fn test_tool_node_new() {
        let tools = vec![Box::new(EchoTool) as Box<dyn Tool>];
        let node = TestToolNode::new(tools);

        assert_eq!(node.tool_count(), 1);
        assert!(node.has_tool("echo"));
        assert!(!node.has_tool("nonexistent"));
    }

    #[tokio::test]
    async fn test_tool_node_with_config() {
        let config = ToolNodeConfig::<juncture_core::state::messages::MessagesState> {
            tools: vec![ToolEntry::from_stateless(Box::new(EchoTool))],
            handle_errors: false,
            validate_input: false,
            call_transformer: None,
            interceptor: None,
            tools_condition: None,
        };
        let node = TestToolNode::with_config(config);

        assert_eq!(node.tool_count(), 1);
        assert!(node.has_tool("echo"));
    }

    #[tokio::test]
    async fn test_tool_node_execute_single() {
        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "Echo this",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].tool_call_id, Some("call_1".to_string()));
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert_eq!(text, "hello");
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_execute_multiple() {
        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "Echo these",
            vec![
                ToolCall {
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "first"}),
                },
                ToolCall {
                    id: "call_2".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "second"}),
                },
            ],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 2);

        // Results should be in order
        assert_eq!(results[0].tool_call_id, Some("call_1".to_string()));
        assert_eq!(results[1].tool_call_id, Some("call_2".to_string()));
    }

    #[tokio::test]
    async fn test_tool_node_no_tool_calls() {
        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai("No tools here")];

        let results = node.execute(&messages).await;
        assert!(results.is_err());
        assert!(matches!(
            results.unwrap_err(),
            ToolError::ValidationFailed(_)
        ));
    }

    #[tokio::test]
    async fn test_tool_node_tool_not_found_with_error_handling() {
        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "Call nonexistent",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "nonexistent".to_string(),
                arguments: json!({}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        // Should return error as tool result
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("tool not found") && text.contains("nonexistent"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with error message")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_tool_not_found_without_error_handling() {
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_error_handling(false);
        let messages = vec![Message::ai_with_tool_calls(
            "Call nonexistent",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "nonexistent".to_string(),
                arguments: json!({}),
            }],
        )];

        let results = node.execute(&messages).await;
        assert!(results.is_err());
        assert!(matches!(results.unwrap_err(), ToolError::ToolNotFound(_)));
    }

    #[tokio::test]
    async fn test_tool_node_tool_failure_with_error_handling() {
        let node = TestToolNode::new(vec![Box::new(FailTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "Fail",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "fail".to_string(),
                arguments: json!({}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        // Should return error as tool result
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("Error:"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with error message")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_tool_failure_without_error_handling() {
        let node =
            TestToolNode::new(vec![Box::new(FailTool) as Box<dyn Tool>]).with_error_handling(false);
        let messages = vec![Message::ai_with_tool_calls(
            "Fail",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "fail".to_string(),
                arguments: json!({}),
            }],
        )];

        let results = node.execute(&messages).await;
        assert!(results.is_err());
        assert!(matches!(
            results.unwrap_err(),
            ToolError::ExecutionFailed(_)
        ));
    }

    #[tokio::test]
    async fn test_tool_node_with_error_handling() {
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_error_handling(false);
        assert!(!node.handle_errors);
    }

    #[tokio::test]
    async fn test_tool_node_with_validation() {
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_validation(false);
        assert!(!node.validate_input);
    }

    #[tokio::test]
    async fn test_tool_execution_trace() {
        let mut trace = ToolExecutionTrace::new(
            "test_tool".to_string(),
            "call_123".to_string(),
            1,
            json!({"key": "value"}),
        );
        assert_eq!(trace.tool_name, "test_tool");
        assert_eq!(trace.tool_call_id, "call_123");
        assert_eq!(trace.attempt, 1);
        assert!(!trace.success);
        assert_eq!(trace.duration_ms, 0);
        assert_eq!(trace.input["key"], "value");
        assert!(trace.output.is_none());
        assert!(trace.error.is_none());

        trace.complete(100, true, Some("ok".to_string()), None);
        assert_eq!(trace.duration_ms, 100);
        assert!(trace.success);
        assert_eq!(trace.output, Some("ok".to_string()));
        assert!(trace.error.is_none());
    }

    #[test]
    fn test_tool_execution_trace_now() {
        let trace1 = ToolExecutionTrace::new("t".to_string(), "c".to_string(), 1, json!(null));
        let trace2 = ToolExecutionTrace::new("t".to_string(), "c".to_string(), 1, json!(null));
        // Both should have timestamps close to each other
        assert!(trace2.first_attempt_time >= trace1.first_attempt_time);
    }

    // --- StatefulTool integration tests ---

    /// Test stateful tool that accesses runtime state
    struct StatefulTestTool;

    #[async_trait]
    impl StatefulTool<juncture_core::state::messages::MessagesState> for StatefulTestTool {
        async fn invoke_with_runtime(
            &self,
            _input: serde_json::Value,
            runtime: &ToolRuntime<juncture_core::state::messages::MessagesState>,
        ) -> Result<String, ToolError> {
            let message_count = runtime.state.messages.len();
            Ok(format!("Processed with {message_count} messages in state"))
        }

        fn name(&self) -> &'static str {
            "stateful_test_tool"
        }

        fn description(&self) -> &'static str {
            "A test stateful tool"
        }

        fn schema(&self) -> serde_json::Value {
            json!({"type": "object"})
        }
    }

    #[tokio::test]
    async fn test_stateful_tool_execution() {
        use juncture_core::state::messages::MessagesState;

        // Create a tool node with a stateful tool
        let stateful_entry = ToolEntry::from_stateful(Arc::new(StatefulTestTool));
        let node = ToolNode::<MessagesState>::with_stateful_tools(vec![stateful_entry]);

        // Create test state with messages
        let state = MessagesState {
            messages: vec![Message::human("Hello"), Message::ai("Hi there")],
        };

        // Create tool calls
        let messages = vec![Message::ai_with_tool_calls(
            "Execute stateful tool",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "stateful_test_tool".to_string(),
                arguments: json!({}),
            }],
        )];

        // Execute tools with state
        let results = node
            .execute_with_state(&messages, Some(&state))
            .await
            .unwrap();
        assert_eq!(results.len(), 1);

        // Verify the stateful tool accessed the state correctly
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("2 messages in state"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content")
            }
        }
    }

    #[tokio::test]
    async fn test_mixed_stateless_and_stateful_tools() {
        use juncture_core::state::messages::MessagesState;

        // Create a tool node with both stateless and stateful tools
        let stateless_entry = ToolEntry::from_stateless(Box::new(EchoTool));
        let stateful_entry = ToolEntry::from_stateful(Arc::new(StatefulTestTool));
        let node =
            ToolNode::<MessagesState>::with_stateful_tools(vec![stateless_entry, stateful_entry]);

        // Create test state
        let state = MessagesState {
            messages: vec![Message::human("Test")],
        };

        // Create tool calls for both tools
        let messages = vec![Message::ai_with_tool_calls(
            "Execute both tools",
            vec![
                ToolCall {
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "test message"}),
                },
                ToolCall {
                    id: "call_2".to_string(),
                    name: "stateful_test_tool".to_string(),
                    arguments: json!({}),
                },
            ],
        )];

        // Execute tools with state
        let results = node
            .execute_with_state(&messages, Some(&state))
            .await
            .unwrap();
        assert_eq!(results.len(), 2);

        // Verify both tools executed
        let echo_result = &results[0];
        let stateful_result = &results[1];

        match &echo_result.content {
            juncture_core::state::messages::Content::Text(text) => {
                assert_eq!(text, "test message");
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content")
            }
        }

        match &stateful_result.content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("1 messages in state"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content")
            }
        }
    }

    /// Test tool that returns its input as a JSON string for verification
    struct JsonDumpTool;

    #[async_trait]
    impl Tool for JsonDumpTool {
        fn name(&self) -> &'static str {
            "json_dump"
        }

        fn description(&self) -> &'static str {
            "Returns the input as a JSON string"
        }

        fn schema(&self) -> serde_json::Value {
            json!({"type": "object"})
        }

        async fn invoke(&self, input: serde_json::Value) -> Result<String, ToolError> {
            Ok(input.to_string())
        }
    }

    /// Transformer that injects a default limit parameter into tool calls
    struct AddDefaultLimit;

    impl ToolCallTransformer for AddDefaultLimit {
        fn transform(&self, tool_call: &mut ToolCall) -> Result<(), ToolError> {
            if let Some(obj) = tool_call.arguments.as_object_mut() {
                obj.entry("limit").or_insert(json!(10));
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_tool_node_with_transformer() {
        let node = TestToolNode::new(vec![Box::new(JsonDumpTool) as Box<dyn Tool>])
            .with_transformer(Box::new(AddDefaultLimit));

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "json_dump".to_string(),
                arguments: json!({"query": "test"}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);

        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                let output: serde_json::Value =
                    serde_json::from_str(text).expect("output should be valid JSON");
                assert_eq!(output["limit"], 10);
                assert_eq!(output["query"], "test");
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with transformed arguments")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_with_transformer_error_handling() {
        struct BlockingTransformer;

        impl ToolCallTransformer for BlockingTransformer {
            fn transform(&self, tool_call: &mut ToolCall) -> Result<(), ToolError> {
                Err(ToolError::intercepted(format!(
                    "Transformer blocked '{}'",
                    tool_call.name
                )))
            }
        }

        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>])
            .with_transformer(Box::new(BlockingTransformer));

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("Error:"));
                assert!(text.contains("Transformer blocked"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with error message")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_with_transformer_no_error_handling() {
        struct FatalBlockingTransformer;

        impl ToolCallTransformer for FatalBlockingTransformer {
            fn transform(&self, _tool_call: &mut ToolCall) -> Result<(), ToolError> {
                Err(ToolError::Intercepted("fatal block".to_string()))
            }
        }

        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>])
            .with_transformer(Box::new(FatalBlockingTransformer))
            .with_error_handling(false);

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let result = node.execute(&messages).await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ToolError::Intercepted(_)));
    }

    #[tokio::test]
    async fn test_tool_execution_trace_with_fields() {
        let mut trace = ToolExecutionTrace::new(
            "tracker".to_string(),
            "call_42".to_string(),
            1,
            json!({"cmd": "deploy"}),
        );
        assert_eq!(trace.input["cmd"], "deploy");

        // Simulate a successful execution
        trace.complete(250, true, Some("deployed".to_string()), None);
        assert_eq!(trace.duration_ms, 250);
        assert!(trace.success);
        assert_eq!(trace.output, Some("deployed".to_string()));
        assert!(trace.error.is_none());

        // Simulate a failed execution
        let mut err_trace = ToolExecutionTrace::new(
            "tracker".to_string(),
            "call_99".to_string(),
            2,
            json!({"cmd": "fail"}),
        );
        err_trace.complete(50, false, None, Some("timeout".to_string()));
        assert!(!err_trace.success);
        assert!(err_trace.output.is_none());
        assert_eq!(err_trace.error, Some("timeout".to_string()));
    }

    // --- Validation tests ---

    /// Test tool with a defined JSON schema for validation testing
    struct SchemaTool;

    #[async_trait]
    impl Tool for SchemaTool {
        fn name(&self) -> &'static str {
            "schema_tool"
        }

        fn description(&self) -> &'static str {
            "Tool with defined schema for validation"
        }

        fn schema(&self) -> serde_json::Value {
            json!({
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "count": {"type": "integer"},
                    "active": {"type": "boolean"}
                },
                "required": ["name", "count"]
            })
        }

        async fn invoke(&self, input: serde_json::Value) -> Result<String, ToolError> {
            Ok(format!("Processed: {input}"))
        }
    }

    #[tokio::test]
    async fn test_validation_valid_input_passes() {
        let node = TestToolNode::new(vec![Box::new(SchemaTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "schema_tool".to_string(),
                arguments: json!({"name": "test", "count": 42, "active": true}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("Processed"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content");
            }
        }
    }

    #[tokio::test]
    async fn test_validation_missing_required_field_rejected() {
        let node = TestToolNode::new(vec![Box::new(SchemaTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "schema_tool".to_string(),
                arguments: json!({"name": "test"}), // missing required "count" field
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("Missing required field"));
                assert!(text.contains("count"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with error message");
            }
        }
    }

    #[tokio::test]
    async fn test_validation_wrong_type_rejected() {
        let node = TestToolNode::new(vec![Box::new(SchemaTool) as Box<dyn Tool>]);
        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "schema_tool".to_string(),
                arguments: json!({"name": "test", "count": "not_a_number"}), // count should be integer
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("expected type"));
                assert!(text.contains("count"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content with error message");
            }
        }
    }

    #[tokio::test]
    async fn test_validation_disabled_skips_checks() {
        let node =
            TestToolNode::new(vec![Box::new(SchemaTool) as Box<dyn Tool>]).with_validation(false);
        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "schema_tool".to_string(),
                arguments: json!({"name": "test"}), // missing required "count" but validation is off
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        // Tool processes the input even though it's missing required fields (validation bypassed)
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert!(text.contains("Processed"));
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content");
            }
        }
    }

    #[tokio::test]
    async fn test_validation_propagates_error_when_not_handled() {
        let node = TestToolNode::new(vec![Box::new(SchemaTool) as Box<dyn Tool>])
            .with_error_handling(false);
        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "schema_tool".to_string(),
                arguments: json!({"name": "test"}), // missing required "count"
            }],
        )];

        let result = node.execute(&messages).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::ValidationFailed(_)
        ));
    }

    // --- Tool lifecycle streaming event tests ---

    #[tokio::test]
    async fn test_tool_node_emits_started_and_finished_events() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        #[allow(clippy::redundant_clone, reason = "clarity in test setup")]
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_tools_event_tx(tx);

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let _results = node.execute(&messages).await.unwrap();

        // Collect the events
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }

        // Should have ToolStarted and ToolFinished
        assert!(
            events.iter().any(|e| matches!(
                e,
                juncture_core::stream::ToolsEvent::ToolStarted {
                    tool_call_id,
                    ..
                } if tool_call_id == "call_1"
            )),
            "expected ToolStarted event"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                juncture_core::stream::ToolsEvent::ToolFinished {
                    tool_call_id,
                    ..
                } if tool_call_id == "call_1"
            )),
            "expected ToolFinished event"
        );
    }

    #[tokio::test]
    async fn test_tool_node_emits_events_in_order() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        #[allow(clippy::redundant_clone, reason = "clarity in test setup")]
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_tools_event_tx(tx);

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let _results = node.execute(&messages).await.unwrap();

        // Collect the events in order
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }

        // First event should be ToolStarted, last should be ToolFinished
        if !events.is_empty() {
            assert!(
                matches!(
                    events[0],
                    juncture_core::stream::ToolsEvent::ToolStarted { .. }
                ),
                "first event should be ToolStarted"
            );
            assert!(
                matches!(
                    events[events.len() - 1],
                    juncture_core::stream::ToolsEvent::ToolFinished { .. }
                ),
                "last event should be ToolFinished"
            );
        }
    }

    #[tokio::test]
    async fn test_tool_node_multiple_tools_emit_multiple_events() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        #[allow(clippy::redundant_clone, reason = "clarity in test setup")]
        let node =
            TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>]).with_tools_event_tx(tx);

        let messages = vec![Message::ai_with_tool_calls(
            "test",
            vec![
                ToolCall {
                    id: "call_1".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "first"}),
                },
                ToolCall {
                    id: "call_2".to_string(),
                    name: "echo".to_string(),
                    arguments: json!({"message": "second"}),
                },
            ],
        )];

        let _results = node.execute(&messages).await.unwrap();

        // Count events
        let mut started_count = 0;
        let mut finished_count = 0;
        while let Ok(event) = rx.try_recv() {
            match event {
                juncture_core::stream::ToolsEvent::ToolStarted { .. } => started_count += 1,
                juncture_core::stream::ToolsEvent::ToolFinished { .. } => finished_count += 1,
                _ => {}
            }
        }

        assert_eq!(started_count, 2, "should have 2 ToolStarted events");
        assert_eq!(finished_count, 2, "should have 2 ToolFinished events");
    }

    // --- tools_condition tests ---

    #[tokio::test]
    async fn test_tool_node_with_tools_condition_allows_execution() {
        use std::sync::Arc;

        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>])
            .with_tools_condition(Arc::new(|msg| {
                // Allow execution if message contains "execute"
                msg.content_text().contains("execute")
            }));

        let messages = vec![Message::ai_with_tool_calls(
            "execute this tool",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 1);
        // Tool should have executed
        match &results[0].content {
            juncture_core::state::messages::Content::Text(text) => {
                assert_eq!(text, "hello");
            }
            juncture_core::state::messages::Content::MultiPart(_) => {
                panic!("Expected Text content")
            }
        }
    }

    #[tokio::test]
    async fn test_tool_node_with_tools_condition_blocks_execution() {
        use std::sync::Arc;

        let node = TestToolNode::new(vec![Box::new(EchoTool) as Box<dyn Tool>])
            .with_tools_condition(Arc::new(|msg| {
                // Block execution if message contains "block"
                !msg.content_text().contains("block")
            }));

        let messages = vec![Message::ai_with_tool_calls(
            "block this tool",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "hello"}),
            }],
        )];

        let results = node.execute(&messages).await.unwrap();
        assert_eq!(results.len(), 0);
        // Tool should not have executed
    }

    #[tokio::test]
    async fn test_tool_node_tools_condition_with_config() {
        use std::sync::Arc;

        let config = ToolNodeConfig::<juncture_core::state::messages::MessagesState> {
            tools: vec![ToolEntry::from_stateless(Box::new(EchoTool))],
            handle_errors: true,
            validate_input: true,
            call_transformer: None,
            interceptor: None,
            tools_condition: Some(Arc::new(|msg| msg.content_text().contains("allow"))),
        };
        let node = TestToolNode::with_config(config);

        // Test with allowed message
        let messages_allowed = vec![Message::ai_with_tool_calls(
            "allow execution",
            vec![ToolCall {
                id: "call_1".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "test"}),
            }],
        )];

        let results = node.execute(&messages_allowed).await.unwrap();
        assert_eq!(results.len(), 1);

        // Test with blocked message
        let messages_blocked = vec![Message::ai_with_tool_calls(
            "deny execution",
            vec![ToolCall {
                id: "call_2".to_string(),
                name: "echo".to_string(),
                arguments: json!({"message": "test"}),
            }],
        )];

        let results = node.execute(&messages_blocked).await.unwrap();
        assert_eq!(results.len(), 0);
    }
}

// Rust guideline compliant 2026-05-22