agent-code 0.8.7

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

/// 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 {
            println!();
            *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();

        print!("{text}");
        let _ = std::io::stdout().flush();
        *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("");
            eprintln!("  {} {}", "".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()
            };
            eprintln!(
                "  {} {}{}",
                "".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();
        eprintln!(
            "{} {error}",
            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();
        eprintln!(
            "  {} {}",
            "".with(t.accent),
            format!("compacted ~{freed_tokens} tokens").with(t.muted),
        );
    }

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

/// Spawn a background task that watches for Escape key during streaming.
/// Returns a join handle that should be aborted when the turn completes.
fn spawn_escape_watcher(engine_cancel: impl Fn() + Send + 'static) -> tokio::task::JoinHandle<()> {
    tokio::task::spawn_blocking(move || {
        use crossterm::event::{self, Event, KeyCode, KeyEvent};
        // Poll for Escape key. Exits when Escape is pressed or the task is aborted.
        loop {
            if event::poll(std::time::Duration::from_millis(100)).unwrap_or(false)
                && let Ok(Event::Key(KeyEvent {
                    code: KeyCode::Esc, ..
                })) = event::read()
            {
                engine_cancel();
                break;
            }
        }
    })
}

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

    // Render pixel art crab with shimmer animation.
    let crab_lines = super::tui::render_crab_banner();
    let info_lines = [
        String::new(),
        String::new(),
        format!("  \x1b[1mAgent Code\x1b[0m v{}", env!("CARGO_PKG_VERSION")),
        format!("  {} · session {}", model, session_id_display.as_str()),
        format!("  {cwd}"),
        String::new(),
        String::new(),
    ];

    for (i, crab_line) in crab_lines.iter().enumerate() {
        let info = info_lines.get(i).cloned().unwrap_or_default();
        if info.is_empty() {
            println!("{crab_line}");
        } else {
            println!("{crab_line}{info}");
        }
    }

    // Brief shimmer animation (3 frames, 120ms each).
    for frame in 0..3 {
        let shimmer_lines = super::tui::render_crab_shimmer(frame);
        // Move cursor up to overwrite the crab.
        eprint!("\x1b[{}A", shimmer_lines.len());
        for (i, crab_line) in shimmer_lines.iter().enumerate() {
            let info = info_lines.get(i).cloned().unwrap_or_default();
            if info.is_empty() {
                println!("{crab_line}");
            } else {
                println!("{crab_line}{info}");
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(120));
    }

    // Final static frame.
    eprint!("\x1b[{}A", crab_lines.len());
    for (i, crab_line) in crab_lines.iter().enumerate() {
        let info = info_lines.get(i).cloned().unwrap_or_default();
        if info.is_empty() {
            println!("{crab_line}");
        } else {
            println!("{crab_line}{info}");
        }
    }

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

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

    let mut ctrl_c_pending = false;

    // Fixed footer using DECSTBM scroll regions.
    // Reserve the last 2 rows for the status bar. Content scrolls above.
    let update_footer = |engine: &QueryEngine| {
        let (term_w, term_h) = crossterm::terminal::size().unwrap_or((80, 24));
        let w = term_w as usize;
        let h = term_h as usize;

        let state = engine.state();
        let model_str = &state.config.api.model;
        let turns = state.turn_count;
        let tokens = state.total_usage.total();
        let cost = state.total_cost_usd;

        // Build the status line.
        let left = format!(" {model_str} ");
        let right = if turns > 0 {
            format!(" turn {turns}{tokens} tokens │ ${cost:.4} ")
        } else {
            " ? for shortcuts ".to_string()
        };
        let mid_len = w.saturating_sub(left.len() + right.len());
        let mid = "".repeat(mid_len);

        // Save cursor, move to last row, write status, restore cursor.
        eprint!("\x1b7\x1b[{h};1H\x1b[2K\x1b[90m{left}{mid}{right}\x1b[0m\x1b8");
        let _ = std::io::stderr().flush();
    };

    // Set scroll region: rows 1 to (height-1), pinning last row.
    // Then move cursor to bottom of scroll region so text fills from bottom up.
    let setup_scroll_region = || {
        let (_w, h) = crossterm::terminal::size().unwrap_or((80, 24));
        let scroll_bottom = h - 1;
        // Set scroll region, then move cursor to the bottom of that region.
        eprint!("\x1b[1;{scroll_bottom}r\x1b[{scroll_bottom};1H");
        let _ = std::io::stderr().flush();
    };

    // Reset scroll region on exit.
    let reset_scroll_region = || {
        eprint!("\x1b[r");
        let _ = std::io::stderr().flush();
    };

    setup_scroll_region();
    update_footer(engine);

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

        // Update the pinned footer.
        update_footer(engine);

        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!(
                        "  {}  {}",
                        "/ + 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!(
                        "  {}  {}",
                        "Ctrl+C".with(t.text),
                        "cancel (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 for visual separation.
                // Uses ANSI background color to distinguish user turns from agent output.
                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
                    };
                    // Print each line of the input with background color.
                    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!();
                }

                // ! prefix: run shell command directly (bash mode).
                if input.starts_with('!') {
                    let cmd = input.strip_prefix('!').unwrap_or("").trim();
                    if !cmd.is_empty() {
                        let output = std::process::Command::new("bash")
                            .arg("-c")
                            .arg(cmd)
                            .current_dir(&engine.state().cwd)
                            .output();
                        match output {
                            Ok(out) => {
                                let stdout = String::from_utf8_lossy(&out.stdout);
                                let stderr = String::from_utf8_lossy(&out.stderr);
                                if !stdout.is_empty() {
                                    print!("{stdout}");
                                }
                                if !stderr.is_empty() {
                                    eprint!("{stderr}");
                                }
                            }
                            Err(e) => eprintln!("bash error: {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.
                sink.start_indicator();
                let cancel_token = engine.cancel_token();
                let esc_watcher = spawn_escape_watcher(move || cancel_token.cancel());
                if let Err(e) = engine.run_turn_with_sink(input, &sink).await {
                    {
                        let t = super::theme::current();
                        eprintln!(
                            "{} {e}",
                            super::theme::label(" ERROR ", t.error, crossterm::style::Color::White)
                        );
                    }
                }
                esc_watcher.abort();
                sink.ensure_newline();
                println!();
            }
            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)
        );
    }

    // Reset scroll region before exiting.
    reset_scroll_region();

    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
    }
}