argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
//! Direct Captain: Captain you choose is a turn of the main session in your checkout,
//! as its CLI works when you run it. Your words go through as you typed them, the CLI's own
//! tools and agents do the work, and its last message is the end. No run, task, report, checks,
//! merge, run review, or learned workflow.
//!
//! Around the turn Argonauts Code keeps the sandbox, the limit per message, and fallback, and adds
//! what the CLI would have you answer in its own window: `ask` builds the questions, `listen` takes
//! the questions in, and `rewind` keeps a snapshot before and after each turn so `/rewind` can
//! put files back.

mod ask;
mod listen;
pub(super) mod outside;
mod rewind;
mod rm;

use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};

use argonauts_conductor::sandbox::profile::PROTECTED_PATHS;
use argonauts_core::app::{AppEvent, ChoiceKind};
use argonauts_core::asking::{Ask, AskReply};
use argonauts_core::event::AgentEvent;
use argonauts_core::events::approval::AnswerAction;
use argonauts_core::events::run::{CaptainOrCrewDecision, RunMode};
use argonauts_core::events::session::{InputPart, InputPartKind};
use argonauts_core::names::{ChoiceId, ModelRef, TurnId};
use argonauts_core::outside::changed_outside;
use argonauts_core::settings::approvals::ApprovalMode;
use argonauts_core::settings::approvals::SandboxChoice;
use argonauts_core::settings::fallback::FallbackEntry;
use argonauts_core::settings::protocol::{CaptainKind, ForcedMode};
use argonauts_core::settings::{SettingScope, Settings};
use argonauts_core::{Asks, NoteLevel};
use serde_json::Value;

pub(crate) use self::listen::Asked;
use self::listen::Listener;
use self::rewind::Snapshot;
use super::{
    ConversationState, Turn, handover, lifecycle, run_request, send_queued, standing, tools,
};
use crate::choices::{self, option};
use crate::controller::turn::{self, DirectWords, TurnStep, part};
use crate::controller::{Ctx, Effect};
use argonauts_conductor::fallback::shortlist::{
    Sources, auto_check, shortlist as fallback_shortlist,
};
use argonauts_core::TaskId;
use argonauts_core::events::task::{TaskKind, TaskLimit, TaskSpec};
use argonauts_core::limits::{Candidate, CandidateQuery, TrackRecord, TrackRecords};
use argonauts_core::names::RoleName;

const ANTIGRAVITY: &str = "antigravity-cli";

/// What agy's resumed turn is told when you let it run what it was refused.
const RUN_REFUSED: &str = "You may run the commands you were refused.";

/// Direct Captain's part of the conversation.
#[derive(Debug, Default)]
pub(crate) struct DirectState {
    /// The approval mode on screen, which says whether a direct turn asks.
    approval: ApprovalMode,
    /// Open questions from the turn's CLI, by their id.
    asks: HashMap<ChoiceId, PendingAsk>,
    /// "Yes, and allow edits for the rest of this conversation".
    edits_allowed: bool,
    /// Each direct turn that changed files, oldest first.
    turns: Vec<TurnRecord>,
    /// Stopped turns whose session hasn't ended yet, so their files may still change.
    stopping: HashMap<TurnId, Running>,
    /// agy's refused commands, offered after its turn.
    refused: HashMap<ChoiceId, RefusedOffer>,
    /// The open `/rewind` question. Its answers name turns by their place in `turns`.
    rewinding: Option<ChoiceId>,
    /// Said with your next message: the files `/rewind` put back.
    rewound: Option<String>,
    /// Plans made with plan first on, waiting for "Go ahead with this plan?".
    plans: HashMap<ChoiceId, Planned>,
    /// A turn whose agent ran out, waiting for you to pick who carries it on, or who answers
    /// when it changes nothing.
    fallback: Option<(ChoiceId, PendingFallback)>,
    /// Ignored files turns wrote, which snapshots keep from then on so `/rewind` can put them
    /// back.
    watched: BTreeSet<String>,
    /// The setup line the conversation's session last heard, so it hears a new one only when
    /// something changed.
    pub(super) told_setup: Option<String>,
}

impl std::fmt::Debug for PendingFallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PendingFallback")
            .field("turn", &self.turn.id)
            .field("why", &self.why)
            .field("candidates", &self.candidates)
            .finish_non_exhaustive()
    }
}

/// A turn that ran out, held while the fallback question is open.
struct PendingFallback {
    turn: Turn,
    tried: Vec<ModelRef>,
    why: String,
    /// In the question's order.
    candidates: Vec<ModelRef>,
}

/// A plan-first turn's request, for the turn that goes ahead with it.
#[derive(Debug)]
struct Planned {
    request: String,
    words: DirectWords,
    /// The CLI that planned, as the screen names it.
    cli: String,
}

impl DirectState {
    /// The next conversation keeps the mode and what `/rewind` can put back, and asks about
    /// edits again.
    pub(super) fn carry(&mut self) -> Self {
        Self {
            approval: self.approval,
            turns: std::mem::take(&mut self.turns),
            watched: std::mem::take(&mut self.watched),
            ..Self::default()
        }
    }

    /// A conversation that works in another folder can't put this one's files back, and the
    /// ignored files kept for it are that folder's.
    pub(super) fn forget_turns(&mut self) {
        self.turns.clear();
        self.watched.clear();
    }
}

/// A direct turn in flight.
#[derive(Debug)]
pub(super) struct Running {
    /// Your message.
    text: String,
    /// Answers the turn's questions, and stops when the turn ends.
    listener: Option<Listener>,
    asks: Asks,
    before: Option<Snapshot>,
    /// The commands the turn's tool calls ran, by call id.
    commands: HashMap<String, String>,
    /// Commands agy refused because they needed asking.
    refused: Vec<String>,
    /// What the agent said so far, for a fallback.
    said: String,
    /// Ignored files earlier turns wrote, which every snapshot keeps.
    watched: BTreeSet<String>,
    /// Files the turn's agent reported changing, by path from your folder.
    written: BTreeSet<String>,
    /// Protected files that weren't there when the turn started. The sandbox holds a protected
    /// folder that isn't there yet, but a file only on macOS, so the turn's end checks these.
    unmade: Vec<String>,
    /// The folder it works in, whose files `/rewind` puts back.
    root: PathBuf,
    /// The session has Argonauts Code's tools, so a setup you answered may write Argonauts Code's
    /// files.
    has_tools: bool,
    /// Files a setup you answered wrote during the turn, by path from your folder. The turn's
    /// end leaves them as the setup wrote them.
    setup_wrote: BTreeSet<String>,
    /// The files git didn't track when the turn started, so its end names only the ones it
    /// made.
    untracked: BTreeSet<String>,
    /// Your home, which the line about such a write names as `~`.
    home: Option<PathBuf>,
}

#[derive(Debug)]
struct PendingAsk {
    turn: TurnId,
    tool: String,
    input: Value,
    question: ask::Question,
    reply: tokio::sync::oneshot::Sender<AskReply>,
}

#[derive(Debug)]
struct RefusedOffer {
    worker: ModelRef,
    /// The turn's request, which the turn that runs the commands carries on.
    request: String,
}

#[derive(Debug)]
struct TurnRecord {
    text: String,
    before: Snapshot,
    after: Snapshot,
    changed: Vec<String>,
}

/// Captain you choose runs direct: `captain.kind` says so, and nothing that needs a worktree is on.
pub(crate) fn captain_is_direct(settings: &Settings) -> bool {
    settings.captain.direct()
}

/// What a direct turn after the estimate says, so the agent starts from the plan it wrote.
pub(super) const GO_AHEAD: &str = "Go ahead.";

/// The choice settled on direct Captain: Captain your words chose where `captain.kind` is direct,
/// or Captain the rules picked where `captain_or_crew.captain_kind` says so, with nothing on that
/// needs a worktree.
pub(super) fn picks_direct(captain_or_crew: &CaptainOrCrewDecision) -> bool {
    captain_or_crew.mode == RunMode::Captain && captain_or_crew.captain == Some(CaptainKind::Direct)
}

/// The Captain workflow sends every message to the main session as a direct turn.
pub(crate) fn workflow_is_direct(settings: &Settings) -> bool {
    settings.captain_or_crew.force == Some(ForcedMode::Captain) && captain_is_direct(settings)
}

pub(crate) fn set_approval(conversation: &mut ConversationState, mode: ApprovalMode) {
    conversation.direct.approval = mode;
}

/// The approval mode on screen.
pub(super) fn approval(conversation: &ConversationState) -> ApprovalMode {
    conversation.direct.approval
}

/// Starts a direct turn with your message. `asks` overrides what the mode says, as agy's
/// resumed turn does. A CLI that can't ask before each edit gets a checked run instead, when
/// `captain.asks` wants every change asked about.
pub(super) fn begin(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    text: String,
    asks: Option<Asks>,
) -> anyhow::Result<Vec<Effect>> {
    begin_with(ctx, conversation, text, asks, DirectWords::default())
}

/// [`begin`], with what your checked words change about the turn.
pub(super) fn begin_with(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    text: String,
    asks: Option<Asks>,
    words: DirectWords,
) -> anyhow::Result<Vec<Effect>> {
    let asks = asks.unwrap_or_else(|| mode_asks(ctx, conversation, &words));
    if let Some(instead) = instead(ctx, conversation, asks, &text) {
        return Ok(instead);
    }
    start(ctx, conversation, text, asks, |asking| TurnStep::Direct {
        asking,
        go_ahead: None,
        words,
    })?;
    Ok(Vec::new())
}

/// The session that just read `request` goes ahead with it in your checkout. The turn is your
/// request, for `/rewind`, the record, and a run it starts, and the session reads only `words`
/// such as "Go ahead.", as it has your message already.
pub(super) fn go_ahead(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    request: String,
    said: &str,
    asks: Option<Asks>,
    words: DirectWords,
) -> anyhow::Result<Vec<Effect>> {
    let asks = asks.unwrap_or_else(|| mode_asks(ctx, conversation, &words));
    if let Some(instead) = instead(ctx, conversation, asks, &request) {
        return Ok(instead);
    }
    start(ctx, conversation, request, asks, |asking| {
        TurnStep::Direct {
            asking,
            go_ahead: Some(said.to_owned()),
            words,
        }
    })?;
    Ok(Vec::new())
}

/// Who may carry a direct turn on when its agent runs out: `[fallback.main]`'s list, or with
/// no list anywhere the other installed models, as a run's shortlist judges them for the main
/// role, so a disabled, testing, or over-cap agent is left out and a paid API needs your OK.
/// With `same_cli` only the stopped CLI's own models may.
pub(super) fn shortlist(ctx: &Ctx, stopped: &ModelRef, tried: &[ModelRef]) -> Vec<Candidate> {
    let settings = ctx.settings();
    let rules = settings
        .fallback
        .applied_to(RoleName::Main, &stopped.agent_id());
    let listed = if rules.candidates.is_empty() {
        let defaults = turn::default_fallbacks(ctx);
        defaults.into_iter().map(FallbackEntry::Model).collect()
    } else {
        rules.candidates.clone()
    };
    let query = CandidateQuery {
        task: your_checkout(),
        role: RoleName::Main,
        stopped: stopped.clone(),
        exclude_providers: Vec::new(),
        fallback: listed,
        all_valid: false,
    };
    let sources = Sources {
        settings,
        registry: ctx.services.registry.as_ref(),
        plan_usage: ctx.services.plan_usage.as_ref(),
        health: ctx.services.health.as_ref(),
        records: &NoRecords,
        slots: None,
        workers: Some(ctx.services.workers.as_ref()),
    };
    fallback_shortlist(&query, &sources)
        .candidates
        .into_iter()
        .filter(|candidate| {
            !tried.contains(&candidate.worker)
                && (!rules.same_cli || candidate.worker.agent == stopped.agent)
                && ctx.services.workers.get(&candidate.worker).is_ok()
        })
        .collect()
}

/// A direct turn has no task of its own, so the shortlist judges it as one Captain task that owns
/// your checkout.
fn your_checkout() -> TaskSpec {
    TaskSpec {
        id: TaskId::new("direct-001").expect("a valid task id"),
        title: String::new(),
        task: String::new(),
        kind: TaskKind::Captain,
        owned_paths: Vec::new(),
        read_only_paths: Vec::new(),
        forbidden_paths: Vec::new(),
        hidden_paths: Vec::new(),
        depends_on: Vec::new(),
        criteria: Vec::new(),
        worker: None,
        reviewers: Vec::new(),
        limit: TaskLimit::default(),
        predictions: None,
        item: None,
    }
}

/// Track records order a run's candidates; a direct turn takes its list's order.
struct NoRecords;

impl TrackRecords for NoRecords {
    fn get(&self, _: &ModelRef, _: &str) -> Option<TrackRecord> {
        None
    }
}

/// The fallback question: who carries the turn on, each with what it costs, or stop here. A turn
/// that changes nothing has nothing to carry on, so it asks who answers and that agent reads
/// the turn from its start.
pub(super) fn ask_fallback(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: Turn,
    tried: Vec<ModelRef>,
    why: String,
    candidates: &[Candidate],
) {
    let from = ctx.names.worker(&turn.worker);
    let mut options: Vec<_> = candidates
        .iter()
        .take(9)
        .zip('1'..='9')
        .map(|(candidate, key)| {
            let mut offered = option(
                key,
                &ctx.names.worker(&candidate.worker),
                AnswerAction::Choose {
                    value: candidate.worker.to_string(),
                },
                false,
            );
            offered.detail = Some(if candidate.needs_confirm {
                "an API key, billed to your account".to_owned()
            } else {
                candidate.plan_usage_text.clone()
            })
            .filter(|detail| !detail.trim().is_empty());
            offered
        })
        .collect();
    options.push(option(
        's',
        "Stop here",
        AnswerAction::Choose {
            value: "stop".to_owned(),
        },
        false,
    ));
    let (asked, detail) = if turn.step.writes() {
        let (told, _) = fallback(ctx, &turn);
        ("Who carries it on?", vec![format!("They're told {told}.")])
    } else {
        ("Who answers instead?", Vec::new())
    };
    let id = ctx.next_choice_id();
    let mut choice = choices::app_choice(
        id.clone(),
        ChoiceKind::Fallback,
        format!("{from} {why}. {asked}"),
        detail,
        options,
    );
    choice.bell = true;
    let pending = PendingFallback {
        turn,
        tried,
        why,
        candidates: candidates
            .iter()
            .map(|candidate| candidate.worker.clone())
            .collect(),
    };
    if let Some((old, earlier)) = conversation.direct.fallback.replace((id, pending)) {
        ctx.send(AppEvent::ChoiceClosed {
            id: old,
            outcome: "Stopped".to_owned(),
        });
        // A turn that only answers already said it failed, and changed nothing to report.
        if earlier.turn.step.writes() {
            let error = format!("{} {}", earlier.turn.worker, earlier.why);
            lifecycle::end_direct(ctx, conversation, earlier.turn, error);
        }
    }
    ctx.send(AppEvent::Choice { choice });
}

fn answer_fallback(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    pending: PendingFallback,
    value: &str,
) -> anyhow::Result<Vec<Effect>> {
    let picked = pending
        .candidates
        .iter()
        .find(|worker| worker.to_string() == value)
        .cloned();
    let answers = !pending.turn.step.writes();
    let Some(to) = picked.filter(|_| conversation.turn.is_none()) else {
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: "Stopped".to_owned(),
        });
        if answers {
            return Ok(send_queued(conversation));
        }
        let error = format!("{} {}", pending.turn.worker, pending.why);
        return Ok(lifecycle::end_direct(
            ctx,
            conversation,
            pending.turn,
            error,
        ));
    };
    let does = if answers { "answers" } else { "carries it on" };
    ctx.send(AppEvent::ChoiceClosed {
        id,
        outcome: format!("{} {does}", ctx.names.worker(&to)),
    });
    if answers {
        return lifecycle::answer_on(ctx, conversation, pending.turn, pending.tried, &to);
    }
    lifecycle::fallback(
        ctx,
        conversation,
        pending.turn,
        pending.tried,
        pending.why,
        to,
    )
}

/// Plan first in direct Captain: the turn reads and plans, and changes nothing until you say go
/// ahead with its plan.
pub(super) fn plan(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    text: String,
    words: DirectWords,
) -> anyhow::Result<Vec<Effect>> {
    lifecycle::begin(ctx, conversation, text, |_| TurnStep::Plan { words })?;
    Ok(Vec::new())
}

/// What the session reads when you go ahead with its plan.
pub(super) const GO_AHEAD_WITH_PLAN: &str = "Go ahead with this plan.";

/// After a plan-first turn's plan: "Go ahead with this plan?". See [`offer_go_ahead`] for what
/// comes back.
pub(super) fn offer_plan(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: &Turn,
) -> Option<DirectWords> {
    match &turn.step {
        TurnStep::Plan { words } => offer_go_ahead(ctx, conversation, turn, words.clone()),
        _ => None,
    }
}

/// "Go ahead with this plan?" for `turn`'s request, whose reply was the plan. On autopilot
/// nothing waits for you: one line says the plan goes ahead, and `words` come back for the
/// caller to start the turn that carries it out, once this one has ended.
pub(super) fn offer_go_ahead(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: &Turn,
    words: DirectWords,
) -> Option<DirectWords> {
    let cli = ctx.names.cli(&turn.worker.agent);
    // An agent's session carried on works in the run's worktree, not your checkout.
    let folder = if conversation.folder(ctx) == ctx.env.repo_root.as_path() {
        "your checkout"
    } else {
        "the run's worktree"
    };
    if conversation.direct.approval == ApprovalMode::Autopilot {
        ctx.notice(
            NoteLevel::Info,
            format!("Decided on autopilot · {cli} goes ahead with its plan in {folder}."),
        );
        return Some(words);
    }
    let id = ctx.next_choice_id();
    let mut choice = choices::app_choice(
        id.clone(),
        ChoiceKind::GoAhead,
        "Go ahead with this plan?".to_owned(),
        vec![format!("{cli} carries it out in {folder}.")],
        choices::options(ChoiceKind::GoAhead),
    );
    choice.bell = true;
    conversation.direct.plans.insert(
        id,
        Planned {
            request: turn.text.clone(),
            words,
            cli,
        },
    );
    ctx.send(AppEvent::Choice { choice });
    None
}

fn answer_plan(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    planned: Planned,
    value: &str,
) -> anyhow::Result<Vec<Effect>> {
    if value != "yes" {
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: "No · nothing changed".to_owned(),
        });
        return Ok(Vec::new());
    }
    // One turn at a time, and this one needs the session the plan was made in.
    if conversation.turn.is_some() {
        ctx.notice(
            NoteLevel::Info,
            "A turn is running. Answer the plan's question once it ends.",
        );
        conversation.direct.plans.insert(id, planned);
        return Ok(Vec::new());
    }
    ctx.send(AppEvent::ChoiceClosed {
        id,
        outcome: "Yes, go ahead".to_owned(),
    });
    go_ahead(
        ctx,
        conversation,
        planned.request,
        GO_AHEAD_WITH_PLAN,
        None,
        planned.words,
    )
}

/// Codex, agy, and OpenCode can't be asked before each edit in a headless run.
fn asks_each(worker: &str) -> bool {
    !matches!(worker, "codex" | ANTIGRAVITY | "opencode")
}

/// What happens instead of a direct turn whose CLI can't ask before each edit when every change
/// should be asked about: in your checkout, a checked run. An agent's session carried on waits
/// until you allow it to go on, since a checked worktree would start a new session.
fn instead(
    ctx: &mut Ctx,
    conversation: &ConversationState,
    asks: Asks,
    text: &str,
) -> Option<Vec<Effect>> {
    match &conversation.place {
        Some(place) if asks == Asks::EveryChange && !asks_each(&place.worker.agent) => {
            let cli = ctx.names.cli(&place.worker.agent);
            ctx.notice(
                NoteLevel::Info,
                format!(
                    "{cli} can't ask before each edit in a headless run, and a checked worktree \
                     would leave this session behind. Auto mode, or captain.asks = \"like_cli\", \
                     lets it carry on."
                ),
            );
            Some(Vec::new())
        }
        Some(_) => None,
        None => checked_instead(ctx, asks, text).map(|run| vec![run]),
    }
}

/// One of the CLI's own commands, where the conversation works: your checkout, or the folder
/// of the agent's session it carries on.
pub(super) fn begin_agent(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    shown: String,
    prompt: String,
) -> anyhow::Result<Vec<Effect>> {
    let asks = mode_asks(ctx, conversation, &DirectWords::default());
    start(ctx, conversation, shown, asks, |asking| TurnStep::Cli {
        prompt,
        direct: Some(asking),
    })?;
    Ok(Vec::new())
}

/// Nothing in auto mode or autopilot, unless your words asked to be asked first, and what
/// `captain.asks` says otherwise. Words only ever add asking: none make a turn ask less than its
/// mode says.
fn mode_asks(ctx: &Ctx, conversation: &ConversationState, words: &DirectWords) -> Asks {
    match conversation.direct.approval {
        ApprovalMode::Auto | ApprovalMode::Autopilot if !words.supervised => Asks::Never,
        ApprovalMode::Auto
        | ApprovalMode::Autopilot
        | ApprovalMode::Supervised
        | ApprovalMode::AutoPreview => ctx.settings().captain.asks,
    }
}

/// Codex, agy, and OpenCode can't be asked before each edit in stage 1, so `every_change` runs
/// them in a checked worktree, and a line says why.
fn checked_instead(ctx: &Ctx, asks: Asks, text: &str) -> Option<Effect> {
    let main = &ctx.settings().crew.main;
    if asks != Asks::EveryChange || asks_each(&main.agent) {
        return None;
    }
    let cli = ctx.names.cli(&main.agent);
    ctx.notice(
        NoteLevel::Info,
        format!(
            "{cli} can't ask before each edit in a headless run, so this runs in a checked worktree."
        ),
    );
    let request = run_request(ctx, text.to_owned(), RunMode::Captain, None, None);
    Some(handover::start(request))
}

fn start(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    text: String,
    asks: Asks,
    step: impl FnOnce(Option<argonauts_core::session_runner::Asking>) -> TurnStep,
) -> anyhow::Result<()> {
    // Its folder is there before the snapshot `/rewind` takes of it.
    if !lifecycle::place_ready(ctx, conversation)? {
        return Ok(());
    }
    let settings = ctx.settings();
    // What the session may call to make something happen outside itself, and the standing
    // lines that tell it so.
    let offered = tools::offered(ctx, conversation);
    let lines = standing::lines(&offered);
    let rewind = settings.captain.rewind.then(|| max_bytes(settings));
    let next = TurnId::numbered(conversation.turns + 1);
    let roles = crate::controller::ask_role::roles(settings);
    let listener = if asks != Asks::Never || !offered.is_empty() || !roles.is_empty() {
        Some(listen::listen(ctx.internal.clone(), next)?)
    } else {
        None
    };
    let asking = listener.as_ref().map(|listener| {
        let mut asking = listener.asking(asks, offered, lines);
        asking.roles = roles;
        asking
    });
    let root = conversation.folder(ctx).to_path_buf();
    let watched = conversation.direct.watched.clone();
    // A folder with no git keeps nothing to go back to until `/git` turns its history on.
    let rewind = rewind.filter(|_| ctx.env.git().has_history() || root != ctx.env.repo_root);
    let before = rewind.and_then(|max| match rewind::take(&root, max, &watched) {
        Ok(snapshot) => Some(snapshot),
        Err(err) => {
            ctx.notice(
                NoteLevel::Warn,
                format!("/rewind can't put back what this turn changes: {err:#}"),
            );
            None
        }
    });
    let unmade = unmade_files(ctx, &root);
    let untracked = untracked_files(&root);
    lifecycle::begin(ctx, conversation, text.clone(), |_| step(asking))?;
    if let Some(turn) = conversation.turn.as_mut() {
        turn.direct = Some(Running {
            text,
            listener,
            asks,
            before,
            commands: HashMap::new(),
            refused: Vec::new(),
            said: String::new(),
            watched,
            written: BTreeSet::new(),
            unmade,
            root,
            has_tools: turn.step.has_tools(),
            setup_wrote: BTreeSet::new(),
            untracked,
            home: ctx.env.user_home.clone(),
        });
    }
    Ok(())
}

/// The files in `root` that git neither tracks nor ignores, by path from it. None in a folder
/// with no git, where nothing is tracked.
fn untracked_files(root: &Path) -> BTreeSet<String> {
    if !crate::git::has_git(root) {
        return BTreeSet::new();
    }
    let listed = crate::git::git(root, &["ls-files", "--others", "--exclude-standard", "-z"]);
    listed
        .map(|listed| {
            listed
                .split('\0')
                .filter(|path| !path.is_empty())
                .map(str::to_owned)
                .collect()
        })
        .unwrap_or_default()
}

/// The most files the line names before it counts the rest.
const MOST_UNTRACKED: usize = 3;

/// The files the turn made that git doesn't track, so a scratch file the agent left doesn't
/// hide in your checkout: `Left untracked: test_slug_fix.py`. A setup you answered wrote its
/// files on purpose, so they aren't named.
fn left_untracked(running: &Running) -> Option<String> {
    let made: Vec<String> = untracked_files(&running.root)
        .into_iter()
        .filter(|path| !running.untracked.contains(path) && !running.setup_wrote.contains(path))
        .collect();
    let named = match made.as_slice() {
        [] => return None,
        [one] => one.clone(),
        [first, second] => format!("{first} and {second}"),
        [first, second, third] => format!("{first}, {second} and {third}"),
        many => format!(
            "{} and {} more",
            many[..MOST_UNTRACKED].join(", "),
            many.len() - MOST_UNTRACKED
        ),
    };
    Some(format!("Left untracked: {named}"))
}

/// The protected files that aren't in the turn's folder now, when our sandbox wraps the turn.
/// With it off the CLI works as when you start it, and nothing is protected.
fn unmade_files(ctx: &Ctx, root: &Path) -> Vec<String> {
    let sandboxed = !matches!(
        ctx.settings().sandbox.mode,
        SandboxChoice::Tool | SandboxChoice::None
    );
    PROTECTED_PATHS
        .iter()
        .filter(|path| sandboxed && !path.ends_with('/'))
        .filter(|path| std::fs::symlink_metadata(root.join(path)).is_err())
        .map(|path| (*path).to_owned())
        .collect()
}

/// A protected file the turn made anyway, where the sandbox couldn't hold it, is moved into the
/// turn's own folder, where nothing loads it, and a line says where.
fn set_aside_planted(
    ctx: &Ctx,
    conversation: &ConversationState,
    running: &Running,
    turn: &TurnId,
) {
    let root = &running.root;
    let made: Vec<&String> = running
        .unmade
        .iter()
        .filter(|path| std::fs::symlink_metadata(root.join(path)).is_ok())
        .collect();
    if made.is_empty() {
        return;
    }
    let aside = ctx
        .env
        .conversation_dir()
        .join(conversation.id.as_str())
        .join(turn.as_str())
        .join("set-aside");
    for path in made {
        let moved = std::fs::create_dir_all(&aside)
            .and_then(|()| std::fs::rename(root.join(path), aside.join(path)));
        match moved {
            Ok(()) => ctx.notice(
                NoteLevel::Warn,
                format!(
                    "This turn made {path}, which configures agents, so it's set aside in {} where \
                     nothing loads it. Move it back yourself if you want it.",
                    aside.display()
                ),
            ),
            Err(err) => ctx.notice(
                NoteLevel::Warn,
                format!("This turn made {path}, which configures agents, and it couldn't be set aside: {err}. Look it over before any agent runs here."),
            ),
        }
    }
}

/// Notes a direct turn's prompt carries after your message: what `/rewind` put back, and for a
/// session with Argonauts Code's tools, the setup in use when it hasn't heard it. Argonauts Code
/// adds no instructions of its own beyond those.
pub(super) fn notes(
    ctx: &Ctx,
    conversation: &mut ConversationState,
    step: &TurnStep,
    fresh: bool,
) -> Vec<InputPart> {
    let mut notes: Vec<InputPart> = conversation
        .direct
        .rewound
        .take()
        .map(|text| part(InputPartKind::Notes, "rewind", text))
        .into_iter()
        .collect();
    if step.has_tools() {
        notes.extend(standing::setup_note(ctx, conversation, fresh));
    }
    notes
}

/// Follows the turn's events for what comes after it: agy's refused commands, and what the
/// agent said, for a fallback. Gives the line a write outside your folder leaves, once it's
/// done.
pub(super) fn on_agent(running: &mut Running, event: &AgentEvent) -> Option<String> {
    match event {
        AgentEvent::ToolStarted { id, input, .. } => {
            let command = ["CommandLine", "command", "cmd"]
                .iter()
                .find_map(|key| input.get(*key).and_then(Value::as_str));
            if let Some(command) = command {
                running.commands.insert(id.clone(), command.to_owned());
            }
        }
        AgentEvent::FileChanged { path, .. } => {
            running.written.extend(in_your_folder(&running.root, path));
            return changed_outside(&[&running.root], event, running.home.as_deref());
        }
        AgentEvent::ToolFinished {
            id,
            ok: false,
            output,
            parent: None,
        } => {
            let refused = output.as_deref().is_some_and(|output| {
                output.contains("permission check failed")
                    || output.contains("required approval")
                    || output.contains("auto-denied")
            });
            if let Some(command) = running.commands.get(id).filter(|_| refused)
                && !running.refused.contains(command)
            {
                running.refused.push(command.clone());
            }
        }
        AgentEvent::TextDelta { text, parent: None } => running.said.push_str(text),
        AgentEvent::Message { text, parent: None } if running.said.is_empty() => {
            running.said.push_str(text);
        }
        _ => {}
    }
    None
}

/// A file the agent changed, by path from your folder. One outside your folder isn't
/// `/rewind`'s.
fn in_your_folder(root: &Path, changed: &str) -> Option<String> {
    let path = Path::new(changed);
    // The CLI may name your folder by its real path, such as /private/var for /var.
    let real = root.canonicalize().ok();
    let relative = if path.is_absolute() {
        path.strip_prefix(root)
            .ok()
            .or_else(|| path.strip_prefix(real.as_deref()?).ok())?
    } else {
        path
    };
    let relative = relative.to_str()?.trim_start_matches("./");
    (!relative.is_empty() && !relative.starts_with("..")).then(|| relative.to_owned())
}

/// After the turn's answer: the snapshot for `/rewind`, then agy's refused commands, offered.
pub(super) fn finished(ctx: &mut Ctx, conversation: &mut ConversationState, turn: &mut Turn) {
    let Some(mut running) = turn.direct.take() else {
        return;
    };
    close_asks(ctx, conversation, &turn.id);
    set_aside_planted(ctx, conversation, &running, &turn.id);
    record(ctx, conversation, &mut running);
    if let Some(left) = left_untracked(&running) {
        ctx.notice(NoteLevel::Info, left);
    }
    let agy = turn.worker.agent == ANTIGRAVITY;
    if agy && running.asks != Asks::Never && !running.refused.is_empty() {
        offer_refused(ctx, conversation, turn, &running.refused);
    }
}

/// A turn that ended without its answer, such as at the limit or a crash: one line says
/// what it changed, so the end is never silent.
pub(super) fn failed(ctx: &mut Ctx, conversation: &mut ConversationState, turn: &mut Turn) {
    let Some(mut running) = turn.direct.take() else {
        return;
    };
    close_asks(ctx, conversation, &turn.id);
    set_aside_planted(ctx, conversation, &running, &turn.id);
    let changed = record(ctx, conversation, &mut running);
    match changed {
        Some(summary) => ctx.notice(NoteLevel::Info, format!("Stopped · {summary}")),
        None => ctx.notice(NoteLevel::Info, "Stopped · nothing changed"),
    }
    if let Some(left) = left_untracked(&running) {
        ctx.notice(NoteLevel::Info, left);
    }
}

/// What a turn left in your checkout, for the lines after its end.
#[derive(Debug, Default)]
pub(super) struct Kept {
    /// What it changed and what `/rewind` puts back, when it changed anything.
    pub(super) changed: Option<String>,
    /// The files it made that git doesn't track.
    untracked: Option<String>,
}

impl Kept {
    pub(super) fn say(&self, ctx: &Ctx) {
        for line in [&self.changed, &self.untracked].into_iter().flatten() {
            ctx.notice(NoteLevel::Info, line.clone());
        }
    }
}

/// A turn a watchdog stopped keeps what it changed, as one Esc stops does.
pub(super) fn kept_after_watchdog(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: &mut Turn,
) -> Kept {
    let Some(mut running) = turn.direct.take() else {
        return Kept::default();
    };
    close_asks(ctx, conversation, &turn.id);
    set_aside_planted(ctx, conversation, &running, &turn.id);
    let changed = record(ctx, conversation, &mut running);
    Kept {
        changed,
        untracked: left_untracked(&running),
    }
}

/// Esc: the turn is stopping, and its files are counted once its session ends.
pub(super) fn cancelled(ctx: &mut Ctx, conversation: &mut ConversationState, turn: &mut Turn) {
    close_asks(ctx, conversation, &turn.id);
    if let Some(mut running) = turn.direct.take() {
        running.listener = None;
        conversation
            .direct
            .stopping
            .insert(turn.id.clone(), running);
    }
}

/// A stopped turn's session ended: what it changed, and `/rewind`.
pub(super) fn stopped(ctx: &mut Ctx, conversation: &mut ConversationState, id: &TurnId) {
    let Some(mut running) = conversation.direct.stopping.remove(id) else {
        return;
    };
    set_aside_planted(ctx, conversation, &running, id);
    if let Some(summary) = record(ctx, conversation, &mut running) {
        ctx.notice(NoteLevel::Info, summary);
    }
    if let Some(left) = left_untracked(&running) {
        ctx.notice(NoteLevel::Info, left);
    }
}

/// What the next agent is told when this one runs out, as a note in its prompt and as the
/// `↷` line says it: the files changed so far, and what the last agent said.
pub(super) fn fallback(ctx: &Ctx, turn: &Turn) -> (String, Option<InputPart>) {
    let Some(running) = turn.direct.as_ref() else {
        return ("your request".to_owned(), None);
    };
    let root = &running.root;
    let max = max_bytes(ctx.settings());
    let changed = running
        .before
        .as_ref()
        .and_then(|before| {
            let keep = running.watched.union(&running.written).cloned().collect();
            let now = rewind::take(root, max, &keep).ok()?;
            let mut changed = rewind::changed(root, before, &now).ok()?;
            changed.extend(rewind::unkept(root, before, &running.written, max));
            changed.sort();
            changed.dedup();
            Some(changed)
        })
        .unwrap_or_default();
    let told = match changed.as_slice() {
        [] => "your request and the transcript so far".to_owned(),
        [one] => format!("your request, the transcript so far, and that {one} changed"),
        many => format!(
            "your request, the transcript so far, and that {} files changed",
            many.len()
        ),
    };
    let mut text = String::from(
        "Another agent started on this request in this folder and stopped before it finished. \
         Carry on from where it left off.",
    );
    if !changed.is_empty() {
        text.push_str(&format!(
            "\n\nFiles it changed so far: {}.",
            changed.join(", ")
        ));
    }
    if !running.said.trim().is_empty() {
        text.push_str(&format!("\n\nWhat it said:\n{}", running.said.trim()));
    }
    (told, Some(part(InputPartKind::Fallback, "fallback", text)))
}

/// The snapshot after the turn, kept when the turn changed something, and a line saying what
/// changed and what `/rewind` can put back. `None` when it changed nothing or there was no
/// snapshot.
fn record(
    ctx: &Ctx,
    conversation: &mut ConversationState,
    running: &mut Running,
) -> Option<String> {
    running.listener = None;
    let before = running.before.take()?;
    let root = &running.root;
    let max = max_bytes(ctx.settings());
    // Ignored files the turn wrote are kept from now on, so a later turn's can be put back.
    for path in &running.written {
        if rewind::ignored(root, path) {
            conversation.direct.watched.insert(path.clone());
        }
    }
    let after = rewind::take(root, max, &conversation.direct.watched)
        .inspect_err(|err| {
            ctx.notice(
                NoteLevel::Warn,
                format!("/rewind can't put back what this turn changed: {err:#}"),
            );
        })
        .ok()?;
    let unkept = rewind::unkept(root, &before, &running.written, max);
    let mut changed = rewind::changed(root, &before, &after).ok()?;
    changed.extend(unkept.iter().cloned());
    changed.sort();
    changed.dedup();
    if changed.is_empty() {
        return None;
    }
    keep_setup_files(ctx, running, &before, &after, &changed, max);
    // Such as "app.py (+1 -1) changed · /rewind puts it back, except .env".
    let mut summary = rewind::summary(root, &before, &after, &changed);
    summary.push_str(" · /rewind puts it back");
    match unkept.as_slice() {
        [] => {}
        [one] => summary.push_str(&format!(", except {one}")),
        [rest @ .., last] => summary.push_str(&format!(", except {} and {last}", rest.join(", "))),
    }
    conversation.direct.turns.push(TurnRecord {
        text: running.text.clone(),
        before,
        after,
        changed,
    });
    Some(summary)
}

/// Notes the files a setup you answered wrote in the turn `turn`, so its end keeps them.
pub(in crate::controller::conversation) fn setup_wrote(
    conversation: &mut super::ConversationState,
    turn: &TurnId,
    paths: &[PathBuf],
) {
    let Some(running) = conversation
        .turn
        .as_mut()
        .filter(|running| &running.id == turn)
        .and_then(|turn| turn.direct.as_mut())
    else {
        return;
    };
    let root = running.root.clone();
    let from_root = paths
        .iter()
        .filter_map(|path| path.strip_prefix(&root).ok())
        .filter_map(|path| path.to_str().map(str::to_owned));
    running.setup_wrote.extend(from_root);
}

/// Whether one of the turn's shell commands names `path` in `.argonauts`: the path itself, or
/// the folder and the file's name, as `cd .argonauts && sed -i … config.toml` does.
fn named_by_command(running: &Running, path: &str) -> bool {
    let name = Path::new(path)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(path);
    running
        .commands
        .values()
        .any(|command| ask::names_setup_folder(command) && command.contains(name))
}

/// The main session never edits Argonauts Code's own files: a setup changes them, after you pick
/// where. Our sandbox keeps `.argonauts/` closed to a direct turn. With it off,
/// what the turn wrote there goes back at once: its own edits, and the files a shell command
/// named, unless a setup you answered wrote them. Anything else that changed there is named,
/// unless the session has Argonauts Code's tools, whose setups you answered write there.
fn keep_setup_files(
    ctx: &Ctx,
    running: &Running,
    before: &rewind::Snapshot,
    after: &rewind::Snapshot,
    changed: &[String],
    max: u64,
) {
    if !ctx.settings().sandbox.mode.ours_off() {
        return;
    }
    let (edited, other): (Vec<String>, Vec<String>) = changed
        .iter()
        .filter(|path| ask::in_setup_folder(path))
        .filter(|path| !running.setup_wrote.contains(*path))
        .cloned()
        .partition(|path| running.written.contains(path) || named_by_command(running, path));
    if !edited.is_empty() {
        match rewind::restore(&running.root, before, after, &edited, max) {
            Ok(restored) if !restored.put_back.is_empty() => ctx.notice(
                NoteLevel::Warn,
                format!(
                    "This turn edited {}, which only a setup changes, so it's put back. Ask for \
                     the change in words and a question asks where to keep it.",
                    restored.put_back.join(", ")
                ),
            ),
            Ok(_) => {}
            Err(err) => ctx.notice(
                NoteLevel::Warn,
                format!(
                    "This turn edited Argonauts Code's own files and they couldn't be put back: {err:#}"
                ),
            ),
        }
    }
    if !other.is_empty() && !running.has_tools {
        ctx.notice(
            NoteLevel::Warn,
            format!(
                "{} changed during this turn. Only a setup should change Argonauts Code's files; \
                 /rewind puts them back.",
                other.join(", ")
            ),
        );
    }
}

fn max_bytes(settings: &Settings) -> u64 {
    settings.captain.rewind_max_mb.saturating_mul(1024 * 1024)
}

/// A question from the turn's session: answered at once when you already allowed it,
/// otherwise shown to you.
pub(crate) fn on_asked(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: &TurnId,
    asked: Asked,
) -> anyhow::Result<Vec<Effect>> {
    let current = conversation
        .turn
        .as_ref()
        .filter(|current| &current.id == turn);
    let Some(current) = current else {
        let _ = asked
            .reply
            .send(AskReply::deny("That turn is over, so nothing runs for it."));
        return Ok(Vec::new());
    };
    match asked.ask {
        Ask::Permission {
            tool_name, input, ..
        } => {
            let patterns = &ctx.settings().approvals.allow_commands;
            if ask::allowed(
                &tool_name,
                &input,
                conversation.direct.edits_allowed,
                patterns,
            ) {
                let _ = asked.reply.send(AskReply::allow(&input));
                return Ok(Vec::new());
            }
            // Autopilot came on after this turn's CLI was told to ask.
            if conversation.direct.approval == ApprovalMode::Autopilot && !asked_by_words(current) {
                let _ = asked.reply.send(on_autopilot(&tool_name, &input));
                return Ok(Vec::new());
            }
            let cli = ctx.names.cli(&current.worker.agent);
            let question = ask::Question::of(&tool_name, &input);
            let id = ctx.next_choice_id();
            let mut choice = choices::app_choice(
                id.clone(),
                ChoiceKind::Permission,
                question.title(&cli, &tool_name),
                question.body.clone(),
                question.options(&cli),
            );
            choice.bell = true;
            conversation.direct.asks.insert(
                id,
                PendingAsk {
                    turn: turn.clone(),
                    tool: tool_name,
                    input,
                    question,
                    reply: asked.reply,
                },
            );
            ctx.send(AppEvent::Choice { choice });
            Ok(Vec::new())
        }
        Ask::Tool { name, arguments } => {
            let call = tools::Call {
                turn: turn.clone(),
                arguments,
                reply: asked.reply,
            };
            Ok(tools::call(ctx, conversation, &name, call))
        }
        Ask::Role { role, what, .. } => {
            let role_asked = crate::controller::ask_role::Asked {
                role,
                what,
                request: current.text.clone(),
                folder: conversation.folder(ctx).to_path_buf(),
            };
            crate::controller::ask_role::answer(ctx, role_asked, asked.reply);
            Ok(Vec::new())
        }
    }
}

/// Your own words had this turn ask you first, which stands whatever the mode on screen.
fn asked_by_words(turn: &Turn) -> bool {
    matches!(&turn.step, TurnStep::Direct { words, .. } if words.supervised)
}

/// Autopilot's answer to what a turn's CLI asks: yes, or a no it carries on from.
fn on_autopilot(tool: &str, input: &Value) -> AskReply {
    if ask::autopilot_allows(tool, input) {
        AskReply::allow(input)
    } else {
        ask::not_on_autopilot()
    }
}

/// Autopilot came on with questions open, and nothing waits for you there. What a turn's CLI
/// asked gets autopilot's answer, unless your own words had that turn ask you first. A turn
/// waiting for who carries it on goes to the first agent that may take it, a plan made first
/// goes ahead, and agy runs what it was refused, as a turn started on autopilot would have.
pub(super) fn settle_on_autopilot(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
) -> anyhow::Result<Vec<Effect>> {
    settle_asks(ctx, conversation);
    let mut effects = settle_fallback(ctx, conversation)?;
    effects.extend(settle_plans(ctx, conversation)?);
    effects.extend(settle_refused(ctx, conversation)?);
    Ok(effects)
}

fn settle_asks(ctx: &Ctx, conversation: &mut ConversationState) {
    let asks_you = conversation
        .turn
        .as_ref()
        .filter(|turn| asked_by_words(turn))
        .map(|turn| turn.id.clone());
    let mut open: Vec<ChoiceId> = conversation
        .direct
        .asks
        .iter()
        .filter(|(_, pending)| Some(&pending.turn) != asks_you.as_ref())
        .map(|(id, _)| id.clone())
        .collect();
    open.sort();
    for id in open {
        let Some(pending) = conversation.direct.asks.remove(&id) else {
            continue;
        };
        let about = &pending.question.about;
        let outcome = if ask::autopilot_allows(&pending.tool, &pending.input) {
            format!("Decided on autopilot · yes to {about}")
        } else {
            format!("Decided on autopilot · no to {about}, which is asked about every time")
        };
        let _ = pending
            .reply
            .send(on_autopilot(&pending.tool, &pending.input));
        ctx.send(AppEvent::ChoiceClosed { id, outcome });
    }
}

/// The turn waiting on "Who carries it on?" or "Who answers instead?" goes to the first agent
/// that may take it by itself, and stops where only agents billed to an API key are left, as
/// one that ran out on autopilot does.
fn settle_fallback(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
) -> anyhow::Result<Vec<Effect>> {
    let Some((id, pending)) = conversation.direct.fallback.take() else {
        return Ok(Vec::new());
    };
    // One turn at a time, and another may have taken its place while the question was open.
    let next = if conversation.turn.is_some() {
        Err("Decided on autopilot · another turn is running, so it stops here.")
    } else {
        shortlist(ctx, &pending.turn.worker, &pending.tried)
            .into_iter()
            .find(|candidate| auto_check(candidate).is_ok())
            .map(|candidate| candidate.worker)
            .ok_or(lifecycle::PAID_ONLY_ON_AUTOPILOT)
    };
    let answers = !pending.turn.step.writes();
    match next {
        Ok(to) => {
            let does = if answers { "answers" } else { "carries it on" };
            ctx.send(AppEvent::ChoiceClosed {
                id,
                outcome: format!("Decided on autopilot · {} {does}", ctx.names.worker(&to)),
            });
            if answers {
                return lifecycle::answer_on(ctx, conversation, pending.turn, pending.tried, &to);
            }
            lifecycle::fallback(
                ctx,
                conversation,
                pending.turn,
                pending.tried,
                pending.why,
                to,
            )
        }
        Err(why_not) => {
            ctx.send(AppEvent::ChoiceClosed {
                id,
                outcome: why_not.to_owned(),
            });
            // A turn that only answers already said it failed, and changed nothing to report.
            if answers {
                return Ok(send_queued(conversation));
            }
            let error = format!("{} {}", pending.turn.worker, pending.why);
            Ok(lifecycle::end_direct(
                ctx,
                conversation,
                pending.turn,
                error,
            ))
        }
    }
}

/// A plan waiting on "Go ahead with this plan?" goes ahead, as one made on autopilot does. The
/// session that planned carries it out, one turn at a time, so a plan that can't have its
/// turn now closes.
fn settle_plans(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
) -> anyhow::Result<Vec<Effect>> {
    let mut open: Vec<ChoiceId> = conversation.direct.plans.keys().cloned().collect();
    open.sort();
    let mut effects = Vec::new();
    for id in open {
        let Some(planned) = conversation.direct.plans.remove(&id) else {
            continue;
        };
        if conversation.turn.is_some() {
            ctx.send(AppEvent::ChoiceClosed {
                id,
                outcome: "Decided on autopilot · not carried out, since a turn is running. \
                          Ask again to have it done."
                    .to_owned(),
            });
            continue;
        }
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: format!(
                "Decided on autopilot · {} goes ahead with its plan",
                planned.cli
            ),
        });
        effects.extend(go_ahead(
            ctx,
            conversation,
            planned.request,
            GO_AHEAD_WITH_PLAN,
            None,
            planned.words,
        )?);
    }
    Ok(effects)
}

/// agy's offer to run what it was refused gets a yes, as a turn started on autopilot runs
/// commands unasked in our sandbox. The grant is for one turn of agy's own session, so an offer
/// that can't have it now closes.
fn settle_refused(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
) -> anyhow::Result<Vec<Effect>> {
    let mut open: Vec<ChoiceId> = conversation.direct.refused.keys().cloned().collect();
    open.sort();
    let mut effects = Vec::new();
    for id in open {
        let Some(offer) = conversation.direct.refused.remove(&id) else {
            continue;
        };
        if conversation.turn.is_some() {
            ctx.send(AppEvent::ChoiceClosed {
                id,
                outcome: "Decided on autopilot · not run, since a turn is running. Ask again \
                          to have them run."
                    .to_owned(),
            });
            continue;
        }
        let cli = ctx.names.cli(&offer.worker.agent);
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: format!(
                "Decided on autopilot · {cli} continues, running commands without asking"
            ),
        });
        effects.extend(go_ahead(
            ctx,
            conversation,
            offer.request,
            RUN_REFUSED,
            Some(Asks::Never),
            DirectWords::default(),
        )?);
    }
    Ok(effects)
}

/// A question of `turn`'s is open, so its CLI waits on you in silence.
pub(super) fn waits_on_you(conversation: &ConversationState, turn: &TurnId) -> bool {
    conversation
        .direct
        .asks
        .values()
        .any(|ask| &ask.turn == turn)
}

pub(crate) fn owns_choice(conversation: &ConversationState, id: &ChoiceId) -> bool {
    conversation.direct.asks.contains_key(id)
        || conversation.direct.refused.contains_key(id)
        || conversation.direct.plans.contains_key(id)
        || conversation.direct.rewinding.as_ref() == Some(id)
        || conversation
            .direct
            .fallback
            .as_ref()
            .is_some_and(|(open, _)| open == id)
}

pub(crate) fn answer_choice(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    action: &AnswerAction,
) -> anyhow::Result<Vec<Effect>> {
    let value = match action {
        AnswerAction::Choose { value } => value.as_str(),
        AnswerAction::Cancel => "no",
        other => anyhow::bail!("{other:?} doesn't answer this question"),
    };
    if let Some(pending) = conversation.direct.asks.remove(&id) {
        return answer_ask(ctx, conversation, id, pending, value);
    }
    if let Some(offer) = conversation.direct.refused.remove(&id) {
        return answer_refused(ctx, conversation, id, offer, value);
    }
    if let Some(planned) = conversation.direct.plans.remove(&id) {
        return answer_plan(ctx, conversation, id, planned, value);
    }
    if conversation
        .direct
        .fallback
        .as_ref()
        .is_some_and(|(open, _)| open == &id)
        && let Some((_, pending)) = conversation.direct.fallback.take()
    {
        return answer_fallback(ctx, conversation, id, pending, value);
    }
    if conversation.direct.rewinding.as_ref() == Some(&id) {
        return rewind_to(ctx, conversation, id, value);
    }
    ctx.notice(NoteLevel::Info, "That question is already closed.");
    Ok(Vec::new())
}

/// Esc: No to a question, the `/rewind` question closed, and agy's offer left waiting.
pub(crate) fn set_aside(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
) -> anyhow::Result<Vec<Effect>> {
    if conversation.direct.refused.contains_key(&id) {
        return Ok(Vec::new());
    }
    answer_choice(ctx, conversation, id, &AnswerAction::Cancel)
}

fn answer_ask(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    pending: PendingAsk,
    value: &str,
) -> anyhow::Result<Vec<Effect>> {
    let mut effects = Vec::new();
    // Such as "Yes to the edit to notes.txt", since the question's own text goes when it
    // closes.
    let about = pending.question.about.clone();
    let outcome = match value {
        "yes" => {
            let _ = pending.reply.send(AskReply::allow(&pending.input));
            format!("Yes to {about}")
        }
        "always" => {
            effects = grant(ctx, conversation, &pending.question.grant)?;
            // What's now allowed answers the questions already waiting on it.
            let _ = pending.reply.send(AskReply::allow(&pending.input));
            answer_waiting(ctx, conversation);
            format!("Yes to {about}, and don't ask again")
        }
        "no" => {
            let _ = pending.reply.send(ask::no());
            // As in Claude Code: No stops the turn, and your next message goes to the agent.
            if conversation
                .turn
                .as_ref()
                .is_some_and(|turn| turn.id == pending.turn)
            {
                effects.extend(super::cancel_turn(ctx, conversation)?);
            }
            format!("No to {about}")
        }
        other => {
            conversation.direct.asks.insert(id, pending);
            anyhow::bail!("{other:?} isn't one of this question's answers");
        }
    };
    ctx.send(AppEvent::ChoiceClosed { id, outcome });
    Ok(effects)
}

/// Saves what "don't ask again" covers: edits for this conversation, or a pattern at "This
/// project, just me", which you set by answering, as with any safety confirm.
fn grant(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    grant: &ask::Grant,
) -> anyhow::Result<Vec<Effect>> {
    let pattern = match grant {
        ask::Grant::Edits => {
            conversation.direct.edits_allowed = true;
            return Ok(Vec::new());
        }
        ask::Grant::Commands(prefix) => ask::command_pattern(prefix),
        ask::Grant::Tool(tool) => tool.clone(),
        ask::Grant::Never => return Ok(Vec::new()),
    };
    let mut patterns = ctx.settings().approvals.allow_commands.clone();
    if patterns.contains(&pattern) {
        return Ok(Vec::new());
    }
    patterns.push(pattern);
    let value = toml::Value::Array(patterns.into_iter().map(toml::Value::String).collect());
    crate::controller::settings::save_answered(
        ctx,
        "approvals.allow_commands",
        value.to_string(),
        SettingScope::ProjectLocal,
    )
}

/// Questions still open that your last answer now allows.
fn answer_waiting(ctx: &mut Ctx, conversation: &mut ConversationState) {
    let patterns = ctx.settings().approvals.allow_commands.clone();
    let edits = conversation.direct.edits_allowed;
    let allowed: Vec<ChoiceId> = conversation
        .direct
        .asks
        .iter()
        .filter(|(_, pending)| ask::allowed(&pending.tool, &pending.input, edits, &patterns))
        .map(|(id, _)| id.clone())
        .collect();
    for id in allowed {
        if let Some(pending) = conversation.direct.asks.remove(&id) {
            let _ = pending.reply.send(AskReply::allow(&pending.input));
            ctx.send(AppEvent::ChoiceClosed {
                id,
                outcome: "Yes".to_owned(),
            });
        }
    }
}

/// The turn's open questions close with it, each a no.
fn close_asks(ctx: &Ctx, conversation: &mut ConversationState, turn: &TurnId) {
    let ids: Vec<ChoiceId> = conversation
        .direct
        .asks
        .iter()
        .filter(|(_, pending)| &pending.turn == turn)
        .map(|(id, _)| id.clone())
        .collect();
    for id in ids {
        conversation.direct.asks.remove(&id);
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: "The turn ended.".to_owned(),
        });
    }
}

fn offer_refused(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    turn: &Turn,
    commands: &[String],
) {
    let cli = ctx.names.cli(&turn.worker.agent);
    let id = ctx.next_choice_id();
    let mut options = choices::options(ChoiceKind::RefusedCommands);
    if let Some(first) = options.first_mut() {
        first.detail = Some(
            "one more turn in which agy runs commands without asking, in our sandbox".to_owned(),
        );
    }
    let choice = choices::app_choice(
        id.clone(),
        ChoiceKind::RefusedCommands,
        format!("Let {cli} run what it was refused?"),
        commands.to_vec(),
        options,
    );
    conversation.direct.refused.insert(
        id,
        RefusedOffer {
            worker: turn.worker.clone(),
            request: turn.text.clone(),
        },
    );
    ctx.send(AppEvent::Choice { choice });
}

/// "Yes, and continue" resumes agy for one turn with `--dangerously-skip-permissions`, inside
/// our sandbox: permission rules can't be set for one agy run, so this is the narrowest grant.
fn answer_refused(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    offer: RefusedOffer,
    value: &str,
) -> anyhow::Result<Vec<Effect>> {
    if value != "continue" {
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: "No".to_owned(),
        });
        return Ok(Vec::new());
    }
    // The grant is for one turn of agy's own session, so it waits for the turn that's running.
    if conversation.turn.is_some() {
        ctx.notice(
            NoteLevel::Info,
            "A turn is running. Answer agy's question once it ends.",
        );
        conversation.direct.refused.insert(id, offer);
        return Ok(Vec::new());
    }
    let cli = ctx.names.cli(&offer.worker.agent);
    ctx.send(AppEvent::ChoiceClosed {
        id,
        outcome: format!("{cli} continues, running commands without asking"),
    });
    go_ahead(
        ctx,
        conversation,
        offer.request,
        RUN_REFUSED,
        Some(Asks::Never),
        DirectWords::default(),
    )
}

/// `/rewind` in a direct conversation: your messages whose turns changed files, newest first.
pub(crate) fn rewind(ctx: &mut Ctx, conversation: &mut ConversationState) -> bool {
    if conversation.direct.turns.is_empty() {
        if !ctx.env.git().has_history() && conversation.place.is_none() {
            ctx.notice(
                NoteLevel::Info,
                "This folder has no git, so nothing was kept to go back to. /git turns on a \
                 hidden history, and /rewind works from then on.",
            );
            return true;
        }
        return false;
    }
    let id = ctx.next_choice_id();
    let newest = conversation.direct.turns.len() - 1;
    let options = conversation
        .direct
        .turns
        .iter()
        .enumerate()
        .rev()
        .zip('a'..='z')
        .map(|((index, record), key)| {
            let mut option = option(
                key,
                &crate::controller::recap::title_from_request(&record.text),
                choices::choose(&index.to_string()),
                index == newest,
            );
            option.detail = Some(match record.changed.len() {
                1 => record.changed[0].clone(),
                n => format!("{n} files"),
            });
            option
        })
        .collect();
    let choice = choices::app_choice(
        id.clone(),
        ChoiceKind::RewindTurn,
        "Put back the files changed since which message?",
        vec!["Files you changed since stay as you left them.".to_owned()],
        options,
    );
    conversation.direct.rewinding = Some(id);
    ctx.send(AppEvent::Choice { choice });
    true
}

fn rewind_to(
    ctx: &mut Ctx,
    conversation: &mut ConversationState,
    id: ChoiceId,
    value: &str,
) -> anyhow::Result<Vec<Effect>> {
    conversation.direct.rewinding = None;
    let Ok(from) = value.parse::<usize>() else {
        ctx.send(AppEvent::ChoiceClosed {
            id,
            outcome: choices::NOT_CHANGED.to_owned(),
        });
        return Ok(Vec::new());
    };
    let (Some(target), Some(last)) = (
        conversation.direct.turns.get(from),
        conversation.direct.turns.last(),
    ) else {
        anyhow::bail!("that message's files can't be put back any more");
    };
    let mut paths: Vec<String> = conversation.direct.turns[from..]
        .iter()
        .flat_map(|record| record.changed.iter().cloned())
        .collect();
    paths.sort();
    paths.dedup();
    let root = conversation.folder(ctx).to_path_buf();
    let restored = rewind::restore(
        &root,
        &target.before,
        &last.after,
        &paths,
        max_bytes(ctx.settings()),
    )?;
    let asked = target.text.clone();
    conversation.direct.turns.truncate(from);
    let mut outcome = match restored.put_back.len() {
        0 => "Nothing to put back".to_owned(),
        1 => format!("Put back {}", restored.put_back[0]),
        n => format!("Put back {n} files"),
    };
    if !restored.kept.is_empty() {
        outcome.push_str(&format!(
            " · kept as you changed them: {}",
            restored.kept.join(", ")
        ));
    }
    if !restored.cant.is_empty() {
        outcome.push_str(&format!(
            " · can't put back, as nothing kept how they were: {}",
            restored.cant.join(", ")
        ));
    }
    ctx.send(AppEvent::ChoiceClosed { id, outcome });
    if !restored.put_back.is_empty() {
        conversation.direct.rewound = Some(format!(
            "The user put back these files to how they were before \"{}\": {}.",
            asked,
            restored.put_back.join(", ")
        ));
    }
    Ok(Vec::new())
}