supercode-cli 0.5.117

Volter Harness — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
//! `supercode message`: cross-session messaging from any agent's shell.
//!
//! The agent-facing half of the mailbox (`supercode_harness::mailbox`). Every
//! coding harness can run a shell command, so this command is the one reply
//! door every harness shares. Its texts are written for the agent that runs
//! it: each outcome says what happened, whether anything was sent, and what
//! (not) to do next, and the exit code says the same for scripts:
//!
//! | exit | meaning |
//! |---|---|
//! | 0 | delivered, queued or held |
//! | 2 | refused |
//! | 3 | unknown or stale address |
//! | 4 | stored, not delivered (the receiver has no delivery door) |
//! | 5 | failed |
//! | 6 | `wait` timed out with no mail |
//!
//! The sender is never declared: it is resolved from this process's ancestry
//! (the harness process that ran the shell), so a reply always has a live
//! address to return to.

use std::io::Read;
use std::path::PathBuf;
use std::time::{Duration, Instant};

use anyhow::{anyhow, Result};
use clap::Subcommand;
use supercode_harness::claude_relay::{gate_decision, gate_denial, QueuedSend};
use supercode_harness::mail_route::{resolve_caller, Caller, Door};
use supercode_harness::mailbox::{
    local_machine_name, mail_root, Envelope, MailAddress, MailKind, Mailbox,
};
use supercode_harness::HarnessHomes;

use supercode_harness::mail_send::{EXIT_FAILED, EXIT_REFUSED, EXIT_UNKNOWN};
const EXIT_TIMEOUT: i32 = 6;

/// Longest `wait` a caller may ask for; agents' shell tools time out soon
/// after, and a killed wait reads as a failure.
const MAX_WAIT: Duration = Duration::from_secs(100);

#[derive(Subcommand)]
pub(crate) enum MessageAction {
    /// List the sessions you can message: this machine's, then those on the team's other online
    /// machines, each with its status and, when it runs in a machine daemon's pane, that pane.
    #[command(alias = "ls")]
    List {
        /// Print JSON instead of a table.
        #[arg(long)]
        json: bool,
    },
    /// Send a message. The body is the argument, or stdin (use a quoted
    /// heredoc for anything with quotes, `$` or several lines), or --file.
    Send {
        /// Receiver: an address (sc:<machine>:<harness>:<id>), name@machine,
        /// or a name that is unique on this machine.
        to: String,
        /// A short body. Omit it to read the body from stdin.
        body: Option<String>,
        /// A short subject displayed on the unopened envelope.
        #[arg(long)]
        subject: Option<String>,
        /// Read the body from this file.
        #[arg(long, value_name = "PATH", conflicts_with = "body")]
        file: Option<PathBuf>,
        /// Id of the message this one answers.
        #[arg(long = "re", value_name = "MESSAGE_ID")]
        in_reply_to: Option<String>,
        /// Also send one notice to your mailbox when the receiver next goes idle.
        #[arg(long)]
        notify_when_idle: bool,
        /// Only enqueue; never start a turn in an idle receiver.
        #[arg(long)]
        queue: bool,
        /// Idempotency key: repeating a send with the same key does not send twice.
        #[arg(long, value_name = "KEY")]
        id: Option<String>,
    },
    /// Reply to a message in your mailbox (its id, or any unambiguous prefix): the reply goes to its
    /// sender and joins its thread, as an email's reply does. `send` composes a new message.
    Reply {
        /// The message you answer.
        id: String,
        /// A short body. Omit it to read the body from stdin.
        body: Option<String>,
        /// Read the body from this file.
        #[arg(long, value_name = "PATH", conflicts_with = "body")]
        file: Option<PathBuf>,
        /// Also send one notice to your mailbox when the receiver next goes idle.
        #[arg(long)]
        notify_when_idle: bool,
        /// Only enqueue; never start a turn in an idle receiver.
        #[arg(long)]
        queue: bool,
    },
    /// Show the conversation a message belongs to, from every mailbox here, oldest first: what it
    /// answers, what answers it, and so on (replies, including those inferred from a transcript).
    Thread {
        /// A message in the conversation (its id, or any unambiguous prefix).
        id: String,
        /// Print JSON instead of the rendered messages.
        #[arg(long)]
        json: bool,
    },
    /// Hand a root you received as an agent's main session to a new session of the agent: it
    /// opens in a pane with the root, holds the thread (every reply wakes it), and you stay CC.
    /// Prints where the conversation continues.
    Delegate {
        /// The root (its id, or any unambiguous prefix), as your inbox shows it.
        root: String,
        /// Start the session here instead of the agent's folder.
        #[arg(long, value_name = "DIR")]
        folder: Option<PathBuf>,
        /// The program to start instead of the agent's (`claude`).
        #[arg(long, value_name = "PROGRAM")]
        harness: Option<String>,
    },
    /// List an agent's threads (yours, when you are one of its sessions): each thread's id,
    /// the session holding it, its participants and its newest line. Read one with `thread`.
    Threads {
        /// The agent whose threads to list.
        #[arg(long)]
        agent: Option<String>,
        /// Print JSON instead of a table.
        #[arg(long)]
        json: bool,
    },
    /// Show your unread messages, each with how to answer it. Every message has an id: mail from
    /// sessions and notices, a Room member's or a voice turn, and each line your user typed
    /// (with --all).
    Inbox {
        /// Also show messages already read, and the lines your user typed.
        #[arg(long)]
        all: bool,
        /// Print JSON instead of the rendered messages.
        #[arg(long)]
        json: bool,
        /// Read another session's inbox instead (its address, on this machine or another of the
        /// team's, or its name while it runs here): everything into and out of it, read or not.
        /// Marks nothing read.
        #[arg(long, value_name = "SESSION")]
        session: Option<String>,
        /// Only the newest N messages already read (unread ones are always shown): your recent
        /// inbox, with --all or --session.
        #[arg(long, value_name = "N")]
        recent: Option<usize>,
    },
    /// Show the messages with these ids, from any mailbox on this machine or the team's other
    /// online machines: who sent each, when, to which session, and its words. An id may be cut
    /// short to any unambiguous prefix, as git takes a short hash (`u-63f7`). Exits 3 when one is
    /// not found or is ambiguous.
    Show {
        /// Message ids or prefixes (`m-…` mail, `u-…` a line a user typed, `a-…` an answer).
        #[arg(required = true, value_name = "ID")]
        ids: Vec<String>,
        /// Print JSON instead of the rendered messages.
        #[arg(long)]
        json: bool,
        /// Show the answers to these messages instead: each message filed in its sender's mailbox
        /// whose `in_reply_to` names it (what a card waiting on a reply waits for).
        #[arg(long)]
        replies: bool,
    },
    /// Wait for the next message (bounded; never polls a session).
    Wait {
        /// Only wake for mail from this sender.
        #[arg(long, value_name = "TO")]
        from: Option<String>,
        /// Seconds to wait, at most 100.
        #[arg(long, default_value_t = 100)]
        timeout: u64,
    },
    /// Set up a harness's delivery door, so messages to its sessions are shown
    /// to them. `codex`: adds supercode's mail hooks to Codex's hooks.json.
    Setup {
        /// Harness to set up (codex).
        harness: String,
    },
    /// A harness hook that points its session at unread mail (internal).
    #[command(hide = true)]
    Hook {
        /// Harness whose hook this is (codex).
        harness: String,
    },
    /// UserPromptSubmit hook of a Claude relay: files inbound mail (internal).
    #[command(hide = true)]
    RelayInbound {
        /// Address of the session the relay speaks for.
        represented: String,
        /// The relay's directory.
        directory: PathBuf,
    },
    /// Deliver one request that arrived through this machine's Teams mail door
    /// (internal).
    #[command(hide = true)]
    RemoteDeliver,
    /// Serve messaging to an agent as MCP tools over stdio: list_agents,
    /// send_message, read_messages (`teams connect --install` registers it
    /// with each harness).
    Mcp,
    /// Deliver one filed message to its session by the session's door, and
    /// mark it read (internal; a relay's hook starts it).
    #[command(hide = true)]
    Push {
        /// The session's address.
        address: String,
        /// The message's id.
        id: String,
    },
    /// PreToolUse hook of a Claude relay (internal).
    #[command(hide = true)]
    Gate {
        /// The relay's directory.
        directory: PathBuf,
    },
    /// PostToolUse and Stop hook of a Claude relay: records Claude's receipt
    /// for the queued send (internal).
    #[command(hide = true)]
    RelayReceipt {
        /// The relay's directory.
        directory: PathBuf,
    },
    /// Watch idle subscriptions and send their notices, type the user's
    /// waiting turns into their panes, and serve the Claude relays' Messages
    /// API (internal; the machine daemon runs it).
    #[command(hide = true)]
    Watch,
    /// Register a native launch or handle its structured question (internal).
    #[command(hide = true)]
    NativeQuestionHook { binding: PathBuf },
    /// Refresh registered native questions into their creators' mailboxes.
    Questions,
}

/// Run one `supercode message` action. Returns the process exit code.
pub(crate) async fn run(action: &MessageAction) -> Result<i32> {
    let homes = HarnessHomes::default();
    match action {
        MessageAction::NativeQuestionHook { binding } => {
            let mut text = String::new();
            std::io::stdin().read_to_string(&mut text)?;
            let output =
                supercode_harness::mail_question::hook(binding, serde_json::from_str(&text)?)
                    .await?;
            println!("{output}");
            Ok(0)
        }
        MessageAction::Questions => {
            supercode_harness::mail_question::poll().await;
            Ok(0)
        }
        MessageAction::List { json } => list(&homes, *json),
        MessageAction::Send {
            to,
            body,
            subject,
            file,
            in_reply_to,
            notify_when_idle,
            queue,
            id,
        } => {
            let body = read_body(body.as_deref(), file.as_ref())?;
            send(
                &homes,
                to,
                &body,
                supercode_harness::mail_send::SendOptions {
                    subject: subject.clone(),
                    in_reply_to: in_reply_to.clone(),
                    notify_when_idle: *notify_when_idle,
                    queue: *queue,
                    idempotency_key: id.clone(),
                    notice: false,
                },
            )
            .await
        }
        MessageAction::Inbox {
            all,
            json,
            session,
            recent,
        } => match session {
            Some(session) => inbox_of(&homes, session, *json, *recent),
            None => inbox(&homes, *all || recent.is_some(), *json, *recent),
        },
        MessageAction::Show {
            ids,
            json,
            replies: true,
        } => show_replies(ids, *json),
        MessageAction::Show { ids, json, .. } => show(&homes, ids, *json),
        MessageAction::Reply {
            id,
            body,
            file,
            notify_when_idle,
            queue,
        } => {
            let mailbox = match caller_mailbox(&homes) {
                Ok(mailbox) => mailbox,
                Err(message) => {
                    eprintln!("{message}");
                    return Ok(EXIT_REFUSED);
                }
            };
            let found = mailbox.find_prefix(id)?;
            let [answered] = found.as_slice() else {
                eprintln!(
                    "Not sent: {id} names {} messages in your mailbox. Name the one you answer as \
                     its envelope shows it.",
                    found.len()
                );
                return Ok(EXIT_REFUSED);
            };
            if answered.envelope.kind == MailKind::Notice {
                eprintln!("Not sent: {id} is an automated notice; nothing reads a reply to it.");
                return Ok(EXIT_REFUSED);
            }
            let body = read_body(body.as_deref(), file.as_ref())?;
            send(
                &homes,
                &answered.envelope.from.to_string(),
                &body,
                supercode_harness::mail_send::SendOptions {
                    subject: answered.envelope.subject.as_ref().map(|subject| {
                        if subject.starts_with("Re: ") {
                            subject.clone()
                        } else {
                            format!("Re: {subject}")
                        }
                    }),
                    in_reply_to: Some(answered.envelope.id.clone()),
                    notify_when_idle: *notify_when_idle,
                    queue: *queue,
                    idempotency_key: None,
                    notice: false,
                },
            )
            .await
        }
        MessageAction::Thread { id, json } => thread(id, *json),
        MessageAction::Delegate {
            root,
            folder,
            harness,
        } => delegate(&homes, root, folder.as_deref(), harness.as_deref()),
        MessageAction::Threads { agent, json } => threads(&homes, agent.as_deref(), *json),
        MessageAction::Wait { from, timeout } => wait(&homes, from.as_deref(), *timeout).await,
        MessageAction::RelayInbound {
            represented,
            directory,
        } => relay_inbound(&homes, represented, directory),
        MessageAction::RemoteDeliver => remote_deliver(&homes).await,
        MessageAction::Push { address, id } => push(&homes, address, id).await,
        MessageAction::Mcp => {
            let cwd = std::env::current_dir().unwrap_or_default();
            supercode_harness::mcp::serve_stdio(
                &supercode_harness::mail_mcp::registry(),
                &supercode_harness::tools::ToolContext::new(cwd),
            )
            .await?;
            Ok(0)
        }
        MessageAction::Gate { directory } => gate(directory),
        MessageAction::RelayReceipt { directory } => relay_receipt(directory),
        MessageAction::Setup { harness } => setup(harness),
        MessageAction::Hook { harness } => hook(harness),
        MessageAction::Watch => {
            tokio::spawn(async {
                if let Err(error) = supercode_harness::relay_endpoint::serve_relay_endpoint().await
                {
                    eprintln!("supercode: the relay endpoint stopped: {error}");
                    std::process::exit(1);
                }
            });
            let mut watcher = supercode_harness::mail_watch::IdleWatcher::new();
            // Its daemon may die without stopping it (a service manager's kill, a crash); reparented, it would run on
            // beside the next daemon's watcher and type each waiting turn twice. It goes with the daemon that began it.
            #[cfg(unix)]
            let parent = std::os::unix::process::parent_id();
            let mut ticks: u64 = 0;
            loop {
                #[cfg(unix)]
                if std::os::unix::process::parent_id() != parent {
                    return Ok(0);
                }
                if ticks % 5 == 0 {
                    supercode_harness::mail_question::poll().await;
                }
                watcher.tick(&homes).await;
                // every ten seconds: an agent's directly started sessions become threads, and
                // lines typed into its sessions reach whoever is CC on them
                if ticks % 5 == 0 {
                    supercode_harness::mail_agent::register_folder_sessions(&homes);
                    supercode_harness::mail_agent::copy_typed_lines(&homes);
                    supercode_harness::mail_agent::close_idle_threads(&homes);
                }
                supercode_harness::mail_watch::deliver_waiting_user_turns(&homes).await;
                supercode_harness::mail_watch::wake_waiting_hook_mail(&homes).await;
                // about once a minute: the mail relays of sessions that have ended are retired
                if ticks % 30 == 0 {
                    supercode_harness::claude_relay::retire_relays_of_ended_sessions(&homes).await;
                }
                ticks = ticks.wrapping_add(1);
                tokio::time::sleep(Duration::from_secs(2)).await;
            }
        }
    }
}

/// `message delegate`: main hands the thread of `root` to a new session of its agent.
/// Open a new session of `program` in its own pane (headful: the machine shows its window) in
/// `directory`, typed `input` once ready, and return its address. Claude is told its session id
/// before it starts; any other harness (Codex) is found as the session that appears in the new
/// pane, within a minute. The launch key means a second call never opens a second pane.
fn open_session(
    homes: &HarnessHomes,
    program: &str,
    directory: &std::path::Path,
    key: &str,
    input: &str,
    ready: &dyn Fn(&supercode_harness::mailbox::MailAddress) -> std::result::Result<(), String>,
) -> std::result::Result<supercode_harness::mailbox::MailAddress, String> {
    let stem = std::path::Path::new(program)
        .file_stem()
        .and_then(|stem| stem.to_str())
        .unwrap_or(program)
        .to_string();
    let claude = stem == "claude" || stem == "claude-code";
    let mut extra = Vec::new();
    let mut known = None;
    if claude {
        let mut random = [0u8; 16];
        getrandom::getrandom(&mut random).map_err(|error| error.to_string())?;
        random[6] = (random[6] & 0x0f) | 0x40;
        random[8] = (random[8] & 0x3f) | 0x80;
        let hex: String = random.iter().map(|byte| format!("{byte:02x}")).collect();
        let session_id = format!(
            "{}-{}-{}-{}-{}",
            &hex[..8],
            &hex[8..12],
            &hex[12..16],
            &hex[16..20],
            &hex[20..]
        );
        known = Some(
            supercode_harness::mailbox::MailAddress::new(
                supercode_harness::mailbox::local_machine_name(),
                "claude-code",
                &session_id,
            )
            .map_err(|error| error.to_string())?,
        );
        extra = vec!["--".to_string(), "--session-id".to_string(), session_id];
    }
    // What the session must find from its first turn is in place before it starts, when its address is known.
    if let Some(address) = &known {
        ready(address)?;
    }
    let program_path =
        supercode_harness::claude_relay::supercode_program().map_err(|error| error.to_string())?;
    let output = std::process::Command::new(program_path)
        .arg("--cwd")
        .arg(directory)
        .args([
            "open", "--new", program, "--key", key, "--input", input, "--detach",
        ])
        .args(&extra)
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|error| error.to_string())?;
    if !output.status.success() {
        return Err(format!(
            "the session did not start: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    if let Some(address) = known {
        return Ok(address);
    }
    let printed: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_default();
    let pane = printed["pane"]
        .as_str()
        .ok_or_else(|| "the new pane was not reported".to_string())?
        .to_string();
    let started = Instant::now();
    while started.elapsed() < Duration::from_secs(60) {
        if let Some(session) = supercode_harness::mail_route::LiveSessions::read(homes)
            .all()
            .iter()
            .find(|session| {
                supercode_harness::mail_route::daemon_pane(session).as_deref() == Some(&pane)
            })
        {
            ready(&session.address)?;
            return Ok(session.address.clone());
        }
        std::thread::sleep(Duration::from_millis(500));
    }
    Err(format!(
        "{program} started in pane {pane}, but no session appeared there within a minute"
    ))
}

fn delegate(
    homes: &HarnessHomes,
    root: &str,
    folder: Option<&std::path::Path>,
    harness: Option<&str>,
) -> Result<i32> {
    use supercode_harness::mail_agent;
    let mailbox = match caller_mailbox(homes) {
        Ok(mailbox) => mailbox,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let found = mailbox.find_prefix(root)?;
    let [stored] = found.as_slice() else {
        eprintln!(
            "Not delegated: {root} names {} messages in your mailbox. Name the root as your inbox \
             shows it.",
            found.len()
        );
        return Ok(EXIT_REFUSED);
    };
    let thread_id = stored.envelope.thread_id().to_string();
    // A line in main's own session (its terminal, its DM) is a root of the agent: main opens its thread to delegate it.
    let opened = match mail_agent::thread(&thread_id) {
        Some(thread) => Some(thread),
        None => mail_agent::root_of_main(mailbox.address(), &stored.envelope)?,
    };
    let Some(thread) = opened else {
        eprintln!(
            "Not delegated: {} is not in a thread of an agent. Only a root an agent received can \
             be delegated.",
            supercode_harness::mailbox::short_id(&stored.envelope.id)
        );
        return Ok(EXIT_REFUSED);
    };
    let Some(agent) = mail_agent::load(&thread.agent) else {
        eprintln!(
            "Not delegated: agent {} is no longer declared.",
            thread.agent
        );
        return Ok(EXIT_REFUSED);
    };
    let caller = mailbox.address().clone();
    if agent.main_session != caller || thread.holder != caller {
        eprintln!(
            "Not delegated: only {}'s main session delegates a thread it holds.",
            agent.name
        );
        return Ok(EXIT_REFUSED);
    }
    let program = harness
        .map(str::to_string)
        .or_else(|| agent.harness.clone())
        .unwrap_or_else(|| "claude".to_string());
    let directory = folder
        .map(std::path::Path::to_path_buf)
        .or_else(|| agent.folder.clone())
        .or_else(|| std::env::current_dir().ok())
        .ok_or_else(|| anyhow::anyhow!("no directory to start the session in"))?;
    let shown_root = supercode_harness::mailbox::short_id(&thread.id);
    let input = format!(
        "You are a session of agent {name}, holding its thread {shown_root}. Read it: supercode \
         message thread {shown_root}. Answer in it with supercode message reply <id>; what you \
         send stays in this thread, and {name}'s main session is CC on it.",
        name = agent.name
    );
    // The new session holds the thread and has its messages before it starts, so its first turn finds its root
    // (a Codex session, whose id is known only once it runs, takes them as soon as it is found).
    let thread_id = thread.id.clone();
    let hand_over =
        |holder: &supercode_harness::mailbox::MailAddress| -> std::result::Result<(), String> {
            let holder_mailbox = Mailbox::open(&supercode_harness::mailbox::mail_root(), holder)
                .map_err(|error| error.to_string())?;
            for line in mailbox.list().map_err(|error| error.to_string())? {
                if line.envelope.thread_id() == thread_id {
                    // A line typed into main's terminal reaches the holder as one typed in another session
                    // (`Typed`, ADR 0008): as `User` mail, the holder's own transcript reading would take it back.
                    let mut envelope = line.envelope.clone();
                    if envelope.kind == supercode_harness::mailbox::MailKind::User {
                        envelope.kind = supercode_harness::mailbox::MailKind::Typed;
                    }
                    holder_mailbox
                        .deliver_read(&envelope)
                        .map_err(|error| error.to_string())?;
                }
            }
            mail_agent::delegate_to(&thread_id, holder, true).map_err(|error| error.to_string())?;
            Ok(())
        };
    let holder = match open_session(
        homes,
        &program,
        &directory,
        &format!("delegate:{}", thread.id),
        &input,
        &hand_over,
    ) {
        Ok(holder) => holder,
        Err(message) => {
            // The thread goes back to main, so nothing waits on a session that never started.
            mail_agent::delegate_to(&thread.id, &caller, false)?;
            eprintln!("Not delegated: {message}");
            return Ok(EXIT_FAILED);
        }
    };
    let session_id = holder.session_id.clone();
    println!(
        "Delegated thread {shown_root} to a new session of {} ({holder}) in {}. You are CC on it. \
         Continue there: supercode open {session_id}",
        agent.name,
        directory.display()
    );
    Ok(0)
}

/// `message threads`: an agent's threads, oldest first.
fn threads(homes: &HarnessHomes, agent: Option<&str>, json: bool) -> Result<i32> {
    use supercode_harness::mail_agent;
    let name = match agent {
        Some(name) => name.to_string(),
        None => {
            let caller = caller_mailbox(homes)
                .map(|mailbox| mailbox.address().clone())
                .ok();
            match caller.as_ref().and_then(mail_agent::agent_of_session) {
                Some(agent) => agent.name,
                None => {
                    eprintln!(
                        "Name the agent with --agent: this session is not one of an agent's."
                    );
                    return Ok(EXIT_REFUSED);
                }
            }
        }
    };
    let rows: Vec<serde_json::Value> = mail_agent::threads_of(&name)
        .into_iter()
        .map(|thread| {
            let newest = supercode_harness::mail_transcript::find_messages(
                &supercode_harness::mailbox::mail_root(),
                &thread.id,
            )
            .ok()
            .and_then(|found| found.into_iter().next())
            .map(|(_, stored)| stored.envelope.body.lines().next().unwrap_or("").to_string());
            serde_json::json!({
                "id": thread.id,
                "holder": thread.holder.to_string(),
                "participants": thread.participants.iter().map(|p| serde_json::json!({
                    "address": p.address.to_string(),
                    "role": match p.role { mail_agent::Role::To => "to", mail_agent::Role::Cc => "cc" },
                })).collect::<Vec<_>>(),
                "surface": thread.surface,
                "opened_at": supercode_interchange::sidecar::ms_to_rfc3339(thread.created_at_ms as i64),
                "root": newest,
            })
        })
        .collect();
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(0);
    }
    if rows.is_empty() {
        println!("Agent {name} has no threads.");
        return Ok(0);
    }
    for row in rows {
        let id = row["id"].as_str().unwrap_or_default();
        let participants: Vec<String> = row["participants"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|p| {
                format!(
                    "{} ({})",
                    p["address"].as_str().unwrap_or_default(),
                    p["role"].as_str().unwrap_or_default()
                )
            })
            .collect();
        println!(
            "{}  opened {}  held by {}\n  {}\n  {}",
            supercode_harness::mailbox::short_id(id),
            row["opened_at"].as_str().unwrap_or_default(),
            row["holder"].as_str().unwrap_or_default(),
            participants.join(", "),
            row["root"].as_str().unwrap_or("(no root message)")
        );
    }
    Ok(0)
}

/// `supercode agent`: declare an agent's mailbox record and read it.
#[derive(Subcommand)]
pub(crate) enum AgentAction {
    /// Declare an agent on this machine, or replace its record: its main session receives every
    /// root addressed to it (`sc:<machine>:agent:<name>`).
    Declare {
        /// Its name.
        name: String,
        /// Its main session: an address, or the name of a session running here.
        #[arg(
            long,
            value_name = "SESSION",
            required_unless_present = "open",
            conflicts_with = "open"
        )]
        main: Option<String>,
        /// Start its main session instead: a new pane running this program (`claude`, `codex`) in
        /// `--folder`, typed `--input` once ready. A declared main that is still running, or that
        /// mail may resume, is kept, so an install's every start may say this.
        #[arg(long, value_name = "PROGRAM")]
        open: Option<String>,
        /// With --open: the main session's first message.
        #[arg(long, value_name = "TEXT", requires = "open")]
        input: Option<String>,
        /// Where its sessions start; a session started directly here is one of its threads.
        #[arg(long, value_name = "DIR")]
        folder: Option<PathBuf>,
        /// The program `message delegate` starts (`claude`).
        #[arg(long, value_name = "PROGRAM")]
        harness: Option<String>,
        /// Minutes a session `message delegate` started may stay idle before its process ends; the
        /// next reply in its thread resumes it.
        #[arg(long, value_name = "MINUTES")]
        idle_minutes: Option<u64>,
        /// It is the owner's account manager: every line the owner writes to any agent is CC'd
        /// to it.
        #[arg(long)]
        owners_account_manager: bool,
    },
    /// Show one declared agent, or all of them.
    Show {
        /// Its name.
        name: Option<String>,
        /// Print JSON.
        #[arg(long)]
        json: bool,
    },
}

/// Run `supercode agent`.
pub(crate) fn run_agent(action: &AgentAction) -> Result<i32> {
    use supercode_harness::mail_agent;
    let homes = HarnessHomes::default();
    match action {
        AgentAction::Declare {
            name,
            main,
            open,
            input,
            folder,
            harness,
            idle_minutes,
            owners_account_manager,
        } => {
            let main = match (main, open) {
                (Some(main), _) => main.clone(),
                (None, Some(program)) => {
                    let live = supercode_harness::mail_route::LiveSessions::read(&homes);
                    let kept = mail_agent::load(name)
                        .map(|agent| agent.main_session)
                        .filter(|main| {
                            live.all().iter().any(|session| &session.address == main)
                                || mail_agent::resumable(main)
                        });
                    match kept {
                        Some(main) => main.to_string(),
                        None => {
                            let directory = match folder {
                                Some(folder) => std::fs::canonicalize(folder)?,
                                None => std::env::current_dir()?,
                            };
                            let first = input.clone().unwrap_or_else(|| {
                                format!(
                                    "You are the main session of agent {name}. Roots addressed to it \
                                     reach you: answer each or delegate it (supercode message delegate)."
                                )
                            });
                            match open_session(
                                &homes,
                                program,
                                &directory,
                                &format!("agent:{name}"),
                                &first,
                                &|_| Ok(()),
                            ) {
                                Ok(address) => address.to_string(),
                                Err(message) => {
                                    eprintln!("Not declared: {message}");
                                    return Ok(EXIT_FAILED);
                                }
                            }
                        }
                    }
                }
                (None, None) => unreachable!("clap requires --main or --open"),
            };
            let main = &main;
            let main_session = match supercode_harness::mailbox::MailAddress::parse(main) {
                Ok(address) => address,
                Err(_) => {
                    match supercode_harness::mail_route::LiveSessions::read(&homes).resolve(main) {
                        Ok(session) => session.address.clone(),
                        Err(
                            supercode_harness::mail_route::Unresolved::Stale(message)
                            | supercode_harness::mail_route::Unresolved::Unknown(message),
                        ) => {
                            eprintln!("{message}");
                            return Ok(EXIT_UNKNOWN);
                        }
                    }
                }
            };
            let folder = match folder {
                Some(folder) => Some(std::fs::canonicalize(folder)?),
                None => None,
            };
            let agent = mail_agent::Agent {
                name: name.clone(),
                main_session,
                folder,
                harness: harness.clone(),
                idle_minutes: *idle_minutes,
            };
            mail_agent::declare(&agent)?;
            if *owners_account_manager {
                mail_agent::set_owners_account_manager(name)?;
            }
            println!(
                "Declared agent {name} ({}): roots go to {}.{}",
                agent.address()?,
                agent.main_session,
                if *owners_account_manager {
                    " It is the owner's account manager."
                } else {
                    ""
                }
            );
            Ok(0)
        }
        AgentAction::Show { name, json } => {
            let agents: Vec<mail_agent::Agent> = match name {
                Some(name) => match mail_agent::load(name) {
                    Some(agent) => vec![agent],
                    None => {
                        eprintln!("No agent named {name} is declared on this machine.");
                        return Ok(EXIT_UNKNOWN);
                    }
                },
                None => mail_agent::all_agents(),
            };
            let account_manager = mail_agent::owners_account_manager().map(|agent| agent.name);
            if *json {
                println!("{}", serde_json::to_string_pretty(&agents)?);
                return Ok(0);
            }
            if agents.is_empty() {
                println!("No agents are declared on this machine.");
            }
            for agent in agents {
                println!(
                    "{}  {}\n  main: {}\n  folder: {}\n  threads: {}{}",
                    agent.name,
                    agent.address()?,
                    agent.main_session,
                    agent
                        .folder
                        .as_ref()
                        .map_or("(none)".to_string(), |folder| folder.display().to_string()),
                    mail_agent::threads_of(&agent.name).len(),
                    if account_manager.as_deref() == Some(agent.name.as_str()) {
                        "\n  the owner's account manager"
                    } else {
                        ""
                    }
                );
            }
            Ok(0)
        }
    }
}

/// The sessions on this machine that can be messaged, as `message list --json` rows.
fn session_rows(homes: &HarnessHomes) -> Vec<serde_json::Value> {
    // The daemon's pane listing is read beside the live sessions, not after them: each is a daemon
    // round trip of its own (t_23e47b73).
    let panes_read = std::thread::spawn(daemon_pane_processes);
    let live = supercode_harness::mail_route::LiveSessions::read(homes);
    let mut panes = Some(panes_read.join().unwrap_or_default());
    let mut parents = None;
    live.all()
        .iter()
        .map(|peer| {
            serde_json::json!({
                "name": peer.name,
                "harness": peer.address.harness,
                "status": peer.status,
                "delivery": peer.door.name(),
                "address": peer.address.to_string(),
                "pane": session_pane_in(peer.tmux.as_deref(), peer.pid, &mut panes, &mut parents),
                "last_message_at_ms": peer.last_message_at_ms(homes),
                "pending_request": peer.pending_request(homes),
            })
        })
        .collect()
}

/// The sessions on the team's other online machines, asked of each machine's
/// mail door in parallel; a machine that cannot answer is left out. Empty
/// without a Teams context.
/// The team's other machines that are enrolled and online now.
fn team_machines() -> Vec<String> {
    supercode_harness::slow_log::timed("teams machines list", team_machines_now)
}

fn team_machines_now() -> Vec<String> {
    let Ok(program) = supercode_harness::claude_relay::supercode_program() else {
        return Vec::new();
    };
    let Ok(output) = std::process::Command::new(program)
        .args(["teams", "machines", "list", "--json"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
    else {
        return Vec::new();
    };
    let local = supercode_harness::mailbox::local_machine_name();
    let machines: Vec<String> = serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .ok()
        .and_then(|value| value["items"].as_array().cloned())
        .unwrap_or_default()
        .into_iter()
        .filter(|machine| machine["enrollment"] == "active" && machine["connection"] == "online")
        .filter_map(|machine| machine["name"].as_str().map(str::to_string))
        .filter(|name| *name != local)
        .collect();
    machines
}

fn team_rows() -> Vec<serde_json::Value> {
    let handles: Vec<_> = team_machines()
        .into_iter()
        .map(|machine| {
            std::thread::spawn(move || {
                supercode_harness::mailbox::teams_mail(&machine, &serde_json::json!({"op": "list"}))
                    .ok()
                    .and_then(|answer| answer["sessions"].as_array().cloned())
                    .unwrap_or_default()
            })
        })
        .collect();
    handles
        .into_iter()
        .flat_map(|handle| handle.join().unwrap_or_default())
        .collect()
}

fn list(homes: &HarnessHomes, json: bool) -> Result<i32> {
    // The team's other machines are asked beside this machine's own sessions.
    let team = std::thread::spawn(team_rows);
    let mut rows = session_rows(homes);
    rows.extend(team.join().unwrap_or_default());
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(0);
    }
    println!(
        "{:<34} {:<12} {:<8} {:<9} {:<16} ADDRESS",
        "NAME", "HARNESS", "STATUS", "DELIVERY", "PANE"
    );
    let text =
        |row: &serde_json::Value, key: &str| row[key].as_str().unwrap_or_default().to_string();
    for row in &rows {
        println!(
            "{:<34} {:<12} {:<8} {:<9} {:<16} {}",
            text(row, "name"),
            text(row, "harness"),
            text(row, "status"),
            text(row, "delivery"),
            text(row, "pane"),
            text(row, "address")
        );
    }
    Ok(0)
}

fn read_body(body: Option<&str>, file: Option<&PathBuf>) -> Result<String> {
    let text = match (body, file) {
        (Some(body), _) => body.to_string(),
        (None, Some(path)) => std::fs::read_to_string(path)
            .map_err(|error| anyhow!("could not read {}: {error}", path.display()))?,
        (None, None) => {
            let mut text = String::new();
            std::io::stdin().read_to_string(&mut text)?;
            text
        }
    };
    let text = text.trim_end_matches('\n').to_string();
    if text.trim().is_empty() {
        return Err(anyhow!("Nothing was sent: the message is empty."));
    }
    Ok(text)
}

/// Print an outcome for the agent (a success on stdout, anything else on
/// stderr) and return its exit code.
fn print_outcome(outcome: supercode_harness::mail_send::Outcome) -> i32 {
    if outcome.code == 0 {
        println!("{}", outcome.text);
    } else {
        eprintln!("{}", outcome.text);
    }
    outcome.code
}

async fn send(
    homes: &HarnessHomes,
    to: &str,
    body: &str,
    options: supercode_harness::mail_send::SendOptions,
) -> Result<i32> {
    let caller = match resolve_caller(homes, &supercode_harness::mail_route::process_ancestry()) {
        Ok(caller) => caller,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let to = team_address(homes, to).unwrap_or_else(|| to.to_string());
    let outcome = supercode_harness::mail_send::send(homes, &caller, &to, body, options).await?;
    Ok(print_outcome(outcome))
}

/// A name `list` prints for a session on another of the team's machines is sendable as its bare
/// name, as a session here is: when no session here has the name, the team's other machines are
/// asked, and a single session there with it is its address.
fn team_address(homes: &HarnessHomes, to: &str) -> Option<String> {
    if to.contains('@') || to.starts_with("sc:") {
        return None;
    }
    let short = |row: &serde_json::Value| {
        row["name"]
            .as_str()
            .unwrap_or_default()
            .split('@')
            .next()
            .unwrap_or_default()
            .to_string()
    };
    if session_rows(homes).iter().any(|row| short(row) == to) {
        return None;
    }
    let found: Vec<String> = team_rows()
        .iter()
        .filter(|row| short(row) == to)
        .filter_map(|row| row["address"].as_str().map(str::to_string))
        .collect();
    match found.as_slice() {
        [only] => Some(only.clone()),
        _ => None,
    }
}

/// The daemon pane a session runs in: the tmux session Claude records, when it is a daemon
/// pane, else the pane whose process is the session's own or one of its ancestors (a pane
/// with no tmux under it, as on Windows). `panes` holds this machine's panes once read.
pub(crate) fn session_pane(
    tmux: Option<&str>,
    pid: Option<u32>,
    panes: &mut Option<Vec<(u32, String)>>,
) -> Option<String> {
    session_pane_in(tmux, pid, panes, &mut None)
}

/// [`session_pane`], with the process table read once for every session a caller maps.
fn session_pane_in(
    tmux: Option<&str>,
    pid: Option<u32>,
    panes: &mut Option<Vec<(u32, String)>>,
    parents: &mut Option<std::collections::HashMap<u32, u32>>,
) -> Option<String> {
    if let Some(pane) = tmux
        .and_then(|tmux| tmux.split(':').next())
        .filter(|session| crate::open::is_daemon_pane(session))
    {
        return Some(pane.to_string());
    }
    let pid = pid?;
    let panes = panes.get_or_insert_with(daemon_pane_processes);
    if panes.is_empty() {
        return None;
    }
    let parents = parents.get_or_insert_with(supercode_harness::mail_route::parent_table);
    let ancestry = supercode_harness::mail_route::ancestry_in(pid, parents);
    ancestry.iter().find_map(|ancestor| {
        panes
            .iter()
            .find(|(root, _)| root == ancestor)
            .map(|(_, pane)| pane.clone())
    })
}

/// This machine's daemon panes by their root process, from `teams panes ls --processes` (the pane
/// listing alone, no screen read); none when no daemon answers.
fn daemon_pane_processes() -> Vec<(u32, String)> {
    supercode_harness::slow_log::timed("teams panes ls --processes", daemon_pane_processes_now)
}

fn daemon_pane_processes_now() -> Vec<(u32, String)> {
    let Ok(program) = std::env::current_exe() else {
        return Vec::new();
    };
    let Ok(output) = std::process::Command::new(program)
        .args(["teams", "panes", "ls", "--processes"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
    else {
        return Vec::new();
    };
    serde_json::from_slice::<Vec<serde_json::Value>>(&output.stdout)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|row| {
            let pid = u32::try_from(row["pid"].as_u64()?).ok()?;
            Some((pid, row["pane"].as_str()?.to_string()))
        })
        .collect()
}

/// The running session `wanted` names on another of the team's machines, as its `message list`
/// row: an address or `name@machine` there (asked of that machine only), or a bare name no
/// session here has and exactly one session there has.
pub(crate) fn team_session(homes: &HarnessHomes, wanted: &str) -> Option<serde_json::Value> {
    let Some(machine) = other_machine(wanted) else {
        let address = team_address(homes, wanted)?;
        return team_rows()
            .into_iter()
            .find(|row| row["address"].as_str() == Some(&address));
    };
    let rows = supercode_harness::mailbox::teams_mail(&machine, &serde_json::json!({"op": "list"}))
        .ok()?["sessions"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    let address = MailAddress::parse(wanted)
        .ok()
        .map(|address| address.to_string());
    rows.into_iter().find(|row| match &address {
        Some(address) => row["address"].as_str() == Some(address),
        None => {
            row["name"].as_str().and_then(|name| name.split('@').next()) == wanted.split('@').next()
        }
    })
}

/// The machine a session name or address names when it is another of the team's machines
/// (an `sc:` address there, or `name@machine`), in the form addresses use.
pub(crate) fn other_machine(wanted: &str) -> Option<String> {
    let machine = match MailAddress::parse(wanted) {
        Ok(address) => address.machine,
        Err(_) => supercode_harness::mailbox::normal_machine_name(wanted.rsplit_once('@')?.1),
    };
    (machine != local_machine_name()).then_some(machine)
}

fn caller_mailbox(homes: &HarnessHomes) -> std::result::Result<Mailbox, String> {
    let caller = resolve_caller(homes, &supercode_harness::mail_route::process_ancestry())?;
    Mailbox::open(&mail_root(), &caller.address).map_err(|error| error.to_string())
}

fn inbox(homes: &HarnessHomes, all: bool, json: bool, last: Option<usize>) -> Result<i32> {
    let mailbox = match caller_mailbox(homes) {
        Ok(mailbox) => mailbox,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let transcript = supercode_harness::mail_transcript::read(homes, mailbox.address());
    if all {
        if let Some(mail) = &transcript {
            supercode_harness::mail_transcript::file_typed_lines(&mailbox, mail)?;
        }
    }
    let claimed = mailbox.claim_unread()?;
    let stored = if all {
        let mut stored: Vec<_> = mailbox
            .list()?
            .into_iter()
            .filter(|stored| {
                // A user turn being typed in (claimed by its typer, not yet acknowledged) is this session's current
                // input: the session sees it while it answers it, as it sees its read mail.
                stored.state == supercode_harness::mailbox::MailState::Read
                    || (stored.envelope.kind == MailKind::User
                        && stored
                            .path
                            .parent()
                            .and_then(|dir| dir.file_name())
                            .is_some_and(|dir| dir == "claimed"))
            })
            .collect();
        // Unread mail is always shown: it is marked read once printed.
        if let Some(last) = last {
            stored.drain(..stored.len().saturating_sub(last));
        }
        stored.extend(claimed.iter().cloned());
        stored.sort_by_key(|stored| stored.envelope.created_at_ms);
        stored
    } else {
        claimed.clone()
    };
    let deliveries = supercode_harness::mail_transcript::deliveries(
        mailbox.address(),
        &stored,
        transcript.as_ref(),
    );
    if json {
        let rows: Vec<_> = stored
            .iter()
            .map(|stored| message_row(mailbox.address(), stored, &deliveries))
            .collect();
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else if stored.is_empty() {
        println!("No unread messages.");
    } else {
        for stored in &stored {
            println!("{}\n", listed(&stored.envelope, &deliveries));
        }
    }
    // Acknowledged only after printing: a crash before this shows them again.
    for stored in &claimed {
        mailbox.acknowledge(stored)?;
    }
    Ok(0)
}

/// A message as an inbox lists it: when it was sent and when it reached the model; a user's turn,
/// delivered as the bare words the user wrote, also with the id and author its delivery leaves out.
fn listed(envelope: &Envelope, deliveries: &Deliveries) -> String {
    let sent = supercode_interchange::sidecar::ms_to_rfc3339(envelope.created_at_ms as i64);
    let native = supercode_harness::mail_question::delivered_at(envelope)
        .map(|at_ms| supercode_harness::mail_transcript::Delivery::Delivered { at_ms });
    let delivered = native
        .as_ref()
        .or_else(|| deliveries.get(&envelope.id))
        .map(supercode_harness::mail_transcript::Delivery::describe)
        .unwrap_or_else(|| "unknown".to_string());
    if envelope.kind == MailKind::Answer {
        return format!("{}\n(sent {sent})", envelope.render());
    }
    if envelope.kind != MailKind::User {
        return format!(
            "{}\n(sent {sent}; delivered to the model: {delivered})",
            envelope.render()
        );
    }
    format!(
        "<user-message id=\"{}\" from-name=\"{}\"{} sent=\"{sent}\" delivered=\"{delivered}\">\n{}\n</user-message>",
        supercode_harness::mailbox::short_id(&envelope.id),
        printable(&envelope.from_name),
        envelope.in_reply_to.as_deref().map_or(String::new(), |parent| format!(
            " in-reply-to=\"{}\"{}",
            supercode_harness::mailbox::short_id(parent),
            if envelope.in_reply_to_inferred { " in-reply-to-inferred=\"true\"" } else { "" }
        )),
        supercode_harness::mailbox::escape_body(&envelope.body),
    )
}

type Deliveries = std::collections::BTreeMap<String, supercode_harness::mail_transcript::Delivery>;

fn message_row(
    address: &MailAddress,
    stored: &supercode_harness::mailbox::StoredEnvelope,
    deliveries: &Deliveries,
) -> serde_json::Value {
    serde_json::json!({
        "session": address.to_string(),
        "state": stored.state,
        "delivery": supercode_harness::mail_question::delivered_at(&stored.envelope)
            .map(|at_ms| supercode_harness::mail_transcript::Delivery::Delivered { at_ms })
            .as_ref().or_else(|| deliveries.get(&stored.envelope.id)),
        "envelope": stored.envelope,
        "rendered": listed(&stored.envelope, deliveries),
    })
}

/// `inbox --session`: everything into and out of another session, read without marking anything
/// read: its mail, the lines its user typed, its messages to other sessions and its answers to its
/// user, oldest first.
fn inbox_of(homes: &HarnessHomes, session: &str, json: bool, last: Option<usize>) -> Result<i32> {
    let address = match MailAddress::parse(session) {
        Ok(address) => address,
        Err(_) => match supercode_harness::mail_route::LiveSessions::read(homes).resolve(session) {
            Ok(live) => live.address.clone(),
            Err(_) => {
                eprintln!(
                    "No running session here is named \"{session}\". Name it by its address \
                     (sc:<machine>:<harness>:<id>), which also works after it has ended and on \
                     the team's other machines; supercode message list shows the running ones."
                );
                return Ok(EXIT_UNKNOWN);
            }
        },
    };
    let rows = if address.machine == local_machine_name() {
        inbox_rows(homes, &address, last)?
    } else {
        let request =
            serde_json::json!({"op": "inbox", "session": address.to_string(), "recent": last});
        match supercode_harness::mailbox::teams_mail(&address.machine, &request) {
            Ok(answer) if answer["code"].as_i64() == Some(0) => {
                answer["rows"].as_array().cloned().unwrap_or_default()
            }
            Ok(answer) => {
                eprintln!(
                    "{}",
                    answer["text"].as_str().unwrap_or("its machine refused")
                );
                return Ok(EXIT_UNKNOWN);
            }
            Err(error) => {
                eprintln!(
                    "{address} is on machine {}, which did not answer: {error}",
                    address.machine
                );
                return Ok(EXIT_UNKNOWN);
            }
        }
    };
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else if rows.is_empty() {
        println!("{address} has no messages.");
    } else {
        for row in &rows {
            if row["direction"] == "out" {
                println!("Sent to {}:", row["session"].as_str().unwrap_or_default());
            }
            println!("{}\n", row["rendered"].as_str().unwrap_or_default());
        }
    }
    Ok(0)
}

/// How many receivers' transcripts one listing reads for the state of the messages it sent.
const MAX_RECEIVERS_READ: usize = 6;

/// Everything into and out of the session at `address` on this machine, oldest first, as
/// `inbox --session --json` rows (the newest `last` only, when given).
fn inbox_rows(
    homes: &HarnessHomes,
    address: &MailAddress,
    last: Option<usize>,
) -> Result<Vec<serde_json::Value>> {
    let name = supercode_harness::mail_route::LiveSessions::read(homes)
        .all()
        .iter()
        .find(|session| &session.address == address)
        .map(|session| session.name.clone())
        .unwrap_or_else(|| {
            let short: String = address.session_id.chars().take(8).collect();
            format!("{}-{short}@{}", address.harness, address.machine)
        });
    let root = mail_root();
    let mailbox = Mailbox::open(&root, address)?;
    let transcript = supercode_harness::mail_transcript::read(homes, address);
    if let Some(mail) = &transcript {
        supercode_harness::mail_transcript::file_typed_lines(&mailbox, mail)?;
        supercode_harness::mail_transcript::file_answers(&root, address, &name, mail)?;
    }
    let received: Vec<_> = mailbox
        .list()?
        .into_iter()
        .filter(|stored| {
            !(stored.envelope.kind == MailKind::Question && &stored.envelope.from == address)
        })
        .collect();
    let mut deliveries =
        supercode_harness::mail_transcript::deliveries(address, &received, transcript.as_ref());
    let sent = supercode_harness::mail_transcript::sent_by(&root, address);
    let mut timeline: Vec<(
        &MailAddress,
        &supercode_harness::mailbox::StoredEnvelope,
        &str,
    )> = received
        .iter()
        .map(|stored| (address, stored, "in"))
        .chain(sent.iter().map(|(to, stored)| (to, stored, "out")))
        .collect();
    timeline.sort_by_key(|(_, stored, _)| stored.envelope.created_at_ms);
    if let Some(last) = last {
        timeline.drain(..timeline.len().saturating_sub(last));
    }
    // Where a message it sent stands is read from its receiver's transcript. Each is a full read,
    // so the listing reads the receivers of its newest messages; `show <id>` reads any other.
    let mut receivers: Vec<&MailAddress> = Vec::new();
    for (to, _, direction) in timeline.iter().rev() {
        if *direction == "out" && !receivers.contains(to) && receivers.len() < MAX_RECEIVERS_READ {
            receivers.push(to);
        }
    }
    for to in receivers {
        let theirs: Vec<supercode_harness::mailbox::StoredEnvelope> = timeline
            .iter()
            .filter(|(receiver, _, direction)| *direction == "out" && *receiver == to)
            .map(|(_, stored, _)| (*stored).clone())
            .collect();
        let mail = supercode_harness::mail_transcript::read(homes, to);
        deliveries.extend(supercode_harness::mail_transcript::deliveries(
            to,
            &theirs,
            mail.as_ref(),
        ));
    }
    for (_, stored, direction) in &timeline {
        if *direction == "out" && !deliveries.contains_key(&stored.envelope.id) {
            deliveries.insert(
                stored.envelope.id.clone(),
                supercode_harness::mail_transcript::Delivery::NotRead,
            );
        }
    }
    Ok(timeline
        .iter()
        .map(|(mailbox, stored, direction)| {
            let mut row = message_row(mailbox, stored, &deliveries);
            row["direction"] = serde_json::json!(direction);
            row
        })
        .collect())
}

/// `thread`: the conversation a message belongs to. Every message here is one node; a reply's
/// `in_reply_to` (stated or inferred) is its edge to what it answers, and a stored thread id joins
/// a message whose parent is not filed here. The conversation is everything reachable from the
/// message's root, oldest first.
fn thread(id: &str, json: bool) -> Result<i32> {
    let root_dir = mail_root();
    let mut all: std::collections::HashMap<
        String,
        (MailAddress, supercode_harness::mailbox::StoredEnvelope),
    > = std::collections::HashMap::new();
    for mailbox in supercode_harness::mailbox::all_mailboxes(&root_dir) {
        for stored in mailbox.list().unwrap_or_default() {
            all.entry(stored.envelope.id.clone())
                .or_insert((mailbox.address().clone(), stored));
        }
    }
    let matches: Vec<&String> = all.keys().filter(|key| key.starts_with(id)).collect();
    let [start] = matches.as_slice() else {
        eprintln!(
            "{id} names {} messages here; give one message's id.",
            matches.len()
        );
        return Ok(EXIT_UNKNOWN);
    };
    // Up to the root: the oldest ancestor filed here.
    let mut root = (*start).clone();
    let mut seen = std::collections::HashSet::new();
    while let Some(parent) = all
        .get(&root)
        .and_then(|(_, stored)| stored.envelope.in_reply_to.clone())
        .filter(|parent| all.contains_key(parent))
    {
        if !seen.insert(parent.clone()) {
            break;
        }
        root = parent;
    }
    let thread_of_root = all[&root].1.envelope.thread_id().to_string();
    // Down from the root: every reply, and every message naming the same thread.
    let mut children: std::collections::HashMap<&str, Vec<&str>> = std::collections::HashMap::new();
    for (key, (_, stored)) in &all {
        if let Some(parent) = &stored.envelope.in_reply_to {
            children
                .entry(parent.as_str())
                .or_default()
                .push(key.as_str());
        }
    }
    let mut members: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let mut queue: Vec<&str> = vec![root.as_str()];
    queue.extend(
        all.iter()
            .filter(|(_, (_, stored))| {
                stored.envelope.thread.as_deref() == Some(thread_of_root.as_str())
            })
            .map(|(key, _)| key.as_str()),
    );
    while let Some(next) = queue.pop() {
        if members.insert(next) {
            queue.extend(children.get(next).cloned().unwrap_or_default());
        }
    }
    let mut conversation: Vec<&(MailAddress, supercode_harness::mailbox::StoredEnvelope)> =
        members.iter().map(|key| &all[*key]).collect();
    conversation.sort_by_key(|(_, stored)| stored.envelope.created_at_ms);
    let deliveries = Deliveries::new();
    if json {
        let rows: Vec<_> = conversation
            .iter()
            .map(|(mailbox, stored)| message_row(mailbox, stored, &deliveries))
            .collect();
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else {
        for (mailbox, stored) in &conversation {
            println!("To {mailbox}:\n{}\n", listed(&stored.envelope, &deliveries));
        }
    }
    Ok(0)
}

/// `show`: messages by id or by an unambiguous prefix of one (as git takes a short hash), from
/// whichever mailbox holds each: this machine's, else the team's other online machines'.
fn show(homes: &HarnessHomes, ids: &[String], json: bool) -> Result<i32> {
    let mut rows = show_rows(homes, ids)?;
    let wanted: Vec<String> = rows
        .iter()
        .filter(|row| row["found"] == false && row["ambiguous"].is_null())
        .filter_map(|row| row["id"].as_str().map(str::to_string))
        .collect();
    if !wanted.is_empty() {
        // Every online machine is asked at once, as `team_rows` asks them for sessions.
        let handles: Vec<_> = team_machines()
            .into_iter()
            .map(|machine| {
                let request = serde_json::json!({"op": "show", "ids": wanted});
                std::thread::spawn(move || {
                    supercode_harness::mailbox::teams_mail(&machine, &request).ok()
                })
            })
            .collect();
        for handle in handles {
            let Some(answer) = handle.join().ok().flatten() else {
                continue;
            };
            for there in answer["rows"].as_array().cloned().unwrap_or_default() {
                if there["found"] != true && there["ambiguous"].is_null() {
                    continue;
                }
                if let Some(row) = rows
                    .iter_mut()
                    .find(|row| row["id"] == there["id"] && row["found"] == false)
                {
                    *row = there;
                }
            }
        }
    }
    let missing = rows.iter().any(|row| row["found"] != true);
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else {
        for row in &rows {
            let id = row["id"].as_str().unwrap_or_default();
            if row["found"] == true {
                println!(
                    "In the inbox of {} on {}:\n{}\n",
                    row["message"]["session"].as_str().unwrap_or_default(),
                    row["machine"].as_str().unwrap_or_default(),
                    row["message"]["rendered"].as_str().unwrap_or_default()
                );
            } else if let Some(ambiguous) = row["ambiguous"].as_array() {
                let ids: Vec<&str> = ambiguous.iter().filter_map(|id| id.as_str()).collect();
                println!("{id} is ambiguous: {}. Give more of it.\n", ids.join(", "));
            } else {
                println!(
                    "{id}: no mailbox here or on the team's online machines holds it (a prefix \
                     needs the kind and at least {} hex digits).\n",
                    supercode_harness::mail_transcript::MIN_PREFIX_DIGITS
                );
            }
        }
    }
    Ok(if missing { EXIT_UNKNOWN } else { 0 })
}

/// `show --replies`: for each message this machine holds, the messages in its sender's mailbox
/// that answer it (their `in_reply_to` names it, whole or by the short id a receipt shows).
fn show_replies(ids: &[String], json: bool) -> Result<i32> {
    let root = mail_root();
    let mut rows = Vec::new();
    for id in ids {
        let mut found = supercode_harness::mail_transcript::find_messages(&root, id)?;
        if found.len() != 1 {
            rows.push(serde_json::json!({"id": id, "found": false}));
            continue;
        }
        let (_, asked) = found.remove(0);
        let asked_id = asked.envelope.id.clone();
        let asker = asked.envelope.from.clone();
        let names_it =
            |reply: &str| reply == asked_id || (reply.len() >= 10 && asked_id.starts_with(reply));
        let replies: Vec<serde_json::Value> = Mailbox::open(&root, &asker)
            .and_then(|mailbox| mailbox.list())
            .unwrap_or_default()
            .into_iter()
            .filter(|stored| stored.envelope.in_reply_to.as_deref().is_some_and(names_it))
            .map(|stored| {
                serde_json::json!({
                    "id": stored.envelope.id,
                    "from": stored.envelope.from.to_string(),
                    "from_name": stored.envelope.from_name,
                    "created_at_ms": stored.envelope.created_at_ms,
                    "body": stored.envelope.body,
                })
            })
            .collect();
        rows.push(serde_json::json!({
            "id": id,
            "found": true,
            "message": asked_id,
            "asker": asker.to_string(),
            "replies": replies,
        }));
    }
    let missing = rows.iter().any(|row| row["found"] != true);
    if json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
    } else {
        for row in &rows {
            let id = row["id"].as_str().unwrap_or_default();
            if row["found"] != true {
                println!("{id}: no mailbox on this machine holds it.\n");
                continue;
            }
            let replies = row["replies"].as_array().cloned().unwrap_or_default();
            if replies.is_empty() {
                println!(
                    "{id}: no answer in {}'s mailbox yet.\n",
                    row["asker"].as_str().unwrap_or_default()
                );
            }
            for reply in replies {
                println!(
                    "{id} answered by {} ({}):\n{}\n",
                    reply["from_name"].as_str().unwrap_or_default(),
                    reply["id"].as_str().unwrap_or_default(),
                    reply["body"].as_str().unwrap_or_default()
                );
            }
        }
    }
    Ok(if missing { EXIT_UNKNOWN } else { 0 })
}

/// `show --json` rows for the messages this machine holds: `found`, and the message with the
/// session and machine it is filed for; `ambiguous` (the ids a prefix matches) when it names more
/// than one.
fn show_rows(homes: &HarnessHomes, ids: &[String]) -> Result<Vec<serde_json::Value>> {
    let root = mail_root();
    let mut rows = Vec::new();
    // One pass over the mailboxes for every id, and each session's transcript read once.
    let wanted: Vec<&str> = ids.iter().map(String::as_str).collect();
    let found_by_id = supercode_harness::mail_transcript::find_messages_many(&root, &wanted)?;
    let mut transcripts = std::collections::HashMap::new();
    for (id, mut found) in ids.iter().zip(found_by_id) {
        rows.push(match found.len() {
            0 => serde_json::json!({"id": id, "found": false}),
            1 => {
                let (mailbox, stored) = found.remove(0);
                let address = mailbox.address();
                let transcript = transcripts
                    .entry(address.to_string())
                    .or_insert_with(|| supercode_harness::mail_transcript::read(homes, address));
                let deliveries = supercode_harness::mail_transcript::deliveries(
                    address,
                    std::slice::from_ref(&stored),
                    transcript.as_ref(),
                );
                serde_json::json!({
                    "id": id,
                    "found": true,
                    "machine": local_machine_name(),
                    "message": message_row(address, &stored, &deliveries),
                })
            }
            _ => serde_json::json!({
                "id": id,
                "found": false,
                "ambiguous": found.iter().map(|(_, stored)| stored.envelope.id.clone()).collect::<Vec<_>>(),
            }),
        });
    }
    Ok(rows)
}

async fn wait(homes: &HarnessHomes, from: Option<&str>, timeout: u64) -> Result<i32> {
    let mailbox = match caller_mailbox(homes) {
        Ok(mailbox) => mailbox,
        Err(message) => {
            eprintln!("{message}");
            return Ok(EXIT_REFUSED);
        }
    };
    let sessions = supercode_harness::mail_route::LiveSessions::read(homes);
    let wanted = from.map(|from| match sessions.resolve(from) {
        Ok(session) => session.address.to_string(),
        _ => from.to_string(),
    });
    let limit = Duration::from_secs(timeout).min(MAX_WAIT);
    let started = Instant::now();
    loop {
        let waiting = mailbox.unread()?.into_iter().any(|stored| {
            wanted.as_deref().is_none_or(|wanted| {
                stored.envelope.from.to_string() == wanted
                    || stored.envelope.from_name.starts_with(wanted)
            })
        });
        if waiting {
            // Everything unread is handed over, not only the awaited sender's:
            // a message the agent is not shown now would stay silent.
            let claimed = mailbox.claim_unread()?;
            for stored in &claimed {
                println!("{}\n", stored.envelope.render());
            }
            for stored in &claimed {
                mailbox.acknowledge(stored)?;
            }
            return Ok(0);
        }
        if started.elapsed() >= limit {
            println!(
                "No mail within {} seconds; nothing is lost.",
                limit.as_secs()
            );
            return Ok(EXIT_TIMEOUT);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

fn gate(directory: &std::path::Path) -> Result<i32> {
    let paths = supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf());
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let hook_input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let queued: Option<QueuedSend> = std::fs::read(&paths.queue)
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok());
    if let Some(reason) = gate_decision(&hook_input, queued.as_ref()) {
        // A send that was queued and refused still answers its sender.
        if queued.is_some() && !paths.receipt.exists() {
            std::fs::write(
                &paths.receipt,
                serde_json::json!({"denied": reason}).to_string(),
            )
            .ok();
        }
        println!("{}", gate_denial(&reason));
    }
    Ok(0)
}

/// A relay's PostToolUse and PostToolUseFailure (SendMessage), Stop and StopFailure hook:
/// record Claude's own answer to the queued send, its error, or that the turn ended without one.
fn relay_receipt(directory: &std::path::Path) -> Result<i32> {
    let paths = supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf());
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    if !paths.queue.exists() || paths.receipt.exists() {
        return Ok(0);
    }
    let receipt = match input
        .get("hook_event_name")
        .and_then(serde_json::Value::as_str)
    {
        Some("PostToolUse") => {
            serde_json::json!({"tool_response": input.get("tool_response").cloned().unwrap_or_default()})
        }
        Some("PostToolUseFailure") => serde_json::json!({
            "send_failed": input
                .get("error")
                .map(|error| error.as_str().map_or_else(|| error.to_string(), str::to_string))
                .unwrap_or_default(),
        }),
        // Why the turn ended without sending: its last words, or the API error that ended it
        // (StopFailure: a usage limit, an overload).
        // A turn that began before this send was queued (the last send's, still ending) is not its answer: the next
        // send's queue is already written when the last turn's Stop runs, and its closing words read as this one's.
        Some("Stop" | "StopFailure") if !turn_is_queued_send(&paths) => return Ok(0),
        Some(event @ ("Stop" | "StopFailure")) => {
            let text = |key: &str| input.get(key).and_then(serde_json::Value::as_str);
            let said = match event {
                "StopFailure" => Some(format!(
                    "{} ({})",
                    text("error_details")
                        .or(text("last_assistant_message"))
                        .unwrap_or_default(),
                    text("error").unwrap_or("error")
                )),
                _ => text("last_assistant_message").map(str::to_string),
            };
            serde_json::json!({
                "turn_ended": true,
                "said": said.map(|said| said.chars().take(300).collect::<String>()),
            })
        }
        _ => return Ok(0),
    };
    std::fs::write(&paths.receipt, receipt.to_string())?;
    Ok(0)
}

/// Whether the turn a relay's Stop hook ends is the queued send's own: the prompt that began it (recorded by the
/// relay's UserPromptSubmit hook) is that send's turn. With nothing recorded, it is taken to be.
fn turn_is_queued_send(paths: &supercode_harness::claude_relay::RelayPaths) -> bool {
    let Some(queued) = std::fs::read(&paths.queue)
        .ok()
        .and_then(|bytes| serde_json::from_slice::<QueuedSend>(&bytes).ok())
    else {
        return true;
    };
    std::fs::read_to_string(&paths.turn).map_or(true, |prompt| {
        prompt.contains(&supercode_harness::claude_relay::send_turn(&queued))
    })
}

fn setup(harness: &str) -> Result<i32> {
    if harness != "codex" {
        eprintln!(
            "Nothing to set up for {harness}: claude-code sessions are reached natively, and \
             other harnesses have no delivery door yet."
        );
        return Ok(EXIT_REFUSED);
    }
    let (path, added) = install_codex_hooks()?;
    if added.is_empty() {
        println!("supercode's mail hooks are already in {}.", path.display());
    } else {
        println!(
            "Added supercode's mail hooks ({}) to {}.",
            added.join(", "),
            path.display()
        );
    }
    println!(
        "Codex runs a new hook only after its user trusts it: in Codex, open /hooks and trust the \
         supercode entries. Until then, messages to Codex sessions are stored, not shown."
    );
    Ok(0)
}

/// Add supercode's mail hooks to Codex's user hooks file, once: the delivery
/// door of every Codex session on this machine. Returns the file and the
/// events it added.
pub(crate) fn install_codex_hooks() -> Result<(std::path::PathBuf, Vec<&'static str>)> {
    let path = supercode_harness::mail_route::codex_hooks_path();
    let original = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => "{}".into(),
        Err(error) => return Err(error.into()),
    };
    let mut document: serde_json::Value = serde_json::from_str(&original)
        .map_err(|error| anyhow!("{} is not valid JSON: {error}", path.display()))?;
    let command = format!(
        "{} {}",
        supercode_harness::claude_relay::supercode_program()?.display(),
        supercode_harness::mail_route::CODEX_HOOK_ARGUMENTS
    );
    let hooks = document
        .as_object_mut()
        .ok_or_else(|| anyhow!("{} must hold a JSON object", path.display()))?
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let mut added = Vec::new();
    for event in ["PostToolUse", "Stop", "UserPromptSubmit"] {
        let entries = hooks
            .as_object_mut()
            .ok_or_else(|| anyhow!("`hooks` in {} must be an object", path.display()))?
            .entry(event)
            .or_insert_with(|| serde_json::json!([]));
        let list = entries
            .as_array_mut()
            .ok_or_else(|| anyhow!("`hooks.{event}` in {} must be a list", path.display()))?;
        if list.iter().any(|entry| {
            entry
                .to_string()
                .contains(supercode_harness::mail_route::CODEX_HOOK_ARGUMENTS)
        }) {
            continue;
        }
        // Appended, never inserted: Codex keys each hook's trust by its
        // position, so entries already trusted keep their places.
        let mut entry = serde_json::json!({
            "hooks": [{"type": "command", "command": command, "timeout": 10}]
        });
        if event == "PostToolUse" {
            entry["matcher"] = serde_json::json!(".*");
        }
        list.push(entry);
        added.push(event);
    }
    if !added.is_empty() {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let temporary = path.with_extension("json.supercode-tmp");
        std::fs::write(&temporary, serde_json::to_string_pretty(&document)? + "\n")?;
        std::fs::rename(&temporary, &path)?;
    }
    Ok((path, added))
}

/// A harness hook: when the session has unread mail, point it there. It
/// never shows or claims a message itself — hook context carries the
/// harness's own authority, so peer text travels only through `inbox`, which
/// wraps it in its trust paragraph.
fn hook(harness: &str) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let Some(session_id) = input.get("session_id").and_then(serde_json::Value::as_str) else {
        return Ok(0);
    };
    let Ok(address) = MailAddress::new(local_machine_name(), harness, session_id) else {
        return Ok(0);
    };
    let mailbox = Mailbox::open(&mail_root(), &address)?;
    let pending = mailbox.pending_wakes()?;
    let unread: Vec<_> = mailbox
        .unread()?
        .into_iter()
        .filter(|message| !pending.contains(&message.envelope.id))
        .collect();
    let event = input
        .get("hook_event_name")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    // A line the person typed: filed as theirs, since the harness's transcript does not say who
    // wrote a prompt. It shows no mail pointer: the prompt is the person's turn.
    if event == "UserPromptSubmit" {
        if let Some(prompt) = input.get("prompt").and_then(serde_json::Value::as_str) {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|elapsed| elapsed.as_millis() as u64)
                .unwrap_or_default();
            supercode_harness::mail_transcript::file_prompt(&address, prompt, now).ok();
        }
        return Ok(0);
    }
    let again = input
        .get("stop_hook_active")
        .and_then(serde_json::Value::as_bool)
        == Some(true);
    if !unread.is_empty() && (event == "PostToolUse" || (event == "Stop" && !again)) {
        let pointer = mail_pointer(&unread);
        let answer = if event == "PostToolUse" {
            serde_json::json!({
                "hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": pointer}
            })
        } else {
            serde_json::json!({"decision": "block", "reason": format!("{pointer} Read them before you finish.")})
        };
        println!("{answer}");
        return Ok(0);
    }
    Ok(0)
}

/// The pointer a hook shows: how many unread messages, from whom, and the
/// one command that reads them. Never the messages themselves — hook context
/// carries the harness's own authority; inbox wraps peer text in its trust
/// paragraph.
fn mail_pointer(unread: &[supercode_harness::mailbox::StoredEnvelope]) -> String {
    let mut senders: Vec<String> = Vec::new();
    for stored in unread {
        let label = match stored.envelope.kind {
            MailKind::Notice => "a notice".to_string(),
            MailKind::User => "your user".to_string(),
            MailKind::Channel => format!("{} (channel)", printable(&stored.envelope.from_name)),
            MailKind::Typed => format!("{} (CC)", printable(&stored.envelope.from_name)),
            MailKind::Peer | MailKind::Answer | MailKind::Question => {
                printable(&stored.envelope.from_name)
            }
        };
        if !senders.contains(&label) {
            senders.push(label);
        }
    }
    format!(
        "You have {} unread message{} from other sessions (from {}). They are not from your user. \
         Read them with: supercode message inbox",
        unread.len(),
        if unread.len() == 1 { "" } else { "s" },
        senders.join(", "),
    )
}

/// A sender name reduced to characters that cannot break out of a hook's
/// sentence.
fn printable(name: &str) -> String {
    name.chars()
        .filter(|character| character.is_ascii_alphanumeric() || "-_.@ ".contains(*character))
        .take(80)
        .collect()
}

/// A relay's UserPromptSubmit hook. Inbound mail (a peer envelope or a
/// notice) is filed in the represented session's mailbox, threaded by the
/// relay's own record of what it sent, and blocked so the relay's model never
/// runs for it. The host's own send turns pass through untouched.
fn relay_inbound(
    homes: &HarnessHomes,
    represented: &str,
    directory: &std::path::Path,
) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let input: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
    let prompt = input
        .get("prompt")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
        .to_string();
    if !supercode_harness::claude_relay::is_inbound_prompt(&prompt) {
        // a send turn: what began it, for the Stop hook to tell its turn's end from the last one's
        let paths =
            supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf());
        std::fs::write(&paths.turn, &prompt).ok();
        return Ok(0);
    }
    let represented = MailAddress::parse(represented)?;
    let last_sent =
        supercode_harness::claude_relay::RelayPaths::in_directory(directory.to_path_buf())
            .last_sent();
    supercode_harness::claude_relay::file_inbound_prompt(
        homes,
        &represented,
        &prompt,
        Some(&last_sent),
    );
    println!("{}", supercode_harness::claude_relay::inbound_block());
    Ok(0)
}

/// A request another machine's `supercode message` sent through this
/// machine's Teams mail door: deliver it here through the same doors a local
/// send uses, and answer `{code, text}` on stdout.
/// One filed message, delivered through its session's door. It stays in the
/// mailbox, unread, when no door reaches the session or delivery fails.
async fn push(homes: &HarnessHomes, address: &str, id: &str) -> Result<i32> {
    let to = MailAddress::parse(address).map_err(|error| anyhow!("{error}"))?;
    let mailbox = Mailbox::open(&mail_root(), &to)?;
    let Some(stored) = mailbox.find(id)? else {
        return Ok(0);
    };
    if stored.state != supercode_harness::mailbox::MailState::Unread {
        return Ok(0);
    }
    // Only doors that hand a message to the session take it from here; for
    // the rest (an operator's inbox, a Codex hook, no door) the mailbox is
    // where it is read, and it stays unread there.
    let door = match supercode_harness::mail_route::door_for(homes, &to) {
        Ok(door @ (Door::Native(_) | Door::Runtime(_))) => door,
        _ => return Ok(0),
    };
    match supercode_harness::mail_route::deliver(&stored.envelope, &to, &door, true, false).await {
        Ok(Ok(_)) => {
            mailbox.mark_read(&stored)?;
            Ok(0)
        }
        Ok(Err(refused)) => {
            eprintln!("supercode: {id} stays in {to}'s mailbox: {refused:?}");
            Ok(supercode_harness::mail_send::EXIT_REFUSED)
        }
        Err(error) => {
            eprintln!("supercode: {id} stays in {to}'s mailbox: {error}");
            Ok(supercode_harness::mail_send::EXIT_FAILED)
        }
    }
}

/// `remote-deliver` `turn`: user mail into one session here, through the door a session's own
/// user speaks through (its runtime, its pane's empty composer, or its mailbox until then). The
/// answer names the door, or says the session is not here.
async fn remote_turn(homes: &HarnessHomes, request: &serde_json::Value) -> Result<i32> {
    let text = request["text"].as_str().unwrap_or_default();
    let name: String = request["from_name"]
        .as_str()
        .unwrap_or("a Room member")
        .trim()
        .chars()
        .map(|character| {
            if character.is_whitespace() || character == '@' {
                '-'
            } else {
                character
            }
        })
        .collect();
    let answer = match (
        MailAddress::new(
            local_machine_name(),
            request["harness"].as_str().unwrap_or_default(),
            request["session"].as_str().unwrap_or_default(),
        ),
        MailAddress::new(local_machine_name(), "operator", &name),
    ) {
        (Ok(to), Ok(sender)) => {
            let envelope = Envelope::new(
                sender,
                request["from_name"].as_str().unwrap_or(&name).to_string(),
                MailKind::User,
                supercode_harness::mailbox::ReplyVia::None,
                text.to_string(),
            )?;
            match supercode_harness::mail_route::deliver_user_turn(homes, &envelope, &to).await {
                Ok(turn) => serde_json::json!({
                    "code": 0,
                    "turn_id": envelope.id,
                    "door": match turn {
                        supercode_harness::mail_route::UserTurn::Steered
                        | supercode_harness::mail_route::UserTurn::Started => "runtime",
                        supercode_harness::mail_route::UserTurn::Typed => "pane",
                        supercode_harness::mail_route::UserTurn::Waiting => "waiting",
                    },
                }),
                Err(message) => serde_json::json!({"code": EXIT_UNKNOWN, "text": message}),
            }
        }
        (Err(error), _) | (_, Err(error)) => {
            serde_json::json!({"code": EXIT_REFUSED, "text": error.to_string()})
        }
    };
    println!("{answer}");
    Ok(0)
}

async fn remote_deliver(homes: &HarnessHomes) -> Result<i32> {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input)?;
    let request: serde_json::Value = serde_json::from_str(&input)?;
    // The sessions here a caller with this machine's mail door can message.
    if request["op"].as_str() == Some("list") {
        println!(
            "{}",
            serde_json::json!({"code": 0, "sessions": session_rows(homes)})
        );
        return Ok(0);
    }
    // Messages by id, and one session's in and out: what `show` and `inbox --session` read here.
    if request["op"].as_str() == Some("show") {
        let ids: Vec<String> = request["ids"]
            .as_array()
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| id.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();
        println!(
            "{}",
            serde_json::json!({"code": 0, "rows": show_rows(homes, &ids)?})
        );
        return Ok(0);
    }
    if request["op"].as_str() == Some("inbox") {
        let answer = match MailAddress::parse(request["session"].as_str().unwrap_or_default()) {
            Ok(address) if address.machine == local_machine_name() => {
                let recent = request["recent"].as_u64().map(|recent| recent as usize);
                serde_json::json!({"code": 0, "rows": inbox_rows(homes, &address, recent)?})
            }
            Ok(address) => {
                serde_json::json!({"code": EXIT_UNKNOWN, "text": format!("{address} is not on this machine.")})
            }
            Err(error) => serde_json::json!({"code": EXIT_REFUSED, "text": error.to_string()}),
        };
        println!("{answer}");
        return Ok(0);
    }
    let outcome = match request["op"].as_str() {
        Some("file") => {
            let to = MailAddress::parse(request["to"].as_str().unwrap_or_default())?;
            let mut envelope: Envelope = serde_json::from_value(request["envelope"].clone())?;
            // The receiving side resolves who sent it; the filer's own identity claim is never trusted.
            envelope.sender_identity = supercode_harness::mailbox::resolve_filed_sender(
                &envelope,
                request["via_principal"].as_str(),
            );
            if to.machine != local_machine_name() {
                supercode_harness::mail_send::Outcome::new(
                    EXIT_UNKNOWN,
                    format!("{to} is not on this machine."),
                )
            } else {
                Mailbox::open(&mail_root(), &to)?.deliver(&envelope)?;
                supercode_harness::mail_send::Outcome::new(0, format!("filed for {to}"))
            }
        }
        Some("send") => {
            let caller = Caller {
                address: MailAddress::parse(request["from"].as_str().unwrap_or_default())?,
                name: request["from_name"]
                    .as_str()
                    .unwrap_or_default()
                    .to_string(),
            };
            supercode_harness::mail_send::send(
                homes,
                &caller,
                request["to"].as_str().unwrap_or_default(),
                request["body"].as_str().unwrap_or_default(),
                supercode_harness::mail_send::SendOptions {
                    subject: request["subject"].as_str().map(str::to_string),
                    in_reply_to: request["in_reply_to"].as_str().map(str::to_string),
                    notify_when_idle: request["notify_when_idle"].as_bool().unwrap_or(false),
                    queue: request["queue"].as_bool().unwrap_or(false),
                    idempotency_key: request["id"].as_str().map(str::to_string),
                    notice: request["notice"].as_bool().unwrap_or(false),
                },
            )
            .await?
        }
        Some("turn") => {
            // A person's line as a session's own user turn (a Room member typing into a session bound
            // to their Room): the daemon has checked the grant and names who typed it.
            return remote_turn(homes, &request).await;
        }
        _ => supercode_harness::mail_send::Outcome::new(
            EXIT_REFUSED,
            "Not sent: the mail door takes send, file or turn.",
        ),
    };
    println!(
        "{}",
        serde_json::json!({"code": outcome.code, "text": outcome.text, "receipt": outcome.receipt})
    );
    Ok(0)
}