repl-core 1.13.0

Core REPL engine for the Symbi platform
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
//! DSL Evaluator for the Symbiont REPL
//!
//! Executes parsed DSL programs with runtime integration and policy enforcement.

use crate::dsl::ast::*;
use crate::error::{ReplError, Result};
use crate::execution_monitor::{ExecutionMonitor, TraceEventType};
use crate::runtime_bridge::RuntimeBridge;
use crate::session::SessionSnapshot;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use symbi_runtime::integrations::policy_engine::engine::PolicyDecision;
use symbi_runtime::types::security::Capability;
use tokio::sync::RwLock;
use uuid::Uuid;

type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
type BuiltinFunction = fn(&[DslValue]) -> Result<DslValue>;
type AsyncBuiltinFn =
    Arc<dyn Fn(Vec<DslValue>) -> BoxFuture<'static, Result<DslValue>> + Send + Sync>;

/// Execution context for DSL evaluation
#[derive(Debug, Clone)]
pub struct ExecutionContext {
    /// Variables in scope
    pub variables: HashMap<String, DslValue>,
    /// Function definitions
    pub functions: HashMap<String, FunctionDefinition>,
    /// Current agent instance
    pub agent_id: Option<Uuid>,
    /// Execution depth (for recursion protection)
    pub depth: usize,
    /// Maximum execution depth
    pub max_depth: usize,
}

impl Default for ExecutionContext {
    fn default() -> Self {
        Self {
            variables: HashMap::new(),
            functions: HashMap::new(),
            agent_id: None,
            depth: 0,
            max_depth: 100,
        }
    }
}

/// Runtime value in the DSL
#[derive(Debug, Clone, PartialEq)]
pub enum DslValue {
    String(String),
    Number(f64),
    Integer(i64),
    Boolean(bool),
    Duration { value: u64, unit: DurationUnit },
    Size { value: u64, unit: SizeUnit },
    List(Vec<DslValue>),
    Map(HashMap<String, DslValue>),
    Null,
    Agent(Box<AgentInstance>),
    Function(String),       // Function name reference
    Lambda(LambdaFunction), // Lambda function
}

/// Lambda function value
#[derive(Debug, Clone, PartialEq)]
pub struct LambdaFunction {
    pub parameters: Vec<String>,
    pub body: Expression,
    pub captured_context: HashMap<String, DslValue>,
}

impl DslValue {
    /// Convert to JSON value for serialization
    pub fn to_json(&self) -> JsonValue {
        match self {
            DslValue::String(s) => JsonValue::String(s.clone()),
            DslValue::Number(n) => JsonValue::Number(
                serde_json::Number::from_f64(*n).unwrap_or_else(|| serde_json::Number::from(0)),
            ),
            DslValue::Integer(i) => JsonValue::Number(serde_json::Number::from(*i)),
            DslValue::Boolean(b) => JsonValue::Bool(*b),
            DslValue::Duration { value, unit } => {
                let unit_str = match unit {
                    DurationUnit::Milliseconds => "ms",
                    DurationUnit::Seconds => "s",
                    DurationUnit::Minutes => "m",
                    DurationUnit::Hours => "h",
                    DurationUnit::Days => "d",
                };
                JsonValue::String(format!("{}{}", value, unit_str))
            }
            DslValue::Size { value, unit } => {
                let unit_str = match unit {
                    SizeUnit::Bytes => "B",
                    SizeUnit::KB => "KB",
                    SizeUnit::MB => "MB",
                    SizeUnit::GB => "GB",
                    SizeUnit::TB => "TB",
                };
                JsonValue::String(format!("{}{}", value, unit_str))
            }
            DslValue::List(items) => JsonValue::Array(items.iter().map(|v| v.to_json()).collect()),
            DslValue::Map(entries) => {
                let mut map = serde_json::Map::new();
                for (k, v) in entries {
                    map.insert(k.clone(), v.to_json());
                }
                JsonValue::Object(map)
            }
            DslValue::Null => JsonValue::Null,
            DslValue::Agent(agent) => JsonValue::String(format!("Agent({})", agent.id)),
            DslValue::Function(name) => JsonValue::String(format!("Function({})", name)),
            DslValue::Lambda(lambda) => {
                JsonValue::String(format!("Lambda({} params)", lambda.parameters.len()))
            }
        }
    }

    /// Get the type name for error messages
    pub fn type_name(&self) -> &'static str {
        match self {
            DslValue::String(_) => "string",
            DslValue::Number(_) => "number",
            DslValue::Integer(_) => "integer",
            DslValue::Boolean(_) => "boolean",
            DslValue::Duration { .. } => "duration",
            DslValue::Size { .. } => "size",
            DslValue::List(_) => "list",
            DslValue::Map(_) => "map",
            DslValue::Null => "null",
            DslValue::Agent(_) => "agent",
            DslValue::Function(_) => "function",
            DslValue::Lambda(_) => "lambda",
        }
    }

    /// Check if value is truthy
    pub fn is_truthy(&self) -> bool {
        match self {
            DslValue::Boolean(b) => *b,
            DslValue::Null => false,
            DslValue::String(s) => !s.is_empty(),
            DslValue::Number(n) => *n != 0.0,
            DslValue::Integer(i) => *i != 0,
            DslValue::List(items) => !items.is_empty(),
            DslValue::Map(entries) => !entries.is_empty(),
            DslValue::Lambda(_) => true,
            _ => true,
        }
    }
}

/// Agent instance in the DSL runtime
#[derive(Debug, Clone, PartialEq)]
pub struct AgentInstance {
    pub id: Uuid,
    pub definition: AgentDefinition,
    pub state: AgentState,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Agent execution state
#[derive(Debug, Clone, PartialEq)]
pub enum AgentState {
    Created,
    Starting,
    Running,
    Paused,
    Stopping,
    Stopped,
    Failed(String),
}

/// Execution result from DSL evaluation
#[derive(Debug, Clone)]
pub enum ExecutionResult {
    Value(DslValue),
    Return(DslValue),
    Continue,
    Break,
    Error(String),
}

/// DSL Evaluator with runtime integration
pub struct DslEvaluator {
    /// Runtime bridge for Symbiont integration
    runtime_bridge: Arc<RuntimeBridge>,
    /// Active agent instances
    agents: Arc<RwLock<HashMap<Uuid, AgentInstance>>>,
    /// Global execution context
    global_context: Arc<Mutex<ExecutionContext>>,
    /// Built-in functions (sync)
    builtins: HashMap<String, BuiltinFunction>,
    /// Async built-in functions (reasoning, patterns)
    async_builtins: HashMap<String, AsyncBuiltinFn>,
    /// Execution monitor for debugging and tracing
    monitor: Arc<ExecutionMonitor>,
}

impl DslEvaluator {
    /// Create a new DSL evaluator
    pub fn new(runtime_bridge: Arc<RuntimeBridge>) -> Self {
        let mut builtins: HashMap<String, BuiltinFunction> = HashMap::new();

        // Register built-in functions (sync)
        builtins.insert("print".to_string(), builtin_print as BuiltinFunction);
        builtins.insert("len".to_string(), builtin_len as BuiltinFunction);
        builtins.insert("upper".to_string(), builtin_upper as BuiltinFunction);
        builtins.insert("lower".to_string(), builtin_lower as BuiltinFunction);
        builtins.insert("format".to_string(), builtin_format as BuiltinFunction);
        builtins.insert(
            "parse_json".to_string(),
            crate::dsl::reasoning_builtins::builtin_parse_json as BuiltinFunction,
        );

        // Register async built-in functions (reasoning + patterns)
        let async_builtins = Self::register_async_builtins(&runtime_bridge);

        Self {
            runtime_bridge,
            agents: Arc::new(RwLock::new(HashMap::new())),
            global_context: Arc::new(Mutex::new(ExecutionContext::default())),
            builtins,
            async_builtins,
            monitor: Arc::new(ExecutionMonitor::new()),
        }
    }

    /// Register async builtins that need access to the reasoning infrastructure.
    fn register_async_builtins(bridge: &Arc<RuntimeBridge>) -> HashMap<String, AsyncBuiltinFn> {
        use crate::dsl::agent_composition;
        use crate::dsl::pattern_builtins;
        use crate::dsl::reasoning_builtins;

        let mut async_builtins: HashMap<String, AsyncBuiltinFn> = HashMap::new();
        let ctx = bridge.reasoning_context();

        // Reasoning builtins
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "reason".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { reasoning_builtins::builtin_reason(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "llm_call".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { reasoning_builtins::builtin_llm_call(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "delegate".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { reasoning_builtins::builtin_delegate(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "tool_call".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(
                        async move { reasoning_builtins::builtin_tool_call(&args, &ctx).await },
                    )
                }),
            );
        }

        // Pattern builtins
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "chain".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { pattern_builtins::builtin_chain(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "debate".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { pattern_builtins::builtin_debate(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "map_reduce".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { pattern_builtins::builtin_map_reduce(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "director".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { pattern_builtins::builtin_director(&args, &ctx).await })
                }),
            );
        }

        // Agent composition builtins
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "spawn_agent".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(
                        async move { agent_composition::builtin_spawn_agent(&args, &ctx).await },
                    )
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "ask".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { agent_composition::builtin_ask(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "send_to".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { agent_composition::builtin_send_to(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "parallel".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { agent_composition::builtin_parallel(&args, &ctx).await })
                }),
            );
        }
        {
            let ctx = ctx.clone();
            async_builtins.insert(
                "race".to_string(),
                Arc::new(move |args| {
                    let ctx = ctx.clone();
                    Box::pin(async move { agent_composition::builtin_race(&args, &ctx).await })
                }),
            );
        }

        async_builtins
    }

    /// Get the execution monitor
    pub fn monitor(&self) -> Arc<ExecutionMonitor> {
        Arc::clone(&self.monitor)
    }

    /// Return the names of all registered synchronous built-in functions.
    pub fn builtin_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
        names.sort();
        names
    }

    /// Return the names of all registered asynchronous built-in functions.
    pub fn async_builtin_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.async_builtins.keys().cloned().collect();
        names.sort();
        names
    }

    /// Return the names of user-defined agents known to this evaluator.
    pub fn user_defined_names(&self) -> Vec<String> {
        // Agents are stored behind an async RwLock; we return an empty vec when
        // the lock cannot be acquired without blocking.
        if let Ok(guard) = self.agents.try_read() {
            let mut names: Vec<String> =
                guard.values().map(|a| a.definition.name.clone()).collect();
            names.sort();
            names
        } else {
            vec![]
        }
    }

    /// Execute a DSL program
    pub async fn execute_program(&self, program: Program) -> Result<DslValue> {
        let mut context = ExecutionContext::default();

        // First pass: collect function definitions
        for declaration in &program.declarations {
            if let Declaration::Function(func) = declaration {
                context.functions.insert(func.name.clone(), func.clone());
            }
        }

        // Second pass: execute declarations
        let mut last_value = DslValue::Null;
        for declaration in &program.declarations {
            match self.execute_declaration(declaration, &mut context).await? {
                ExecutionResult::Value(value) => last_value = value,
                ExecutionResult::Return(value) => return Ok(value),
                ExecutionResult::Error(msg) => return Err(ReplError::Execution(msg)),
                _ => {}
            }
        }

        Ok(last_value)
    }

    /// Execute a declaration
    async fn execute_declaration(
        &self,
        declaration: &Declaration,
        context: &mut ExecutionContext,
    ) -> Result<ExecutionResult> {
        match declaration {
            Declaration::Agent(agent_def) => self.create_agent(agent_def.clone(), context).await,
            Declaration::Behavior(behavior_def) => {
                // Register behavior as a function
                let func_def = FunctionDefinition {
                    name: behavior_def.name.clone(),
                    parameters: behavior_def.input.clone().unwrap_or_default(),
                    return_type: behavior_def.output.as_ref().map(|_| Type::Any),
                    body: behavior_def.steps.clone(),
                    span: behavior_def.span.clone(),
                };
                context
                    .functions
                    .insert(behavior_def.name.clone(), func_def);
                Ok(ExecutionResult::Value(DslValue::Function(
                    behavior_def.name.clone(),
                )))
            }
            Declaration::Function(func_def) => {
                context
                    .functions
                    .insert(func_def.name.clone(), func_def.clone());
                Ok(ExecutionResult::Value(DslValue::Function(
                    func_def.name.clone(),
                )))
            }
            Declaration::EventHandler(handler) => {
                // Register event handler with runtime bridge
                let agent_id = context.agent_id.unwrap_or_else(Uuid::new_v4);

                match self
                    .runtime_bridge
                    .register_event_handler(
                        &agent_id.to_string(),
                        &handler.event_name,
                        &handler.event_name,
                    )
                    .await
                {
                    Ok(_) => {
                        tracing::info!(
                            "Registered event handler '{}' for agent {}",
                            handler.event_name,
                            agent_id
                        );
                        Ok(ExecutionResult::Value(DslValue::Function(
                            handler.event_name.clone(),
                        )))
                    }
                    Err(e) => {
                        tracing::error!("Failed to register event handler: {}", e);
                        Err(ReplError::Runtime(format!(
                            "Failed to register event handler: {}",
                            e
                        )))
                    }
                }
            }
            Declaration::Struct(struct_def) => {
                // Register struct type in the context for later use
                let struct_info = format!("{}:{}", struct_def.name, struct_def.fields.len());
                context.variables.insert(
                    format!("type_{}", struct_def.name),
                    DslValue::String(struct_info.clone()),
                );

                tracing::info!(
                    "Registered struct type '{}' with {} fields",
                    struct_def.name,
                    struct_def.fields.len()
                );
                Ok(ExecutionResult::Value(DslValue::String(format!(
                    "Struct({})",
                    struct_def.name
                ))))
            }
        }
    }

    /// Create an agent instance
    pub async fn create_agent(
        &self,
        agent_def: AgentDefinition,
        context: &mut ExecutionContext,
    ) -> Result<ExecutionResult> {
        // Check capabilities
        if let Some(security) = &agent_def.security {
            for capability in &security.capabilities {
                if !self.check_capability(capability).await? {
                    return Err(ReplError::Security(format!(
                        "Missing capability: {}",
                        capability
                    )));
                }
            }
        }

        let agent_id = Uuid::new_v4();
        let agent = AgentInstance {
            id: agent_id,
            definition: agent_def.clone(),
            state: AgentState::Created,
            created_at: chrono::Utc::now(),
        };

        // Log agent creation
        self.monitor
            .log_agent_event(&agent, TraceEventType::AgentCreated);

        // Store agent instance
        self.agents.write().await.insert(agent_id, agent.clone());
        context.agent_id = Some(agent_id);

        tracing::info!("Agent '{}' created with ID {}", agent_def.name, agent_id);
        Ok(ExecutionResult::Value(DslValue::Agent(Box::new(agent))))
    }

    /// Execute a block of statements
    fn execute_block<'a>(
        &'a self,
        block: &'a Block,
        context: &'a mut ExecutionContext,
    ) -> BoxFuture<'a, Result<ExecutionResult>> {
        Box::pin(async move {
            if context.depth >= context.max_depth {
                return Err(ReplError::Execution(
                    "Maximum execution depth exceeded".to_string(),
                ));
            }

            context.depth += 1;

            let mut last_result = ExecutionResult::Value(DslValue::Null);

            for statement in &block.statements {
                match self.execute_statement(statement, context).await? {
                    ExecutionResult::Return(value) => {
                        context.depth -= 1;
                        return Ok(ExecutionResult::Return(value));
                    }
                    ExecutionResult::Break | ExecutionResult::Continue => {
                        context.depth -= 1;
                        return Ok(last_result);
                    }
                    ExecutionResult::Error(msg) => {
                        context.depth -= 1;
                        return Err(ReplError::Execution(msg));
                    }
                    result => last_result = result,
                }
            }

            context.depth -= 1;
            Ok(last_result)
        })
    }

    /// Execute a statement
    async fn execute_statement(
        &self,
        statement: &Statement,
        context: &mut ExecutionContext,
    ) -> Result<ExecutionResult> {
        match statement {
            Statement::Let(let_stmt) => {
                let value = self
                    .evaluate_expression_impl(&let_stmt.value, context)
                    .await?;
                context.variables.insert(let_stmt.name.clone(), value);
                Ok(ExecutionResult::Value(DslValue::Null))
            }
            Statement::If(if_stmt) => {
                let condition = self
                    .evaluate_expression_impl(&if_stmt.condition, context)
                    .await?;

                if condition.is_truthy() {
                    self.execute_block(&if_stmt.then_block, context).await
                } else {
                    // Check else-if conditions
                    for else_if in &if_stmt.else_ifs {
                        let else_condition = self
                            .evaluate_expression_impl(&else_if.condition, context)
                            .await?;
                        if else_condition.is_truthy() {
                            return self.execute_block(&else_if.block, context).await;
                        }
                    }

                    // Execute else block if present
                    if let Some(else_block) = &if_stmt.else_block {
                        self.execute_block(else_block, context).await
                    } else {
                        Ok(ExecutionResult::Value(DslValue::Null))
                    }
                }
            }
            Statement::Return(ret_stmt) => {
                let value = if let Some(expr) = &ret_stmt.value {
                    self.evaluate_expression_impl(expr, context).await?
                } else {
                    DslValue::Null
                };
                Ok(ExecutionResult::Return(value))
            }
            Statement::Emit(emit_stmt) => {
                let data = if let Some(expr) = &emit_stmt.data {
                    self.evaluate_expression_impl(expr, context).await?
                } else {
                    DslValue::Null
                };

                // Emit event through runtime bridge
                let agent_id = context.agent_id.unwrap_or_else(Uuid::new_v4);

                match self
                    .runtime_bridge
                    .emit_event(
                        &agent_id.to_string(),
                        &emit_stmt.event_name,
                        &data.to_json(),
                    )
                    .await
                {
                    Ok(_) => {
                        tracing::info!(
                            "Successfully emitted event: {} with data: {:?}",
                            emit_stmt.event_name,
                            data
                        );
                    }
                    Err(e) => {
                        tracing::error!("Failed to emit event '{}': {}", emit_stmt.event_name, e);
                        return Err(ReplError::Runtime(format!("Failed to emit event: {}", e)));
                    }
                }
                Ok(ExecutionResult::Value(DslValue::Null))
            }
            Statement::Require(req_stmt) => {
                match &req_stmt.requirement {
                    RequirementType::Capability(cap_name) => {
                        if !self.check_capability(cap_name).await? {
                            return Err(ReplError::Security(format!(
                                "Missing capability: {}",
                                cap_name
                            )));
                        }
                    }
                    RequirementType::Capabilities(cap_names) => {
                        for cap_name in cap_names {
                            if !self.check_capability(cap_name).await? {
                                return Err(ReplError::Security(format!(
                                    "Missing capability: {}",
                                    cap_name
                                )));
                            }
                        }
                    }
                }
                Ok(ExecutionResult::Value(DslValue::Null))
            }
            Statement::Expression(expr) => {
                let value = self.evaluate_expression_impl(expr, context).await?;
                Ok(ExecutionResult::Value(value))
            }
            // Implement remaining statement types with basic functionality
            Statement::Match(match_stmt) => {
                let value = self
                    .evaluate_expression_impl(&match_stmt.expression, context)
                    .await?;

                for arm in &match_stmt.arms {
                    if self.pattern_matches(&arm.pattern, &value) {
                        return self
                            .evaluate_expression_impl(&arm.body, context)
                            .await
                            .map(ExecutionResult::Value);
                    }
                }

                // No match found
                Err(ReplError::Execution(
                    "No matching pattern found".to_string(),
                ))
            }
            Statement::For(for_stmt) => {
                let iterable = self
                    .evaluate_expression_impl(&for_stmt.iterable, context)
                    .await?;

                match iterable {
                    DslValue::List(items) => {
                        for item in items {
                            context.variables.insert(for_stmt.variable.clone(), item);
                            match self.execute_block(&for_stmt.body, context).await? {
                                ExecutionResult::Break => break,
                                ExecutionResult::Continue => continue,
                                ExecutionResult::Return(value) => {
                                    return Ok(ExecutionResult::Return(value))
                                }
                                _ => {}
                            }
                        }
                        Ok(ExecutionResult::Value(DslValue::Null))
                    }
                    _ => Err(ReplError::Execution(
                        "For loop requires iterable value".to_string(),
                    )),
                }
            }
            Statement::While(while_stmt) => {
                loop {
                    let condition = self
                        .evaluate_expression_impl(&while_stmt.condition, context)
                        .await?;
                    if !condition.is_truthy() {
                        break;
                    }

                    match self.execute_block(&while_stmt.body, context).await? {
                        ExecutionResult::Break => break,
                        ExecutionResult::Continue => continue,
                        ExecutionResult::Return(value) => {
                            return Ok(ExecutionResult::Return(value))
                        }
                        _ => {}
                    }
                }
                Ok(ExecutionResult::Value(DslValue::Null))
            }
            Statement::Try(try_stmt) => {
                // Execute try block
                match self.execute_block(&try_stmt.try_block, context).await {
                    Ok(result) => Ok(result),
                    Err(_) => {
                        // Execute catch block
                        self.execute_block(&try_stmt.catch_block, context).await
                    }
                }
            }
            Statement::Check(check_stmt) => {
                // Check policy validation (simplified implementation)
                tracing::info!("Policy check for: {}", check_stmt.policy_name);
                Ok(ExecutionResult::Value(DslValue::Boolean(true)))
            }
        }
    }

    /// Evaluate an expression
    pub async fn evaluate_expression(
        &self,
        expression: &Expression,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        self.evaluate_expression_impl(expression, context).await
    }

    /// Internal implementation for expression evaluation
    fn evaluate_expression_impl<'a>(
        &'a self,
        expression: &'a Expression,
        context: &'a mut ExecutionContext,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<DslValue>> + Send + 'a>> {
        Box::pin(async move {
            match expression {
                Expression::Literal(literal) => self.evaluate_literal(literal),
                Expression::Identifier(identifier) => {
                    if let Some(value) = context.variables.get(&identifier.name) {
                        Ok(value.clone())
                    } else {
                        Err(ReplError::Execution(format!(
                            "Undefined variable: {}",
                            identifier.name
                        )))
                    }
                }
                Expression::FieldAccess(field_access) => {
                    let object = self
                        .evaluate_expression_impl(&field_access.object, context)
                        .await?;
                    self.access_field(object, &field_access.field)
                }
                Expression::IndexAccess(index_access) => {
                    let object = self
                        .evaluate_expression_impl(&index_access.object, context)
                        .await?;
                    let index = self
                        .evaluate_expression_impl(&index_access.index, context)
                        .await?;
                    self.access_index(object, index)
                }
                Expression::FunctionCall(func_call) => {
                    self.call_function(&func_call.function, &func_call.arguments, context)
                        .await
                }
                Expression::MethodCall(method_call) => {
                    let object = self
                        .evaluate_expression_impl(&method_call.object, context)
                        .await?;
                    self.call_method(object, &method_call.method, &method_call.arguments, context)
                        .await
                }
                Expression::BinaryOp(binary_op) => {
                    let left = self
                        .evaluate_expression_impl(&binary_op.left, context)
                        .await?;
                    let right = self
                        .evaluate_expression_impl(&binary_op.right, context)
                        .await?;
                    self.evaluate_binary_op(&binary_op.operator, left, right)
                }
                Expression::UnaryOp(unary_op) => {
                    let operand = self
                        .evaluate_expression_impl(&unary_op.operand, context)
                        .await?;
                    self.evaluate_unary_op(&unary_op.operator, operand)
                }
                Expression::Assignment(assignment) => {
                    let value = self
                        .evaluate_expression_impl(&assignment.value, context)
                        .await?;

                    if let Expression::Identifier(identifier) = assignment.target.as_ref() {
                        context
                            .variables
                            .insert(identifier.name.clone(), value.clone());
                        Ok(value)
                    } else {
                        Err(ReplError::Execution(
                            "Invalid assignment target".to_string(),
                        ))
                    }
                }
                Expression::List(list_expr) => {
                    let mut items = Vec::new();
                    for element in &list_expr.elements {
                        items.push(self.evaluate_expression_impl(element, context).await?);
                    }
                    Ok(DslValue::List(items))
                }
                Expression::Map(map_expr) => {
                    let mut entries = HashMap::new();
                    for entry in &map_expr.entries {
                        let key = self.evaluate_expression_impl(&entry.key, context).await?;
                        let value = self.evaluate_expression_impl(&entry.value, context).await?;

                        if let DslValue::String(key_str) = key {
                            entries.insert(key_str, value);
                        } else {
                            return Err(ReplError::Execution(
                                "Map keys must be strings".to_string(),
                            ));
                        }
                    }
                    Ok(DslValue::Map(entries))
                }
                Expression::Invoke(invoke) => {
                    self.evaluate_invoke_expression(invoke, context).await
                }
                Expression::Lambda(lambda) => {
                    self.evaluate_lambda_expression(lambda, context).await
                }
                Expression::Conditional(conditional) => {
                    let condition = self
                        .evaluate_expression_impl(&conditional.condition, context)
                        .await?;

                    if condition.is_truthy() {
                        self.evaluate_expression_impl(&conditional.if_true, context)
                            .await
                    } else {
                        self.evaluate_expression_impl(&conditional.if_false, context)
                            .await
                    }
                }
            }
        })
    }

    /// Evaluate a literal
    pub fn evaluate_literal(&self, literal: &Literal) -> Result<DslValue> {
        match literal {
            Literal::String(s) => Ok(DslValue::String(s.clone())),
            Literal::Number(n) => Ok(DslValue::Number(*n)),
            Literal::Integer(i) => Ok(DslValue::Integer(*i)),
            Literal::Boolean(b) => Ok(DslValue::Boolean(*b)),
            Literal::Duration(duration) => Ok(DslValue::Duration {
                value: duration.value,
                unit: duration.unit.clone(),
            }),
            Literal::Size(size) => Ok(DslValue::Size {
                value: size.value,
                unit: size.unit.clone(),
            }),
            Literal::Null => Ok(DslValue::Null),
        }
    }

    /// Access a field on an object
    fn access_field(&self, object: DslValue, field: &str) -> Result<DslValue> {
        match object {
            DslValue::Map(entries) => entries
                .get(field)
                .cloned()
                .ok_or_else(|| ReplError::Execution(format!("Field '{}' not found", field))),
            DslValue::Agent(agent) => match field {
                "id" => Ok(DslValue::String(agent.id.to_string())),
                "state" => Ok(DslValue::String(format!("{:?}", agent.state))),
                "created_at" => Ok(DslValue::String(agent.created_at.to_rfc3339())),
                _ => Err(ReplError::Execution(format!(
                    "Agent field '{}' not found",
                    field
                ))),
            },
            _ => Err(ReplError::Execution(format!(
                "Cannot access field on {}",
                object.type_name()
            ))),
        }
    }

    /// Access an index on an object
    fn access_index(&self, object: DslValue, index: DslValue) -> Result<DslValue> {
        match (object, index) {
            (DslValue::List(items), DslValue::Integer(i)) => {
                let idx = if i < 0 { items.len() as i64 + i } else { i } as usize;

                items
                    .get(idx)
                    .cloned()
                    .ok_or_else(|| ReplError::Execution("Index out of bounds".to_string()))
            }
            (DslValue::Map(entries), DslValue::String(key)) => entries
                .get(&key)
                .cloned()
                .ok_or_else(|| ReplError::Execution(format!("Key '{}' not found", key))),
            (obj, idx) => Err(ReplError::Execution(format!(
                "Cannot index {} with {}",
                obj.type_name(),
                idx.type_name()
            ))),
        }
    }

    /// Call a function
    async fn call_function(
        &self,
        name: &str,
        arguments: &[Expression],
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        // Evaluate arguments
        let mut arg_values = Vec::new();
        for arg in arguments {
            arg_values.push(self.evaluate_expression_impl(arg, context).await?);
        }

        // Check for sync built-in functions
        if let Some(builtin) = self.builtins.get(name) {
            return builtin(&arg_values);
        }

        // Check for async built-in functions (reasoning, patterns)
        if let Some(async_builtin) = self.async_builtins.get(name) {
            return async_builtin(arg_values).await;
        }

        // Check for user-defined functions
        if let Some(func_def) = context.functions.get(name).cloned() {
            return self.call_user_function(func_def, arg_values, context).await;
        }

        Err(ReplError::Execution(format!("Unknown function: {}", name)))
    }

    /// Call a user-defined function
    async fn call_user_function(
        &self,
        func_def: FunctionDefinition,
        arguments: Vec<DslValue>,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        // Create new scope
        let mut new_context = context.clone();
        new_context.variables.clear();

        // Bind parameters
        for (i, param) in func_def.parameters.parameters.iter().enumerate() {
            let value = match arguments.get(i) {
                Some(value) => value.clone(),
                None => {
                    if let Some(default_expr) = &param.default_value {
                        // Evaluate default value expression
                        self.evaluate_expression_impl(default_expr, &mut new_context)
                            .await?
                    } else {
                        return Err(ReplError::Execution(format!(
                            "Missing argument for parameter '{}'",
                            param.name
                        )));
                    }
                }
            };

            new_context.variables.insert(param.name.clone(), value);
        }

        // Execute function body
        match self.execute_block(&func_def.body, &mut new_context).await? {
            ExecutionResult::Value(value) => Ok(value),
            ExecutionResult::Return(value) => Ok(value),
            _ => Ok(DslValue::Null),
        }
    }

    /// Call a method on an object
    async fn call_method(
        &self,
        object: DslValue,
        method: &str,
        arguments: &[Expression],
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        let mut arg_values = vec![object.clone()];
        for arg in arguments {
            arg_values.push(self.evaluate_expression(arg, context).await?);
        }

        match (&object, method) {
            (DslValue::String(_), "upper") => builtin_upper(&[object]),
            (DslValue::String(_), "lower") => builtin_lower(&[object]),
            (DslValue::List(_) | DslValue::Map(_) | DslValue::String(_), "len") => {
                builtin_len(&[object])
            }
            _ => Err(ReplError::Execution(format!(
                "Method '{}' not found on {}",
                method,
                object.type_name()
            ))),
        }
    }

    /// Evaluate binary operation
    fn evaluate_binary_op(
        &self,
        operator: &BinaryOperator,
        left: DslValue,
        right: DslValue,
    ) -> Result<DslValue> {
        match operator {
            BinaryOperator::Add => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Number(l + r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l + r)),
                (DslValue::String(l), DslValue::String(r)) => Ok(DslValue::String(l + &r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for addition".to_string(),
                )),
            },
            BinaryOperator::Subtract => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Number(l - r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l - r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for subtraction".to_string(),
                )),
            },
            BinaryOperator::Multiply => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Number(l * r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l * r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for multiplication".to_string(),
                )),
            },
            BinaryOperator::Divide => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => {
                    if r == 0.0 {
                        Err(ReplError::Execution("Division by zero".to_string()))
                    } else {
                        Ok(DslValue::Number(l / r))
                    }
                }
                (DslValue::Integer(l), DslValue::Integer(r)) => {
                    if r == 0 {
                        Err(ReplError::Execution("Division by zero".to_string()))
                    } else {
                        Ok(DslValue::Integer(l / r))
                    }
                }
                _ => Err(ReplError::Execution(
                    "Invalid operands for division".to_string(),
                )),
            },
            BinaryOperator::Modulo => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => {
                    if r == 0 {
                        Err(ReplError::Execution("Modulo by zero".to_string()))
                    } else {
                        Ok(DslValue::Integer(l % r))
                    }
                }
                _ => Err(ReplError::Execution(
                    "Invalid operands for modulo".to_string(),
                )),
            },
            BinaryOperator::Equal => Ok(DslValue::Boolean(left == right)),
            BinaryOperator::NotEqual => Ok(DslValue::Boolean(left != right)),
            BinaryOperator::LessThan => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Boolean(l < r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Boolean(l < r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for comparison".to_string(),
                )),
            },
            BinaryOperator::LessThanOrEqual => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Boolean(l <= r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Boolean(l <= r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for comparison".to_string(),
                )),
            },
            BinaryOperator::GreaterThan => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Boolean(l > r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Boolean(l > r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for comparison".to_string(),
                )),
            },
            BinaryOperator::GreaterThanOrEqual => match (left, right) {
                (DslValue::Number(l), DslValue::Number(r)) => Ok(DslValue::Boolean(l >= r)),
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Boolean(l >= r)),
                _ => Err(ReplError::Execution(
                    "Invalid operands for comparison".to_string(),
                )),
            },
            BinaryOperator::And => Ok(DslValue::Boolean(left.is_truthy() && right.is_truthy())),
            BinaryOperator::Or => Ok(DslValue::Boolean(left.is_truthy() || right.is_truthy())),
            // Bitwise operations
            BinaryOperator::BitwiseAnd => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l & r)),
                _ => Err(ReplError::Execution(
                    "Bitwise AND requires integer operands".to_string(),
                )),
            },
            BinaryOperator::BitwiseOr => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l | r)),
                _ => Err(ReplError::Execution(
                    "Bitwise OR requires integer operands".to_string(),
                )),
            },
            BinaryOperator::BitwiseXor => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => Ok(DslValue::Integer(l ^ r)),
                _ => Err(ReplError::Execution(
                    "Bitwise XOR requires integer operands".to_string(),
                )),
            },
            BinaryOperator::LeftShift => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => {
                    if !(0..=63).contains(&r) {
                        Err(ReplError::Execution("Invalid shift amount".to_string()))
                    } else {
                        Ok(DslValue::Integer(l << r))
                    }
                }
                _ => Err(ReplError::Execution(
                    "Left shift requires integer operands".to_string(),
                )),
            },
            BinaryOperator::RightShift => match (left, right) {
                (DslValue::Integer(l), DslValue::Integer(r)) => {
                    if !(0..=63).contains(&r) {
                        Err(ReplError::Execution("Invalid shift amount".to_string()))
                    } else {
                        Ok(DslValue::Integer(l >> r))
                    }
                }
                _ => Err(ReplError::Execution(
                    "Right shift requires integer operands".to_string(),
                )),
            },
        }
    }

    /// Evaluate unary operation
    fn evaluate_unary_op(&self, operator: &UnaryOperator, operand: DslValue) -> Result<DslValue> {
        match operator {
            UnaryOperator::Not => Ok(DslValue::Boolean(!operand.is_truthy())),
            UnaryOperator::Negate => match operand {
                DslValue::Number(n) => Ok(DslValue::Number(-n)),
                DslValue::Integer(i) => Ok(DslValue::Integer(-i)),
                _ => Err(ReplError::Execution(
                    "Invalid operand for negation".to_string(),
                )),
            },
            UnaryOperator::BitwiseNot => match operand {
                DslValue::Integer(i) => Ok(DslValue::Integer(!i)),
                _ => Err(ReplError::Execution(
                    "Bitwise NOT requires integer operand".to_string(),
                )),
            },
        }
    }

    /// Check if a capability is available
    async fn check_capability(&self, capability_name: &str) -> Result<bool> {
        let capability = match capability_name {
            "filesystem" => Capability::FileRead("/".to_string()), // Generic file read capability
            "network" => Capability::NetworkRequest("*".to_string()), // Generic network capability
            "execute" => Capability::Execute("*".to_string()),     // Generic execute capability
            "data" => Capability::DataRead("*".to_string()),       // Generic data capability
            _ => return Ok(false),
        };

        // For now, use a default agent ID - this should be context-specific in real implementation
        let agent_id = "default";
        match self
            .runtime_bridge
            .check_capability(agent_id, &capability)
            .await
        {
            Ok(PolicyDecision::Allow) => Ok(true),
            Ok(PolicyDecision::Deny) => Ok(false),
            Err(e) => Err(ReplError::Runtime(format!(
                "Capability check failed: {}",
                e
            ))),
        }
    }

    /// Get agent by ID
    pub async fn get_agent(&self, agent_id: Uuid) -> Option<AgentInstance> {
        self.agents.read().await.get(&agent_id).cloned()
    }

    /// List all agents
    pub async fn list_agents(&self) -> Vec<AgentInstance> {
        self.agents.read().await.values().cloned().collect()
    }

    /// Start an agent
    pub async fn start_agent(&self, agent_id: Uuid) -> Result<()> {
        let mut agents = self.agents.write().await;
        if let Some(agent) = agents.get_mut(&agent_id) {
            agent.state = AgentState::Starting;

            // Log the event
            self.monitor
                .log_agent_event(agent, TraceEventType::AgentStarted);

            // Integrate with runtime to actually start the agent
            match self.runtime_bridge.initialize().await {
                Ok(_) => {
                    agent.state = AgentState::Running;
                    tracing::info!("Agent {} started and integrated with runtime", agent_id);
                    Ok(())
                }
                Err(e) => {
                    agent.state = AgentState::Failed(format!("Runtime integration failed: {}", e));
                    tracing::error!("Failed to start agent {}: {}", agent_id, e);
                    Err(ReplError::Runtime(format!("Failed to start agent: {}", e)))
                }
            }
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Stop an agent
    pub async fn stop_agent(&self, agent_id: Uuid) -> Result<()> {
        let mut agents = self.agents.write().await;
        if let Some(agent) = agents.get_mut(&agent_id) {
            agent.state = AgentState::Stopping;
            // Log the stopping event
            self.monitor
                .log_agent_event(agent, TraceEventType::AgentStopped);

            // Integrate with runtime to actually stop the agent
            // Note: In a real implementation, this would call runtime bridge methods to stop the agent
            // For now, we just set the state as there's no agent-specific stop method in the current runtime bridge
            agent.state = AgentState::Stopped;
            tracing::info!("Agent {} stopped", agent_id);
            Ok(())
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Pause an agent
    pub async fn pause_agent(&self, agent_id: Uuid) -> Result<()> {
        let mut agents = self.agents.write().await;
        if let Some(agent) = agents.get_mut(&agent_id) {
            match agent.state {
                AgentState::Running => {
                    agent.state = AgentState::Paused;
                    self.monitor
                        .log_agent_event(agent, TraceEventType::AgentPaused);
                    tracing::info!("Agent {} paused", agent_id);
                    Ok(())
                }
                _ => Err(ReplError::Execution(format!(
                    "Agent {} is not running",
                    agent_id
                ))),
            }
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Resume a paused agent
    pub async fn resume_agent(&self, agent_id: Uuid) -> Result<()> {
        let mut agents = self.agents.write().await;
        if let Some(agent) = agents.get_mut(&agent_id) {
            match agent.state {
                AgentState::Paused => {
                    agent.state = AgentState::Running;
                    self.monitor
                        .log_agent_event(agent, TraceEventType::AgentResumed);
                    tracing::info!("Agent {} resumed", agent_id);
                    Ok(())
                }
                _ => Err(ReplError::Execution(format!(
                    "Agent {} is not paused",
                    agent_id
                ))),
            }
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Destroy an agent
    pub async fn destroy_agent(&self, agent_id: Uuid) -> Result<()> {
        let mut agents = self.agents.write().await;
        if let Some(agent) = agents.remove(&agent_id) {
            self.monitor
                .log_agent_event(&agent, TraceEventType::AgentDestroyed);
            tracing::info!("Agent {} destroyed", agent_id);
            Ok(())
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Execute a specific behavior on an agent
    pub async fn execute_agent_behavior(
        &self,
        agent_id: Uuid,
        behavior_name: &str,
        args: &str,
    ) -> Result<DslValue> {
        // Get agent reference
        let agent = {
            let agents = self.agents.read().await;
            agents
                .get(&agent_id)
                .cloned()
                .ok_or_else(|| ReplError::Execution(format!("Agent {} not found", agent_id)))?
        };

        // Check if agent is in valid state for execution
        match agent.state {
            AgentState::Running => {}
            AgentState::Created => {
                return Err(ReplError::Execution(format!(
                    "Agent {} is not started",
                    agent_id
                )));
            }
            AgentState::Paused => {
                return Err(ReplError::Execution(format!(
                    "Agent {} is paused",
                    agent_id
                )));
            }
            AgentState::Stopped => {
                return Err(ReplError::Execution(format!(
                    "Agent {} is stopped",
                    agent_id
                )));
            }
            AgentState::Failed(ref reason) => {
                return Err(ReplError::Execution(format!(
                    "Agent {} failed: {}",
                    agent_id, reason
                )));
            }
            _ => {
                return Err(ReplError::Execution(format!(
                    "Agent {} is not ready for execution",
                    agent_id
                )));
            }
        }

        // Look up behavior in global context (behaviors are defined separately)
        let behavior = {
            let context_guard = self.global_context.lock().unwrap();
            let behavior = context_guard.functions.get(behavior_name).ok_or_else(|| {
                ReplError::Execution(format!("Behavior '{}' not found", behavior_name))
            })?;
            behavior.clone()
        };

        // Parse arguments if provided
        let mut context = ExecutionContext {
            agent_id: Some(agent_id),
            ..ExecutionContext::default()
        };

        // Simple argument parsing - in a real implementation this would be more sophisticated
        if !args.is_empty() {
            // For now, just parse as a single string argument
            context
                .variables
                .insert("args".to_string(), DslValue::String(args.to_string()));
        }

        // Execute the behavior with policy enforcement
        self.execute_function_with_policies(&behavior, &mut context)
            .await
    }

    /// Execute a function with policy enforcement
    async fn execute_function_with_policies(
        &self,
        function: &FunctionDefinition,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        // Start monitoring execution
        let execution_id = self
            .monitor
            .start_execution(context.agent_id, Some(function.name.clone()));

        // Log execution start
        tracing::info!(
            "Executing function '{}' for agent {:?}",
            function.name,
            context.agent_id
        );

        // Execute the function body
        let result = match self.execute_block(&function.body, context).await? {
            ExecutionResult::Value(value) => Ok(value),
            ExecutionResult::Return(value) => Ok(value),
            ExecutionResult::Error(msg) => Err(ReplError::Execution(msg)),
            _ => Ok(DslValue::Null),
        };

        // End monitoring execution - handle the clone issue
        match &result {
            Ok(value) => {
                self.monitor.end_execution(execution_id, Ok(value.clone()));
            }
            Err(error) => {
                let error_msg = format!("{}", error);
                self.monitor
                    .end_execution(execution_id, Err(ReplError::Execution(error_msg)));
            }
        }

        result
    }

    /// Get debug information for an agent
    pub async fn debug_agent(&self, agent_id: Uuid) -> Result<String> {
        let agents = self.agents.read().await;
        if let Some(agent) = agents.get(&agent_id) {
            let mut debug_info = String::new();
            debug_info.push_str("Agent Debug Information:\n");
            debug_info.push_str(&format!("  ID: {}\n", agent.id));
            debug_info.push_str(&format!("  Name: {}\n", agent.definition.name));

            if let Some(version) = &agent.definition.metadata.version {
                debug_info.push_str(&format!("  Version: {}\n", version));
            }

            debug_info.push_str(&format!("  State: {:?}\n", agent.state));
            debug_info.push_str(&format!(
                "  Created: {}\n",
                agent.created_at.format("%Y-%m-%d %H:%M:%S UTC")
            ));

            if let Some(description) = &agent.definition.metadata.description {
                debug_info.push_str(&format!("  Description: {}\n", description));
            }

            if let Some(author) = &agent.definition.metadata.author {
                debug_info.push_str(&format!("  Author: {}\n", author));
            }

            // Count available functions/behaviors in global context
            let context_guard = self.global_context.lock().unwrap();
            let function_count = context_guard.functions.len();
            drop(context_guard);

            debug_info.push_str(&format!(
                "  Available Functions/Behaviors: {}\n",
                function_count
            ));

            if let Some(security) = &agent.definition.security {
                debug_info.push_str(&format!(
                    "  Required Capabilities: {}\n",
                    security.capabilities.len()
                ));
                for cap in &security.capabilities {
                    debug_info.push_str(&format!("    - {}\n", cap));
                }
            }

            if let Some(resources) = &agent.definition.resources {
                debug_info.push_str("  Resource Configuration:\n");
                if let Some(memory) = &resources.memory {
                    debug_info
                        .push_str(&format!("    Memory: {}{:?}\n", memory.value, memory.unit));
                }
                if let Some(cpu) = &resources.cpu {
                    debug_info.push_str(&format!("    CPU: {}{:?}\n", cpu.value, cpu.unit));
                }
                if let Some(network) = resources.network {
                    debug_info.push_str(&format!("    Network: {}\n", network));
                }
                if let Some(storage) = &resources.storage {
                    debug_info.push_str(&format!(
                        "    Storage: {}{:?}\n",
                        storage.value, storage.unit
                    ));
                }
            }

            Ok(debug_info)
        } else {
            Err(ReplError::Execution(format!(
                "Agent {} not found",
                agent_id
            )))
        }
    }

    /// Create a snapshot of the evaluator state
    pub async fn create_snapshot(&self) -> SessionSnapshot {
        let agents = self.agents.read().await.clone();
        let context = self.global_context.lock().unwrap().clone();

        SessionSnapshot {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            data: serde_json::json!({
                "agents": agents.iter().map(|(id, agent)| {
                    (id.to_string(), serde_json::json!({
                        "id": agent.id,
                        "definition": agent.definition.name,
                        "state": format!("{:?}", agent.state),
                        "created_at": agent.created_at
                    }))
                }).collect::<serde_json::Map<_, _>>(),
                "context": {
                    "variables": context.variables.iter().map(|(k, v)| {
                        (k.clone(), v.to_json())
                    }).collect::<serde_json::Map<_, _>>(),
                    "functions": context.functions.keys().collect::<Vec<_>>()
                }
            }),
        }
    }

    /// Restore from a snapshot
    pub async fn restore_snapshot(&self, snapshot: &SessionSnapshot) -> Result<()> {
        // Clear current state
        self.agents.write().await.clear();
        self.global_context.lock().unwrap().variables.clear();
        self.global_context.lock().unwrap().functions.clear();

        // Extract data from snapshot
        if let Some(snapshot_data) = snapshot.data.as_object() {
            // Restore agents
            if let Some(agents_data) = snapshot_data.get("agents").and_then(|v| v.as_object()) {
                for (agent_id_str, agent_data) in agents_data {
                    if let Ok(agent_id) = uuid::Uuid::parse_str(agent_id_str) {
                        if let Some(_agent_obj) = agent_data.as_object() {
                            // In a real implementation, you'd reconstruct the full AgentInstance
                            // from the serialized data. For now, we'll create a placeholder
                            tracing::info!("Restored agent {} from snapshot", agent_id);
                        }
                    }
                }
            }

            // Restore context variables
            if let Some(context_data) = snapshot_data.get("context").and_then(|v| v.as_object()) {
                if let Some(variables) = context_data.get("variables").and_then(|v| v.as_object()) {
                    let mut context_guard = self.global_context.lock().unwrap();
                    for (var_name, var_value) in variables {
                        // Convert JSON value back to DslValue
                        let dsl_value = Self::json_to_dsl_value(var_value);
                        context_guard.variables.insert(var_name.clone(), dsl_value);
                    }
                }

                // Functions would need to be restored from their definitions
                // This is a simplified implementation
                if let Some(functions) = context_data.get("functions").and_then(|v| v.as_array()) {
                    tracing::info!(
                        "Restored {} function definitions from snapshot",
                        functions.len()
                    );
                }
            }
        }

        tracing::info!(
            "Successfully restored evaluator state from snapshot {}",
            snapshot.id
        );
        Ok(())
    }

    /// Helper method to convert JSON value to DslValue
    fn json_to_dsl_value(json_value: &JsonValue) -> DslValue {
        match json_value {
            JsonValue::String(s) => DslValue::String(s.clone()),
            JsonValue::Number(n) => {
                if let Some(i) = n.as_i64() {
                    DslValue::Integer(i)
                } else {
                    DslValue::Number(n.as_f64().unwrap_or(0.0))
                }
            }
            JsonValue::Bool(b) => DslValue::Boolean(*b),
            JsonValue::Array(arr) => {
                let items = arr.iter().map(Self::json_to_dsl_value).collect();
                DslValue::List(items)
            }
            JsonValue::Object(obj) => {
                let mut entries = HashMap::new();
                for (k, v) in obj {
                    entries.insert(k.clone(), Self::json_to_dsl_value(v));
                }
                DslValue::Map(entries)
            }
            JsonValue::Null => DslValue::Null,
        }
    }

    /// Evaluate invoke expression for behavior invocation
    async fn evaluate_invoke_expression(
        &self,
        invoke: &InvokeExpression,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        let behavior_name = &invoke.behavior;

        // Look up behavior in context
        let behavior_def = {
            let context_guard = self.global_context.lock().unwrap();
            context_guard
                .functions
                .get(behavior_name)
                .cloned()
                .ok_or_else(|| {
                    ReplError::Execution(format!("Behavior '{}' not found", behavior_name))
                })?
        };

        // Evaluate arguments
        let mut arg_values = Vec::new();
        for param in &behavior_def.parameters.parameters {
            if let Some(arg_expr) = invoke.arguments.get(&param.name) {
                arg_values.push(self.evaluate_expression_impl(arg_expr, context).await?);
            } else if let Some(default_expr) = &param.default_value {
                arg_values.push(self.evaluate_expression_impl(default_expr, context).await?);
            } else {
                return Err(ReplError::Execution(format!(
                    "Missing argument for parameter '{}'",
                    param.name
                )));
            }
        }

        // Execute the behavior
        self.call_user_function(behavior_def, arg_values, context)
            .await
    }

    /// Evaluate lambda expression
    async fn evaluate_lambda_expression(
        &self,
        lambda: &LambdaExpression,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        // Capture current context for closure
        let captured_context = context.variables.clone();

        let lambda_func = LambdaFunction {
            parameters: lambda.parameters.clone(),
            body: *lambda.body.clone(),
            captured_context,
        };

        Ok(DslValue::Lambda(lambda_func))
    }

    /// Call a lambda function
    async fn _call_lambda(
        &self,
        lambda: &LambdaFunction,
        arguments: Vec<DslValue>,
        context: &mut ExecutionContext,
    ) -> Result<DslValue> {
        // Create new scope with captured context
        let mut new_context = context.clone();
        new_context.variables = lambda.captured_context.clone();

        // Bind parameters
        if arguments.len() != lambda.parameters.len() {
            return Err(ReplError::Execution(format!(
                "Lambda expects {} arguments, got {}",
                lambda.parameters.len(),
                arguments.len()
            )));
        }

        for (param_name, arg_value) in lambda.parameters.iter().zip(arguments.iter()) {
            new_context
                .variables
                .insert(param_name.clone(), arg_value.clone());
        }

        // Execute lambda body
        self.evaluate_expression_impl(&lambda.body, &mut new_context)
            .await
    }

    /// Check if pattern matches value
    fn pattern_matches(&self, pattern: &Pattern, value: &DslValue) -> bool {
        match pattern {
            Pattern::Literal(literal) => {
                if let Ok(literal_value) = self.evaluate_literal(literal) {
                    &literal_value == value
                } else {
                    false
                }
            }
            Pattern::Wildcard => true,
            Pattern::Identifier(_) => true, // Identifiers always match and bind
        }
    }
}

// Built-in functions
pub fn builtin_print(args: &[DslValue]) -> Result<DslValue> {
    let output = args
        .iter()
        .map(|v| match v {
            DslValue::String(s) => s.clone(),
            other => format!("{:?}", other),
        })
        .collect::<Vec<_>>()
        .join(" ");

    println!("{}", output);
    Ok(DslValue::Null)
}

pub fn builtin_len(args: &[DslValue]) -> Result<DslValue> {
    if args.len() != 1 {
        return Err(ReplError::Execution(
            "len() takes exactly one argument".to_string(),
        ));
    }

    let len = match &args[0] {
        DslValue::String(s) => s.len() as i64,
        DslValue::List(items) => items.len() as i64,
        DslValue::Map(entries) => entries.len() as i64,
        _ => {
            return Err(ReplError::Execution(
                "len() requires string, list, or map".to_string(),
            ))
        }
    };

    Ok(DslValue::Integer(len))
}

pub fn builtin_upper(args: &[DslValue]) -> Result<DslValue> {
    if args.len() != 1 {
        return Err(ReplError::Execution(
            "upper() takes exactly one argument".to_string(),
        ));
    }

    match &args[0] {
        DslValue::String(s) => Ok(DslValue::String(s.to_uppercase())),
        _ => Err(ReplError::Execution(
            "upper() requires string argument".to_string(),
        )),
    }
}

pub fn builtin_lower(args: &[DslValue]) -> Result<DslValue> {
    if args.len() != 1 {
        return Err(ReplError::Execution(
            "lower() takes exactly one argument".to_string(),
        ));
    }

    match &args[0] {
        DslValue::String(s) => Ok(DslValue::String(s.to_lowercase())),
        _ => Err(ReplError::Execution(
            "lower() requires string argument".to_string(),
        )),
    }
}

pub fn builtin_format(args: &[DslValue]) -> Result<DslValue> {
    if args.is_empty() {
        return Err(ReplError::Execution(
            "format() requires at least one argument".to_string(),
        ));
    }

    let format_str = match &args[0] {
        DslValue::String(s) => s,
        _ => {
            return Err(ReplError::Execution(
                "format() first argument must be string".to_string(),
            ))
        }
    };

    // Simple format implementation - replace {} with arguments
    let mut result = format_str.clone();
    for arg in &args[1..] {
        let placeholder = "{}";
        if let Some(pos) = result.find(placeholder) {
            let replacement = match arg {
                DslValue::String(s) => s.clone(),
                DslValue::Number(n) => n.to_string(),
                DslValue::Integer(i) => i.to_string(),
                DslValue::Boolean(b) => b.to_string(),
                other => format!("{:?}", other),
            };
            result.replace_range(pos..pos + placeholder.len(), &replacement);
        }
    }

    Ok(DslValue::String(result))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dsl::{lexer::Lexer, parser::Parser};

    async fn create_test_evaluator() -> DslEvaluator {
        let runtime_bridge = Arc::new(RuntimeBridge::new_permissive_for_dev());
        DslEvaluator::new(runtime_bridge)
    }

    async fn evaluate_source(source: &str) -> Result<DslValue> {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize()?;
        let mut parser = Parser::new(tokens);
        let program = parser.parse()?;

        let evaluator = create_test_evaluator().await;
        evaluator.execute_program(program).await
    }

    #[tokio::test]
    async fn test_basic_arithmetic() {
        let result = evaluate_source(
            r#"
            function test() {
                return 2 + 3 * 4
            }
        "#,
        )
        .await
        .unwrap();
        assert_eq!(result, DslValue::Function("test".to_string()));
    }

    #[tokio::test]
    async fn test_variable_assignment() {
        let result = evaluate_source(
            r#"
            function test() {
                let x = 42
                return x
            }
        "#,
        )
        .await
        .unwrap();
        assert_eq!(result, DslValue::Function("test".to_string()));
    }

    #[tokio::test]
    async fn test_function_call() {
        let result = evaluate_source(
            r#"
            function add(a: number, b: number) -> number {
                return a + b
            }
        "#,
        )
        .await
        .unwrap();
        assert_eq!(result, DslValue::Function("add".to_string()));
    }

    #[tokio::test]
    async fn test_builtin_functions() {
        // Test that builtin functions work correctly
        let result = builtin_len(&[DslValue::String("hello".to_string())]);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), DslValue::Integer(5));

        let result = builtin_upper(&[DslValue::String("hello".to_string())]);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), DslValue::String("HELLO".to_string()));
    }
}