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_tracked(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        .stdout(Stdio::piped())
148        .stderr(Stdio::piped())
149        .spawn();
150
151    let child = match child {
152        Ok(c) => c,
153        Err(e) => {
154            tracing::error!("lean-ctx: failed to execute: {e}");
155            return 127;
156        }
157    };
158
159    let output = match child.wait_with_output() {
160        Ok(o) => o,
161        Err(e) => {
162            tracing::error!("lean-ctx: failed to wait: {e}");
163            return 127;
164        }
165    };
166
167    let duration_ms = start.elapsed().as_millis();
168    let exit_code = output.status.code().unwrap_or(1);
169    let stdout = super::platform::decode_output(&output.stdout);
170    let stderr = super::platform::decode_output(&output.stderr);
171
172    let full_output = combine_output(&stdout, &stderr);
173    let input_tokens = count_tokens(&full_output);
174
175    let (compressed, output_tokens) =
176        super::compress::compress_and_measure(command, &stdout, &stderr);
177
178    crate::core::tool_lifecycle::record_shell_command(input_tokens, output_tokens);
179
180    if !compressed.is_empty() {
181        let _ = io::stdout().write_all(compressed.as_bytes());
182        if !compressed.ends_with('\n') {
183            let _ = io::stdout().write_all(b"\n");
184        }
185    }
186    let should_tee = match cfg.tee_mode {
187        config::TeeMode::Always => !full_output.trim().is_empty(),
188        config::TeeMode::Failures => exit_code != 0 && !full_output.trim().is_empty(),
189        config::TeeMode::Never => false,
190    };
191    if should_tee {
192        if let Some(path) = super::redact::save_tee(command, &full_output) {
193            eprintln!("[lean-ctx: full output -> {path} (redacted, 24h TTL)]");
194        }
195    }
196
197    let threshold = cfg.slow_command_threshold_ms;
198    if threshold > 0 && duration_ms >= threshold as u128 {
199        slow_log::record(command, duration_ms, exit_code);
200    }
201
202    exit_code
203}
204
205#[cfg(test)]
206mod exec_tests {
207    #[test]
208    fn exec_direct_runs_true() {
209        let code = super::exec_direct(&["true".to_string()]);
210        assert_eq!(code, 0);
211    }
212
213    #[test]
214    fn exec_direct_runs_false() {
215        let code = super::exec_direct(&["false".to_string()]);
216        assert_ne!(code, 0);
217    }
218
219    #[test]
220    fn exec_direct_preserves_args_with_special_chars() {
221        let code = super::exec_direct(&[
222            "echo".to_string(),
223            "hello world".to_string(),
224            "it's here".to_string(),
225            "a \"quoted\" thing".to_string(),
226        ]);
227        assert_eq!(code, 0);
228    }
229
230    #[test]
231    fn exec_direct_nonexistent_returns_127() {
232        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
233        assert_eq!(code, 127);
234    }
235
236    #[test]
237    fn exec_argv_empty_returns_127() {
238        let code = super::exec_argv(&[]);
239        assert_eq!(code, 127);
240    }
241
242    #[test]
243    fn exec_argv_runs_simple_command() {
244        let code = super::exec_argv(&["true".to_string()]);
245        assert_eq!(code, 0);
246    }
247
248    #[test]
249    fn exec_argv_passes_through_when_disabled() {
250        std::env::set_var("LEAN_CTX_DISABLED", "1");
251        let code = super::exec_argv(&["true".to_string()]);
252        std::env::remove_var("LEAN_CTX_DISABLED");
253        assert_eq!(code, 0);
254    }
255}