agent-code 0.17.0

An AI-powered coding agent for the terminal, written in pure Rust
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
//! Interactive REPL (Read-Eval-Print Loop).
//!
//! The main user interaction loop. Reads input via rustyline,
//! passes it to the query engine, and streams output to the terminal.
//! Integrates markdown rendering, activity indicators, and permission
//! prompts.

use std::borrow::Cow;
use std::io::Write;
use std::sync::{Arc, Mutex};

use crossterm::style::Stylize;
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{Context, Helper};

use crate::ui::activity::ActivityIndicator;
use agent_code_lib::llm::message::Usage;
use agent_code_lib::query::{QueryEngine, StreamSink};
use agent_code_lib::tools::ToolResult;

/// Write to stdout with LF → CRLF translation. Needed because the escape-key
/// watcher (`spawn_escape_watcher`) holds the terminal in raw mode for the
/// entire duration of a streaming turn, and in raw mode a bare `\n` moves the
/// cursor down one row without returning to column 0 — causing subsequent
/// lines to drift right by the column of the previous line. Any code path
/// that prints during a turn must go through this helper (or the tui
/// renderer, which already uses `\r\n` internally).
fn raw_print(text: &str) {
    let translated = text.replace("\r\n", "\n").replace('\n', "\r\n");
    let mut out = std::io::stdout().lock();
    let _ = out.write_all(translated.as_bytes());
    let _ = out.flush();
}

/// Like `raw_print`, but for stderr.
fn raw_eprint(text: &str) {
    let translated = text.replace("\r\n", "\n").replace('\n', "\r\n");
    let mut err = std::io::stderr().lock();
    let _ = err.write_all(translated.as_bytes());
    let _ = err.flush();
}

/// Tab-completion helper for slash commands.
struct CommandCompleter;

impl Completer for CommandCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        // Only complete at the start of input for / commands.
        if !line.starts_with('/') {
            return Ok((0, vec![]));
        }

        let partial = &line[1..pos];
        let matches: Vec<Pair> = crate::commands::COMMANDS
            .iter()
            .filter(|c| !c.hidden)
            .filter(|c| c.name.starts_with(partial))
            .map(|c| Pair {
                display: format!("/{}{}", c.name, c.description),
                replacement: format!("/{}", c.name),
            })
            .collect();

        // Start replacement from position 0 (replacing the whole /partial).
        Ok((0, matches))
    }
}

impl Hinter for CommandCompleter {
    type Hint = String;

    fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<String> {
        if !line.starts_with('/') || pos < 2 {
            return None;
        }

        let partial = &line[1..pos];
        crate::commands::COMMANDS
            .iter()
            .filter(|c| !c.hidden)
            .find(|c| c.name.starts_with(partial) && c.name != partial)
            .map(|c| c.name[partial.len()..].to_string())
    }
}

impl Highlighter for CommandCompleter {
    fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
        // Show hints in grey.
        Cow::Owned(format!("\x1b[90m{hint}\x1b[0m"))
    }
}

impl Validator for CommandCompleter {}
impl Helper for CommandCompleter {}

/// Stream sink that writes to the terminal with full rendering.
struct TerminalSink {
    /// Tracks whether we're mid-line (for proper newline handling).
    mid_line: Arc<Mutex<bool>>,
    /// Accumulates the full response text for post-render.
    response_buffer: Arc<Mutex<String>>,
    /// Activity indicator (shown while waiting for LLM).
    indicator: Arc<Mutex<Option<ActivityIndicator>>>,
    /// Whether verbose mode is on (shows usage stats inline).
    verbose: bool,
    /// Accumulated turn state for the summary panel.
    turn_state: super::tui::SharedTurnState,
}

impl TerminalSink {
    fn new(verbose: bool) -> Self {
        Self {
            mid_line: Arc::new(Mutex::new(false)),
            response_buffer: Arc::new(Mutex::new(String::new())),
            indicator: Arc::new(Mutex::new(None)),
            verbose,
            turn_state: super::tui::new_turn_state(),
        }
    }

    /// Start the activity indicator (call when API request begins).
    fn start_indicator(&self) {
        if let Ok(mut guard) = self.indicator.lock()
            && guard.is_none()
        {
            *guard = Some(ActivityIndicator::thinking());
        }
    }

    fn ensure_newline(&self) {
        let mut mid = self.mid_line.lock().unwrap();
        if *mid {
            raw_print("\n");
            *mid = false;
        }
    }

    /// Stop the activity indicator (called when first token arrives).
    fn stop_indicator(&self) {
        if let Ok(mut guard) = self.indicator.lock()
            && let Some(ind) = guard.take()
        {
            ind.stop();
        }
    }

    /// Restart the activity indicator (called between tool execution and next LLM call).
    fn restart_indicator(&self) {
        if let Ok(mut guard) = self.indicator.lock() {
            *guard = Some(ActivityIndicator::thinking());
        }
    }
}

impl StreamSink for TerminalSink {
    fn on_text(&self, text: &str) {
        // First text token: stop the activity indicator.
        self.stop_indicator();

        raw_print(text);
        *self.mid_line.lock().unwrap() = !text.ends_with('\n');

        // Buffer for potential post-processing (markdown render of full blocks).
        self.response_buffer.lock().unwrap().push_str(text);
    }

    fn on_tool_start(&self, tool_name: &str, input: &serde_json::Value) {
        self.stop_indicator();
        self.ensure_newline();
        let detail = summarize_tool_input(tool_name, input);

        // Track in turn state.
        self.turn_state
            .lock()
            .unwrap()
            .add_tool_start(tool_name, &detail);

        // Render inline tool header.
        super::tui::render_tool_block(tool_name, &detail, None, false);
    }

    fn on_tool_result(&self, _tool_name: &str, result: &ToolResult) {
        // Track in turn state.
        self.turn_state
            .lock()
            .unwrap()
            .complete_last_tool(&result.content, result.is_error);

        // Render inline result line.
        let t = super::theme::current();
        if result.is_error {
            let first_line = result.content.lines().next().unwrap_or("");
            raw_eprint(&format!(
                "  {} {}\n",
                "".with(t.error),
                first_line.with(t.error)
            ));
        } else {
            let preview: String = result
                .content
                .lines()
                .next()
                .unwrap_or("(ok)")
                .chars()
                .take(80)
                .collect();
            let line_count = result.content.lines().count();
            let suffix = if line_count > 1 {
                format!(" (+{} lines)", line_count - 1)
                    .with(t.muted)
                    .to_string()
            } else {
                String::new()
            };
            raw_eprint(&format!(
                "  {} {}{}\n",
                "".with(t.success),
                preview.with(t.muted),
                suffix
            ));
        }
        self.restart_indicator();
    }

    fn on_thinking(&self, text: &str) {
        self.stop_indicator();
        self.turn_state.lock().unwrap().thinking_chars = text.len();
        super::tui::render_thinking_block(text);
    }

    fn on_turn_complete(&self, turn: usize) {
        self.stop_indicator();
        self.ensure_newline();

        // Render the turn summary panel if there were multiple tool calls
        // or at least one success. Skip for single-error turns (noisy).
        let state = self.turn_state.lock().unwrap();
        let has_success = state.tools.iter().any(|t| !t.is_error);
        if state.tools.len() > 1 || has_success {
            super::tui::render_turn_summary(&state, turn);
        }
        drop(state);

        // Clear turn state for next turn.
        self.turn_state.lock().unwrap().clear();
    }

    fn on_error(&self, error: &str) {
        self.stop_indicator();
        self.ensure_newline();
        let t = super::theme::current();
        raw_eprint(&format!(
            "{} {error}\n",
            super::theme::label(" ERROR ", t.error, crossterm::style::Color::White)
        ));
    }

    fn on_usage(&self, usage: &Usage) {
        // Track in turn state for the summary panel.
        {
            let mut state = self.turn_state.lock().unwrap();
            state.tokens_in = usage.input_tokens;
            state.tokens_out = usage.output_tokens;
            state.cache_read = usage.cache_read_input_tokens;
            state.cache_write = usage.cache_creation_input_tokens;
        }
    }

    fn on_compact(&self, freed_tokens: u64) {
        let t = super::theme::current();
        raw_eprint(&format!(
            "  {} {}\n",
            "".with(t.accent),
            format!("compacted ~{freed_tokens} tokens").with(t.muted),
        ));
    }

    fn on_warning(&self, msg: &str) {
        let t = super::theme::current();
        raw_eprint(&format!(
            "{} {msg}\n",
            super::theme::label(" WARN ", t.warning, crossterm::style::Color::Black)
        ));
    }
}

/// Spawn a background task that watches for the Escape key during streaming.
/// Returns a guard that stops the watcher on drop (restoring terminal state).
/// Uses crossterm raw mode only while actively polling, and yields quickly
/// to avoid competing with rustyline for stdin.
fn spawn_escape_watcher(engine: &QueryEngine) -> EscapeWatcherGuard {
    let cancel_token = engine.cancel_token();
    let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let stop2 = stop.clone();

    let handle = std::thread::spawn(move || {
        use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};

        // Enable raw mode so we can capture individual keypresses.
        if crossterm::terminal::enable_raw_mode().is_err() {
            return;
        }

        while !stop2.load(std::sync::atomic::Ordering::Relaxed) {
            // Poll with a short timeout to check the stop flag frequently.
            if event::poll(std::time::Duration::from_millis(100)).unwrap_or(false)
                && let Ok(Event::Key(KeyEvent {
                    code, modifiers, ..
                })) = event::read()
            {
                match code {
                    KeyCode::Esc => {
                        cancel_token.cancel();
                        break;
                    }
                    // Also handle Ctrl+C here since raw mode intercepts it.
                    KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                        cancel_token.cancel();
                        break;
                    }
                    _ => {}
                }
            }
        }

        let _ = crossterm::terminal::disable_raw_mode();
    });

    EscapeWatcherGuard {
        stop,
        handle: Some(handle),
    }
}

/// RAII guard that stops the escape watcher thread and restores terminal state.
struct EscapeWatcherGuard {
    stop: Arc<std::sync::atomic::AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl Drop for EscapeWatcherGuard {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
        // Ensure raw mode is off even if thread panicked.
        let _ = crossterm::terminal::disable_raw_mode();
    }
}

/// Run the interactive REPL loop.
pub async fn run_repl(engine: &mut QueryEngine) -> anyhow::Result<()> {
    // Configure editing mode and load custom keybindings.
    let input_mode = super::keymap::InputMode::default();
    let _keybindings = super::keybindings::KeybindingRegistry::load();
    let rl_config = rustyline::Config::builder()
        .edit_mode(input_mode.to_edit_mode())
        .completion_type(rustyline::config::CompletionType::List)
        .bracketed_paste(true)
        .build();
    let mut rl =
        rustyline::Editor::<CommandCompleter, rustyline::history::DefaultHistory>::with_config(
            rl_config,
        )?;
    rl.set_helper(Some(CommandCompleter));

    // Generate a session ID for persistence. Clone for later use since
    // Stylize methods consume the String.
    let session_id = agent_code_lib::services::session::new_session_id();
    let session_id_display = session_id.clone();

    // Initialize session notes and clean up old ones.
    agent_code_lib::memory::session_notes::init_session_notes(&session_id);
    agent_code_lib::memory::session_notes::cleanup_old_notes();

    // Load project-scoped history (hashed from cwd).
    let history_path = dirs::data_dir().map(|d| {
        let cwd = &engine.state().cwd;
        // Hash the cwd to create a project-specific history file.
        let hash: u64 = cwd
            .bytes()
            .fold(5381u64, |h, b| h.wrapping_mul(33).wrapping_add(b as u64));
        d.join("agent-code")
            .join("history")
            .join(format!("{hash:x}.txt"))
    });
    if let Some(ref path) = history_path {
        let _ = std::fs::create_dir_all(path.parent().unwrap());
        let _ = rl.load_history(path);
    }

    let verbose = engine.state().config.ui.syntax_highlight; // Use as verbose proxy for now.

    // Welcome message.
    // Render the welcome banner.
    let term_width = crossterm::terminal::size()
        .map(|(w, _)| w as usize)
        .unwrap_or(80);
    let divider = "".repeat(term_width.min(100));
    let model = engine.state().config.api.model.clone();
    let cwd = engine.state().cwd.clone();

    // Initialize theme.
    let theme_name = super::theme::resolve_theme(&engine.state().config.ui.theme);
    super::theme::init(&theme_name);
    let t = super::theme::current();

    println!();

    // Simple 3-line robot mascot rendered in the current theme accent color.
    // Replaces the earlier pixel-art crab — see commit history for the
    // rationale (we preferred the minimal look).
    println!(
        "  {}   {} v{}",
        "▐▛██▜▌".with(t.accent).bold(),
        "Agent Code".with(t.text).bold(),
        env!("CARGO_PKG_VERSION"),
    );
    println!(
        "  {}   {} · session {}",
        "▝▜██▛▘".with(t.accent),
        model.with(t.text).bold(),
        session_id_display.as_str().with(t.muted),
    );
    println!("  {}   {}", "  ▘▘  ".with(t.accent), cwd.with(t.muted),);

    println!();
    println!("{}", divider.with(t.muted));

    // Show hint for shortcuts.
    println!("  {}", "? for shortcuts".with(t.muted),);
    println!();

    let mut ctrl_c_pending = false;

    loop {
        let sink = TerminalSink::new(verbose);
        let t = super::theme::current();

        // Inline status divider before prompt (after first turn).
        {
            let state = engine.state();
            if state.turn_count > 0 {
                let term_w = crossterm::terminal::size()
                    .map(|(w, _)| w as usize)
                    .unwrap_or(80)
                    .min(100);
                let status = format!(
                    " {} · turn {} · {} tokens · ${:.4} ",
                    state.config.api.model,
                    state.turn_count,
                    state.total_usage.total(),
                    state.total_cost_usd,
                );
                let pad = term_w.saturating_sub(status.len());
                let left = pad / 2;
                let right = pad - left;
                eprintln!(
                    "{}{}{}",
                    "".repeat(left).with(t.muted),
                    status.with(t.muted),
                    "".repeat(right).with(t.muted),
                );
            }
        }

        let prompt = format!("{} ", "".with(t.accent).bold());

        match rl.readline(&prompt) {
            Ok(line) => {
                ctrl_c_pending = false;
                let mut input_buf = line.clone();

                // Multi-line input: if line ends with \, keep reading.
                while input_buf.trim_end().ends_with('\\') {
                    input_buf.truncate(input_buf.trim_end().len() - 1);
                    input_buf.push('\n');
                    let cont_prompt = format!("{} ", ".".with(t.muted));
                    match rl.readline(&cont_prompt) {
                        Ok(next) => input_buf.push_str(&next),
                        Err(_) => break,
                    }
                }

                let input = input_buf.trim();
                if input.is_empty() {
                    continue;
                }

                // Toggle shortcuts help panel on "?".
                if input == "?" {
                    let t = super::theme::current();
                    println!();
                    println!("  {}", "Keyboard Shortcuts".with(t.accent).bold());
                    println!("  {}", "".repeat(50).with(t.muted));
                    println!(
                        "  {}  {}",
                        "! command".with(t.text),
                        "run shell command directly".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "@ path/file".with(t.text),
                        "attach file contents to prompt".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "& prompt".with(t.text),
                        "run prompt in background".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/ + command".with(t.text),
                        "slash commands (/help to list all)".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "Tab".with(t.text),
                        "auto-complete /commands".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "\\ + Enter".with(t.text),
                        "multi-line input".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "Esc / Ctrl+C".with(t.text),
                        "cancel (Ctrl+C twice to exit)".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "Ctrl+R".with(t.text),
                        "search history".with(t.muted),
                    );
                    println!("  {}  {}", "Ctrl+D".with(t.text), "exit".with(t.muted),);
                    println!("  {}", "".repeat(50).with(t.muted));
                    println!(
                        "  {}  {}",
                        "/model <name>".with(t.text),
                        "switch model".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/scroll".with(t.text),
                        "scrollable conversation view".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/snip <N-M>".with(t.text),
                        "remove messages from history".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/fork".with(t.text),
                        "branch conversation".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/rewind".with(t.text),
                        "undo last turn".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/features".with(t.text),
                        "show feature flags".with(t.muted),
                    );
                    println!(
                        "  {}  {}",
                        "/doctor".with(t.text),
                        "check environment health".with(t.muted),
                    );
                    println!();
                    continue;
                }

                rl.add_history_entry(input)?;

                // Re-echo user input with styled background, overwriting rustyline's echo.
                if !input.starts_with('/') && input != "?" && !input.starts_with('!') {
                    let t = super::theme::current();
                    let bg = if t.is_dark {
                        "\x1b[48;2;55;55;55m" // dark: subtle grey bg
                    } else {
                        "\x1b[48;2;235;235;240m" // light: subtle grey bg
                    };
                    // Move cursor up to overwrite rustyline's echo line.
                    let line_count = input.lines().count().max(1);
                    eprint!("\x1b[{line_count}A\x1b[2K");
                    let _ = std::io::stderr().flush();
                    // Print styled version.
                    for line in input.lines() {
                        let pad = crossterm::terminal::size()
                            .map(|(w, _)| w as usize)
                            .unwrap_or(80)
                            .saturating_sub(line.len() + 4);
                        println!(
                            "{bg}  {} {}{}\x1b[0m",
                            "".with(t.accent),
                            line,
                            " ".repeat(pad),
                        );
                    }
                    println!();
                }

                // @ file path expansion: inline file contents into the prompt.
                let input = if input.contains('@') {
                    expand_file_references(input, &engine.state().cwd)
                } else {
                    input.to_string()
                };
                let input = input.trim();

                // & prefix: run prompt in background (fire-and-forget agent turn).
                if input.starts_with('&') {
                    let bg_input = input.strip_prefix('&').unwrap_or("").trim().to_string();
                    if !bg_input.is_empty() {
                        let t = super::theme::current();
                        eprintln!(
                            "  {} {}",
                            "".with(t.accent),
                            format!("background: {}", &bg_input[..bg_input.len().min(60)])
                                .with(t.muted),
                        );
                        // TODO: spawn actual background agent turn.
                        // For now, just run it as a normal turn.
                        sink.start_indicator();
                        if let Err(e) = engine.run_turn_with_sink(&bg_input, &sink).await {
                            let t = super::theme::current();
                            eprintln!(
                                "{} {e}",
                                super::theme::label(
                                    " ERROR ",
                                    t.error,
                                    crossterm::style::Color::White
                                )
                            );
                        }
                        sink.ensure_newline();
                        println!();
                    }
                    continue;
                }

                // ! prefix: run shell command directly with context injection.
                // Output streams in real-time AND gets injected into conversation
                // history so the agent can reference it in subsequent turns.
                if input.starts_with('!') {
                    let cmd = input.strip_prefix('!').unwrap_or("").trim();
                    if !cmd.is_empty() {
                        use agent_code_lib::services::shell_passthrough;

                        let cwd = std::path::Path::new(&engine.state().cwd);
                        match shell_passthrough::run_and_capture(
                            cmd,
                            cwd,
                            |line| println!("{line}"),
                            |line| eprintln!("{line}"),
                        ) {
                            Ok(output) => {
                                if let Some(msg) =
                                    shell_passthrough::build_context_message(cmd, &output)
                                {
                                    engine.state_mut().push_message(msg);
                                }
                            }
                            Err(e) => eprintln!("{e}"),
                        }
                    }
                    continue;
                }

                // Handle slash commands.
                if input.starts_with('/') {
                    match crate::commands::execute(input, engine) {
                        crate::commands::CommandResult::Handled => continue,
                        crate::commands::CommandResult::Exit => break,
                        crate::commands::CommandResult::Passthrough(text) => {
                            sink.start_indicator();
                            if let Err(e) = engine.run_turn_with_sink(&text, &sink).await {
                                {
                                    let t = super::theme::current();
                                    eprintln!(
                                        "{} {e}",
                                        super::theme::label(
                                            " ERROR ",
                                            t.error,
                                            crossterm::style::Color::White
                                        )
                                    );
                                }
                            }
                            sink.ensure_newline();
                            println!();
                        }
                        crate::commands::CommandResult::Prompt(prompt) => {
                            sink.start_indicator();
                            if let Err(e) = engine.run_turn_with_sink(&prompt, &sink).await {
                                {
                                    let t = super::theme::current();
                                    eprintln!(
                                        "{} {e}",
                                        super::theme::label(
                                            " ERROR ",
                                            t.error,
                                            crossterm::style::Color::White
                                        )
                                    );
                                }
                            }
                            sink.ensure_newline();
                            println!();
                        }
                    }
                    continue;
                }

                // Run the agent turn with Escape key watcher for cancellation.
                let _esc_guard = spawn_escape_watcher(engine);
                sink.start_indicator();
                if let Err(e) = engine.run_turn_with_sink(input, &sink).await {
                    {
                        let t = super::theme::current();
                        raw_eprint(&format!(
                            "{} {e}\n",
                            super::theme::label(" ERROR ", t.error, crossterm::style::Color::White)
                        ));
                    }
                }
                drop(_esc_guard);
                sink.ensure_newline();
                println!();

                // Auto-save session after each turn.
                {
                    let state = engine.state();
                    let _ = agent_code_lib::services::session::save_session_full(
                        &session_id,
                        &state.messages,
                        &state.cwd,
                        &state.config.api.model,
                        state.turn_count,
                        state.total_cost_usd,
                        state.total_usage.input_tokens,
                        state.total_usage.output_tokens,
                        state.plan_mode,
                    );
                }
            }
            Err(ReadlineError::Interrupted) => {
                if engine.state().is_query_active {
                    engine.cancel();
                    eprintln!("{}", "(cancelled)".with(super::theme::current().muted));
                    ctrl_c_pending = false;
                } else if ctrl_c_pending {
                    // Second Ctrl+C at prompt — exit.
                    break;
                } else {
                    // First Ctrl+C at prompt — show hint, continue.
                    eprintln!(
                        "{}",
                        "(Ctrl+C again to exit, or type /exit)".with(super::theme::current().muted)
                    );
                    ctrl_c_pending = true;
                }
            }
            Err(ReadlineError::Eof) => {
                break;
            }
            Err(e) => {
                eprintln!("Input error: {e}");
                break;
            }
        }
    }

    // Save history.
    if let Some(ref path) = history_path {
        let _ = rl.save_history(path);
    }

    // Persist session.
    let state = engine.state();
    if !state.messages.is_empty() {
        match agent_code_lib::services::session::save_session(
            &session_id,
            &state.messages,
            &state.cwd,
            &state.config.api.model,
            state.turn_count,
        ) {
            Ok(_) => {}
            Err(e) => eprintln!(
                "{}",
                format!("Failed to save session: {e}").with(super::theme::current().muted)
            ),
        }
    }

    // Print session summary.
    let divider = "".repeat(term_width.min(100));
    let t = super::theme::current();
    println!("{}", divider.with(t.muted));
    if state.total_usage.total() > 0 {
        println!(
            "  {} {} turns | {} tokens | ${:.4} | session {}",
            "session".with(t.accent),
            state.turn_count,
            state.total_usage.total(),
            state.total_cost_usd,
            session_id_display.as_str().with(t.muted),
        );
    } else {
        println!(
            "  {} session {}",
            "goodbye".with(t.accent),
            session_id_display.as_str().with(t.muted)
        );
    }

    Ok(())
}

/// Create a short summary of tool input for display.
fn summarize_tool_input(tool_name: &str, input: &serde_json::Value) -> String {
    let raw = match tool_name {
        "Bash" => input
            .get("command")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "FileRead" | "FileWrite" | "FileEdit" | "NotebookEdit" => input
            .get("file_path")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "Grep" | "Glob" | "WebSearch" => input
            .get("pattern")
            .or_else(|| input.get("query"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "WebFetch" => input
            .get("url")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "Agent" => input
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        _ => {
            // Compact JSON preview.
            serde_json::to_string(input)
                .unwrap_or_default()
                .chars()
                .take(80)
                .collect()
        }
    };

    // Truncate long summaries.
    if raw.len() > 120 {
        format!("{}...", &raw[..117])
    } else {
        raw
    }
}

/// Expand @path references in user input to include file contents.
/// e.g., "explain @src/main.rs" → "explain\n\nContents of src/main.rs:\n```\n...```"
fn expand_file_references(input: &str, cwd: &str) -> String {
    let mut result = String::new();
    let mut last_end = 0;

    // Find @path patterns (@ followed by non-whitespace chars containing / or .).
    let chars: Vec<char> = input.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '@'
            && (i == 0 || chars[i - 1].is_whitespace())
            && i + 1 < chars.len()
            && !chars[i + 1].is_whitespace()
        {
            // Collect the path.
            let start = i + 1;
            let mut end = start;
            while end < chars.len() && !chars[end].is_whitespace() {
                end += 1;
            }
            let path_str: String = chars[start..end].iter().collect();

            // Only expand if it looks like a file path (contains / or .).
            if path_str.contains('/') || path_str.contains('.') {
                let full_path = std::path::Path::new(cwd).join(&path_str);
                if full_path.exists() && full_path.is_file() {
                    // Add text before the @reference.
                    let before: String = chars[last_end..i].iter().collect();
                    result.push_str(&before);

                    // Read and inline the file.
                    match std::fs::read_to_string(&full_path) {
                        Ok(content) => {
                            let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
                            // Truncate large files.
                            let display = if content.len() > 50_000 {
                                format!(
                                    "{}...\n(truncated, {} bytes total)",
                                    &content[..50_000],
                                    content.len()
                                )
                            } else {
                                content
                            };
                            result.push_str(&format!(
                                "\n\nContents of {path_str}:\n```{ext}\n{display}\n```\n"
                            ));
                        }
                        Err(_) => {
                            result.push('@');
                            result.push_str(&path_str);
                        }
                    }
                    last_end = end;
                    i = end;
                    continue;
                }
            }
        }
        i += 1;
    }

    // Append remaining text.
    let remaining: String = chars[last_end..].iter().collect();
    result.push_str(&remaining);
    result
}

#[cfg(test)]
mod raw_print_tests {
    //! The translation used by `raw_print` / `raw_eprint` is extracted here as
    //! a pure function so we can test it without touching stdout. The bug
    //! these guard against: during a streaming turn the escape watcher holds
    //! the terminal in raw mode, where a bare `\n` moves the cursor down one
    //! row without returning to column 0. Every newline emitted by the
    //! streaming sink must therefore be `\r\n`.

    fn translate(text: &str) -> String {
        text.replace("\r\n", "\n").replace('\n', "\r\n")
    }

    #[test]
    fn bare_lf_becomes_crlf() {
        assert_eq!(translate("a\nb"), "a\r\nb");
    }

    #[test]
    fn existing_crlf_is_preserved_not_doubled() {
        // Must not produce `\r\r\n`.
        assert_eq!(translate("a\r\nb"), "a\r\nb");
    }

    #[test]
    fn multiple_newlines_all_translated() {
        assert_eq!(translate("a\nb\nc\n"), "a\r\nb\r\nc\r\n");
    }

    #[test]
    fn text_without_newlines_is_unchanged() {
        assert_eq!(translate("hello world"), "hello world");
    }

    #[test]
    fn empty_string() {
        assert_eq!(translate(""), "");
    }

    #[test]
    fn mixed_lf_and_crlf() {
        assert_eq!(translate("a\nb\r\nc\n"), "a\r\nb\r\nc\r\n");
    }

    #[test]
    fn lone_cr_is_not_touched() {
        // Activity indicator and other helpers use bare `\r` to rewrite the
        // current line; that must survive translation intact.
        assert_eq!(translate("\rstatus"), "\rstatus");
    }

    #[test]
    fn cr_followed_by_text_then_lf() {
        assert_eq!(translate("\rstatus\n"), "\rstatus\r\n");
    }
}