procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
mod account;
mod agent;
mod anthropic;
mod app;
mod bench;
mod budget;
mod channels;
mod config;
mod context;
mod credentials;
mod diag;
mod knowledge;
mod llm;
mod mcp;
mod oauth;
mod openai;
mod party;
mod personas;
mod project;
mod registries;
mod risk;
mod runtime;
mod session;
mod skills;
mod sse;
mod tools;
mod ui;
mod verify;
mod wizard;

use color_eyre::Result;
use crossterm::cursor::SetCursorStyle;
use crossterm::event::{self, Event};
use ratatui::DefaultTerminal;
use tokio::sync::mpsc;

// A thin steady bar reads better against a text input than the terminal's default block, which
// buries the character it sits on. Reset on the way out so a user's own terminal preference isn't
// left overridden after Procyon quits.
fn set_cursor_style(style: SetCursorStyle) {
    let _ = crossterm::execute!(std::io::stdout(), style);
}

const USAGE: &str = "\
procyon - development harness for Stellar and Soroban

    procyon                  start a new session
    procyon --resume         resume the most recent session for this directory
    procyon --resume <id>    resume a specific session
    procyon --sessions       list sessions for this directory
    procyon --authorize <name>   sign in to an MCP server that requires OAuth
    procyon --knowledge      print the knowledge snapshot (skills, digests, servers)
    procyon --bench [name]   run the Developer Parity tasks in bench/tasks
    procyon --exec <prompt>   run one prompt with no terminal and print the answer
    procyon --exec <prompt> --allow-changes   ...and let it write, deploy or sign
    procyon --help
";

#[derive(Debug)]
enum Startup {
    New,
    Resume(Option<String>),
    ListSessions,
    Authorize(Option<String>),
    /// Run the benchmark tasks. `Some(name)` runs one of them, for iterating on a task without
    /// paying for the whole suite.
    Bench(Option<String>),
    /// Print what the agent would be working from. Commit it, diff it, and a change in behaviour
    /// can be traced to a change in inputs instead of being blamed on the model.
    Knowledge,
    /// One prompt, no terminal. `allow_changes` is the operator's answer, given up front, to every
    /// approval the run would otherwise have to ask about — there is no screen to ask on.
    Exec {
        prompt: String,
        allow_changes: bool,
    },
    ShowUsage,
}

fn parse_args<I: Iterator<Item = String>>(args: I) -> Startup {
    let mut args = args.peekable();
    match args.next().as_deref() {
        None => Startup::New,
        Some("--sessions") => Startup::ListSessions,
        Some("--help" | "-h") => Startup::ShowUsage,
        Some("--resume") => Startup::Resume(args.next()),
        Some("--authorize") => Startup::Authorize(args.next()),
        Some("--knowledge") => Startup::Knowledge,
        Some("--bench") => Startup::Bench(args.next().filter(|name| !name.starts_with("--"))),
        Some("--exec") => {
            // The flag is read from anywhere after `--exec`, not just from the position after the
            // prompt: `--exec --allow-changes "..."` is a reasonable thing to type, and taking it
            // as the prompt would run the word `--allow-changes` as a question.
            let rest: Vec<String> = args.collect();
            let allow_changes = rest.iter().any(|arg| arg == "--allow-changes");
            match rest
                .into_iter()
                .find(|arg| !arg.starts_with("--") && !arg.trim().is_empty())
            {
                Some(prompt) => Startup::Exec {
                    prompt,
                    allow_changes,
                },
                None => Startup::ShowUsage,
            }
        }
        Some(_) => Startup::ShowUsage,
    }
}

// Resolved before the TUI starts so listing and argument errors print to a normal terminal.
async fn resolve_startup(
    startup: Startup,
    cfg: &config::AppConfig,
) -> Result<Option<std::path::PathBuf>> {
    let cwd = std::env::current_dir()?;

    match startup {
        Startup::New => Ok(None),
        Startup::ShowUsage => {
            print!("{}", USAGE);
            std::process::exit(0);
        }
        Startup::Bench(only) => {
            let tasks = bench::load_tasks(&cwd.join("bench").join("tasks"))?;
            let tasks: Vec<_> = match &only {
                Some(name) => tasks.into_iter().filter(|t| &t.name == name).collect(),
                None => tasks,
            };
            if tasks.is_empty() {
                color_eyre::eyre::bail!("No benchmark task named {}", only.unwrap_or_default());
            }

            // Printed as each task finishes rather than collected and printed at the end: a suite
            // is minutes per task, and a run with no output until it is over is a run people kill.
            let mut outcomes = Vec::new();
            for task in &tasks {
                let outcome = bench::run_task(cfg, task).await;
                eprintln!("{}", outcome.summary());
                outcomes.push(outcome);
            }
            // The report on stdout, the progress on stderr, so `--bench > report.toml` gives a
            // report and still shows its progress.
            print!("{}", bench::report_toml(&outcomes));
            std::process::exit(if outcomes.iter().all(|o| o.accepted) {
                0
            } else {
                1
            });
        }
        Startup::Knowledge => {
            print!("{}", knowledge::snapshot(cfg).await.to_toml());
            std::process::exit(0);
        }
        // Answered here rather than by starting the TUI: the whole point is that no terminal is
        // taken over, so the answer goes to stdout and the process ends with a status a script can
        // read.
        Startup::Exec {
            prompt,
            allow_changes,
        } => match runtime::run_once(cfg, &prompt, allow_changes).await {
            Ok(run) => {
                println!("{}", run.text.trim_end());
                std::process::exit(0);
            }
            Err(e) => {
                eprintln!("procyon: {}", e);
                std::process::exit(1);
            }
        },
        Startup::ListSessions => {
            let sessions = session::list(&cwd).await?;
            if sessions.is_empty() {
                println!("No sessions recorded for {}", cwd.display());
            } else {
                for (_, header) in &sessions {
                    println!("{}  {}", header.id, header.created_at);
                }
            }
            std::process::exit(0);
        }
        Startup::Authorize(which) => {
            let name = which.ok_or_else(|| {
                color_eyre::eyre::eyre!("--authorize needs a server name from config.toml")
            })?;
            let server = cfg
                .mcp_servers
                .iter()
                .find(|s| s.name == name)
                .ok_or_else(|| {
                    color_eyre::eyre::eyre!("No mcp_servers entry named '{}' in the config", name)
                })?;

            // Runs before the TUI: the flow prints a URL and waits, which needs a usable terminal.
            mcp::authorize(server)
                .await
                .map_err(|e| color_eyre::eyre::eyre!(e))?;
            std::process::exit(0);
        }
        Startup::Resume(which) => {
            let sessions = session::list(&cwd).await?;
            let found = match &which {
                Some(id) => sessions.into_iter().find(|(_, h)| &h.id == id),
                None => sessions.into_iter().next(),
            };
            match found {
                Some((path, _)) => Ok(Some(path)),
                None => match which {
                    Some(id) => color_eyre::eyre::bail!("No session {} for {}", id, cwd.display()),
                    None => color_eyre::eyre::bail!("No session to resume in {}", cwd.display()),
                },
            }
        }
    }
}

fn main() -> Result<()> {
    color_eyre::install()?;
    dotenvy::dotenv().ok();

    let startup = parse_args(std::env::args().skip(1));

    // Loaded before entering raw mode: a malformed config must report onto a usable terminal
    // instead of an alternate screen that is about to be torn down.
    let cfg = config::AppConfig::load()?;

    // On first run, offer the onboarding wizard before the main TUI.
    let cfg = if config::AppConfig::is_first_run() {
        let mut terminal = ratatui::init();
        set_cursor_style(SetCursorStyle::SteadyBar);
        let result = wizard::run_wizard(&mut terminal);
        set_cursor_style(SetCursorStyle::DefaultUserShape);
        ratatui::restore();

        match result? {
            Some(wizard_cfg) => wizard_cfg,
            None => cfg, // User skipped; proceed with defaults.
        }
    } else {
        cfg
    };

    let resume_from = tokio::runtime::Runtime::new()?.block_on(resolve_startup(startup, &cfg))?;

    let mut terminal = ratatui::init();
    set_cursor_style(SetCursorStyle::SteadyBar);
    let result = run(&mut terminal, cfg, resume_from);
    set_cursor_style(SetCursorStyle::DefaultUserShape);
    ratatui::restore();
    result
}

#[tokio::main]
async fn run(
    terminal: &mut DefaultTerminal,
    cfg: config::AppConfig,
    resume_from: Option<std::path::PathBuf>,
) -> Result<()> {
    let theme = cfg.theme.clone();

    let mut state = app::AppState::new();
    let channels = channels::Channels::new();

    let user_tx = channels.user_tx.clone();
    let agent_tx = channels.agent_tx.clone();
    let mut agent_rx = channels.agent_rx;

    // Shared rather than sent: the agent is inside the turn loop when the user wants to stop it,
    // and so is not reading commands.
    state.cancel = channels.cancel.clone();
    state.approval_tx = Some(channels.approval_tx);
    let cancel = channels.cancel;
    let approvals = channels.approval_rx;

    tokio::spawn(async move {
        agent_task(
            channels.user_rx,
            agent_tx,
            cfg,
            resume_from,
            cancel,
            approvals,
        )
        .await;
    });

    // A dedicated blocking thread owns stdin: `spawn_blocking` inside `select!` cannot be
    // cancelled, so a losing read would swallow the next keypress.
    let (input_tx, mut input_rx) = mpsc::unbounded_channel();
    std::thread::spawn(move || {
        while let Ok(ev) = event::read() {
            if input_tx.send(ev).is_err() {
                break;
            }
        }
    });

    // Keypresses and agent updates are the only things that used to trigger a redraw, so nothing
    // could animate. This tick is what drives the context panel's spinner while a turn is in
    // flight; `state.tick()` is cheap enough that redrawing on it ~8 times a second even while
    // idle isn't worth special-casing away.
    let mut spinner = tokio::time::interval(std::time::Duration::from_millis(120));
    spinner.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

    loop {
        terminal.draw(|frame| {
            ui::render(frame, &mut state, &theme);
        })?;

        tokio::select! {
            Some(ev) = input_rx.recv() => {
                if let Event::Key(key) = ev {
                    if state.handle_key(key, &user_tx) {
                        let _ = user_tx.send(channels::UserCommand::Quit);
                        return Ok(());
                    }
                }
            }
            Some(update) = agent_rx.recv() => {
                state.handle_agent_update(update);
            }
            _ = spinner.tick() => {
                state.tick();
            }
        }
    }
}

/// What goes into the history in place of the reply the user cut short.
///
/// The marker is in-band because the model reads this back on the next turn: without it, a
/// sentence that stops mid-word looks like something it chose to say, and it will try to continue
/// a thought the user deliberately ended.
fn interrupted_text(partial: &str) -> String {
    let partial = partial.trim_end();
    if partial.is_empty() {
        "[The user interrupted this turn before any reply was produced.]".to_string()
    } else {
        format!("{}\n\n[The user interrupted this turn here.]", partial)
    }
}

/// Fold the gathered workspace into what the status line and `/status` display.
fn workspace_snapshot(
    ctx: &context::WorkspaceContext,
    cfg: &config::AppConfig,
    mcp_connected: &[String],
) -> channels::WorkspaceSnapshot {
    let mcp_servers = cfg
        .mcp_servers
        .iter()
        .map(|s| channels::McpServerStatus {
            name: s.name.clone(),
            connected: mcp_connected.iter().any(|line| line.contains(&s.name)),
            detail: s.endpoint_label(),
        })
        .collect();

    channels::WorkspaceSnapshot {
        project_name: ctx
            .project
            .as_ref()
            .map(|p| p.name.clone())
            .unwrap_or_else(|| "No project".to_string()),
        contract_name: ctx
            .project
            .as_ref()
            .and_then(|p| p.contracts.first().map(|c| c.name.clone())),
        // Only a project.toml records a network. An inferred project defaults to testnet because
        // the filesystem does not say, and letting that invented value overwrite the user's
        // configured default would silently move them off `local`.
        network: ctx
            .project
            .as_ref()
            .filter(|p| !p.is_inferred())
            .map(|p| p.default_network.to_string())
            .unwrap_or_else(|| cfg.default_network.clone()),
        account: ctx
            .accounts
            .first()
            .map(|a| a.split(' ').next().unwrap_or("None").to_string())
            .unwrap_or_else(|| "None".to_string()),
        mcp_servers,
        mainnet_allowed: tools::mainnet::mainnet_allowed(),
    }
}

async fn agent_task(
    mut user_rx: mpsc::UnboundedReceiver<channels::UserCommand>,
    agent_tx: mpsc::UnboundedSender<channels::AgentUpdate>,
    mut cfg: config::AppConfig,
    resume_from: Option<std::path::PathBuf>,
    cancel: channels::CancelFlag,
    approvals: mpsc::UnboundedReceiver<channels::ApprovalDecision>,
) {
    // The window depends on which model the config selected, so it is resolved once here rather
    // than read from a constant at each check.
    let mut context_window = budget::context_window(cfg.provider, &cfg.default_model);
    // A missing credential used to end the task here. That took the command channel down with it,
    // so every later `/model` reached a dropped receiver while the UI — which discards send
    // failures — kept reporting switches that never happened. The one recovery the user has is the
    // one the exit removed, so the agent stays up without a client instead.
    let mut client = match llm::LlmClient::from_config(&cfg) {
        Ok(client) => Some(client),
        Err(e) => {
            let _ = agent_tx.send(channels::AgentUpdate::Error(e.to_string()));
            None
        }
    };
    let _ = agent_tx.send(channels::AgentUpdate::Ready {
        provider: cfg.provider.to_string(),
        model: cfg.default_model.clone(),
        credential: client.is_some(),
    });

    // The tool set, the MCP servers and the plugins all come from `runtime`, which is also what
    // `--exec` loads: a second front end that offered a different set of tools would make every
    // measurement taken through one of them untransferable to the other.
    let loaded = runtime::load_tools(
        &cfg,
        Some(std::sync::Arc::new(tools::approval::Approver::new(
            agent_tx.clone(),
            approvals,
            cancel.clone(),
        ))),
    )
    .await;
    let registry = loaded.registry;
    let mcp_connected = loaded.mcp_connected;

    // Connected servers are reported by the structured `McpStatus` below and shown by `/status`;
    // announcing each one in the transcript too was startup noise that also faked a running turn.
    for problem in &loaded.problems {
        let _ = agent_tx.send(channels::AgentUpdate::Error(problem.clone()));
    }
    for notice in &loaded.notices {
        let _ = agent_tx.send(channels::AgentUpdate::Notice(notice.clone()));
    }

    // Structured MCP status for the Context panel.
    {
        let statuses: Vec<channels::McpServerStatus> = cfg
            .mcp_servers
            .iter()
            .map(|s| channels::McpServerStatus {
                name: s.name.clone(),
                connected: mcp_connected.iter().any(|line| line.contains(&s.name)),
                detail: s.endpoint_label(),
            })
            .collect();
        let _ = agent_tx.send(channels::AgentUpdate::McpStatus(statuses));
    }

    let tool_defs = registry.definitions();
    let config_for_subagent = std::sync::Arc::new(cfg.clone());

    // Add spawn_agent to tool definitions so the LLM knows about it,
    // but handle execution specially since it needs the full registry.
    let spawn_agent_def = crate::agent::ToolDefinition {
        name: "spawn_agent".to_string(),
        description: "Spawn a sub-agent with a custom system prompt and optional tool subset. \
             The sub-agent runs independently with its own LLM context and returns \
             a text response. Use this to delegate tasks to specialized personas."
            .to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "system_prompt": {
                    "type": "string",
                    "description": "System prompt defining the sub-agent's persona and instructions"
                },
                "message": {
                    "type": "string",
                    "description": "The task or question for the sub-agent to handle"
                },
                "model": {
                    "type": "string",
                    "description": "Optional model override (e.g. 'claude-haiku')"
                },
                "max_tokens": {
                    "type": "integer",
                    "description": "Optional max tokens override"
                },
                "allowed_tools": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Optional list of tool names the sub-agent may use. If omitted, all tools except spawn_agent are available."
                },
                "timeout_secs": {
                    "type": "integer",
                    "description": "Optional deadline for each LLM request the sub-agent makes, in seconds (default 120)"
                }
            },
            "required": ["system_prompt", "message"]
        }),
    };
    let mut tool_defs_with_spawn = tool_defs;
    tool_defs_with_spawn.push(spawn_agent_def);
    let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));

    let (mut log, mut history) = match resume_from {
        Some(path) => match session::resume(&path).await {
            Ok(resumed) => {
                // The transcript first, so the notice lands under the conversation it describes
                // rather than above an empty screen.
                let _ = agent_tx.send(channels::AgentUpdate::History(resumed.transcript));
                let _ = agent_tx.send(channels::AgentUpdate::Notice(format!(
                    "Resumed session {}.",
                    resumed.log.id(),
                )));
                (Some(resumed.log), resumed.history)
            }
            Err(e) => {
                let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                    "Could not resume {}: {}",
                    path.display(),
                    e
                )));
                (None, Vec::new())
            }
        },
        None => match session::SessionLog::create(&cwd).await {
            // A fresh session records by default; saying so — with a full path — on every launch
            // was the single longest line on an otherwise empty screen.
            Ok(log) => (Some(log), Vec::new()),
            Err(e) => {
                let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                    "Running without a session log: {}",
                    e
                )));
                (None, Vec::new())
            }
        },
    };

    let mut explain = false;
    let mut budget = budget::Budget::new();

    // Output from tools the user ran themselves, waiting to be folded into their next prompt. Not
    // pushed into `history` when it happens: that would put two user messages in a row, which the
    // wire formats do not all accept. Folded in rather than dropped because the workflow is press
    // Ctrl+T, read the failure, ask why — and the model has to have seen what the user saw.
    let mut quick_action_output: Vec<String> = Vec::new();

    // What has already been tried this session, for the next turn's prompt. Kept here rather than
    // read back out of the conversation because the conversation is the thing that gets compacted.
    let mut operations = context::OperationLog::default();

    // What the local server has, so `/model` and its autocomplete can name real models instead of
    // a built-in list of suggestions that omitted the model actually in use.
    let _ = agent_tx.send(channels::AgentUpdate::LocalModels(
        llm::installed_models(&cfg).await.unwrap_or_default(),
    ));

    // Sent once before the first prompt: the per-turn snapshot below is the only other source, so
    // until a turn ran `/status` reported the `AppState` defaults — "No project" in a project.
    if let Ok(cwd) = std::env::current_dir() {
        let ctx = context::WorkspaceContext::gather(&cwd, &mcp_connected).await;
        let _ = agent_tx.send(channels::AgentUpdate::Workspace(workspace_snapshot(
            &ctx,
            &cfg,
            &mcp_connected,
        )));
    }

    while let Some(cmd) = user_rx.recv().await {
        match cmd {
            channels::UserCommand::SendPrompt(prompt) => {
                // An Esc pressed while idle, or one still set from the turn it stopped, would
                // otherwise cancel this turn before it began.
                cancel.take();

                // Anything the user ran themselves since the last turn goes in ahead of what they
                // typed, so "why did that fail?" is answerable.
                let prompt = if quick_action_output.is_empty() {
                    prompt
                } else {
                    format!(
                        "{}\n\n{}",
                        std::mem::take(&mut quick_action_output).join("\n\n"),
                        prompt
                    )
                };

                // Refused rather than queued: without a client there is nothing to send the turn
                // to, and recording it would leave the session log claiming a turn that never ran.
                let Some(client) = client.as_ref() else {
                    let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                        "No credential for provider {}, so the prompt was not sent. Set {} and \
                         restart, or switch to a local provider with `/model provider ollama`.",
                        cfg.provider,
                        cfg.key_env_var()
                    )));
                    let _ = agent_tx.send(channels::AgentUpdate::ResponseEnd);
                    continue;
                };

                let _ = agent_tx.send(channels::AgentUpdate::Status("Thinking...".to_string()));

                // Rebuilt per turn: the project, contracts and accounts change as the agent works,
                // and a snapshot taken at boot would go stale mid-conversation.
                let workspace = match std::env::current_dir() {
                    Ok(cwd) => {
                        let ctx = context::WorkspaceContext::gather(&cwd, &mcp_connected)
                            .await
                            .with_session(skill_names().await, operations.recent())
                            .with_unverified(verify::session().pending());
                        // Push structured snapshot for the Context panel — network/account/contract/mcp
                        let _ = agent_tx.send(channels::AgentUpdate::Workspace(
                            workspace_snapshot(&ctx, &cfg, &mcp_connected),
                        ));
                        Some(ctx.system_prompt())
                    }
                    Err(e) => {
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "Cannot determine the working directory: {}",
                            e
                        )));
                        None
                    }
                };

                record(&mut log, &agent_tx, session::SessionEvent::TurnStart).await;
                record(
                    &mut log,
                    &agent_tx,
                    session::SessionEvent::UserMessage {
                        text: prompt.clone(),
                    },
                )
                .await;

                history.push(agent::Message::user(&prompt));

                let (text_tx, mut text_rx) = mpsc::unbounded_channel::<String>();

                // What the model has said so far in the round trip now in flight. Only read on
                // cancel: `send_message_streaming` returns the blocks it assembled, and a cancel
                // is exactly the case where it never returns them, so without this the text
                // already on the user's screen would be missing from the history.
                let streamed = std::sync::Arc::new(std::sync::Mutex::new(String::new()));

                let agent_tx_clone = agent_tx.clone();
                let streamed_w = streamed.clone();
                let forwarder = tokio::spawn(async move {
                    while let Some(text) = text_rx.recv().await {
                        if let Ok(mut buf) = streamed_w.lock() {
                            buf.push_str(&text);
                        }
                        let _ = agent_tx_clone.send(channels::AgentUpdate::ResponseChunk(text));
                    }
                });

                // A turn recorded as complete when its request failed makes the log claim
                // something that did not happen.
                let mut turn_failed = false;
                let mut turn_cancelled = false;

                // Scoped to the turn, deliberately. As a function-level binding it was only ever
                // cleared after a successful request, so the first turn that failed to recover
                // disarmed the overflow retry for the rest of the session.
                let mut overflow_retried = false;
                // Once compaction has reported that it cannot shrink this history, retrying it on
                // every tool round trip buys nothing and costs a summarization request each time.
                let mut compaction_stalled = false;
                // Warned once per turn rather than on every round trip once it stays true.
                let mut truncation_risk_warned = false;

                // Ollama's real window is a server setting, not a property of the model, and it is
                // only knowable once the model is loaded — which it is not before the first
                // request. So it is re-read per turn rather than resolved at boot: a user who
                // raises `OLLAMA_CONTEXT_LENGTH` and restarts their server should stop being
                // warned about a ceiling that no longer exists, without restarting Procyon too.
                if let Some(actual) = llm::ollama_context_length(&cfg, &cfg.default_model).await {
                    if actual != context_window {
                        context_window = actual;
                        budget.invalidate();
                    }
                }

                // The window the prompt may occupy, with room for the reply the provider will
                // count against the same window.
                let prompt_window = budget::usable_window(context_window, cfg.max_tokens as usize);

                loop {
                    // Between round trips: the cheapest place to stop, and the only one that
                    // needs no unwinding — nothing is in flight and the history is consistent.
                    if cancel.is_raised() {
                        turn_cancelled = true;
                        break;
                    }
                    // Scoped to this round trip. Text from earlier ones is already in `history` as
                    // assistant blocks, so carrying it forward would record it twice on a cancel.
                    if let Ok(mut buf) = streamed.lock() {
                        buf.clear();
                    }

                    let system = build_system_prompt(workspace.as_deref(), explain);
                    let turn_tools =
                        runtime::tools_for_provider(cfg.provider, &tool_defs_with_spawn);

                    // The system prompt is rebuilt per turn and the tool block carries every MCP
                    // server's schemas, so neither is a constant the threshold can ignore.
                    budget.set_envelope(budget::price_envelope(system.as_deref(), &turn_tools));

                    // Checked before the request goes out, so pressure is relieved instead of
                    // being discovered as an API error.
                    if !compaction_stalled && budget.is_over_threshold(&history, prompt_window) {
                        let shrank = compact(
                            client,
                            &mut history,
                            &mut budget,
                            budget::retain_tokens(prompt_window),
                            &agent_tx,
                            &mut log,
                        )
                        .await;
                        compaction_stalled = !shrank;
                    }

                    // Reported after compaction, so the gauge shows what is actually about to be
                    // sent rather than the peak that triggered the trim. Against `prompt_window`
                    // rather than the raw window: that is the budget the conversation really has,
                    // once the reply the provider counts against the same window is reserved.
                    let _ = agent_tx.send(channels::AgentUpdate::Context {
                        used: budget.total(&history),
                        window: prompt_window,
                    });

                    // Every other provider rejects an over-budget request with an error the retry
                    // below reacts to. Ollama's OpenAI-compatible endpoint does neither — verified
                    // against a live 0.20.4 server, it silently truncates the prompt and answers
                    // HTTP 200 as if nothing were missing. Once compaction has nothing left to
                    // trim, that silent failure is the only way this turn can go wrong, so it is
                    // said out loud instead of showing up as a confidently wrong answer. Cutting
                    // the tool list to `OLLAMA_CORE_TOOLS` above keeps this from firing in the
                    // common case; it is left in for whatever still does not fit (a long
                    // conversation, an unusually large project context).
                    if !truncation_risk_warned
                        && matches!(cfg.provider, config::Provider::Ollama)
                        && budget.is_over_threshold(&history, prompt_window)
                    {
                        truncation_risk_warned = true;
                        // Says what to do about it. The warning used to end at "may be based on an
                        // incomplete prompt", which is honest and also a dead end: the ceiling is
                        // the server's, set by an environment variable, and nothing on screen said
                        // so. A user reading it had no way to know the fix was one line.
                        let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                            "Warning: the system prompt and {} tool definitions do not fit in the \
                             {} tokens this Ollama server loaded {} with, and there is nothing \
                             left to trim. Ollama truncates silently rather than erroring, so this \
                             response may be based on an incomplete prompt. The window is the \
                             server's, not the model's — restart it with \
                             OLLAMA_CONTEXT_LENGTH=32768 (the model itself supports far more) and \
                             this stops.",
                            turn_tools.len(),
                            context_window,
                            cfg.default_model,
                        )));
                    }

                    // The request is about to leave the process; make sure what led to it is on
                    // disk first.
                    barrier(&mut log, &agent_tx).await;

                    // Racing the request against the flag is what makes Esc feel immediate: losing
                    // the race drops the response future, which closes the connection mid-stream
                    // rather than waiting out a reply the user has already given up on.
                    let sent = tokio::select! {
                        biased;
                        result = client.send_message_streaming(
                            &history,
                            Some(&turn_tools),
                            system.as_deref(),
                            &text_tx,
                        ) => Some(result),
                        _ = cancel.wait() => None,
                    };

                    let Some(sent) = sent else {
                        // Whatever the model managed to say is on screen already, so it belongs in
                        // the history too — and an assistant turn has to follow the user turn that
                        // is already there.
                        let partial = streamed.lock().map(|b| b.clone()).unwrap_or_default();
                        let blocks = vec![agent::ContentPart::Text {
                            text: interrupted_text(&partial),
                        }];
                        record(
                            &mut log,
                            &agent_tx,
                            session::SessionEvent::AssistantMessage {
                                blocks: blocks.clone(),
                            },
                        )
                        .await;
                        history.push(agent::Message::assistant(blocks));
                        turn_cancelled = true;
                        break;
                    };

                    let outcome = match sent {
                        Ok(outcome) => outcome,
                        Err(e) => {
                            // The estimator can be wrong; if the provider says the window is
                            // blown, compact ignoring the retained tail and try once more.
                            if is_context_overflow(&e) && !overflow_retried {
                                overflow_retried = true;
                                let _ = agent_tx.send(channels::AgentUpdate::Status(
                                    "Context window exceeded, compacting and retrying.".to_string(),
                                ));
                                // Retained at the ratio the threshold path uses, not at zero: a
                                // zero retain hands the summarizer the entire history the provider
                                // just refused for being too long, so the one request that could
                                // save the turn is the one most likely to be refused as well.
                                let shrank = compact(
                                    client,
                                    &mut history,
                                    &mut budget,
                                    budget::retain_tokens(prompt_window),
                                    &agent_tx,
                                    &mut log,
                                )
                                .await;
                                // Retrying an unchanged history reissues a request that is
                                // byte-identical to the one that just failed: the same rejection,
                                // billed twice.
                                if shrank {
                                    continue;
                                }
                                let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                                    "Context window exceeded and the history could not be \
                                     shrunk, so the request was not retried: {}",
                                    e
                                )));
                                turn_failed = true;
                                break;
                            }
                            let _ = agent_tx.send(channels::AgentUpdate::Error(e.to_string()));
                            turn_failed = true;
                            break;
                        }
                    };

                    overflow_retried = false;
                    let usage = outcome.usage;

                    // Before anything records or renders it: a call the model wrote as text is a
                    // call, and letting it through as prose put raw JSON on screen where a reply
                    // should have been — and left the tool unrun.
                    let (blocks, recovered) = agent::recover_text_tool_calls(outcome.blocks);
                    if recovered {
                        // The text is already on screen, streamed chunk by chunk while the model
                        // produced it.
                        let _ = agent_tx.send(channels::AgentUpdate::RetractResponse);
                    }

                    if blocks.is_empty() {
                        break;
                    }

                    record(
                        &mut log,
                        &agent_tx,
                        session::SessionEvent::AssistantMessage {
                            blocks: blocks.clone(),
                        },
                    )
                    .await;
                    history.push(agent::Message::assistant(blocks.clone()));

                    // Anchored after the push: the reported total includes the output tokens, and
                    // those are part of the next request's prompt. Anchoring first left the
                    // estimator charging for the same reply a second time as a delta.
                    if let Some(usage) = usage {
                        budget.anchor(usage.total(), &history);
                    }

                    let tool_uses: Vec<_> = blocks
                        .iter()
                        .filter_map(|b| match b {
                            agent::ContentPart::ToolUse { id, name, input } => {
                                Some((id.clone(), name.clone(), input.clone()))
                            }
                            _ => None,
                        })
                        .collect();

                    if tool_uses.is_empty() {
                        break;
                    }

                    // The API requires every tool_result for one assistant turn to arrive in a
                    // single user message.
                    let mut results = Vec::with_capacity(tool_uses.len());
                    for (id, name, input) in tool_uses {
                        // Every `tool_use` must be answered even when the user has stopped the
                        // turn: a missing `tool_result` is rejected by both wire formats, and the
                        // block is already in the history and the session log. So the remaining
                        // calls are skipped by answering them, not by dropping them.
                        //
                        // A tool already running is left to finish. It may be a build or a deploy,
                        // and a half-killed one is a worse thing to hand back than a slow one.
                        if cancel.is_raised() {
                            turn_cancelled = true;
                            let content = "Error: the user interrupted the turn before this tool \
                                           ran."
                                .to_string();
                            record(
                                &mut log,
                                &agent_tx,
                                session::SessionEvent::ToolResult {
                                    id: id.clone(),
                                    content: content.clone(),
                                    is_error: true,
                                },
                            )
                            .await;
                            results.push((id, content));
                            continue;
                        }

                        let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                            "Using tool: {}",
                            name
                        )));

                        // Recorded and made durable *before* the tool runs, so a crash leaves
                        // evidence that it may already have acted.
                        record(
                            &mut log,
                            &agent_tx,
                            session::SessionEvent::ToolCall {
                                id: id.clone(),
                                name: name.clone(),
                            },
                        )
                        .await;
                        barrier(&mut log, &agent_tx).await;

                        // Kept before `input` is moved into the call: the verification ledger
                        // keys off the path a write was aimed at, and by the time the outcome is
                        // known the arguments are gone.
                        let recorded_input = input.clone();
                        let outcome = if name == "spawn_agent" {
                            handle_spawn_agent(&config_for_subagent, &registry, input).await
                        } else {
                            registry.execute(&name, input).await
                        };
                        let is_error = outcome.is_err();
                        operations
                            .record(&name, outcome.as_ref().map(|_| ()).map_err(|e| e.as_str()));
                        verify::session().record(&name, &recorded_input, !is_error);
                        // The one place the UI can learn a tool's outcome. Sent before the result
                        // is recorded so the trace settles as soon as the work does, rather than
                        // waiting for the turn to end.
                        let _ = agent_tx.send(channels::AgentUpdate::ToolFinished {
                            name: name.clone(),
                            ok: !is_error,
                        });
                        // Clamped before it is recorded, not after: the session log is folded back
                        // into the history on resume, so logging the full result and sending a
                        // clamped one would make a resumed conversation diverge from the live one.
                        let result_str = agent::clamp_tool_result(match outcome {
                            Ok(r) => r,
                            Err(e) => format!("Error: {}", e),
                        });

                        record(
                            &mut log,
                            &agent_tx,
                            session::SessionEvent::ToolResult {
                                id: id.clone(),
                                content: result_str.clone(),
                                is_error,
                            },
                        )
                        .await;
                        results.push((id, result_str));
                    }

                    history.push(agent::Message::tool_results(results));

                    // Pushed first, then stopped: leaving the loop before the results reached the
                    // history would strand the assistant turn holding the `tool_use` blocks.
                    if turn_cancelled {
                        break;
                    }
                }

                drop(text_tx);
                let _ = forwarder.await;

                if turn_cancelled {
                    let _ = agent_tx.send(channels::AgentUpdate::Notice(
                        "Turn interrupted. The conversation is kept, so you can carry on from \
                         here."
                            .to_string(),
                    ));
                }

                record(
                    &mut log,
                    &agent_tx,
                    session::SessionEvent::TurnEnd {
                        reason: if turn_cancelled {
                            session::TurnEnd::Interrupted
                        } else if turn_failed {
                            session::TurnEnd::Failed
                        } else {
                            session::TurnEnd::Complete
                        },
                    },
                )
                .await;
                barrier(&mut log, &agent_tx).await;
                let _ = agent_tx.send(channels::AgentUpdate::ResponseEnd);
            }
            channels::UserCommand::RunTool { name, input, label } => {
                cancel.take();

                // The same `Using tool:` shape the agent's own calls take, so the trace looks the
                // same whether the user or the model started it.
                let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                    "Using tool: {}",
                    name
                )));

                // Through the registry, so the approval gate applies. Deploy is bound to Ctrl+D
                // and signs: a keystroke must not be able to submit without being asked.
                let recorded_input = input.clone();
                let outcome = registry.execute(&name, input).await;
                let ok = outcome.is_ok();
                operations.record(&name, outcome.as_ref().map(|_| ()).map_err(|e| e.as_str()));
                verify::session().record(&name, &recorded_input, ok);
                let _ = agent_tx.send(channels::AgentUpdate::ToolFinished {
                    name: name.clone(),
                    ok,
                });

                let output = match outcome {
                    Ok(text) => text,
                    Err(e) => format!("Error: {}", e),
                };
                let output = agent::clamp_tool_result(output);

                let _ = agent_tx.send(channels::AgentUpdate::Notice(format!(
                    "{}{}\n{}",
                    label,
                    if ok { "done" } else { "failed" },
                    output.trim_end()
                )));
                let _ = agent_tx.send(channels::AgentUpdate::ResponseEnd);

                quick_action_output.push(format!(
                    "[The user ran {} themselves and was shown this output:\n{}\n]",
                    name, output
                ));
            }
            channels::UserCommand::SetExplain(enabled) => {
                explain = enabled;
                // The anchor priced a different request envelope.
                budget.invalidate();
            }
            channels::UserCommand::SwitchModel { provider, model } => {
                let mut new_cfg = cfg.clone();
                new_cfg.provider = provider;
                new_cfg.default_model = model.clone();

                // Asked of the server, not of a built-in list, and only where the server can
                // answer. A switch used to be accepted unchecked, so a typo became the session's
                // model and the first sign of it was a turn that failed.
                if let Some(installed) = llm::installed_models(&new_cfg).await {
                    if !llm::is_installed(&installed, &model) {
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "{} has no model named '{}'. Installed: {}.",
                            provider,
                            model,
                            installed.join(", ")
                        )));
                        let _ = agent_tx.send(channels::AgentUpdate::Ready {
                            provider: cfg.provider.to_string(),
                            model: cfg.default_model.clone(),
                            credential: client.is_some(),
                        });
                        continue;
                    }
                }

                match llm::LlmClient::from_config(&new_cfg) {
                    Ok(new_client) => {
                        client = Some(new_client);
                        cfg.provider = provider;
                        cfg.default_model = model.clone();
                        context_window = budget::context_window(provider, &model);
                        budget.invalidate();
                        // Persisted so the next launch resumes on the provider/model actually in
                        // use, rather than silently reverting to whatever `config.toml` said
                        // before this switch. A failure to write is reported but not fatal: the
                        // live client this session already switched successfully.
                        match cfg.save() {
                            // Said out loud, because it is not a session setting: this rewrites
                            // `default_model` in the one config every directory shares, so a
                            // switch made to try something out silently became the default
                            // everywhere until the user noticed and put it back.
                            Ok(()) => {
                                let _ = agent_tx.send(channels::AgentUpdate::Notice(format!(
                                    "Now on {} / {}, and saved as the default for new sessions in \
                                     every directory.",
                                    provider, model
                                )));
                            }
                            Err(e) => {
                                let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                                    "Switched for this session, but could not save it as the \
                                     default: {}",
                                    e
                                )));
                            }
                        }
                        // Switching to a local provider is the documented way out of a boot with
                        // no credential, so this is what clears `NeedsCredential` in the header.
                        let _ = agent_tx.send(channels::AgentUpdate::Ready {
                            provider: provider.to_string(),
                            model,
                            credential: true,
                        });
                        // Re-asked: the switch may have moved between a local server and a remote
                        // provider, and the old list describes neither.
                        let _ = agent_tx.send(channels::AgentUpdate::LocalModels(
                            llm::installed_models(&cfg).await.unwrap_or_default(),
                        ));
                    }
                    Err(e) => {
                        // The old client is kept: a switch that could not be built must not take
                        // away the one that was working.
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "Failed to switch model: {}",
                            e
                        )));
                        let _ = agent_tx.send(channels::AgentUpdate::Ready {
                            provider: cfg.provider.to_string(),
                            model: cfg.default_model.clone(),
                            credential: client.is_some(),
                        });
                    }
                }
            }
            channels::UserCommand::InstallStellarBuild => {
                // The installer is a shell script; there is no Windows equivalent to run it with,
                // and pretending to try would just fail confusingly deep inside a spawned process.
                if !cfg!(unix) {
                    let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                        "Stellar Build's installer is a shell script and only runs on Unix-like \
                         systems. Install it manually from {}",
                        channels::STELLAR_BUILD_INSTALL_URL
                    )));
                    continue;
                }

                let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                    "Downloading {}",
                    channels::STELLAR_BUILD_INSTALL_URL
                )));

                let script = reqwest::Client::new()
                    .get(channels::STELLAR_BUILD_INSTALL_URL)
                    .send()
                    .await
                    .and_then(|r| r.error_for_status());

                let script = match script {
                    Ok(resp) => resp.text().await,
                    Err(e) => Err(e),
                };

                let script = match script {
                    Ok(s) => s,
                    Err(e) => {
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "Failed to download the Stellar Build installer: {}",
                            e
                        )));
                        continue;
                    }
                };

                let _ = agent_tx.send(channels::AgentUpdate::Status(
                    "Running the Stellar Build installer...".to_string(),
                ));

                match run_shell_script(&script).await {
                    Ok(output) if output.status.success() => {
                        let _ = agent_tx.send(channels::AgentUpdate::Status(
                            "Stellar Build installed. Restart Procyon to pick up the new \
                             personas."
                                .to_string(),
                        ));
                    }
                    Ok(output) => {
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "Stellar Build's installer exited with {}: {}",
                            output.status,
                            String::from_utf8_lossy(&output.stderr).trim()
                        )));
                    }
                    Err(e) => {
                        let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                            "Failed to run the Stellar Build installer: {}",
                            e
                        )));
                    }
                }
            }
            channels::UserCommand::ChangeProject(name) => {
                let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                    "Project changed to: {}",
                    name
                )));
            }
            channels::UserCommand::Quit => break,
        }
    }
}

/// Handles the spawn_agent tool call by running a sub-agent with its own LLM context.
async fn handle_spawn_agent(
    config: &std::sync::Arc<config::AppConfig>,
    registry: &tools::ToolRegistry,
    input: serde_json::Value,
) -> Result<String, String> {
    let system_prompt = input
        .get("system_prompt")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Missing 'system_prompt' field".to_string())?
        .to_string();

    let message = input
        .get("message")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "Missing 'message' field".to_string())?
        .to_string();

    let model = input
        .get("model")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let max_tokens = input
        .get("max_tokens")
        .and_then(|v| v.as_u64())
        .map(|n| n as u32);

    let allowed_tools = input
        .get("allowed_tools")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect::<Vec<_>>()
        });

    let mut cfg = (**config).clone();
    if let Some(m) = model {
        cfg.default_model = m;
    }
    if let Some(t) = max_tokens {
        cfg.max_tokens = t;
    }

    let timeout_secs = input.get("timeout_secs").and_then(|v| v.as_u64());

    let subagent_config = crate::agent::subagent::SubAgentConfig {
        system_prompt,
        message,
        model: None,
        max_tokens: None,
        max_rounds: None,
        allowed_tools,
        timeout_secs,
    };

    let response = crate::agent::subagent::run_subagent(&cfg, subagent_config, registry)
        .await
        .map_err(|e| format!("Sub-agent failed: {}", e))?;

    Ok(format!(
        "[Sub-agent completed in {} round trip(s)]\n\n{}",
        response.round_trips, response.text
    ))
}

// Lifted from the reference harness: a fixed-section checkpoint keeps the summary useful for
// resuming work rather than being a vague recap.
const COMPACT_INSTRUCTION: &str = "\
Summarize the conversation so far as a handoff checkpoint. Use exactly these sections:\n\
1. Primary request and intent\n\
2. Key technical concepts\n\
3. Files and code touched (with paths)\n\
4. Errors encountered and how they were fixed\n\
5. Pending work\n\
6. Current work in progress\n\
7. Next step\n\
8. Critical context worth carrying forward\n\
\n\
Be specific: keep file paths, contract ids, network names, addresses and error text verbatim. \
If the conversation already contains a <compacted-summary> block, merge it into your output \
rather than nesting it.";

const CHECKPOINT_PREAMBLE: &str =
    "This conversation was compacted to fit the context window. Earlier turns are replaced by \
     the checkpoint below.";

// Every provider words an overflow differently and none of them give it a machine-readable code,
// so the classifier is a list of their phrasings. Missing one costs the user's turn: the retry
// after compaction is the only thing that saves it.
const OVERFLOW_PHRASES: &[&str] = &[
    "context window",
    "context_length_exceeded",
    "model_context_window_exceeded",
    "prompt is too long",
    "prompt too long",
    "input is too long",
    "maximum context length",
    "maximum prompt length",
    "reduce the length",
    "too many tokens",
    "token limit exceeded",
    "exceeded model token limit",
    "request_too_large",
    "request entity too large",
    "longer than the model's context length",
    "exceeds the available context size",
    "greater than the context length",
];

// A throttle or rate limit can quote a token count too, and compacting in response to one throws
// away history to fix a problem that waiting would have fixed.
const OVERFLOW_EXCLUSIONS: &[&str] = &["rate limit", "too many requests", "service unavailable"];

// Piped to `bash`'s stdin rather than written to a temp file and executed: the installer runs
// exactly once per confirmation, so there is nothing worth leaving on disk afterward.
async fn run_shell_script(script: &str) -> std::io::Result<std::process::Output> {
    use tokio::io::AsyncWriteExt;

    let mut child = tokio::process::Command::new("bash")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(script.as_bytes()).await?;
    }

    child.wait_with_output().await
}

fn is_context_overflow(error: &color_eyre::Report) -> bool {
    let text = error.to_string().to_lowercase();

    if OVERFLOW_EXCLUSIONS
        .iter()
        .any(|phrase| text.contains(phrase))
    {
        return false;
    }

    OVERFLOW_PHRASES.iter().any(|phrase| text.contains(phrase))
}

/// Renders a slice of the conversation as plain text for the summarizer to read.
///
/// The compaction request used to be the messages themselves, sent with the full tool block. Two
/// things went wrong with that. A model handed tools answers with a tool call, and a small one
/// reliably does: the reply came back with a `tool_use` and no text, so the summary was empty and
/// compaction gave up — on a history it was called to shrink. And the tool block is thousands of
/// tokens, spent on the one request made precisely because the window is too tight.
///
/// Flattened, the request carries no tools at all — there is nothing to call and nothing to
/// validate against, on either wire format — and it is a fraction of the size.
fn transcript_for_summary(history: &[agent::Message]) -> String {
    let mut out = String::new();

    for message in history {
        for part in &message.content {
            match part {
                agent::ContentPart::Text { text } if !text.trim().is_empty() => {
                    out.push_str(&format!("{}: {}\n\n", message.role, text.trim()));
                }
                // Kept, not dropped: which tools ran and what they returned is most of what a
                // handoff checkpoint is for.
                agent::ContentPart::ToolUse { name, input, .. } => {
                    out.push_str(&format!("tool call: {}({})\n\n", name, input));
                }
                agent::ContentPart::ToolResult { content, .. } => {
                    out.push_str(&format!("tool result: {}\n\n", content.trim()));
                }
                agent::ContentPart::Text { .. } => {}
            }
        }
    }

    out
}

fn frame_summary(summary: &str) -> agent::Message {
    agent::Message::user(&format!(
        "{}\n\n<compacted-summary>\n{}\n</compacted-summary>",
        CHECKPOINT_PREAMBLE, summary
    ))
}

// Replaces the head of the history with an LLM checkpoint, keeping `retain` tokens of the newest
// turns verbatim. Reports through the chat instead of returning an error: failing to compact is
// not a reason to lose the user's turn.
//
// Returns whether the history actually got smaller. Every caller needs that answer: retrying a
// request against a history that did not change reissues the request that just failed, and
// re-attempting compaction on the next round trip pays for another summary that will not help
// either. Both used to happen because the outcome was not reported at all.
async fn compact(
    client: &llm::LlmClient,
    history: &mut Vec<agent::Message>,
    budget: &mut budget::Budget,
    retain: usize,
    agent_tx: &mpsc::UnboundedSender<channels::AgentUpdate>,
    log: &mut Option<session::SessionLog>,
) -> bool {
    let cut = match budget::select_cut(history, retain) {
        budget::CutChoice::Compact(cut) => cut,
        budget::CutChoice::NothingToCompact => return false,
        budget::CutChoice::NoSafeCut => {
            let _ = agent_tx.send(channels::AgentUpdate::Status(
                "Cannot compact: no cut point leaves every tool call paired.".to_string(),
            ));
            return false;
        }
    };

    let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
        "Compacting {} of {} messages to fit the context window.",
        cut,
        history.len()
    )));

    let shadowed_tokens = budget::price_history(&history[..cut]);

    let request = vec![agent::Message::user(&format!(
        "{}\n\n---\n\n{}",
        transcript_for_summary(&history[..cut]),
        COMPACT_INSTRUCTION
    ))];

    // No tools and no system prompt: this is a summarization, not a turn. Both were being sent,
    // and both are large — on the one request made because the window is already too tight.
    let blocks = match client.send_message(&request, None, None).await {
        Ok(blocks) => blocks,
        Err(e) => {
            // A notice, not an error: the turn goes on without the compaction, so calling this a
            // failure marked the whole execution trace failed for something it recovered from.
            let _ = agent_tx.send(channels::AgentUpdate::Notice(format!(
                "Could not compact the history, so this turn runs on it unchanged: {}",
                e
            )));
            return false;
        }
    };

    let summary: String = blocks
        .iter()
        .filter_map(|block| match block {
            agent::ContentPart::Text { text } => Some(text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n");

    if summary.trim().is_empty() {
        let _ = agent_tx.send(channels::AgentUpdate::Notice(
            "The model returned no summary, so the history is unchanged and this turn runs on it \
             as it is."
                .to_string(),
        ));
        return false;
    }

    let framed = frame_summary(&summary);
    // A summary no smaller than what it replaces would leave the next turn just as full.
    if budget::price_message(&framed) >= shadowed_tokens {
        let _ = agent_tx.send(channels::AgentUpdate::Notice(
            "The summary came back no smaller than what it would replace, so the history is \
             unchanged."
                .to_string(),
        ));
        return false;
    }

    // Recorded before the splice so the log and the live history describe the same replacement.
    // `checkpoint` is the framed text, so folding the log rebuilds this exact message.
    let checkpoint = match &framed.content.first() {
        Some(agent::ContentPart::Text { text }) => text.clone(),
        _ => summary.clone(),
    };
    record(
        log,
        agent_tx,
        session::SessionEvent::Compacted {
            checkpoint,
            replaced: cut,
        },
    )
    .await;

    history.splice(0..cut, std::iter::once(framed));
    // The anchor priced a prefix that no longer exists.
    budget.invalidate();

    let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
        "Compacted to {} messages.",
        history.len()
    )));
    true
}

// Persistence must never cost the user a turn: a log failure is reported and the conversation
// continues without it.
async fn record(
    log: &mut Option<session::SessionLog>,
    agent_tx: &mpsc::UnboundedSender<channels::AgentUpdate>,
    event: session::SessionEvent,
) {
    if let Some(log) = log.as_mut() {
        if let Err(e) = log.append(event).await {
            let _ = agent_tx.send(channels::AgentUpdate::Error(format!("Session log: {}", e)));
        }
    }
}

// Durability barrier, placed before anything whose effect outlives the process: the model request
// and each tool that may act on the world.
async fn barrier(
    log: &mut Option<session::SessionLog>,
    agent_tx: &mpsc::UnboundedSender<channels::AgentUpdate>,
) {
    if let Some(log) = log.as_mut() {
        if let Err(e) = log.flush().await {
            let _ = agent_tx.send(channels::AgentUpdate::Error(format!("Session log: {}", e)));
        }
    }
}

/// The installed skills, by name, for the workspace prompt.
///
/// Read through the process-wide registry, so this is the same list `list_skills` and `run_skill`
/// resolve against — a prompt that advertised a skill those two could not find would be worse than
/// saying nothing.
async fn skill_names() -> Vec<String> {
    registries::skills()
        .await
        .all()
        .iter()
        .map(|skill| skill.name.clone())
        .collect()
}

// The explain instruction is appended rather than replacing the workspace prompt, so toggling it
// keeps the environment description the model relies on.
fn build_system_prompt(workspace: Option<&str>, explain: bool) -> Option<String> {
    match (workspace, explain) {
        (None, false) => None,
        (None, true) => Some(agent::EXPLAIN_SYSTEM_PROMPT.to_string()),
        (Some(base), false) => Some(base.to_string()),
        (Some(base), true) => Some(format!("{}\n\n{}", base, agent::EXPLAIN_SYSTEM_PROMPT)),
    }
}

#[cfg(test)]
mod tests {
    use super::build_system_prompt;
    use crate::runtime::tools_for_provider;

    use super::{parse_args, Startup};
    use crate::agent;
    use crate::config;

    fn args(list: &[&str]) -> Startup {
        parse_args(list.iter().map(|s| s.to_string()))
    }

    #[test]
    fn no_arguments_starts_a_new_session() {
        assert!(matches!(args(&[]), Startup::New));
    }

    // --- compaction ---------------------------------------------------------------------------

    #[test]
    fn the_summary_request_keeps_what_a_handoff_needs() {
        let history = vec![
            agent::Message::user("deploy the counter"),
            agent::Message::assistant(vec![
                agent::ContentPart::Text {
                    text: "Deploying now.".to_string(),
                },
                agent::ContentPart::ToolUse {
                    id: "t1".to_string(),
                    name: "caatinga_deploy".to_string(),
                    input: serde_json::json!({"network": "testnet"}),
                },
            ]),
            agent::Message::tool_results(vec![("t1".to_string(), "contract CDLZ".to_string())]),
        ];

        let text = super::transcript_for_summary(&history);

        assert!(text.contains("deploy the counter"));
        assert!(text.contains("Deploying now."));
        // Which tools ran and what they returned is most of what a checkpoint is for, so
        // flattening must not be the same as dropping.
        assert!(text.contains("caatinga_deploy"), "got {}", text);
        assert!(text.contains("testnet"), "got {}", text);
        assert!(text.contains("CDLZ"), "got {}", text);
    }

    #[test]
    fn the_summary_request_says_who_said_what() {
        let history = vec![
            agent::Message::user("oi"),
            agent::Message::assistant(vec![agent::ContentPart::Text {
                text: "ola".to_string(),
            }]),
        ];

        let text = super::transcript_for_summary(&history);
        // A transcript with the turns run together reads as one voice, and the summary inherits
        // that confusion.
        assert!(text.contains("user: oi"), "got {}", text);
        assert!(text.contains("assistant: ola"), "got {}", text);
    }

    #[test]
    fn empty_text_blocks_do_not_become_empty_turns() {
        let history = vec![agent::Message::assistant(vec![agent::ContentPart::Text {
            text: "   \n ".to_string(),
        }])];
        assert!(super::transcript_for_summary(&history).is_empty());
    }

    // --- interrupting a turn ---------------------------------------------------------------

    #[test]
    fn an_interrupted_reply_keeps_what_was_already_said() {
        let text = super::interrupted_text("A Stellar é uma rede");
        assert!(text.starts_with("A Stellar é uma rede"));
        // The model reads this back next turn; unmarked, a sentence cut mid-word looks like a
        // thought it chose to stop, and it will try to finish it.
        assert!(text.contains("interrupted"));
    }

    #[test]
    fn an_interrupt_before_any_text_still_produces_a_block() {
        // An assistant turn has to follow the user turn already in the history, so this can never
        // be empty.
        assert!(!super::interrupted_text("").is_empty());
        assert!(!super::interrupted_text("   \n").is_empty());
    }

    #[test]
    fn taking_the_cancel_flag_clears_it() {
        let flag = crate::channels::CancelFlag::default();
        assert!(!flag.take());

        flag.raise();
        assert!(flag.is_raised());
        assert!(flag.take(), "take reports the raise it consumed");
        assert!(
            !flag.is_raised(),
            "a flag left raised would cancel the following turn on arrival"
        );
    }

    #[test]
    fn a_cancel_flag_is_shared_by_its_clones() {
        // The UI raises its clone; the agent reads its own. Copies that did not share would make
        // Esc a no-op that looks wired up.
        let ui = crate::channels::CancelFlag::default();
        let agent = ui.clone();

        ui.raise();
        assert!(agent.is_raised());
    }

    // --- workspace snapshot ----------------------------------------------------------------

    fn snapshot_context(
        project: Option<crate::project::Project>,
    ) -> crate::context::WorkspaceContext {
        crate::context::WorkspaceContext {
            cwd: std::path::PathBuf::from("/w/demo"),
            project,
            accounts: Vec::new(),
            stellar_cli: None,
            npx: false,
            mcp_servers: Vec::new(),
            skills: Vec::new(),
            operations: Vec::new(),
            unverified: Vec::new(),
            caatinga_config: false,
        }
    }

    fn snapshot_config(default_network: &str) -> config::AppConfig {
        config::AppConfig {
            default_network: default_network.to_string(),
            ..config::AppConfig::default()
        }
    }

    #[test]
    fn a_discovered_project_reaches_the_status_line() {
        let mut project = crate::project::Project::new("my-app");
        project.source = crate::project::ProjectSource::Inferred;
        project.contracts.push(crate::project::Contract {
            name: "counter".to_string(),
            address: None,
            wasm_path: None,
        });

        let snap = super::workspace_snapshot(
            &snapshot_context(Some(project)),
            &snapshot_config("testnet"),
            &[],
        );
        assert_eq!(snap.project_name, "my-app");
        assert_eq!(snap.contract_name.as_deref(), Some("counter"));
    }

    #[test]
    fn an_inferred_project_does_not_override_the_configured_network() {
        let project = crate::project::Project {
            source: crate::project::ProjectSource::Inferred,
            ..crate::project::Project::new("my-app")
        };

        // Inference always says testnet because the filesystem does not record a network. Letting
        // that win would move a user configured for `local` without them touching anything.
        let snap = super::workspace_snapshot(
            &snapshot_context(Some(project)),
            &snapshot_config("local"),
            &[],
        );
        assert_eq!(snap.network, "local");
    }

    #[test]
    fn a_configured_project_still_sets_the_network() {
        let project = crate::project::Project {
            default_network: crate::project::Network::Mainnet,
            ..crate::project::Project::new("my-app")
        };

        let snap = super::workspace_snapshot(
            &snapshot_context(Some(project)),
            &snapshot_config("local"),
            &[],
        );
        assert_eq!(snap.network, "mainnet");
    }

    #[test]
    fn no_project_falls_back_to_the_config() {
        let snap =
            super::workspace_snapshot(&snapshot_context(None), &snapshot_config("local"), &[]);
        assert_eq!(snap.project_name, "No project");
        assert!(snap.contract_name.is_none());
        assert_eq!(snap.network, "local");
    }

    #[test]
    fn resume_without_an_id_means_the_latest() {
        assert!(matches!(args(&["--resume"]), Startup::Resume(None)));
    }

    #[test]
    fn resume_with_an_id_targets_that_session() {
        match args(&["--resume", "20260821T120000-42"]) {
            Startup::Resume(Some(id)) => assert_eq!(id, "20260821T120000-42"),
            _ => panic!("expected a targeted resume"),
        }
    }

    #[test]
    fn authorize_takes_a_server_name() {
        match args(&["--authorize", "raven"]) {
            Startup::Authorize(Some(name)) => assert_eq!(name, "raven"),
            other => panic!("expected an authorize request, got {:?}", other),
        }
        assert!(matches!(args(&["--authorize"]), Startup::Authorize(None)));
    }

    #[test]
    fn exec_takes_a_prompt_and_defaults_to_changing_nothing() {
        match args(&["--exec", "what network am I on?"]) {
            Startup::Exec {
                prompt,
                allow_changes,
            } => {
                assert_eq!(prompt, "what network am I on?");
                assert!(
                    !allow_changes,
                    "an unattended run must not write by default"
                );
            }
            other => panic!("expected an exec request, got {:?}", other),
        }
    }

    // Both orders, because both get typed — and reading `--allow-changes` as the prompt would run
    // the flag as a question while refusing every write it asked for.
    #[test]
    fn exec_accepts_the_flag_on_either_side_of_the_prompt() {
        for argv in [
            &["--exec", "deploy the counter", "--allow-changes"],
            &["--exec", "--allow-changes", "deploy the counter"],
        ] {
            match args(argv) {
                Startup::Exec {
                    prompt,
                    allow_changes,
                } => {
                    assert_eq!(prompt, "deploy the counter", "{:?}", argv);
                    assert!(allow_changes, "{:?}", argv);
                }
                other => panic!("expected an exec request, got {:?}", other),
            }
        }
    }

    #[test]
    fn exec_without_a_prompt_is_a_usage_error_rather_than_an_empty_turn() {
        assert!(matches!(args(&["--exec"]), Startup::ShowUsage));
        assert!(matches!(args(&["--exec", "   "]), Startup::ShowUsage));
        assert!(matches!(
            args(&["--exec", "--allow-changes"]),
            Startup::ShowUsage
        ));
    }

    #[test]
    fn sessions_and_help_are_recognised() {
        assert!(matches!(args(&["--sessions"]), Startup::ListSessions));
        assert!(matches!(args(&["--help"]), Startup::ShowUsage));
        assert!(matches!(args(&["-h"]), Startup::ShowUsage));
    }

    #[test]
    fn an_unknown_flag_shows_usage_rather_than_starting() {
        assert!(matches!(args(&["--wat"]), Startup::ShowUsage));
    }

    #[test]
    fn workspace_context_is_sent_even_with_explain_off() {
        let prompt = build_system_prompt(Some("WORKSPACE"), false).unwrap();
        assert_eq!(prompt, "WORKSPACE");
    }

    #[test]
    fn explain_is_appended_without_dropping_the_workspace() {
        let prompt = build_system_prompt(Some("WORKSPACE"), true).unwrap();
        assert!(prompt.starts_with("WORKSPACE"));
        assert!(prompt.contains(crate::agent::EXPLAIN_SYSTEM_PROMPT));
    }

    #[test]
    fn no_workspace_and_no_explain_sends_no_system_prompt() {
        assert!(build_system_prompt(None, false).is_none());
    }

    fn tool(name: &str) -> agent::ToolDefinition {
        agent::ToolDefinition {
            name: name.to_string(),
            description: String::new(),
            input_schema: serde_json::json!({}),
        }
    }

    #[test]
    fn a_non_ollama_provider_gets_every_tool() {
        let all = vec![tool("grep"), tool("spawn_agent"), tool("party_mode")];
        let kept = tools_for_provider(config::Provider::Anthropic, &all);
        assert_eq!(kept.len(), all.len());
    }

    // Measured at ~4,358 estimated tokens for the full registry — already past the 4,096-token
    // window Ollama enforces regardless of the model loaded, before any conversation at all.
    #[test]
    fn ollama_keeps_only_the_core_edit_build_deploy_tools() {
        let all = vec![
            tool("grep"),
            tool("read_file"),
            tool("caatinga_deploy"),
            tool("spawn_agent"),
            tool("party_mode"),
            tool("talk_to"),
            tool("run_skill"),
        ];
        let kept = tools_for_provider(config::Provider::Ollama, &all);
        let names: Vec<_> = kept.iter().map(|t| t.name.as_str()).collect();
        assert_eq!(names, vec!["grep", "read_file", "caatinga_deploy"]);
    }

    // The narrowing is a budget decision, and a budget decision must not silently remove the tool
    // that decides whether the work was any good. Cut from the list, `run_tests` did not degrade
    // into "not available on this provider" — the model reported that no such tool exists at all.
    #[test]
    fn ollama_keeps_the_test_runner() {
        let kept = tools_for_provider(config::Provider::Ollama, &[tool("run_tests")]);
        assert_eq!(kept.len(), 1, "run_tests must survive the Ollama filter");
    }
}

#[cfg(test)]
mod overflow_tests {
    use super::is_context_overflow;

    fn overflows(message: &str) -> bool {
        is_context_overflow(&color_eyre::eyre::eyre!("{}", message))
    }

    #[test]
    fn recognizes_each_providers_phrasing() {
        // Anthropic
        assert!(overflows(
            "prompt is too long: 210000 tokens > 200000 maximum"
        ));
        // OpenAI and the dialect that copies it
        assert!(overflows(
            "This model's maximum context length is 128000 tokens. Please reduce the length of the messages."
        ));
        assert!(overflows(
            "API error 400: {\"code\":\"context_length_exceeded\"}"
        ));
        // DeepSeek
        assert!(overflows(
            "This model's maximum context length is 65536 tokens"
        ));
        // Local servers
        assert!(overflows(
            "the input (9000 tokens) is longer than the model's context length (8192 tokens)"
        ));
    }

    // Compacting throws history away; doing it because the provider was busy loses the user's
    // context to fix something that waiting would have fixed.
    #[test]
    fn a_rate_limit_is_not_an_overflow() {
        assert!(!overflows(
            "Rate limit reached for 200000 tokens per minute"
        ));
        assert!(!overflows("429 Too Many Requests"));
        assert!(!overflows("Service Unavailable: overloaded"));
    }

    #[test]
    fn an_unrelated_failure_is_not_an_overflow() {
        assert!(!overflows("error sending request: connection refused"));
        assert!(!overflows("API error 401: invalid api key"));
    }
}