rab-agent 0.1.0

rab is a lightweight, extensible, Rust-based coding agent.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
use crate::agent::extension::{AgentTool, Cancel, Extension, ToolOutput};
use crate::agent::extension::{ToolRenderContext, ToolRenderer};
use crate::tui::Theme;
use crate::tui::visual_truncate::truncate_to_visual_lines;
use anyhow::Context;
use async_trait::async_trait;
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use tokio::sync::{Mutex as TokioMutex, mpsc::UnboundedSender};

pub struct BashExtension {
    cwd: std::path::PathBuf,
}

impl BashExtension {
    pub fn new(cwd: std::path::PathBuf) -> Self {
        Self { cwd }
    }
}

impl Extension for BashExtension {
    fn name(&self) -> Cow<'static, str> {
        "bash".into()
    }

    fn tools(&self) -> Vec<Box<dyn AgentTool>> {
        vec![Box::new(BashTool {
            cwd: self.cwd.clone(),
        })]
    }
}

struct BashTool {
    cwd: std::path::PathBuf,
}

// ── Constants ────────────────────────────────────────────────────

const DEFAULT_MAX_LINES: usize = 2000;
const DEFAULT_MAX_BYTES: usize = 50 * 1024; // 50KB
const DEFAULT_TIMEOUT_SECS: u64 = 300; // 5 minutes default timeout for all commands

// ── Helpers ──────────────────────────────────────────────────────

/// Kill a process group by its leader PID.
#[cfg(unix)]
fn kill_process_group(pid: u32) {
    if pid > 0 {
        let _ = std::process::Command::new("kill")
            .arg("--")
            .arg(format!("-{}", pid))
            .spawn();
    }
}

#[cfg(not(unix))]
fn kill_process_group(pid: u32) {
    let _ = pid;
}

/// Spawn a bash command with process group setup for clean cancellation.
fn spawn_bash_command(
    command: &str,
    cwd: &std::path::Path,
) -> std::io::Result<tokio::process::Child> {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let mut std_cmd = std::process::Command::new("sh");
        std_cmd.arg("-c").arg(command).current_dir(cwd);
        unsafe {
            std_cmd.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
        let mut tokio_cmd = tokio::process::Command::from(std_cmd);
        tokio_cmd
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
    }
    #[cfg(not(unix))]
    {
        tokio::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .current_dir(cwd)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
    }
}

/// Format the final bash execution result, matching pi's bash tool output format.
///
/// Pi's bash tool (LLM-called) returns raw output, not the `bashExecutionToText` format.
/// - Non-empty output → raw output (no Ran prefix, no backtick fences)
/// - Empty output → "(no output)"
/// - Truncated → raw output + `\n\n[Showing lines X-Y of Z... Full output: path]`
/// - Non-zero exit → returned as Err with output + `\n\nCommand exited with code N`
/// - Cancelled → returned as Err with output + `\n\nCommand aborted`
fn finish_bash_execution(
    _command: &str,
    combined: &str,
    exit_code: i32,
    cancelled: bool,
    _started_at: Instant,
    on_update: Option<UnboundedSender<ToolOutput>>,
) -> Result<ToolOutput, anyhow::Error> {
    // Apply tail truncation (pi-style: keep last N lines/bytes)
    let trunc = truncate_tail(combined, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES);

    // Build output text: raw output or (no output)
    let mut result_text = if trunc.content.is_empty() {
        "(no output)".to_string()
    } else {
        trunc.content.clone()
    };

    // Truncation notice (matching pi: appended to text, not in details)
    if trunc.truncated {
        let tmp_dir = std::env::temp_dir().join("rab-bash");
        let _ = std::fs::create_dir_all(&tmp_dir);
        let tmp_path = tmp_dir.join(format!("{}.txt", uuid::Uuid::new_v4()));
        let saved = if std::fs::write(&tmp_path, combined).is_ok() {
            Some(tmp_path)
        } else {
            None
        };

        let start_line = trunc.total_lines - trunc.output_lines + 1;
        let end_line = trunc.total_lines;

        let notice = if trunc.truncated_by == "lines" {
            format!(
                "\n\n[Showing lines {}-{} of {}. Full output: {}]",
                start_line,
                end_line,
                trunc.total_lines,
                saved
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_default()
            )
        } else {
            format!(
                "\n\n[Showing lines {}-{} of {} ({} limit). Full output: {}]",
                start_line,
                end_line,
                trunc.total_lines,
                format_size(DEFAULT_MAX_BYTES),
                saved
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_default()
            )
        };
        result_text.push_str(&notice);
    }

    // Send final update (before error conversion, so UI shows the output)
    if let Some(ref tx) = on_update {
        let _ = tx.send(ToolOutput::ok(result_text.clone()));
    }

    // Error cases: return as Err with output + status (matching pi)
    if cancelled {
        let err_msg = if result_text.is_empty() || result_text == "(no output)" {
            "Command aborted".to_string()
        } else {
            format!("{}\n\nCommand aborted", result_text)
        };
        return Err(anyhow::anyhow!("{}", err_msg));
    }

    if exit_code != 0 {
        let err_msg = if result_text.is_empty() || result_text == "(no output)" {
            format!("Command exited with code {}", exit_code)
        } else {
            format!("{}\n\nCommand exited with code {}", result_text, exit_code)
        };
        return Err(anyhow::anyhow!("{}", err_msg));
    }

    Ok(ToolOutput::ok(result_text))
}

/// Format bytes as a human-readable size string, matching pi's format.
fn format_size(bytes: usize) -> String {
    if bytes < 1024 {
        format!("{}B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1}KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.1}MB", bytes as f64 / (1024.0 * 1024.0))
    }
}

/// Truncation result for tail-based truncation (keep last N lines/bytes).
struct TailTruncation {
    /// Truncated output content.
    content: String,
    /// Whether truncation occurred.
    truncated: bool,
    // Fields below are only used in tests; kept for test assertions.
    #[allow(dead_code)]
    total_lines: usize,
    #[allow(dead_code)]
    output_lines: usize,
    #[allow(dead_code)]
    output_bytes: usize,
    #[allow(dead_code)]
    truncated_by: &'static str, // "lines" | "bytes"
    #[allow(dead_code)]
    last_line_partial: bool,
}

/// Truncate content from the tail, keeping complete lines that fit within limits.
/// Keeps the LAST N lines/bytes. Never returns partial lines unless the last line
/// of the original content exceeds the byte limit.
fn truncate_tail(content: &str, max_lines: usize, max_bytes: usize) -> TailTruncation {
    let total_bytes = content.len();
    let lines: Vec<&str> = content.lines().collect();
    let total_lines = lines.len();

    // Check if no truncation needed
    if total_lines <= max_lines && total_bytes <= max_bytes {
        return TailTruncation {
            content: content.to_string(),
            truncated: false,
            total_lines,
            output_lines: total_lines,
            output_bytes: total_bytes,
            truncated_by: "",
            last_line_partial: false,
        };
    }

    // Work backwards from the end
    let mut output: Vec<&str> = Vec::new();
    let mut byte_count: usize = 0;
    let mut truncated_by = "lines";
    let mut last_line_partial = false;

    for line in lines.iter().rev().take(max_lines) {
        let line_bytes = line.len();
        let with_newline = if output.is_empty() {
            line_bytes
        } else {
            line_bytes + 1 // +1 for preceding newline
        };

        if byte_count + with_newline > max_bytes {
            truncated_by = "bytes";
            // If we haven't added ANY lines yet and this line exceeds maxBytes,
            // take the end of the line (partial)
            if output.is_empty() {
                let end_start = line.len().saturating_sub(max_bytes);
                let truncated_line = &line[end_start..];
                output.push(truncated_line);
                byte_count = truncated_line.len();
                last_line_partial = true;
            }
            break;
        }

        output.push(line);
        byte_count += with_newline;
    }

    if output.len() >= max_lines && byte_count <= max_bytes {
        truncated_by = "lines";
    }

    output.reverse();
    TailTruncation {
        content: output.join("\n"),
        truncated: true,
        total_lines,
        output_lines: output.len(),
        output_bytes: byte_count,
        truncated_by,
        last_line_partial,
    }
}

// ── AgentTool implementation ─────────────────────────────────────

#[async_trait]
impl AgentTool for BashTool {
    fn name(&self) -> &str {
        "bash"
    }

    fn description(&self) -> &str {
        "Execute a bash command in the current working directory. Returns stdout and stderr. \
         Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, \
         full output is saved to a temp file. Optionally provide a timeout in seconds."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "required": ["command"],
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Bash command to execute"
                },
                "timeout": {
                    "type": "number",
                    "description": "Timeout in seconds (optional, no default timeout)"
                }
            }
        })
    }

    fn label(&self) -> &str {
        "Execute bash commands (ls, grep, find, etc.)"
    }

    fn renderer(&self) -> Option<Box<dyn ToolRenderer>> {
        Some(Box::new(BashRenderer))
    }

    async fn execute(
        &self,
        tool_call_id: String,
        args: serde_json::Value,
        cancel: Cancel,
        on_update: Option<UnboundedSender<ToolOutput>>,
    ) -> anyhow::Result<ToolOutput> {
        let _ = tool_call_id;
        let command = args["command"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing 'command' argument"))?;
        let timeout = args["timeout"].as_u64().or(Some(DEFAULT_TIMEOUT_SECS));
        let started_at = Instant::now();

        cancel.check()?;

        // Build the command with process group setup for process-tree killing
        let mut child = spawn_bash_command(command, &self.cwd)
            .with_context(|| format!("Failed to spawn command: {}", command))?;

        let pid = child.id().unwrap_or(0);

        // Shared output buffer for streaming reads
        let combined = Arc::new(TokioMutex::new(String::new()));
        let combined_clone = combined.clone();

        // Read stdout in a background task
        let stdout_pipe = child
            .stdout
            .take()
            .ok_or_else(|| anyhow::anyhow!("Failed to capture stdout"))?;
        let stderr_pipe = child
            .stderr
            .take()
            .ok_or_else(|| anyhow::anyhow!("Failed to capture stderr"))?;

        use tokio::io::AsyncReadExt;
        let read_task = tokio::spawn(async move {
            let mut stdout_buf = vec![0u8; 4096];
            let mut stderr_buf = vec![0u8; 4096];
            let mut stdout_reader = stdout_pipe;
            let mut stderr_reader = stderr_pipe;
            let mut stdout_done = false;
            let mut stderr_done = false;
            loop {
                tokio::select! {
                    result = stdout_reader.read(&mut stdout_buf), if !stdout_done => {
                        match result {
                            Ok(0) => stdout_done = true,
                            Ok(n) => {
                                let mut out = combined_clone.lock().await;
                                out.push_str(&String::from_utf8_lossy(&stdout_buf[..n]));
                            }
                            Err(_) => stdout_done = true,
                        }
                    }
                    result = stderr_reader.read(&mut stderr_buf), if !stderr_done => {
                        match result {
                            Ok(0) => stderr_done = true,
                            Ok(n) => {
                                let mut out = combined_clone.lock().await;
                                out.push_str(&String::from_utf8_lossy(&stderr_buf[..n]));
                            }
                            Err(_) => stderr_done = true,
                        }
                    }
                }
                if stdout_done && stderr_done {
                    break;
                }
            }
        });

        // Set up cancellation monitor: kill the process group if cancelled
        let cancelled = Arc::new(AtomicBool::new(false));
        let cancel_clone = cancelled.clone();
        let _cancel_monitor: tokio::task::JoinHandle<()> = tokio::spawn(async move {
            while !cancel.is_cancelled() {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
            cancel_clone.store(true, Ordering::SeqCst);
            kill_process_group(pid);
        });

        // Wait for the process to exit, with optional timeout and streaming updates
        let timeout_dur = timeout.map(std::time::Duration::from_secs);
        loop {
            // Check cancellation
            if cancelled.load(Ordering::SeqCst) {
                kill_process_group(pid);
                read_task.abort();
                return Err(anyhow::anyhow!("Command aborted"));
            }

            // Check timeout
            if let Some(dur) = timeout_dur
                && started_at.elapsed() > dur
            {
                kill_process_group(pid);
                read_task.abort();
                return Err(anyhow::anyhow!(
                    "Command timed out after {} seconds",
                    timeout.unwrap_or(0)
                ));
            }

            // Send streaming update (1s tick interval, matching pi)
            if let Some(ref tx) = on_update {
                let out = combined.lock().await;
                if !out.is_empty() {
                    let elapsed = started_at.elapsed();
                    let display = format!(
                        "{}\n\n[Elapsed {:.1}s]",
                        out.trim_end(),
                        elapsed.as_secs_f64()
                    );
                    let _ = tx.send(ToolOutput::ok(display));
                }
            }

            // Check if process has exited
            match child.try_wait() {
                Ok(Some(status)) => {
                    read_task.await.ok();
                    let combined_str = combined.lock().await.clone();
                    let exit_code = status.code().unwrap_or(-1);

                    return finish_bash_execution(
                        command,
                        &combined_str,
                        exit_code,
                        false,
                        started_at,
                        on_update,
                    );
                }
                Ok(None) => {
                    // Still running, poll again soon (1s tick, matching pi)
                    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
                }
                Err(_) => {
                    read_task.await.ok();
                    let combined_str = combined.lock().await.clone();
                    let exit_code = -1;
                    return finish_bash_execution(
                        command,
                        &combined_str,
                        exit_code,
                        false,
                        started_at,
                        on_update,
                    );
                }
            }
        }
    }
}

/// Tool renderer for the `bash` tool.
/// Formats call headers with `$ command` and result with tail-based preview.
struct BashRenderer;

// ── Command detection for better headers ────────────────────────

/// Try to extract a meaningful description from a command string.
/// Returns (command_name, description) if recognized.
fn parse_command(cmd: &str) -> Option<(&'static str, Option<String>)> {
    let trimmed = cmd.trim();

    // Skip leading env vars (VAR=value) and cd commands
    let effective = {
        let mut rest = trimmed;
        loop {
            // Check for VAR=value pattern
            if let Some(eq_pos) = rest.find('=') {
                let var_name = &rest[..eq_pos];
                // Valid env var name: only alphanumeric and underscore
                if !var_name.is_empty() && var_name.chars().all(|c| c.is_alphanumeric() || c == '_')
                {
                    // Skip past the value (space-separated or end)
                    let after_eq = &rest[eq_pos + 1..];
                    if let Some(space_pos) = after_eq.find(' ') {
                        rest = after_eq[space_pos + 1..].trim_start();
                        continue;
                    } else {
                        // No space after value - this is just a VAR=value command
                        rest = "";
                        break;
                    }
                }
            }
            break;
        }
        rest
    };

    // ls
    if effective.starts_with("ls ") || effective == "ls" {
        let path = extract_ls_path(effective);
        return Some(("ls", path));
    }

    // grep
    if effective.starts_with("grep ") || effective.starts_with("rg ") {
        let info = extract_grep_info(effective);
        return Some(("grep", info));
    }

    // find
    if effective.starts_with("find ") {
        let info = extract_find_info(effective);
        return Some(("find", info));
    }

    // cat
    if effective.starts_with("cat ") || effective == "cat" {
        let path = effective.strip_prefix("cat ").map(|s| s.trim().to_string());
        return Some(("cat", path));
    }

    // head/tail
    if effective.starts_with("head ") || effective.starts_with("tail ") {
        let (cmd_name, rest) = if effective.starts_with("head") {
            ("head", effective.strip_prefix("head").unwrap_or(""))
        } else {
            ("tail", effective.strip_prefix("tail").unwrap_or(""))
        };
        let path = rest.trim();
        let path_opt = if path.is_empty() {
            None
        } else {
            Some(path.to_string())
        };
        return Some((cmd_name, path_opt));
    }

    // wc
    if effective.starts_with("wc ") || effective == "wc" {
        let path = effective.strip_prefix("wc ").map(|s| s.trim().to_string());
        return Some(("wc", path));
    }

    None
}

/// Extract path argument from ls command.
fn extract_ls_path(cmd: &str) -> Option<String> {
    // Simple: ls [path]
    let args = cmd.strip_prefix("ls").unwrap_or("").trim();
    if args.is_empty() {
        Some(".".to_string())
    } else {
        // Take last non-flag argument
        args.split_whitespace()
            .rfind(|a| !a.starts_with('-'))
            .map(|s| s.to_string())
    }
}

/// Extract search info from grep command.
fn extract_grep_info(cmd: &str) -> Option<String> {
    let args = cmd
        .strip_prefix("grep")
        .or_else(|| cmd.strip_prefix("rg"))
        .unwrap_or("")
        .trim();
    if args.is_empty() {
        return None;
    }
    // Find the pattern (first non-flag argument)
    let mut pattern = None;
    let mut files = Vec::new();
    let mut skip_next = false;
    for arg in args.split_whitespace() {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg.starts_with('-') {
            // Flags that take a value
            if arg == "-n" || arg == "-C" || arg == "-A" || arg == "-B" || arg == "--max-count" {
                skip_next = true;
            }
            continue;
        }
        if pattern.is_none() {
            pattern = Some(arg);
        } else {
            files.push(arg);
        }
    }
    let mut desc = String::new();
    if let Some(p) = pattern {
        desc.push_str(p);
    }
    if !files.is_empty() {
        desc.push_str(" in ");
        desc.push_str(&files.join(", "));
    }
    if desc.is_empty() { None } else { Some(desc) }
}

/// Extract search info from find command.
fn extract_find_info(cmd: &str) -> Option<String> {
    let args = cmd.strip_prefix("find").unwrap_or("").trim();
    if args.is_empty() {
        return Some(".".to_string());
    }
    // Find path and name pattern
    let mut path = None;
    let mut name = None;
    let mut skip_next = false;
    for arg in args.split_whitespace() {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg == "-name" || arg == "-path" || arg == "-type" {
            skip_next = true;
            if arg == "-name" {
                // Next arg is the pattern
                continue;
            }
        }
        if arg.starts_with('-') {
            continue;
        }
        if path.is_none() {
            path = Some(arg);
        }
    }
    // Re-parse to get -name value
    let mut it = args.split_whitespace();
    while let Some(arg) = it.next() {
        if arg == "-name" {
            name = it.next();
        }
    }
    let mut desc = path.unwrap_or(".").to_string();
    if let Some(n) = name {
        desc.push_str(&format!(" (name={})", n));
    }
    Some(desc)
}

/// Format a header for recognized commands.
fn format_command_header(cmd: &str, theme: &dyn Theme) -> Option<String> {
    let (name, desc) = parse_command(cmd)?;
    let title = theme.fg("toolTitle", &theme.bold(name));
    let detail = desc
        .map(|d| format!(" {}", theme.fg("accent", &d)))
        .unwrap_or_default();
    Some(format!("{}{}", title, detail))
}

// ── Visual-line-aware truncation (delegated to shared module) ────

impl ToolRenderer for BashRenderer {
    fn render_call(
        &self,
        args: &serde_json::Value,
        _width: usize,
        theme: &dyn Theme,
        _ctx: &ToolRenderContext,
    ) -> Vec<String> {
        let cmd = args
            .get("command")
            .and_then(|v| v.as_str())
            .unwrap_or("...");
        let timeout = args.get("timeout").and_then(|v| v.as_i64());
        let timeout_suffix = timeout
            .map(|t| theme.fg("muted", &format!(" (timeout {}s)", t)))
            .unwrap_or_default();

        // Detect common commands and show them with a nicer header
        if let Some(header) = format_command_header(cmd, theme) {
            vec![format!("{}{}", header, timeout_suffix)]
        } else {
            vec![format!(
                "{}{}",
                theme.fg("toolTitle", &theme.bold(&format!("$ {}", cmd))),
                timeout_suffix
            )]
        }
    }

    fn render_result(
        &self,
        content: &str,
        width: usize,
        theme: &dyn Theme,
        ctx: &ToolRenderContext,
    ) -> Vec<String> {
        let mut lines: Vec<String> = Vec::new();

        // Strip truncation footer
        let clean = strip_context_truncation_footer(content);
        let all_lines: Vec<&str> = clean.split('\n').collect();

        if all_lines.is_empty() || (all_lines.len() == 1 && all_lines[0].is_empty()) {
            return lines;
        }

        // Visual-line-aware truncation (matching pi's truncateToVisualLines)
        let preview_count = 5;
        let (preview_lines, hidden_line_count) = if ctx.expanded {
            (all_lines.clone(), 0)
        } else {
            truncate_to_visual_lines(&all_lines, width, preview_count)
        };

        if !ctx.expanded && hidden_line_count > 0 {
            let hint = if ctx.expand_key.is_empty() {
                theme.fg("muted", &format!("... {} earlier lines", hidden_line_count))
            } else {
                theme.fg(
                    "muted",
                    &format!(
                        "... ({} earlier lines, {} to expand)",
                        hidden_line_count, ctx.expand_key
                    ),
                )
            };
            lines.push(hint);
        }

        let fg_key = if ctx.is_error { "error" } else { "toolOutput" };
        for line in &preview_lines {
            if line.is_empty() {
                lines.push(String::new());
            } else {
                lines.push(theme.fg(fg_key, line));
            }
        }

        // Duration
        if let Some(secs) = ctx.duration_secs {
            let is_complete = ctx.exit_code.is_some() || ctx.cancelled;
            let label = if is_complete { "Took" } else { "Elapsed" };
            lines.push(theme.fg("muted", &format!("{} {:.1}s", label, secs)));
        }

        // Status
        if ctx.cancelled {
            lines.push(theme.fg("warning", "(cancelled)"));
        } else if let Some(code) = ctx.exit_code
            && code != 0
        {
            lines.push(theme.fg("warning", &format!("(exit {})", code)));
        }

        // Truncation warnings
        if ctx.was_truncated {
            if let Some(ref path) = ctx.full_output_path {
                lines.push(theme.fg(
                    "warning",
                    &format!("Output truncated. Full output: {}", path),
                ));
            } else {
                lines.push(theme.fg("warning", "Output truncated."));
            }
        }

        lines
    }
}

/// Strip the context-truncation footer from bash output.
fn strip_context_truncation_footer(output: &str) -> String {
    let lines: Vec<&str> = output.lines().collect();
    if lines.len() < 3 {
        return output.to_string();
    }
    let last = lines.last().map_or("", |v| v).trim();
    if last.starts_with('[')
        && (last.contains("Showing lines") || last.contains("Showing last"))
        && last.contains("Full output:")
    {
        let before: Vec<&str> = lines[..lines.len() - 1].to_vec();
        if !before.is_empty() && before[before.len() - 1].is_empty() {
            before[..before.len() - 1].join("\n")
        } else {
            before.join("\n")
        }
    } else {
        output.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_tool() -> BashTool {
        BashTool {
            cwd: std::env::temp_dir(),
        }
    }

    #[tokio::test]
    async fn runs_simple_command() {
        let tool = make_tool();
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo hello"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(output.content.contains("hello"));
    }

    #[tokio::test]
    async fn captures_stderr() {
        let tool = make_tool();
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo err >&2"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(output.content.contains("err"));
    }

    #[tokio::test]
    async fn cancel_aborts() {
        let tool = make_tool();
        let cancel = Cancel::new();
        cancel.cancel();
        let result = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "sleep 10"}),
                cancel,
                None,
            )
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("cancelled") || err.contains("aborted"),
            "expected cancellation error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn timeout_works() {
        let tool = make_tool();
        let result = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "sleep 10", "timeout": 1}),
                Cancel::new(),
                None,
            )
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("timed out"));
    }

    #[test]
    fn test_truncate_tail_no_truncation() {
        let result = truncate_tail("hello\nworld\n", 2000, 50000);
        assert!(!result.truncated);
        assert_eq!(result.content, "hello\nworld\n");
    }

    #[test]
    fn test_truncate_tail_by_lines() {
        let content: String = (1..=5000).map(|i| format!("line {}\n", i)).collect();
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        assert!(result.content.starts_with("line 3001"));
        assert_eq!(result.content.lines().count(), 2000);
    }

    #[test]
    fn test_truncate_tail_by_bytes() {
        let content: String = (1..=100)
            .map(|i| format!("line {} {}\n", i, "x".repeat(1000)))
            .collect();
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        assert!(result.content.len() <= 50000);
        assert!(result.content.lines().count() < 100);
    }

    #[test]
    fn test_truncate_tail_partial_last_line() {
        // A single line that exceeds the byte limit
        let content = format!("short\n{}\n", "x".repeat(60000));
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        assert!(!result.content.starts_with("short"));
        assert!(result.content.len() <= 50000);
    }

    #[test]
    fn test_truncate_tail_empty() {
        let result = truncate_tail("", 2000, 50000);
        assert!(!result.truncated);
        assert_eq!(result.content, "");
    }

    // ── Exit code integration tests ──────────────────────────────

    #[tokio::test]
    async fn exit_code_nonzero() {
        let tool = make_tool();
        let result = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "exit 42"}),
                Cancel::new(),
                None,
            )
            .await;
        assert!(result.is_err(), "non-zero exit should return error");
        let err = result.unwrap_err().to_string();
        assert!(err.contains("exited with code 42"), "got: {}", err);
    }

    #[tokio::test]
    async fn exit_code_with_output() {
        let tool = make_tool();
        let result = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo before && exit 1"}),
                Cancel::new(),
                None,
            )
            .await;
        assert!(result.is_err(), "non-zero exit should return error");
        let err = result.unwrap_err().to_string();
        assert!(err.contains("before"), "got: {}", err);
        assert!(err.contains("exited with code 1"), "got: {}", err);
    }

    #[tokio::test]
    async fn no_output() {
        let tool = make_tool();
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "true"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(
            output.content.contains("(no output)"),
            "got: {}",
            output.content
        );
    }

    #[tokio::test]
    async fn combined_stdout_stderr() {
        let tool = make_tool();
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo out; echo err >&2"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(output.content.contains("out"), "got: {}", output.content);
        assert!(output.content.contains("err"), "got: {}", output.content);
    }

    #[tokio::test]
    async fn runs_in_cwd() {
        let tmp = std::env::temp_dir().join(format!("rab-bash-cwd-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("marker.txt"), "hello").unwrap();

        let tool = BashTool { cwd: tmp.clone() };
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "cat marker.txt"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(output.content.contains("hello"), "got: {}", output.content);
    }

    #[tokio::test]
    async fn missing_command_errors() {
        let tool = make_tool();
        let result = tool
            .execute("id".into(), serde_json::json!({}), Cancel::new(), None)
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("command"), "got: {}", err);
    }

    #[tokio::test]
    async fn timeout_with_partial_output() {
        let tool = make_tool();
        // Command that produces some output then hangs
        let result = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo start && sleep 10 && echo end", "timeout": 1}),
                Cancel::new(),
                None,
            )
            .await;
        // May timeout before process is killed, which is fine
        // The key is it doesn't hang forever
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("timed out"), "got: {}", err);
    }

    #[tokio::test]
    async fn cancel_during_long_command() {
        let tool = make_tool();
        let cancel = Cancel::new();
        let cancel_clone = cancel.clone();

        let handle = tokio::spawn(async move {
            tool.execute(
                "id".into(),
                serde_json::json!({"command": "sleep 30"}),
                cancel_clone,
                None,
            )
            .await
        });

        // Give it a moment to start
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        cancel.cancel();

        let result = handle.await.unwrap();
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("aborted") || err.contains("cancelled"),
            "expected cancellation error, got: {}",
            err
        );
    }

    // ── Truncation boundary tests ────────────────────────────────

    #[test]
    fn test_truncate_tail_exact_line_fit() {
        // Content exactly at the line limit - no truncation
        let lines: String = (1..=2000).map(|i| format!("line {}\n", i)).collect();
        let result = truncate_tail(&lines, 2000, 50000);
        assert!(
            !result.truncated,
            "should not truncate when exactly at line limit"
        );
        assert!(result.content.lines().count() == 2000);
    }

    #[test]
    fn test_truncate_tail_one_over_line_limit() {
        let lines: String = (1..=2001).map(|i| format!("line {}\n", i)).collect();
        let result = truncate_tail(&lines, 2000, 50000);
        assert!(result.truncated);
        assert_eq!(result.content.lines().count(), 2000);
        // Should keep last 2000 lines
        assert!(result.content.starts_with("line 2"));
    }

    #[test]
    fn test_truncate_tail_exact_byte_fit() {
        // Content exactly at byte limit - no truncation
        let line = "a".repeat(50000);
        let result = truncate_tail(&line, 2000, 50000);
        assert!(!result.truncated);
    }

    #[test]
    fn test_truncate_tail_one_byte_over() {
        // Content one byte over the limit
        let line = "a".repeat(50001);
        let result = truncate_tail(&line, 2000, 50000);
        assert!(result.truncated);
        assert!(result.content.len() <= 50000);
    }

    #[test]
    fn test_truncate_tail_single_line_under_limit() {
        let result = truncate_tail("hello world", 2000, 50000);
        assert!(!result.truncated);
        assert_eq!(result.content, "hello world");
    }

    #[test]
    fn test_truncate_tail_trailing_newline() {
        let result = truncate_tail("a\nb\n", 2000, 50000);
        assert!(!result.truncated);
        assert_eq!(result.content, "a\nb\n");
    }

    #[test]
    fn test_truncate_tail_no_trailing_newline() {
        let result = truncate_tail("a\nb", 2000, 50000);
        assert!(!result.truncated);
        assert_eq!(result.content, "a\nb");
    }

    #[test]
    fn test_truncate_tail_single_line_exceeds_limit() {
        let content = "x".repeat(60000);
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        assert!(result.last_line_partial);
        // Should keep the last 50000 bytes of the line
        assert_eq!(result.content.len(), 50000);
        assert!(result.content.ends_with("x".repeat(50000).as_str()));
    }

    #[test]
    fn test_truncate_tail_byte_count_respects_newlines() {
        // Each line is 1000 bytes, 50 lines = 50KB, plus 49 newlines = ~49 bytes extra
        // At 2000 line limit, byte limit should be hit first
        let content: String = (1..=100)
            .map(|i| format!("line {} {}\n", i, "x".repeat(1000)))
            .collect();
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        // Output bytes should be at most 50000 (byte limit)
        assert!(
            result.output_bytes <= 50000,
            "output_bytes {} exceeds limit 50000",
            result.output_bytes
        );
    }

    // ── Truncation footer tests ─────────────────────────────────

    #[tokio::test]
    async fn truncated_by_lines_shows_footer() {
        let tool = make_tool();
        // Generate 3000 lines of output (exceeds 2000 line limit)
        let cmd = "for i in $(seq 1 3000); do echo \"line $i\"; done";
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": cmd}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        assert!(
            output.content.contains("Showing lines"),
            "got: {}",
            output.content
        );
        assert!(
            output.content.contains("Full output:"),
            "got: {}",
            output.content
        );
    }

    #[tokio::test]
    async fn small_output_no_footer() {
        let tool = make_tool();
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": "echo hello"}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        // Small output should not have footer markers
        assert!(
            !output.content.contains("Output truncated"),
            "got: {}",
            output.content
        );
        assert!(
            !output.content.contains("Full output:"),
            "got: {}",
            output.content
        );
    }

    #[tokio::test]
    async fn truncated_saves_temp_file() {
        let tool = make_tool();
        // Generate enough output to exceed line limit
        let cmd = "for i in $(seq 1 3000); do echo \"line $i\"; done";
        let output = tool
            .execute(
                "id".into(),
                serde_json::json!({"command": cmd}),
                Cancel::new(),
                None,
            )
            .await
            .unwrap();
        // Should mention a temp file path
        assert!(
            output.content.contains("/rab-bash/"),
            "expected temp file path, got: {}",
            output.content
        );
    }

    // ── Truncate tail: many short lines ──────────────────────────

    #[test]
    fn test_truncate_tail_many_short_lines() {
        // 10000 very short lines, well under byte limit
        let content: String = (1..=10000).map(|i| format!("{}\n", i)).collect();
        let result = truncate_tail(&content, 2000, 50000);
        assert!(result.truncated);
        assert_eq!(result.truncated_by, "lines");
        assert_eq!(result.output_lines, 2000);
        // Should keep the last 2000 lines
        assert!(
            result.content.starts_with("8001"),
            "starts with: {:?}",
            &result.content[..10]
        );
    }

    #[test]
    fn test_truncate_tail_lines_and_bytes_both_exceeded() {
        // Both limits exceeded - byte limit should win (more restrictive)
        let content: String = (1..=5000)
            .map(|i| format!("line {} {}\n", i, "x".repeat(100)))
            .collect();
        let result = truncate_tail(&content, 2000, 30000);
        assert!(result.truncated);
        // With 100-byte lines, 300 lines would be ~30KB + newlines
        // So byte limit should be hit before line limit
        assert_eq!(result.truncated_by, "bytes");
        assert!(result.output_lines < 2000);
    }
}

#[cfg(test)]
mod command_tests {
    use super::*;

    #[test]
    fn test_parse_ls() {
        let result = parse_command("ls -la src/");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "ls");
        assert_eq!(desc, Some("src/".to_string()));
    }

    #[test]
    fn test_parse_ls_default() {
        let result = parse_command("ls");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "ls");
        assert_eq!(desc, Some(".".to_string()));
    }

    #[test]
    fn test_parse_grep() {
        let result = parse_command("grep -r \"pattern\" src/");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "grep");
        assert!(desc.is_some());
        let desc = desc.unwrap();
        assert!(desc.contains("pattern"));
        assert!(desc.contains("src/"));
    }

    #[test]
    fn test_parse_rg() {
        let result = parse_command("rg pattern src/");
        assert!(result.is_some());
        let (name, _) = result.unwrap();
        assert_eq!(name, "grep");
    }

    #[test]
    fn test_parse_find() {
        let result = parse_command("find . -name \"*.rs\"");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "find");
        assert!(desc.is_some());
        let desc = desc.unwrap();
        assert!(desc.contains("."));
        assert!(desc.contains("*.rs"));
    }

    #[test]
    fn test_parse_cat() {
        let result = parse_command("cat README.md");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "cat");
        assert_eq!(desc, Some("README.md".to_string()));
    }

    #[test]
    fn test_parse_head() {
        let result = parse_command("head -20 file.txt");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "head");
        assert_eq!(desc, Some("-20 file.txt".to_string()));
    }

    #[test]
    fn test_parse_tail() {
        let result = parse_command("tail -f log.txt");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "tail");
        assert_eq!(desc, Some("-f log.txt".to_string()));
    }

    #[test]
    fn test_parse_wc() {
        let result = parse_command("wc -l file.txt");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "wc");
        assert_eq!(desc, Some("-l file.txt".to_string()));
    }

    #[test]
    fn test_parse_unknown() {
        let result = parse_command("echo hello");
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_with_env() {
        let result = parse_command("FOO=bar ls src/");
        assert!(result.is_some());
        let (name, desc) = result.unwrap();
        assert_eq!(name, "ls");
        assert_eq!(desc, Some("src/".to_string()));
    }
}