Skip to main content

lean_ctx/tools/
ctx_shell.rs

1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5/// Validates a shell command before execution. Returns Some(error_message) if
6/// the command should be rejected, None if it's safe to run.
7pub fn validate_command(command: &str) -> Option<String> {
8    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
9    let project_root = crate::core::config::Config::find_project_root();
10    validate_command_with_write_allow_paths(command, &write_allow_paths, project_root.as_deref())
11}
12
13/// Validate without knowing where the command will run.
14///
15/// A relative redirect target cannot be placed, so it is refused — the
16/// conservative reading. Callers that know the working directory should use
17/// [`validate_command_in_cwd`] instead, which resolves the destination first.
18pub(crate) fn validate_command_with_write_allow_paths(
19    command: &str,
20    write_allow_paths: &[String],
21    project_root: Option<&str>,
22) -> Option<String> {
23    validate_command_in_cwd(command, write_allow_paths, project_root, None)
24}
25
26/// Validate against the directory the command will actually run in (#1811).
27///
28/// The write guard classifies the *destination*, so a relative redirect target
29/// has to be placed before it can be judged. Without a `cwd` it cannot be, and
30/// every relative target was refused — which made `cwd=<scratch> … > probe.txt`
31/// fail while the identical absolute path succeeded, under a message promising
32/// that the destination decides.
33pub(crate) fn validate_command_in_cwd(
34    command: &str,
35    write_allow_paths: &[String],
36    project_root: Option<&str>,
37    cwd: Option<&str>,
38) -> Option<String> {
39    if command.len() > MAX_COMMAND_BYTES {
40        return Some(format!(
41            "ERROR: Command too large ({} bytes, limit {}). \
42             If you're writing file content, use the native Write/Edit tool instead. \
43             ctx_shell is for reading command output only (git, cargo, npm, etc.).",
44            command.len(),
45            MAX_COMMAND_BYTES
46        ));
47    }
48
49    // #931: strip heredoc bodies before the redirect scanner — a `>` inside a
50    // heredoc body is opaque data, not a file-write redirect.
51    let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
52    // #1850: a relative target lands where its own command runs, and a `cd`
53    // earlier in the line moves that. Judging every target against the call's
54    // `cwd` blocked `cd /tmp && echo x > out.txt` and let `cd <project> && echo
55    // x > f` from a scratch cwd write straight into the project. Each segment
56    // is judged against its own directory; where that cannot be known, a
57    // relative target is refused.
58    let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
59    // #1768: the rule is the destination, not the size of the payload. The
60    // refusal used to justify itself with "MCP protocol corruption on large
61    // payloads" while the guard allows a megabyte into /tmp and blocks two
62    // bytes into a project file — so the stated reason argued *against* the
63    // verdict in both directions, and steered callers to retry smaller (no
64    // effect) or to avoid the sanctioned scratch capture. The reasons that
65    // actually hold are the ones #1303 and #1142 established: ctx_shell
66    // compresses what it returns, so output redirected into a file you keep
67    // can land there with compression markers instead of the command's own
68    // bytes; and a scratch capture is precisely how a large payload stays out
69    // of the MCP channel.
70    if let Some(target) = segments.iter().find_map(|(segment, here)| {
71        disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
72    }) {
73        return Some(format!(
74            "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
75             not the size of the output. ctx_shell compresses what it returns, so capturing \
76             that output into a file you keep can write compression markers instead of the \
77             command's own bytes. \
78             The rule is output capture (`>`, `>>`, `| tee`) into a project path — other \
79             commands are not restricted. \
80             Write the file with the native Write tool or ctx_patch, or capture to a scratch \
81             path (/tmp, /var/tmp, $TMPDIR), which is allowed and keeps the output out of \
82             the MCP channel entirely.{}",
83            relative_target_note(&target)
84        ));
85    }
86
87    // #989: tee detection must run on heredoc-stripped text to avoid false
88    // positives when the word "tee" appears in heredoc/quoted payloads.
89    //
90    // #1671: the rule is the destination, not the pipe. The message used to say
91    // "tee without pipe" and then state that piped tee is allowed — so it
92    // rejected a command and, in the next sentence, described that exact
93    // command as permitted. A reviewer read it, concluded the block was correct
94    // because an alternative was offered, and closed a review with no findings.
95    // Naming the pipe also sent callers off to restructure their pipeline,
96    // which cannot help: `… | tee FILE | wc -l` is judged identically.
97    if let Some(target) = segments.iter().find_map(|(segment, here)| {
98        disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
99    }) {
100        return Some(format!(
101            "ERROR: ctx_shell refuses `tee {target}` — the destination is inside the \
102             project, and ctx_shell compresses what it returns, so the captured bytes may \
103             not be the command's own. \
104             Piping makes no difference: the destination decides. \
105             The rule is output capture into a project path — other commands are not \
106             restricted. \
107             Write the file with the native Write tool, or tee to a scratch path \
108             (/tmp, /var/tmp, $TMPDIR), which is allowed.{}",
109            relative_target_note(&target)
110        ));
111    }
112
113    if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
114        return Some(
115            "ERROR: ctx_shell detected a heredoc writing to a file. \
116             ctx_shell compresses what it returns, so content it captures into a file may \
117             not be the bytes you wrote. Use the native Write tool to create the file. \
118             Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
119                .to_string(),
120        );
121    }
122
123    // #1672: on the heredoc-stripped text, for the same reason as #931 and
124    // #989 above. A download flag inside a heredoc *body* is opaque data — a
125    // commit message, a doc, a fixture — and refusing the call for it blocks
126    // writing about the guard at all. This detector was simply never switched
127    // over when the other two were.
128    if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
129        return Some(format!(
130            "ERROR: ctx_shell detected a file download/write ({reason}). \
131             Writing fetched bytes through ctx_shell risks capturing compressed output \
132             instead of the payload — redirect-free flags bypass the redirect check, so \
133             they are blocked too (GH #391). \
134             For text, fetch to stdout: curl <url> / wget -qO- <url>. \
135             For a binary (image, PDF, archive) neither stdout nor the editor's Write \
136             tool can carry the bytes — download to an absolute scratch path instead, \
137             e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661)."
138        ));
139    }
140
141    None
142}
143
144/// How a relative target is placed — said when one is refused, because the
145/// answer is usually to say where it should go (#1850).
146fn relative_target_note(target: &str) -> &'static str {
147    let t = target
148        .trim_start_matches(['>', '&', '|'])
149        .trim_matches(['"', '\'']);
150    if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
151        return "";
152    }
153    " A relative target is placed in the directory its own command runs in: the call's \
154     `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
155     known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
156     run — a relative target is refused; give an absolute path."
157}
158
159/// Each segment of the heredoc-stripped command with the directory it runs in,
160/// as a string for the path checks. An empty `cwd` is no `cwd`.
161fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
162    let base = cwd
163        .filter(|c| !c.trim().is_empty())
164        .map(std::path::Path::new);
165    crate::core::command_cwd::segments_with_cwd(command, base)
166        .into_iter()
167        .map(|s| {
168            let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
169            (s.segment, here)
170        })
171        .collect()
172}
173
174/// Well-known Unix scratch prefixes that agents use on every platform.
175/// On Windows, `/tmp/foo` is not a real absolute path, but Git Bash, WSL,
176/// and agent-generated commands routinely target it.  (#1467)
177fn is_unix_scratch_prefix(path: &str) -> bool {
178    for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
179        if path == prefix || path.starts_with(&format!("{prefix}/")) {
180            return true;
181        }
182    }
183    false
184}
185
186/// Detects download/copy tools writing directly to files via their own flags.
187/// Returns true when a path targets a scratch/temp location outside the
188/// project, where file downloads are safe (#1021).
189fn is_scratch_path(path: &str) -> bool {
190    if is_unix_scratch_prefix(path) {
191        return true;
192    }
193    if let Ok(tmpdir) = std::env::var("TMPDIR")
194        && !tmpdir.is_empty()
195        && std::path::Path::new(path).starts_with(tmpdir.as_str())
196    {
197        return true;
198    }
199    // Windows: %TEMP% / std::env::temp_dir()
200    let tmp = std::env::temp_dir();
201    if std::path::Path::new(path).starts_with(&tmp) {
202        return true;
203    }
204    false
205}
206
207/// (`curl -o`, `wget` default mode, `dd of=`) — the redirect-free equivalent of
208/// `> file`, reported as a `validate_command` bypass in GH #391.
209fn download_to_file_reason(command: &str) -> Option<String> {
210    // #1661: the scratch carve-out is written in absolute paths, but agents
211    // reach a scratch directory the way a person would — `cd <scratchpad> &&
212    // curl -o shot.png …`. Judged as the bare string `shot.png`, a target that
213    // lands squarely inside the sanctioned directory looked like a project
214    // write and was blocked, leaving no in-tool way to fetch a binary at all.
215    // Segments are paired with the directory they actually run in so a relative
216    // target is judged where it lands.
217    for seg_cwd in crate::core::command_cwd::segments_with_cwd(command, None) {
218        let seg = seg_cwd.segment;
219        let here = seg_cwd.cwd;
220        let resolve = |path: &str| -> String {
221            let p = std::path::Path::new(path);
222            // `starts_with('/')`: shell text, so a Unix-absolute target is
223            // absolute on Windows too, where `is_absolute` disagrees (#1467).
224            if p.is_absolute() || path.starts_with('/') {
225                return path.to_string();
226            }
227            // Without a known directory the target stays unresolved, which the
228            // scratch check then rejects — the guard errs closed.
229            match here.as_deref() {
230                Some(dir) => crate::core::command_cwd::join_in(dir, path)
231                    .to_string_lossy()
232                    .into_owned(),
233                None => path.to_string(),
234            }
235        };
236        let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
237        let Some(first) = tokens.first() else {
238            continue;
239        };
240        let base = first.rsplit('/').next().unwrap_or(first);
241        match base {
242            "curl" => {
243                let tokens_slice = &tokens[1..];
244                for (i, tok) in tokens_slice.iter().enumerate() {
245                    let target: Option<&str> = if tok == "--output" {
246                        tokens_slice.get(i + 1).map(String::as_str)
247                    } else if let Some(val) = tok.strip_prefix("--output=") {
248                        Some(val)
249                    } else if tok == "--output-dir" {
250                        tokens_slice.get(i + 1).map(String::as_str)
251                    } else if let Some(val) = tok.strip_prefix("--output-dir=") {
252                        Some(val)
253                    } else if tok.starts_with('-')
254                        && !tok.starts_with("--")
255                        && tok[1..].contains('o')
256                    {
257                        // -o <file>: next token is the path
258                        tokens_slice.get(i + 1).map(String::as_str)
259                    } else if tok == "--remote-name"
260                        || tok == "--remote-name-all"
261                        || (tok.starts_with('-')
262                            && !tok.starts_with("--")
263                            && tok[1..].contains('O'))
264                    {
265                        Some(".")
266                    } else {
267                        None
268                    };
269                    if let Some(path) = target {
270                        if is_scratch_path(&resolve(path)) {
271                            continue;
272                        }
273                        return Some(format!("curl {tok}"));
274                    }
275                }
276            }
277            "wget" => {
278                // wget writes a file BY DEFAULT; only stdout/no-download modes pass.
279                let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
280                    tok == "--output-document=-"
281                        || tok == "-O-"
282                        || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
283                        || ((tok == "-O" || tok == "--output-document")
284                            && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
285                        || tok == "--spider"
286                });
287                if !to_stdout {
288                    return Some(
289                        "wget downloads to a file by default; use wget -qO- <url> for stdout"
290                            .to_string(),
291                    );
292                }
293            }
294            "dd" => {
295                for tok in &tokens[1..] {
296                    if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
297                        return Some(format!("dd {tok}"));
298                    }
299                }
300            }
301            _ => {}
302        }
303    }
304    None
305}
306
307/// Returns true only for heredocs that redirect to files (the dangerous pattern).
308/// Legitimate heredoc uses (input piping, inline scripts) are allowed through.
309/// `segments` is the heredoc-stripped command with each segment's directory.
310fn is_heredoc_file_write(
311    command: &str,
312    segments: &[(String, Option<String>)],
313    write_allow_paths: &[String],
314    project_root: Option<&str>,
315) -> bool {
316    let has_heredoc = command.contains("<<");
317    if !has_heredoc {
318        return false;
319    }
320    let cmd_lower = command.to_lowercase();
321    let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
322    let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
323    if !has_known_heredoc {
324        return false;
325    }
326    // #931: the segments come from the heredoc-stripped text, so `>` / `>>`
327    // inside the body are not mistaken for file-write redirects.
328    segments.iter().any(|(segment, here)| {
329        disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
330            .is_some()
331    })
332}
333
334/// Detects shell redirect operators (`>` or `>>`) that write to files.
335/// Ignores `>` inside quotes, after a backslash escape (`\"` must not toggle
336/// quote state, `\>` is a literal), `2>` (stderr), `/dev/null`, and
337/// comparison operators.
338/// #848: temp directory targets are read-back, not persistent writes.
339/// #848/#989: targets that are NOT persistent project-file writes.
340/// Redirecting to temp dirs, /dev/* devices, or paths containing shell
341/// variables (which we cannot resolve at parse time) is output capture,
342/// not file authoring.
343pub fn is_temp_redirect_target(target: &str) -> bool {
344    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
345    // No cwd here: this public helper judges a target in isolation, so a
346    // relative one stays unplaceable and therefore not allowed (#1811).
347    is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
348}
349
350fn is_write_allowed_redirect_target(
351    target: &str,
352    write_allow_paths: &[String],
353    project_root: Option<&str>,
354    cwd: Option<&str>,
355) -> bool {
356    // `>|` is the noclobber-override form of `>`; the `|` is not part of the path.
357    let t = target.trim_start_matches(['>', '&', '|']);
358    // #1142: agents quote scratch paths (`> "$TMPDIR/x.log"`, `> "/private/tmp/x"`);
359    // strip quotes so quoted and unquoted targets are judged identically.
360    let t = t.trim_matches(['"', '\'']);
361    if t.starts_with('$') || t.starts_with("${") {
362        // Preserve #989's escape hatch for harness-provided scratch paths.
363        return true;
364    }
365
366    // On Windows, agents often use Unix-style /tmp paths (Git Bash, WSL,
367    // or Claude generating Unix commands).  `/tmp/foo` is not absolute per
368    // std::path on Windows, so check well-known scratch prefixes before
369    // the is_absolute gate.  (#1467)
370    if is_unix_scratch_prefix(t) {
371        return true;
372    }
373
374    // #1811: a relative target is a destination like any other — it just needs
375    // placing first. The guard used to refuse every relative target outright,
376    // so `cwd=<scratch> … > probe.txt` was blocked while the identical
377    // `> <scratch>/probe.txt` was allowed, and the refusal said "the
378    // destination decides" about a destination it had not resolved.
379    //
380    // Resolving narrows as often as it widens: a relative target under a
381    // project cwd now resolves *into* the project and is refused on the same
382    // rule as an absolute one, instead of by accident of its spelling.
383    //
384    // `cwd` is the directory the target's own command runs in — the call's
385    // `cwd` moved by any `cd` before it (#1850, `command_cwd`), or `None` when
386    // that cannot be known, which refuses a relative target below.
387    let path = std::path::Path::new(t);
388    let resolved_input;
389    let path = if path.is_absolute() {
390        path
391    } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
392        resolved_input = std::path::Path::new(base).join(path);
393        resolved_input.as_path()
394    } else {
395        return false;
396    };
397    let resolved = resolve_path_for_comparison(path);
398    if project_root.is_some_and(|root| {
399        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
400    }) {
401        return false;
402    }
403    write_allow_paths.iter().any(|allowed| {
404        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
405    })
406}
407
408fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
409    use std::path::{Component, PathBuf};
410
411    let mut normalized = PathBuf::new();
412    for component in path.components() {
413        match component {
414            Component::CurDir => {}
415            Component::ParentDir => {
416                normalized.pop();
417            }
418            other => normalized.push(other.as_os_str()),
419        }
420    }
421
422    let mut unresolved = Vec::new();
423    let mut existing = normalized.clone();
424    while !existing.exists() {
425        let Some(name) = existing.file_name() else {
426            break;
427        };
428        unresolved.push(name.to_os_string());
429        if !existing.pop() {
430            break;
431        }
432    }
433    let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
434    for component in unresolved.iter().rev() {
435        resolved.push(component);
436    }
437    resolved
438}
439
440fn tee_targets(command: &str) -> Vec<String> {
441    crate::core::shell_allowlist::extract_all_commands_pub(command)
442        .into_iter()
443        .filter_map(|segment| {
444            let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
445            let first = tokens.first()?;
446            if first.rsplit('/').next().unwrap_or(first) != "tee" {
447                return None;
448            }
449            let mut after_separator = false;
450            Some(
451                tokens
452                    .iter()
453                    .skip(1)
454                    .find(|token| {
455                        if *token == "--" {
456                            after_separator = true;
457                            return false;
458                        }
459                        after_separator || !token.starts_with('-')
460                    })
461                    .cloned()
462                    .unwrap_or_default(),
463            )
464        })
465        .collect()
466}
467
468/// The first `tee` destination that is not a permitted write target.
469///
470/// Returns the path so the refusal can name it (#1671). The rule is entirely
471/// about the destination — whether the `tee` is piped makes no difference — and
472/// a message that cannot name the destination ends up describing some other
473/// rule instead.
474fn disallowed_tee_target(
475    command: &str,
476    write_allow_paths: &[String],
477    project_root: Option<&str>,
478    cwd: Option<&str>,
479) -> Option<String> {
480    tee_targets(command).into_iter().find(|target| {
481        !target.is_empty()
482            && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
483    })
484}
485
486/// True when the command redirects into a path it may not write.
487///
488/// Test-only convenience: every production caller needs the offending target
489/// for its message and goes to [`disallowed_write_redirect_target`] directly
490/// (#1768). The assertions here only care about the verdict, and reading
491/// `.is_some()` into every one of them would obscure what they pin.
492#[cfg(test)]
493fn has_file_write_redirect(
494    command: &str,
495    write_allow_paths: &[String],
496    project_root: Option<&str>,
497) -> bool {
498    // No cwd: these assertions pin the target-spelling rules, where a relative
499    // target is unplaceable and therefore refused (#1811). The cwd-resolution
500    // behaviour has its own tests that call the public entry point.
501    disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
502}
503
504/// The first redirect target that is **not** write-allowed, or `None` when the
505/// command writes nowhere it may not.
506///
507/// Returns the target rather than a bare verdict so the refusal can name what
508/// tripped it (#1768) — the same reason [`disallowed_tee_target`] exists. A
509/// guard that states a rule the caller cannot map onto their own command gets
510/// read as something else (there, "piping"; here, "large payloads"), and every
511/// such misreading sends the caller somewhere that cannot help.
512fn disallowed_write_redirect_target(
513    command: &str,
514    write_allow_paths: &[String],
515    project_root: Option<&str>,
516    cwd: Option<&str>,
517) -> Option<String> {
518    let bytes = command.as_bytes();
519    let len = bytes.len();
520    let mut i = 0;
521    let mut in_single_quote = false;
522    let mut in_double_quote = false;
523
524    while i < len {
525        let c = bytes[i];
526        if c == b'\\' && !in_single_quote {
527            // A backslash escapes the next byte (POSIX: outside quotes and
528            // inside double quotes; inside single quotes it is literal).
529            // Without this, an escaped quote like `\"` toggled the quote
530            // state and literal `>` in quoted prose (e.g. `(root: <root>)`
531            // in a gh --body string) read as a redirect (#903).
532            i += 2;
533            continue;
534        }
535        if c == b'\'' && !in_double_quote {
536            in_single_quote = !in_single_quote;
537        } else if c == b'"' && !in_single_quote {
538            in_double_quote = !in_double_quote;
539        } else if c == b'>' && !in_single_quote && !in_double_quote {
540            if i > 0 && bytes[i - 1] == b'2' {
541                i += 1;
542                continue;
543            }
544            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
545                i + 2
546            } else {
547                i + 1
548            };
549            // The redirect *operator* can carry one more character: `>|`
550            // overrides noclobber and `>&` duplicates a descriptor. Neither
551            // belongs to the target word, so strip it before reading the word
552            // and re-attach `&` for the fd check below.
553            let rest = command[target_start..].trim_start();
554            let (rest, fd_dup) = match rest.strip_prefix('|') {
555                Some(r) => (r, false),
556                None => match rest.strip_prefix('&') {
557                    Some(r) => (r, true),
558                    None => (rest, false),
559                },
560            };
561            // The word ends at whitespace *or* at a shell metacharacter
562            // (#1659). Stopping only at whitespace made the verdict depend on
563            // where the redirect sat: `echo a 1>/dev/null` read the target as
564            // `/dev/null` and was allowed, while `echo a 1>/dev/null; echo b`
565            // read `/dev/null;` — semicolon included, since it is not
566            // whitespace — missed the /dev/null exemption, and was blocked as a
567            // file write. `&&` happened to work only because a space precedes
568            // it. Same redirect, same shell semantics, opposite verdicts.
569            //
570            // `(` is deliberately not a terminator: it would reduce the
571            // process-substitution target `>(cmd)` to an empty word, and an
572            // empty word falls through unblocked.
573            let word: String = rest
574                .chars()
575                .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
576                .collect();
577            let target = if fd_dup { format!("&{word}") } else { word };
578            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
579                i += 1;
580                continue;
581            }
582            // #1142: `>&1` / `>&2` duplicate a file descriptor — no file involved.
583            // (`2>&1` is already skipped by the `2>` case above.)
584            if let Some(fd) = target.strip_prefix('&')
585                && !fd.is_empty()
586                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
587            {
588                i += 1;
589                continue;
590            }
591            // #848: allow redirects to temp directories — agents capture
592            // build output for grepping, not writing persistent files.
593            if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
594                i += 1;
595                continue;
596            }
597            if !target.is_empty() {
598                return Some(target);
599            }
600        }
601        i += 1;
602    }
603    None
604}
605
606/// On Windows cmd.exe, `;` is not a valid command separator.
607/// Convert `cmd1; cmd2` to `cmd1 && cmd2` when running under cmd.exe.
608pub fn normalize_command_for_shell(command: &str) -> String {
609    if !cfg!(windows) {
610        return command.to_string();
611    }
612    let (_, flag) = crate::shell::shell_and_flag();
613    if flag != "/C" {
614        return command.to_string();
615    }
616    let bytes = command.as_bytes();
617    let mut result = Vec::with_capacity(bytes.len() + 16);
618    let mut in_single = false;
619    let mut in_double = false;
620    for (i, &b) in bytes.iter().enumerate() {
621        if b == b'\'' && !in_double {
622            in_single = !in_single;
623        } else if b == b'"' && !in_single {
624            in_double = !in_double;
625        } else if b == b';' && !in_single && !in_double {
626            result.extend_from_slice(b" && ");
627            continue;
628        }
629        result.push(b);
630        let _ = i;
631    }
632    String::from_utf8(result).unwrap_or_else(|_| command.to_string())
633}
634
635/// Compresses shell command output using the unified compression pipeline.
636/// Delegates to the same exit-code-aware logic used by the CLI, so a failed
637/// command (`exit_code != 0`) is preserved verbatim and successful output is
638/// compressed consistently (excluded_commands, structural routing, terse). #810.
639pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
640    crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
641}
642
643pub fn handle_with_context(
644    command: &str,
645    output: &str,
646    exit_code: i32,
647    crp_mode: CrpMode,
648    project_root: Option<&str>,
649) -> String {
650    let mut result = handle(command, output, exit_code, crp_mode);
651
652    {
653        if let Some(root) = project_root {
654            let estimated_tokens = result.len() / 4;
655            if estimated_tokens > 500 {
656                let kernel_budget = 100;
657                if let Some(enrichment) =
658                    crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
659                    && !enrichment.blocks.is_empty()
660                {
661                    result.push_str("\n--- kernel context ---\n");
662                    result.push_str(&enrichment.blocks);
663                }
664            }
665        }
666    }
667
668    result
669}
670
671#[cfg(test)]
672mod kernel_tests {
673    use super::handle_with_context;
674    use crate::tools::CrpMode;
675
676    #[test]
677    fn handle_with_context_does_not_panic_on_short_output() {
678        let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
679        assert!(!result.is_empty());
680    }
681}
682
683#[cfg(test)]
684fn is_search_command(command: &str) -> bool {
685    let cmd = command.trim_start();
686    cmd.starts_with("grep ")
687        || cmd.starts_with("rg ")
688        || cmd.starts_with("find ")
689        || cmd.starts_with("fd ")
690        || cmd.starts_with("ag ")
691        || cmd.starts_with("ack ")
692}
693
694#[cfg(test)]
695fn generic_compress(output: &str) -> String {
696    let output = crate::core::compressor::strip_ansi(output);
697    let lines: Vec<&str> = output
698        .lines()
699        .filter(|l| {
700            let t = l.trim();
701            !t.is_empty()
702        })
703        .collect();
704
705    if lines.len() <= 20 {
706        return lines.join("\n");
707    }
708
709    let show_count = (lines.len() / 3).min(30);
710    let half = show_count / 2;
711    let first = &lines[..half];
712    let last = &lines[lines.len() - half..];
713    let omitted = lines.len() - (half * 2);
714    format!(
715        "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
716        first.join("\n"),
717        half * 2,
718        lines.len(),
719        omitted,
720        last.join("\n")
721    )
722}
723
724/// Detects OAuth device code flow output that must not be compressed.
725/// Uses a two-tier approach: strong signals match alone (very specific to
726/// device code flows), weak signals require a URL/domain in the same output.
727pub fn contains_auth_flow(output: &str) -> bool {
728    let lower = output.to_lowercase();
729
730    const STRONG_SIGNALS: &[&str] = &[
731        "devicelogin",
732        "deviceauth",
733        "device_code",
734        "device code",
735        "device-code",
736        "verification_uri",
737        "user_code",
738        "one-time code",
739    ];
740
741    if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
742        return true;
743    }
744
745    const WEAK_SIGNALS: &[&str] = &[
746        "enter the code",
747        "enter this code",
748        "enter code:",
749        "use the code",
750        "use a web browser to open",
751        "open the page",
752        "authenticate by visiting",
753        "sign in with the code",
754        "sign in using a code",
755        "verification code",
756        "authorize this device",
757        "waiting for authentication",
758        "waiting for login",
759        "waiting for you to authenticate",
760        "open your browser",
761        "open in your browser",
762    ];
763
764    let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
765    if !has_weak_signal {
766        return false;
767    }
768
769    lower.contains("http://") || lower.contains("https://")
770}
771
772#[cfg(test)]
773mod tests;