procyon 0.1.0

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
mod account;
mod agent;
mod anthropic;
mod app;
mod budget;
mod channels;
mod config;
mod context;
mod credentials;
mod diag;
mod llm;
mod mcp;
mod oauth;
mod openai;
mod party;
mod personas;
mod project;
mod registries;
mod session;
mod skills;
mod sse;
mod tools;
mod ui;
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 --help
";

#[derive(Debug)]
enum Startup {
    New,
    Resume(Option<String>),
    ListSessions,
    Authorize(Option<String>),
    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(_) => 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::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;

    tokio::spawn(async move {
        agent_task(channels.user_rx, agent_tx, cfg, resume_from).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();
            }
        }
    }
}

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>,
) {
    // 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(),
    });

    let mut registry = tools::ToolRegistry::new();
    registry.register(Box::new(tools::search::ListDirTool));
    registry.register(Box::new(tools::search::GlobTool));
    registry.register(Box::new(tools::search::GrepTool));
    registry.register(Box::new(tools::project::ProjectInitTool));
    registry.register(Box::new(tools::project::ProjectInfoTool));
    registry.register(Box::new(tools::caatinga::CaatingaBuildTool));
    registry.register(Box::new(tools::caatinga::CaatingaDeployTool));
    registry.register(Box::new(tools::file::ReadFileTool));
    registry.register(Box::new(tools::file::WriteFileTool));
    registry.register(Box::new(tools::file::EditFileTool));
    registry.register(Box::new(tools::invoke::CaatingaInvokeTool));
    registry.register(Box::new(tools::invoke::CaatingaReadTool));
    registry.register(Box::new(tools::invoke::StellarCliInvokeTool));
    registry.register(Box::new(tools::caatinga::CaatingaDoctorTool));
    registry.register(Box::new(tools::accounts::AccountCreateTool));
    registry.register(Box::new(tools::accounts::AccountListTool));
    registry.register(Box::new(tools::accounts::AccountBalanceTool));
    registry.register(Box::new(tools::test::RunTestsTool));
    registry.register(Box::new(tools::bindings::GenerateBindingsTool));
    registry.register(Box::new(tools::docs::GenerateDocsTool));
    registry.register(Box::new(tools::events::SubscribeEventsTool));
    registry.register(Box::new(tools::events::FilterEventsTool));
    registry.register(Box::new(tools::plugin::ListPluginsTool));
    registry.register(Box::new(tools::update::CheckUpdateTool));
    registry.register(Box::new(tools::skill::RunSkillTool));
    registry.register(Box::new(tools::skill::ListSkillsTool));
    registry.register(Box::new(tools::persona::TalkToTool));
    registry.register(Box::new(tools::persona::ListPersonasTool));
    registry.register(Box::new(tools::party::PartyModeTool));

    // Remote MCP tools are namespaced by server, and registered before plugins so a plugin
    // manifest cannot shadow one either.
    let (mcp_tools, mcp_connected, mcp_problems) = mcp::load_servers(&cfg.mcp_servers).await;
    for tool in mcp_tools {
        if let Err(e) = registry.try_register(tool) {
            let _ = agent_tx.send(channels::AgentUpdate::Status(format!("MCP {}", e)));
        }
    }
    // 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.
    let _ = &mcp_connected;
    for problem in &mcp_problems {
        let _ = agent_tx.send(channels::AgentUpdate::Error(problem.clone()));
    }
    // Structured MCP status for the Context panel (in addition to the trace messages above).
    {
        let statuses: Vec<channels::McpServerStatus> = cfg
            .mcp_servers
            .iter()
            .map(|s| {
                let detail = s.endpoint_label();
                let connected = mcp_connected.iter().any(|line| line.contains(&s.name));
                channels::McpServerStatus {
                    name: s.name.clone(),
                    connected,
                    detail,
                }
            })
            .collect();
        let _ = agent_tx.send(channels::AgentUpdate::McpStatus(statuses));
    }

    // Registered after the builtins so a manifest cannot shadow one of them.
    let (plugin_tools, mut plugin_warnings) = tools::plugin::load_plugin_tools();
    let plugin_count = plugin_tools.len();
    for tool in plugin_tools {
        if let Err(e) = registry.try_register(tool) {
            plugin_warnings.push(format!("Plugin {}", e));
        }
    }
    if plugin_count > 0 {
        let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
            "Loaded {} plugin tool(s)",
            plugin_count - plugin_warnings.len()
        )));
    }
    for warning in plugin_warnings {
        let _ = agent_tx.send(channels::AgentUpdate::Status(warning));
    }

    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((log, messages)) => {
                let _ = agent_tx.send(channels::AgentUpdate::Notice(format!(
                    "Resumed session {} with {} message(s).",
                    log.id(),
                    messages.len()
                )));
                (Some(log), messages)
            }
            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();

    while let Some(cmd) = user_rx.recv().await {
        match cmd {
            channels::UserCommand::SendPrompt(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;
                        // Push structured snapshot for the Context panel — network/account/contract/mcp
                        {
                            let mcp_statuses: Vec<channels::McpServerStatus> = cfg
                                .mcp_servers
                                .iter()
                                .map(|s| {
                                    let detail = s.endpoint_label();
                                    let connected =
                                        mcp_connected.iter().any(|line| line.contains(&s.name));
                                    channels::McpServerStatus {
                                        name: s.name.clone(),
                                        connected,
                                        detail,
                                    }
                                })
                                .collect();
                            let snap = 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())),
                                network: ctx
                                    .project
                                    .as_ref()
                                    .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: mcp_statuses,
                            };
                            let _ = agent_tx.send(channels::AgentUpdate::Workspace(snap));
                        }
                        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>();

                let agent_tx_clone = agent_tx.clone();
                let forwarder = tokio::spawn(async move {
                    while let Some(text) = text_rx.recv().await {
                        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;

                // 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;

                // 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 {
                    let system = build_system_prompt(workspace.as_deref(), explain);
                    let turn_tools = 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,
                            system.as_deref(),
                            &turn_tools,
                            budget::retain_tokens(prompt_window),
                            &agent_tx,
                            &mut log,
                        )
                        .await;
                        compaction_stalled = !shrank;
                    }

                    // 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;
                        let _ = agent_tx.send(channels::AgentUpdate::Status(format!(
                            "Warning: the system prompt and {} tool definitions already exceed \
                             Ollama's context window with nothing left to trim. Ollama truncates \
                             silently rather than erroring, so this response may be based on an \
                             incomplete prompt.",
                            turn_tools.len()
                        )));
                    }

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

                    let outcome = match client
                        .send_message_streaming(
                            &history,
                            Some(&turn_tools),
                            system.as_deref(),
                            &text_tx,
                        )
                        .await
                    {
                        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,
                                    system.as_deref(),
                                    &turn_tools,
                                    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;
                    let blocks = outcome.blocks;

                    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 {
                        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;

                        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();
                        // 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));
                }

                drop(text_tx);
                let _ = forwarder.await;
                record(
                    &mut log,
                    &agent_tx,
                    session::SessionEvent::TurnEnd {
                        reason: 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::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();
                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.
                        if let Err(e) = cfg.save() {
                            let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                                "Switched, but failed to save it to config.toml: {}",
                                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,
                        });
                    }
                    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))
}

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.
#[allow(clippy::too_many_arguments)]
async fn compact(
    client: &llm::LlmClient,
    history: &mut Vec<agent::Message>,
    budget: &mut budget::Budget,
    system: Option<&str>,
    tool_defs: &[agent::ToolDefinition],
    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 mut request = history[..cut].to_vec();
    request.push(agent::Message::user(COMPACT_INSTRUCTION));

    let blocks = match client.send_message(&request, Some(tool_defs), system).await {
        Ok(blocks) => blocks,
        Err(e) => {
            let _ = agent_tx.send(channels::AgentUpdate::Error(format!(
                "Compaction failed: {}",
                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::Error(
            "Compaction produced no summary; history left unchanged.".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::Error(
            "Compaction did not shrink the history; left 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 full registry's schemas alone were measured at ~4,358 estimated tokens for 30 tools —
// already past Ollama's 4,096-token ceiling (see `budget::context_window`) before a single
// message of conversation. This is the subset that keeps the core edit-build-deploy loop usable
// within that window; everything cut here (personas, party mode, spawn_agent, skills) is still
// reachable by switching to a provider with real headroom.
const OLLAMA_CORE_TOOLS: &[&str] = &[
    "list_dir",
    "glob",
    "grep",
    "project_init",
    "project_info",
    "read_file",
    "write_file",
    "edit_file",
    "caatinga_build",
    "caatinga_deploy",
    "caatinga_invoke",
    "caatinga_read",
    "caatinga_doctor",
    "stellar_invoke",
];

/// The tool definitions to actually offer this turn.
///
/// Computed per turn rather than once at boot: a live `/model provider ollama` switch has to
/// shrink what gets sent on the very next request, not only on a session that started that way.
fn tools_for_provider(
    provider: config::Provider,
    tools: &[agent::ToolDefinition],
) -> Vec<agent::ToolDefinition> {
    if provider != config::Provider::Ollama {
        return tools.to_vec();
    }
    tools
        .iter()
        .filter(|t| OLLAMA_CORE_TOOLS.contains(&t.name.as_str()))
        .cloned()
        .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 super::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));
    }

    #[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 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"]);
    }
}

#[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"));
    }
}