sofos 0.2.2

An interactive AI coding agent for your terminal
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
pub mod conversation;
mod request_builder;
mod response_handler;
pub mod tui;

pub use conversation::ConversationHistory;
pub use request_builder::RequestBuilder;
pub use response_handler::ResponseHandler;

use std::io::IsTerminal;

use crate::api::LlmClient::Anthropic;
use crate::api::{CreateMessageRequest, ImageSource, LlmClient, MessageContentBlock, MorphClient};
use crate::config::{ModelConfig, NORMAL_MODE_MESSAGE, SAFE_MODE_MESSAGE};
use crate::error::{Result, SofosError};
use crate::mcp::McpManager;
use crate::session::{DisplayMessage, HistoryManager, SessionMetadata, SessionState};
use crate::tools::ToolExecutor;
use crate::tools::image::{ImageLoader, ImageReference, extract_image_references};
use crate::ui::{UI, set_safe_mode_cursor_style};
use colored::Colorize;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;

/// Shared buffer used by the TUI to inject user messages mid-turn. The UI
/// thread pushes text onto this vec when the worker is busy; the tool loop
/// in [`ResponseHandler`] drains it between tool-call iterations and merges
/// the accumulated text into the user turn that carries the tool results.
pub type SteerQueue = Arc<Mutex<Vec<String>>>;

pub struct ReplConfig {
    pub model: String,
    pub max_tokens: u32,
    pub enable_thinking: bool,
    pub thinking_budget: u32,
    pub safe_mode: bool,
}

impl ReplConfig {
    pub fn new(
        model: String,
        max_tokens: u32,
        enable_thinking: bool,
        thinking_budget: u32,
        safe_mode: bool,
    ) -> Self {
        Self {
            model,
            max_tokens,
            enable_thinking,
            thinking_budget,
            safe_mode,
        }
    }
}

pub struct Repl {
    client: LlmClient,
    tool_executor: ToolExecutor,
    history_manager: HistoryManager,
    image_loader: ImageLoader,
    ui: UI,
    model_config: ModelConfig,
    session_state: SessionState,
    safe_mode: bool,
    available_tools: Vec<crate::api::Tool>,
    /// Interrupt flag shared with the TUI. Set to `true` when the user presses
    /// ESC/Ctrl+C during an AI turn; checked by the API request loop.
    interrupt_flag: Arc<AtomicBool>,
    /// Shared buffer of pending steering messages the user typed while a
    /// turn was already running. Drained by the tool loop between
    /// iterations so the user can redirect in-flight work without having
    /// to interrupt it.
    steer_queue: SteerQueue,
    /// Text the TUI should print through its captured-stdout pipe right
    /// after `OutputCapture` is installed. Collected in `main.rs` (logo,
    /// workspace, model, reasoning/thinking, morph availability) so the
    /// same lines that used to go to the real tty before the TUI took
    /// over now flow through the history pipeline — keeping the viewport
    /// from overwriting them on terminals whose cursor-position DSR
    /// doesn't answer (e.g. Ghostty), where our fallback was `(0, 0)`.
    startup_banner: String,
    /// Shared tokio runtime driving every `block_on` in the REPL
    /// (initial request, compaction summary, tool-list refresh). Built
    /// once in [`Self::new`] and reused for the lifetime of the `Repl`.
    /// Previously each call site constructed a fresh
    /// `Runtime::new()` and dropped it on return — expensive per-turn
    /// (thread-pool spin-up + epoll registration) and fd-exhaustion-
    /// prone under sustained load. Works because the TUI worker runs
    /// on a plain `std::thread` (see `tui/worker.rs`), so the REPL's
    /// owned runtime is the only tokio context on that thread.
    runtime: tokio::runtime::Runtime,
}

impl Repl {
    pub fn new(
        client: LlmClient,
        config: ReplConfig,
        workspace: PathBuf,
        morph_client: Option<MorphClient>,
    ) -> Result<Self> {
        // One runtime for the whole REPL lifetime — reused by every
        // in-REPL `block_on` below (initial request, tool-list refresh,
        // compaction summary). See the `runtime` field doc on `Repl`.
        let runtime = tokio::runtime::Runtime::new()
            .map_err(|e| SofosError::Config(format!("Failed to create async runtime: {}", e)))?;

        let mcp_manager = runtime.block_on(async {
            match McpManager::new(workspace.clone()).await {
                Ok(manager) => Some(manager),
                Err(e) => {
                    eprintln!("Warning: Failed to initialize MCP manager: {}", e);
                    None
                }
            }
        });

        let tool_executor = ToolExecutor::new(
            workspace.clone(),
            morph_client,
            mcp_manager,
            config.safe_mode,
            std::io::stdin().is_terminal(),
        )?;

        let has_morph = tool_executor.has_morph();
        let has_code_search = tool_executor.has_code_search();

        let history_manager = HistoryManager::new(workspace.clone())?;
        let image_loader = ImageLoader::new(workspace.clone())?;

        // Load custom instructions
        let custom_instructions = history_manager.load_custom_instructions()?;

        if custom_instructions.is_some() {
            eprintln!("{}", "Loaded custom instructions".bright_green());
        }

        // Validate thinking budget
        if config.enable_thinking && config.thinking_budget >= config.max_tokens {
            return Err(SofosError::Config(format!(
                "thinking_budget ({}) must be less than max_tokens ({})",
                config.thinking_budget, config.max_tokens
            )));
        }

        let mut conversation =
            ConversationHistory::with_features(has_morph, has_code_search, custom_instructions);

        if config.safe_mode {
            conversation.add_user_message(SAFE_MODE_MESSAGE.to_string());
            set_safe_mode_cursor_style()?;
        }

        let session_id = HistoryManager::generate_session_id();
        let session_state = SessionState::new(session_id, conversation);
        let model_config = ModelConfig::new(
            config.model,
            config.max_tokens,
            config.enable_thinking,
            config.thinking_budget,
        );

        let ui = UI::new();

        // Initialize available tools (needs async) — uses the runtime
        // before it's moved into the struct so the async block can
        // borrow `tool_executor` without conflicting with the struct's
        // own borrow rules.
        let available_tools = runtime.block_on(async { tool_executor.get_available_tools().await });

        Ok(Self {
            client,
            tool_executor,
            history_manager,
            image_loader,
            ui,
            model_config,
            session_state,
            safe_mode: config.safe_mode,
            available_tools,
            interrupt_flag: Arc::new(AtomicBool::new(false)),
            steer_queue: Arc::new(Mutex::new(Vec::new())),
            startup_banner: String::new(),
            runtime,
        })
    }

    pub fn run(self) -> Result<()> {
        tui::run(self)
    }

    /// Hand the TUI the logo + workspace/model/morph lines that `main.rs`
    /// used to `println!` straight to stdout. The TUI replays them through
    /// its capture pipe after the alternate-output redirection is live so
    /// they land above the viewport instead of being overdrawn by it.
    pub fn set_startup_banner(&mut self, text: String) {
        self.startup_banner = text;
    }

    pub(crate) fn take_startup_banner(&mut self) -> String {
        std::mem::take(&mut self.startup_banner)
    }

    /// Install the interrupt flag used by the TUI to signal ESC/Ctrl+C during
    /// an AI turn. Called once before the worker thread takes ownership.
    pub fn install_interrupt_flag(&mut self, flag: Arc<AtomicBool>) {
        self.interrupt_flag = flag;
    }

    /// Install the shared steer queue used by the TUI to inject mid-turn
    /// user messages. Called once before the worker thread takes ownership
    /// so UI and worker share the same buffer.
    pub fn install_steer_queue(&mut self, queue: SteerQueue) {
        self.steer_queue = queue;
    }

    pub fn model_label(&self) -> String {
        self.model_config.model.clone()
    }

    pub fn list_saved_sessions(&self) -> Result<Vec<SessionMetadata>> {
        self.history_manager.list_sessions()
    }

    /// Snapshot of the user-facing state displayed in the TUI status line.
    pub fn status_snapshot(&self) -> tui::event::StatusSnapshot {
        let reasoning = if matches!(self.client, Anthropic(_)) {
            if self.model_config.enable_thinking {
                format!("thinking: {} tok", self.model_config.thinking_budget)
            } else {
                "thinking: off".to_string()
            }
        } else if self.model_config.enable_thinking {
            "effort: high".to_string()
        } else {
            "effort: low".to_string()
        };

        tui::event::StatusSnapshot {
            model: self.model_config.model.clone(),
            mode: if self.safe_mode {
                tui::event::Mode::Safe
            } else {
                tui::event::Mode::Normal
            },
            reasoning,
            input_tokens: self.session_state.total_input_tokens,
            output_tokens: self.session_state.total_output_tokens,
        }
    }

    pub fn process_message(
        &mut self,
        user_input: &str,
        pasted_images: Vec<crate::clipboard::PastedImage>,
    ) -> Result<()> {
        let (remaining_text, image_refs) = extract_image_references(user_input);

        let has_images = !image_refs.is_empty() || !pasted_images.is_empty();

        if !image_refs.is_empty() {
            println!(
                "{} Detected {} image reference(s)",
                "🔍".bright_cyan(),
                image_refs.len()
            );
        }

        let content_blocks = if has_images {
            let mut blocks: Vec<MessageContentBlock> = Vec::new();

            for pasted in &pasted_images {
                blocks.push(MessageContentBlock::Image {
                    source: ImageSource::Base64 {
                        media_type: pasted.media_type.clone(),
                        data: pasted.base64_data.clone(),
                    },
                    cache_control: None,
                });
            }
            let mut failed_images: Vec<String> = Vec::new();

            // Load images first (Claude recommends images before text)
            for img_ref in &image_refs {
                match self.image_loader.load_image(img_ref) {
                    Ok(source) => {
                        let api_source = match source {
                            crate::tools::image::ImageSource::Base64 { media_type, data } => {
                                ImageSource::Base64 { media_type, data }
                            }
                            crate::tools::image::ImageSource::Url { url } => {
                                ImageSource::Url { url }
                            }
                        };
                        blocks.push(MessageContentBlock::Image {
                            source: api_source,
                            cache_control: None,
                        });

                        let path_str = match img_ref {
                            ImageReference::LocalPath(p) => format!("local: {}", p),
                            ImageReference::WebUrl(u) => format!("url: {}", u),
                        };
                        println!("{} {}", "📷 Image loaded:".bright_cyan(), path_str.dimmed());
                    }
                    Err(e) => {
                        let path_str = match img_ref {
                            ImageReference::LocalPath(p) => p.clone(),
                            ImageReference::WebUrl(u) => u.clone(),
                        };
                        let error_msg = format!("[Failed to load image '{}': {}]", path_str, e);
                        failed_images.push(error_msg);
                        println!(
                            "\n{} {}\n",
                            "⚠️  Failed to load image:".bright_yellow().bold(),
                            e
                        );
                    }
                }
            }

            let mut text_parts: Vec<String> = Vec::new();

            if !remaining_text.trim().is_empty() {
                text_parts.push(remaining_text.clone());
            }

            if !failed_images.is_empty() {
                text_parts.extend(failed_images);
            }

            if !text_parts.is_empty() {
                blocks.push(MessageContentBlock::Text {
                    text: text_parts.join("\n\n"),
                    cache_control: None,
                });
            } else if blocks.is_empty() {
                return Err(SofosError::ToolExecution(
                    "No valid images or text in message".to_string(),
                ));
            }

            Some(blocks)
        } else {
            None
        };

        if let Some(blocks) = content_blocks {
            self.session_state.conversation.add_user_with_blocks(blocks);
        } else {
            self.session_state
                .conversation
                .add_user_message(user_input.to_string());
        }

        self.session_state
            .display_messages
            .push(DisplayMessage::UserMessage {
                content: user_input.to_string(),
            });

        if self.session_state.conversation.needs_compaction() {
            let _ = self.compact_conversation(false);
        }

        let initial_request = self.build_initial_request();

        let runtime = &self.runtime;

        let use_streaming = false;
        let client_for_retry = self.client.clone();

        let response_result: Result<_> = if use_streaming {
            let printer = Arc::new(crate::ui::StreamPrinter::new());
            let p_text = printer.clone();
            let p_think = printer.clone();
            let interrupt = Arc::clone(&self.interrupt_flag);

            let client = self.client.clone();
            let req = initial_request;
            let result = runtime.block_on(async move {
                client
                    .create_message_streaming(
                        req,
                        move |t| p_text.on_text_delta(t),
                        move |t| p_think.on_thinking_delta(t),
                        interrupt,
                    )
                    .await
            });

            printer.finish();
            result
        } else {
            let interrupt_flag = Arc::clone(&self.interrupt_flag);
            let client = self.client.clone();
            let req = initial_request;
            let mut request_handle = runtime.spawn(async move { client.create_message(req).await });

            let result = runtime.block_on(async {
                tokio::select! {
                    res = &mut request_handle => {
                        match res {
                            Ok(inner) => inner,
                            Err(e) => Err(SofosError::Join(format!("{}", e)))
                        }
                    }
                    _ = Self::wait_for_interrupt(Arc::clone(&interrupt_flag)) => {
                        request_handle.abort();
                        Err(SofosError::Interrupted)
                    }
                }
            });

            if self.interrupt_flag.load(Ordering::Relaxed) {
                self.handle_initial_interrupt();
                return Ok(());
            }

            result
        };

        // Handle API errors, especially those related to invalid images
        let response = match response_result {
            Ok(resp) => resp,
            Err(e) => {
                // Check if this is an image-related API error
                if let SofosError::Api(ref msg) = e {
                    let is_400_error = msg.contains("400");
                    let is_image_error = msg.contains("Unable to download")
                        || msg.contains("invalid_request_error")
                        || msg.contains("verify the URL");

                    // Check if current message OR conversation has images
                    let current_has_images = !image_refs.is_empty();
                    let conversation_has_images = self
                        .session_state
                        .conversation
                        .messages()
                        .iter()
                        .any(|msg| {
                            use crate::api::{MessageContent, MessageContentBlock};
                            if let MessageContent::Blocks { content } = &msg.content {
                                content
                                    .iter()
                                    .any(|block| matches!(block, MessageContentBlock::Image { .. }))
                            } else {
                                false
                            }
                        });

                    let has_images = current_has_images || conversation_has_images;

                    if is_400_error && is_image_error && has_images {
                        println!(
                            "\n{} One or more image URLs in the conversation could not be loaded by the API\n",
                            "⚠️  Image loading error:".bright_yellow().bold()
                        );

                        // Backup conversation before mutating, in case the retry also fails
                        let conversation_backup =
                            self.session_state.conversation.messages().to_vec();

                        self.session_state.conversation.remove_last_message();

                        // Remove ALL images from conversation
                        let messages = self.session_state.conversation.messages();
                        let mut cleaned_messages = Vec::new();

                        for msg in messages {
                            use crate::api::{Message, MessageContent, MessageContentBlock};
                            let cleaned_msg = match &msg.content {
                                MessageContent::Blocks { content } => {
                                    let filtered_blocks: Vec<MessageContentBlock> = content
                                        .iter()
                                        .filter(|block| {
                                            !matches!(block, MessageContentBlock::Image { .. })
                                        })
                                        .cloned()
                                        .collect();

                                    if filtered_blocks.is_empty() {
                                        continue;
                                    } else {
                                        Message {
                                            role: msg.role.clone(),
                                            content: MessageContent::Blocks {
                                                content: filtered_blocks,
                                            },
                                        }
                                    }
                                }
                                _ => msg.clone(),
                            };
                            cleaned_messages.push(cleaned_msg);
                        }

                        self.session_state.conversation.clear();
                        self.session_state
                            .conversation
                            .restore_messages(cleaned_messages);

                        let error_message = if !image_refs.is_empty() {
                            "[SYSTEM ERROR: Image URLs in your message could not be loaded and have been removed from the conversation.]"
                        } else {
                            "[SYSTEM ERROR: Image URLs from a previous message could not be loaded and have been removed from the conversation. You can continue normally.]"
                        }.to_string();

                        self.session_state
                            .conversation
                            .add_user_message(error_message);
                        let new_request = self.build_initial_request();

                        println!("{}", "Retrying request without images...".dimmed());
                        println!();

                        match runtime
                            .block_on(async { client_for_retry.create_message(new_request).await })
                        {
                            Ok(resp) => resp,
                            Err(retry_err) => {
                                // Restore original conversation on retry failure
                                self.session_state.conversation.clear();
                                self.session_state
                                    .conversation
                                    .restore_messages(conversation_backup);
                                // Add error context instead of removing user message
                                self.session_state
                                    .conversation
                                    .add_assistant_with_blocks(vec![
                                        crate::api::MessageContentBlock::Text {
                                            text: format!(
                                                "[Image loading failed and retry also failed: {}. \
                                             Your message is preserved above.]",
                                                retry_err
                                            ),
                                            cache_control: None,
                                        },
                                    ]);
                                return Err(retry_err);
                            }
                        }
                    } else {
                        // Add error context so the AI knows what happened on next turn
                        self.session_state
                            .conversation
                            .add_assistant_with_blocks(vec![
                                crate::api::MessageContentBlock::Text {
                                    text: format!(
                                        "[API error: {}. I was unable to process your request.]",
                                        msg
                                    ),
                                    cache_control: None,
                                },
                            ]);
                        return Err(e);
                    }
                } else {
                    // Add error context so the AI knows what happened on next turn
                    self.session_state
                        .conversation
                        .add_assistant_with_blocks(vec![crate::api::MessageContentBlock::Text {
                            text: format!(
                                "[System error: {}. I was unable to process your request.]",
                                e
                            ),
                            cache_control: None,
                        }]);
                    return Err(e);
                }
            }
        };

        self.session_state
            .add_tokens(response.usage.input_tokens, response.usage.output_tokens);

        let mut handler = ResponseHandler::new(
            self.client.clone(),
            self.tool_executor.clone(),
            self.session_state.conversation.clone(),
            self.model_config.model.clone(),
            self.model_config.max_tokens,
            self.model_config.enable_thinking,
            self.model_config.thinking_budget,
            self.available_tools.clone(),
            use_streaming,
            Arc::clone(&self.interrupt_flag),
            Arc::clone(&self.steer_queue),
        );

        let result = runtime.block_on(handler.handle_response(
            response.content,
            &mut self.session_state.display_messages,
            &mut self.session_state.total_input_tokens,
            &mut self.session_state.total_output_tokens,
        ));

        // Always preserve conversation state so the AI retains context on retry
        self.session_state.conversation = handler.conversation().clone();

        match result {
            Ok(_) => Ok(()),
            Err(SofosError::Interrupted) => Ok(()),
            Err(e) => {
                // Add error context so the AI knows what happened on next turn.
                // Check last message role to maintain proper alternation —
                // the conversation could end on either role depending on where
                // the error occurred (e.g. after assistant reasoning vs after tool results).
                let error_text = format!(
                    "[System error during processing: {}. Previous actions are preserved above.]",
                    e
                );
                let last_role = self
                    .session_state
                    .conversation
                    .messages()
                    .last()
                    .map(|m| m.role.as_str());
                if last_role == Some("assistant") {
                    // Last message is assistant — add user error context
                    self.session_state.conversation.add_user_message(error_text);
                } else {
                    // Last message is user (tool results) or empty — add assistant error context
                    self.session_state
                        .conversation
                        .add_assistant_with_blocks(vec![crate::api::MessageContentBlock::Text {
                            text: error_text,
                            cache_control: None,
                        }]);
                }
                Err(e)
            }
        }
    }

    /// Build initial request for user message
    fn build_initial_request(&self) -> CreateMessageRequest {
        RequestBuilder::new(
            &self.client,
            &self.model_config.model,
            self.model_config.max_tokens,
            &self.session_state.conversation,
            self.get_available_tools(),
            self.model_config.enable_thinking,
            self.model_config.thinking_budget,
        )
        .build()
    }

    pub fn process_single_prompt(&mut self, prompt: &str) -> Result<()> {
        let symbol = if self.safe_mode { "λ:" } else { "λ>" };
        println!("{} {}", symbol.bright_green().bold(), prompt);
        println!();
        self.process_message(prompt, vec![])?;
        self.save_current_session()?;
        UI::display_session_summary(
            &self.model_config.model,
            self.session_state.total_input_tokens,
            self.session_state.total_output_tokens,
        );

        Ok(())
    }

    // Public methods for command implementations

    pub fn save_current_session(&self) -> Result<()> {
        if self.session_state.conversation.messages().is_empty() {
            return Ok(());
        }

        self.history_manager.save_session(
            &self.session_state.session_id,
            self.session_state.conversation.messages(),
            &self.session_state.display_messages,
            self.session_state.conversation.system_prompt(),
        )?;

        Ok(())
    }

    pub fn get_session_summary(&self) -> (String, u32, u32) {
        (
            self.model_config.model.clone(),
            self.session_state.total_input_tokens,
            self.session_state.total_output_tokens,
        )
    }

    pub fn handle_clear_command(&mut self) -> Result<()> {
        let new_session_id = HistoryManager::generate_session_id();
        self.session_state.conversation.clear();
        self.session_state.clear(new_session_id);
        self.session_state
            .conversation
            .add_user_message("The session history has been cleared".to_string());
        println!("\n{}\n", "Conversation history cleared.".bright_yellow());
        Ok(())
    }

    pub fn handle_resume_command(&mut self) -> Result<()> {
        let sessions = self.history_manager.list_sessions()?;

        if sessions.is_empty() {
            println!("{}", "No saved sessions found.".yellow());
            return Ok(());
        }

        let selected_id = crate::session::select_session(sessions)?;

        if let Some(session_id) = selected_id {
            self.load_session_by_id(&session_id)?;
            println!(
                "{} {}",
                "Session loaded:".bright_green(),
                "Continue your conversation below".dimmed()
            );
            println!();
        }

        Ok(())
    }

    pub fn handle_think_on(&mut self) {
        self.model_config.set_thinking(true);

        if matches!(self.client, Anthropic(_)) {
            println!(
                "\n{} (budget: {} tokens)\n",
                "Extended thinking enabled.".bright_green(),
                self.model_config.thinking_budget
            );
        } else {
            let reasoning = Some(crate::api::Reasoning::enabled());
            let effort: Option<&str> = reasoning.as_ref().map(|r| r.effort.as_str());

            if let Some(e) = effort {
                println!("\n{} {}\n", "Reasoning effort:".bright_green(), e);
            }
        }
    }

    pub fn handle_think_off(&mut self) {
        self.model_config.set_thinking(false);

        if matches!(self.client, Anthropic(_)) {
            println!("\n{}\n", "Extended thinking disabled.".bright_yellow());
        } else {
            let reasoning = Some(crate::api::Reasoning::disabled());
            let effort: Option<&str> = reasoning.as_ref().map(|r| r.effort.as_str());

            if let Some(e) = effort {
                println!("\n{} {}\n", "Reasoning effort:".bright_green(), e);
            }
        }
    }

    pub fn handle_think_status(&self) {
        if self.model_config.enable_thinking {
            println!(
                "\n{} (budget: {} tokens)\n",
                "Extended thinking is enabled".bright_green(),
                self.model_config.thinking_budget
            );
        } else {
            println!("\n{}\n", "Extended thinking is disabled".bright_yellow());
        }
    }

    pub fn enable_safe_mode(&mut self) {
        if !self.safe_mode {
            self.safe_mode = true;
            self.tool_executor.set_safe_mode(true);
            self.refresh_available_tools();

            self.session_state
                .conversation
                .add_user_message(SAFE_MODE_MESSAGE.to_string());
        }
    }

    pub fn disable_safe_mode(&mut self) {
        if self.safe_mode {
            self.safe_mode = false;
            self.tool_executor.set_safe_mode(false);
            self.refresh_available_tools();

            self.session_state
                .conversation
                .add_user_message(NORMAL_MODE_MESSAGE.to_string());
        }
    }

    fn refresh_available_tools(&mut self) {
        // Disjoint field borrows: `self.runtime` and `self.tool_executor`
        // are different fields, so the async block's borrow of
        // `tool_executor` doesn't conflict with the runtime's `&self`
        // receiver on `block_on`.
        let tools = self
            .runtime
            .block_on(async { self.tool_executor.get_available_tools().await });
        self.available_tools = tools;
    }

    pub fn load_session_by_id(&mut self, session_id: &str) -> Result<()> {
        let session = self.history_manager.load_session(session_id)?;

        self.session_state.session_id = session.id.clone();
        self.session_state.conversation.clear();
        self.session_state
            .conversation
            .restore_messages(session.api_messages.clone());
        self.session_state.display_messages = session.display_messages.clone();

        println!(
            "{} {} ({} messages)",
            "Loaded session:".bright_green(),
            session.id,
            session.api_messages.len()
        );
        println!();

        self.ui.display_session(&session)?;

        Ok(())
    }

    fn handle_initial_interrupt(&mut self) {
        println!(
            "\n{}",
            "Interrupted by user. You can now provide additional guidance.".bright_yellow()
        );
        println!();

        let interrupt_msg = "INTERRUPT: The user pressed ESC to interrupt the request before receiving a response. \
                             They want to provide additional guidance or clarification. Wait for their next message.";
        self.session_state
            .conversation
            .add_user_message(interrupt_msg.to_string());

        self.session_state
            .display_messages
            .push(DisplayMessage::UserMessage {
                content: "[Interrupted - no response received]".to_string(),
            });
    }

    fn get_available_tools(&self) -> Vec<crate::api::Tool> {
        self.available_tools.clone()
    }

    /// Compact the conversation by truncating tool results and summarizing older messages.
    /// Returns Ok(true) if compaction was performed, Ok(false) if skipped.
    pub fn compact_conversation(&mut self, force: bool) -> Result<bool> {
        if !force && !self.session_state.conversation.needs_compaction() {
            return Ok(false);
        }

        let tokens_before = self.session_state.conversation.estimate_total_tokens();

        // Phase 1: Truncate large tool results in older messages
        let split_point = self.session_state.conversation.compaction_split_point();
        if split_point == 0 {
            if force {
                println!("\n{}\n", "Not enough messages to compact.".bright_yellow());
            }
            return Ok(false);
        }

        self.session_state
            .conversation
            .truncate_tool_results(split_point);

        if !force && !self.session_state.conversation.needs_compaction() {
            let tokens_after = self.session_state.conversation.estimate_total_tokens();
            println!(
                "\n{} {} -> {} tokens (tool results truncated)\n",
                "Compacted:".bright_green(),
                tokens_before,
                tokens_after
            );
            return Ok(true);
        }

        // Phase 2: Summarize older messages via the LLM
        let older_messages: Vec<_> =
            self.session_state.conversation.messages()[..split_point].to_vec();
        let serialized = ConversationHistory::serialize_messages_for_summary(&older_messages);

        let summary_system = vec![crate::api::SystemPrompt::new_cached_with_ttl(
            "You are a conversation summarizer. Produce a detailed but concise summary of the following \
             coding assistant conversation. Preserve:\n\
             1. All file paths mentioned or modified\n\
             2. Key decisions made and their rationale\n\
             3. Current state of any ongoing task\n\
             4. Any errors encountered and how they were resolved\n\n\
             Format as structured sections. Do NOT include raw file contents or verbose tool output — \
             just what was done and decided."
                .to_string(),
            None,
        )];

        let summary_request = CreateMessageRequest {
            model: self.model_config.model.clone(),
            max_tokens: 4096,
            messages: vec![crate::api::Message::user(serialized)],
            system: Some(summary_system),
            tools: None,
            stream: None,
            thinking: None,
            reasoning: None,
        };

        let interrupt_flag = Arc::clone(&self.interrupt_flag);
        let client = self.client.clone();
        let mut request_handle = self
            .runtime
            .spawn(async move { client.create_message(summary_request).await });

        let response_result = self.runtime.block_on(async {
            tokio::select! {
                res = &mut request_handle => {
                    match res {
                        Ok(inner) => inner,
                        Err(e) => Err(SofosError::Join(format!("{}", e)))
                    }
                }
                _ = Self::wait_for_interrupt(Arc::clone(&interrupt_flag)) => {
                    request_handle.abort();
                    Err(SofosError::Interrupted)
                }
            }
        });

        match response_result {
            Ok(response) => {
                let summary_text: String = response
                    .content
                    .iter()
                    .filter_map(|block| {
                        if let crate::api::ContentBlock::Text { text } = block {
                            Some(text.as_str())
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                if summary_text.len() < 50 {
                    UI::print_warning(
                        "Compaction produced an insufficient summary. Falling back to trimming.",
                    );
                    self.session_state.conversation.fallback_trim();
                    return Ok(false);
                }

                self.session_state
                    .conversation
                    .replace_with_summary(summary_text, split_point);

                self.session_state
                    .add_tokens(response.usage.input_tokens, response.usage.output_tokens);

                let tokens_after = self.session_state.conversation.estimate_total_tokens();
                println!(
                    "{} {} -> {} tokens (saved {}%)",
                    "Compacted:".bright_green(),
                    tokens_before,
                    tokens_after,
                    if tokens_before > 0 {
                        100 - (tokens_after * 100 / tokens_before)
                    } else {
                        0
                    }
                );

                Ok(true)
            }
            Err(SofosError::Interrupted) => {
                UI::print_warning("Compaction interrupted. Falling back to trimming.");
                self.session_state.conversation.fallback_trim();
                Ok(false)
            }
            Err(e) => {
                UI::print_warning(&format!(
                    "Compaction failed: {}. Falling back to trimming.",
                    e
                ));
                self.session_state.conversation.fallback_trim();
                Ok(false)
            }
        }
    }

    pub fn handle_compact_command(&mut self) -> Result<()> {
        self.compact_conversation(true)?;
        Ok(())
    }

    /// Await the interrupt flag in an async-friendly loop (50ms poll).
    async fn wait_for_interrupt(flag: Arc<AtomicBool>) {
        while !flag.load(Ordering::Relaxed) {
            sleep(Duration::from_millis(50)).await;
        }
    }
}