adk-gateway 1.0.0

Multi-channel AI gateway for adk-rust agents — Telegram, Slack, WhatsApp, Discord, Matrix + control panel
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
//! Executable ADK tool wrappers for gateway operations.
//!
//! Wraps KnowledgeGraph and AgentRegistry operations as real `FunctionTool`
//! instances that the LLM agent can call. The ToolContext provides `user_id()`
//! for scoping KG operations to the correct user.

use adk_core::ToolContext;
use adk_tool::FunctionTool;
use schemars::JsonSchema;
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use arc_swap::ArcSwap;
use dashmap::DashMap;
use tokio::sync::broadcast;

use crate::agent_codegen::AgentCodegen;
use crate::agent_registry::AgentRegistry;
use crate::control_panel::ws::WsEvent;
use crate::knowledge_graph::KnowledgeGraph;
use crate::process_manager::ProcessManager;
use crate::proxy_pool::RemoteAgentProxyPool;
use crate::rbac_bridge::RbacBridge;
use crate::router::MessageRouter;

// ── Knowledge Graph Tools ──────────────────────────────────────────

/// Build executable KG tools that scope operations to the current user_id.
pub fn build_kg_tools(kg: Arc<KnowledgeGraph>) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![
        Arc::new(kg_create_entities(kg.clone())),
        Arc::new(kg_add_observations(kg.clone())),
        Arc::new(kg_search_nodes(kg.clone())),
        Arc::new(kg_read_graph(kg.clone())),
        Arc::new(kg_delete_entities(kg.clone())),
    ]
}

fn kg_create_entities(kg: Arc<KnowledgeGraph>) -> FunctionTool {
    FunctionTool::new(
        "kg_create_entities",
        "Create entities in the knowledge graph. Each entity has a name, type, and optional observations. Use this to store facts about the user, their projects, preferences, and important context.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let kg = kg.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                tracing::info!(user_id = %user_id, "kg_create_entities: storing for user");
                let entities = args.get("entities")
                    .and_then(|v| v.as_array())
                    .ok_or_else(|| adk_core::AdkError::tool("'entities' array is required".to_string()))?;

                let inputs: Vec<crate::knowledge_graph::CreateEntityInput> = entities.iter()
                    .filter_map(|e| {
                        let name = e.get("name")?.as_str()?.to_string();
                        let entity_type = e.get("entity_type")
                            .or_else(|| e.get("type"))
                            .and_then(|v| v.as_str())
                            .unwrap_or("general")
                            .to_string();
                        let observations = e.get("observations")
                            .and_then(|v| v.as_array())
                            .map(|arr| arr.iter().filter_map(|o| o.as_str().map(String::from)).collect())
                            .unwrap_or_default();
                        Some(crate::knowledge_graph::CreateEntityInput { name, entity_type, observations })
                    })
                    .collect();

                if inputs.is_empty() {
                    return Ok(serde_json::json!({"error": "no valid entities provided"}));
                }

                let created_names = kg.create_entities(&user_id, inputs);
                Ok(serde_json::json!({
                    "created": created_names.len(),
                    "entities": created_names
                }))
            }
        },
    )
}

fn kg_add_observations(kg: Arc<KnowledgeGraph>) -> FunctionTool {
    FunctionTool::new(
        "kg_add_observations",
        "Add observations (facts, notes, preferences) to an existing entity in the knowledge graph. The entity must already exist.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let kg = kg.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                let entity_name = args.get("entity_name")
                    .or_else(|| args.get("entity"))
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'entity_name' is required".to_string()))?
                    .to_string();
                let observations: Vec<String> = args.get("observations")
                    .and_then(|v| v.as_array())
                    .map(|arr| arr.iter().filter_map(|o| o.as_str().map(String::from)).collect())
                    .unwrap_or_default();

                if observations.is_empty() {
                    return Ok(serde_json::json!({"error": "no observations provided"}));
                }

                let count = observations.len();
                match kg.add_observations(&user_id, &entity_name, observations) {
                    Some(ids) => Ok(serde_json::json!({
                        "entity": entity_name,
                        "added": ids.len()
                    })),
                    None => Ok(serde_json::json!({
                        "error": format!("entity '{}' not found", entity_name),
                        "attempted": count
                    })),
                }
            }
        },
    )
}

fn kg_search_nodes(kg: Arc<KnowledgeGraph>) -> FunctionTool {
    FunctionTool::new(
        "kg_search_nodes",
        "Search for entities in the knowledge graph by text query. Returns matching entities with their observations.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let kg = kg.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                let query = args.get("query")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");

                let results = kg.search_nodes(&user_id, query);
                let entries: Vec<Value> = results.iter().map(|r| {
                    serde_json::json!({
                        "name": r.entity.name,
                        "type": r.entity.entity_type,
                        "observations": r.entity.observations.iter()
                            .map(|o| &o.content)
                            .collect::<Vec<_>>(),
                    })
                }).collect();

                if entries.is_empty() {
                    Ok(serde_json::json!({
                        "results": [],
                        "count": 0,
                        "message": format!("No entities matching '{}' found in the knowledge graph.", query)
                    }))
                } else {
                    Ok(serde_json::json!({
                        "results": entries,
                        "count": entries.len()
                    }))
                }
            }
        },
    )
    .with_read_only(true)
}

fn kg_read_graph(kg: Arc<KnowledgeGraph>) -> FunctionTool {
    FunctionTool::new(
        "kg_read_graph",
        "Read the entire knowledge graph for the current user. Returns all entities, their types, observations, and relations.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let kg = kg.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                let _ = args; // no args needed

                tracing::info!(user_id = %user_id, "kg_read_graph: querying KG");

                let (entities, relations) = kg.read_graph(&user_id);

                tracing::info!(
                    user_id = %user_id,
                    entity_count = entities.len(),
                    relation_count = relations.len(),
                    "kg_read_graph: results"
                );

                let entity_values: Vec<Value> = entities.iter().map(|e| {
                    serde_json::json!({
                        "name": e.name,
                        "type": e.entity_type,
                        "observations": e.observations.iter()
                            .map(|o| &o.content)
                            .collect::<Vec<_>>(),
                    })
                }).collect();
                let relation_values: Vec<Value> = relations.iter().map(|r| {
                    serde_json::json!({
                        "source": r.source,
                        "target": r.target,
                        "relation_type": r.relation_type,
                    })
                }).collect();

                if entity_values.is_empty() && relation_values.is_empty() {
                    Ok(serde_json::json!({
                        "entities": [],
                        "relations": [],
                        "entity_count": 0,
                        "relation_count": 0,
                        "message": "Knowledge graph is empty for this user. No entities or relations stored yet."
                    }))
                } else {
                    Ok(serde_json::json!({
                        "entities": entity_values,
                        "relations": relation_values,
                        "entity_count": entity_values.len(),
                        "relation_count": relation_values.len()
                    }))
                }
            }
        },
    )
    .with_read_only(true)
}

fn kg_delete_entities(kg: Arc<KnowledgeGraph>) -> FunctionTool {
    FunctionTool::new(
        "kg_delete_entities",
        "Delete entities from the knowledge graph by name. Also removes associated relations.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let kg = kg.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                let names: Vec<String> = args
                    .get("names")
                    .or_else(|| args.get("entities"))
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|n| n.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default();

                if names.is_empty() {
                    return Ok(serde_json::json!({"error": "no entity names provided"}));
                }

                let deleted = kg.delete_entities(&user_id, names);
                Ok(serde_json::json!({
                    "deleted": deleted
                }))
            }
        },
    )
}

// ── Agent Management Tools ─────────────────────────────────────────

/// Build executable agent management tools (system agent only).
/// Note: This is a simplified version that creates tools without full wiring.
/// For production use, prefer `build_agent_management_tools()` which includes
/// RBAC, WebSocket events, and workspace directory creation.
/// Retained for integration tests that only need basic agent_list/agent_create.
#[allow(dead_code)]
pub fn build_agent_tools(
    registry: Arc<AgentRegistry>,
    rbac: Arc<RbacBridge>,
    ws_broadcast: broadcast::Sender<WsEvent>,
    workspace_root: PathBuf,
) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![
        Arc::new(agent_list_tool(registry.clone())),
        Arc::new(agent_create_tool(
            registry.clone(),
            rbac,
            ws_broadcast,
            workspace_root,
        )),
    ]
}

/// Build all 6 executable agent management tools with full subsystem wiring.
pub fn build_agent_management_tools(
    registry: Arc<AgentRegistry>,
    process_manager: Arc<ProcessManager>,
    proxy_pool: Arc<RemoteAgentProxyPool>,
    rbac: Arc<RbacBridge>,
    router: Arc<ArcSwap<MessageRouter>>,
    codegen: Arc<AgentCodegen>,
    ws_broadcast: broadcast::Sender<WsEvent>,
    workspace_root: PathBuf,
    global_config: Arc<arc_swap::ArcSwap<crate::config::GatewayConfig>>,
) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![
        Arc::new(agent_list_tool(registry.clone())),
        Arc::new(agent_create_tool(
            registry.clone(),
            rbac.clone(),
            ws_broadcast.clone(),
            workspace_root.clone(),
        )),
        Arc::new(agent_start_tool(
            registry.clone(),
            process_manager.clone(),
            proxy_pool.clone(),
            rbac.clone(),
            router.clone(),
            codegen.clone(),
            ws_broadcast.clone(),
            workspace_root.clone(),
            global_config.clone(),
        )),
        Arc::new(agent_stop_tool(
            registry.clone(),
            process_manager.clone(),
            proxy_pool.clone(),
            router.clone(),
            ws_broadcast.clone(),
        )),
        Arc::new(agent_delete_tool(
            registry.clone(),
            rbac.clone(),
            router.clone(),
            ws_broadcast.clone(),
        )),
        Arc::new(agent_configure_tool(
            registry.clone(),
            process_manager.clone(),
            proxy_pool.clone(),
            rbac.clone(),
            router.clone(),
            codegen.clone(),
            ws_broadcast.clone(),
            workspace_root,
            global_config,
        )),
    ]
}

fn agent_list_tool(registry: Arc<AgentRegistry>) -> FunctionTool {
    FunctionTool::new(
        "agent_list",
        "List all registered agents with their current lifecycle state, model, and description.",
        move |_ctx: Arc<dyn ToolContext>, _args: Value| {
            let registry = registry.clone();
            async move {
                let agents = registry.list();
                let entries: Vec<Value> = agents
                    .iter()
                    .map(|(id, record)| {
                        serde_json::json!({
                            "id": id,
                            "name": record.config.name,
                            "description": record.config.description,
                            "state": format!("{:?}", record.state),
                            "model": record.config.model,
                            "auto_start": record.config.auto_start,
                        })
                    })
                    .collect();

                Ok(serde_json::json!({
                    "agents": entries,
                    "count": entries.len()
                }))
            }
        },
    )
    .with_read_only(true)
}

fn agent_create_tool(
    registry: Arc<AgentRegistry>,
    rbac: Arc<RbacBridge>,
    ws_broadcast: broadcast::Sender<WsEvent>,
    workspace_root: PathBuf,
) -> FunctionTool {
    FunctionTool::new(
        "agent_create",
        "Create a new specialist LLM sub-agent for conversation routing and specialized tasks. NOT for coding tasks — use delegate_to_coding_agent for code changes. Requires: name, description, model (e.g. 'anthropic/claude-sonnet-4'), instruction. Optional: tools (array of tool names), auto_start (bool), channel_bindings (array of 'channel:account_id').",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let registry = registry.clone();
            let rbac = rbac.clone();
            let ws_broadcast = ws_broadcast.clone();
            let workspace_root = workspace_root.clone();
            async move {
                let name = args.get("name")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'name' is required".to_string()))?
                    .to_string();

                let description = args.get("description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let model = args.get("model")
                    .and_then(|v| v.as_str())
                    .unwrap_or("anthropic/claude-sonnet-4")
                    .to_string();

                let instruction = args.get("instruction")
                    .and_then(|v| v.as_str())
                    .unwrap_or("You are a helpful specialist agent.")
                    .to_string();

                let tools: Vec<String> = args.get("tools")
                    .and_then(|v| v.as_array())
                    .map(|arr| arr.iter().filter_map(|t| t.as_str().map(String::from)).collect())
                    .unwrap_or_default();

                let auto_start = args.get("auto_start")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);

                let id = name.to_lowercase()
                    .chars()
                    .map(|c| if c.is_alphanumeric() || c == '-' { c } else { '-' })
                    .collect::<String>();

                let config = crate::agent_config::AgentConfig {
                    id: id.clone(),
                    name,
                    description,
                    agent_type: crate::agent_config::AgentType::Llm,
                    model,
                    api_key_env: String::new(),
                    instruction,
                    tools: tools.clone(),
                    action_nodes: vec![],
                    workflow_edges: vec![],
                    sub_agents: vec![],
                    role: crate::agent_config::AgentRoleConfig {
                        allow: tools,
                        deny: vec![],
                    },
                    channel_bindings: vec![],
                    auto_start,
                    temperature: None,
                    max_output_tokens: None,
                    model_override: None,
                };

                // 1. Register agent in the AgentRegistry
                let agent_id = match registry.create_agent(config.clone()) {
                    Ok(aid) => aid,
                    Err(e) => {
                        return Ok(serde_json::json!({
                            "created": false,
                            "error": e.to_string()
                        }));
                    }
                };

                // 2. Create workspace directories (context/, data/, src/)
                let agent_dir = workspace_root.join("agents").join(&agent_id);
                let context_dir = agent_dir.join("context");
                let data_dir = agent_dir.join("data");
                let src_dir = agent_dir.join("src");

                for dir in [&context_dir, &data_dir, &src_dir] {
                    if let Err(e) = std::fs::create_dir_all(dir) {
                        tracing::warn!(
                            agent_id = %agent_id,
                            dir = %dir.display(),
                            error = %e,
                            "failed to create workspace directory"
                        );
                    }
                }

                // 3. Write default context files
                let default_context_files: &[(&str, &str)] = &[
                    ("PROFILE.md", "# Agent Profile\n\nSpecialist agent profile.\n"),
                    ("USER.md", "# User Context\n\nUser-specific context and preferences.\n"),
                    ("PROJECTS.md", "# Projects\n\nActive projects and tasks.\n"),
                    ("HABITS.md", "# Habits\n\nUser habits and patterns.\n"),
                    ("NOTES.md", "# Notes\n\nGeneral notes and observations.\n"),
                    ("BOOTSTRAP.md", "# Bootstrap\n\nInitial setup and configuration context.\n"),
                ];

                for (filename, content) in default_context_files {
                    let file_path = context_dir.join(filename);
                    if let Err(e) = std::fs::write(&file_path, content) {
                        tracing::warn!(
                            agent_id = %agent_id,
                            file = %file_path.display(),
                            error = %e,
                            "failed to write default context file"
                        );
                    }
                }

                // 4. Register RBAC role (strips system tools)
                let stripped = rbac.register_agent(&agent_id, &config.role);
                if !stripped.is_empty() {
                    tracing::info!(
                        agent_id = %agent_id,
                        stripped = ?stripped,
                        "stripped system tool permissions from agent role"
                    );
                }

                // 5. Emit WsEvent::AgentState { state: "Created" }
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Created".into(),
                });

                Ok(serde_json::json!({
                    "created": true,
                    "agent_id": agent_id,
                    "message": format!("Agent '{}' created successfully.", agent_id)
                }))
            }
        },
    )
}

fn agent_stop_tool(
    registry: Arc<AgentRegistry>,
    process_manager: Arc<ProcessManager>,
    proxy_pool: Arc<RemoteAgentProxyPool>,
    router: Arc<ArcSwap<MessageRouter>>,
    ws_broadcast: broadcast::Sender<WsEvent>,
) -> FunctionTool {
    FunctionTool::new(
        "agent_stop",
        "Stop a running User Agent by ID. Gracefully drains the process, removes it from the proxy pool and message router.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let registry = registry.clone();
            let process_manager = process_manager.clone();
            let proxy_pool = proxy_pool.clone();
            let router = router.clone();
            let ws_broadcast = ws_broadcast.clone();
            async move {
                let agent_id = args.get("agent_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'agent_id' is required".to_string()))?
                    .to_string();

                // Verify agent exists in registry
                {
                    let _entry = registry.get(&agent_id)
                        .ok_or_else(|| adk_core::AdkError::tool(
                            format!("agent '{}' not found in registry", agent_id)
                        ))?;
                }

                // 1. Transition to Stopping
                registry.transition(&agent_id, crate::agent_config::LifecycleState::Stopping)
                    .map_err(|e| adk_core::AdkError::tool(
                        format!("failed to transition '{}' to Stopping: {}", agent_id, e)
                    ))?;

                // Emit Stopping event
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Stopping".into(),
                });

                // 2. Stop the process with 10s drain timeout
                if let Err(e) = process_manager.stop(&agent_id, Duration::from_secs(10)).await {
                    tracing::warn!(
                        agent_id = %agent_id,
                        error = %e,
                        "process stop failed, continuing with cleanup"
                    );
                }

                // 3. Remove from ProxyPool
                proxy_pool.remove(&agent_id);

                // 4. Remove agent bindings from MessageRouter via ArcSwap clone-mutate-store
                let current = router.load();
                let mut new_router = (**current).clone();
                new_router.remove_agent_bindings(&agent_id);
                router.store(Arc::new(new_router));

                // 5. Transition to Stopped
                let _ = registry.transition(&agent_id, crate::agent_config::LifecycleState::Stopped);

                // 6. Emit Stopped WebSocket event
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Stopped".into(),
                });

                Ok(serde_json::json!({
                    "stopped": true,
                    "agent_id": agent_id,
                    "state": "Stopped"
                }))
            }
        },
    )
}

fn agent_start_tool(
    registry: Arc<AgentRegistry>,
    process_manager: Arc<ProcessManager>,
    proxy_pool: Arc<RemoteAgentProxyPool>,
    rbac: Arc<RbacBridge>,
    router: Arc<ArcSwap<MessageRouter>>,
    codegen: Arc<AgentCodegen>,
    ws_broadcast: broadcast::Sender<WsEvent>,
    workspace_root: PathBuf,
    global_config: Arc<arc_swap::ArcSwap<crate::config::GatewayConfig>>,
) -> FunctionTool {
    FunctionTool::new(
        "agent_start",
        "Start a User Agent by ID. Builds the agent binary, spawns the process, waits for readiness, and registers it for message routing.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let registry = registry.clone();
            let process_manager = process_manager.clone();
            let proxy_pool = proxy_pool.clone();
            let rbac = rbac.clone();
            let router = router.clone();
            let codegen = codegen.clone();
            let ws_broadcast = ws_broadcast.clone();
            let workspace_root = workspace_root.clone();
            let global_config = global_config.clone();
            async move {
                let agent_id = args.get("agent_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'agent_id' is required".to_string()))?
                    .to_string();

                // Get the agent config from the registry
                let config = {
                    let entry = registry.get(&agent_id)
                        .ok_or_else(|| adk_core::AdkError::tool(
                            format!("agent '{}' not found in registry", agent_id)
                        ))?;
                    entry.config.clone()
                };

                // Resolve the effective primary model using per-agent category overrides (R9.3, R9.5, R9.6)
                let global_cfg = global_config.load();
                let effective_model = config
                    .resolve_model("primary", &global_cfg.agent.model)
                    .unwrap_or(config.model.as_str());

                // 1. Transition to Starting
                registry.transition(&agent_id, crate::agent_config::LifecycleState::Starting)
                    .map_err(|e| adk_core::AdkError::tool(
                        format!("failed to transition '{}' to Starting: {}", agent_id, e)
                    ))?;

                // Emit Starting WebSocket event
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Starting".into(),
                });

                // 2. Build agent binary via codegen
                let binary_path = match codegen.build_agent(&config).await {
                    Ok(path) => path,
                    Err(e) => {
                        let _ = registry.transition(
                            &agent_id,
                            crate::agent_config::LifecycleState::Error {
                                message: format!("build failed: {}", e),
                            },
                        );
                        let _ = ws_broadcast.send(WsEvent::AgentState {
                            agent_id: agent_id.clone(),
                            state: "Error".into(),
                        });
                        return Ok(serde_json::json!({
                            "started": false,
                            "agent_id": agent_id,
                            "error": format!("build failed: {}", e)
                        }));
                    }
                };

                // 3. Resolve API key env and build env map
                let api_key_env = config.resolve_api_key_env().to_string();
                let mut env = HashMap::new();
                env.insert("AGENT_ID".to_string(), agent_id.clone());
                env.insert("AGENT_MODEL".to_string(), effective_model.to_string());
                if let Ok(val) = std::env::var(&api_key_env) {
                    env.insert(api_key_env.clone(), val);
                }
                env.insert(
                    "AGENT_DATA_DIR".to_string(),
                    workspace_root
                        .join("agents")
                        .join(&agent_id)
                        .join("data")
                        .display()
                        .to_string(),
                );

                // 4. Spawn process
                let port = match process_manager.spawn(&agent_id, &binary_path, env).await {
                    Ok(port) => port,
                    Err(e) => {
                        let _ = registry.transition(
                            &agent_id,
                            crate::agent_config::LifecycleState::Error {
                                message: format!("spawn failed: {}", e),
                            },
                        );
                        let _ = ws_broadcast.send(WsEvent::AgentState {
                            agent_id: agent_id.clone(),
                            state: "Error".into(),
                        });
                        return Ok(serde_json::json!({
                            "started": false,
                            "agent_id": agent_id,
                            "error": format!("spawn failed: {}", e)
                        }));
                    }
                };

                // 5. Wait for readiness (30s timeout)
                if let Err(e) = process_manager.wait_ready(&agent_id, Duration::from_secs(30)).await {
                    // Cleanup on timeout
                    let _ = process_manager.stop(&agent_id, Duration::from_secs(5)).await;
                    proxy_pool.remove(&agent_id);
                    let _ = registry.transition(
                        &agent_id,
                        crate::agent_config::LifecycleState::Error {
                            message: format!("readiness check failed: {}", e),
                        },
                    );
                    let _ = ws_broadcast.send(WsEvent::AgentState {
                        agent_id: agent_id.clone(),
                        state: "Error".into(),
                    });
                    return Ok(serde_json::json!({
                        "started": false,
                        "agent_id": agent_id,
                        "error": format!("agent '{}' failed readiness check: {}", agent_id, e)
                    }));
                }

                // 6. Register proxy
                proxy_pool.register(&agent_id, port);

                // 7. Register RBAC role
                rbac.register_agent(&agent_id, &config.role);

                // 8. Add router bindings (clone-mutate-store via ArcSwap)
                if !config.channel_bindings.is_empty() {
                    let current = router.load();
                    let mut new_router = (**current).clone();
                    new_router.add_agent_bindings(&agent_id, &config.channel_bindings);
                    router.store(Arc::new(new_router));
                }

                // 9. Transition to Running
                let _ = registry.transition(&agent_id, crate::agent_config::LifecycleState::Running);

                // 10. Emit WebSocket event
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Running".into(),
                });

                Ok(serde_json::json!({
                    "started": true,
                    "agent_id": agent_id,
                    "port": port,
                    "state": "Running"
                }))
            }
        },
    )
}

fn agent_delete_tool(
    registry: Arc<AgentRegistry>,
    rbac: Arc<RbacBridge>,
    router: Arc<ArcSwap<MessageRouter>>,
    ws_broadcast: broadcast::Sender<WsEvent>,
) -> FunctionTool {
    FunctionTool::new(
        "agent_delete",
        "Delete a User Agent by ID. The agent must be in Stopped or Error state. Removes the agent from the registry, RBAC roles, and message router bindings.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let registry = registry.clone();
            let rbac = rbac.clone();
            let router = router.clone();
            let ws_broadcast = ws_broadcast.clone();
            async move {
                let agent_id = args.get("agent_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'agent_id' is required".to_string()))?
                    .to_string();

                // 1. Verify agent is in Stopped or Error state (AgentRegistry::delete enforces this)
                //    We call delete which checks the precondition internally.
                registry.delete(&agent_id)
                    .map_err(|e| adk_core::AdkError::tool(
                        format!("cannot delete agent '{}': {}", agent_id, e)
                    ))?;

                // 2. Remove RBAC role
                rbac.remove_agent(&agent_id);

                // 3. Remove any residual router bindings via ArcSwap clone-mutate-store
                let current = router.load();
                let mut new_router = (**current).clone();
                new_router.remove_agent_bindings(&agent_id);
                router.store(Arc::new(new_router));

                // 4. Emit Deleted WebSocket event
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Deleted".into(),
                });

                Ok(serde_json::json!({
                    "deleted": true,
                    "agent_id": agent_id,
                    "state": "Deleted"
                }))
            }
        },
    )
}

fn agent_configure_tool(
    registry: Arc<AgentRegistry>,
    process_manager: Arc<ProcessManager>,
    proxy_pool: Arc<RemoteAgentProxyPool>,
    rbac: Arc<RbacBridge>,
    router: Arc<ArcSwap<MessageRouter>>,
    codegen: Arc<AgentCodegen>,
    ws_broadcast: broadcast::Sender<WsEvent>,
    workspace_root: PathBuf,
    global_config: Arc<arc_swap::ArcSwap<crate::config::GatewayConfig>>,
) -> FunctionTool {
    FunctionTool::new(
        "agent_configure",
        "Update a User Agent's configuration. Accepts the agent_id and a new config object. If the agent is Running, it will be stopped, reconfigured, and restarted automatically.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let registry = registry.clone();
            let process_manager = process_manager.clone();
            let proxy_pool = proxy_pool.clone();
            let rbac = rbac.clone();
            let router = router.clone();
            let codegen = codegen.clone();
            let ws_broadcast = ws_broadcast.clone();
            let workspace_root = workspace_root.clone();
            let global_config = global_config.clone();
            async move {
                let agent_id = args.get("agent_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'agent_id' is required".to_string()))?
                    .to_string();

                let config_value = args.get("config")
                    .ok_or_else(|| adk_core::AdkError::tool("'config' is required".to_string()))?;

                let new_config: crate::agent_config::AgentConfig = serde_json::from_value(config_value.clone())
                    .map_err(|e| adk_core::AdkError::tool(
                        format!("invalid config: {}", e)
                    ))?;

                // Validate config ID matches agent_id
                if new_config.id != agent_id {
                    return Err(adk_core::AdkError::tool(
                        format!("config id '{}' does not match agent_id '{}'", new_config.id, agent_id)
                    ));
                }

                // Get current state and old config to determine if restart is needed
                let (was_running, old_channel_bindings) = {
                    let entry = registry.get(&agent_id)
                        .ok_or_else(|| adk_core::AdkError::tool(
                            format!("agent '{}' not found in registry", agent_id)
                        ))?;
                    let running = entry.state == crate::agent_config::LifecycleState::Running;
                    let old_bindings = entry.config.channel_bindings.clone();
                    (running, old_bindings)
                };

                // If agent was Running: stop it first
                if was_running {
                    // Transition to Stopping
                    registry.transition(&agent_id, crate::agent_config::LifecycleState::Stopping)
                        .map_err(|e| adk_core::AdkError::tool(
                            format!("failed to transition '{}' to Stopping: {}", agent_id, e)
                        ))?;

                    let _ = ws_broadcast.send(WsEvent::AgentState {
                        agent_id: agent_id.clone(),
                        state: "Stopping".into(),
                    });

                    // Stop the process with 10s drain timeout
                    if let Err(e) = process_manager.stop(&agent_id, Duration::from_secs(10)).await {
                        tracing::warn!(
                            agent_id = %agent_id,
                            error = %e,
                            "process stop failed during configure, continuing with cleanup"
                        );
                    }

                    // Remove from ProxyPool
                    proxy_pool.remove(&agent_id);

                    // Remove old router bindings
                    let current = router.load();
                    let mut new_router = (**current).clone();
                    new_router.remove_agent_bindings(&agent_id);
                    router.store(Arc::new(new_router));

                    // Transition to Stopped
                    let _ = registry.transition(&agent_id, crate::agent_config::LifecycleState::Stopped);

                    let _ = ws_broadcast.send(WsEvent::AgentState {
                        agent_id: agent_id.clone(),
                        state: "Stopped".into(),
                    });
                }

                // Update config in registry
                registry.update_config(&agent_id, new_config.clone())
                    .map_err(|e| adk_core::AdkError::tool(
                        format!("failed to update config for '{}': {}", agent_id, e)
                    ))?;

                // Re-register RBAC role with new config
                rbac.register_agent(&agent_id, &new_config.role);

                // Update router bindings if channel_bindings changed
                if new_config.channel_bindings != old_channel_bindings {
                    let current = router.load();
                    let mut new_router = (**current).clone();
                    new_router.update_agent_bindings(&agent_id, &new_config.channel_bindings);
                    router.store(Arc::new(new_router));
                }

                // If agent was Running: restart it
                if was_running {
                    // Transition to Starting
                    registry.transition(&agent_id, crate::agent_config::LifecycleState::Starting)
                        .map_err(|e| adk_core::AdkError::tool(
                            format!("failed to transition '{}' to Starting: {}", agent_id, e)
                        ))?;

                    // Emit Starting WebSocket event
                    let _ = ws_broadcast.send(WsEvent::AgentState {
                        agent_id: agent_id.clone(),
                        state: "Starting".into(),
                    });

                    // Build agent binary via codegen
                    let binary_path = match codegen.build_agent(&new_config).await {
                        Ok(path) => path,
                        Err(e) => {
                            let _ = registry.transition(
                                &agent_id,
                                crate::agent_config::LifecycleState::Error {
                                    message: format!("build failed during configure: {}", e),
                                },
                            );
                            let _ = ws_broadcast.send(WsEvent::AgentState {
                                agent_id: agent_id.clone(),
                                state: "Error".into(),
                            });
                            return Ok(serde_json::json!({
                                "configured": true,
                                "restarted": false,
                                "agent_id": agent_id,
                                "error": format!("config updated but restart failed: build error: {}", e)
                            }));
                        }
                    };

                    // Resolve API key env and build env map
                    let global_cfg = global_config.load();
                    let effective_model = new_config
                        .resolve_model("primary", &global_cfg.agent.model)
                        .unwrap_or(new_config.model.as_str());
                    let api_key_env = new_config.resolve_api_key_env().to_string();
                    let mut env = HashMap::new();
                    env.insert("AGENT_ID".to_string(), agent_id.clone());
                    env.insert("AGENT_MODEL".to_string(), effective_model.to_string());
                    if let Ok(val) = std::env::var(&api_key_env) {
                        env.insert(api_key_env.clone(), val);
                    }
                    env.insert(
                        "AGENT_DATA_DIR".to_string(),
                        workspace_root
                            .join("agents")
                            .join(&agent_id)
                            .join("data")
                            .display()
                            .to_string(),
                    );

                    // Spawn process
                    let port = match process_manager.spawn(&agent_id, &binary_path, env).await {
                        Ok(port) => port,
                        Err(e) => {
                            let _ = registry.transition(
                                &agent_id,
                                crate::agent_config::LifecycleState::Error {
                                    message: format!("spawn failed during configure: {}", e),
                                },
                            );
                            let _ = ws_broadcast.send(WsEvent::AgentState {
                                agent_id: agent_id.clone(),
                                state: "Error".into(),
                            });
                            return Ok(serde_json::json!({
                                "configured": true,
                                "restarted": false,
                                "agent_id": agent_id,
                                "error": format!("config updated but restart failed: spawn error: {}", e)
                            }));
                        }
                    };

                    // Wait for readiness (30s timeout)
                    if let Err(e) = process_manager.wait_ready(&agent_id, Duration::from_secs(30)).await {
                        // Cleanup on timeout
                        let _ = process_manager.stop(&agent_id, Duration::from_secs(5)).await;
                        proxy_pool.remove(&agent_id);
                        let _ = registry.transition(
                            &agent_id,
                            crate::agent_config::LifecycleState::Error {
                                message: format!("readiness check failed during configure: {}", e),
                            },
                        );
                        let _ = ws_broadcast.send(WsEvent::AgentState {
                            agent_id: agent_id.clone(),
                            state: "Error".into(),
                        });
                        return Ok(serde_json::json!({
                            "configured": true,
                            "restarted": false,
                            "agent_id": agent_id,
                            "error": format!("config updated but restart failed: readiness timeout: {}", e)
                        }));
                    }

                    // Register proxy
                    proxy_pool.register(&agent_id, port);

                    // Re-add router bindings for the new config (if not already done above)
                    if !new_config.channel_bindings.is_empty() {
                        let current = router.load();
                        let mut new_router = (**current).clone();
                        // Ensure bindings are current (update_agent_bindings replaces)
                        new_router.update_agent_bindings(&agent_id, &new_config.channel_bindings);
                        router.store(Arc::new(new_router));
                    }

                    // Transition to Running
                    let _ = registry.transition(&agent_id, crate::agent_config::LifecycleState::Running);

                    // Emit Running WebSocket event
                    let _ = ws_broadcast.send(WsEvent::AgentState {
                        agent_id: agent_id.clone(),
                        state: "Running".into(),
                    });

                    return Ok(serde_json::json!({
                        "configured": true,
                        "restarted": true,
                        "agent_id": agent_id,
                        "port": port,
                        "state": "Running"
                    }));
                }

                // Agent was not running — just emit state event for the config update
                let _ = ws_broadcast.send(WsEvent::AgentState {
                    agent_id: agent_id.clone(),
                    state: "Configured".into(),
                });

                Ok(serde_json::json!({
                    "configured": true,
                    "restarted": false,
                    "agent_id": agent_id,
                    "state": "Configured"
                }))
            }
        },
    )
}

// ── Scheduled Task Tools ───────────────────────────────────────────

/// Build executable scheduled task tools.
pub fn build_scheduled_task_tools(
    cron_scheduler: Arc<tokio::sync::Mutex<Option<crate::cron::CronScheduler>>>,
    config: Arc<ArcSwap<crate::config::GatewayConfig>>,
    config_path: PathBuf,
) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![
        Arc::new(task_list_tool(cron_scheduler.clone())),
        Arc::new(task_create_tool(
            cron_scheduler.clone(),
            config.clone(),
            config_path.clone(),
        )),
        Arc::new(task_cancel_tool(cron_scheduler.clone())),
        Arc::new(task_delete_tool(
            cron_scheduler.clone(),
            config.clone(),
            config_path,
        )),
    ]
}

fn task_list_tool(
    scheduler: Arc<tokio::sync::Mutex<Option<crate::cron::CronScheduler>>>,
) -> FunctionTool {
    FunctionTool::new(
        "task_list",
        "List all scheduled tasks (cron jobs) with their ID, schedule, message, delivery target, and status.",
        move |_ctx: Arc<dyn ToolContext>, _args: Value| {
            let scheduler = scheduler.clone();
            async move {
                let guard = scheduler.lock().await;
                let jobs: Vec<Value> = match guard.as_ref() {
                    Some(sched) => {
                        sched.list_all_jobs().iter().map(|(job, status)| {
                            serde_json::json!({
                                "id": job.id,
                                "schedule": job.schedule,
                                "message": job.message,
                                "delivery": job.deliver_to.as_ref().map(|d| serde_json::json!({
                                    "channel": d.channel,
                                    "target": d.target,
                                })),
                                "status": format!("{:?}", status),
                            })
                        }).collect()
                    }
                    None => vec![],
                };

                Ok(serde_json::json!({
                    "tasks": jobs,
                    "count": jobs.len()
                }))
            }
        },
    )
    .with_read_only(true)
}

fn task_create_tool(
    scheduler: Arc<tokio::sync::Mutex<Option<crate::cron::CronScheduler>>>,
    config: Arc<ArcSwap<crate::config::GatewayConfig>>,
    config_path: PathBuf,
) -> FunctionTool {
    FunctionTool::new(
        "task_create",
        "Create a new scheduled task. Required: id (unique string), schedule (e.g. '@every 5m', '@every 1h'), message (text to send or 'ask:prompt' for agent processing). Optional: delivery (object with 'channel' and 'target' fields).",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let scheduler = scheduler.clone();
            let config = config.clone();
            let config_path = config_path.clone();
            async move {
                let id = args.get("id").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
                let schedule = args.get("schedule").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
                let message = args.get("message").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();

                if id.is_empty() || schedule.is_empty() || message.is_empty() {
                    return Err(adk_core::AdkError::tool(
                        "Required fields: 'id', 'schedule', 'message'".to_string()
                    ));
                }

                let delivery = args.get("delivery").and_then(|d| {
                    let channel = d.get("channel")?.as_str()?.to_string();
                    let target = d.get("target")?.as_str()?.to_string();
                    if channel.is_empty() { return None; }
                    Some(crate::config::CronDelivery { channel, target })
                });

                let suppress_keyword = args.get("suppress_keyword")
                    .and_then(|v| v.as_str())
                    .filter(|s| !s.is_empty())
                    .map(|s| s.to_string());

                let new_job = crate::config::CronJob {
                    id: id.clone(),
                    schedule: schedule.clone(),
                    message: message.clone(),
                    deliver_to: delivery,
                    suppress_keyword,
                    target: None,
                    workspace: None,
                };

                // Persist to config
                let mut cfg = config.load().as_ref().clone();
                if cfg.cron.jobs.iter().any(|j| j.id == id) {
                    return Err(adk_core::AdkError::tool(
                        format!("Task with ID '{}' already exists", id)
                    ));
                }
                cfg.cron.jobs.push(new_job.clone());

                let output = serde_json::to_string_pretty(&cfg)
                    .map_err(|e| adk_core::AdkError::tool(format!("Serialize error: {e}")))?;
                std::fs::write(&config_path, &output)
                    .map_err(|e| adk_core::AdkError::tool(format!("Write error: {e}")))?;

                // Hot-reload
                config.store(std::sync::Arc::new(cfg.clone()));
                let mut guard = scheduler.lock().await;
                if let Some(sched) = guard.as_mut() {
                    sched.reconcile(&cfg.cron.jobs);
                }

                Ok(serde_json::json!({
                    "created": true,
                    "id": id,
                    "schedule": schedule,
                    "message": message
                }))
            }
        },
    )
}

fn task_cancel_tool(
    scheduler: Arc<tokio::sync::Mutex<Option<crate::cron::CronScheduler>>>,
) -> FunctionTool {
    FunctionTool::new(
        "task_cancel",
        "Cancel (pause) a running scheduled task by ID. The task remains in config but stops firing.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let scheduler = scheduler.clone();
            async move {
                let id = args.get("id").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
                if id.is_empty() {
                    return Err(adk_core::AdkError::tool("'id' is required".to_string()));
                }

                let mut guard = scheduler.lock().await;
                if let Some(sched) = guard.as_mut() {
                    sched.cancel(&id);
                }

                Ok(serde_json::json!({
                    "cancelled": true,
                    "id": id
                }))
            }
        },
    )
}

fn task_delete_tool(
    scheduler: Arc<tokio::sync::Mutex<Option<crate::cron::CronScheduler>>>,
    config: Arc<ArcSwap<crate::config::GatewayConfig>>,
    config_path: PathBuf,
) -> FunctionTool {
    FunctionTool::new(
        "task_delete",
        "Permanently delete a scheduled task by ID. Removes it from config and stops it if running.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let scheduler = scheduler.clone();
            let config = config.clone();
            let config_path = config_path.clone();
            async move {
                let id = args.get("id").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
                if id.is_empty() {
                    return Err(adk_core::AdkError::tool("'id' is required".to_string()));
                }

                // Remove from config
                let mut cfg = config.load().as_ref().clone();
                let before = cfg.cron.jobs.len();
                cfg.cron.jobs.retain(|j| j.id != id);

                if cfg.cron.jobs.len() == before {
                    return Err(adk_core::AdkError::tool(
                        format!("Task '{}' not found", id)
                    ));
                }

                let output = serde_json::to_string_pretty(&cfg)
                    .map_err(|e| adk_core::AdkError::tool(format!("Serialize error: {e}")))?;
                std::fs::write(&config_path, &output)
                    .map_err(|e| adk_core::AdkError::tool(format!("Write error: {e}")))?;

                // Hot-reload
                config.store(std::sync::Arc::new(cfg.clone()));
                let mut guard = scheduler.lock().await;
                if let Some(sched) = guard.as_mut() {
                    sched.reconcile(&cfg.cron.jobs);
                }

                Ok(serde_json::json!({
                    "deleted": true,
                    "id": id
                }))
            }
        },
    )
}

// ── Filesystem Tools ───────────────────────────────────────────────

/// Build read-only filesystem tools for the system agent.
pub fn build_filesystem_tools(workspace_root: PathBuf) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![
        Arc::new(fs_pwd_tool(workspace_root.clone())),
        Arc::new(fs_list_tool(workspace_root.clone())),
        Arc::new(fs_tree_tool(workspace_root.clone())),
        Arc::new(fs_read_tool(workspace_root.clone())),
        Arc::new(fs_search_tool(workspace_root)),
    ]
}

/// Build the coding agent delegation tool.
pub fn build_coding_agent_delegation_tool(
    delegator: Arc<crate::coding_agent::delegator::TaskDelegator>,
) -> Arc<dyn adk_core::Tool> {
    Arc::new(FunctionTool::new(
        "delegate_to_coding_agent",
        "Delegate a coding task to a registered coding agent (e.g., Claude Code, Kiro CLI, Codex). The agent executes the task in a real workspace with filesystem access — writing code, running commands, creating files. Use coding_agent_list first to see available agents. NOT for creating new agents — use agent_create for that.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let delegator = delegator.clone();
            async move {
                let agent = args.get("agent")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'agent' field is required (agent ID or alias)"))?;

                let task = args.get("task")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'task' field is required (task description)"))?;

                let workspace = args.get("workspace")
                    .and_then(|v| v.as_str())
                    .map(std::path::PathBuf::from);

                let file_context: Option<Vec<std::path::PathBuf>> = args.get("files")
                    .and_then(|v| v.as_array())
                    .map(|arr| arr.iter().filter_map(|v| v.as_str().map(std::path::PathBuf::from)).collect());

                // Derive the reply target from the calling user's context so the
                // agent's results stream back to the user who requested them.
                // user_id format is "{channel_type}:{sender_id}" (see session_bridge).
                let user_id = ctx.user_id().to_string();
                let (channel_type, channel_id) = match user_id.split_once(':') {
                    Some((ct, id)) => (ct.to_string(), id.to_string()),
                    None => ("internal".to_string(), "system".to_string()),
                };

                let request = crate::coding_agent::models::TaskRequest {
                    description: task.to_string(),
                    trigger: crate::coding_agent::models::TaskTrigger::AgentDelegation {
                        source_agent_id: "system".to_string(),
                    },
                    workspace,
                    file_context,
                    reply_to: crate::coding_agent::models::ReplyTarget {
                        channel_type,
                        channel_id,
                        message_id: None,
                    },
                };

                match delegator.delegate(agent, request).await {
                    Ok(task_id) => Ok(serde_json::json!({
                        "status": "queued",
                        "task_id": task_id,
                        "agent": agent,
                        "message": format!("Task delegated to '{}'. The agent is now working and will stream progress and results directly to this chat. Task ID: {}", agent, task_id)
                    })),
                    Err(e) => Ok(serde_json::json!({
                        "status": "error",
                        "error": format!("{}", e),
                        "agent": agent
                    })),
                }
            }
        },
    ))
}

/// Build the coding agent list tool — lets the LLM discover available coding agents.
pub fn build_coding_agent_list_tool(
    registry: Arc<crate::coding_agent::registry::CodingAgentRegistry>,
) -> Arc<dyn adk_core::Tool> {
    Arc::new(FunctionTool::new(
        "coding_agent_list",
        "List all registered coding agents with their current status. Use this to discover which coding agents are available before delegating tasks. Shows agent ID, alias, backend type, connection status, and workspaces.",
        move |_ctx: Arc<dyn ToolContext>, _args: Value| {
            let registry = registry.clone();
            async move {
                let agents = registry.list_agents();
                let list: Vec<serde_json::Value> = agents.iter().map(|a| {
                    let status_str = match &a.status {
                        crate::coding_agent::status::AgentConnectionStatus::Connected => "connected",
                        crate::coding_agent::status::AgentConnectionStatus::Disconnected { .. } => "disconnected",
                        crate::coding_agent::status::AgentConnectionStatus::Error { .. } => "error",
                        crate::coding_agent::status::AgentConnectionStatus::Unknown => "unknown",
                    };
                    serde_json::json!({
                        "id": a.id,
                        "alias": a.config.alias,
                        "backend_type": a.backend_type,
                        "status": status_str,
                        "workspaces": a.config.workspaces.iter().map(|w| w.display().to_string()).collect::<Vec<_>>(),
                    })
                }).collect();

                if list.is_empty() {
                    Ok(serde_json::json!({
                        "agents": [],
                        "message": "No coding agents registered. The user can add one via the Control Panel at /ui/coding-agents/new"
                    }))
                } else {
                    Ok(serde_json::json!({
                        "agents": list,
                        "count": list.len()
                    }))
                }
            }
        },
    ))
}

/// Build the coding agent task status tool — check if a delegated task is done.
pub fn build_coding_agent_task_status_tool(
    task_history: Arc<crate::coding_agent::history::TaskHistory>,
    history_db: Arc<crate::coding_agent::history_db::PersistentTaskHistory>,
) -> Arc<dyn adk_core::Tool> {
    Arc::new(FunctionTool::new(
        "coding_agent_task_status",
        "Check the status of a previously delegated coding agent task. Returns the current state (queued, running, completed, failed, cancelled) and the output/result if completed. Use this to check on tasks you delegated with delegate_to_coding_agent.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let task_history = task_history.clone();
            let history_db = history_db.clone();
            async move {
                let task_id = args.get("task_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| adk_core::AdkError::tool("'task_id' field is required"))?;

                // Try persistent DB first, then in-memory
                let task = history_db.get_task(&task_id.to_string())
                    .or_else(|| task_history.get_task(&task_id.to_string()));

                match task {
                    Some(entry) => {
                        let (status, output, error) = match &entry.state {
                            crate::coding_agent::models::TaskState::Queued { .. } => {
                                ("queued".to_string(), None, None)
                            }
                            crate::coding_agent::models::TaskState::Running { progress_percent, .. } => {
                                ("running".to_string(), progress_percent.map(|p| format!("{}% complete", p)), None)
                            }
                            crate::coding_agent::models::TaskState::Completed { result, .. } => {
                                ("completed".to_string(), Some(result.output.clone()), None)
                            }
                            crate::coding_agent::models::TaskState::Failed { error, .. } => {
                                let err_msg = format!("{:?}", error);
                                ("failed".to_string(), None, Some(err_msg))
                            }
                            crate::coding_agent::models::TaskState::Cancelled { reason, .. } => {
                                ("cancelled".to_string(), None, Some(format!("{:?}", reason)))
                            }
                        };

                        Ok(serde_json::json!({
                            "task_id": task_id,
                            "agent_id": entry.agent_id,
                            "description": entry.description,
                            "status": status,
                            "output": output,
                            "error": error,
                        }))
                    }
                    None => Ok(serde_json::json!({
                        "task_id": task_id,
                        "status": "not_found",
                        "message": "Task not found. It may have expired from history or the ID is incorrect."
                    })),
                }
            }
        },
    ))
}

// ── Filesystem Tool Parameter Schemas ──────────────────────────────

/// Parameters for fs_list tool.
#[derive(serde::Serialize, JsonSchema)]
struct FsListParams {
    /// Path to list (relative to workspace root or absolute). Use '.' for root.
    path: Option<String>,
    /// Whether to show hidden files (starting with '.'). Default: false.
    show_hidden: Option<bool>,
}

/// Parameters for fs_read tool.
#[derive(serde::Serialize, JsonSchema)]
struct FsReadParams {
    /// Path to the file to read (relative to workspace root or absolute). Required.
    path: String,
}

/// Parameters for fs_tree tool.
#[derive(serde::Serialize, JsonSchema)]
struct FsTreeParams {
    /// Path to show tree for (relative to workspace root or absolute). Default: '.'.
    path: Option<String>,
    /// Maximum depth to recurse (default 2, max 5).
    depth: Option<u64>,
    /// Whether to show hidden files. Default: false.
    show_hidden: Option<bool>,
}

/// Parameters for fs_search tool.
#[derive(serde::Serialize, JsonSchema)]
struct FsSearchParams {
    /// The filename pattern to search for (case-insensitive substring match). Required.
    query: String,
    /// Optional subdirectory path to limit the search scope.
    path: Option<String>,
}

fn fs_pwd_tool(root: PathBuf) -> FunctionTool {
    FunctionTool::new(
        "fs_pwd",
        "Show the current workspace root directory (absolute path). No arguments needed.",
        move |_ctx: Arc<dyn ToolContext>, _args: Value| {
            let root = root.clone();
            async move {
                let abs = root.canonicalize().unwrap_or_else(|_| root.clone());
                Ok(serde_json::json!({
                    "workspace_root": abs.to_string_lossy(),
                }))
            }
        },
    )
    .with_read_only(true)
}

fn fs_list_tool(root: PathBuf) -> FunctionTool {
    FunctionTool::new(
        "fs_list",
        "List files and directories at a given path. Returns names, types (file/dir), and sizes. Path can be relative to workspace root or absolute. Use '.' for the root directory. Supports '..' for parent traversal within the filesystem.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let root = root.clone();
            async move {
                let path_str = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
                let show_hidden = args.get("show_hidden").and_then(|v| v.as_bool()).unwrap_or(false);

                // Support absolute paths or relative to workspace
                let target = if std::path::Path::new(path_str).is_absolute() {
                    PathBuf::from(path_str)
                } else {
                    root.join(path_str)
                };

                let canonical = target.canonicalize().map_err(|e| {
                    adk_core::AdkError::tool(format!("Path not found: {e}"))
                })?;

                let mut entries = Vec::new();
                let read_dir = std::fs::read_dir(&canonical).map_err(|e| {
                    adk_core::AdkError::tool(format!("Cannot read directory: {e}"))
                })?;

                for entry in read_dir.flatten() {
                    let meta = entry.metadata().ok();
                    let name = entry.file_name().to_string_lossy().to_string();

                    // Skip hidden files unless requested, always skip heavy dirs
                    if !show_hidden && name.starts_with('.') {
                        continue;
                    }
                    if name == "node_modules" || name == "target" {
                        continue;
                    }

                    entries.push(serde_json::json!({
                        "name": name,
                        "type": if meta.as_ref().map(|m| m.is_dir()).unwrap_or(false) { "dir" } else { "file" },
                        "size": meta.as_ref().map(|m| m.len()).unwrap_or(0),
                    }));
                }

                entries.sort_by(|a, b| {
                    let a_type = a["type"].as_str().unwrap_or("");
                    let b_type = b["type"].as_str().unwrap_or("");
                    // Directories first, then alphabetical
                    b_type.cmp(a_type).then_with(|| {
                        a["name"].as_str().unwrap_or("").cmp(b["name"].as_str().unwrap_or(""))
                    })
                });

                Ok(serde_json::json!({
                    "path": canonical.to_string_lossy(),
                    "entries": entries,
                    "count": entries.len()
                }))
            }
        },
    )
    .with_read_only(true)
    .with_parameters_schema::<FsListParams>()
}

fn fs_read_tool(root: PathBuf) -> FunctionTool {
    FunctionTool::new(
        "fs_read",
        "Read the contents of a file. Path can be relative to workspace root or absolute. Returns the text content (max 50KB). For binary files, returns a size indicator instead.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let root = root.clone();
            async move {
                let path_str = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
                if path_str.is_empty() {
                    return Err(adk_core::AdkError::tool("'path' is required".to_string()));
                }

                let target = if std::path::Path::new(path_str).is_absolute() {
                    PathBuf::from(path_str)
                } else {
                    root.join(path_str)
                };

                let canonical = target.canonicalize().map_err(|e| {
                    adk_core::AdkError::tool(format!("Path not found: {e}"))
                })?;

                let meta = std::fs::metadata(&canonical).map_err(|e| {
                    adk_core::AdkError::tool(format!("Cannot read file: {e}"))
                })?;

                if meta.is_dir() {
                    return Err(adk_core::AdkError::tool("Path is a directory, use fs_list instead".to_string()));
                }

                // Cap at 50KB to avoid blowing up context
                const MAX_SIZE: u64 = 50 * 1024;
                if meta.len() > MAX_SIZE {
                    return Ok(serde_json::json!({
                        "path": path_str,
                        "truncated": true,
                        "size": meta.len(),
                        "content": std::fs::read_to_string(&canonical)
                            .map(|s| s[..MAX_SIZE as usize].to_string())
                            .unwrap_or_else(|_| format!("[Binary file, {} bytes]", meta.len()))
                    }));
                }

                match std::fs::read_to_string(&canonical) {
                    Ok(content) => Ok(serde_json::json!({
                        "path": path_str,
                        "size": meta.len(),
                        "content": content
                    })),
                    Err(_) => Ok(serde_json::json!({
                        "path": path_str,
                        "size": meta.len(),
                        "content": format!("[Binary file, {} bytes]", meta.len())
                    })),
                }
            }
        },
    )
    .with_read_only(true)
    .with_parameters_schema::<FsReadParams>()
}

fn fs_tree_tool(root: PathBuf) -> FunctionTool {
    FunctionTool::new(
        "fs_tree",
        "Show a directory tree structure with configurable depth. Path can be relative or absolute. Returns an indented tree view of files and directories. Optional 'depth' (default 2, max 5).",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let root = root.clone();
            async move {
                let path_str = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
                let max_depth = args.get("depth").and_then(|v| v.as_u64()).unwrap_or(2).min(5) as usize;
                let show_hidden = args.get("show_hidden").and_then(|v| v.as_bool()).unwrap_or(false);

                let target = if std::path::Path::new(path_str).is_absolute() {
                    PathBuf::from(path_str)
                } else {
                    root.join(path_str)
                };

                let canonical = target.canonicalize().map_err(|e| {
                    adk_core::AdkError::tool(format!("Path not found: {e}"))
                })?;

                if !canonical.is_dir() {
                    return Err(adk_core::AdkError::tool("Path is not a directory".to_string()));
                }

                let mut tree = String::new();
                let mut file_count = 0usize;
                let mut dir_count = 0usize;

                fn walk(
                    dir: &std::path::Path,
                    prefix: &str,
                    depth: usize,
                    max_depth: usize,
                    show_hidden: bool,
                    tree: &mut String,
                    file_count: &mut usize,
                    dir_count: &mut usize,
                ) {
                    if depth >= max_depth { return; }

                    let mut entries: Vec<_> = match std::fs::read_dir(dir) {
                        Ok(rd) => rd.flatten().collect(),
                        Err(_) => return,
                    };
                    entries.sort_by_key(|e| e.file_name());

                    // Filter
                    let entries: Vec<_> = entries.into_iter().filter(|e| {
                        let name = e.file_name().to_string_lossy().to_string();
                        if !show_hidden && name.starts_with('.') { return false; }
                        if name == "node_modules" || name == "target" { return false; }
                        true
                    }).collect();

                    let count = entries.len();
                    for (i, entry) in entries.iter().enumerate() {
                        let is_last = i == count - 1;
                        let connector = if is_last { "└── " } else { "├── " };
                        let name = entry.file_name().to_string_lossy().to_string();
                        let is_dir = entry.metadata().map(|m| m.is_dir()).unwrap_or(false);

                        tree.push_str(&format!("{}{}{}{}\n", prefix, connector, name, if is_dir { "/" } else { "" }));

                        if is_dir {
                            *dir_count += 1;
                            let new_prefix = format!("{}{}", prefix, if is_last { "    " } else { "" });
                            walk(&entry.path(), &new_prefix, depth + 1, max_depth, show_hidden, tree, file_count, dir_count);
                        } else {
                            *file_count += 1;
                        }
                    }
                }

                let root_name = canonical.file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| canonical.to_string_lossy().to_string());
                tree.push_str(&format!("{}/\n", root_name));
                walk(&canonical, "", 0, max_depth, show_hidden, &mut tree, &mut file_count, &mut dir_count);

                Ok(serde_json::json!({
                    "path": canonical.to_string_lossy(),
                    "tree": tree,
                    "directories": dir_count,
                    "files": file_count
                }))
            }
        },
    )
    .with_read_only(true)
    .with_parameters_schema::<FsTreeParams>()
}

fn fs_search_tool(root: PathBuf) -> FunctionTool {
    FunctionTool::new(
        "fs_search",
        "Search for files by name pattern (case-insensitive substring match). Returns matching file paths. Path can be relative or absolute. Optional 'path' to limit search to a subdirectory.",
        move |_ctx: Arc<dyn ToolContext>, args: Value| {
            let root = root.clone();
            async move {
                let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("").to_lowercase();
                if query.is_empty() {
                    return Err(adk_core::AdkError::tool("'query' is required".to_string()));
                }

                let sub_path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
                let search_root = if std::path::Path::new(sub_path).is_absolute() {
                    PathBuf::from(sub_path)
                } else {
                    root.join(sub_path)
                };

                let canonical = search_root.canonicalize().unwrap_or_else(|_| search_root.clone());

                let mut matches = Vec::new();
                let mut stack = vec![canonical.clone()];
                let max_results = 50;

                while let Some(dir) = stack.pop() {
                    if matches.len() >= max_results { break; }

                    let entries = match std::fs::read_dir(&dir) {
                        Ok(e) => e,
                        Err(_) => continue,
                    };

                    for entry in entries.flatten() {
                        let name = entry.file_name().to_string_lossy().to_string();

                        // Skip hidden/noise
                        if name.starts_with('.') || name == "node_modules" || name == "target" {
                            continue;
                        }

                        let path = entry.path();
                        if path.is_dir() {
                            stack.push(path);
                        } else if name.to_lowercase().contains(&query) {
                            matches.push(path.to_string_lossy().to_string());
                            if matches.len() >= max_results { break; }
                        }
                    }
                }

                if matches.is_empty() {
                    Ok(serde_json::json!({
                        "query": query,
                        "matches": [],
                        "count": 0,
                        "message": format!("No files matching '{}' found in '{}'. The search is complete — do not retry with the same query.", query, canonical.to_string_lossy())
                    }))
                } else {
                    Ok(serde_json::json!({
                        "query": query,
                        "matches": matches,
                        "count": matches.len(),
                        "truncated": matches.len() >= max_results
                    }))
                }
            }
        },
    )
    .with_read_only(true)
    .with_parameters_schema::<FsSearchParams>()
}

// ── Channel Tools (send_photo) ─────────────────────────────────────

/// Build channel interaction tools (send_photo, etc.)
pub fn build_channel_tools(
    channel_map: Arc<DashMap<crate::channel::ChannelKey, Arc<dyn crate::channel::Channel>>>,
) -> Vec<Arc<dyn adk_core::Tool>> {
    vec![Arc::new(send_photo_tool(channel_map))]
}

fn send_photo_tool(
    channel_map: Arc<DashMap<crate::channel::ChannelKey, Arc<dyn crate::channel::Channel>>>,
) -> FunctionTool {
    FunctionTool::new(
        "send_photo",
        "Send a photo/image to the user's chat. Provide either a file 'path' (absolute path to an image file on disk) or 'base64' (base64-encoded image data). Optional 'caption' text. The image is sent to the current user's Telegram chat.",
        move |ctx: Arc<dyn ToolContext>, args: Value| {
            let channel_map = channel_map.clone();
            async move {
                let user_id = ctx.user_id().to_string();
                let caption = args.get("caption").and_then(|v| v.as_str()).map(|s| s.to_string());

                // Get image data from either path or base64
                let (data, mime_type) = if let Some(path_str) = args.get("path").and_then(|v| v.as_str()) {
                    let path = std::path::Path::new(path_str);
                    let bytes = std::fs::read(path).map_err(|e| {
                        adk_core::AdkError::tool(format!("Cannot read file '{}': {e}", path_str))
                    })?;
                    let mime = match path.extension().and_then(|e| e.to_str()) {
                        Some("png") => "image/png",
                        Some("jpg") | Some("jpeg") => "image/jpeg",
                        Some("gif") => "image/gif",
                        Some("webp") => "image/webp",
                        _ => "image/png",
                    };
                    (bytes, mime.to_string())
                } else if let Some(b64) = args.get("base64").and_then(|v| v.as_str()) {
                    let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64)
                        .map_err(|e| adk_core::AdkError::tool(format!("Invalid base64: {e}")))?;
                    let mime = args.get("mime_type").and_then(|v| v.as_str()).unwrap_or("image/png").to_string();
                    (bytes, mime)
                } else {
                    return Err(adk_core::AdkError::tool(
                        "Either 'path' (file path) or 'base64' (base64 data) is required".to_string()
                    ));
                };

                // Validate: Telegram rejects photos > 10MB
                const MAX_PHOTO_SIZE: usize = 10 * 1024 * 1024;
                if data.len() > MAX_PHOTO_SIZE {
                    return Err(adk_core::AdkError::tool(
                        format!("Image too large ({} bytes). Telegram limit is 10MB.", data.len())
                    ));
                }

                // Validate: check for valid image magic bytes
                let is_valid_image = data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) // PNG
                    || data.starts_with(&[0xFF, 0xD8, 0xFF]) // JPEG
                    || data.starts_with(b"GIF8") // GIF
                    || data.starts_with(b"RIFF"); // WebP

                if !is_valid_image {
                    // Try to send as document instead if it's not a recognized image format
                    return Err(adk_core::AdkError::tool(
                        "File does not appear to be a valid image (PNG/JPEG/GIF/WebP). Check the file format.".to_string()
                    ));
                }

                // If JPEG and > 5MB, it might fail — truncate quality note
                if data.len() > 5 * 1024 * 1024 && mime_type == "image/jpeg" {
                    tracing::warn!(size = data.len(), "large JPEG may fail Telegram processing");
                }

                // Extract the numeric chat ID from user_id (format: "telegram:12345")
                let chat_id = user_id.split(':').last().unwrap_or(&user_id).to_string();

                // Find the telegram channel and send
                let key = crate::channel::ChannelKey {
                    channel_type: crate::channel::ChannelType::Telegram,
                    account_id: "default".to_string(),
                };

                if let Some(ch) = channel_map.get(&key) {
                    ch.send_photo(&chat_id, &data, &mime_type, caption.as_deref())
                        .await
                        .map_err(|e| adk_core::AdkError::tool(format!("Failed to send photo: {e}")))?;

                    Ok(serde_json::json!({
                        "sent": true,
                        "chat_id": chat_id,
                        "size_bytes": data.len(),
                        "mime_type": mime_type
                    }))
                } else {
                    Err(adk_core::AdkError::tool("No Telegram channel available".to_string()))
                }
            }
        },
    )
}