Skip to main content

winx_code_agent/tools/
bash_command.rs

1//! Implementation of the `BashCommand` tool with WCGW parity.
2//!
3//! This module provides the implementation for the `BashCommand` tool, which is used
4//! to execute shell commands, check command status, and interact with the shell.
5//! Matches the behavior of wcgw Python implementation 1:1.
6
7use anyhow::Context as AnyhowContext;
8use rand::RngExt;
9use regex::Regex;
10use std::collections::HashMap;
11use std::fmt::Write as FmtWrite;
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex as StdMutex};
14use std::time::{Duration, Instant};
15use tokio::sync::Mutex;
16use tokio::time::sleep;
17use tracing::{debug, error, info, warn};
18
19use crate::errors::{Result, WinxError};
20use crate::state::bash_state::BashState;
21use crate::state::live_terminal::ScreenUpdate;
22use crate::state::pty::PtyShell;
23use crate::state::terminal::{render_terminal_output, strip_ansi_codes};
24use crate::types::{normalize_thread_id, BashCommand, BashCommandAction, SpecialKey};
25
26type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
27
28// ==================== WCGW-Style Constants ====================
29
30/// Default timeout for command execution (seconds) - matches WCGW Python Config.timeout
31const DEFAULT_TIMEOUT: f64 = 5.0;
32
33/// Extended timeout while output is still being produced - matches WCGW Python `Config.timeout_while_output`
34const TIMEOUT_WHILE_OUTPUT: f64 = 20.0;
35
36/// Number of iterations to wait without new output before giving up - matches WCGW Python `Config.output_wait_patience`
37const OUTPUT_WAIT_PATIENCE: i32 = 3;
38
39/// Polling slice for adaptive output reads. We read in chunks this long and
40/// return as soon as the prompt returns, instead of sleeping the full budget.
41const POLL_SLICE_SECS: f64 = 0.5;
42
43/// Chunk size for sending commands (characters) - matches WCGW Python (64 chars)
44const COMMAND_CHUNK_SIZE: usize = 64;
45
46/// Chunk size for sending text input (characters) - matches WCGW Python (128 chars)
47const TEXT_CHUNK_SIZE: usize = 128;
48
49/// Cheap byte-level safety net. We never even consider token counting if the
50/// raw payload is smaller than this — tokenizing is fast but not free, and
51/// the vast majority of responses are tiny status updates.
52const MAX_OUTPUT_LENGTH: usize = 100_000;
53
54/// Token budget reserved for a single PTY response when token-aware truncation
55/// kicks in. Picked to leave plenty of room for the surrounding context — most
56/// frontier models have 128k+ windows, so 25k for one shell payload is generous
57/// without monopolizing the conversation.
58const MAX_OUTPUT_TOKENS: usize = 25_000;
59
60/// Delay between typing text and the submitting Enter. Ink-based TUIs (Claude
61/// Code) collapse a burst of bytes into a single render tick and drop a CR that
62/// arrives glued to the text — the input box updates but never submits. Sending
63/// the Enter as a separate write after this short pause lets the TUI commit the
64/// typed text first, so `submit: true` reliably submits. ~40ms is imperceptible
65/// yet enough for the event loop to flush; harmless for plain shells.
66const SUBMIT_NUDGE_DELAY: Duration = Duration::from_millis(40);
67
68/// `screen` diff mode emits a per-line delta only when at most this many lines
69/// changed; beyond that the full frame is cheaper to read than a giant diff.
70const SCREEN_DIFF_THRESHOLD: usize = 10;
71
72/// Tail of `text` at most `max_len` bytes long, snapped up to a char boundary so
73/// we never slice through a multibyte UTF-8 sequence (which would panic).
74fn char_safe_tail(text: &str, max_len: usize) -> &str {
75    if text.len() <= max_len {
76        return text;
77    }
78    let mut start = text.len() - max_len;
79    while start < text.len() && !text.is_char_boundary(start) {
80        start += 1;
81    }
82    &text[start..]
83}
84
85/// Truncate `text` so its Claude token count stays under `max_tokens`.
86///
87/// We tokenize the tail of the string only when the raw byte length already
88/// exceeds the byte cap; otherwise we trust the byte budget and return as-is.
89/// When the tail still overshoots, we keep the last `max_tokens - reserve`
90/// tokens and prepend a "(...truncated)" marker — exactly what wcgw does in
91/// `_incremental_text`.
92fn truncate_to_token_budget(text: &str, max_tokens: usize) -> std::borrow::Cow<'_, str> {
93    if text.len() <= MAX_OUTPUT_LENGTH {
94        return std::borrow::Cow::Borrowed(text);
95    }
96
97    let Some(tokens) = crate::utils::encoder::encode_ids(text) else {
98        // Fallback to the byte-based truncation we used before the tokenizer.
99        return std::borrow::Cow::Owned(format!(
100            "(...truncated)\n{}",
101            char_safe_tail(text, MAX_OUTPUT_LENGTH)
102        ));
103    };
104
105    if tokens.len() <= max_tokens {
106        return std::borrow::Cow::Borrowed(text);
107    }
108
109    // Reserve one token slot for the marker overhead.
110    let keep = max_tokens.saturating_sub(1);
111    let tail = &tokens[tokens.len() - keep..];
112    let decoded = crate::utils::encoder::decode_ids(tail).unwrap_or_else(|| {
113        // Tokenizer present but decode failed: fall back to a byte tail.
114        char_safe_tail(text, MAX_OUTPUT_LENGTH).to_string()
115    });
116    std::borrow::Cow::Owned(format!("(...truncated)\n{decoded}"))
117}
118
119/// Message when a command is already running - matches WCGW Python `WAITING_INPUT_MESSAGE`
120const 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.
1211. Get its output using status check.
1222. Use `send_ascii` or `send_specials` to give inputs to the running program OR
1233. kill the previous program by sending ctrl+c first using `send_ascii` or `send_specials`
1244. Interrupt and run the process in background
125";
126
127// ==================== Background Shell Manager ====================
128
129/// Snapshot of a background shell that has exited but whose final output has not
130/// yet been consumed by the caller. We keep it around so the next call (typically
131/// a `status_check`) can return the trailing output before the entry is gone.
132#[derive(Debug, Clone)]
133pub struct ExitedShellInfo {
134    pub last_command: String,
135    pub final_output: String,
136    pub exited_at: Instant,
137}
138
139/// Manages background shell sessions - matches WCGW Python's `background_shells` dict
140#[derive(Debug, Default)]
141pub struct BackgroundShellManager {
142    shells: HashMap<String, SharedPtyShell>,
143    /// Recently exited shells that still owe their final output to the caller.
144    /// Entries are consumed the first time the caller queries the id, then dropped.
145    tombstones: HashMap<String, ExitedShellInfo>,
146}
147
148impl BackgroundShellManager {
149    /// Tombstones older than this are garbage-collected on the next prune pass.
150    const TOMBSTONE_TTL: Duration = Duration::from_secs(300);
151
152    /// Create a new background shell manager
153    pub fn new() -> Self {
154        Self { shells: HashMap::new(), tombstones: HashMap::new() }
155    }
156
157    /// Start a new background shell and return its command ID
158    pub fn start_new_shell(&mut self, working_dir: &Path, restricted_mode: bool) -> Result<String> {
159        let cid = format!("{:010x}", rand::rng().random::<u32>());
160
161        let shell = PtyShell::new(working_dir, restricted_mode).map_err(|e| {
162            WinxError::CommandExecutionError(format!("Failed to start background shell: {e}"))
163        })?;
164
165        self.shells.insert(cid.clone(), Arc::new(Mutex::new(Some(shell))));
166
167        info!("Started background shell with id: {}", cid);
168        Ok(cid)
169    }
170
171    /// Get a background shell by its command ID
172    pub fn get_shell(&self, bg_command_id: &str) -> Option<SharedPtyShell> {
173        self.shells.get(bg_command_id).cloned()
174    }
175
176    /// Remove and cleanup a background shell
177    pub fn remove_shell(&mut self, bg_command_id: &str) -> bool {
178        if let Some(shell_arc) = self.shells.remove(bg_command_id) {
179            if let Ok(mut guard) = shell_arc.try_lock() {
180                *guard = None;
181            }
182            info!("Removed background shell: {}", bg_command_id);
183            true
184        } else {
185            false
186        }
187    }
188
189    fn prune_finished_shells(&mut self) {
190        // GC old tombstones first.
191        let now = Instant::now();
192        self.tombstones.retain(|_, info| now.duration_since(info.exited_at) < Self::TOMBSTONE_TTL);
193
194        let mut finished: Vec<(String, Option<ExitedShellInfo>)> = Vec::new();
195
196        for (id, shell_arc) in &self.shells {
197            let Ok(mut guard) = shell_arc.try_lock() else {
198                continue;
199            };
200
201            let Some(shell) = guard.as_mut() else {
202                finished.push((id.clone(), None));
203                continue;
204            };
205
206            if !shell.is_alive() {
207                let tombstone = ExitedShellInfo {
208                    last_command: shell.last_command.clone(),
209                    final_output: std::mem::take(&mut shell.output_buffer),
210                    exited_at: now,
211                };
212                finished.push((id.clone(), Some(tombstone)));
213                continue;
214            }
215
216            // Never prune shells that haven't received a command yet.
217            // The global BG_SHELL_MANAGER is shared across parallel tests; a freshly
218            // spawned shell would otherwise be evicted between start_new_shell and
219            // the first send_command, leading to "Failed to get background shell".
220            if shell.last_command.is_empty() {
221                continue;
222            }
223
224            if shell.command_running {
225                // Non-blocking: draining here must NOT hold the global manager
226                // lock across a 100ms blocking read (that serializes every other
227                // background-shell op behind a single slow PTY).
228                shell.poll_output_nonblocking();
229            }
230
231            if !shell.command_running {
232                let tombstone = ExitedShellInfo {
233                    last_command: shell.last_command.clone(),
234                    final_output: std::mem::take(&mut shell.output_buffer),
235                    exited_at: now,
236                };
237                finished.push((id.clone(), Some(tombstone)));
238            }
239        }
240
241        for (id, tombstone) in finished {
242            self.remove_shell(&id);
243            if let Some(info) = tombstone {
244                self.tombstones.insert(id, info);
245            }
246        }
247    }
248
249    /// Look up the tombstone for a recently-exited shell, if any.
250    ///
251    /// The entry stays in the map until the TTL expires (see
252    /// `prune_finished_shells`), so repeated `status_check` calls on the same
253    /// `bg_command_id` keep returning the cached final output instead of
254    /// flipping to "shell not found" after the first read.
255    pub fn peek_tombstone(&self, bg_command_id: &str) -> Option<ExitedShellInfo> {
256        self.tombstones.get(bg_command_id).cloned()
257    }
258
259    /// Get info about all running background shells - matches WCGW Python `get_bg_running_commandsinfo`
260    pub fn get_running_info(&mut self) -> String {
261        self.prune_finished_shells();
262
263        if self.shells.is_empty() {
264            return "No command running in background.\n".to_string();
265        }
266
267        let mut running = Vec::new();
268        for (id, shell_arc) in &self.shells {
269            if let Ok(guard) = shell_arc.try_lock() {
270                if let Some(bash) = guard.as_ref() {
271                    if bash.command_running {
272                        running
273                            .push(format!("Command: {}, bg_command_id: {}", bash.last_command, id));
274                    }
275                }
276            } else {
277                running.push(format!("Command: <busy>, bg_command_id: {id}"));
278            }
279        }
280
281        if running.is_empty() {
282            "No command running in background.\n".to_string()
283        } else {
284            format!("Following background commands are attached:\n{}\n", running.join("\n"))
285        }
286    }
287}
288
289// Global background shell manager (thread-safe) - matches WCGW Python's BashState.background_shells
290lazy_static::lazy_static! {
291    static ref BG_SHELL_MANAGER: StdMutex<BackgroundShellManager> = StdMutex::new(BackgroundShellManager::new());
292}
293
294/// Lock the global background-shell manager, recovering from poisoning.
295///
296/// A panic while holding this lock (e.g. in the rendering path during a prune)
297/// must NOT permanently brick all background-shell functionality for the rest of
298/// the server's lifetime. The manager's data stays consistent across a panic, so
299/// recovering the inner guard is safe.
300fn lock_bg_manager() -> std::sync::MutexGuard<'static, BackgroundShellManager> {
301    BG_SHELL_MANAGER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
302}
303
304// ==================== WCGW-Style Helper Functions ====================
305
306/// Get WCGW-style status string - matches WCGW Python's `get_status()`
307fn get_status(
308    bash_state: &BashState,
309    is_bg: bool,
310    bg_id: Option<&str>,
311    is_running: bool,
312    running_for: Option<&str>,
313    exit_code: Option<i32>,
314) -> String {
315    let mut status = "\n\n---\n\n".to_string();
316
317    if is_bg {
318        if let Some(id) = bg_id {
319            let _ = writeln!(status, "bg_command_id = {id}");
320        }
321    }
322
323    if is_running {
324        status.push_str("status = still running\n");
325        if let Some(duration) = running_for {
326            let _ = writeln!(status, "running for = {duration}");
327        }
328    } else {
329        status.push_str("status = process exited\n");
330        // Exit code of the just-finished command, parsed from the prompt marker
331        // (`──➤<nonce>:<code>`). Lets the agent see failure without grepping stderr.
332        if let Some(code) = exit_code {
333            let _ = writeln!(status, "exit code = {code}");
334        }
335    }
336
337    let _ = writeln!(status, "cwd = {}", bash_state.cwd.display());
338
339    if !is_bg {
340        // Add background shell info for main shell - matches WCGW Python
341        {
342            let mut manager = lock_bg_manager();
343            status.push_str("This is the main shell. ");
344            status.push_str(&manager.get_running_info());
345        }
346    }
347
348    status.trim_end().to_string()
349}
350
351/// Process output with WCGW-style incremental text handling - matches WCGW Python _`incremental_text`
352fn wcgw_incremental_text(text: &str, last_pending_output: &str) -> String {
353    let truncated = truncate_to_token_budget(text, MAX_OUTPUT_TOKENS);
354    let text = truncated.as_ref();
355
356    if last_pending_output.is_empty() {
357        let rendered = render_terminal_output(text);
358        return rstrip_lines(&rendered).trim_start().to_string();
359    }
360
361    let last_rendered = render_terminal_output(last_pending_output);
362    if last_rendered.is_empty() {
363        return rstrip_lines(&render_terminal_output(text));
364    }
365
366    // Get text after last pending output. Snap the offset down to a char
367    // boundary: `last_pending_output.len()` is a byte count and may land inside
368    // a multibyte code point of `text`, which would panic on the slice.
369    let text_after_last = if text.len() > last_pending_output.len() {
370        let cut = crate::utils::floor_char_boundary(text, last_pending_output.len());
371        &text[cut..]
372    } else {
373        text
374    };
375
376    let combined = format!("{}\n{}", last_rendered.join("\n"), text_after_last);
377    let new_rendered = render_terminal_output(&combined);
378
379    // Get incremental part - matches WCGW Python get_incremental_output
380    let incremental = get_incremental_output(&last_rendered, &new_rendered);
381    rstrip_lines(&incremental)
382}
383
384fn extract_prompt_cwd(output: &str) -> Option<PathBuf> {
385    static PROMPT_RE: std::sync::OnceLock<Option<Regex>> = std::sync::OnceLock::new();
386    let prompt_regex =
387        PROMPT_RE.get_or_init(|| Regex::new(r"◉ (?P<cwd>[^\r\n]*?)──➤").ok()).as_ref()?;
388    let stripped = strip_ansi_codes(output);
389
390    prompt_regex
391        .captures_iter(&stripped)
392        .filter_map(|captures| captures.name("cwd").map(|cwd| cwd.as_str().trim()))
393        .filter(|cwd| !cwd.is_empty())
394        .last()
395        .map(PathBuf::from)
396}
397
398/// Right-strip each line and join - matches WCGW Python rstrip
399fn rstrip_lines(lines: &[String]) -> String {
400    lines.iter().map(|line| line.trim_end()).collect::<Vec<_>>().join("\n")
401}
402
403/// Get incremental output between old and new - matches WCGW Python `get_incremental_output`
404fn get_incremental_output(old_output: &[String], new_output: &[String]) -> Vec<String> {
405    if old_output.is_empty() {
406        return new_output.to_vec();
407    }
408
409    let nold = old_output.len();
410    let nnew = new_output.len();
411
412    // Find where old output ends in new output
413    for i in (0..nnew).rev() {
414        if new_output[i] != old_output[nold - 1] {
415            continue;
416        }
417
418        let mut matched = true;
419        for j in (0..i).rev() {
420            let old_idx = (nold as i64 - 1 + j as i64 - i as i64) as isize;
421            if old_idx < 0 {
422                break;
423            }
424            if new_output[j] != old_output[old_idx as usize] {
425                matched = false;
426                break;
427            }
428        }
429
430        if matched {
431            return new_output[i + 1..].to_vec();
432        }
433    }
434
435    new_output.to_vec()
436}
437
438fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
439    let mut start = 0;
440
441    while start < text.len() {
442        let mut end = (start + chunk_size).min(text.len());
443        while !text.is_char_boundary(end) {
444            end -= 1;
445        }
446        if end == start {
447            end = text[start..].char_indices().nth(1).map_or(text.len(), |(idx, _)| start + idx);
448        }
449
450        shell.send_text(&text[start..end]).map_err(|e| {
451            WinxError::CommandExecutionError(format!("Failed to write PTY input: {e}"))
452        })?;
453        start = end;
454    }
455
456    Ok(())
457}
458
459/// Send the submitting Enter as a separate, slightly-delayed write so an
460/// Ink-based TUI doesn't swallow a CR glued to the preceding input. Briefly
461/// drops the shell lock during the pause so the reader thread keeps draining.
462/// See [`SUBMIT_NUDGE_DELAY`].
463async fn submit_enter(shell_arc: &SharedPtyShell) -> Result<()> {
464    tokio::time::sleep(SUBMIT_NUDGE_DELAY).await;
465    let mut guard = shell_arc.lock().await;
466    let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
467    bash.send_special_key("Enter")
468        .map_err(|e| WinxError::CommandExecutionError(format!("Failed to submit: {e}")))?;
469    Ok(())
470}
471
472// ==================== Main Tool Handler ====================
473
474/// Handles the `BashCommand` tool call with WCGW parity
475///
476/// This function processes the `BashCommand` tool call following WCGW Python's
477/// `execute_bash()` function behavior exactly.
478#[tracing::instrument(level = "info", skip(bash_state_arc, bash_command))]
479pub async fn handle_tool_call(
480    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
481    bash_command: BashCommand,
482) -> Result<String> {
483    info!("BashCommand tool called with: {:?}", bash_command);
484
485    let thread_id = normalize_thread_id(&bash_command.thread_id);
486
487    // Check if thread_id is empty
488    if thread_id.is_empty() {
489        error!("Empty thread_id provided in BashCommand");
490        return Err(WinxError::ThreadIdMismatch(
491            "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID.".to_string()
492        ));
493    }
494
495    // Extract bash_state data
496    let mut bash_state: BashState;
497    {
498        let bash_state_guard = bash_state_arc.lock().await;
499
500        let Some(state) = &*bash_state_guard else {
501            error!("BashState not initialized");
502            return Err(WinxError::BashStateNotInitialized);
503        };
504
505        bash_state = state.clone();
506    }
507
508    // Verify thread ID matches - matches WCGW Python thread_id check
509    if thread_id != bash_state.current_thread_id {
510        // Try to load state from thread_id - matches WCGW Python load_state_from_thread_id
511        if !bash_state.load_state_from_disk(&thread_id).unwrap_or(false) {
512            return Err(WinxError::ThreadIdMismatch(format!(
513                "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
514            )));
515        }
516    }
517
518    // Calculate effective timeout - matches WCGW Python
519    // SECURITY: Ensure timeout is not negative to prevent unexpected behavior
520    let timeout_s = bash_command
521        .wait_for_seconds
522        .map_or(DEFAULT_TIMEOUT, |t| f64::from(t).max(0.0))
523        .min(TIMEOUT_WHILE_OUTPUT);
524
525    // Execute the action based on type - matches WCGW Python's _execute_bash()
526    let result = execute_bash_action(&mut bash_state, &bash_command.action_json, timeout_s).await;
527
528    {
529        let mut bash_state_guard = bash_state_arc.lock().await;
530        if let Some(state) = bash_state_guard.as_mut() {
531            state.cwd.clone_from(&bash_state.cwd);
532        }
533    }
534
535    // Remove echo if it's a command - matches WCGW Python
536    match result {
537        Ok(mut output) => {
538            if let BashCommandAction::Command { ref command, .. } = bash_command.action_json {
539                let cmd_trimmed = command.trim();
540                if output.starts_with(cmd_trimmed) {
541                    output = output[cmd_trimmed.len()..].to_string();
542                }
543            }
544            Ok(output)
545        }
546        Err(e) => Err(e),
547    }
548}
549
550/// Execute a bash action - matches WCGW Python's _`execute_bash()` function
551#[allow(clippy::too_many_lines)]
552async fn execute_bash_action(
553    bash_state: &mut BashState,
554    action: &BashCommandAction,
555    timeout_s: f64,
556) -> Result<String> {
557    let mut is_bg = false;
558    let mut bg_id: Option<String> = None;
559
560    // Handle bg_command_id routing - matches WCGW Python
561    let bg_shell: Option<SharedPtyShell> = match action {
562        BashCommandAction::Command { .. } => None, // Commands don't use bg_command_id for routing
563        BashCommandAction::StatusCheck { bg_command_id, .. }
564        | BashCommandAction::SendText { bg_command_id, .. }
565        | BashCommandAction::SendSpecials { bg_command_id, .. }
566        | BashCommandAction::SendAscii { bg_command_id, .. }
567        | BashCommandAction::Screen { bg_command_id, .. }
568        | BashCommandAction::WaitForTurn { bg_command_id, .. } => {
569            if let Some(id) = bg_command_id {
570                let mut manager = BG_SHELL_MANAGER.lock().map_err(|e| {
571                    WinxError::BashStateLockError(format!("Failed to lock bg manager: {e}"))
572                })?;
573                manager.prune_finished_shells();
574
575                if let Some(shell) = manager.get_shell(id) {
576                    is_bg = true;
577                    bg_id = Some(id.clone());
578                    Some(shell)
579                } else if let Some(tombstone) = manager.peek_tombstone(id) {
580                    // Shell already exited. For a status check we can hand back the
581                    // final cached output exactly once. For anything else (send_text,
582                    // send_specials, send_ascii) tell the caller the shell is gone
583                    // and include the captured output so they can recover state.
584                    drop(manager);
585                    return finalize_tombstone(&bash_state.cwd, id, tombstone, action);
586                } else {
587                    // Error message matches WCGW Python
588                    let error = format!(
589                        "No shell found running with command id {}.\n{}",
590                        id,
591                        manager.get_running_info()
592                    );
593                    return Err(WinxError::CommandExecutionError(error));
594                }
595            } else {
596                None
597            }
598        }
599    };
600
601    // Process based on action type - matches WCGW Python _execute_bash dispatch
602    match action {
603        BashCommandAction::Command { command, is_background, allow_multi } => {
604            execute_command(bash_state, command, *is_background, *allow_multi, timeout_s).await
605        }
606        BashCommandAction::StatusCheck { scrollback_lines, verbose, .. } => {
607            execute_status_check(
608                bash_state,
609                bg_shell,
610                is_bg,
611                bg_id.as_deref(),
612                timeout_s,
613                *scrollback_lines,
614                *verbose,
615            )
616            .await
617        }
618        BashCommandAction::SendText { send_text, submit, .. } => {
619            execute_send_text(
620                bash_state,
621                send_text,
622                *submit,
623                bg_shell,
624                is_bg,
625                bg_id.as_deref(),
626                timeout_s,
627            )
628            .await
629        }
630        BashCommandAction::SendSpecials { send_specials, submit, .. } => {
631            execute_send_specials(
632                bash_state,
633                send_specials,
634                *submit,
635                bg_shell,
636                is_bg,
637                bg_id.as_deref(),
638                timeout_s,
639            )
640            .await
641        }
642        BashCommandAction::SendAscii { send_ascii, submit, .. } => {
643            execute_send_ascii(
644                bash_state,
645                send_ascii,
646                *submit,
647                bg_shell,
648                is_bg,
649                bg_id.as_deref(),
650                timeout_s,
651            )
652            .await
653        }
654        BashCommandAction::Screen { lines, diff, .. } => {
655            execute_screen(bash_state, bg_shell, is_bg, bg_id.as_deref(), *lines, *diff).await
656        }
657        BashCommandAction::WaitForTurn { recognizer, quiet_ms, timeout_seconds, lines, .. } => {
658            execute_wait_for_turn(
659                bash_state,
660                bg_shell,
661                is_bg,
662                bg_id.as_deref(),
663                recognizer.as_deref(),
664                *quiet_ms,
665                *timeout_seconds,
666                *lines,
667            )
668            .await
669        }
670    }
671}
672
673/// Strip a trailing `| tail ...` from a command (wcgw parity, `strip_tail_pipe`).
674///
675/// LLMs habitually pipe output through `tail`, but we already truncate output
676/// server-side — stripping the pipe avoids hiding the earlier output the model
677/// usually wants. Only a `tail` at the very end of the command is removed.
678///
679/// This matches wcgw by default. Set `WINX_KEEP_TAIL_PIPE=1` to preserve the
680/// pipe instead (winx's original behavior), e.g. when you deliberately want only
681/// the tail of a huge log rather than the server-side truncation.
682fn strip_tail_pipe(command: &str) -> String {
683    strip_tail_pipe_impl(command, keep_tail_pipe())
684}
685
686/// Pure core of [`strip_tail_pipe`], split out so both modes are unit-testable
687/// without touching process-wide env vars (tests run concurrently).
688fn strip_tail_pipe_impl(command: &str, keep: bool) -> String {
689    static RE: std::sync::OnceLock<Option<regex::Regex>> = std::sync::OnceLock::new();
690    if keep {
691        return command.to_string();
692    }
693    let re = RE.get_or_init(|| regex::Regex::new(r"\|\s*tail(?:\s+(?:-n\s*|-)?(\d+))?\s*$").ok());
694    match re.as_ref().and_then(|re| re.find(command)) {
695        Some(matched) => command[..matched.start()].trim_end().to_string(),
696        None => command.to_string(),
697    }
698}
699
700/// Whether the user opted out of `| tail` stripping via `WINX_KEEP_TAIL_PIPE`.
701fn keep_tail_pipe() -> bool {
702    std::env::var("WINX_KEEP_TAIL_PIPE").is_ok_and(|value| {
703        let value = value.trim();
704        !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
705    })
706}
707
708/// Execute a command - matches WCGW Python's Command handling in _`execute_bash`
709async fn execute_command(
710    bash_state: &mut BashState,
711    command: &str,
712    is_background: bool,
713    allow_multi: bool,
714    timeout_s: f64,
715) -> Result<String> {
716    // wcgw strips a trailing `| tail` before anything else (model_validator).
717    let stripped_command = strip_tail_pipe(command);
718    let command = stripped_command.as_str();
719    debug!("Processing Command action: {command:?} (allow_multi={allow_multi})");
720
721    // Check mode permissions - matches WCGW Python bash_command_mode check
722    if !bash_state.is_command_allowed(command) {
723        error!("Command '{}' not allowed in current mode", command);
724        return Err(WinxError::CommandNotAllowed(
725            "Error: BashCommand not allowed in current mode".to_string(),
726        ));
727    }
728
729    // Single-statement guard (wcgw parity). Callers can opt out via
730    // `allow_multi: true` when they knowingly want to chain commands
731    // without wrapping in `bash -lc '...'`.
732    let command = command.trim();
733    if !allow_multi {
734        crate::utils::bash_parser::assert_single_statement(command)?;
735    }
736
737    // If background execution requested, start new shell - matches WCGW Python is_background handling
738    if is_background {
739        return execute_in_background(bash_state, command, timeout_s).await;
740    }
741
742    // Check if a command is already running - matches WCGW Python state check
743    {
744        let bash_guard = bash_state.pty_shell.lock().await;
745
746        if let Some(ref bash) = *bash_guard {
747            if bash.command_running {
748                return Err(WinxError::CommandExecutionError(WAITING_INPUT_MESSAGE.to_string()));
749            }
750        }
751    }
752
753    // Initialize bash if needed
754    if bash_state.pty_shell.lock().await.is_none() {
755        bash_state
756            .init_pty_shell()
757            .await
758            .map_err(|e| WinxError::CommandExecutionError(format!("Failed to init bash: {e}")))?;
759    }
760
761    // Clear prompt before sending - matches WCGW Python clear_to_run.
762    // Drain any leftover output and, if the shell still looks busy, send
763    // Ctrl-C so the new command lands on a fresh prompt instead of being
764    // appended to whatever was hanging on stdin.
765    {
766        let needs_reset = {
767            let mut bash_guard = bash_state.pty_shell.lock().await;
768            match bash_guard.as_mut() {
769                Some(bash) => match bash.clear_to_run(DEFAULT_TIMEOUT as f32) {
770                    Ok(true) => false,
771                    Ok(false) => {
772                        warn!("clear_to_run: shell still busy after Ctrl-C, resetting it");
773                        true
774                    }
775                    Err(e) => {
776                        warn!("clear_to_run failed ({e}), resetting shell");
777                        true
778                    }
779                },
780                None => false,
781            }
782        };
783        // wcgw parity: a shell that won't return to a prompt even after Ctrl-C is
784        // recreated, so the new command lands on a fresh prompt instead of being
785        // appended to a hung shell. init_pty_shell rebuilds at the same cwd/mode.
786        if needs_reset {
787            if let Err(e) = bash_state.init_pty_shell().await {
788                warn!("Failed to reset shell after clear_to_run: {e}");
789            }
790        }
791    }
792
793    // Send command in chunks of 64 characters - matches WCGW Python exactly
794    {
795        let mut bash_guard = bash_state.pty_shell.lock().await;
796
797        let bash = bash_guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
798
799        bash.output_buffer.clear();
800        bash.output_truncated = false;
801        // Send in chunks - matches WCGW Python: for i in range(0, len(command), 64)
802        send_utf8_in_byte_chunks(bash, command, COMMAND_CHUNK_SIZE)?;
803
804        // Send linesep to execute - matches WCGW Python bash_state.send(bash_state.linesep, ...)
805        bash.send_special_key("Enter").map_err(|e| {
806            WinxError::CommandExecutionError(format!("Failed to send newline: {e}"))
807        })?;
808
809        bash.last_command = command.to_string();
810        bash.command_running = true;
811    }
812
813    // Wait for output with WCGW-style patience handling
814    let shell_arc = bash_state.pty_shell.clone();
815    wait_for_output(bash_state, &shell_arc, timeout_s, false, None, false).await
816}
817
818/// Wait for command output with WCGW-style patience handling - matches WCGW Python expect/wait logic.
819///
820/// `shell_arc` selects which shell to read from (main shell or a bg shell handle).
821async fn wait_for_output(
822    bash_state: &mut BashState,
823    shell_arc: &SharedPtyShell,
824    timeout_s: f64,
825    is_bg: bool,
826    bg_id: Option<&str>,
827    is_status_check: bool,
828) -> Result<String> {
829    let start = Instant::now();
830    let wait = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
831    let mut last_pending_output = String::new();
832    let mut complete = false;
833
834    // Adaptive polling instead of a blind sleep. wcgw sleeps the full `wait`
835    // budget before reading even once, so a `pwd` that finishes in 10ms still
836    // costs ~5s. Instead we read in short slices and return the moment the
837    // prompt comes back (`read_output` already exits early on prompt + drain),
838    // dropping fast-command latency from seconds to ~100ms. Long-running
839    // commands still consume the whole budget, since we loop until `complete`
840    // or `wait` elapses — identical upper-bound behavior, far snappier floor.
841    let mut output = String::new();
842    loop {
843        let elapsed = start.elapsed().as_secs_f64();
844        if elapsed >= wait {
845            break;
846        }
847        let slice = (wait - elapsed).clamp(0.1, POLL_SLICE_SECS);
848        let (out, done) = {
849            let mut bash_guard = shell_arc.lock().await;
850            match bash_guard.as_mut() {
851                Some(bash) => bash.read_output(slice as f32).map_err(|e| {
852                    WinxError::CommandExecutionError(format!("Failed to read output: {e}"))
853                })?,
854                None => (String::new(), true),
855            }
856        };
857        output = out;
858        complete = done;
859        if complete {
860            break;
861        }
862    }
863
864    // If not complete and this is a status check, use WCGW-style patience waiting.
865    //
866    // Treat `timeout_s` (== caller's `wait_for_seconds`, capped at
867    // `TIMEOUT_WHILE_OUTPUT`) as the hard upper bound on the TOTAL wall-clock
868    // spent inside this call. wcgw computes `remaining = TIMEOUT_WHILE_OUTPUT
869    // - wait`, which makes a 2-second `wait_for_seconds` block for almost 20s
870    // on a TUI that keeps emitting spinner frames. We diverge from wcgw here
871    // because driving agents expect their wait budget to be respected.
872    if !complete && is_status_check {
873        let budget_secs = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
874        let iter_wait_secs = 0.5_f64;
875        let mut patience = OUTPUT_WAIT_PATIENCE;
876
877        let incremental = wcgw_incremental_text(&output, &last_pending_output);
878        if incremental.is_empty() {
879            patience -= 1;
880        }
881
882        let mut last_incremental = incremental;
883
884        while start.elapsed().as_secs_f64() < budget_secs && patience > 0 {
885            let remaining = (budget_secs - start.elapsed().as_secs_f64()).max(0.0);
886            if remaining < 0.1 {
887                break;
888            }
889            sleep(Duration::from_secs_f64(iter_wait_secs.min(remaining))).await;
890
891            let (new_output, done) = {
892                let mut bash_guard = shell_arc.lock().await;
893
894                if let Some(bash) = bash_guard.as_mut() {
895                    bash.read_output(0.5).map_err(|e| {
896                        WinxError::CommandExecutionError(format!("Failed to read output: {e}"))
897                    })?
898                } else {
899                    (String::new(), true)
900                }
901            };
902
903            if done {
904                complete = true;
905                output = new_output;
906                break;
907            }
908
909            // Check if output changed - matches WCGW Python patience logic
910            let new_incremental = wcgw_incremental_text(&new_output, &last_pending_output);
911            if new_incremental == last_incremental {
912                patience -= 1;
913            } else {
914                patience = OUTPUT_WAIT_PATIENCE; // Reset patience on new output
915            }
916            last_incremental = new_incremental;
917
918            output = new_output;
919        }
920
921        if !complete {
922            // Update pending output - matches WCGW Python bash_state.set_pending(text)
923            last_pending_output = output.clone();
924        }
925    }
926
927    if complete {
928        if let Some(cwd) = extract_prompt_cwd(&output) {
929            bash_state.cwd = cwd;
930        }
931    }
932
933    // Process output through terminal emulation - matches WCGW Python _incremental_text
934    let rendered = wcgw_incremental_text(&output, &last_pending_output);
935
936    // Conscious compression: collapse mechanical repetition (identical line runs,
937    // blank-line blocks) before truncating, to save tokens without dropping any
938    // unique context. Falls back to the raw text when nothing is safe to collapse.
939    let rendered = {
940        let before_lines = rendered.lines().count();
941        match crate::utils::output_compress::compress_output(&rendered) {
942            Some(compressed) => {
943                debug!(
944                    from_lines = before_lines,
945                    to_lines = compressed.lines().count(),
946                    "winx collapsed mechanical repetition in shell output"
947                );
948                compressed
949            }
950            None => rendered,
951        }
952    };
953
954    // Truncate if needed - matches WCGW Python token truncation
955    let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();
956
957    // Calculate running duration for status
958    let running_for =
959        if complete { None } else { Some(format!("{} seconds", start.elapsed().as_secs())) };
960
961    // Surface the just-finished command's exit code (parsed from the prompt
962    // marker) so the agent sees failure without grepping stderr.
963    let mut exit_code = None;
964    if complete {
965        exit_code = shell_arc.lock().await.as_ref().and_then(|shell| shell.last_exit_code);
966    }
967
968    // Add status - matches WCGW Python get_status
969    let status = get_status(bash_state, is_bg, bg_id, !complete, running_for.as_deref(), exit_code);
970    Ok(format!("{rendered}{status}"))
971}
972
973/// Render the final cached output of an exited background shell.
974///
975/// `status_check` is allowed to "consume" the tombstone and return the trailing
976/// output exactly once. Send-style actions (`send_text`, `send_specials`,
977/// `send_ascii`) cannot interact with a dead shell, so we return an explicit
978/// error that still includes the captured output so the agent can recover state.
979fn finalize_tombstone(
980    cwd: &Path,
981    id: &str,
982    tombstone: ExitedShellInfo,
983    action: &BashCommandAction,
984) -> Result<String> {
985    let ExitedShellInfo { last_command, final_output, .. } = tombstone;
986    match action {
987        // A dead shell's turn is over: Screen/WaitForTurn hand back the final
988        // captured output as the snapshot, exactly like a status check.
989        BashCommandAction::StatusCheck { .. }
990        | BashCommandAction::Screen { .. }
991        | BashCommandAction::WaitForTurn { .. } => {
992            let rendered = wcgw_incremental_text(&final_output, "");
993            let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();
994            // Build a compact status block matching `get_status` for a finished bg shell.
995            let mut status = "\n\n---\n\n".to_string();
996            let _ = writeln!(status, "bg_command_id = {id}");
997            status.push_str("status = process exited\n");
998            let _ = writeln!(status, "cwd = {}", cwd.display());
999            Ok(format!("{rendered}{}", status.trim_end()))
1000        }
1001        BashCommandAction::SendText { .. }
1002        | BashCommandAction::SendSpecials { .. }
1003        | BashCommandAction::SendAscii { .. } => Err(WinxError::CommandExecutionError(format!(
1004            "Background shell {id} already exited (last command: {last_command}).\nFinal captured output:\n{final_output}"
1005        ))),
1006        BashCommandAction::Command { .. } => {
1007            // We only enter `finalize_tombstone` from the bg routing path, which
1008            // never matches Command. Treat this as a programmer error.
1009            unreachable!("finalize_tombstone called for non-bg action")
1010        }
1011    }
1012}
1013
1014/// Execute a status check - matches WCGW Python's `StatusCheck` handling.
1015///
1016/// New behavior (v0.2.308):
1017/// - Deduplicates against the last response by fingerprint; when nothing
1018///   changed and `verbose=false`, returns a compact "no new output" payload
1019///   instead of resending the same screen.
1020/// - Optional `scrollback_lines` pulls bounded history from the `PtyShell`
1021///   ringbuffer so agents can reorient after a long pause.
1022async fn execute_status_check(
1023    bash_state: &mut BashState,
1024    bg_shell: Option<SharedPtyShell>,
1025    is_bg: bool,
1026    bg_id: Option<&str>,
1027    timeout_s: f64,
1028    scrollback_lines: Option<usize>,
1029    verbose: bool,
1030) -> Result<String> {
1031    debug!("Processing StatusCheck action (verbose={verbose}, scrollback={scrollback_lines:?})");
1032
1033    // Pick the shell we're going to inspect: bg shell when bg_command_id was provided,
1034    // otherwise fall back to the main interactive shell.
1035    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1036
1037    // Check if there's a running command - matches WCGW Python state check
1038    let is_running = {
1039        let guard = shell_arc.lock().await;
1040        if let Some(ref bash) = *guard {
1041            bash.command_running
1042        } else {
1043            false
1044        }
1045    };
1046
1047    // If no command running and not background, return error - matches WCGW Python
1048    if !is_running && !is_bg {
1049        let mut manager = lock_bg_manager();
1050        let error = format!(
1051            "No command is currently running, so there's nothing to check. The previous \
1052             command already finished and its output was returned when it completed. Start a \
1053             new command, or pass a bg_command_id if you launched one in the background.\n{}",
1054            manager.get_running_info()
1055        );
1056        return Err(WinxError::CommandExecutionError(error));
1057    }
1058
1059    // Read output with patience handling - this IS a status check
1060    let response = wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, true).await?;
1061
1062    // Inter-call dedup: hash only the response *body* (the chunk before the
1063    // `\n\n---\n` status footer). The footer contains a live "running for"
1064    // counter that would otherwise defeat the comparison.
1065    let body = response.split("\n\n---\n").next().unwrap_or(&response);
1066    if !verbose && scrollback_lines.is_none() {
1067        let mut guard = shell_arc.lock().await;
1068        if let Some(bash) = guard.as_mut() {
1069            let fingerprint = PtyShell::fingerprint(body);
1070            if Some(fingerprint) == bash.last_returned_hash {
1071                let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1072                return Ok(format!("no new output since last check{status}"));
1073            }
1074            bash.last_returned_hash = Some(fingerprint);
1075        }
1076    } else if !verbose {
1077        // Still record the hash so subsequent non-scrollback calls can dedup.
1078        let mut guard = shell_arc.lock().await;
1079        if let Some(bash) = guard.as_mut() {
1080            bash.last_returned_hash = Some(PtyShell::fingerprint(body));
1081        }
1082    }
1083
1084    // Optional scrollback prefix — only ever pulled when the caller asks for it.
1085    if let Some(lines) = scrollback_lines {
1086        if lines > 0 {
1087            let scrollback = {
1088                let guard = shell_arc.lock().await;
1089                guard.as_ref().map(|s| s.collect_scrollback(lines)).unwrap_or_default()
1090            };
1091            if !scrollback.is_empty() {
1092                let count = scrollback.lines().count();
1093                return Ok(format!(
1094                    "--- scrollback ({count} lines) ---\n{scrollback}\n--- latest ---\n{response}"
1095                ));
1096            }
1097        }
1098    }
1099
1100    Ok(response)
1101}
1102
1103/// Execute `Screen` — a stable, point-in-time snapshot of a shell's live
1104/// terminal screen (consolidated grid, ANSI stripped). No waiting, no dedup;
1105/// the foundation for reading an interactive TUI's current frame.
1106async fn execute_screen(
1107    bash_state: &BashState,
1108    bg_shell: Option<SharedPtyShell>,
1109    is_bg: bool,
1110    bg_id: Option<&str>,
1111    lines: Option<usize>,
1112    diff: bool,
1113) -> Result<String> {
1114    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1115    let max_lines = lines.unwrap_or(0);
1116
1117    if diff {
1118        let (update, is_running, in_alt, cursor) = {
1119            let guard = shell_arc.lock().await;
1120            match guard.as_ref() {
1121                Some(bash) => (
1122                    bash.live_snapshot_diff(max_lines, SCREEN_DIFF_THRESHOLD),
1123                    bash.command_running,
1124                    bash.live_in_alt_screen(),
1125                    bash.live_cursor_position(),
1126                ),
1127                None => (ScreenUpdate::Full(Vec::new()), false, false, (0, 0)),
1128            }
1129        };
1130        let (crow, ccol) = cursor;
1131        let alt = if in_alt { " [alt-screen]" } else { "" };
1132        let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1133        let body = match update {
1134            ScreenUpdate::Unchanged => "(no change since last screen)".to_string(),
1135            ScreenUpdate::Diff(changed) => {
1136                let mut out = String::from("(changed lines only)\n");
1137                for (row, content) in changed {
1138                    let _ = writeln!(out, "{row:>4}: {content}");
1139                }
1140                out
1141            }
1142            ScreenUpdate::Full(snap) => {
1143                let joined = snap.join("\n");
1144                if joined.trim().is_empty() {
1145                    "(screen is empty)".to_string()
1146                } else {
1147                    truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1148                }
1149            }
1150        };
1151        return Ok(format!(
1152            "--- live screen{alt} [cursor row={crow} col={ccol}] (diff) ---\n{body}{status}"
1153        ));
1154    }
1155
1156    let (snapshot, is_running, in_alt, cursor) = {
1157        let guard = shell_arc.lock().await;
1158        match guard.as_ref() {
1159            Some(bash) => (
1160                bash.live_snapshot(max_lines),
1161                bash.command_running,
1162                bash.live_in_alt_screen(),
1163                bash.live_cursor_position(),
1164            ),
1165            None => (Vec::new(), false, false, (0, 0)),
1166        }
1167    };
1168
1169    let joined = snapshot.join("\n");
1170    let body = if joined.trim().is_empty() {
1171        "(screen is empty)".to_string()
1172    } else {
1173        truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1174    };
1175    let alt = if in_alt { " [alt-screen]" } else { "" };
1176    let (crow, ccol) = cursor;
1177    let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1178    Ok(format!("--- live screen{alt} [cursor row={crow} col={ccol}] ---\n{body}{status}"))
1179}
1180
1181/// Execute `WaitForTurn` — block until an interactive TUI finishes its turn.
1182///
1183/// Polls the live screen, combining a per-app recognizer (claude/codex/auto)
1184/// with a generic quiescence window: the turn is "ready" when the recognizer
1185/// reports awaiting-input/approval (after a short settle) or, for an unknown
1186/// TUI, when the screen simply stops changing for `quiet`. Returns the stable
1187/// snapshot plus the detected state.
1188#[allow(clippy::too_many_arguments)]
1189async fn execute_wait_for_turn(
1190    bash_state: &BashState,
1191    bg_shell: Option<SharedPtyShell>,
1192    is_bg: bool,
1193    bg_id: Option<&str>,
1194    recognizer_hint: Option<&str>,
1195    quiet_ms: Option<u64>,
1196    timeout_seconds: Option<f32>,
1197    lines: Option<usize>,
1198) -> Result<String> {
1199    use crate::state::turn::{recognizer_for, TurnState};
1200
1201    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1202    let recognizer = recognizer_for(recognizer_hint.unwrap_or("auto"));
1203    let quiet = Duration::from_millis(quiet_ms.unwrap_or(600).clamp(50, 10_000));
1204    let settle = quiet.min(Duration::from_millis(300));
1205    let hard_cap =
1206        Duration::from_secs_f64(f64::from(timeout_seconds.unwrap_or(30.0)).clamp(0.5, 600.0));
1207    let max_lines = lines.unwrap_or(0);
1208    let poll = Duration::from_millis(120);
1209    // Grace period so a freshly-prompted app has time to react before we'd
1210    // otherwise mistake the *pre-input* idle screen for a finished turn.
1211    let warmup = Duration::from_millis(2500);
1212
1213    let start = Instant::now();
1214    let mut last_hash: Option<u64> = None;
1215    let mut initial_hash: Option<u64> = None;
1216    let mut stable_since = Instant::now();
1217    let mut seen_busy = false;
1218
1219    loop {
1220        let (snapshot, in_alt, alive, running) = {
1221            let mut guard = shell_arc.lock().await;
1222            match guard.as_mut() {
1223                Some(bash) => (
1224                    bash.live_snapshot(max_lines),
1225                    bash.live_in_alt_screen(),
1226                    bash.is_alive(),
1227                    bash.command_running,
1228                ),
1229                None => (Vec::new(), false, false, false),
1230            }
1231        };
1232
1233        let hash = PtyShell::fingerprint(&snapshot.join("\n"));
1234        if initial_hash.is_none() {
1235            initial_hash = Some(hash);
1236        }
1237        if Some(hash) != last_hash {
1238            last_hash = Some(hash);
1239            stable_since = Instant::now();
1240        }
1241
1242        let state = recognizer.detect(&snapshot);
1243        if state == TurnState::Busy {
1244            seen_busy = true;
1245        }
1246        let stable_for = stable_since.elapsed();
1247        // Don't call it "done" until something actually happened since we began
1248        // waiting: the app went Busy, the screen changed from the first frame we
1249        // saw, or the warmup elapsed (instant reply / nothing to do).
1250        let activity = seen_busy || Some(hash) != initial_hash || start.elapsed() >= warmup;
1251        let ready = match state {
1252            TurnState::Busy => false,
1253            // A short settle is enough once we saw it go Busy; otherwise wait the
1254            // full quiet window so a slow first token isn't read as "done".
1255            TurnState::AwaitingInput | TurnState::AwaitingApproval => {
1256                activity && stable_for >= if seen_busy { settle } else { quiet }
1257            }
1258            TurnState::Unknown => activity && stable_for >= quiet,
1259        };
1260
1261        let timed_out = start.elapsed() >= hard_cap;
1262        if ready || !alive || timed_out {
1263            let reason = if !alive {
1264                "exited"
1265            } else if ready {
1266                "ready"
1267            } else {
1268                "timeout"
1269            };
1270            let joined = snapshot.join("\n");
1271            let body = if joined.trim().is_empty() {
1272                "(screen is empty)".to_string()
1273            } else {
1274                truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1275            };
1276            let alt = if in_alt { " [alt-screen]" } else { "" };
1277            let header = format!(
1278                "--- turn: {} ({}, recognizer={}, waited {:.1}s){} ---",
1279                state.as_str(),
1280                reason,
1281                recognizer.name(),
1282                start.elapsed().as_secs_f64(),
1283                alt
1284            );
1285            let status = get_status(bash_state, is_bg, bg_id, running, None, None);
1286            return Ok(format!("{header}\n{body}{status}"));
1287        }
1288
1289        tokio::time::sleep(poll).await;
1290    }
1291}
1292
1293/// Execute `send_text` - matches WCGW Python's `SendText` handling
1294async fn execute_send_text(
1295    bash_state: &mut BashState,
1296    text: &str,
1297    submit: bool,
1298    bg_shell: Option<SharedPtyShell>,
1299    is_bg: bool,
1300    bg_id: Option<&str>,
1301    timeout_s: f64,
1302) -> Result<String> {
1303    debug!("Processing SendText action: {text:?} (submit={submit})");
1304
1305    // Validate - matches WCGW Python
1306    if text.is_empty() {
1307        return Err(WinxError::CommandExecutionError(
1308            "Failure: send_text cannot be empty".to_string(),
1309        ));
1310    }
1311
1312    // Get the target shell
1313    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1314
1315    // Send text in chunks of 128 characters - matches WCGW Python exactly
1316    {
1317        let mut guard = shell_arc.lock().await;
1318
1319        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1320
1321        // Send in chunks - matches WCGW Python: for i in range(0, len(command_data.send_text), 128)
1322        send_utf8_in_byte_chunks(bash, text, TEXT_CHUNK_SIZE)?;
1323    }
1324
1325    // Only submit when explicitly asked. The Enter goes as a separate, delayed
1326    // write so Ink TUIs (Claude Code) don't swallow a CR glued to the text — a
1327    // bare CR there is otherwise treated as a soft newline and never submits.
1328    if submit {
1329        submit_enter(&shell_arc).await?;
1330    }
1331
1332    // Wait for output
1333    wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await
1334}
1335
1336/// Execute `send_specials` - matches WCGW Python's `SendSpecials` handling exactly
1337async fn execute_send_specials(
1338    bash_state: &mut BashState,
1339    keys: &[SpecialKey],
1340    submit: bool,
1341    bg_shell: Option<SharedPtyShell>,
1342    is_bg: bool,
1343    bg_id: Option<&str>,
1344    timeout_s: f64,
1345) -> Result<String> {
1346    debug!("Processing SendSpecials action: {keys:?} (submit={submit})");
1347
1348    // Validate - matches WCGW Python
1349    if keys.is_empty() {
1350        return Err(WinxError::CommandExecutionError(
1351            "Failure: send_specials cannot be empty".to_string(),
1352        ));
1353    }
1354
1355    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1356    let mut is_interrupt = false;
1357
1358    {
1359        let mut guard = shell_arc.lock().await;
1360
1361        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1362
1363        // Send each special key - matches WCGW Python exactly
1364        for key in keys {
1365            match key {
1366                SpecialKey::KeyUp => {
1367                    // matches WCGW Python: bash_state.send("\033[A", ...)
1368                    bash.send_special_key("KeyUp").map_err(|e| {
1369                        WinxError::CommandExecutionError(format!("Failed to send KeyUp: {e}"))
1370                    })?;
1371                }
1372                SpecialKey::KeyDown => {
1373                    // matches WCGW Python: bash_state.send("\033[B", ...)
1374                    bash.send_special_key("KeyDown").map_err(|e| {
1375                        WinxError::CommandExecutionError(format!("Failed to send KeyDown: {e}"))
1376                    })?;
1377                }
1378                SpecialKey::KeyLeft => {
1379                    // matches WCGW Python: bash_state.send("\033[D", ...)
1380                    bash.send_special_key("KeyLeft").map_err(|e| {
1381                        WinxError::CommandExecutionError(format!("Failed to send KeyLeft: {e}"))
1382                    })?;
1383                }
1384                SpecialKey::KeyRight => {
1385                    // matches WCGW Python: bash_state.send("\033[C", ...)
1386                    bash.send_special_key("KeyRight").map_err(|e| {
1387                        WinxError::CommandExecutionError(format!("Failed to send KeyRight: {e}"))
1388                    })?;
1389                }
1390                SpecialKey::Enter => {
1391                    // matches WCGW Python: bash_state.send("\x0d", ...) - carriage return
1392                    bash.send_special_key("Enter").map_err(|e| {
1393                        WinxError::CommandExecutionError(format!("Failed to send Enter: {e}"))
1394                    })?;
1395                }
1396                SpecialKey::CtrlC => {
1397                    // matches WCGW Python: bash_state.sendintr()
1398                    bash.send_interrupt().map_err(|e| {
1399                        WinxError::CommandExecutionError(format!("Failed to send interrupt: {e}"))
1400                    })?;
1401                    is_interrupt = true;
1402                }
1403                SpecialKey::CtrlD => {
1404                    // matches WCGW Python: bash_state.sendintr() - same as Ctrl+C in WCGW
1405                    bash.send_eof().map_err(|e| {
1406                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+D: {e}"))
1407                    })?;
1408                    is_interrupt = true;
1409                }
1410                SpecialKey::CtrlZ => {
1411                    // Ctrl+Z = SIGTSTP (suspend) - ASCII 0x1a
1412                    bash.send_suspend().map_err(|e| {
1413                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+Z: {e}"))
1414                    })?;
1415                }
1416            }
1417        }
1418    }
1419
1420    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
1421    // Ink TUI doesn't drop the CR.
1422    if submit {
1423        submit_enter(&shell_arc).await?;
1424    }
1425
1426    // NOTE: wcgw treats a bare Enter as a status check and applies its
1427    // patience loop. We deliberately diverge: for a driving agent (e.g.,
1428    // pushing Enter to submit text in a TUI) the patience loop swallows the
1429    // immediate response. Callers that want patience semantics should use the
1430    // explicit `status_check` action instead.
1431
1432    // Wait for output
1433    let mut output =
1434        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;
1435
1436    // Add interrupt failure message if still running - matches WCGW Python exactly
1437    if is_interrupt && output.contains("status = still running") {
1438        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
1439    }
1440
1441    Ok(output)
1442}
1443
1444/// Execute `send_ascii` - matches WCGW Python's `SendAscii` handling
1445async fn execute_send_ascii(
1446    bash_state: &mut BashState,
1447    ascii_codes: &[u8],
1448    submit: bool,
1449    bg_shell: Option<SharedPtyShell>,
1450    is_bg: bool,
1451    bg_id: Option<&str>,
1452    timeout_s: f64,
1453) -> Result<String> {
1454    debug!("Processing SendAscii action: {ascii_codes:?} (submit={submit})");
1455
1456    // Validate - matches WCGW Python
1457    if ascii_codes.is_empty() {
1458        return Err(WinxError::CommandExecutionError(
1459            "Failure: send_ascii cannot be empty".to_string(),
1460        ));
1461    }
1462
1463    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1464    let mut is_interrupt = false;
1465
1466    {
1467        let mut guard = shell_arc.lock().await;
1468
1469        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1470
1471        // Send each ASCII code - matches WCGW Python
1472        for &code in ascii_codes {
1473            // matches WCGW Python: bash_state.send(chr(ascii_char), ...)
1474            bash.send_bytes(&[code]).map_err(|e| {
1475                WinxError::CommandExecutionError(format!("Failed to write ASCII code: {e}"))
1476            })?;
1477
1478            // Check for interrupt - matches WCGW Python: if ascii_char == 3: is_interrupt = True
1479            if code == 3 {
1480                is_interrupt = true;
1481            }
1482        }
1483    }
1484
1485    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
1486    // Ink TUI doesn't drop the CR.
1487    if submit {
1488        submit_enter(&shell_arc).await?;
1489    }
1490
1491    // Same divergence from wcgw as in `execute_send_specials`: send_ascii [10]
1492    // or [13] is treated as a direct write, not a status check. Callers that
1493    // need patience-aware reads should use `status_check`.
1494
1495    // Wait for output
1496    let mut output =
1497        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;
1498
1499    // Add interrupt failure message if still running - matches WCGW Python
1500    if is_interrupt && output.contains("status = still running") {
1501        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
1502    }
1503
1504    Ok(output)
1505}
1506
1507/// Execute command in background - matches WCGW Python's `is_background` handling
1508async fn execute_in_background(
1509    bash_state: &mut BashState,
1510    command: &str,
1511    timeout_s: f64,
1512) -> Result<String> {
1513    debug!("Executing command in background: {}", command);
1514
1515    // Start a new background shell - matches WCGW Python bash_state.start_new_bg_shell
1516    let restricted_mode =
1517        matches!(bash_state.bash_command_mode.bash_mode, crate::types::BashMode::RestrictedMode);
1518
1519    let bg_id = {
1520        let mut manager = lock_bg_manager();
1521        manager.start_new_shell(&bash_state.cwd, restricted_mode)?
1522    };
1523
1524    // Get the shell
1525    let shell_arc = {
1526        let manager = lock_bg_manager();
1527        manager.get_shell(&bg_id).ok_or_else(|| {
1528            WinxError::CommandExecutionError("Failed to get background shell".to_string())
1529        })?
1530    };
1531
1532    // Send command via the same PTY path used by foreground execute_command.
1533    {
1534        let mut guard = shell_arc.lock().await;
1535        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1536        bash.send_command(command).map_err(|e| {
1537            WinxError::CommandExecutionError(format!("Failed to send bg command: {e}"))
1538        })?;
1539    }
1540    debug!("bg[{}]: send_command returned, replying with bg_command_id", bg_id);
1541
1542    let _ = timeout_s;
1543    let _ = shell_arc;
1544    Ok(get_status(bash_state, true, Some(&bg_id), true, None, None))
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549    use super::strip_tail_pipe_impl;
1550
1551    #[test]
1552    fn strips_trailing_tail_by_default() {
1553        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", false), "seq 1 5");
1554        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", false), "cat log");
1555        assert_eq!(strip_tail_pipe_impl("cat log | tail", false), "cat log");
1556        assert_eq!(strip_tail_pipe_impl("ls -la|tail -5", false), "ls -la");
1557    }
1558
1559    #[test]
1560    fn keeps_command_without_trailing_tail() {
1561        // tail not at the end, or piped further, must be left alone.
1562        assert_eq!(strip_tail_pipe_impl("tail -f log | grep err", false), "tail -f log | grep err");
1563        assert_eq!(strip_tail_pipe_impl("echo hi", false), "echo hi");
1564        assert_eq!(
1565            strip_tail_pipe_impl("cat a | tail -5 | wc -l", false),
1566            "cat a | tail -5 | wc -l"
1567        );
1568    }
1569
1570    #[test]
1571    fn keep_mode_preserves_tail_pipe() {
1572        // WINX_KEEP_TAIL_PIPE behavior: command passes through untouched.
1573        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", true), "seq 1 5 | tail -2");
1574        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", true), "cat log | tail -n 20");
1575    }
1576}