blyte-agent 0.66.1

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

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use blyte_provider::ToolSpec;
use serde_json::{json, Value};

use crate::approval::{matching_rule, Approval, ApprovalConfig};
use crate::fs::Fs;
use crate::shell::{poll_backoff, Shell, POLL_START};

pub trait PeerTools: Send + Sync {
    /// The running surfaces on this machine, as text for the model.
    fn surfaces(&self) -> Result<String, String>;
    /// Sends `message` to the surface named `name`; the text says delivered or held.
    fn tell(&self, name: &str, message: &str) -> Result<String, String>;
}

static READ_ROOTS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
static DISPATCH_CMD: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
static BLYTE_TOOL: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
static BLYTE_SURFACE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
static APPROVAL: std::sync::RwLock<Option<ApprovalConfig>> = std::sync::RwLock::new(None);
static PEER_TOOLS: std::sync::RwLock<Option<Arc<dyn PeerTools>>> = std::sync::RwLock::new(None);
static WRITE_SCOPE: std::sync::RwLock<Option<WriteScope>> = std::sync::RwLock::new(None);
thread_local! {
    static BLYTE_REQUEST: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
    static BLYTE_STARTED_BY: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Absolute, canonical directories where `write` and `edit` may write without user approval.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteScope {
    pub allowed: Vec<PathBuf>,
    pub edit_worktrees: Option<PathBuf>,
}

fn refused_blyte_tool_command(args: &[String]) -> Option<&'static str> {
    let first = args.first().map(|s| s.as_str())?;
    if first == "combine" {
        return Some("combine");
    }
    if first == "review" {
        let mut iter = args[1..].iter();
        while let Some(arg) = iter.next() {
            if arg == "--" {
                break;
            }
            if arg == "--model-review" {
                return Some("review --model-review");
            }
            let verdict_val = if arg == "--verdict" {
                iter.next().map(|s| s.as_str())
            } else {
                arg.strip_prefix("--verdict=")
            };
            if let Some(val) = verdict_val {
                if val.eq_ignore_ascii_case("accepted") {
                    return Some("review --verdict accepted");
                }
                if val.eq_ignore_ascii_case("fixed") {
                    return Some("review --verdict fixed");
                }
            }
        }
    }
    None
}

pub const BLYTE_TOOL_COMMANDS: [&str; 9] = [
    "dispatch",
    "wait",
    "status",
    "review",
    "plan",
    "init",
    "clean",
    "edit-start",
    "edit-finish",
];

pub fn set_blyte_request(request: Option<String>) {
    BLYTE_REQUEST.with(|slot| {
        *slot.borrow_mut() = request;
    });
}

pub fn blyte_request() -> Option<String> {
    BLYTE_REQUEST.with(|slot| slot.borrow().clone())
}

pub fn set_blyte_started_by(name: Option<String>) {
    BLYTE_STARTED_BY.with(|slot| {
        *slot.borrow_mut() = name;
    });
}

pub fn blyte_started_by() -> Option<String> {
    BLYTE_STARTED_BY.with(|slot| slot.borrow().clone())
}

pub fn set_blyte_tool(exe: Option<std::path::PathBuf>) {
    match BLYTE_TOOL.write() {
        Ok(mut lock) => *lock = exe,
        Err(poisoned) => *poisoned.into_inner() = exe,
    }
}

pub fn blyte_tool() -> Option<PathBuf> {
    BLYTE_TOOL
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

pub fn set_blyte_surface(surface: Option<String>) {
    match BLYTE_SURFACE.write() {
        Ok(mut lock) => *lock = surface,
        Err(poisoned) => *poisoned.into_inner() = surface,
    }
}

pub fn blyte_surface() -> Option<String> {
    BLYTE_SURFACE
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

pub fn set_approval(config: Option<ApprovalConfig>) {
    match APPROVAL.write() {
        Ok(mut lock) => *lock = config,
        Err(poisoned) => *poisoned.into_inner() = config,
    }
}

pub fn approval() -> Option<ApprovalConfig> {
    APPROVAL
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

pub fn set_peer_tools(tools: Option<Arc<dyn PeerTools>>) {
    match PEER_TOOLS.write() {
        Ok(mut lock) => *lock = tools,
        Err(poisoned) => *poisoned.into_inner() = tools,
    }
}

pub fn peer_tools() -> Option<Arc<dyn PeerTools>> {
    PEER_TOOLS
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

pub fn set_write_scope(scope: Option<WriteScope>) {
    match WRITE_SCOPE.write() {
        Ok(mut lock) => *lock = scope,
        Err(poisoned) => *poisoned.into_inner() = scope,
    }
}

pub fn write_scope() -> Option<WriteScope> {
    WRITE_SCOPE
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

/// Set the host dispatch command for the conversation model's `dispatch` tool.
pub fn set_dispatch_cmd(cmd: Option<String>) {
    match DISPATCH_CMD.write() {
        Ok(mut lock) => *lock = cmd,
        Err(poisoned) => *poisoned.into_inner() = cmd,
    }
}

/// The currently configured dispatch command, if any.
pub fn dispatch_cmd() -> Option<String> {
    DISPATCH_CMD
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

/// Extra directories allowed for reading with `read` and `grep`.
///
/// Later calls replace earlier ones.
pub fn set_read_roots(roots: Vec<PathBuf>) {
    match READ_ROOTS.write() {
        Ok(mut lock) => *lock = roots,
        Err(poisoned) => *poisoned.into_inner() = roots,
    }
}

/// The directories set with `set_read_roots`.
pub fn read_roots() -> Vec<PathBuf> {
    READ_ROOTS
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone())
}

/// Output over this many lines is distilled to head and tail before entering context.
///
/// Sized from measurement, not intuition: across 64 recorded command outputs the median was
/// 165-307 lines and exactly one exceeded a thousand -- at 25,105 lines, 88% of that run's
/// entire output volume and 26x the next largest (FINDINGS 13.26). The distribution is a heavy
/// tail, so the bound exists for the rare case; it must not clip the common one.
pub const OUTPUT_LINE_BUDGET: usize = 400;

/// Lines a `read` returns at once, within `MAX_OUTPUT_CHARS`. Larger than `OUTPUT_LINE_BUDGET`
/// because a file the model asked for is the point, not noise: at 400 lines a dogfood run spent
/// 15 turns paging through one 650-line file, each re-sending the whole prompt.
pub const READ_LINE_BUDGET: usize = 2_000;

/// Most matches a single search returns. The count of what was cut is always reported, so a
/// truncated search reads as truncated rather than as a complete answer with few hits.
pub const MAX_MATCHES: usize = 200;

/// Longest line kept whole. Minified code puts megabytes on one line, which a line budget alone
/// never catches: a single grep over node_modules overflowed a 1,048,576-token request.
pub const MAX_LINE_CHARS: usize = 500;

/// Longest line `read` keeps whole. Larger than `MAX_LINE_CHARS` because a file the model asked
/// for is the point, not noise: a plan's 640-character contract line was clipped at 500 and the
/// model spent three turns failing to see it. Minified files are still clipped, here and by
/// `MAX_OUTPUT_CHARS`.
pub const READ_LINE_CHARS: usize = 2_000;

/// Most characters a single tool result may carry (about 15K tokens), after line clipping and
/// line distillation. The final guarantee that one result cannot swamp the context.
pub const MAX_OUTPUT_CHARS: usize = 60_000;

/// `bound_output_lines` with a caller-chosen line length (`read` uses `READ_LINE_CHARS`).
pub fn bound_output_with(text: &str, line_budget: usize, line_chars: usize) -> String {
    let clipped: Vec<String> = text
        .lines()
        .map(|l| {
            let n = l.chars().count();
            if n > line_chars {
                let head: String = l.chars().take(line_chars).collect();
                format!(
                    "{head} …[{} more chars clipped by blyte; the grep tool shows the text around a match]",
                    n - line_chars
                )
            } else {
                l.to_string()
            }
        })
        .collect();
    let mut joined = clipped.join("\n");
    if text.ends_with('\n') {
        joined.push('\n');
    }
    let distilled = distil(&joined, line_budget);
    let total = distilled.chars().count();
    if total <= MAX_OUTPUT_CHARS {
        return distilled;
    }
    let head_n = MAX_OUTPUT_CHARS * 2 / 3;
    let tail_n = MAX_OUTPUT_CHARS - head_n;
    let head: String = distilled.chars().take(head_n).collect();
    let tail: String = distilled.chars().skip(total - tail_n).collect();
    format!(
        "{head}\n\n[... {} chars elided by blyte ...]\n\n{tail}",
        total - head_n - tail_n
    )
}

/// `bound_output` with a caller-chosen line budget (`read` uses `READ_LINE_BUDGET`).
pub fn bound_output_lines(text: &str, line_budget: usize) -> String {
    bound_output_with(text, line_budget, MAX_LINE_CHARS)
}

/// Bound a tool's output by size: clip over-long lines, distil to `OUTPUT_LINE_BUDGET` lines,
/// then cap the total, keeping head and tail. Ordinary output passes through unchanged.
pub fn bound_output(text: &str) -> String {
    bound_output_lines(text, OUTPUT_LINE_BUDGET)
}

/// Match-centred excerpt for long lines.
///
/// When `text` has at most `max` characters, return it unchanged. Otherwise keep the whole match
/// (cut the match itself to `max` characters if it alone is longer) and split the rest of the
/// `max` budget evenly before and after it, shifting any unused side to the other; prefix
/// `…[<n> chars] ` when characters were dropped before, and suffix ` …[<n> chars]` when dropped
/// after, `<n>` being the count dropped. Never split a UTF-8 character.
pub fn excerpt_around(text: &str, start: usize, end: usize, max: usize) -> String {
    let total_chars = text.chars().count();
    if total_chars <= max {
        return text.to_string();
    }
    if start > text.len()
        || end > text.len()
        || start > end
        || !text.is_char_boundary(start)
        || !text.is_char_boundary(end)
    {
        return text.to_string();
    }

    let before = &text[..start];
    let matched = &text[start..end];
    let after = &text[end..];

    let before_chars = before.chars().count();
    let match_chars = matched.chars().count();
    let after_chars = after.chars().count();

    if match_chars >= max {
        let kept_match: String = matched.chars().take(max).collect();
        let dropped_before = before_chars;
        let dropped_after = after_chars + (match_chars - max);
        let mut out = String::new();
        if dropped_before > 0 {
            out.push_str(&format!("…[{dropped_before} chars] "));
        }
        out.push_str(&kept_match);
        if dropped_after > 0 {
            out.push_str(&format!(" …[{dropped_after} chars]"));
        }
        return out;
    }

    let rem = max - match_chars;
    let half_before = rem / 2;
    let half_after = rem - half_before;

    let (take_before, take_after) = if before_chars < half_before {
        let tb = before_chars;
        let ta = (rem - tb).min(after_chars);
        (tb, ta)
    } else if after_chars < half_after {
        let ta = after_chars;
        let tb = (rem - ta).min(before_chars);
        (tb, ta)
    } else {
        (half_before, half_after)
    };

    let dropped_before = before_chars - take_before;
    let dropped_after = after_chars - take_after;

    let mut out = String::new();
    if dropped_before > 0 {
        out.push_str(&format!("…[{dropped_before} chars] "));
    }
    let kept_before: String = before
        .chars()
        .skip(dropped_before)
        .take(take_before)
        .collect();
    out.push_str(&kept_before);
    out.push_str(matched);
    let kept_after: String = after.chars().take(take_after).collect();
    out.push_str(&kept_after);
    if dropped_after > 0 {
        out.push_str(&format!(" …[{dropped_after} chars]"));
    }
    out
}

/// Most matches `excerpt_matches` shows from one line.
const MAX_EXCERPTS_PER_LINE: usize = 5;

/// An excerpt of a long `text` showing every match in `found` (byte ranges, in order; at most
/// `MAX_EXCERPTS_PER_LINE`) with some context each, within about `max` characters. One match is
/// `excerpt_around`. On sanitize-git-repo the first match in a 21,367-character line was an
/// innocent `hf_cache_dir`; the secret was 15,000 characters later.
pub fn excerpt_matches(text: &str, found: &[(usize, usize)], max: usize) -> String {
    if found.len() <= 1 || text.chars().count() <= max {
        return match found.first() {
            Some(&(s, e)) => excerpt_around(text, s, e, max),
            None => text.to_string(),
        };
    }
    let shown = &found[..found.len().min(MAX_EXCERPTS_PER_LINE)];
    let match_chars: usize = shown.iter().map(|&(s, e)| text[s..e].chars().count()).sum();
    let context = max.saturating_sub(match_chars) / (2 * shown.len());
    // Char-index windows around each match, merged where they overlap.
    let to_char = |b: usize| text[..b].chars().count();
    let total = text.chars().count();
    let mut windows: Vec<(usize, usize)> = Vec::new();
    for &(s, e) in shown {
        let (cs, ce) = (to_char(s), to_char(e));
        let w = (cs.saturating_sub(context), (ce + context).min(total));
        match windows.last_mut() {
            Some(last) if w.0 <= last.1 => last.1 = last.1.max(w.1),
            _ => windows.push(w),
        }
    }
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::new();
    let mut pos = 0;
    for (i, &(a, b)) in windows.iter().enumerate() {
        if a > pos {
            if i == 0 {
                out.push_str(&format!("…[{} chars] ", a - pos));
            } else {
                out.push_str(&format!(" …[{} chars] ", a - pos));
            }
        }
        out.extend(&chars[a..b]);
        pos = b;
    }
    if pos < total {
        out.push_str(&format!(" …[{} chars]", total - pos));
    }
    if found.len() > shown.len() {
        out.push_str(&format!(
            " [{} more matches in this line]",
            found.len() - shown.len()
        ));
    }
    out
}

fn split_grep_prefix(line: &str) -> (&str, &str) {
    static PREFIX_RE: std::sync::LazyLock<regex::Regex> =
        std::sync::LazyLock::new(|| regex::Regex::new(r"^(\d+:\d+:|\d+:|.*?:\d+:)").unwrap());
    if let Some(m) = PREFIX_RE.find(line) {
        (&line[..m.end()], &line[m.end()..])
    } else {
        ("", line)
    }
}

/// Ceiling on a single MODEL-ISSUED command.
///
/// Deliberately much shorter than the gate's budget, because the two have different shapes. A
/// verification suite legitimately runs for many minutes and gets its own longer deadline in
/// `run::Runner`. A command the model types while exploring is almost always seconds, and when
/// it is not it is usually wrong: the first live run opened with `find / -name pytest`, which
/// at the previous 900s ceiling was entitled to fifteen minutes of walking the filesystem
/// before anything intervened. Enforcing a bound is not enough on its own -- the bound has to
/// be near the size of the work.
///
/// 300s still accommodates a genuine `npm install` or `cargo build`. Past that the command is
/// killed, the model is told so, and it can re-issue something narrower.
pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300);

/// Ceiling on `blyte edit-finish`, which runs the repository's verification gate in the foreground
/// and therefore needs a gate-sized budget rather than the 300s exploration command limit.
pub const EDIT_FINISH_TIMEOUT: Duration = Duration::from_secs(3600);

pub fn blyte_command_timeout(subcommand: &str) -> Duration {
    if subcommand == "edit-finish" {
        EDIT_FINISH_TIMEOUT
    } else {
        COMMAND_TIMEOUT
    }
}

fn command_ceiling(name: &str, args: &Value) -> Duration {
    if name == "blyte" {
        if let Some(first) = args
            .get("args")
            .and_then(|v| v.as_array())
            .and_then(|a| a.first())
            .and_then(|v| v.as_str())
        {
            return blyte_command_timeout(first);
        }
    }
    COMMAND_TIMEOUT
}

#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutcome {
    pub content: String,
    pub is_error: bool,
}

impl ToolOutcome {
    fn ok(s: impl Into<String>) -> Self {
        Self {
            content: s.into(),
            is_error: false,
        }
    }
    fn err(s: impl Into<String>) -> Self {
        Self {
            content: s.into(),
            is_error: true,
        }
    }
}

/// Keep head and tail, drop the middle, and say how much was dropped.
///
/// Truncating the tail alone would be worse than useless for the case this exists for: a test
/// runner puts its summary at the end, so tail-clipping hides the answer and keeps the noise.
pub fn distil(text: &str, budget: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() <= budget {
        return text.to_string();
    }
    let head = budget * 2 / 3;
    let tail = budget - head;
    let dropped = lines.len() - budget;
    let mut out = lines[..head].join("\n");
    out.push_str(&format!(
        "\n\n[... {dropped} lines elided by blyte ...]\n\n"
    ));
    out.push_str(&lines[lines.len() - tail..].join("\n"));
    out
}

/// Resolve `.` and `..` textually, without touching the filesystem.
///
/// Belt to `canonicalize`'s braces, and not redundant. `Path::starts_with` compares COMPONENTS,
/// so `/ws/../../escaped.rs` lexically starts with `/ws` and passes a naive containment check.
/// That makes the whole escape guarantee rest on canonicalize normalising `..` -- true for
/// `std::fs` and for `readlink -f`, but a property of the implementation rather than of the
/// check. Normalising first means a weak or failing canonicalize cannot be walked past.
///
/// Leading `..` that would climb above the root are dropped rather than preserved: there is no
/// legitimate path above the workspace, so collapsing them keeps the result inside where the
/// caller can still reject it on its merits.
fn lexically_normalize(p: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if !out.pop() {
                    // Nothing to pop: keep it so an escape remains visible to the check
                    // rather than silently becoming the root itself.
                    out.push("..");
                }
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Reject a path that escapes the workspace.
///
/// Checked against the CANONICAL path, so `../` and symlinks cannot walk out. The previous
/// harness relied on a prompt rule -- "confine all inspections to the workspace" -- which is
/// exactly the kind of instruction Invariant IV exists because agents ignore under pressure.
fn resolve_in_workspace(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
    let joined = lexically_normalize(&if Path::new(raw).is_absolute() {
        PathBuf::from(raw)
    } else {
        root.join(raw)
    });
    let root_c = fs
        .canonicalize(root)
        .map_err(|e| format!("workspace root unreadable: {e}"))?;

    // Canonicalise the NEAREST EXISTING ancestor, starting with the target itself. Walking
    // straight to `.parent()` was wrong for a directory target: `Path::new("/a/b/.").parent()`
    // is `/a`, not `/a/b`, so searching the workspace root as `.` resolved to its parent and was
    // refused. Starting at the target and climbing only when it does not exist keeps both cases
    // right -- an existing directory checks itself, a file about to be created checks the
    // directory it will land in -- and neither is waved through unchecked.
    let mut probe = joined.as_path();
    let probe_c = loop {
        if let Ok(c) = fs.canonicalize(probe) {
            break c;
        }
        match probe.parent() {
            Some(p) => probe = p,
            // Nothing in the chain exists: fall back to a lexical check rather than allowing it.
            None => break joined.clone(),
        }
    };
    if !probe_c.starts_with(&root_c) {
        return Err(format!("path escapes the workspace: {raw}"));
    }
    Ok(joined)
}

fn resolve_real_target(fs: &dyn Fs, path: &Path) -> Result<PathBuf, String> {
    let mut probe = path;
    let mut tail: Vec<std::ffi::OsString> = Vec::new();
    loop {
        match fs.canonicalize(probe) {
            Ok(mut resolved) => {
                for part in tail.into_iter().rev() {
                    resolved.push(part);
                }
                return Ok(resolved);
            }
            Err(e) => {
                let exists_or_unreadable = if fs.is_local() {
                    match std::fs::symlink_metadata(probe) {
                        Ok(_) => true,
                        Err(meta_err) => meta_err.kind() != std::io::ErrorKind::NotFound,
                    }
                } else {
                    false
                };
                if exists_or_unreadable {
                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
                }
                let Some(name) = probe.file_name() else {
                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
                };
                tail.push(name.to_os_string());
                let Some(parent) = probe.parent() else {
                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
                };
                probe = parent;
            }
        }
    }
}

/// Reports whether `real_target` lies inside an open direct edit's worktree under
/// `edit_worktrees`: `<edit_worktrees>/<id>/<rest>` where `<edit_worktrees>/<id>.edit.json`
/// exists, `<edit_worktrees>/<id>.json` does not, `<edit_worktrees>/<id>` is a directory, and no
/// path component below `<id>/` is `.git`.
fn is_in_open_edit_worktree(edit_worktrees: &Path, real_target: &Path) -> Result<bool, String> {
    use std::path::Component;
    let Ok(rel) = real_target.strip_prefix(edit_worktrees) else {
        return Ok(false);
    };
    let mut comps = rel.components();
    let Some(Component::Normal(id)) = comps.next() else {
        return Ok(false);
    };
    let mut has_child = false;
    for comp in comps {
        has_child = true;
        match comp {
            Component::Normal(name) if name == ".git" => return Ok(false),
            Component::Normal(_) => {}
            _ => return Ok(false),
        }
    }
    if !has_child {
        return Ok(false);
    }
    crate::sandbox::is_open_edit_worktree_id(edit_worktrees, id)
}

fn check_write_scope(fs: &dyn Fs, tool: &str, path: &Path) -> Result<(), String> {
    let Some(scope) = write_scope() else {
        return Ok(());
    };
    let real_target = resolve_real_target(fs, path)?;
    if scope.allowed.iter().any(|dir| real_target.starts_with(dir)) {
        return Ok(());
    }
    if let Some(edit_worktrees) = &scope.edit_worktrees {
        if is_in_open_edit_worktree(edit_worktrees, &real_target)? {
            return Ok(());
        }
    }
    let allowed_list = scope
        .allowed
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    let cmd = format!("{tool} {}", real_target.display());
    let reason = format!("outside the directories this conversation may write ({allowed_list})");
    let Some(cfg) = approval() else {
        return Err(format!(
            "write was not made: {} is outside the directories this conversation may write ({allowed_list}); no approver is configured (the user can approve writes outside these directories).",
            real_target.display()
        ));
    };
    match cfg.approver.ask(&cmd, &reason) {
        Approval::Approved => Ok(()),
        Approval::Denied => Err(format!(
            "write was not made: {} is outside the directories this conversation may write ({allowed_list}); the user refused (the user can approve writes outside these directories).",
            real_target.display()
        )),
        Approval::Unavailable => Err(format!(
            "write was not made: {} is outside the directories this conversation may write ({allowed_list}); nobody can approve it in this run (the user can approve writes outside these directories).",
            real_target.display()
        )),
    }
}

/// Reject a path that escapes the workspace, unless an absolute path is inside a read root.
pub(crate) fn resolve_for_read(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
    if let Ok(p) = resolve_in_workspace(fs, root, raw) {
        return Ok(p);
    }
    let roots = READ_ROOTS
        .read()
        .map(|r| r.clone())
        .unwrap_or_else(|e| e.into_inner().clone());
    let p = Path::new(raw);
    if p.is_absolute() {
        let joined = lexically_normalize(p);
        let mut probe = joined.as_path();
        let probe_c = loop {
            if let Ok(c) = fs.canonicalize(probe) {
                break Some(c);
            }
            match probe.parent() {
                Some(p) => probe = p,
                None => break None,
            }
        };
        if let Some(probe_c) = probe_c {
            for r in &roots {
                if let Ok(rc) = fs.canonicalize(r) {
                    if probe_c.starts_with(&rc) {
                        return Ok(joined);
                    }
                }
            }
        }
    }
    let extra = if roots.is_empty() {
        String::new()
    } else {
        let list: Vec<String> = roots.iter().map(|r| r.display().to_string()).collect();
        format!(" and {}", list.join(", "))
    };
    Err(format!(
        "path escapes the workspace: {raw}. This run can read the workspace{extra}. Do not look for another copy: if the task needs this path, say in your answer that it was not readable."
    ))
}

/// Single-quote for `bash -lc`, so a pattern containing spaces, `$` or `"` is passed verbatim.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// Optional accelerators worth telling the model about, because their presence changes strategy.
///
/// POSIX-guaranteed utilities (`sed`, `awk`, `find`, `xargs`, `grep`) are deliberately absent:
/// they are present everywhere, so listing them is noise in every prompt for no decision.
/// Pretty printers (bat, eza, dust, delta) and interactive tools are deliberately absent: their
/// colour, icons and pagers cost a model tokens it cannot use.
pub const ACCELERATORS: &[&str] = &["rg", "fd", "sd", "tokei", "jq", "ast-grep"];

/// Language toolchains. Reported against what the REPOSITORY declares, not as a bare list --
/// "this is a Node project and `npm` is not reachable" is actionable; "npm: absent" is not.
pub const TOOLCHAINS: &[&str] = &[
    "git", "cargo", "go", "npm", "yarn", "pnpm", "python3", "pytest", "node", "make",
];

/// What is reachable in the execution environment, probed through the seam.
pub fn available_binaries(shell: &dyn Shell, root: &Path) -> Result<Vec<String>, String> {
    let mut all: Vec<&'static str> = ACCELERATORS.to_vec();
    all.extend_from_slice(TOOLCHAINS);
    shell.available_binaries(root, &all)
}

fn bash_description() -> String {
    format!(
        "Run a shell command in the workspace and wait for it to finish. \
         Commands run to completion (up to {}s). \
         A background job started with its output redirected keeps running after the command \
         returns, and nothing reports when it exits. \
         Output over {} lines is elided in the middle. \
         To find files or search file contents use the `glob` and `grep` tools, not \
         `find`, `grep -r` or `rg` in the shell; they respect .gitignore, are capped \
         and cannot hang.",
        COMMAND_TIMEOUT.as_secs(),
        OUTPUT_LINE_BUDGET
    )
}

pub fn specs() -> Vec<ToolSpec> {
    let mut tools = vec![
        ToolSpec {
            name: "read".into(),
            description: "Read a file. Up to 2,000 lines (60,000 characters) come back in one call, so read whole files; pass start_line/end_line only for larger ones.".into(),
            parameters: json!({"type":"object","properties":{
                "path":{"type":"string"},
                "start_line":{"type":"integer","description":"1-indexed, inclusive"},
                "end_line":{"type":"integer","description":"1-indexed, inclusive"}},
                "required":["path"]}),
        },
        ToolSpec {
            name: "write".into(),
            description: "Create or overwrite a file with exact content.".into(),
            parameters: json!({"type":"object","properties":{
                "path":{"type":"string"},"content":{"type":"string"}},
                "required":["path","content"]}),
        },
        ToolSpec {
            name: "edit".into(),
            description: "Replace an exact, unique string in a file. Fails if absent or ambiguous."
                .into(),
            parameters: json!({"type":"object","properties":{
                "path":{"type":"string"},"old":{"type":"string"},"new":{"type":"string"}},
                "required":["path","old","new"]}),
        },
        ToolSpec {
            name: "bash".into(),
            description: bash_description(),
            parameters: if approval().is_some() {
                json!({
                    "type": "object",
                    "properties": {
                        "command": {"type": "string"},
                        "unsandboxed": {
                            "type": "boolean",
                            "description": "Run this one command outside the sandbox, with the user's network and credentials. It runs only if the user approves it."
                        },
                        "reason": {
                            "type": "string",
                            "description": "One line telling the user why the command must leave the sandbox."
                        }
                    },
                    "required": ["command"]
                })
            } else {
                json!({"type":"object","properties":{
                    "command":{"type":"string"}},"required":["command"]})
            },
        },
        ToolSpec {
            name: "glob".into(),
            description: "Find files by glob pattern, e.g. `src/**/*.rs`. Respects .gitignore; \
                          `.git` is skipped. Fast, and the right \
                          first move when you do not know where something lives."
                .into(),
            parameters: json!({"type":"object","properties":{
                "pattern":{"type":"string","description":"glob, relative to path (or the workspace)"},
                "path":{"type":"string","description":"directory to search under; defaults to the workspace; may be an absolute path under a read root"}},
                "required":["pattern"]}),
        },
        ToolSpec {
            name: "grep".into(),
            description: format!(
                "Search file contents by regular expression, returning `path:line:text`. \
                 Respects .gitignore. Use `glob` to find files by name and `grep` to find them \
                 by content. Capped at {MAX_MATCHES} matches, and the total is always reported."
            ),
            parameters: json!({"type":"object","properties":{
                "pattern":{"type":"string","description":"regular expression"},
                "path":{"type":"string","description":"subtree to search; defaults to the workspace"},
                "glob":{"type":"string","description":"restrict to files matching this glob, e.g. `*.ts`"}},
                "required":["pattern"]}),
        },
    ];
    if dispatch_cmd().is_some() {
        tools.push(ToolSpec {
            name: "dispatch".into(),
            description: "Delegate work to an implementer task on the host.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "task": {
                        "type": "string",
                        "description": "Task instructions for the implementer"
                    },
                    "gate": {
                        "type": "string",
                        "description": "Verification command that decides completion"
                    },
                    "max_seconds": {
                        "type": "integer",
                        "description": "Optional wall-clock limit in seconds"
                    }
                },
                "required": ["task", "gate"]
            }),
        });
    }
    if blyte_tool().is_some() {
        tools.push(ToolSpec {
            name: "blyte".into(),
            description: "Run one of blyte's own commands on the host: dispatch, wait, status, review, plan, init, clean, edit-start, edit-finish.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "args": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "The words after `blyte`"
                    },
                    "background": {
                        "type": "boolean",
                        "description": "Start a `dispatch` in the background and return at once"
                    }
                },
                "required": ["args"]
            }),
        });
    }
    if peer_tools().is_some() {
        tools.push(ToolSpec {
            name: "surfaces".into(),
            description: "List the surfaces running on this machine: name, repository, branch and what each is doing.".into(),
            parameters: json!({
                "type": "object",
                "properties": {}
            }),
        });
        tools.push(ToolSpec {
            name: "tell".into(),
            description: "Send a message to another running surface by name. Its model reads it between turns as a message from this surface, not from its user. Returns delivered or held.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Name of the target surface"
                    },
                    "message": {
                        "type": "string",
                        "description": "Message to send"
                    }
                },
                "required": ["name", "message"]
            }),
        });
    }
    tools
}

/// The search command. ripgrep honours .gitignore, which keeps dependency and build trees out of
/// results; the grep fallback (used when a container has no rg) excludes them explicitly, or a
/// search over node_modules returns megabyte-long minified lines.
pub fn grep_command(use_rg: bool, pattern: &str, sub: &str, glob: &str) -> String {
    if use_rg {
        let globarg = if glob.is_empty() {
            String::new()
        } else {
            format!("--glob {}", shell_quote(glob))
        };
        format!(
            "rg --line-number --no-heading --color never {globarg} -e {} {} | head -n {}",
            shell_quote(pattern),
            shell_quote(sub),
            MAX_MATCHES + 1
        )
    } else {
        let globarg = if glob.is_empty() {
            String::new()
        } else {
            format!("--include={}", shell_quote(glob))
        };
        let excludes = ["node_modules", ".git", "target", ".venv", "dist", "build"]
            .iter()
            .map(|d| format!("--exclude-dir={d}"))
            .collect::<Vec<_>>()
            .join(" ");
        format!(
            "grep -rnIE {excludes} {globarg} -e {} {} | head -n {}",
            shell_quote(pattern),
            shell_quote(sub),
            MAX_MATCHES + 1
        )
    }
}

/// Execute one tool call.
///
/// `shell` decides WHERE commands land -- host, container, remote. The tools never know, which
/// is the point: the previous harness encoded that in a prompt instruction and the worker
/// edited the host whenever the instruction went missing.
///
/// `fs` decides WHERE files live. Kept separate from `shell` because the two can differ: a
/// container with a bind-mounted workspace shares the conversation model's files while running its
/// own commands, and a remote sandbox shares neither. Pairing the wrong two would have the
/// model editing one filesystem and verifying another.
pub fn execute(
    root: &Path,
    shell: &dyn Shell,
    fs: &dyn Fs,
    name: &str,
    args: &Value,
) -> ToolOutcome {
    execute_with_deadline(root, shell, fs, name, args, None)
}

pub fn execute_with_deadline(
    root: &Path,
    shell: &dyn Shell,
    fs: &dyn Fs,
    name: &str,
    args: &Value,
    deadline: Option<std::time::Instant>,
) -> ToolOutcome {
    let ceiling = command_ceiling(name, args);
    let command_timeout = match deadline {
        Some(d) => ceiling.min(d.saturating_duration_since(std::time::Instant::now())),
        None => ceiling,
    };
    execute_with_timeout(root, shell, fs, name, args, command_timeout)
}

pub fn execute_with_timeout(
    root: &Path,
    shell: &dyn Shell,
    fs: &dyn Fs,
    name: &str,
    args: &Value,
    timeout: Duration,
) -> ToolOutcome {
    let ceiling = command_ceiling(name, args);
    let mut outcome = execute_unbounded(root, shell, fs, name, args, ceiling.min(timeout));
    outcome.content = if name == "read" {
        bound_output_with(&outcome.content, READ_LINE_BUDGET, READ_LINE_CHARS)
    } else if name == "grep" {
        bound_output_with(&outcome.content, OUTPUT_LINE_BUDGET, READ_LINE_CHARS)
    } else {
        bound_output_lines(&outcome.content, OUTPUT_LINE_BUDGET)
    };
    outcome
}

/// The tools themselves; `execute` bounds whatever they return.
fn execute_unbounded(
    root: &Path,
    shell: &dyn Shell,
    fs: &dyn Fs,
    name: &str,
    args: &Value,
    command_timeout: Duration,
) -> ToolOutcome {
    let s = |k: &str| {
        args.get(k)
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string()
    };
    match name {
        "read" => {
            let path = match resolve_for_read(fs, root, &s("path")) {
                Ok(p) => p,
                Err(e) => return ToolOutcome::err(e),
            };
            let body = match fs.read(&path) {
                Ok(b) => b,
                Err(e) => return ToolOutcome::err(e),
            };
            let lines: Vec<&str> = body.lines().collect();
            let start = args
                .get("start_line")
                .and_then(|v| v.as_u64())
                .unwrap_or(1)
                .max(1) as usize;
            // A read from the top of a file that fits comes back whole, whatever end_line says:
            // models page from line 1 out of habit (a shadow run read 700 lines as six 200-line
            // calls). A range starting later is a deliberate re-read and is honoured.
            let fits = lines.len() <= READ_LINE_BUDGET && body.chars().count() <= MAX_OUTPUT_CHARS;
            let end = if start == 1 && fits {
                lines.len()
            } else {
                args.get("end_line")
                    .and_then(|v| v.as_u64())
                    .map(|e| e as usize)
                    .unwrap_or(lines.len())
                    .min(lines.len())
            };
            if start > lines.len() {
                return ToolOutcome::err(format!(
                    "{} has {} lines; start_line {start} is past the end",
                    s("path"),
                    lines.len()
                ));
            }
            if end < start {
                return ToolOutcome::err(format!(
                    "end_line {end} is before start_line {start} in {}",
                    s("path")
                ));
            }
            // Numbered, because an agent that cannot cite a line cannot edit precisely.
            let body = lines[start - 1..end]
                .iter()
                .enumerate()
                .map(|(i, l)| format!("{:>6}\t{l}", start + i))
                .collect::<Vec<_>>()
                .join("\n");
            ToolOutcome::ok(distil(&body, READ_LINE_BUDGET))
        }
        "write" => {
            let path = match resolve_in_workspace(fs, root, &s("path")) {
                Ok(p) => p,
                Err(e) => return ToolOutcome::err(e),
            };
            if let Err(e) = check_write_scope(fs, "write", &path) {
                return ToolOutcome::err(e);
            }
            match fs.write(&path, &s("content")) {
                Ok(_) => ToolOutcome::ok(format!("wrote {}", s("path"))),
                Err(e) => ToolOutcome::err(e),
            }
        }
        "edit" => {
            let path = match resolve_in_workspace(fs, root, &s("path")) {
                Ok(p) => p,
                Err(e) => return ToolOutcome::err(e),
            };
            if let Err(e) = check_write_scope(fs, "edit", &path) {
                return ToolOutcome::err(e);
            }
            let body = match fs.read(&path) {
                Ok(b) => b,
                Err(e) => return ToolOutcome::err(e),
            };
            let (old, new) = (s("old"), s("new"));
            match body.matches(&old).count() {
                0 => ToolOutcome::err(format!("`old` not found in {}. Read it first.", s("path"))),
                // Ambiguity is an error, never a guess: replacing the first of several matches
                // silently edits the wrong place and the agent cannot tell.
                n if n > 1 => ToolOutcome::err(format!(
                    "`old` appears {n} times in {}; include more context to make it unique",
                    s("path")
                )),
                _ => match fs.write(&path, &body.replacen(&old, &new, 1)) {
                    Ok(_) => ToolOutcome::ok(format!("edited {}", s("path"))),
                    Err(e) => ToolOutcome::err(e),
                },
            }
        }
        "bash" => {
            let command = s("command");
            let unsandboxed = args
                .get("unsandboxed")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            if unsandboxed {
                let Some(cfg) = approval() else {
                    return ToolOutcome::err("this run cannot run commands outside the sandbox");
                };
                let reason_raw = s("reason");
                let reason = reason_raw.trim();
                if reason.is_empty() {
                    return ToolOutcome::err("give a one-line reason with an unsandboxed command");
                }
                let banner = if let Some(rule) = matching_rule(&command, &cfg.rules) {
                    format!("ran outside the sandbox (allowed by rule \"{rule}\")")
                } else {
                    match cfg.approver.ask(&command, reason) {
                        Approval::Approved => {
                            "ran outside the sandbox (approved by the user)".to_string()
                        }
                        Approval::Denied => {
                            return ToolOutcome::err(
                                "the user refused this command; it was not run. Do not try to run it another way.",
                            );
                        }
                        Approval::Unavailable => {
                            return ToolOutcome::err(
                                "nobody can approve a command in this run, so it was not run",
                            );
                        }
                    }
                };
                match shell.exec_host(&command, root, command_timeout) {
                    Ok(o) => {
                        let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
                        ToolOutcome {
                            content: format!("{banner}\nexit {}\n{body}", o.exit_code),
                            is_error: o.exit_code != 0,
                        }
                    }
                    Err(e) => ToolOutcome::err(e),
                }
            } else {
                match shell.exec_user(&command, root, command_timeout) {
                    Ok(o) => {
                        let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
                        ToolOutcome {
                            content: format!("exit {}\n{body}", o.exit_code),
                            is_error: o.exit_code != 0,
                        }
                    }
                    Err(e) => ToolOutcome::err(e),
                }
            }
        }
        "glob" => {
            let pattern = s("pattern");
            let raw_path = s("path");
            let sub = if raw_path.is_empty() { "." } else { &raw_path };
            let dir = match resolve_for_read(fs, root, sub) {
                Ok(d) => d,
                Err(e) => return ToolOutcome::err(e),
            };
            // .gitignore-aware, fd/ripgrep style. A local workspace expands in-process; a
            // container lists its repository with one `git ls-files` and matches here. Outside a
            // git repository, or for patterns not handled here, the shell glob below runs as before.
            let outcome = |hits: Vec<String>| {
                if hits.is_empty() {
                    ToolOutcome::ok(format!("no files match {pattern}"))
                } else {
                    let shown: Vec<String> = if raw_path.is_empty() {
                        hits
                    } else {
                        let base = Path::new(&raw_path);
                        hits.into_iter()
                            .map(|h| base.join(h).to_string_lossy().into_owned())
                            .collect()
                    };
                    ToolOutcome::ok(format!("{} file(s):\n{}", shown.len(), shown.join("\n")))
                }
            };
            if fs.is_local() {
                if let Some(hits) = crate::search::glob_paths(&dir, &pattern, MAX_MATCHES) {
                    return outcome(hits);
                }
            } else if let Ok(o) = shell.exec(
                "if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then \
                 git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard; \
                 else echo __BLYTE_NO_GIT__; fi",
                &dir,
                command_timeout,
            ) {
                if o.exit_code == 0 && !o.stdout.starts_with("__BLYTE_NO_GIT__") {
                    if let Some(hits) = crate::search::glob_filter(&o.stdout, &pattern, MAX_MATCHES)
                    {
                        return outcome(hits);
                    }
                }
            }
            // Delegated to the shell rather than a glob crate so that `**`, brace expansion and
            // character classes behave exactly as the model expects from a terminal.
            // When bash has globstar (Linux / bash 4+), use it. On platforms where bash lacks
            // globstar (such as macOS /bin/bash 3.2), fall back to zsh which supports `**` natively.
            let cmd = format!(
                "if shopt -s globstar 2>/dev/null; then \
                     shopt -s nullglob dotglob 2>/dev/null; \
                     printf '%s\\n' {pattern}; \
                 elif command -v zsh >/dev/null 2>&1; then \
                     zsh -c 'setopt null_glob glob_dots 2>/dev/null; printf \"%s\\n\" {pattern}'; \
                 else \
                     shopt -s nullglob dotglob 2>/dev/null; \
                     printf '%s\\n' {pattern}; \
                 fi | head -n {MAX_MATCHES}"
            );
            match shell.exec(&cmd, &dir, command_timeout) {
                Ok(o) => {
                    let hits: Vec<String> = o
                        .stdout
                        .lines()
                        .filter(|l| !l.trim().is_empty())
                        .map(String::from)
                        .collect();
                    outcome(hits)
                }
                Err(e) => ToolOutcome::err(format!("glob failed: {e}")),
            }
        }
        "grep" => {
            let pattern = s("pattern");
            let sub = {
                let p = s("path");
                if p.is_empty() {
                    ".".to_string()
                } else {
                    p
                }
            };
            if let Err(e) = resolve_for_read(fs, root, &sub) {
                return ToolOutcome::err(e);
            }
            let glob_str = s("glob");
            // A local workspace is searched in-process with ripgrep's libraries; elsewhere one
            // command, using rg when the environment has it (no separate probe).
            let lines: Vec<String> = if fs.is_local() {
                match crate::search::grep_lines(root, &sub, &pattern, &glob_str, MAX_MATCHES + 1) {
                    Ok(l) => l,
                    Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
                }
            } else {
                let cmd = format!(
                    "if command -v rg >/dev/null 2>&1; then {}; else {}; fi",
                    grep_command(true, &pattern, &sub, &glob_str),
                    grep_command(false, &pattern, &sub, &glob_str)
                );
                match shell.exec(&cmd, root, command_timeout) {
                    Ok(o) => o
                        .stdout
                        .lines()
                        .filter(|l| !l.trim().is_empty())
                        .map(String::from)
                        .collect(),
                    Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
                }
            };
            if lines.is_empty() {
                return ToolOutcome::ok(format!("no matches for {pattern}"));
            }
            let pattern_re = regex::Regex::new(&pattern).ok();
            let lines: Vec<String> = lines
                .into_iter()
                .map(|line| {
                    if line.chars().count() <= MAX_LINE_CHARS {
                        return line;
                    }
                    let Some(ref re) = pattern_re else {
                        return line;
                    };
                    let (prefix, rest) = split_grep_prefix(&line);
                    let found: Vec<(usize, usize)> =
                        re.find_iter(rest).map(|m| (m.start(), m.end())).collect();
                    if found.is_empty() {
                        line
                    } else {
                        format!("{prefix}{}", excerpt_matches(rest, &found, MAX_LINE_CHARS))
                    }
                })
                .collect();
            if lines.len() > MAX_MATCHES {
                ToolOutcome::ok(format!(
                    "{}\n\n[capped at {MAX_MATCHES} matches; narrow the pattern or pass `glob` \
                     to see the rest]",
                    lines[..MAX_MATCHES].join("\n")
                ))
            } else {
                ToolOutcome::ok(format!("{} match(es):\n{}", lines.len(), lines.join("\n")))
            }
        }
        "dispatch" => {
            let Some(cmd) = dispatch_cmd() else {
                return ToolOutcome::err("unknown tool: dispatch");
            };
            let json_bytes = match serialize_dispatch_args(args) {
                Ok(bytes) => bytes,
                Err(msg) => return ToolOutcome::err(msg),
            };
            let parent_session = dispatch_parent_session();
            let mut cmd_builder = std::process::Command::new("sh");
            cmd_builder
                .arg("-c")
                .arg(&cmd)
                .env("BLYTE_DISPATCH_PARENT", &parent_session)
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped());
            if root.is_dir() {
                cmd_builder.current_dir(root);
            }
            let mut child = match cmd_builder.spawn() {
                Ok(c) => c,
                Err(e) => return ToolOutcome::err(format!("dispatch failed to spawn: {e}")),
            };

            let Some(mut stdin) = child.stdin.take() else {
                let _ = child.kill();
                let _ = child.wait();
                return ToolOutcome::err("dispatch failed: stdin pipe unavailable");
            };
            let write_err = std::io::Write::write_all(&mut stdin, &json_bytes).err();
            drop(stdin);

            match (write_err, child.wait_with_output()) {
                (None, Ok(output)) if output.status.success() => {
                    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
                    ToolOutcome::ok(stdout)
                }
                (None, Ok(output)) => ToolOutcome::err(format_dispatch_failure(&output)),
                (None, Err(e)) => ToolOutcome::err(format!("dispatch command failed: {e}")),
                (Some(write_err), Ok(output)) if output.status.success() => ToolOutcome::err(
                    format!("dispatch failed to write arguments to stdin: {write_err}"),
                ),
                (Some(write_err), Ok(output)) => ToolOutcome::err(format!(
                    "{}\ndispatch also failed to write arguments to stdin: {write_err}",
                    format_dispatch_failure(&output)
                )),
                (Some(write_err), Err(wait_err)) => ToolOutcome::err(format!(
                    "dispatch failed to write arguments to stdin: {write_err}; dispatch command also failed: {wait_err}"
                )),
            }
        }
        "blyte" => {
            let Some(exe) = blyte_tool() else {
                return ToolOutcome::err("unknown tool: blyte");
            };
            let cmd_args: Vec<String> = match args.get("args").and_then(|v| v.as_array()) {
                Some(arr) => {
                    let mut out = Vec::with_capacity(arr.len());
                    for item in arr {
                        match item.as_str() {
                            Some(s) => out.push(s.to_string()),
                            None => return ToolOutcome::err("args must be an array of strings"),
                        }
                    }
                    out
                }
                None => Vec::new(),
            };
            let Some(first) = cmd_args.first().map(|s| s.as_str()) else {
                return ToolOutcome::err(format!(
                    "the blyte tool runs only: {}",
                    BLYTE_TOOL_COMMANDS.join(", ")
                ));
            };
            if let Some(refused) = refused_blyte_tool_command(&cmd_args) {
                return ToolOutcome::err(crate::shell::model_shell_refusal_message(refused));
            }
            if !BLYTE_TOOL_COMMANDS.contains(&first) {
                return ToolOutcome::err(format!(
                    "the blyte tool runs only: {}",
                    BLYTE_TOOL_COMMANDS.join(", ")
                ));
            }
            let background = args
                .get("background")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            if background && first != "dispatch" {
                return ToolOutcome::err("only dispatch can run in the background");
            }

            let mut exec_args = cmd_args.clone();
            if matches!(first, "dispatch" | "edit-finish") {
                if cmd_args
                    .iter()
                    .skip(1)
                    .any(|a| a == "--request" || a.starts_with("--request="))
                {
                    return ToolOutcome::err("do not pass --request; blyte sets it automatically");
                }
                if cmd_args
                    .iter()
                    .skip(1)
                    .any(|a| a == "--surface" || a.starts_with("--surface="))
                {
                    return ToolOutcome::err("do not pass --surface; blyte sets it automatically");
                }
                if cmd_args
                    .iter()
                    .skip(1)
                    .any(|a| a == "--started-by" || a.starts_with("--started-by="))
                {
                    return ToolOutcome::err(
                        "do not pass --started-by; blyte sets it automatically",
                    );
                }
                if let Some(req_id) = blyte_request() {
                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
                        exec_args.insert(pos, req_id);
                        exec_args.insert(pos, "--request".to_string());
                    } else {
                        exec_args.push("--request".to_string());
                        exec_args.push(req_id);
                    }
                }
                if let Some(surface_id) = blyte_surface() {
                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
                        exec_args.insert(pos, surface_id);
                        exec_args.insert(pos, "--surface".to_string());
                    } else {
                        exec_args.push("--surface".to_string());
                        exec_args.push(surface_id);
                    }
                }
                if let Some(started_by) = blyte_started_by() {
                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
                        exec_args.insert(pos, started_by);
                        exec_args.insert(pos, "--started-by".to_string());
                    } else {
                        exec_args.push("--started-by".to_string());
                        exec_args.push(started_by);
                    }
                }
            }

            let parent_session = dispatch_parent_session();
            let mut cmd_builder = std::process::Command::new(&exe);
            cmd_builder
                .args(&exec_args)
                .env("BLYTE_DISPATCH_PARENT", &parent_session)
                .env_remove(crate::shell::MODEL_SHELL_ENV)
                .stdin(std::process::Stdio::null());
            if root.is_dir() {
                cmd_builder.current_dir(root);
            }

            if background {
                let Some(id) = cmd_args.get(1).filter(|s| !s.is_empty()) else {
                    return ToolOutcome::err("dispatch needs an id");
                };
                return run_background_dispatch(cmd_builder, root, id);
            }

            match run_command_bounded(cmd_builder, command_timeout) {
                Ok((0, stdout, _stderr)) => ToolOutcome::ok(stdout),
                Ok((2, stdout, stderr)) if first == "wait" => {
                    let lines: Vec<&str> = stderr.lines().collect();
                    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
                        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
                    } else {
                        stderr.trim_end().to_string()
                    };
                    let mut parts = vec!["still waiting".to_string()];
                    if !stdout.trim().is_empty() {
                        parts.push(stdout.trim_end().to_string());
                    }
                    if !tail.trim().is_empty() {
                        parts.push(tail);
                    }
                    ToolOutcome::ok(parts.join("\n"))
                }
                Ok((code, stdout, stderr)) => {
                    let lines: Vec<&str> = stderr.lines().collect();
                    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
                        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
                    } else {
                        stderr.trim_end().to_string()
                    };
                    let mut parts = vec![format!("exit {code}")];
                    if !stdout.trim().is_empty() {
                        parts.push(stdout.trim_end().to_string());
                    }
                    if !tail.trim().is_empty() {
                        parts.push(tail);
                    }
                    ToolOutcome::err(parts.join("\n"))
                }
                Err(e) => ToolOutcome::err(e),
            }
        }
        "surfaces" => {
            let Some(peer) = peer_tools() else {
                return ToolOutcome::err("the surfaces tool is not available here");
            };
            match peer.surfaces() {
                Ok(text) => ToolOutcome::ok(text),
                Err(text) => ToolOutcome::err(text),
            }
        }
        "tell" => {
            let Some(peer) = peer_tools() else {
                return ToolOutcome::err("the tell tool is not available here");
            };
            let Some(target) = args
                .get("name")
                .and_then(|v| v.as_str())
                .filter(|v| !v.trim().is_empty())
            else {
                return ToolOutcome::err("tell needs a name and a message");
            };
            let Some(message) = args
                .get("message")
                .and_then(|v| v.as_str())
                .filter(|v| !v.trim().is_empty())
            else {
                return ToolOutcome::err("tell needs a name and a message");
            };
            match peer.tell(target, message) {
                Ok(text) => ToolOutcome::ok(text),
                Err(text) => ToolOutcome::err(text),
            }
        }
        other => ToolOutcome::err(format!("unknown tool: {other}")),
    }
}

const BACKGROUND_STARTUP_WAIT: Duration = Duration::from_secs(2);
const BACKGROUND_STARTUP_POLL: Duration = Duration::from_millis(50);

fn run_background_dispatch(
    mut cmd_builder: std::process::Command,
    root: &Path,
    id: &str,
) -> ToolOutcome {
    let wt_dir = root.join(".wt");
    let out_path = wt_dir.join(format!("{id}.dispatch.out"));
    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
        return ToolOutcome::err(format!(
            "cannot create {} for {}: {e}",
            wt_dir.display(),
            out_path.display()
        ));
    }
    let out_file = match std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&out_path)
    {
        Ok(f) => f,
        Err(e) => {
            return ToolOutcome::err(format!("cannot open {}: {e}", out_path.display()));
        }
    };
    let err_file = match out_file.try_clone() {
        Ok(f) => f,
        Err(e) => {
            return ToolOutcome::err(format!(
                "cannot clone output file {}: {e}",
                out_path.display()
            ));
        }
    };
    cmd_builder
        .stdout(std::process::Stdio::from(out_file))
        .stderr(std::process::Stdio::from(err_file));

    let mut child = match cmd_builder.spawn() {
        Ok(c) => c,
        Err(e) => return ToolOutcome::err(format!("blyte failed to spawn: {e}")),
    };
    drop(cmd_builder);

    let deadline = std::time::Instant::now() + BACKGROUND_STARTUP_WAIT;
    let exited = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) => {
                let now = std::time::Instant::now();
                if now >= deadline {
                    break None;
                }
                std::thread::sleep(BACKGROUND_STARTUP_POLL.min(deadline - now));
            }
            Err(e) => {
                return ToolOutcome::err(format!("blyte wait failed for dispatch {id}: {e}"));
            }
        }
    };

    match exited {
        Some(status) => {
            let raw = match std::fs::read(&out_path) {
                Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
                Err(e) => {
                    return ToolOutcome::err(format!(
                        "dispatch {id} exited ({status}), and reading {} failed: {e}",
                        out_path.display()
                    ));
                }
            };
            let body = raw.trim_end();
            if status.success() {
                if body.is_empty() {
                    ToolOutcome::ok(format!("dispatch {id} finished"))
                } else {
                    ToolOutcome::ok(format!("dispatch {id} finished\n{body}"))
                }
            } else {
                let header = match status.code() {
                    Some(code) => format!("dispatch {id} failed to start (exit {code})"),
                    None => format!("dispatch {id} failed to start ({status})"),
                };
                if body.is_empty() {
                    ToolOutcome::err(header)
                } else {
                    ToolOutcome::err(format!("{header}\n{body}"))
                }
            }
        }
        None => {
            std::thread::spawn(move || {
                let _ = child.wait();
            });
            ToolOutcome::ok(format!(
                "started {id} in the background; use wait to learn when it ends; output: {}",
                out_path.display()
            ))
        }
    }
}

fn format_dispatch_failure(output: &std::process::Output) -> String {
    let stderr_str = String::from_utf8_lossy(&output.stderr);
    let lines: Vec<&str> = stderr_str.lines().collect();
    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
    } else if !stderr_str.trim().is_empty() {
        stderr_str.trim_end().to_string()
    } else {
        match output.status.code() {
            Some(code) => format!("exit {code}"),
            None => format!("terminated without exit code ({})", output.status),
        }
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    if stdout.trim().is_empty() {
        tail
    } else {
        format!("{}\n{tail}", stdout.trim_end())
    }
}

fn serialize_dispatch_args<T: serde::Serialize>(args: &T) -> Result<Vec<u8>, String> {
    serde_json::to_vec(args).map_err(|e| format!("dispatch failed to serialize arguments: {e}"))
}

fn dispatch_parent_session() -> String {
    std::env::var("BLYTE_SESSION")
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            format!("{now}-{}", std::process::id())
        })
}

fn run_command_bounded(
    mut cmd: std::process::Command,
    timeout: Duration,
) -> Result<(i32, String, String), String> {
    use std::io::Read;
    use std::process::Stdio;

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

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }

    let mut child = cmd
        .spawn()
        .map_err(|e| format!("blyte failed to spawn: {e}"))?;

    let mut so = child.stdout.take().ok_or("no stdout")?;
    let mut se = child.stderr.take().ok_or("no stderr")?;
    let t_out = std::thread::spawn(move || {
        let mut b = Vec::new();
        let _ = so.read_to_end(&mut b);
        String::from_utf8_lossy(&b).into_owned()
    });
    let t_err = std::thread::spawn(move || {
        let mut b = Vec::new();
        let _ = se.read_to_end(&mut b);
        String::from_utf8_lossy(&b).into_owned()
    });

    let deadline = std::time::Instant::now() + timeout;
    let mut poll = POLL_START;
    let status = loop {
        match child
            .try_wait()
            .map_err(|e| format!("blyte wait failed: {e}"))?
        {
            Some(s) => break Some(s),
            None if std::time::Instant::now() >= deadline => {
                #[cfg(unix)]
                {
                    let pgid = child.id() as i32;
                    if pgid > 0 {
                        unsafe {
                            libc::kill(-pgid, libc::SIGKILL);
                        }
                    } else {
                        let _ = child.kill();
                    }
                }
                #[cfg(not(unix))]
                {
                    let _ = child.kill();
                }
                let _ = child.wait();
                break None;
            }
            None => {
                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
                let (sleep, next) = poll_backoff(poll, remaining);
                std::thread::sleep(sleep);
                poll = next;
            }
        }
    };

    let stdout = t_out
        .join()
        .map_err(|_| "blyte: reading the command's output failed".to_string())?;
    let stderr = t_err
        .join()
        .map_err(|_| "blyte: reading the command's errors failed".to_string())?;

    match status {
        Some(s) => match s.code() {
            Some(code) => Ok((code, stdout, stderr)),
            None => Err(format!(
                "blyte ended without an exit code ({s}); its output so far:\n{stdout}{stderr}"
            )),
        },
        None => Ok((
            124,
            stdout,
            format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
        )),
    }
}

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

    #[test]
    fn bash_description_says_background_jobs_keep_running() {
        let all = specs();
        let desc = &all
            .iter()
            .find(|t| t.name == "bash")
            .expect("bash spec missing")
            .description;
        assert!(
            desc.contains(
                "A background job started with its output redirected keeps running after the command returns, and nothing reports when it exits."
            ),
            "got {desc:?}"
        );
        assert!(
            !desc.contains("there is no background mode"),
            "got {desc:?}"
        );
    }

    #[test]
    fn serialize_dispatch_args_surfaces_serialization_error() {
        struct FailingSerialize;

        impl serde::Serialize for FailingSerialize {
            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("unsupported map key"))
            }
        }

        let err = serialize_dispatch_args(&FailingSerialize).unwrap_err();
        assert!(err.contains("serialize"), "got: {err}");
        assert!(err.contains("unsupported map key"), "got: {err}");
    }
}