lingshu-tools 0.10.0

Tool registry, ToolHandler trait, and 50+ tool implementations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
//! # execute_code — Sandboxed code execution with RPC tool access
//!
//! Programmatic Tool Calling (PTC): the LLM writes a Python script that can
//! call Lingshu tools via RPC, collapsing multi-step tool chains into a
//! single inference turn.
//!
//! Architecture (matches hermes-agent):
//! ```text
//!   execute_code(code)
//!//!       ├── generate lingshu_tools.py (RPC stubs for approved sandbox tools)
//!       ├── start Unix domain socket RPC listener
//!       ├── spawn child:  python3 script.py
//!       │       └── script calls lingshu_tools.web_search() etc.
//!       │               └── RPC over UDS → parent dispatches via ToolRegistry
//!       ├── capture stdout (head+tail, 50KB cap) + stderr (10KB)
//!       └── return JSON { status, output, tool_calls_made, duration_seconds }
//! ```
//!
//! Also supports non-Python languages (JS, TS, Bash, Ruby, Perl, Rust) but
//! these run without RPC tool access (same as before).
//!
//! Security:
//! - Child env is sanitized: API keys/tokens/secrets are stripped
//! - Only 7 tools are exposed via RPC (no skill_manage, no memory etc.)
//! - Tool call limit (50) prevents runaway loops
//! - Process group kill with SIGTERM→SIGKILL escalation

use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
#[cfg(unix)]
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STD};
use serde::Deserialize;
use serde_json::json;

use lingshu_types::{ToolError, ToolSchema};

#[cfg(unix)]
use crate::describe_execution_filesystem;
#[cfg(unix)]
use crate::execution_tmp::{BACKEND_TMP_ROOT, wrap_command_with_tmp_env};
use crate::execution_tmp::{ensure_default_shared_tmp_dir, temp_env_pairs};
#[cfg(unix)]
use crate::registry::ToolRegistry;
use crate::registry::{ToolContext, ToolHandler};
#[cfg(unix)]
use crate::tools::backend_pool::get_or_create_backend;
#[cfg(unix)]
use crate::tools::backends;
use crate::tools::backends::redact_output;

/// Maximum execution time before we kill the subprocess (5 minutes like hermes).
const DEFAULT_TIMEOUT_SECS: u64 = 300;

/// Maximum stdout bytes returned to the LLM (50KB like hermes).
const MAX_STDOUT_BYTES: usize = 50_000;
/// Maximum stderr bytes (10KB like hermes).
const MAX_STDERR_BYTES: usize = 10_000;
/// Max tool calls per script execution.
#[cfg(unix)]
const MAX_TOOL_CALLS: usize = 50;

/// Tools allowed inside the execute_code sandbox.
///
/// First-principles inclusion criteria — a tool is included when ALL of:
///   1. Pure data-access OR idempotent mutation (no irreversible external effects)
///   2. Does not spawn another agent / require interactive user input
///   3. Is NOT self-referential (execute_code must never call execute_code)
///   4. A realistic script genuinely benefits from calling it inline rather
///      than forwarding the raw payload back to the outer agent for handling
///
/// Explicitly EXCLUDED by category:
///   • clarify / checkpoint           — require live user interaction, deadlock in subprocess
///   • execute_code / delegate_task / moa — recursive agent spawning
///   • browser_* / browser_vision     — browser state is stateful & shared with parent
///   • memory_read / memory_write     — persistent user store is parent-owned; scripts
///                                      should not permanently mutate agent memory
///   • send_message                   — external side effect (sends real messages)
///   • manage_cron_jobs / manage_todo_list — agentic scheduling side effects
///   • skill_*                        — skill management from scripts is unsafe
///   • ha_* (Home Assistant)          — controls physical devices; irreversible
///   • mcp_* (MCP client)             — external MCP servers have uncontrolled side effects
///   • text_to_speech / generate_image — generates media files; heavy & side-effecting
///   • kill_process / run_process / list_processes — the parent agent's own process tree
///
/// Tool-by-tool rationale for inclusions:
///   web_search      — read-only; most common scripting need
///   web_extract     — read-only; idempotent HTTP fetch
///   web_crawl       — read-only; multi-page superset of web_extract; without it
///                     scripts must loop web_extract manually with ad-hoc link parsing
///   read_file       — read-only; core file I/O
///   pdf_to_markdown — read-only PDF parsing via EdgeParse; useful for local document analysis
///   write_file      — write; already powerful but script output must go somewhere
///   search_files    — read-only; structural grep
///   patch           — targeted in-place edit; idempotent when re-run with same args
///   terminal        — foreground-only subprocess (background/pty blocked); the parent
///                     agent is still responsible for reviewing output
///   vision_analyze  — media input read; same as read_file but for images; frontier
///                     models (GPT-4.1) import it as `from lingshu_tools import vision_analyze`
///                     — omitting it causes ImportError and silent image-analysis failure
///   transcribe_audio — same reasoning as vision_analyze but for audio; takes a local
///                      file path, returns text; no side effects beyond local I/O
///   session_search  — read-only SQLite FTS5 query over past sessions; lets scripts
///                     retrieve context without pulling entire conversation into prompt
#[cfg(unix)]
const SANDBOX_ALLOWED_TOOLS: &[&str] = &[
    "web_search",
    "web_extract",
    "web_crawl",
    "read_file",
    "pdf_to_markdown",
    "write_file",
    "search_files",
    "patch",
    "terminal",
    "vision_analyze",
    "transcribe_audio",
    "session_search",
];

/// Terminal parameters that must not be used from sandbox scripts.
#[cfg(unix)]
const TERMINAL_BLOCKED_PARAMS: &[&str] = &["background", "check_interval", "pty", "watch_patterns"];

pub struct ExecuteCodeToolReal;

#[derive(Deserialize)]
struct ExecuteCodeArgs {
    /// For Python, this is optional (defaults to "python").
    /// For other languages, required.
    #[serde(default = "default_language")]
    language: String,
    code: String,
    #[serde(default)]
    timeout: Option<u64>,
}

fn default_language() -> String {
    "python".to_string()
}

/// Map language name → (runtime command, file extension).
fn resolve_runtime(lang: &str) -> Option<(&'static str, &'static str)> {
    match lang.to_lowercase().as_str() {
        "python" | "python3" | "py" => Some(("python3", ".py")),
        "javascript" | "js" | "node" => Some(("node", ".js")),
        "typescript" | "ts" => Some(("npx tsx", ".ts")),
        "bash" | "sh" | "shell" => Some(("bash", ".sh")),
        "ruby" | "rb" => Some(("ruby", ".rb")),
        "perl" | "pl" => Some(("perl", ".pl")),
        "rust" | "rs" => Some(("rustc_run", ".rs")), // special: compile+run
        _ => None,
    }
}

// ─── RPC stub generator ─────────────────────────────────────────────

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RpcTransport {
    Uds,
    File,
}

/// Generate the `lingshu_tools.py` module that child scripts import.
/// Each stub function sends an RPC request over a Unix domain socket
/// back to the parent process, which dispatches through the ToolRegistry.
#[cfg(unix)]
fn generate_tools_module(available_tools: &[&str], transport: RpcTransport) -> String {
    let mut stubs = String::new();
    let available_set: std::collections::HashSet<&str> = available_tools.iter().copied().collect();

    for &tool in SANDBOX_ALLOWED_TOOLS {
        if !available_set.contains(tool) {
            stubs.push_str(&format!(
                r#"
def {tool}(*args, **kwargs):
    raise RuntimeError("Tool '{tool}' is not available in this execute_code session. Available: " + ", ".join(AVAILABLE_TOOLS))
"#
            ));
            continue;
        }
        let stub = match tool {
            "web_search" => {
                r#"
def web_search(query: str, max_results: int = 5, backend: str = None):
    """Search the web. Returns {"query", "backend", "results":[{"url","title","description"}]}."""
    args = {"query": query, "max_results": max_results}
    if backend is not None:
        args["backend"] = backend
    return _call("web_search", args)
"#
            }
            "web_extract" => {
                r#"
def web_extract(url: str, max_chars: int = 8000, backend: str = None, render_js_fallback: bool = True):
    """Extract one URL. Returns {"backend","result":{"url","title","content","extractor","content_type","content_format"}}."""
    args = {"url": url, "max_chars": max_chars, "render_js_fallback": render_js_fallback}
    if backend is not None:
        args["backend"] = backend
    return _call("web_extract", args)
"#
            }
            "web_crawl" => {
                r#"
def web_crawl(url: str, instructions: str = None, max_pages: int = 8, max_depth: int = 2, max_chars_per_page: int = 4000, same_path_only: bool = False, backend: str = None, render_js_fallback: bool = True):
    """Recursively crawl a website starting from a URL.
    Returns {"success", "backend", "pages_visited", "results":[{"url","title","depth","content","extractor","content_type","content_format"}]}.
    Use instructions to focus on specific content (e.g. 'find API docs').
    Prefer this over looping web_extract when you need multiple linked pages.
    """
    args = {"url": url, "max_pages": max_pages, "max_depth": max_depth,
            "max_chars_per_page": max_chars_per_page, "same_path_only": same_path_only,
            "render_js_fallback": render_js_fallback}
    if instructions is not None:
        args["instructions"] = instructions
    if backend is not None:
        args["backend"] = backend
    return _call("web_crawl", args)
"#
            }
            "read_file" => {
                r#"
def read_file(path: str, offset: int = 1, limit: int = 500):
    """Read a file (1-indexed lines). Returns dict with "content" and "total_lines"."""
    return _call("read_file", {"path": path, "offset": offset, "limit": limit})
"#
            }
            "pdf_to_markdown" => {
                r#"
def pdf_to_markdown(path: str, output_path: str = None, max_chars: int = 20000):
    """Convert a local PDF file to Markdown using EdgeParse.
    This is fast structural PDF parsing, not OCR.
    Returns {"success", "path", "output_path", "extractor", "parsing_mode", "content_format", "truncated", "total_chars", "markdown"}.
    """
    args = {"path": path, "max_chars": max_chars}
    if output_path is not None:
        args["output_path"] = output_path
    return _call("pdf_to_markdown", args)
"#
            }
            "write_file" => {
                r#"
def write_file(path: str, content: str):
    """Write content to a file (always overwrites). Returns dict with status."""
    return _call("write_file", {"path": path, "content": content})
"#
            }
            "search_files" => {
                r#"
def search_files(pattern: str, target: str = "content", path: str = ".", file_glob: str = None, limit: int = 50, offset: int = 0, output_mode: str = "content", context: int = 0):
    """Search file contents (target="content") or find files by name (target="files"). Returns dict with "matches"."""
    return _call("search_files", {"pattern": pattern, "target": target, "path": path, "file_glob": file_glob, "limit": limit, "offset": offset, "output_mode": output_mode, "context": context})
"#
            }
            "patch" => {
                r#"
def patch(path: str = None, old_string: str = None, new_string: str = None, replace_all: bool = False, mode: str = "replace", patch: str = None):
    """Targeted find-and-replace (mode="replace") or V4A multi-file patches (mode="patch"). Returns dict with status."""
    return _call("patch", {"path": path, "old_string": old_string, "new_string": new_string, "replace_all": replace_all, "mode": mode, "patch": patch})
"#
            }
            "terminal" => {
                r#"
def terminal(command: str, timeout: int = None, workdir: str = None):
    """Run a shell command (foreground only). Returns dict with "output" and "exit_code"."""
    return _call("terminal", {"command": command, "timeout": timeout, "workdir": workdir})
"#
            }
            "vision_analyze" => {
                r#"
def vision_analyze(image_source: str, question: str = "Describe this image in detail.", detail: str = "high"):
    """Analyze a local image file or https:// image URL using the vision LLM.
    image_source: absolute file path (png/jpg/webp/…) or https:// URL.
    Returns dict with "content" containing the model's description.
    Use this for any local image path or remote image URL.
    Do NOT use this for browser screenshots — use browser_vision instead.
    """
    return _call("vision_analyze", {"image_source": image_source, "question": question, "detail": detail})
"#
            }
            "transcribe_audio" => {
                r#"
def transcribe_audio(file_path: str, provider: str = None, model: str = None, language: str = "en"):
    """Transcribe speech from an audio file to text.
    file_path: path to audio file (mp3, mp4, m4a, wav, webm, ogg, etc.).
    provider: 'local' (default, free), 'groq', or 'openai'.
    Returns dict with "text" containing the transcription.
    """
    args = {"file_path": file_path, "language": language}
    if provider is not None:
        args["provider"] = provider
    if model is not None:
        args["model"] = model
    return _call("transcribe_audio", args)
"#
            }
            "session_search" => {
                r#"
def session_search(query: str, limit: int = 10):
    """Search past conversation sessions using full-text search.
    Returns dict with "results" list of {session_id, snippet, timestamp}.
    Use this to retrieve context from earlier conversations.
    """
    return _call("session_search", {"query": query, "limit": limit})
"#
            }
            _ => continue,
        };
        stubs.push_str(stub);
    }

    let header = match transport {
        RpcTransport::Uds => {
            r#""""Auto-generated Lingshu tools RPC stubs."""
import json, os, socket, shlex, time

_sock = None


# ---------------------------------------------------------------------------
# Convenience helpers (avoid common scripting pitfalls)
# ---------------------------------------------------------------------------

def json_parse(text: str):
    """Parse JSON tolerant of control characters (strict=False).
    Use this instead of json.loads() when parsing output from terminal()
    or web_extract() that may contain raw tabs/newlines in strings."""
    return json.loads(text, strict=False)


def shell_quote(s: str) -> str:
    """Shell-escape a string for safe interpolation into commands.
    Use this when inserting dynamic content into terminal() commands:
        terminal(f"echo {shell_quote(user_input)}")
    """
    return shlex.quote(s)


def retry(fn, max_attempts=3, delay=2):
    """Retry a function up to max_attempts times with exponential backoff.
    Use for transient failures (network errors, API rate limits):
        result = retry(lambda: terminal("gh issue list ..."))
    """
    last_err = None
    for attempt in range(max_attempts):
        try:
            return fn()
        except Exception as e:
            last_err = e
            if attempt < max_attempts - 1:
                time.sleep(delay * (2 ** attempt))
    raise last_err


def _connect():
    global _sock
    if _sock is None:
        _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        _sock.connect(os.environ["EDGECRAB_RPC_SOCKET"])
        _sock.settimeout(300)
    return _sock


def _call(tool_name, args):
    """Send a tool call to the parent process and return the parsed result."""
    conn = _connect()
    request = json.dumps({"tool": tool_name, "args": args}) + "\n"
    conn.sendall(request.encode())
    buf = b""
    while True:
        chunk = conn.recv(65536)
        if not chunk:
            raise RuntimeError("Agent process disconnected")
        buf += chunk
        if buf.endswith(b"\n"):
            break
    raw = buf.decode().strip()
    result = json.loads(raw)
    if isinstance(result, str):
        try:
            return json.loads(result)
        except (json.JSONDecodeError, TypeError):
            return result
    return result
"#
        }
        RpcTransport::File => {
            r#""""Auto-generated Lingshu tools RPC stubs (file transport)."""
import json, os, shlex, time

_seq = 0
_RPC_DIR = os.environ.get("EDGECRAB_RPC_DIR", "/tmp/lingshu_rpc")


# ---------------------------------------------------------------------------
# Convenience helpers (avoid common scripting pitfalls)
# ---------------------------------------------------------------------------

def json_parse(text: str):
    """Parse JSON tolerant of control characters (strict=False).
    Use this instead of json.loads() when parsing output from terminal()
    or web_extract() that may contain raw tabs/newlines in strings."""
    return json.loads(text, strict=False)


def shell_quote(s: str) -> str:
    """Shell-escape a string for safe interpolation into commands.
    Use this when inserting dynamic content into terminal() commands:
        terminal(f"echo {shell_quote(user_input)}")
    """
    return shlex.quote(s)


def retry(fn, max_attempts=3, delay=2):
    """Retry a function up to max_attempts times with exponential backoff.
    Use for transient failures (network errors, API rate limits):
        result = retry(lambda: terminal("gh issue list ..."))
    """
    last_err = None
    for attempt in range(max_attempts):
        try:
            return fn()
        except Exception as e:
            last_err = e
            if attempt < max_attempts - 1:
                time.sleep(delay * (2 ** attempt))
    raise last_err


def _call(tool_name, args):
    """Send a tool call to the parent process and wait for a response file."""
    global _seq
    _seq += 1
    seq_str = f"{_seq:06d}"
    req_file = os.path.join(_RPC_DIR, f"req_{seq_str}")
    res_file = os.path.join(_RPC_DIR, f"res_{seq_str}")

    tmp = req_file + ".tmp"
    with open(tmp, "w") as f:
        json.dump({"tool": tool_name, "args": args, "seq": _seq}, f)
    os.rename(tmp, req_file)

    deadline = time.monotonic() + 300
    poll_interval = 0.05
    while not os.path.exists(res_file):
        if time.monotonic() > deadline:
            raise RuntimeError(f"RPC timeout: no response for {tool_name} after 300s")
        time.sleep(poll_interval)
        poll_interval = min(poll_interval * 1.2, 0.25)

    with open(res_file) as f:
        raw = f.read()

    try:
        os.unlink(res_file)
    except OSError:
        pass

    result = json.loads(raw)
    if isinstance(result, str):
        try:
            return json.loads(result)
        except (json.JSONDecodeError, TypeError):
            return result
    return result
"#
        }
    };

    format!("{header}\nAVAILABLE_TOOLS = {available_tools:?}\n\n{stubs}\n")
}

// ─── RPC server (runs in a tokio task) ──────────────────────────────

/// Accept one client connection and dispatch tool-call requests until
/// the client disconnects or the call limit is reached.
#[cfg(unix)]
async fn rpc_server_loop(
    listener: tokio::net::UnixListener,
    registry: Arc<ToolRegistry>,
    ctx: ToolContext,
    tool_call_counter: Arc<std::sync::atomic::AtomicUsize>,
    allowed_tools: Arc<Vec<String>>,
) {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

    // Wait up to 5s for the child to connect
    let accept_result = tokio::time::timeout(Duration::from_secs(5), listener.accept()).await;
    let stream = match accept_result {
        Ok(Ok((stream, _))) => stream,
        _ => return,
    };

    let (reader, mut writer) = stream.into_split();
    let mut lines = BufReader::new(reader).lines();

    while let Ok(Some(line)) = lines.next_line().await {
        let line = line.trim().to_string();
        if line.is_empty() {
            continue;
        }

        let request: serde_json::Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(e) => {
                let resp = json!({"error": format!("Invalid RPC request: {e}")});
                let _ = writer.write_all(format!("{}\n", resp).as_bytes()).await;
                continue;
            }
        };

        let tool_name = request
            .get("tool")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let mut tool_args = request.get("args").cloned().unwrap_or(json!({}));

        // Enforce allow-list
        if !allowed_tools.contains(&tool_name) {
            let available = allowed_tools.join(", ");
            let resp = json!({
                "error": format!(
                    "Tool '{}' is not available in execute_code. Available: {}",
                    tool_name, available
                )
            });
            let _ = writer.write_all(format!("{}\n", resp).as_bytes()).await;
            continue;
        }

        // Enforce tool call limit
        let count = tool_call_counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if count >= MAX_TOOL_CALLS {
            let resp = json!({
                "error": format!(
                    "Tool call limit reached ({}). No more tool calls allowed.",
                    MAX_TOOL_CALLS
                )
            });
            let _ = writer.write_all(format!("{}\n", resp).as_bytes()).await;
            continue;
        }

        // Strip forbidden terminal parameters
        if tool_name == "terminal"
            && let Some(obj) = tool_args.as_object_mut()
        {
            for param in TERMINAL_BLOCKED_PARAMS {
                obj.remove(*param);
            }
        }

        // Dispatch through the standard tool handler
        let result = match registry.dispatch(&tool_name, tool_args, &ctx).await {
            Ok(output) => output,
            Err(e) => json!({"error": e.to_string()}).to_string(),
        };

        let _ = writer
            .write_all(format!("{}\n", rpc_response_payload(result)).as_bytes())
            .await;
    }
}

#[cfg(unix)]
fn rpc_response_payload(result: String) -> String {
    if serde_json::from_str::<serde_json::Value>(&result).is_ok() {
        result
    } else {
        json!(result).to_string()
    }
}

#[cfg(unix)]
fn maybe_rewrite_terminal_args(
    tool_name: &str,
    tool_args: &mut serde_json::Value,
    default_remote_workdir: Option<&str>,
) {
    if tool_name != "terminal" {
        return;
    }

    let Some(obj) = tool_args.as_object_mut() else {
        return;
    };

    for param in TERMINAL_BLOCKED_PARAMS {
        obj.remove(*param);
    }

    if let Some(workdir) = default_remote_workdir {
        let has_workdir = obj
            .get("workdir")
            .and_then(|value| value.as_str())
            .is_some_and(|value| !value.is_empty());
        if !has_workdir && let Some(command) = obj.get("command").and_then(|value| value.as_str()) {
            obj.insert(
                "command".into(),
                json!(format!(
                    "cd {} && {}",
                    backends::shell_quote(workdir),
                    command
                )),
            );
        }
    }
}

#[cfg(unix)]
struct RemoteRpcLoop {
    backend: Arc<dyn backends::ExecutionBackend>,
    registry: Arc<ToolRegistry>,
    ctx: ToolContext,
    rpc_dir: String,
    tool_call_counter: Arc<std::sync::atomic::AtomicUsize>,
    allowed_tools: Arc<Vec<String>>,
    stop: tokio_util::sync::CancellationToken,
    terminal_default_workdir: Option<String>,
}

#[cfg(unix)]
async fn remote_rpc_poll_loop(loop_ctx: RemoteRpcLoop) {
    while !loop_ctx.stop.is_cancelled() {
        let pending = match loop_ctx
            .backend
            .execute_oneshot(
                &format!(
                    "ls -1 {} 2>/dev/null | grep '^req_' || true",
                    backends::shell_quote(&loop_ctx.rpc_dir)
                ),
                ".",
                Duration::from_secs(10),
                loop_ctx.stop.clone(),
            )
            .await
        {
            Ok(output) if output.exit_code == 0 => output
                .stdout
                .lines()
                .map(str::trim)
                .filter(|line| !line.is_empty() && !line.ends_with(".tmp"))
                .map(|line| format!("{}/{}", loop_ctx.rpc_dir, line))
                .collect::<Vec<_>>(),
            Ok(_) => Vec::new(),
            Err(_) => Vec::new(),
        };

        if pending.is_empty() {
            tokio::select! {
                _ = loop_ctx.stop.cancelled() => break,
                _ = tokio::time::sleep(Duration::from_millis(100)) => {}
            }
            continue;
        }

        for req_file in pending {
            if loop_ctx.stop.is_cancelled() {
                break;
            }

            let read = match loop_ctx
                .backend
                .execute_oneshot(
                    &format!("cat {}", backends::shell_quote(&req_file)),
                    ".",
                    Duration::from_secs(10),
                    loop_ctx.stop.clone(),
                )
                .await
            {
                Ok(output) if output.exit_code == 0 => output.stdout,
                _ => {
                    let _ = loop_ctx
                        .backend
                        .execute_oneshot(
                            &format!("rm -f {}", backends::shell_quote(&req_file)),
                            ".",
                            Duration::from_secs(5),
                            tokio_util::sync::CancellationToken::new(),
                        )
                        .await;
                    continue;
                }
            };

            let request: serde_json::Value = match serde_json::from_str(read.trim()) {
                Ok(value) => value,
                Err(_) => {
                    let _ = loop_ctx
                        .backend
                        .execute_oneshot(
                            &format!("rm -f {}", backends::shell_quote(&req_file)),
                            ".",
                            Duration::from_secs(5),
                            tokio_util::sync::CancellationToken::new(),
                        )
                        .await;
                    continue;
                }
            };

            let tool_name = request
                .get("tool")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let seq = request
                .get("seq")
                .and_then(|v| v.as_u64())
                .unwrap_or_default();
            let mut tool_args = request.get("args").cloned().unwrap_or(json!({}));
            maybe_rewrite_terminal_args(
                &tool_name,
                &mut tool_args,
                loop_ctx.terminal_default_workdir.as_deref(),
            );

            let result = if !loop_ctx.allowed_tools.contains(&tool_name) {
                let available = loop_ctx.allowed_tools.join(", ");
                json!({
                    "error": format!(
                        "Tool '{}' is not available in execute_code. Available: {}",
                        tool_name, available
                    )
                })
                .to_string()
            } else if loop_ctx
                .tool_call_counter
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
                >= MAX_TOOL_CALLS
            {
                json!({
                    "error": format!(
                        "Tool call limit reached ({}). No more tool calls allowed.",
                        MAX_TOOL_CALLS
                    )
                })
                .to_string()
            } else {
                match loop_ctx
                    .registry
                    .dispatch(&tool_name, tool_args, &loop_ctx.ctx)
                    .await
                {
                    Ok(output) => output,
                    Err(e) => json!({"error": e.to_string()}).to_string(),
                }
            };

            let res_file = format!("{}/res_{seq:06}", loop_ctx.rpc_dir);
            let _ = write_remote_file(
                &*loop_ctx.backend,
                &res_file,
                &rpc_response_payload(result),
                loop_ctx.stop.clone(),
            )
            .await;
            let _ = loop_ctx
                .backend
                .execute_oneshot(
                    &format!("rm -f {}", backends::shell_quote(&req_file)),
                    ".",
                    Duration::from_secs(5),
                    tokio_util::sync::CancellationToken::new(),
                )
                .await;
        }
    }
}

// ─── Environment variable filtering ──────────────────────────────────

/// Env var name prefixes considered safe to pass to child processes.
const SAFE_ENV_PREFIXES: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "LANG",
    "LC_",
    "TERM",
    "TMPDIR",
    "TMP",
    "TEMP",
    "SHELL",
    "LOGNAME",
    "XDG_",
    "PYTHONPATH",
    "VIRTUAL_ENV",
    "CONDA",
];

/// Substrings in env var names that indicate secrets — these are stripped.
const SECRET_SUBSTRINGS: &[&str] = &[
    "KEY",
    "TOKEN",
    "SECRET",
    "PASSWORD",
    "CREDENTIAL",
    "PASSWD",
    "AUTH",
];

/// Build a sanitized environment for the child process.
/// Strips API keys/tokens/secrets, keeps safe system vars.
fn build_child_env(sock_path: &str, cwd: &std::path::Path) -> HashMap<String, String> {
    let mut env = HashMap::new();
    let tmp_root = ensure_default_shared_tmp_dir()
        .unwrap_or_else(|_| crate::execution_tmp::default_shared_tmp_dir());

    for (k, v) in std::env::vars() {
        let upper = k.to_uppercase();

        // Block vars with secret-like names
        if SECRET_SUBSTRINGS.iter().any(|s| upper.contains(s)) {
            continue;
        }

        // Allow vars with known safe prefixes
        if SAFE_ENV_PREFIXES.iter().any(|p| upper.starts_with(p)) {
            env.insert(k, v);
        }
    }

    env.insert("EDGECRAB_RPC_SOCKET".into(), sock_path.into());
    env.insert("PYTHONDONTWRITEBYTECODE".into(), "1".into());
    for (k, v) in temp_env_pairs(&tmp_root.to_string_lossy()) {
        env.insert(k, v);
    }

    // Inject timezone if configured
    if let Ok(tz) = std::env::var("EDGECRAB_TIMEZONE")
        && !tz.is_empty()
    {
        env.insert("TZ".into(), tz);
    }

    // Ensure cwd is importable
    let cwd_str = cwd.to_string_lossy().to_string();
    if let Some(existing) = env.get("PYTHONPATH") {
        env.insert("PYTHONPATH".into(), format!("{cwd_str}:{existing}"));
    } else {
        env.insert("PYTHONPATH".into(), cwd_str);
    }

    env
}

#[cfg(unix)]
async fn write_remote_file(
    backend: &dyn backends::ExecutionBackend,
    path: &str,
    content: &str,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<(), ToolError> {
    let encoded = BASE64_STD.encode(content.as_bytes());
    let scratch_path = format!("{path}.b64");
    let parent = std::path::Path::new(path)
        .parent()
        .map(|p| p.to_string_lossy().into_owned())
        .filter(|p| !p.is_empty())
        .unwrap_or_else(|| ".".into());

    backend
        .execute_oneshot(
            &format!(
                "mkdir -p {} && : > {}",
                backends::shell_quote(&parent),
                backends::shell_quote(&scratch_path)
            ),
            ".",
            Duration::from_secs(10),
            cancel.clone(),
        )
        .await?;

    const CHUNK_BYTES: usize = 24_576;
    for chunk in encoded.as_bytes().chunks(CHUNK_BYTES) {
        let chunk = std::str::from_utf8(chunk).map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("Internal base64 encoding error: {e}"),
        })?;
        backend
            .execute_oneshot(
                &format!(
                    "printf '%s' {} >> {}",
                    backends::shell_quote(chunk),
                    backends::shell_quote(&scratch_path)
                ),
                ".",
                Duration::from_secs(30),
                cancel.clone(),
            )
            .await?;
    }

    let decode = backend
        .execute_oneshot(
            &format!(
                "(base64 -d < {} > {} || base64 -D -i {} -o {}) && rm -f {}",
                backends::shell_quote(&scratch_path),
                backends::shell_quote(path),
                backends::shell_quote(&scratch_path),
                backends::shell_quote(path),
                backends::shell_quote(&scratch_path)
            ),
            ".",
            Duration::from_secs(30),
            cancel,
        )
        .await?;

    if decode.exit_code != 0 {
        return Err(ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!(
                "Failed to materialize remote file {}: {}",
                path,
                decode.format(4_000, 2_000)
            ),
        });
    }

    Ok(())
}

#[cfg(unix)]
async fn prepare_remote_sandbox(
    backend: &dyn backends::ExecutionBackend,
    sandbox_id: &str,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<String, ToolError> {
    let command = format!(
        "tmp_root=\"${{TMPDIR:-/tmp}}\"; dir=\"$tmp_root/lingshu_exec_{}\"; mkdir -p \"$dir/rpc\" && printf '%s' \"$dir\"",
        sandbox_id
    );
    let output = backend
        .execute_oneshot(&command, ".", Duration::from_secs(15), cancel)
        .await?;
    if output.exit_code != 0 {
        return Err(ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!(
                "Failed to prepare remote sandbox directory: {}",
                output.format(4_000, 2_000)
            ),
        });
    }

    let path = output.stdout.trim().to_string();
    if path.is_empty() {
        return Err(ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: "Remote backend returned an empty sandbox directory path.".into(),
        });
    }
    Ok(path)
}

#[cfg(unix)]
fn remote_command_for_runtime(
    runtime: &str,
    script_name: &str,
    rpc_dir: Option<&str>,
    tmp_root: &str,
) -> String {
    let env_prefix = if let Some(rpc_dir) = rpc_dir {
        let mut out = format!(
            "EDGECRAB_RPC_DIR={} PYTHONDONTWRITEBYTECODE=1",
            backends::shell_quote(rpc_dir)
        );
        if let Ok(tz) = std::env::var("EDGECRAB_TIMEZONE")
            && !tz.trim().is_empty()
        {
            out.push(' ');
            out.push_str("TZ=");
            out.push_str(&backends::shell_quote(tz.trim()));
        }
        out
    } else {
        String::new()
    };

    let command = match runtime {
        "rustc_run" => format!(
            "rustc {} -o script_bin && ./script_bin",
            backends::shell_quote(script_name)
        ),
        value if value.contains(' ') => {
            let prefix = if env_prefix.is_empty() {
                String::new()
            } else {
                format!("{env_prefix} ")
            };
            format!("{prefix}{value} {}", backends::shell_quote(script_name))
        }
        value => {
            let prefix = if env_prefix.is_empty() {
                String::new()
            } else {
                format!("{env_prefix} ")
            };
            format!("{prefix}{value} {}", backends::shell_quote(script_name))
        }
    };

    wrap_command_with_tmp_env(&command, tmp_root)
}

#[cfg(unix)]
fn process_outcome_from_exit(exit_code: i32) -> ProcessOutcome {
    match exit_code {
        124 => ProcessOutcome::TimedOut,
        130 => ProcessOutcome::Cancelled,
        code => ProcessOutcome::Completed(code),
    }
}

fn render_execute_code_result(
    stdout: String,
    stderr: String,
    outcome: ProcessOutcome,
    tool_calls_made: usize,
    duration: f64,
    timeout_secs: u64,
) -> String {
    match outcome {
        ProcessOutcome::Completed(exit) => {
            let status = if exit == 0 { "success" } else { "error" };
            let mut result = json!({
                "status": status,
                "output": stdout,
                "tool_calls_made": tool_calls_made,
                "duration_seconds": (duration * 100.0).round() / 100.0,
            });

            if exit != 0 {
                if !stderr.is_empty() {
                    result["error"] = json!(stderr);
                    result["output"] = json!(format!("{stdout}\n--- stderr ---\n{stderr}"));
                } else {
                    result["error"] = json!(format!("Script exited with code {exit}"));
                }
            }

            result.to_string()
        }
        ProcessOutcome::TimedOut => json!({
            "status": "timeout",
            "error": format!("Script timed out after {timeout_secs}s and was killed."),
            "output": if stderr.is_empty() { stdout } else { format!("{stdout}\n--- stderr ---\n{stderr}") },
            "tool_calls_made": tool_calls_made,
            "duration_seconds": (duration * 100.0).round() / 100.0,
        })
        .to_string(),
        ProcessOutcome::Cancelled => json!({
            "status": "interrupted",
            "error": "Execution interrupted by cancellation.",
            "output": format!("{stdout}\n[execution interrupted — user sent a new message]"),
            "tool_calls_made": tool_calls_made,
            "duration_seconds": (duration * 100.0).round() / 100.0,
        })
        .to_string(),
    }
}

#[cfg(unix)]
fn resolve_sandbox_tools(ctx: &ToolContext) -> Vec<&'static str> {
    let fs = describe_execution_filesystem(&ctx.config, &ctx.cwd);
    let allow_terminal = fs.execute_code_terminal_is_safe();
    let Some(registry) = ctx.tool_registry.as_ref() else {
        return Vec::new();
    };

    let mut resolved = Vec::new();
    for &tool_name in SANDBOX_ALLOWED_TOOLS {
        if tool_name == "terminal" && !allow_terminal {
            continue;
        }
        let Some(toolset) = registry.toolset_for_tool(tool_name) else {
            continue;
        };
        if ctx.config.is_tool_enabled(tool_name, &toolset) {
            resolved.push(tool_name);
        }
    }

    resolved
}

#[derive(Debug)]
struct HeadTailCapture {
    head_limit: usize,
    tail_limit: usize,
    head: Vec<u8>,
    tail: VecDeque<u8>,
    total: usize,
}

impl HeadTailCapture {
    fn new(head_limit: usize, tail_limit: usize) -> Self {
        Self {
            head_limit,
            tail_limit,
            head: Vec::new(),
            tail: VecDeque::new(),
            total: 0,
        }
    }

    fn push(&mut self, chunk: &[u8]) {
        self.total = self.total.saturating_add(chunk.len());

        let mut remaining = chunk;
        if self.head.len() < self.head_limit {
            let keep = (self.head_limit - self.head.len()).min(remaining.len());
            self.head.extend_from_slice(&remaining[..keep]);
            remaining = &remaining[keep..];
        }

        if self.tail_limit == 0 || remaining.is_empty() {
            return;
        }

        for &byte in remaining {
            self.tail.push_back(byte);
            while self.tail.len() > self.tail_limit {
                self.tail.pop_front();
            }
        }
    }

    fn into_text(self) -> String {
        if self.total <= self.head.len() + self.tail.len() {
            let mut bytes = self.head;
            bytes.extend(self.tail);
            return String::from_utf8_lossy(&bytes).into_owned();
        }

        let head_text = String::from_utf8_lossy(&self.head).into_owned();
        let tail_bytes: Vec<u8> = self.tail.into_iter().collect();
        let tail_text = String::from_utf8_lossy(&tail_bytes).into_owned();
        let omitted = self
            .total
            .saturating_sub(self.head.len())
            .saturating_sub(tail_bytes.len());
        format!(
            "{head_text}\n\n... [OUTPUT TRUNCATED - {omitted} chars omitted out of {} total] ...\n\n{tail_text}",
            self.total
        )
    }
}

#[derive(Debug)]
struct HeadOnlyCapture {
    limit: usize,
    bytes: Vec<u8>,
    total: usize,
}

impl HeadOnlyCapture {
    fn new(limit: usize) -> Self {
        Self {
            limit,
            bytes: Vec::new(),
            total: 0,
        }
    }

    fn push(&mut self, chunk: &[u8]) {
        self.total = self.total.saturating_add(chunk.len());
        if self.bytes.len() >= self.limit {
            return;
        }
        let keep = (self.limit - self.bytes.len()).min(chunk.len());
        self.bytes.extend_from_slice(&chunk[..keep]);
    }

    fn into_text(self) -> String {
        let text = String::from_utf8_lossy(&self.bytes).into_owned();
        if self.total <= self.limit {
            text
        } else {
            format!("{text}... (stderr truncated)")
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProcessOutcome {
    Completed(i32),
    TimedOut,
    Cancelled,
}

#[derive(Debug)]
struct ProcessRunResult {
    stdout: String,
    stderr: String,
    outcome: ProcessOutcome,
}

async fn capture_stdout(
    mut stdout: tokio::process::ChildStdout,
    progress: Option<std::sync::Arc<crate::tool_progress_tail::ToolProgressTail>>,
) -> Result<String, std::io::Error> {
    use std::sync::Arc;
    use tokio::io::AsyncReadExt;

    let mut capture = HeadTailCapture::new(MAX_STDOUT_BYTES * 2 / 5, MAX_STDOUT_BYTES * 3 / 5);
    let mut buf = [0u8; 4096];
    let mut writer = progress
        .as_ref()
        .map(|reporter| crate::tool_progress_tail::TailByteWriter::stdout(Arc::clone(reporter)));
    loop {
        let read = stdout.read(&mut buf).await?;
        if read == 0 {
            break;
        }
        capture.push(&buf[..read]);
        if let Some(writer) = writer.as_mut() {
            writer.push(&buf[..read]);
        }
    }
    if let Some(writer) = writer.as_mut() {
        writer.finish();
    }
    if let Some(reporter) = progress {
        reporter.flush();
    }
    Ok(capture.into_text())
}

async fn capture_stderr(
    mut stderr: tokio::process::ChildStderr,
    progress: Option<std::sync::Arc<crate::tool_progress_tail::ToolProgressTail>>,
) -> Result<String, std::io::Error> {
    use std::sync::Arc;
    use tokio::io::AsyncReadExt;

    let mut capture = HeadOnlyCapture::new(MAX_STDERR_BYTES);
    let mut buf = [0u8; 4096];
    let mut writer = progress
        .as_ref()
        .map(|reporter| crate::tool_progress_tail::TailByteWriter::stderr(Arc::clone(reporter)));
    loop {
        let read = stderr.read(&mut buf).await?;
        if read == 0 {
            break;
        }
        capture.push(&buf[..read]);
        if let Some(writer) = writer.as_mut() {
            writer.push(&buf[..read]);
        }
    }
    if let Some(writer) = writer.as_mut() {
        writer.finish();
    }
    Ok(capture.into_text())
}

// ─── Process group management ────────────────────────────────────────

/// Kill the child process and its entire process group.
#[cfg(unix)]
async fn kill_process_group(child: &mut tokio::process::Child, escalate: bool) {
    if let Some(pid) = child.id() {
        unsafe {
            libc::killpg(pid as i32, libc::SIGTERM);
        }
        if escalate {
            tokio::time::sleep(Duration::from_secs(2)).await;
            unsafe {
                libc::killpg(pid as i32, libc::SIGKILL);
            }
        }
    }
    let _ = child.start_kill();
}

#[cfg(not(unix))]
async fn kill_process_group(child: &mut tokio::process::Child, _escalate: bool) {
    let _ = child.start_kill();
}

// ─── Head+tail truncation ───────────────────────────────────────────

/// Truncate output keeping both the head (40%) and tail (60%) to preserve
/// the final print() output which is most important.
#[cfg_attr(not(test), allow(dead_code))]
fn head_tail_truncate(text: &str, max_bytes: usize) -> String {
    if text.len() <= max_bytes {
        return text.to_string();
    }

    let head_bytes = (max_bytes * 2) / 5; // 40%
    let tail_bytes = max_bytes - head_bytes; // 60%

    let head_end = (0..=head_bytes)
        .rev()
        .find(|&idx| text.is_char_boundary(idx))
        .unwrap_or(0);
    let tail_start_raw = text.len().saturating_sub(tail_bytes);
    let tail_start = (tail_start_raw..=text.len())
        .find(|&idx| text.is_char_boundary(idx))
        .unwrap_or(text.len());

    if tail_start <= head_end {
        return text[..head_end].to_string();
    }

    let head = &text[..head_end];
    let tail = &text[tail_start..];
    let omitted = text.len() - head_end - (text.len() - tail_start);

    format!(
        "{head}\n\n... [OUTPUT TRUNCATED - {omitted} chars omitted out of {} total] ...\n\n{tail}",
        text.len()
    )
}

// ─── ANSI stripping ─────────────────────────────────────────────────

/// Strip ANSI escape sequences from output so the model never sees them.
fn strip_ansi(text: &str) -> String {
    match strip_ansi_escapes::strip_str(text) {
        s if s.is_empty() && !text.is_empty() => text.to_string(),
        s => s.to_string(),
    }
}

async fn run_command_capture(
    mut cmd: tokio::process::Command,
    timeout_secs: u64,
    cancel: tokio_util::sync::CancellationToken,
    progress: Option<std::sync::Arc<crate::tool_progress_tail::ToolProgressTail>>,
) -> Result<ProcessRunResult, ToolError> {
    use std::process::Stdio;

    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());

    let mut child = cmd.spawn().map_err(|e| ToolError::ExecutionFailed {
        tool: "execute_code".into(),
        message: format!("Failed to spawn process: {e}"),
    })?;

    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: "Failed to capture stdout".into(),
        })?;
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: "Failed to capture stderr".into(),
        })?;

    let progress_stdout = progress.clone();
    let progress_stderr = progress.clone();
    let stdout_task = tokio::spawn(capture_stdout(stdout, progress_stdout));
    let stderr_task = tokio::spawn(capture_stderr(stderr, progress_stderr));

    let outcome = tokio::select! {
        wait_result = child.wait() => {
            let status = wait_result.map_err(|e| ToolError::ExecutionFailed {
                tool: "execute_code".into(),
                message: format!("Process wait failed: {e}"),
            })?;
            ProcessOutcome::Completed(status.code().unwrap_or(-1))
        }
        _ = tokio::time::sleep(Duration::from_secs(timeout_secs)) => {
            kill_process_group(&mut child, true).await;
            let _ = child.wait().await;
            ProcessOutcome::TimedOut
        }
        _ = cancel.cancelled() => {
            kill_process_group(&mut child, false).await;
            let _ = child.wait().await;
            ProcessOutcome::Cancelled
        }
    };

    let stdout = stdout_task
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("stdout capture join failed: {e}"),
        })?
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("stdout capture failed: {e}"),
        })?;
    let stderr = stderr_task
        .await
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("stderr capture join failed: {e}"),
        })?
        .map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("stderr capture failed: {e}"),
        })?;

    Ok(ProcessRunResult {
        stdout,
        stderr,
        outcome,
    })
}

fn configure_process_group(_cmd: &mut tokio::process::Command) {
    #[cfg(unix)]
    unsafe {
        _cmd.pre_exec(|| {
            libc::setpgid(0, 0);
            Ok(())
        });
    }
}

// ─── Tool description builder ────────────────────────────────────────

fn build_description() -> String {
    "Run a Python script that can call Lingshu tools programmatically. \
     Use this when you need 3+ tool calls with processing logic between them, \
     need to filter/reduce large tool outputs before they enter your context, \
     need conditional branching (if X then Y else Z), or need to loop \
     (fetch N pages, process N files, retry on failure).\n\n\
     Use normal tool calls instead when: single tool call with no processing, \
     you need to see the full result and apply complex reasoning, \
     or the task requires interactive user input.\n\n\
     Available via `from lingshu_tools import ...`:\n\n\
       web_search(query: str, max_results: int = 5, backend: str = None) -> dict\n\
         Returns {\"query\", \"backend\", \"results\": [{\"url\", \"title\", \"description\"}, ...]}\n\
       web_extract(url: str, max_chars: int = 8000, backend: str = None, render_js_fallback: bool = True) -> dict\n\
         Returns {\"backend\", \"result\": {\"url\", \"title\", \"content\", \"extractor\", \"content_type\", \"content_format\"}}\n\
       web_crawl(url: str, instructions: str = None, max_pages: int = 8, max_depth: int = 2, backend: str = None, render_js_fallback: bool = True) -> dict\n\
         Crawl multiple linked pages from a start URL. Returns {\"success\", \"backend\", \"pages_visited\", \"results\": [{\"url\", \"title\", \"depth\", \"content\", \"extractor\", \"content_type\", \"content_format\"}, ...]}\n\
       read_file(path: str, offset: int = 1, limit: int = 500) -> dict\n\
         Lines are 1-indexed. Returns {\"content\": \"...\", \"total_lines\": N}\n\
       pdf_to_markdown(path: str, output_path: str = None, max_chars: int = 20000) -> dict\n\
         Convert a local PDF into Markdown using EdgeParse. Fast structural parsing only, not OCR.\n\
       write_file(path: str, content: str) -> dict\n\
         Always overwrites the entire file.\n\
       search_files(pattern: str, target=\"content\", path=\".\", file_glob=None, limit=50) -> dict\n\
         target: \"content\" (search inside files) or \"files\" (find files by name)\n\
       patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict\n\
         Replaces old_string with new_string in the file.\n\
       terminal(command: str, timeout=None, workdir=None) -> dict\n\
         Foreground only (no background/pty). Returns {\"output\": \"...\", \"exit_code\": N}\n\
       vision_analyze(image_source: str, question: str = \"Describe this image.\", detail: str = \"high\") -> dict\n\
         Analyze a local image file path or https:// URL. Returns {\"content\": \"...\"}\n\
       transcribe_audio(file_path: str, provider: str = None, language: str = \"en\") -> dict\n\
         Transcribe an audio file (mp3/wav/m4a/etc.) to text. Returns {\"text\": \"...\"}\n\
       session_search(query: str, limit: int = 10) -> dict\n\
         Full-text search over past sessions. Returns {\"results\": [...]}\n\n\
     Limits: 5-minute timeout, 50KB stdout cap, max 50 tool calls per script. \
     terminal() is foreground-only (no background or pty).\n\n\
     Filesystem rule: direct script file I/O never enforces Lingshu's file-tool path jail. \
     In local mode it sees host paths directly; in non-local terminal backends it runs inside that backend and shares the backend filesystem with `terminal()`. \
     Temp-aware code should prefer `os.environ['EDGECRAB_TMPDIR']` (also exported as `TMPDIR`, `TMP`, and `TEMP`) instead of hard-coding `/tmp`. \
     Prefer read_file/write_file/patch/search_files when you need workspace-root and path-restriction enforcement on host files.\n\n\
     Print your final result to stdout. Use Python stdlib (json, re, math, csv, \
     datetime, collections, etc.) for processing between tool calls.\n\n\
     Also available (no import needed — built into lingshu_tools):\n\
       json_parse(text: str) — json.loads with strict=False; use for terminal() output with control chars\n\
       shell_quote(s: str) — shlex.quote(); use when interpolating dynamic strings into shell commands\n\
       retry(fn, max_attempts=3, delay=2) — retry with exponential backoff for transient failures\n\n\
     Also supports non-Python languages (javascript, typescript, bash, ruby, perl, rust) \
     but without RPC tool access — those run as simple subprocess scripts.\n\n\
     Note: the exact callable subset is also constrained by the current \
     session's enabled toolsets; unavailable helper functions raise a clear \
     runtime error inside the sandbox."
        .to_string()
}

#[cfg(unix)]
async fn execute_remote(
    ctx: &ToolContext,
    runtime: &str,
    ext: &str,
    code: &str,
    timeout_secs: u64,
    is_python: bool,
    sandbox_tools: &[&'static str],
) -> Result<String, ToolError> {
    let backend = get_or_create_backend(ctx).await?;
    if !backend.supports_remote_execute_code() {
        return Err(ToolError::Unavailable {
            tool: "execute_code".into(),
            reason: format!(
                "Remote execute_code is not supported by the {} backend.",
                backend.kind()
            ),
        });
    }

    let exec_start = std::time::Instant::now();
    let sandbox_dir = prepare_remote_sandbox(
        &*backend,
        &uuid::Uuid::new_v4().simple().to_string()[..12],
        ctx.cancel.clone(),
    )
    .await?;
    let script_name = format!("script{ext}");
    let script_path = format!("{sandbox_dir}/{script_name}");
    write_remote_file(&*backend, &script_path, code, ctx.cancel.clone()).await?;

    let tool_call_counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let mut rpc_task = None;
    let rpc_stop = tokio_util::sync::CancellationToken::new();

    if is_python {
        let tools_path = format!("{sandbox_dir}/lingshu_tools.py");
        let tools_src = generate_tools_module(sandbox_tools, RpcTransport::File);
        write_remote_file(&*backend, &tools_path, &tools_src, ctx.cancel.clone()).await?;

        if let Some(registry) = ctx.tool_registry.clone() {
            let rpc_ctx = ToolContext {
                task_id: ctx.task_id.clone(),
                cwd: ctx.cwd.clone(),
                session_id: ctx.session_id.clone(),
                user_task: ctx.user_task.clone(),
                cancel: ctx.cancel.clone(),
                config: ctx.config.clone(),
                state_db: ctx.state_db.clone(),
                platform: ctx.platform,
                process_table: ctx.process_table.clone(),
                provider: ctx.provider.clone(),
                tool_registry: ctx.tool_registry.clone(),
                delegate_depth: ctx.delegate_depth,
                delegate_agent_id: ctx.delegate_agent_id.clone(),
                delegate_parent_id: ctx.delegate_parent_id.clone(),
                sub_agent_runner: ctx.sub_agent_runner.clone(),
                delegation_event_tx: ctx.delegation_event_tx.clone(),
                clarify_tx: None,
                approval_tx: None,
                on_skills_changed: ctx.on_skills_changed.clone(),
                gateway_sender: ctx.gateway_sender.clone(),
                origin_chat: ctx.origin_chat.clone(),
                session_key: ctx.session_key.clone(),
                todo_store: ctx.todo_store.clone(),
                current_tool_call_id: None,
                current_tool_name: None,
                injected_messages: ctx.injected_messages.clone(),
                tool_progress_tx: None,
                watch_notification_tx: None,
                mutation_turn: None,
                lsp_gate: None,
                kanban_task_id: None,
            };
            let rpc_dir = format!("{sandbox_dir}/rpc");
            let allowed = Arc::new(sandbox_tools.iter().map(|tool| tool.to_string()).collect());
            let poll_backend = backend.clone();
            let poll_stop = rpc_stop.clone();
            let poll_counter = tool_call_counter.clone();
            let poll_workdir = sandbox_dir.clone();
            rpc_task = Some(tokio::spawn(async move {
                remote_rpc_poll_loop(RemoteRpcLoop {
                    backend: poll_backend,
                    registry,
                    ctx: rpc_ctx,
                    rpc_dir,
                    tool_call_counter: poll_counter,
                    allowed_tools: allowed,
                    stop: poll_stop,
                    terminal_default_workdir: Some(poll_workdir),
                })
                .await;
            }));
        }
    }

    let rpc_dir = format!("{sandbox_dir}/rpc");
    let remote_command = format!(
        "cd {} && {}",
        backends::shell_quote(&sandbox_dir),
        remote_command_for_runtime(
            runtime,
            &script_name,
            is_python.then_some(rpc_dir.as_str()),
            BACKEND_TMP_ROOT,
        )
    );

    let (reporter, options) =
        crate::tool_progress_tail::ToolProgressTail::reporter_and_options(ctx);

    let output = backend
        .execute(
            &remote_command,
            ".",
            Duration::from_secs(timeout_secs),
            ctx.cancel.clone(),
            options,
        )
        .await?;

    if let Some(reporter) = reporter.as_ref() {
        reporter.flush();
    }

    rpc_stop.cancel();
    if let Some(task) = rpc_task {
        let _ = tokio::time::timeout(Duration::from_secs(5), task).await;
    }

    let _ = backend
        .execute_oneshot(
            &format!("rm -rf {}", backends::shell_quote(&sandbox_dir)),
            ".",
            Duration::from_secs(15),
            tokio_util::sync::CancellationToken::new(),
        )
        .await;

    let stdout = strip_ansi(&redact_output(&head_tail_truncate(
        &output.stdout,
        MAX_STDOUT_BYTES,
    )));
    let stderr = strip_ansi(&redact_output(crate::safe_truncate(
        &output.stderr,
        MAX_STDERR_BYTES,
    )));
    let tool_calls_made = tool_call_counter.load(std::sync::atomic::Ordering::Relaxed);
    let duration = exec_start.elapsed().as_secs_f64();

    Ok(render_execute_code_result(
        stdout,
        stderr,
        process_outcome_from_exit(output.exit_code),
        tool_calls_made,
        duration,
        timeout_secs,
    ))
}

// ─── Tool implementation ─────────────────────────────────────────────

#[async_trait]
impl ToolHandler for ExecuteCodeToolReal {
    fn name(&self) -> &'static str {
        "execute_code"
    }

    fn toolset(&self) -> &'static str {
        "code_execution"
    }

    fn emoji(&self) -> &'static str {
        "🐍"
    }

    fn is_available(&self) -> bool {
        cfg!(unix)
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "execute_code".into(),
            description: build_description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "code": {
                        "type": "string",
                        "description": "Python code to execute. Must be non-empty — only call when you already have a concrete code payload to run. Import tools with `from lingshu_tools import web_search, terminal, ...` and print your final result to stdout."
                    },
                    "language": {
                        "type": "string",
                        "description": "Programming language (default: python). For non-Python: javascript, typescript, bash, ruby, perl, rust — these run without RPC tool access."
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Timeout in seconds (default: 300, max: 600)"
                    }
                },
                "required": ["code"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: ExecuteCodeArgs =
            serde_json::from_value(args).map_err(|e| {
                let raw = e.to_string();
                let message = if raw.contains("missing field `code`") {
                    "Invalid execute_code args: missing field `code`. Only call execute_code when you already have a concrete code payload to run; do not use it as a planning placeholder.".to_string()
                } else {
                    format!("Invalid execute_code args: {raw}")
                };
                ToolError::InvalidArgs {
                    tool: "execute_code".into(),
                    message,
                }
            })?;

        if args.code.trim().is_empty() {
            return Err(ToolError::InvalidArgs {
                tool: "execute_code".into(),
                message: "No code provided.".into(),
            });
        }

        if ctx.cancel.is_cancelled() {
            return Err(ToolError::Other("Cancelled".into()));
        }

        let (runtime, ext) = resolve_runtime(&args.language).ok_or_else(|| {
            ToolError::InvalidArgs {
                tool: "execute_code".into(),
                message: format!(
                    "Unsupported language: '{}'. Supported: python, javascript, typescript, bash, ruby, perl, rust",
                    args.language
                ),
            }
        })?;

        let is_python = matches!(
            args.language.to_lowercase().as_str(),
            "python" | "python3" | "py" | ""
        );
        let timeout_secs = args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS).min(600);
        let (progress_reporter, _) =
            crate::tool_progress_tail::ToolProgressTail::reporter_and_options(ctx);
        #[cfg(unix)]
        let sandbox_tools = resolve_sandbox_tools(ctx);

        let exec_start = std::time::Instant::now();

        #[cfg(unix)]
        if ctx.config.terminal_backend != backends::BackendKind::Local {
            return execute_remote(
                ctx,
                runtime,
                ext,
                &args.code,
                timeout_secs,
                is_python,
                &sandbox_tools,
            )
            .await;
        }

        // Write code to a temp file
        let temp_dir = tempfile::tempdir().map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("Failed to create temp dir: {e}"),
        })?;
        let script_path = temp_dir.path().join(format!("script{ext}"));
        std::fs::write(&script_path, &args.code).map_err(|e| ToolError::ExecutionFailed {
            tool: "execute_code".into(),
            message: format!("Failed to write script: {e}"),
        })?;

        // For Python: set up RPC socket and generate tool stubs
        #[cfg(unix)]
        let rpc_state = if is_python {
            let sock_path = format!("/tmp/lingshu_rpc_{}.sock", uuid::Uuid::new_v4());

            // Generate tool stubs module
            let tools_src = generate_tools_module(&sandbox_tools, RpcTransport::Uds);
            let tools_path = temp_dir.path().join("lingshu_tools.py");
            std::fs::write(&tools_path, &tools_src).map_err(|e| ToolError::ExecutionFailed {
                tool: "execute_code".into(),
                message: format!("Failed to write tools module: {e}"),
            })?;

            // Start UDS listener
            let listener = tokio::net::UnixListener::bind(&sock_path).map_err(|e| {
                ToolError::ExecutionFailed {
                    tool: "execute_code".into(),
                    message: format!("Failed to bind RPC socket: {e}"),
                }
            })?;

            let tool_call_counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));

            // If we have a registry, start the RPC server
            let rpc_handle = if let Some(ref reg) = ctx.tool_registry {
                let reg = reg.clone();
                let rpc_ctx = ToolContext {
                    task_id: ctx.task_id.clone(),
                    cwd: ctx.cwd.clone(),
                    session_id: ctx.session_id.clone(),
                    user_task: ctx.user_task.clone(),
                    cancel: ctx.cancel.clone(),
                    config: ctx.config.clone(),
                    state_db: ctx.state_db.clone(),
                    platform: ctx.platform,
                    process_table: ctx.process_table.clone(),
                    provider: ctx.provider.clone(),
                    tool_registry: ctx.tool_registry.clone(),
                    delegate_depth: ctx.delegate_depth,
                    delegate_agent_id: ctx.delegate_agent_id.clone(),
                    delegate_parent_id: ctx.delegate_parent_id.clone(),
                    sub_agent_runner: ctx.sub_agent_runner.clone(),
                    delegation_event_tx: ctx.delegation_event_tx.clone(),
                    clarify_tx: None,  // No interactive clarify in sandbox
                    approval_tx: None, // No interactive approvals in sandbox
                    on_skills_changed: ctx.on_skills_changed.clone(),
                    gateway_sender: ctx.gateway_sender.clone(),
                    origin_chat: ctx.origin_chat.clone(),
                    session_key: ctx.session_key.clone(),
                    todo_store: ctx.todo_store.clone(),
                    current_tool_call_id: None,
                    current_tool_name: None,
                    injected_messages: ctx.injected_messages.clone(),
                    tool_progress_tx: None,
                    watch_notification_tx: None,
                    mutation_turn: None,
                    lsp_gate: None,
                kanban_task_id: None,
                };
                let counter = tool_call_counter.clone();
                let allowed: Arc<Vec<String>> =
                    Arc::new(sandbox_tools.iter().map(|s| s.to_string()).collect());
                Some(tokio::spawn(async move {
                    rpc_server_loop(listener, reg, rpc_ctx, counter, allowed).await;
                }))
            } else {
                drop(listener);
                None
            };

            Some((sock_path, tool_call_counter, rpc_handle))
        } else {
            None
        };

        #[cfg(not(unix))]
        let rpc_state: Option<(
            String,
            Arc<std::sync::atomic::AtomicUsize>,
            Option<tokio::task::JoinHandle<()>>,
        )> = None;

        // Build a sanitized child environment for every language runtime.
        let sock = if is_python {
            #[cfg(unix)]
            {
                rpc_state.as_ref().map(|(s, _, _)| s.as_str()).unwrap_or("")
            }
            #[cfg(not(unix))]
            {
                ""
            }
        } else {
            ""
        };
        let child_env = build_child_env(sock, &ctx.cwd);

        // Spawn the subprocess
        let run_result = if runtime == "rustc_run" {
            // Rust: compile to temp binary, then run
            let bin_path = temp_dir.path().join("script");
            let mut compile_cmd = tokio::process::Command::new("rustc");
            compile_cmd
                .arg(&script_path)
                .arg("-o")
                .arg(&bin_path)
                .current_dir(&ctx.cwd)
                .env_clear()
                .envs(&child_env);
            configure_process_group(&mut compile_cmd);

            let compile = run_command_capture(
                compile_cmd,
                timeout_secs,
                ctx.cancel.clone(),
                progress_reporter.clone(),
            )
            .await?;
            match compile.outcome {
                ProcessOutcome::Completed(0) => {}
                ProcessOutcome::Completed(_) => {
                    let stderr = strip_ansi(&redact_output(&compile.stderr));
                    return Ok(json!({
                        "status": "error",
                        "error": format!("Compilation error:\n{stderr}"),
                        "tool_calls_made": 0,
                        "duration_seconds": (exec_start.elapsed().as_secs_f64() * 100.0).round() / 100.0,
                    })
                    .to_string());
                }
                ProcessOutcome::TimedOut => {
                    return Ok(json!({
                        "status": "timeout",
                        "error": format!("Rust compilation timed out after {timeout_secs}s and was killed."),
                        "output": strip_ansi(&redact_output(&compile.stdout)),
                        "tool_calls_made": 0,
                        "duration_seconds": (exec_start.elapsed().as_secs_f64() * 100.0).round() / 100.0,
                    })
                    .to_string());
                }
                ProcessOutcome::Cancelled => {
                    return Ok(json!({
                        "status": "interrupted",
                        "error": "Rust compilation interrupted by cancellation.",
                        "output": format!("{}\n[execution interrupted — user sent a new message]", strip_ansi(&redact_output(&compile.stdout))),
                        "tool_calls_made": 0,
                        "duration_seconds": (exec_start.elapsed().as_secs_f64() * 100.0).round() / 100.0,
                    })
                    .to_string());
                }
            }

            let mut run_cmd = tokio::process::Command::new(bin_path);
            run_cmd.current_dir(&ctx.cwd).env_clear().envs(&child_env);
            configure_process_group(&mut run_cmd);
            run_command_capture(
                run_cmd,
                timeout_secs,
                ctx.cancel.clone(),
                progress_reporter.clone(),
            )
            .await?
        } else if runtime.contains(' ') {
            let parts: Vec<&str> = runtime.split_whitespace().collect();
            let mut cmd = tokio::process::Command::new(parts[0]);
            for arg in &parts[1..] {
                cmd.arg(arg);
            }
            cmd.arg(&script_path)
                .current_dir(&ctx.cwd)
                .env_clear()
                .envs(&child_env);
            configure_process_group(&mut cmd);
            run_command_capture(
                cmd,
                timeout_secs,
                ctx.cancel.clone(),
                progress_reporter.clone(),
            )
            .await?
        } else {
            let mut cmd = tokio::process::Command::new(runtime);
            cmd.arg(&script_path)
                .current_dir(&ctx.cwd)
                .env_clear()
                .envs(&child_env);
            configure_process_group(&mut cmd);
            run_command_capture(
                cmd,
                timeout_secs,
                ctx.cancel.clone(),
                progress_reporter.clone(),
            )
            .await?
        };

        let duration = exec_start.elapsed().as_secs_f64();
        let tool_calls_made = rpc_state
            .as_ref()
            .map(|(_, c, _)| c.load(std::sync::atomic::Ordering::Relaxed))
            .unwrap_or(0);

        // Clean up RPC
        #[cfg(unix)]
        if let Some((sock_path, _, rpc_handle)) = &rpc_state {
            let _ = std::fs::remove_file(sock_path);
            if let Some(h) = rpc_handle {
                h.abort();
            }
        }

        let stdout = strip_ansi(&redact_output(&run_result.stdout));
        let stderr = strip_ansi(&redact_output(&run_result.stderr));
        Ok(render_execute_code_result(
            stdout,
            stderr,
            run_result.outcome,
            tool_calls_made,
            duration,
            timeout_secs,
        ))
    }
}

inventory::submit!(&ExecuteCodeToolReal as &dyn ToolHandler);

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use crate::tools::backend_pool::cleanup_backend_for_task;
    #[cfg(unix)]
    use crate::tools::backends::singularity::SINGULARITY_TEST_ENV_LOCK;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::sync::Arc;

    #[test]
    fn resolve_python() {
        let (rt, ext) = resolve_runtime("python").expect("should resolve");
        assert_eq!(rt, "python3");
        assert_eq!(ext, ".py");
    }

    #[test]
    fn resolve_javascript() {
        let (rt, ext) = resolve_runtime("js").expect("should resolve");
        assert_eq!(rt, "node");
        assert_eq!(ext, ".js");
    }

    #[test]
    fn resolve_bash() {
        let (rt, ext) = resolve_runtime("bash").expect("should resolve");
        assert_eq!(rt, "bash");
        assert_eq!(ext, ".sh");
    }

    #[test]
    fn resolve_rust() {
        let (rt, ext) = resolve_runtime("rust").expect("should resolve");
        assert_eq!(rt, "rustc_run");
        assert_eq!(ext, ".rs");
    }

    #[test]
    fn resolve_unknown_returns_none() {
        assert!(resolve_runtime("cobol").is_none());
    }

    #[test]
    fn head_tail_truncate_short() {
        let text = "hello world";
        assert_eq!(head_tail_truncate(text, 100), "hello world");
    }

    #[test]
    fn head_tail_truncate_long() {
        let text = "A".repeat(1000);
        let result = head_tail_truncate(&text, 100);
        assert!(result.contains("OUTPUT TRUNCATED"));
        assert!(result.len() < 200); // head + message + tail
    }

    #[test]
    fn head_tail_truncate_preserves_utf8_boundaries() {
        let text = "🙂".repeat(400);
        let result = head_tail_truncate(&text, 101);
        assert!(!result.is_empty());
    }

    #[test]
    fn strip_ansi_removes_colors() {
        let text = "\x1b[31mred\x1b[0m normal";
        let result = strip_ansi(text);
        assert_eq!(result, "red normal");
    }

    #[cfg(unix)]
    #[test]
    fn generate_tools_module_contains_stubs() {
        let module = generate_tools_module(&["web_search", "terminal"], RpcTransport::Uds);
        assert!(module.contains("def web_search("));
        assert!(module.contains("max_results: int = 5"));
        assert!(module.contains("backend: str = None"));
        assert!(module.contains("def terminal("));
        assert!(module.contains("def json_parse("));
        assert!(module.contains("def shell_quote("));
        assert!(module.contains("def retry("));
        assert!(module.contains("def read_file("));
        assert!(module.contains("not available in this execute_code session"));
    }

    #[cfg(unix)]
    #[test]
    fn generate_tools_module_uses_current_web_extract_signature() {
        let module = generate_tools_module(&["web_extract"], RpcTransport::Uds);
        assert!(module.contains(
            "def web_extract(url: str, max_chars: int = 8000, backend: str = None, render_js_fallback: bool = True):"
        ));
        assert!(module.contains(r#"args = {"url": url, "max_chars": max_chars, "render_js_fallback": render_js_fallback}"#));
    }

    #[cfg(unix)]
    #[test]
    fn generate_tools_module_all_tools() {
        let module = generate_tools_module(SANDBOX_ALLOWED_TOOLS, RpcTransport::Uds);
        for tool in SANDBOX_ALLOWED_TOOLS {
            assert!(
                module.contains(&format!("def {tool}(")),
                "missing stub for {tool}"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn generate_tools_module_file_transport_uses_rpc_dir() {
        let module = generate_tools_module(&["terminal"], RpcTransport::File);
        assert!(module.contains("EDGECRAB_RPC_DIR"));
        assert!(module.contains("req_"));
        assert!(module.contains("res_"));
    }

    #[test]
    fn build_child_env_strips_secrets() {
        // This test verifies the logic but can't easily set real env vars
        let env = build_child_env("/tmp/test.sock", std::path::Path::new("/tmp"));
        assert_eq!(
            env.get("EDGECRAB_RPC_SOCKET").map(|s| s.as_str()),
            Some("/tmp/test.sock")
        );
        assert_eq!(
            env.get("PYTHONDONTWRITEBYTECODE").map(|s| s.as_str()),
            Some("1")
        );
        assert_eq!(
            env.get("EDGECRAB_TMPDIR"),
            env.get("TMPDIR"),
            "child env must align EDGECRAB_TMPDIR and TMPDIR"
        );
    }

    #[cfg(unix)]
    #[test]
    fn remote_command_for_runtime_exports_backend_tmpdir() {
        let command =
            remote_command_for_runtime("python3", "script.py", Some("/tmp/rpc"), BACKEND_TMP_ROOT);
        assert!(command.contains("EDGECRAB_TMPDIR='/tmp/lingshu-tmp'"));
        assert!(command.contains("TMPDIR='/tmp/lingshu-tmp'"));
        assert!(command.contains("python3 'script.py'"));
    }

    #[cfg(unix)]
    #[test]
    fn resolve_sandbox_tools_respects_disabled_toolsets() {
        let mut ctx = ToolContext::test_context();
        ctx.tool_registry = Some(Arc::new(ToolRegistry::new()));
        ctx.config.disabled_toolsets = vec!["web".into(), "terminal".into()];

        let tools = resolve_sandbox_tools(&ctx);
        assert!(!tools.contains(&"web_search"));
        assert!(!tools.contains(&"terminal"));
        assert!(tools.contains(&"read_file"));
    }

    #[cfg(unix)]
    #[test]
    fn resolve_sandbox_tools_keeps_terminal_for_remote_backends() {
        let mut ctx = ToolContext::test_context();
        ctx.tool_registry = Some(Arc::new(ToolRegistry::new()));
        ctx.config.terminal_backend = crate::tools::backends::BackendKind::Modal;

        let tools = resolve_sandbox_tools(&ctx);
        assert!(tools.contains(&"terminal"));
        assert!(tools.contains(&"read_file"));
    }

    #[test]
    fn build_description_mentions_tools() {
        let desc = build_description();
        assert!(desc.contains("web_search"));
        assert!(desc.contains("web_crawl"));
        assert!(desc.contains(
            "web_extract(url: str, max_chars: int = 8000, backend: str = None, render_js_fallback: bool = True)"
        ));
        assert!(desc.contains("transcribe_audio"));
        assert!(desc.contains("session_search"));
        assert!(desc.contains("vision_analyze"));
        assert!(desc.contains("terminal"));
        assert!(desc.contains("lingshu_tools"));
        assert!(
            desc.contains("direct script file I/O never enforces Lingshu's file-tool path jail")
        );
        assert!(desc.contains(
            "runs inside that backend and shares the backend filesystem with `terminal()`"
        ));
    }

    #[tokio::test]
    async fn execute_bash_echo() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(
                json!({ "language": "bash", "code": "echo hello world" }),
                &ctx,
            )
            .await
            .expect("should succeed");
        assert!(result.contains("hello world"));
        assert!(result.contains("success") || result.contains("Exit code: 0"));
    }

    #[tokio::test]
    async fn execute_python_print() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(
                json!({ "language": "python", "code": "print(2 + 2)" }),
                &ctx,
            )
            .await;
        match result {
            Ok(output) => assert!(output.contains("4") || output.contains("status")),
            Err(ToolError::ExecutionFailed { .. }) => {} // acceptable if python3 not found
            Err(e) => panic!("unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn execute_python_default_language() {
        // "code" only, no "language" — should default to python
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(json!({ "code": "print('default python')" }), &ctx)
            .await;
        match result {
            Ok(output) => assert!(output.contains("default python") || output.contains("status")),
            Err(ToolError::ExecutionFailed { .. }) => {}
            Err(e) => panic!("unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn execute_empty_code_rejected() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool.execute(json!({ "code": "  " }), &ctx).await;
        assert!(matches!(result, Err(ToolError::InvalidArgs { .. })));
    }

    #[tokio::test]
    async fn execute_invalid_language() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(json!({ "language": "cobol", "code": "DISPLAY 'HI'" }), &ctx)
            .await;
        assert!(matches!(result, Err(ToolError::InvalidArgs { .. })));
    }

    #[tokio::test]
    async fn execute_bash_failure() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(json!({ "language": "bash", "code": "exit 42" }), &ctx)
            .await
            .expect("should return JSON even on failure");
        assert!(result.contains("error") || result.contains("42"));
    }

    #[tokio::test]
    async fn execute_bash_uses_sanitized_env() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        unsafe {
            std::env::set_var("OPENAI_API_KEY", "sk-test-secret-12345");
        }
        let result = tool
            .execute(
                json!({ "language": "bash", "code": "printf '%s' \"${OPENAI_API_KEY:-NOT_SET}\"" }),
                &ctx,
            )
            .await
            .expect("should return json");
        unsafe {
            std::env::remove_var("OPENAI_API_KEY");
        }

        assert!(result.contains("NOT_SET"), "got: {result}");
        assert!(!result.contains("sk-test-secret-12345"), "got: {result}");
    }

    #[tokio::test]
    async fn execute_timeout_kills_process_and_reports_timeout() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(
                json!({ "language": "bash", "code": "sleep 2", "timeout": 1 }),
                &ctx,
            )
            .await
            .expect("should return timeout json");

        let parsed: serde_json::Value =
            serde_json::from_str(&result).expect("output should be json");
        assert_eq!(parsed["status"], "timeout");
    }

    #[tokio::test]
    async fn execute_returns_json() {
        let tool = ExecuteCodeToolReal;
        let ctx = ToolContext::test_context();
        let result = tool
            .execute(json!({ "language": "bash", "code": "echo ok" }), &ctx)
            .await
            .expect("should succeed");
        // Result should be valid JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&result).expect("output should be JSON");
        assert!(parsed.get("status").is_some());
        assert!(parsed.get("tool_calls_made").is_some());
        assert!(parsed.get("duration_seconds").is_some());
    }

    #[test]
    fn tool_metadata() {
        let tool = ExecuteCodeToolReal;
        assert_eq!(tool.name(), "execute_code");
        assert_eq!(tool.toolset(), "code_execution");
        assert_eq!(tool.emoji(), "🐍");
    }

    #[cfg(unix)]
    fn write_fake_singularity_runtime(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
        let path = dir.path().join("fake-apptainer");
        std::fs::write(&path, body).expect("write fake runtime");
        let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("chmod");
        path
    }

    #[cfg(unix)]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn execute_code_remote_terminal_shares_backend_workdir() {
        let _guard = SINGULARITY_TEST_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().expect("tmpdir");
        let fake = write_fake_singularity_runtime(
            &dir,
            r#"#!/bin/sh
set -eu
case "${1:-}" in
  version)
    echo "apptainer 1.0.0"
    ;;
  instance)
    exit 0
    ;;
  exec)
    workdir="."
    last=""
    while [ "$#" -gt 0 ]; do
      case "$1" in
        --pwd)
          workdir="$2"
          shift 2
          ;;
        *)
          last="$1"
          shift
          ;;
      esac
    done
    mkdir -p "$workdir"
    cd "$workdir"
    exec sh -c "$last"
    ;;
esac
"#,
        );

        unsafe {
            std::env::set_var("EDGECRAB_SINGULARITY_BIN", &fake);
        }

        let mut ctx = ToolContext::test_context();
        ctx.cwd = dir.path().to_path_buf();
        ctx.task_id = format!("exec-remote-{}", uuid::Uuid::new_v4().simple());
        ctx.config.terminal_backend = backends::BackendKind::Singularity;
        ctx.tool_registry = Some(Arc::new(ToolRegistry::new()));

        let tool = ExecuteCodeToolReal;
        let result = tool
            .execute(
                json!({
                    "code": "from lingshu_tools import terminal\nwith open('note.txt', 'w') as fh:\n    fh.write('backend-note')\nprint(terminal('cat note.txt'))\n"
                }),
                &ctx,
            )
            .await
            .expect("remote execute_code");

        assert!(result.contains("backend-note"), "got: {result}");
        let _ = cleanup_backend_for_task(&ctx.task_id).await;
        unsafe {
            std::env::remove_var("EDGECRAB_SINGULARITY_BIN");
        }
    }
}