ai-agent 0.88.0

Idiomatic agent sdk inspired by the claude code source leak
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
// Source: /data/home/swei/claudecode/openclaudecode/src/utils/filePersistence/types.ts
use crate::types::*;
use std::future::Future;

pub use crate::types::{ToolDefinition, ToolInputSchema};

// Schema functions for all tools
fn sleep_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "duration": {
                "type": "number",
                "description": "Duration to sleep in seconds (default: 60)"
            }
        }),
        required: None,
    }
}

fn powershell_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "command": {
                "type": "string",
                "description": "PowerShell command to execute"
            },
            "timeout": {
                "type": "number",
                "description": "Optional timeout in milliseconds (default: 120000, max: 600000)"
            },
            "description": {
                "type": "string",
                "description": "Brief description of what this command does"
            },
            "run_in_background": {
                "type": "boolean",
                "description": "Run the command in the background (default: false)"
            }
        }),
        required: Some(vec!["command".to_string()]),
    }
}

fn monitor_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

fn send_user_file_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

fn web_browser_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

fn brief_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "message": {
                "type": "string",
                "description": "The message for the user. Supports markdown formatting."
            },
            "attachments": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Optional file paths to attach"
            },
            "status": {
                "type": "string",
                "enum": ["normal", "proactive"],
                "description": "Use 'proactive' when surfacing something the user hasn't asked for"
            }
        }),
        required: Some(vec!["message".to_string()]),
    }
}

fn synthetic_output_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

/// A boxed async future that returns a ToolResult or AgentError.
/// This is the standard return type for tool executor functions.
pub type ToolFuture =
    std::pin::Pin<Box<dyn Future<Output = Result<ToolResult, crate::error::AgentError>> + Send>>;

pub trait Tool {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn input_schema(&self) -> ToolInputSchema;
    fn execute(
        &self,
        input: serde_json::Value,
        context: &ToolContext,
    ) -> impl Future<Output = Result<ToolResult, crate::error::AgentError>> + Send;
    /// Backfill observable input before observers see it (SDK stream, transcript, hooks).
    /// Mutates in place to add legacy/derived fields. Must be idempotent.
    /// The original API-bound input is never mutated (preserves prompt cache).
    fn backfill_observable_input(&self, _input: &mut serde_json::Value) {}
}

fn bash_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "command": {
                "type": "string",
                "description": "The command to execute"
            },
            "timeout": {
                "type": "number",
                "description": "Optional timeout in milliseconds"
            },
            "description": {
                "type": "string",
                "description": "Clear, concise description of what this command does in active voice"
            },
            "run_in_background": {
                "type": "boolean",
                "description": "Set to true to run this command in the background. Use Read to read the output later."
            },
            "dangerouslyDisableSandbox": {
                "type": "boolean",
                "description": "Set this to true to dangerously override sandbox mode and run commands without sandboxing."
            }
        }),
        required: Some(vec!["command".to_string()]),
    }
}

fn file_read_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "file_path": {
                "type": "string",
                "description": "The absolute path to the file to read"
            },
            "offset": {
                "type": "integer",
                "description": "The line number to start reading from. Only provide if the file is too large to read at once"
            },
            "limit": {
                "type": "integer",
                "description": "The number of lines to read. Only provide if the file is too large to read at once."
            },
            "pages": {
                "type": "string",
                "description": "Page range for PDF files (e.g., \"1-5\", \"3\", \"10-20\"). Only applicable to PDF files. Maximum 20 pages per request."
            }
        }),
        required: Some(vec!["file_path".to_string()]),
    }
}

fn file_write_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "file_path": {
                "type": "string",
                "description": "The absolute path to the file to write (must be absolute, not relative)"
            },
            "content": {
                "type": "string",
                "description": "The content to write to the file"
            }
        }),
        required: Some(vec!["file_path".to_string(), "content".to_string()]),
    }
}

fn glob_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "pattern": {
                "type": "string",
                "description": "The glob pattern to match files against"
            },
            "path": {
                "type": "string",
                "description": "The directory to search in. If not specified, the current working directory will be used."
            }
        }),
        required: Some(vec!["pattern".to_string()]),
    }
}

fn grep_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "pattern": {
                "type": "string",
                "description": "The regex pattern to search for"
            },
            "path": {
                "type": "string",
                "description": "The file or directory to search in"
            }
        }),
        required: Some(vec!["pattern".to_string()]),
    }
}

fn file_edit_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "file_path": {
                "type": "string",
                "description": "The absolute path to the file to modify"
            },
            "old_string": {
                "type": "string",
                "description": "The exact text to find and replace"
            },
            "new_string": {
                "type": "string",
                "description": "The replacement text"
            },
            "replace_all": {
                "type": "boolean",
                "description": "Replace all occurrences (default false)"
            }
        }),
        required: Some(vec![
            "file_path".to_string(),
            "old_string".to_string(),
            "new_string".to_string(),
        ]),
    }
}

fn notebook_edit_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "notebook_path": {
                "type": "string",
                "description": "The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"
            },
            "cell_id": {
                "type": "string",
                "description": "The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID."
            },
            "new_source": {
                "type": "string",
                "description": "The new source for the cell"
            },
            "cell_type": {
                "type": "string",
                "enum": ["code", "markdown"],
                "description": "The type of the cell (code or markdown). If not specified, defaults to the current cell type."
            },
            "edit_mode": {
                "type": "string",
                "enum": ["replace", "insert", "delete"],
                "description": "The type of edit to make (replace, insert, delete). Defaults to replace."
            }
        }),
        required: Some(vec!["notebook_path".to_string(), "new_source".to_string()]),
    }
}

fn web_fetch_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "url": {
                "type": "string",
                "description": "The URL to fetch content from"
            },
            "headers": {
                "type": "object",
                "description": "Optional HTTP headers",
                "additionalProperties": {
                    "type": "string"
                }
            },
            "prompt": {
                "type": "string",
                "description": "Optional prompt for LLM-based content extraction"
            }
        }),
        required: Some(vec!["url".to_string()]),
    }
}

fn web_search_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "query": {
                "type": "string",
                "description": "The search query to use"
            },
            "allowed_domains": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Only include search results from these domains"
            },
            "blocked_domains": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Never include search results from these domains"
            }
        }),
        required: Some(vec!["query".to_string()]),
    }
}

const ALL_TOOLS: &[(&str, &str, fn() -> ToolDefinition)] = &[
    ("Bash", "Execute shell commands", || ToolDefinition {
        name: "Bash".to_string(),
        description: "Execute shell commands".to_string(),
        input_schema: bash_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("Read", "Read files, images, PDFs, notebooks", || {
        ToolDefinition {
            name: "Read".to_string(),
            description: "Read files from filesystem. Supports text files, images (PNG, JPG, GIF, WebP), PDFs, and Jupyter notebooks. Use offset and limit for large files.".to_string(),
            input_schema: file_read_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: Some(false),
            always_load: Some(true),
            is_mcp: None,
            search_hint: Some("read files, images, PDFs, notebooks".to_string()),
        aliases: None,
    user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("Write", "Write content to files", || ToolDefinition {
        name: "Write".to_string(),
        description: "Write content to files".to_string(),
        input_schema: file_write_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("Glob", "Find files by name pattern or wildcard", || {
        ToolDefinition {
            name: "Glob".to_string(),
            description: "Find files by glob pattern (glob pattern matching for file discovery)"
                .to_string(),
            input_schema: glob_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: Some(false),
            always_load: Some(true),
            is_mcp: None,
            search_hint: Some("find files by name pattern or wildcard".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("Grep", "Search file contents using regex", || {
        ToolDefinition {
        name: "Grep".to_string(),
        description: "Search file contents using regex patterns. Uses ripgrep (rg) if available, falls back to grep.".to_string(),
        input_schema: grep_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: Some(false),
        always_load: Some(true),
        is_mcp: None,
        search_hint: Some("search file contents using regex".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
    }),
    (
        "FileEdit",
        "Edit files by performing exact string replacements",
        || ToolDefinition {
            name: "FileEdit".to_string(),
            description: "Edit files by performing exact string replacements".to_string(),
            input_schema: file_edit_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "NotebookEdit",
        "Edit Jupyter notebook cells (.ipynb)",
        || ToolDefinition {
            name: "NotebookEdit".to_string(),
            description:
                "Edit Jupyter notebook (.ipynb) cells: replace, insert, or delete cell content"
                    .to_string(),
            input_schema: notebook_edit_schema(),
            annotations: None,
            should_defer: Some(true),
            always_load: None,
            is_mcp: None,
            search_hint: Some("edit Jupyter notebook cells (.ipynb)".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "WebFetch",
        "Fetch content from a URL and return it as text",
        || {
            ToolDefinition {
        name: "WebFetch".to_string(),
        description: "Fetch content from a URL and return it as text. Supports HTML pages, JSON APIs, and plain text. Strips HTML tags for readability. Preapproved hosts can be fetched without additional permission.".to_string(),
        input_schema: web_fetch_schema(),
        annotations: None,
        should_defer: Some(true),
        always_load: None,
        is_mcp: None,
        search_hint: Some("fetch web pages and URLs".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
        },
    ),
    ("WebSearch", "Search the web for information", || {
        ToolDefinition {
        name: "WebSearch".to_string(),
        description: "Search the web for information. Returns search results with titles, URLs, and snippets.".to_string(),
        input_schema: web_search_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: Some(true),
        always_load: None,
        is_mcp: None,
        search_hint: Some("web search for information".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
    }),
    (
        "Agent",
        "Launch a new agent to handle complex multi-step tasks",
        || {
            ToolDefinition {
        name: "Agent".to_string(),
        description: "Launch a new agent to handle complex, multi-step tasks autonomously. Use this tool to spawn specialized subagents.".to_string(),
        input_schema: agent_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
        },
    ),
    ("TaskCreate", "Create a new task in the task list", || {
        ToolDefinition {
            name: "TaskCreate".to_string(),
            description: "Create a new task in the task list".to_string(),
            input_schema: task_create_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("TaskList", "List all tasks in the task list", || {
        ToolDefinition {
            name: "TaskList".to_string(),
            description: "List all tasks in the task list".to_string(),
            input_schema: task_list_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("TaskUpdate", "Update an existing task", || ToolDefinition {
        name: "TaskUpdate".to_string(),
        description: "Update an existing task's status or details".to_string(),
        input_schema: task_update_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("TaskGet", "Get details of a specific task", || {
        ToolDefinition {
            name: "TaskGet".to_string(),
            description: "Get details of a specific task by ID".to_string(),
            input_schema: task_get_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    (
        "TeamCreate",
        "Create a team of agents for parallel work",
        || ToolDefinition {
            name: "TeamCreate".to_string(),
            description: "Create a team of agents that can work in parallel".to_string(),
            input_schema: team_create_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    ("TeamDelete", "Delete a team of agents", || ToolDefinition {
        name: "TeamDelete".to_string(),
        description: "Delete a previously created team".to_string(),
        input_schema: team_delete_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("SendMessage", "Send a message to another agent", || {
        ToolDefinition {
            name: "SendMessage".to_string(),
            description: "Send a message to another agent".to_string(),
            input_schema: send_message_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("EnterWorktree", "Create and enter a git worktree", || {
        ToolDefinition {
            name: "EnterWorktree".to_string(),
            description: "Create and enter a git worktree for isolated work".to_string(),
            input_schema: enter_worktree_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    (
        "ExitWorktree",
        "Exit a worktree and return to original directory",
        || ToolDefinition {
            name: "ExitWorktree".to_string(),
            description: "Exit a worktree and return to the original working directory".to_string(),
            input_schema: exit_worktree_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    ("EnterPlanMode", "Enter structured planning mode", || {
        ToolDefinition {
            name: "EnterPlanMode".to_string(),
            description: "Enter structured planning mode to explore and design implementation"
                .to_string(),
            input_schema: enter_plan_mode_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("ExitPlanMode", "Exit planning mode", || ToolDefinition {
        name: "ExitPlanMode".to_string(),
        description: "Exit planning mode and present the plan for approval".to_string(),
        input_schema: exit_plan_mode_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    (
        "AskUserQuestion",
        "Ask the user a question with multiple choice options",
        || ToolDefinition {
            name: "AskUserQuestion".to_string(),
            description: "Ask the user a question with multiple choice options".to_string(),
            input_schema: ask_user_question_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    ("ToolSearch", "Search for available tools", || {
        ToolDefinition {
            name: "ToolSearch".to_string(),
            description: "Search for available tools by name or description".to_string(),
            input_schema: tool_search_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("CronCreate", "Create a scheduled task", || ToolDefinition {
        name: "CronCreate".to_string(),
        description: "Create a scheduled task that runs on a cron schedule".to_string(),
        input_schema: cron_create_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("CronDelete", "Delete a scheduled task", || ToolDefinition {
        name: "CronDelete".to_string(),
        description: "Delete a previously created scheduled task".to_string(),
        input_schema: cron_delete_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("CronList", "List all scheduled tasks", || ToolDefinition {
        name: "CronList".to_string(),
        description: "List all scheduled tasks".to_string(),
        input_schema: cron_list_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("Config", "Read or update configuration", || {
        ToolDefinition {
            name: "Config".to_string(),
            description: "Read or update dynamic configuration".to_string(),
            input_schema: config_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("TodoWrite", "Manage the session task checklist", || {
        ToolDefinition {
            name: "TodoWrite".to_string(),
            description:
                "Update the todo list for this session. Provide the complete updated list of todos."
                    .to_string(),
            input_schema: todo_write_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: Some(true),
            always_load: None,
            is_mcp: None,
            search_hint: Some("manage the session task checklist".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("Skill", "Invoke a skill by name", || {
        ToolDefinition {
        name: "Skill".to_string(),
        description: "Invoke a skill by name. Skills are pre-built workflows or commands that can be executed to accomplish specific tasks.".to_string(),
        input_schema: skill_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: Some("invoke skills and workflows".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
    }),
    ("TaskStop", "Stop a running background task", || {
        ToolDefinition {
        name: "TaskStop".to_string(),
        description: "Stop a running background task by ID. Also accepts shell_id for backward compatibility with the deprecated KillShell tool.".to_string(),
        input_schema: task_stop_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: Some(true),
        always_load: None,
        is_mcp: None,
        search_hint: Some("kill a running background task".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
    }),
    ("TaskOutput", "Retrieve output from background tasks", || {
        ToolDefinition {
        name: "TaskOutput".to_string(),
        description: "Retrieve output from a running or completed background task (bash command, agent, etc.). Supports blocking wait for completion with configurable timeout.".to_string(),
        input_schema: task_output_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: Some("get task output and results".to_string()),
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
    }),
    ("Monitor", "Monitor system resources", || ToolDefinition {
        name: "Monitor".to_string(),
        description: "Monitor system resources and performance".to_string(),
        input_schema: monitor_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    ("send_user_file", "Send a file from user to agent", || {
        ToolDefinition {
            name: "send_user_file".to_string(),
            description: "Send a file from the user to the agent".to_string(),
            input_schema: send_user_file_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    ("WebBrowser", "Control a web browser", || ToolDefinition {
        name: "WebBrowser".to_string(),
        description: "Control a web browser for automation".to_string(),
        input_schema: web_browser_schema(),
        annotations: None,
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
        aliases: None,
        user_facing_name: None,
        interrupt_behavior: None,
    }),
    (
        "LSP",
        "Code intelligence via Language Server Protocol",
        || {
            ToolDefinition {
        name: "LSP".to_string(),
        description: "Interact with Language Server Protocol servers for code intelligence (definitions, references, symbols, hover, call hierarchy)".to_string(),
        input_schema: lsp_schema(),
        annotations: Some(ToolAnnotations::concurrency_safe()),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: None,
    aliases: None,
    user_facing_name: None,
        interrupt_behavior: None,
    }
        },
    ),
    (
        "RemoteTrigger",
        "Manage remote Claude Code agents via CCR API",
        || ToolDefinition {
            name: "RemoteTrigger".to_string(),
            description:
                "Manage scheduled remote Claude Code agents (triggers) via the claude.ai CCR API"
                    .to_string(),
            input_schema: remote_trigger_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    ("ListMcpResourcesTool", "List MCP server resources", || {
        ToolDefinition {
            name: "ListMcpResourcesTool".to_string(),
            description: "List available resources from configured MCP servers".to_string(),
            input_schema: list_mcp_resources_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        }
    }),
    (
        "ReadMcpResourceTool",
        "Read MCP server resources by URI",
        || ToolDefinition {
            name: "ReadMcpResourceTool".to_string(),
            description: "Read a specific resource from an MCP server by URI".to_string(),
            input_schema: read_mcp_resource_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "MCPTool",
        "Execute a tool on an MCP server",
        || ToolDefinition {
            name: "MCPTool".to_string(),
            description: "Execute a tool on an MCP server. MCP tools define their own schemas and are registered dynamically.".to_string(),
            input_schema: mcp_tool_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: Some(true),
            search_hint: Some("execute MCP server tools".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "McpAuth",
        "Authenticate an MCP server",
        || ToolDefinition {
            name: "McpAuth".to_string(),
            description: "Authenticate an MCP server that requires OAuth. Returns an authorization URL for the user to complete the flow.".to_string(),
            input_schema: mcp_auth_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: Some(true),
            search_hint: Some("authenticate MCP server OAuth".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "SendUserMessage",
        "Send a message to the user",
        || ToolDefinition {
            name: "SendUserMessage".to_string(),
            description: "Send a message to the user that they will actually read. Text outside this tool is visible in the detail view, but most won't open it -- the answer lives here.".to_string(),
            input_schema: brief_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: Some("send message to user".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "StructuredOutput",
        "Return structured output in the requested format",
        || ToolDefinition {
            name: "StructuredOutput".to_string(),
            description: "Return structured output in the requested format. You MUST call this tool exactly once at the end of your response to provide the structured output.".to_string(),
            input_schema: synthetic_output_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: Some("return the final response as structured JSON".to_string()),
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "Sleep",
        "Wait for a specified duration",
        || ToolDefinition {
            name: "Sleep".to_string(),
            description: "Wait for a specified duration. The user can interrupt the sleep at any time. Prefer this over Bash(sleep ...) — it doesn't hold a shell process.".to_string(),
            input_schema: sleep_schema(),
            annotations: Some(ToolAnnotations::concurrency_safe()),
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "PowerShell",
        "Execute PowerShell commands",
        || ToolDefinition {
            name: "PowerShell".to_string(),
            description: "Execute a PowerShell command. Windows-only tool for PowerShell cmdlets and native executable execution".to_string(),
            input_schema: powershell_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "OverflowTest",
        "Test overflow behavior",
        || ToolDefinition {
            name: "OverflowTest".to_string(),
            description: "Test overflow behavior (not implemented)".to_string(),
            input_schema: overflow_test_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "ReviewArtifact",
        "Review artifacts",
        || ToolDefinition {
            name: "ReviewArtifact".to_string(),
            description: "Review artifacts (not implemented)".to_string(),
            input_schema: review_artifact_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "Workflow",
        "Manage workflows",
        || ToolDefinition {
            name: "Workflow".to_string(),
            description: "Manage workflows (not implemented)".to_string(),
            input_schema: workflow_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "Snip",
        "Compaction tool",
        || ToolDefinition {
            name: "Snip".to_string(),
            description: "Model-callable compaction tool (not implemented)".to_string(),
            input_schema: snip_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "DiscoverSkills",
        "Discover available skills",
        || ToolDefinition {
            name: "DiscoverSkills".to_string(),
            description: "On-demand skill discovery (not implemented)".to_string(),
            input_schema: discover_skills_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
    (
        "TerminalCapture",
        "Capture terminal screen",
        || ToolDefinition {
            name: "TerminalCapture".to_string(),
            description: "Terminal screen capture (not implemented)".to_string(),
            input_schema: terminal_capture_schema(),
            annotations: None,
            should_defer: None,
            always_load: None,
            is_mcp: None,
            search_hint: None,
            aliases: None,
            user_facing_name: None,
            interrupt_behavior: None,
        },
    ),
];

fn agent_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "description": {
                "type": "string",
                "description": "A short description (3-5 words) summarizing what the agent will do"
            },
            "subagent_type": {
                "type": "string",
                "description": "The type of subagent to use. If omitted, uses the general-purpose agent."
            },
            "prompt": {
                "type": "string",
                "description": "The task prompt for the subagent to execute"
            },
            "model": {
                "type": "string",
                "description": "Optional model override for this subagent"
            },
            "max_turns": {
                "type": "number",
                "description": "Maximum number of turns for this subagent (default: 10)"
            },
            "run_in_background": {
                "type": "boolean",
                "description": "Whether to run the agent in the background (default: false)"
            },
            "isolation": {
                "type": "string",
                "enum": ["worktree", "remote"],
                "description": "Isolation mode: 'worktree' for git worktree, 'remote' for remote CCR"
            }
        }),
        required: Some(vec!["description".to_string(), "prompt".to_string()]),
    }
}

// Task tool schemas
fn task_create_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "subject": { "type": "string", "description": "A brief title for the task" },
            "description": { "type": "string", "description": "What needs to be done" },
            "activeForm": { "type": "string", "description": "Present continuous form shown in spinner when in_progress (e.g., \"Running tests\")" },
            "metadata": {
                "type": "object",
                "description": "Arbitrary metadata to attach to the task"
            }
        }),
        required: Some(vec!["subject".to_string(), "description".to_string()]),
    }
}

fn task_list_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

fn task_update_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "taskId": { "type": "string", "description": "The ID of the task to update" },
            "subject": { "type": "string", "description": "New subject for the task" },
            "description": { "type": "string", "description": "New description for the task" },
            "status": { "type": "string", "enum": ["pending", "in_progress", "completed", "deleted"], "description": "New status for the task" },
            "activeForm": { "type": "string", "description": "Present continuous form shown in spinner when in_progress (e.g., \"Running tests\")" },
            "addBlocks": { "type": "array", "items": {"type": "string"}, "description": "Task IDs that this task blocks" },
            "addBlockedBy": { "type": "array", "items": {"type": "string"}, "description": "Task IDs that block this task" },
            "owner": { "type": "string", "description": "New owner for the task" },
            "metadata": {
                "type": "object",
                "description": "Metadata keys to merge into the task. Set a key to null to delete it."
            }
        }),
        required: Some(vec!["taskId".to_string()]),
    }
}

fn task_get_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "taskId": { "type": "string", "description": "The ID of the task to retrieve" }
        }),
        required: Some(vec!["taskId".to_string()]),
    }
}

// Team tool schemas
fn team_create_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "name": { "type": "string", "description": "Name of the team" },
            "description": { "type": "string", "description": "Description of what the team does" },
            "agents": { "type": "array", "items": serde_json::json!({}), "description": "List of agents in the team" }
        }),
        required: Some(vec!["name".to_string()]),
    }
}

fn team_delete_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "name": { "type": "string", "description": "Name of the team to delete" }
        }),
        required: Some(vec!["name".to_string()]),
    }
}

fn send_message_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "to": { "type": "string", "description": "Agent name to send message to" },
            "message": { "type": "string", "description": "Message content" }
        }),
        required: Some(vec!["to".to_string(), "message".to_string()]),
    }
}

// Worktree tool schemas
fn enter_worktree_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "name": { "type": "string", "description": "Optional name for the worktree" }
        }),
        required: None,
    }
}

fn exit_worktree_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "action": { "type": "string", "enum": ["keep", "remove"], "description": "What to do with the worktree" },
            "discardChanges": { "type": "boolean", "description": "Discard uncommitted changes before removing" }
        }),
        required: None,
    }
}

// Plan mode tool schemas
fn enter_plan_mode_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "allowedPrompts": { "type": "array", "items": { "type": "string" }, "description": "Prompt-based permissions" }
        }),
        required: None,
    }
}

fn exit_plan_mode_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// Ask user question schema
fn ask_user_question_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "question": { "type": "string", "description": "The complete question to ask the user" },
            "header": { "type": "string", "description": "Very short label displayed as a chip/tag (max 12 chars)" },
            "options": { "type": "array", "items": serde_json::json!({}), "description": "Available choices for this question. Must have 2-4 options." },
            "multiSelect": { "type": "boolean", "description": "Set to true to allow the user to select multiple options instead of just one" },
            "preview": { "type": "object", "properties": { "type": { "type": "string", "enum": ["html", "markdown"] }, "content": { "type": "string" } }, "description": "Optional HTML or Markdown preview to show the user alongside the question" }
        }),
        required: Some(vec![
            "question".to_string(),
            "header".to_string(),
            "options".to_string(),
        ]),
    }
}

// ToolSearch schema
fn tool_search_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "query": { "type": "string", "description": "Query to find deferred tools. Use \"select:<tool_name>\" for direct selection, or keywords to search." },
            "max_results": { "type": "number", "description": "Maximum number of results to return (default: 5)" }
        }),
        required: Some(vec!["query".to_string()]),
    }
}

// TaskStop schema
fn task_stop_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "task_id": { "type": "string", "description": "The ID of the background task to stop" },
            "shell_id": { "type": "string", "description": "Deprecated: use task_id instead" }
        }),
        required: None,
    }
}

// TaskOutput schema
fn task_output_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "task_id": { "type": "string", "description": "The task ID to get output from" },
            "block": { "type": "boolean", "description": "Whether to wait for completion. Default: true" },
            "timeout": { "type": "number", "description": "Max wait time in ms. Default: 30000, max: 600000" }
        }),
        required: Some(vec!["task_id".to_string()]),
    }
}

// Cron tool schemas
fn cron_create_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "cron": { "type": "string", "description": "5-field cron expression" },
            "prompt": { "type": "string", "description": "The prompt to execute" },
            "recurring": { "type": "boolean", "description": "true = repeat, false = one-shot" },
            "durable": { "type": "boolean", "description": "true = persist across restarts" }
        }),
        required: Some(vec!["cron".to_string(), "prompt".to_string()]),
    }
}

fn cron_delete_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "id": { "type": "string", "description": "Job ID returned by CronCreate" }
        }),
        required: Some(vec!["id".to_string()]),
    }
}

fn cron_list_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// Config schema
fn config_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "action": { "type": "string", "enum": ["get", "set", "list"], "description": "Action to perform" },
            "key": { "type": "string", "description": "Configuration key" },
            "value": { "type": "string", "description": "Configuration value" }
        }),
        required: Some(vec!["action".to_string()]),
    }
}

// TodoWrite schema
fn todo_write_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "todos": { "type": "array", "items": serde_json::json!({}), "description": "List of todo items" }
        }),
        required: Some(vec!["todos".to_string()]),
    }
}

// Skill schema
fn skill_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "skill": { "type": "string", "description": "The name of the skill to invoke" }
        }),
        required: Some(vec!["skill".to_string()]),
    }
}

// LSP tool schema
fn lsp_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "operation": {
                "type": "string",
                "enum": ["goToDefinition", "findReferences", "hover", "documentSymbol", "workspaceSymbol", "goToImplementation", "prepareCallHierarchy", "incomingCalls", "outgoingCalls"],
                "description": "The LSP operation to perform"
            },
            "filePath": { "type": "string", "description": "The file to operate on" },
            "line": { "type": "integer", "description": "Line number (1-based)" },
            "character": { "type": "integer", "description": "Character offset (1-based)" }
        }),
        required: Some(vec!["operation".to_string(), "filePath".to_string()]),
    }
}

// RemoteTrigger tool schema
fn remote_trigger_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "action": { "type": "string", "enum": ["list", "get", "create", "update", "run"], "description": "The action to perform" },
            "trigger_id": { "type": "string", "description": "Required for get, update, and run" },
            "body": { "type": "object", "description": "JSON body for create and update" }
        }),
        required: Some(vec!["action".to_string()]),
    }
}

// ListMcpResourcesTool schema
fn list_mcp_resources_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "server": { "type": "string", "description": "Optional server name to filter resources by" }
        }),
        required: None,
    }
}

// ReadMcpResourceTool schema
fn read_mcp_resource_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "server": { "type": "string", "description": "The MCP server name" },
            "uri": { "type": "string", "description": "The resource URI to read" }
        }),
        required: Some(vec!["server".to_string(), "uri".to_string()]),
    }
}

// MCPTool schema (generic MCP tool execution)
fn mcp_tool_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "server": {
                "type": "string",
                "description": "The MCP server name"
            },
            "tool": {
                "type": "string",
                "description": "The tool name to execute on the server"
            },
            "arguments": {
                "type": "object",
                "description": "Arguments to pass to the MCP tool"
            }
        }),
        required: Some(vec!["server".to_string(), "tool".to_string()]),
    }
}

// McpAuthTool schema (authenticate MCP server)
fn mcp_auth_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({
            "server": {
                "type": "string",
                "description": "The MCP server name to authenticate"
            }
        }),
        required: Some(vec!["server".to_string()]),
    }
}

// OverflowTest tool schema
fn overflow_test_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// ReviewArtifact tool schema
fn review_artifact_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// Workflow tool schema
fn workflow_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// Snip tool schema
fn snip_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// DiscoverSkills tool schema
fn discover_skills_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

// TerminalCapture tool schema
fn terminal_capture_schema() -> ToolInputSchema {
    ToolInputSchema {
        schema_type: "object".to_string(),
        properties: serde_json::json!({}),
        required: None,
    }
}

pub fn get_all_base_tools() -> Vec<ToolDefinition> {
    ALL_TOOLS.iter().map(|f| f.2()).collect()
}

pub fn filter_tools(
    tools: Vec<ToolDefinition>,
    allowed: Option<Vec<String>>,
    disallowed: Option<Vec<String>>,
) -> Vec<ToolDefinition> {
    let mut result = tools;
    if let Some(allowed) = allowed {
        let allowed_set: std::collections::HashSet<_> = allowed.into_iter().collect();
        result.retain(|t| allowed_set.contains(&t.name));
    }
    if let Some(disallowed) = disallowed {
        let disallowed_set: std::collections::HashSet<_> = disallowed.into_iter().collect();
        result.retain(|t| !disallowed_set.contains(&t.name));
    }
    result
}

// --------------------------------------------------------------------------
// Tool Helper Functions (translated from Tool.ts)
// --------------------------------------------------------------------------

/// Tool with metadata for matching
#[derive(Debug, Clone)]
pub struct ToolWithMetadata {
    pub name: String,
    pub aliases: Option<Vec<String>>,
}

/// Checks if a tool matches the given name (primary name or alias)
pub fn tool_matches_name(tool: &ToolWithMetadata, name: &str) -> bool {
    tool.name == name
        || tool
            .aliases
            .as_ref()
            .map_or(false, |a| a.contains(&name.to_string()))
}

/// Finds a tool by name or alias from a list of tools
pub fn find_tool_by_name<'a>(
    tools: &'a [ToolDefinition],
    name: &str,
) -> Option<&'a ToolDefinition> {
    tools.iter().find(|t| t.name == name)
}

/// Tool definition with optional fields (like ToolDef in TypeScript)
pub struct PartialToolDefinition {
    pub name: String,
    pub description: Option<String>,
    pub input_schema: Option<ToolInputSchema>,
    pub aliases: Option<Vec<String>>,
    pub search_hint: Option<String>,
    pub max_result_size_chars: Option<usize>,
    pub should_defer: Option<bool>,
    pub always_load: Option<bool>,
    pub is_enabled: Option<Box<dyn Fn() -> bool + Send + Sync>>,
    pub is_concurrency_safe: Option<Box<dyn Fn(&serde_json::Value) -> bool + Send + Sync>>,
    pub is_read_only: Option<Box<dyn Fn(&serde_json::Value) -> bool + Send + Sync>>,
    pub is_destructive: Option<Box<dyn Fn(&serde_json::Value) -> bool + Send + Sync>>,
    pub interrupt_behavior: Option<Box<dyn Fn() -> InterruptBehavior + Send + Sync>>,
    pub is_search_or_read_command:
        Option<Box<dyn Fn(&serde_json::Value) -> SearchOrReadCommand + Send + Sync>>,
    pub is_open_world: Option<Box<dyn Fn(&serde_json::Value) -> bool + Send + Sync>>,
    pub requires_user_interaction: Option<Box<dyn Fn() -> bool + Send + Sync>>,
    pub is_mcp: Option<bool>,
    pub is_lsp: Option<bool>,
    pub user_facing_name: Option<Box<dyn Fn(Option<&serde_json::Value>) -> String + Send + Sync>>,
}

impl Default for PartialToolDefinition {
    fn default() -> Self {
        Self {
            name: String::new(),
            description: None,
            input_schema: None,
            aliases: None,
            user_facing_name: None,
            search_hint: None,
            max_result_size_chars: None,
            should_defer: None,
            always_load: None,
            is_enabled: None,
            is_concurrency_safe: None,
            is_read_only: None,
            is_destructive: None,
            interrupt_behavior: None,
            is_search_or_read_command: None,
            is_open_world: None,
            requires_user_interaction: None,
            is_mcp: None,
            is_lsp: None,
        }
    }
}

/// Interrupt behavior when user submits new message while tool is running
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum InterruptBehavior {
    /// Stop the tool and discard its result
    Cancel,
    /// Keep running; the new message waits
    Block,
}

impl Default for InterruptBehavior {
    fn default() -> Self {
        InterruptBehavior::Block
    }
}

/// Search or read command result
#[derive(Debug, Clone, Default)]
pub struct SearchOrReadCommand {
    pub is_search: bool,
    pub is_read: bool,
    pub is_list: Option<bool>,
}

/// Build a complete `ToolDefinition` from a partial definition
pub fn build_tool(def: PartialToolDefinition) -> ToolDefinition {
    ToolDefinition {
        name: def.name.clone(),
        description: def.description.unwrap_or_default(),
        input_schema: def.input_schema.unwrap_or_default(),
        annotations: Some(ToolAnnotations {
            read_only: Some(
                def.is_read_only
                    .map_or(false, |f| f(&serde_json::json!({}))),
            ),
            destructive: Some(
                def.is_destructive
                    .as_ref()
                    .map_or(false, |f| f(&serde_json::json!({}))),
            ),
            concurrency_safe: Some(
                def.is_concurrency_safe
                    .as_ref()
                    .map_or(false, |f| f(&serde_json::json!({}))),
            ),
            open_world: None,
            idempotent: None,
        }),
        should_defer: None,
        always_load: None,
        is_mcp: None,
        search_hint: def.search_hint,
        aliases: def.aliases,
        user_facing_name: def.user_facing_name.map(|f| f(None)),
        interrupt_behavior: None,
    }
}