winx-code-agent 0.2.307

High-performance Rust implementation of WCGW for LLM code agents
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
//! Implementation of the `BashCommand` tool with WCGW parity.
//!
//! This module provides the implementation for the `BashCommand` tool, which is used
//! to execute shell commands, check command status, and interact with the shell.
//! Matches the behavior of wcgw Python implementation 1:1.

use anyhow::Context as AnyhowContext;
use rand::RngExt;
use regex::Regex;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};

use crate::errors::{Result, WinxError};
use crate::state::bash_state::BashState;
use crate::state::pty::PtyShell;
use crate::state::terminal::{render_terminal_output, strip_ansi_codes};
use crate::types::{normalize_thread_id, BashCommand, BashCommandAction, SpecialKey};

type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;

// ==================== WCGW-Style Constants ====================

/// Default timeout for command execution (seconds) - matches WCGW Python Config.timeout
const DEFAULT_TIMEOUT: f64 = 5.0;

/// Extended timeout while output is still being produced - matches WCGW Python `Config.timeout_while_output`
const TIMEOUT_WHILE_OUTPUT: f64 = 20.0;

/// Number of iterations to wait without new output before giving up - matches WCGW Python `Config.output_wait_patience`
const OUTPUT_WAIT_PATIENCE: i32 = 3;

/// Chunk size for sending commands (characters) - matches WCGW Python (64 chars)
const COMMAND_CHUNK_SIZE: usize = 64;

/// Chunk size for sending text input (characters) - matches WCGW Python (128 chars)
const TEXT_CHUNK_SIZE: usize = 128;

/// Maximum output length to prevent excessive responses
const MAX_OUTPUT_LENGTH: usize = 100_000;

/// Message when a command is already running - matches WCGW Python `WAITING_INPUT_MESSAGE`
const WAITING_INPUT_MESSAGE: &str = "A command is already running. NOTE: You can't run multiple shell commands in main shell, likely a previous program hasn't exited.
1. Get its output using status check.
2. Use `send_ascii` or `send_specials` to give inputs to the running program OR
3. kill the previous program by sending ctrl+c first using `send_ascii` or `send_specials`
4. Interrupt and run the process in background
";

// ==================== Background Shell Manager ====================

/// Snapshot of a background shell that has exited but whose final output has not
/// yet been consumed by the caller. We keep it around so the next call (typically
/// a `status_check`) can return the trailing output before the entry is gone.
#[derive(Debug, Clone)]
pub struct ExitedShellInfo {
    pub last_command: String,
    pub final_output: String,
    pub exited_at: Instant,
}

/// Manages background shell sessions - matches WCGW Python's `background_shells` dict
#[derive(Debug, Default)]
pub struct BackgroundShellManager {
    shells: HashMap<String, SharedPtyShell>,
    /// Recently exited shells that still owe their final output to the caller.
    /// Entries are consumed the first time the caller queries the id, then dropped.
    tombstones: HashMap<String, ExitedShellInfo>,
}

impl BackgroundShellManager {
    /// Tombstones older than this are garbage-collected on the next prune pass.
    const TOMBSTONE_TTL: Duration = Duration::from_secs(300);

    /// Create a new background shell manager
    pub fn new() -> Self {
        Self { shells: HashMap::new(), tombstones: HashMap::new() }
    }

    /// Start a new background shell and return its command ID
    pub fn start_new_shell(&mut self, working_dir: &Path, restricted_mode: bool) -> Result<String> {
        let cid = format!("{:010x}", rand::rng().random::<u32>());

        let shell = PtyShell::new(working_dir, restricted_mode).map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to start background shell: {e}"))
        })?;

        self.shells.insert(cid.clone(), Arc::new(Mutex::new(Some(shell))));

        info!("Started background shell with id: {}", cid);
        Ok(cid)
    }

    /// Get a background shell by its command ID
    pub fn get_shell(&self, bg_command_id: &str) -> Option<SharedPtyShell> {
        self.shells.get(bg_command_id).cloned()
    }

    /// Remove and cleanup a background shell
    pub fn remove_shell(&mut self, bg_command_id: &str) -> bool {
        if let Some(shell_arc) = self.shells.remove(bg_command_id) {
            if let Ok(mut guard) = shell_arc.try_lock() {
                *guard = None;
            }
            info!("Removed background shell: {}", bg_command_id);
            true
        } else {
            false
        }
    }

    fn prune_finished_shells(&mut self) {
        // GC old tombstones first.
        let now = Instant::now();
        self.tombstones.retain(|_, info| now.duration_since(info.exited_at) < Self::TOMBSTONE_TTL);

        let mut finished: Vec<(String, Option<ExitedShellInfo>)> = Vec::new();

        for (id, shell_arc) in &self.shells {
            let Ok(mut guard) = shell_arc.try_lock() else {
                continue;
            };

            let Some(shell) = guard.as_mut() else {
                finished.push((id.clone(), None));
                continue;
            };

            if !shell.is_alive() {
                let tombstone = ExitedShellInfo {
                    last_command: shell.last_command.clone(),
                    final_output: shell.output_buffer.clone(),
                    exited_at: now,
                };
                finished.push((id.clone(), Some(tombstone)));
                continue;
            }

            // Never prune shells that haven't received a command yet.
            // The global BG_SHELL_MANAGER is shared across parallel tests; a freshly
            // spawned shell would otherwise be evicted between start_new_shell and
            // the first send_command, leading to "Failed to get background shell".
            if shell.last_command.is_empty() {
                continue;
            }

            if shell.command_running {
                let _ = shell.read_output(0.1);
            }

            if !shell.command_running {
                let tombstone = ExitedShellInfo {
                    last_command: shell.last_command.clone(),
                    final_output: shell.output_buffer.clone(),
                    exited_at: now,
                };
                finished.push((id.clone(), Some(tombstone)));
            }
        }

        for (id, tombstone) in finished {
            self.remove_shell(&id);
            if let Some(info) = tombstone {
                self.tombstones.insert(id, info);
            }
        }
    }

    /// Pop the tombstone for a recently-exited shell, if any. The caller takes
    /// ownership of the final output; subsequent queries will return None.
    pub fn take_tombstone(&mut self, bg_command_id: &str) -> Option<ExitedShellInfo> {
        self.tombstones.remove(bg_command_id)
    }

    /// Get info about all running background shells - matches WCGW Python `get_bg_running_commandsinfo`
    pub fn get_running_info(&mut self) -> String {
        self.prune_finished_shells();

        if self.shells.is_empty() {
            return "No command running in background.\n".to_string();
        }

        let mut running = Vec::new();
        for (id, shell_arc) in &self.shells {
            if let Ok(guard) = shell_arc.try_lock() {
                if let Some(bash) = guard.as_ref() {
                    if bash.command_running {
                        running
                            .push(format!("Command: {}, bg_command_id: {}", bash.last_command, id));
                    }
                }
            } else {
                running.push(format!("Command: <busy>, bg_command_id: {id}"));
            }
        }

        if running.is_empty() {
            "No command running in background.\n".to_string()
        } else {
            format!("Following background commands are attached:\n{}\n", running.join("\n"))
        }
    }
}

// Global background shell manager (thread-safe) - matches WCGW Python's BashState.background_shells
lazy_static::lazy_static! {
    static ref BG_SHELL_MANAGER: StdMutex<BackgroundShellManager> = StdMutex::new(BackgroundShellManager::new());
}

// ==================== WCGW-Style Helper Functions ====================

/// Get WCGW-style status string - matches WCGW Python's `get_status()`
fn get_status(
    bash_state: &BashState,
    is_bg: bool,
    bg_id: Option<&str>,
    is_running: bool,
    running_for: Option<&str>,
) -> String {
    let mut status = "\n\n---\n\n".to_string();

    if is_bg {
        if let Some(id) = bg_id {
            let _ = writeln!(status, "bg_command_id = {id}");
        }
    }

    if is_running {
        status.push_str("status = still running\n");
        if let Some(duration) = running_for {
            let _ = writeln!(status, "running for = {duration}");
        }
    } else {
        status.push_str("status = process exited\n");
    }

    let _ = writeln!(status, "cwd = {}", bash_state.cwd.display());

    if !is_bg {
        // Add background shell info for main shell - matches WCGW Python
        if let Ok(mut manager) = BG_SHELL_MANAGER.lock() {
            status.push_str("This is the main shell. ");
            status.push_str(&manager.get_running_info());
        }
    }

    status.trim_end().to_string()
}

/// Process output with WCGW-style incremental text handling - matches WCGW Python _`incremental_text`
fn wcgw_incremental_text(text: &str, last_pending_output: &str) -> String {
    let text =
        if text.len() > MAX_OUTPUT_LENGTH { &text[text.len() - MAX_OUTPUT_LENGTH..] } else { text };

    if last_pending_output.is_empty() {
        let rendered = render_terminal_output(text);
        return rstrip_lines(&rendered).trim_start().to_string();
    }

    let last_rendered = render_terminal_output(last_pending_output);
    if last_rendered.is_empty() {
        return rstrip_lines(&render_terminal_output(text));
    }

    // Get text after last pending output
    let text_after_last = if text.len() > last_pending_output.len() {
        &text[last_pending_output.len()..]
    } else {
        text
    };

    let combined = format!("{}\n{}", last_rendered.join("\n"), text_after_last);
    let new_rendered = render_terminal_output(&combined);

    // Get incremental part - matches WCGW Python get_incremental_output
    let incremental = get_incremental_output(&last_rendered, &new_rendered);
    rstrip_lines(&incremental)
}

fn extract_prompt_cwd(output: &str) -> Option<PathBuf> {
    let stripped = strip_ansi_codes(output);
    let prompt_regex = Regex::new(r"◉ (?P<cwd>[^\r\n]*?)──➤").ok()?;

    prompt_regex
        .captures_iter(&stripped)
        .filter_map(|captures| captures.name("cwd").map(|cwd| cwd.as_str().trim()))
        .filter(|cwd| !cwd.is_empty())
        .last()
        .map(PathBuf::from)
}

/// Right-strip each line and join - matches WCGW Python rstrip
fn rstrip_lines(lines: &[String]) -> String {
    lines.iter().map(|line| line.trim_end()).collect::<Vec<_>>().join("\n")
}

/// Get incremental output between old and new - matches WCGW Python `get_incremental_output`
fn get_incremental_output(old_output: &[String], new_output: &[String]) -> Vec<String> {
    if old_output.is_empty() {
        return new_output.to_vec();
    }

    let nold = old_output.len();
    let nnew = new_output.len();

    // Find where old output ends in new output
    for i in (0..nnew).rev() {
        if new_output[i] != old_output[nold - 1] {
            continue;
        }

        let mut matched = true;
        for j in (0..i).rev() {
            let old_idx = (nold as i64 - 1 + j as i64 - i as i64) as isize;
            if old_idx < 0 {
                break;
            }
            if new_output[j] != old_output[old_idx as usize] {
                matched = false;
                break;
            }
        }

        if matched {
            return new_output[i + 1..].to_vec();
        }
    }

    new_output.to_vec()
}

fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
    let mut start = 0;

    while start < text.len() {
        let mut end = (start + chunk_size).min(text.len());
        while !text.is_char_boundary(end) {
            end -= 1;
        }
        if end == start {
            end = text[start..].char_indices().nth(1).map_or(text.len(), |(idx, _)| start + idx);
        }

        shell.send_text(&text[start..end]).map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to write PTY input: {e}"))
        })?;
        start = end;
    }

    Ok(())
}

/// Check if action is effectively a status check - matches WCGW Python `is_status_check`
#[allow(dead_code)]
fn is_status_check_action(action: &BashCommandAction) -> bool {
    match action {
        BashCommandAction::StatusCheck { .. } => true,
        BashCommandAction::SendSpecials { send_specials, .. } => {
            send_specials.len() == 1 && send_specials[0] == SpecialKey::Enter
        }
        BashCommandAction::SendAscii { send_ascii, .. } => {
            send_ascii.len() == 1 && send_ascii[0] == 10 // newline
        }
        _ => false,
    }
}

// ==================== Main Tool Handler ====================

/// Handles the `BashCommand` tool call with WCGW parity
///
/// This function processes the `BashCommand` tool call following WCGW Python's
/// `execute_bash()` function behavior exactly.
#[tracing::instrument(level = "info", skip(bash_state_arc, bash_command))]
pub async fn handle_tool_call(
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    bash_command: BashCommand,
) -> Result<String> {
    info!("BashCommand tool called with: {:?}", bash_command);

    let thread_id = normalize_thread_id(&bash_command.thread_id);

    // Check if thread_id is empty
    if thread_id.is_empty() {
        error!("Empty thread_id provided in BashCommand");
        return Err(WinxError::ThreadIdMismatch(
            "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID.".to_string()
        ));
    }

    // Extract bash_state data
    let mut bash_state: BashState;
    {
        let bash_state_guard = bash_state_arc.lock().await;

        let Some(state) = &*bash_state_guard else {
            error!("BashState not initialized");
            return Err(WinxError::BashStateNotInitialized);
        };

        bash_state = state.clone();
    }

    // Verify thread ID matches - matches WCGW Python thread_id check
    if thread_id != bash_state.current_thread_id {
        // Try to load state from thread_id - matches WCGW Python load_state_from_thread_id
        if !bash_state.load_state_from_disk(&thread_id).unwrap_or(false) {
            return Err(WinxError::ThreadIdMismatch(format!(
                "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
            )));
        }
    }

    // Calculate effective timeout - matches WCGW Python
    // SECURITY: Ensure timeout is not negative to prevent unexpected behavior
    let timeout_s = bash_command
        .wait_for_seconds
        .map_or(DEFAULT_TIMEOUT, |t| f64::from(t).max(0.0))
        .min(TIMEOUT_WHILE_OUTPUT);

    // Execute the action based on type - matches WCGW Python's _execute_bash()
    let result = execute_bash_action(&mut bash_state, &bash_command.action_json, timeout_s).await;

    {
        let mut bash_state_guard = bash_state_arc.lock().await;
        if let Some(state) = bash_state_guard.as_mut() {
            state.cwd.clone_from(&bash_state.cwd);
        }
    }

    // Remove echo if it's a command - matches WCGW Python
    match result {
        Ok(mut output) => {
            if let BashCommandAction::Command { ref command, .. } = bash_command.action_json {
                let cmd_trimmed = command.trim();
                if output.starts_with(cmd_trimmed) {
                    output = output[cmd_trimmed.len()..].to_string();
                }
            }
            Ok(output)
        }
        Err(e) => Err(e),
    }
}

/// Execute a bash action - matches WCGW Python's _`execute_bash()` function
async fn execute_bash_action(
    bash_state: &mut BashState,
    action: &BashCommandAction,
    timeout_s: f64,
) -> Result<String> {
    let mut is_bg = false;
    let mut bg_id: Option<String> = None;

    // Handle bg_command_id routing - matches WCGW Python
    let bg_shell: Option<SharedPtyShell> = match action {
        BashCommandAction::Command { .. } => None, // Commands don't use bg_command_id for routing
        BashCommandAction::StatusCheck { bg_command_id, .. }
        | BashCommandAction::SendText { bg_command_id, .. }
        | BashCommandAction::SendSpecials { bg_command_id, .. }
        | BashCommandAction::SendAscii { bg_command_id, .. } => {
            if let Some(id) = bg_command_id {
                let mut manager = BG_SHELL_MANAGER.lock().map_err(|e| {
                    WinxError::BashStateLockError(format!("Failed to lock bg manager: {e}"))
                })?;
                manager.prune_finished_shells();

                if let Some(shell) = manager.get_shell(id) {
                    is_bg = true;
                    bg_id = Some(id.clone());
                    Some(shell)
                } else if let Some(tombstone) = manager.take_tombstone(id) {
                    // Shell already exited. For a status check we can hand back the
                    // final cached output exactly once. For anything else (send_text,
                    // send_specials, send_ascii) tell the caller the shell is gone
                    // and include the captured output so they can recover state.
                    drop(manager);
                    return finalize_tombstone(&bash_state.cwd, id, tombstone, action);
                } else {
                    // Error message matches WCGW Python
                    let error = format!(
                        "No shell found running with command id {}.\n{}",
                        id,
                        manager.get_running_info()
                    );
                    return Err(WinxError::CommandExecutionError(error));
                }
            } else {
                None
            }
        }
    };

    // Process based on action type - matches WCGW Python _execute_bash dispatch
    match action {
        BashCommandAction::Command { command, is_background } => {
            execute_command(bash_state, command, *is_background, timeout_s).await
        }
        BashCommandAction::StatusCheck { .. } => {
            execute_status_check(bash_state, bg_shell, is_bg, bg_id.as_deref(), timeout_s).await
        }
        BashCommandAction::SendText { send_text, submit, .. } => {
            execute_send_text(
                bash_state,
                send_text,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
        BashCommandAction::SendSpecials { send_specials, submit, .. } => {
            execute_send_specials(
                bash_state,
                send_specials,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
        BashCommandAction::SendAscii { send_ascii, submit, .. } => {
            execute_send_ascii(
                bash_state,
                send_ascii,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
    }
}

/// Execute a command - matches WCGW Python's Command handling in _`execute_bash`
async fn execute_command(
    bash_state: &mut BashState,
    command: &str,
    is_background: bool,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing Command action: {}", command);

    // Check mode permissions - matches WCGW Python bash_command_mode check
    if !bash_state.is_command_allowed(command) {
        error!("Command '{}' not allowed in current mode", command);
        return Err(WinxError::CommandNotAllowed(
            "Error: BashCommand not allowed in current mode".to_string(),
        ));
    }

    // Validate single statement - matches WCGW Python assert_single_statement
    let command = command.trim();
    crate::utils::bash_parser::assert_single_statement(command)?;

    // If background execution requested, start new shell - matches WCGW Python is_background handling
    if is_background {
        return execute_in_background(bash_state, command, timeout_s).await;
    }

    // Check if a command is already running - matches WCGW Python state check
    {
        let bash_guard = bash_state.pty_shell.lock().await;

        if let Some(ref bash) = *bash_guard {
            if bash.command_running {
                return Err(WinxError::CommandExecutionError(WAITING_INPUT_MESSAGE.to_string()));
            }
        }
    }

    // Initialize bash if needed
    if bash_state.pty_shell.lock().await.is_none() {
        bash_state
            .init_pty_shell()
            .await
            .map_err(|e| WinxError::CommandExecutionError(format!("Failed to init bash: {e}")))?;
    }

    // Clear prompt before sending - matches WCGW Python clear_to_run
    // (simplified version - WCGW does more complex clearing)

    // Send command in chunks of 64 characters - matches WCGW Python exactly
    {
        let mut bash_guard = bash_state.pty_shell.lock().await;

        let bash = bash_guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        bash.output_buffer.clear();
        bash.output_truncated = false;
        // Send in chunks - matches WCGW Python: for i in range(0, len(command), 64)
        send_utf8_in_byte_chunks(bash, command, COMMAND_CHUNK_SIZE)?;

        // Send linesep to execute - matches WCGW Python bash_state.send(bash_state.linesep, ...)
        bash.send_special_key("Enter").map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to send newline: {e}"))
        })?;

        bash.last_command = command.to_string();
        bash.command_running = true;
    }

    // Wait for output with WCGW-style patience handling
    let shell_arc = bash_state.pty_shell.clone();
    wait_for_output(bash_state, &shell_arc, timeout_s, false, None, false).await
}

/// Wait for command output with WCGW-style patience handling - matches WCGW Python expect/wait logic.
///
/// `shell_arc` selects which shell to read from (main shell or a bg shell handle).
async fn wait_for_output(
    bash_state: &mut BashState,
    shell_arc: &SharedPtyShell,
    timeout_s: f64,
    is_bg: bool,
    bg_id: Option<&str>,
    is_status_check: bool,
) -> Result<String> {
    let start = Instant::now();
    let wait = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
    let mut last_pending_output = String::new();
    let mut complete = false;

    // Initial wait - matches WCGW Python wait = min(timeout_s or CONFIG.timeout, CONFIG.timeout_while_output)
    sleep(Duration::from_secs_f64(wait.min(DEFAULT_TIMEOUT))).await;

    // Read initial output
    let mut output = {
        let mut bash_guard = shell_arc.lock().await;

        if let Some(bash) = bash_guard.as_mut() {
            let (out, done) = bash.read_output(0.5).map_err(|e| {
                WinxError::CommandExecutionError(format!("Failed to read output: {e}"))
            })?;
            complete = done;
            out
        } else {
            String::new()
        }
    };

    // If not complete and this is a status check, use WCGW-style patience waiting
    // Matches WCGW Python: if is_status_check(bash_arg) block
    if !complete && is_status_check {
        let mut remaining = TIMEOUT_WHILE_OUTPUT - wait;
        let mut patience = OUTPUT_WAIT_PATIENCE;

        let incremental = wcgw_incremental_text(&output, &last_pending_output);
        if incremental.is_empty() {
            patience -= 1;
        }

        let mut last_incremental = incremental;

        while remaining > 0.0 && patience > 0 {
            sleep(Duration::from_secs_f64(wait.min(remaining))).await;

            let (new_output, done) = {
                let mut bash_guard = shell_arc.lock().await;

                if let Some(bash) = bash_guard.as_mut() {
                    bash.read_output(0.5).map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to read output: {e}"))
                    })?
                } else {
                    (String::new(), true)
                }
            };

            if done {
                complete = true;
                output = new_output;
                break;
            }

            // Check if output changed - matches WCGW Python patience logic
            let new_incremental = wcgw_incremental_text(&new_output, &last_pending_output);
            if new_incremental == last_incremental {
                patience -= 1;
            } else {
                patience = OUTPUT_WAIT_PATIENCE; // Reset patience on new output
            }
            last_incremental = new_incremental;

            output = new_output;
            remaining -= wait;
        }

        if !complete {
            // Update pending output - matches WCGW Python bash_state.set_pending(text)
            last_pending_output = output.clone();
        }
    }

    if complete {
        if let Some(cwd) = extract_prompt_cwd(&output) {
            bash_state.cwd = cwd;
        }
    }

    // Process output through terminal emulation - matches WCGW Python _incremental_text
    let rendered = wcgw_incremental_text(&output, &last_pending_output);

    // Truncate if needed - matches WCGW Python token truncation
    let rendered = if rendered.len() > MAX_OUTPUT_LENGTH {
        format!("(...truncated)\n{}", &rendered[rendered.len() - MAX_OUTPUT_LENGTH..])
    } else {
        rendered
    };

    // Calculate running duration for status
    let running_for = if complete {
        None
    } else {
        Some(format!("{} seconds", (start.elapsed().as_secs() + timeout_s as u64)))
    };

    // Add status - matches WCGW Python get_status
    let status = get_status(bash_state, is_bg, bg_id, !complete, running_for.as_deref());
    Ok(format!("{rendered}{status}"))
}

/// Render the final cached output of an exited background shell.
///
/// `status_check` is allowed to "consume" the tombstone and return the trailing
/// output exactly once. Send-style actions (`send_text`, `send_specials`,
/// `send_ascii`) cannot interact with a dead shell, so we return an explicit
/// error that still includes the captured output so the agent can recover state.
fn finalize_tombstone(
    cwd: &Path,
    id: &str,
    tombstone: ExitedShellInfo,
    action: &BashCommandAction,
) -> Result<String> {
    let ExitedShellInfo { last_command, final_output, .. } = tombstone;
    match action {
        BashCommandAction::StatusCheck { .. } => {
            let rendered = wcgw_incremental_text(&final_output, "");
            let rendered = if rendered.len() > MAX_OUTPUT_LENGTH {
                format!("(...truncated)\n{}", &rendered[rendered.len() - MAX_OUTPUT_LENGTH..])
            } else {
                rendered
            };
            // Build a compact status block matching `get_status` for a finished bg shell.
            let mut status = "\n\n---\n\n".to_string();
            let _ = writeln!(status, "bg_command_id = {id}");
            status.push_str("status = process exited\n");
            let _ = writeln!(status, "cwd = {}", cwd.display());
            Ok(format!("{rendered}{}", status.trim_end()))
        }
        BashCommandAction::SendText { .. }
        | BashCommandAction::SendSpecials { .. }
        | BashCommandAction::SendAscii { .. } => Err(WinxError::CommandExecutionError(format!(
            "Background shell {id} already exited (last command: {last_command}).\nFinal captured output:\n{final_output}"
        ))),
        BashCommandAction::Command { .. } => {
            // We only enter `finalize_tombstone` from the bg routing path, which
            // never matches Command. Treat this as a programmer error.
            unreachable!("finalize_tombstone called for non-bg action")
        }
    }
}

/// Execute a status check - matches WCGW Python's `StatusCheck` handling
async fn execute_status_check(
    bash_state: &mut BashState,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing StatusCheck action");

    // Pick the shell we're going to inspect: bg shell when bg_command_id was provided,
    // otherwise fall back to the main interactive shell.
    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());

    // Check if there's a running command - matches WCGW Python state check
    let is_running = {
        let guard = shell_arc.lock().await;
        if let Some(ref bash) = *guard {
            bash.command_running
        } else {
            false
        }
    };

    // If no command running and not background, return error - matches WCGW Python
    if !is_running && !is_bg {
        let mut manager = BG_SHELL_MANAGER.lock().map_err(|e| {
            WinxError::BashStateLockError(format!("Failed to lock bg manager: {e}"))
        })?;
        let error =
            format!("No running command to check status of.\n{}", manager.get_running_info());
        return Err(WinxError::CommandExecutionError(error));
    }

    // Read output with patience handling - this IS a status check
    wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, true).await
}

/// Execute `send_text` - matches WCGW Python's `SendText` handling
async fn execute_send_text(
    bash_state: &mut BashState,
    text: &str,
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendText action: {text:?} (submit={submit})");

    // Validate - matches WCGW Python
    if text.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_text cannot be empty".to_string(),
        ));
    }

    // Get the target shell
    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());

    // Send text in chunks of 128 characters - matches WCGW Python exactly
    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send in chunks - matches WCGW Python: for i in range(0, len(command_data.send_text), 128)
        send_utf8_in_byte_chunks(bash, text, TEXT_CHUNK_SIZE)?;

        // Only append Enter when the caller explicitly asks to submit. Many TUIs
        // (e.g., Claude Code) treat a bare CR as a soft newline inside the input
        // box, so blindly auto-Entering interferes with multi-step interaction.
        if submit {
            bash.send_special_key("Enter").map_err(|e| {
                WinxError::CommandExecutionError(format!("Failed to send newline: {e}"))
            })?;
        }
    }

    // Wait for output
    wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await
}

/// Execute `send_specials` - matches WCGW Python's `SendSpecials` handling exactly
async fn execute_send_specials(
    bash_state: &mut BashState,
    keys: &[SpecialKey],
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendSpecials action: {keys:?} (submit={submit})");

    // Validate - matches WCGW Python
    if keys.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_specials cannot be empty".to_string(),
        ));
    }

    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let mut is_interrupt = false;

    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send each special key - matches WCGW Python exactly
        for key in keys {
            match key {
                SpecialKey::KeyUp => {
                    // matches WCGW Python: bash_state.send("\033[A", ...)
                    bash.send_special_key("KeyUp").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyUp: {e}"))
                    })?;
                }
                SpecialKey::KeyDown => {
                    // matches WCGW Python: bash_state.send("\033[B", ...)
                    bash.send_special_key("KeyDown").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyDown: {e}"))
                    })?;
                }
                SpecialKey::KeyLeft => {
                    // matches WCGW Python: bash_state.send("\033[D", ...)
                    bash.send_special_key("KeyLeft").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyLeft: {e}"))
                    })?;
                }
                SpecialKey::KeyRight => {
                    // matches WCGW Python: bash_state.send("\033[C", ...)
                    bash.send_special_key("KeyRight").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyRight: {e}"))
                    })?;
                }
                SpecialKey::Enter => {
                    // matches WCGW Python: bash_state.send("\x0d", ...) - carriage return
                    bash.send_special_key("Enter").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Enter: {e}"))
                    })?;
                }
                SpecialKey::CtrlC => {
                    // matches WCGW Python: bash_state.sendintr()
                    bash.send_interrupt().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send interrupt: {e}"))
                    })?;
                    is_interrupt = true;
                }
                SpecialKey::CtrlD => {
                    // matches WCGW Python: bash_state.sendintr() - same as Ctrl+C in WCGW
                    bash.send_eof().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+D: {e}"))
                    })?;
                    is_interrupt = true;
                }
                SpecialKey::CtrlZ => {
                    // Ctrl+Z = SIGTSTP (suspend) - ASCII 0x1a
                    bash.send_suspend().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+Z: {e}"))
                    })?;
                }
            }
        }
        // Submit (append Enter) only when explicitly requested by the caller.
        if submit {
            bash.send_special_key("Enter")
                .map_err(|e| WinxError::CommandExecutionError(format!("Failed to submit: {e}")))?;
        }
    }

    // Wait for output
    let mut output =
        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;

    // Add interrupt failure message if still running - matches WCGW Python exactly
    if is_interrupt && output.contains("status = still running") {
        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
    }

    Ok(output)
}

/// Execute `send_ascii` - matches WCGW Python's `SendAscii` handling
async fn execute_send_ascii(
    bash_state: &mut BashState,
    ascii_codes: &[u8],
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendAscii action: {ascii_codes:?} (submit={submit})");

    // Validate - matches WCGW Python
    if ascii_codes.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_ascii cannot be empty".to_string(),
        ));
    }

    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let mut is_interrupt = false;

    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send each ASCII code - matches WCGW Python
        for &code in ascii_codes {
            // matches WCGW Python: bash_state.send(chr(ascii_char), ...)
            bash.send_bytes(&[code]).map_err(|e| {
                WinxError::CommandExecutionError(format!("Failed to write ASCII code: {e}"))
            })?;

            // Check for interrupt - matches WCGW Python: if ascii_char == 3: is_interrupt = True
            if code == 3 {
                is_interrupt = true;
            }
        }
        // Submit (append Enter) only when explicitly requested by the caller.
        if submit {
            bash.send_special_key("Enter")
                .map_err(|e| WinxError::CommandExecutionError(format!("Failed to submit: {e}")))?;
        }
    }

    // Wait for output
    let mut output =
        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;

    // Add interrupt failure message if still running - matches WCGW Python
    if is_interrupt && output.contains("status = still running") {
        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
    }

    Ok(output)
}

/// Execute command in background - matches WCGW Python's `is_background` handling
async fn execute_in_background(
    bash_state: &mut BashState,
    command: &str,
    timeout_s: f64,
) -> Result<String> {
    debug!("Executing command in background: {}", command);

    // Start a new background shell - matches WCGW Python bash_state.start_new_bg_shell
    let restricted_mode =
        matches!(bash_state.bash_command_mode.bash_mode, crate::types::BashMode::RestrictedMode);

    let bg_id = {
        let mut manager = BG_SHELL_MANAGER.lock().map_err(|e| {
            WinxError::BashStateLockError(format!("Failed to lock bg manager: {e}"))
        })?;
        manager.start_new_shell(&bash_state.cwd, restricted_mode)?
    };

    // Get the shell
    let shell_arc = {
        let manager = BG_SHELL_MANAGER.lock().map_err(|e| {
            WinxError::BashStateLockError(format!("Failed to lock bg manager: {e}"))
        })?;
        manager.get_shell(&bg_id).ok_or_else(|| {
            WinxError::CommandExecutionError("Failed to get background shell".to_string())
        })?
    };

    // Send command via the same PTY path used by foreground execute_command.
    {
        let mut guard = shell_arc.lock().await;
        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
        bash.send_command(command).map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to send bg command: {e}"))
        })?;
    }
    debug!("bg[{}]: send_command returned, replying with bg_command_id", bg_id);

    let _ = timeout_s;
    let _ = shell_arc;
    Ok(get_status(bash_state, true, Some(&bg_id), true, None))
}

// ==================== Legacy Screen-based Functions (kept for backward compatibility) ====================

/// Process simple command execution for a bash command (legacy)
#[allow(dead_code)]
#[tracing::instrument(level = "debug", skip(command, cwd))]
async fn execute_simple_command(command: &str, cwd: &Path) -> Result<String> {
    debug!("Executing command: {}", command);

    let start_time = Instant::now();
    let mut cmd = Command::new("sh");
    cmd.arg("-c")
        .arg(command)
        .current_dir(cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let output = cmd.output().context("Failed to execute command")?;
    let elapsed = start_time.elapsed();

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    let raw_result = format!("{stdout}{stderr}");
    let mut result = raw_result.clone();
    if !raw_result.is_empty() {
        let rendered_lines = render_terminal_output(&raw_result);
        if rendered_lines.is_empty() {
            // Fallback: just strip ANSI codes if rendering failed or wasn't needed
            result = strip_ansi_codes(&raw_result);
        } else {
            result = rendered_lines.join("\n");
        }
    }

    if result.len() > MAX_OUTPUT_LENGTH {
        result = format!("(...truncated)\n{}", &result[result.len() - MAX_OUTPUT_LENGTH..]);
    }

    let exit_status = if output.status.success() {
        "Command completed successfully".to_string()
    } else {
        format!("Command failed with status: {}", output.status)
    };

    let current_dir = std::env::current_dir()
        .map_or_else(|_| "Unknown".to_string(), |p| p.to_string_lossy().into_owned());

    debug!("Command executed in {:.2?}", elapsed);
    Ok(format!("{result}\n\n---\n\nstatus = {exit_status}\ncwd = {current_dir}\n"))
}

/// Execute command in screen (legacy)
#[allow(dead_code)]
#[tracing::instrument(level = "debug", skip(command, cwd, screen_name))]
async fn execute_in_screen(command: &str, cwd: &Path, screen_name: &str) -> Result<String> {
    debug!("Executing command in screen session '{}': {}", screen_name, command);

    let screen_check = Command::new("which")
        .arg("screen")
        .output()
        .context("Failed to check for screen command")?;

    if !screen_check.status.success() {
        warn!("Screen command not found, falling back to direct execution");
        return execute_simple_command(command, cwd).await;
    }

    let _cleanup = Command::new("screen").args(["-X", "-S", screen_name, "quit"]).output();

    let screen_cmd = format!(
        "screen -dmS {} bash -c '{} ; ec=$? ; echo \"Command completed with exit code: $ec\" ; sleep 1 ; exit $ec'",
        screen_name,
        command.replace('\'', "'\\''")
    );

    let screen_start = Command::new("sh")
        .arg("-c")
        .arg(&screen_cmd)
        .current_dir(cwd)
        .output()
        .context("Failed to start screen session")?;

    if !screen_start.status.success() {
        let stderr = String::from_utf8_lossy(&screen_start.stderr).to_string();
        error!("Failed to start screen session: {}", stderr);
        return Err(WinxError::CommandExecutionError(format!(
            "Failed to start screen session: {stderr}"
        )));
    }

    sleep(Duration::from_millis(300)).await;

    let screen_check =
        Command::new("screen").args(["-ls"]).output().context("Failed to list screen sessions")?;

    let screen_list = String::from_utf8_lossy(&screen_check.stdout).to_string();

    let current_dir = std::env::current_dir()
        .map_or_else(|_| "Unknown".to_string(), |p| p.to_string_lossy().into_owned());

    Ok(format!(
        "Started command in background screen session '{screen_name}'.\n\
        Use status_check to get output.\n\n\
        Screen sessions:\n{screen_list}\n\
        ---\n\n\
        status = running in background\n\
        cwd = {current_dir}\n"
    ))
}

/// Converts a `SpecialKey` to its screen stuff input representation (legacy)
#[allow(dead_code)]
fn special_key_to_screen_input(key: SpecialKey) -> String {
    match key {
        SpecialKey::Enter => String::from("\r"),
        SpecialKey::KeyUp => String::from("\x1b[A"),
        SpecialKey::KeyDown => String::from("\x1b[B"),
        SpecialKey::KeyLeft => String::from("\x1b[D"),
        SpecialKey::KeyRight => String::from("\x1b[C"),
        SpecialKey::CtrlC => String::from("\x03"),
        SpecialKey::CtrlD => String::from("\x04"),
        SpecialKey::CtrlZ => String::from("\x1a"),
    }
}