Skip to main content

lean_ctx/shell/
exec.rs

1use std::io::{self, IsTerminal, Write};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5use crate::core::slow_log;
6use crate::core::tokens::count_tokens;
7
8/// Execute a command from pre-split argv without going through `sh -c`.
9/// Used by `-t` mode when the shell hook passes `"$@"` — arguments are
10/// already correctly split by the user's shell, so re-serializing them
11/// into a string and re-parsing via `sh -c` would risk mangling complex
12/// quoted arguments (em-dashes, `#`, nested quotes, etc.).
13pub fn exec_argv(args: &[String]) -> i32 {
14    if args.is_empty() {
15        return 127;
16    }
17
18    if std::env::var("LEAN_CTX_DISABLED").is_ok() || std::env::var("LEAN_CTX_ACTIVE").is_ok() {
19        return exec_direct(args);
20    }
21
22    let joined = super::platform::join_command(args);
23    let cfg = config::Config::load();
24
25    if super::compress::is_excluded_command(&joined, &cfg.excluded_commands) {
26        let code = exec_direct(args);
27        crate::core::tool_lifecycle::record_shell_command(0, 0);
28        return code;
29    }
30
31    let code = exec_direct(args);
32    crate::core::tool_lifecycle::record_shell_command(0, 0);
33    code
34}
35
36fn exec_direct(args: &[String]) -> i32 {
37    let status = Command::new(&args[0])
38        .args(&args[1..])
39        .env("LEAN_CTX_ACTIVE", "1")
40        .stdin(Stdio::inherit())
41        .stdout(Stdio::inherit())
42        .stderr(Stdio::inherit())
43        .status();
44
45    match status {
46        Ok(s) => s.code().unwrap_or(1),
47        Err(e) => {
48            tracing::error!("lean-ctx: failed to execute: {e}");
49            127
50        }
51    }
52}
53
54pub fn exec(command: &str) -> i32 {
55    let (shell, shell_flag) = super::platform::shell_and_flag();
56    let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
57    let command = command.as_str();
58
59    if std::env::var("LEAN_CTX_DISABLED").is_ok() || std::env::var("LEAN_CTX_ACTIVE").is_ok() {
60        return exec_inherit(command, &shell, &shell_flag);
61    }
62
63    let cfg = config::Config::load();
64    let force_compress = std::env::var("LEAN_CTX_COMPRESS").is_ok();
65    let raw_mode = std::env::var("LEAN_CTX_RAW").is_ok();
66
67    if raw_mode
68        || (!force_compress
69            && super::compress::is_excluded_command(command, &cfg.excluded_commands))
70    {
71        return exec_inherit(command, &shell, &shell_flag);
72    }
73
74    if !force_compress {
75        if io::stdout().is_terminal() {
76            return exec_inherit_tracked(command, &shell, &shell_flag);
77        }
78        let code = exec_inherit(command, &shell, &shell_flag);
79        crate::core::tool_lifecycle::record_shell_command(0, 0);
80        return code;
81    }
82
83    exec_buffered(command, &shell, &shell_flag, &cfg)
84}
85
86fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
87    let status = Command::new(shell)
88        .arg(shell_flag)
89        .arg(command)
90        .env("LEAN_CTX_ACTIVE", "1")
91        .stdin(Stdio::inherit())
92        .stdout(Stdio::inherit())
93        .stderr(Stdio::inherit())
94        .status();
95
96    match status {
97        Ok(s) => s.code().unwrap_or(1),
98        Err(e) => {
99            tracing::error!("lean-ctx: failed to execute: {e}");
100            127
101        }
102    }
103}
104
105fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
106    let code = exec_inherit(command, shell, shell_flag);
107    crate::core::tool_lifecycle::record_shell_command(0, 0);
108    code
109}
110
111fn combine_output(stdout: &str, stderr: &str) -> String {
112    if stderr.is_empty() {
113        stdout.to_string()
114    } else if stdout.is_empty() {
115        stderr.to_string()
116    } else {
117        format!("{stdout}\n{stderr}")
118    }
119}
120
121fn exec_buffered(command: &str, shell: &str, shell_flag: &str, cfg: &config::Config) -> i32 {
122    #[cfg(windows)]
123    super::platform::set_console_utf8();
124
125    let start = std::time::Instant::now();
126
127    let mut cmd = Command::new(shell);
128    cmd.arg(shell_flag);
129
130    #[cfg(windows)]
131    {
132        let is_powershell =
133            shell.to_lowercase().contains("powershell") || shell.to_lowercase().contains("pwsh");
134        if is_powershell {
135            cmd.arg(format!(
136                "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; {command}"
137            ));
138        } else {
139            cmd.arg(command);
140        }
141    }
142    #[cfg(not(windows))]
143    cmd.arg(command);
144
145    let child = cmd
146        .env("LEAN_CTX_ACTIVE", "1")
147        .env_remove("DISPLAY")
148        .env_remove("XAUTHORITY")
149        .env_remove("WAYLAND_DISPLAY")
150        .stdout(Stdio::piped())
151        .stderr(Stdio::piped())
152        .spawn();
153
154    let child = match child {
155        Ok(c) => c,
156        Err(e) => {
157            tracing::error!("lean-ctx: failed to execute: {e}");
158            return 127;
159        }
160    };
161
162    let output = match child.wait_with_output() {
163        Ok(o) => o,
164        Err(e) => {
165            tracing::error!("lean-ctx: failed to wait: {e}");
166            return 127;
167        }
168    };
169
170    let duration_ms = start.elapsed().as_millis();
171    let exit_code = output.status.code().unwrap_or(1);
172    let stdout = super::platform::decode_output(&output.stdout);
173    let stderr = super::platform::decode_output(&output.stderr);
174
175    let full_output = combine_output(&stdout, &stderr);
176    let input_tokens = count_tokens(&full_output);
177
178    let (compressed, output_tokens) =
179        super::compress::compress_and_measure(command, &stdout, &stderr);
180
181    crate::core::tool_lifecycle::record_shell_command(input_tokens, output_tokens);
182
183    if !compressed.is_empty() {
184        let _ = io::stdout().write_all(compressed.as_bytes());
185        if !compressed.ends_with('\n') {
186            let _ = io::stdout().write_all(b"\n");
187        }
188    }
189    let should_tee = match cfg.tee_mode {
190        config::TeeMode::Always => !full_output.trim().is_empty(),
191        config::TeeMode::Failures => exit_code != 0 && !full_output.trim().is_empty(),
192        config::TeeMode::Never => false,
193    };
194    if should_tee {
195        if let Some(path) = super::redact::save_tee(command, &full_output) {
196            eprintln!("[lean-ctx: full output -> {path} (redacted, 24h TTL)]");
197        }
198    }
199
200    let threshold = cfg.slow_command_threshold_ms;
201    if threshold > 0 && duration_ms >= threshold as u128 {
202        slow_log::record(command, duration_ms, exit_code);
203    }
204
205    exit_code
206}
207
208#[cfg(test)]
209mod exec_tests {
210    #[test]
211    fn exec_direct_runs_true() {
212        let code = super::exec_direct(&["true".to_string()]);
213        assert_eq!(code, 0);
214    }
215
216    #[test]
217    fn exec_direct_runs_false() {
218        let code = super::exec_direct(&["false".to_string()]);
219        assert_ne!(code, 0);
220    }
221
222    #[test]
223    fn exec_direct_preserves_args_with_special_chars() {
224        let code = super::exec_direct(&[
225            "echo".to_string(),
226            "hello world".to_string(),
227            "it's here".to_string(),
228            "a \"quoted\" thing".to_string(),
229        ]);
230        assert_eq!(code, 0);
231    }
232
233    #[test]
234    fn exec_direct_nonexistent_returns_127() {
235        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
236        assert_eq!(code, 127);
237    }
238
239    #[test]
240    fn exec_argv_empty_returns_127() {
241        let code = super::exec_argv(&[]);
242        assert_eq!(code, 127);
243    }
244
245    #[test]
246    fn exec_argv_runs_simple_command() {
247        let code = super::exec_argv(&["true".to_string()]);
248        assert_eq!(code, 0);
249    }
250
251    #[test]
252    fn exec_argv_passes_through_when_disabled() {
253        std::env::set_var("LEAN_CTX_DISABLED", "1");
254        let code = super::exec_argv(&["true".to_string()]);
255        std::env::remove_var("LEAN_CTX_DISABLED");
256        assert_eq!(code, 0);
257    }
258}