1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5pub 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
13pub(crate) fn validate_command_with_write_allow_paths(
14 command: &str,
15 write_allow_paths: &[String],
16 project_root: Option<&str>,
17) -> Option<String> {
18 if command.len() > MAX_COMMAND_BYTES {
19 return Some(format!(
20 "ERROR: Command too large ({} bytes, limit {}). \
21 If you're writing file content, use the native Write/Edit tool instead. \
22 ctx_shell is for reading command output only (git, cargo, npm, etc.).",
23 command.len(),
24 MAX_COMMAND_BYTES
25 ));
26 }
27
28 let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
31 if let Some(target) =
43 disallowed_write_redirect_target(&cmd_no_heredoc, write_allow_paths, project_root)
44 {
45 return Some(format!(
46 "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
47 not the size of the output. ctx_shell compresses what it returns, so a redirect \
48 into a file you keep can write compression markers instead of the command's own \
49 bytes, and ctx_shell never modifies project files. \
50 Use the native Write tool or ctx_patch for project files. \
51 Capturing output to a scratch path (/tmp, /var/tmp, $TMPDIR) is allowed — that \
52 keeps the output out of the MCP channel entirely."
53 ));
54 }
55
56 if let Some(target) = disallowed_tee_target(&cmd_no_heredoc, write_allow_paths, project_root) {
67 return Some(format!(
68 "ERROR: ctx_shell refuses `tee {target}` — the destination is inside the \
69 project, and ctx_shell is ONLY for reading command output. \
70 Piping makes no difference: the destination decides. \
71 Use the native Write tool to create/modify project files, or tee to a \
72 scratch path (/tmp, /var/tmp, $TMPDIR), which is allowed."
73 ));
74 }
75
76 if is_heredoc_file_write(command, write_allow_paths, project_root) {
77 return Some(
78 "ERROR: ctx_shell detected a heredoc writing to a file. \
79 Use the native Write tool to create/modify files. \
80 ctx_shell is ONLY for reading command output. \
81 Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
82 .to_string(),
83 );
84 }
85
86 if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
92 return Some(format!(
93 "ERROR: ctx_shell detected a file download/write ({reason}). \
94 ctx_shell is ONLY for reading command output — redirect-free flags bypass \
95 this doctrine, so they are blocked too (GH #391). \
96 For text, fetch to stdout: curl <url> / wget -qO- <url>. \
97 For a binary (image, PDF, archive) neither stdout nor the editor's Write \
98 tool can carry the bytes — download to an absolute scratch path instead, \
99 e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661)."
100 ));
101 }
102
103 None
104}
105
106fn is_unix_scratch_prefix(path: &str) -> bool {
110 for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
111 if path == prefix || path.starts_with(&format!("{prefix}/")) {
112 return true;
113 }
114 }
115 false
116}
117
118fn is_scratch_path(path: &str) -> bool {
122 if is_unix_scratch_prefix(path) {
123 return true;
124 }
125 if let Ok(tmpdir) = std::env::var("TMPDIR")
126 && !tmpdir.is_empty()
127 && std::path::Path::new(path).starts_with(tmpdir.as_str())
128 {
129 return true;
130 }
131 let tmp = std::env::temp_dir();
133 if std::path::Path::new(path).starts_with(&tmp) {
134 return true;
135 }
136 false
137}
138
139fn download_to_file_reason(command: &str) -> Option<String> {
142 for seg_cwd in crate::core::command_cwd::segments_with_cwd(command, None) {
150 let seg = seg_cwd.segment;
151 let here = seg_cwd.cwd;
152 let resolve = |path: &str| -> String {
153 let p = std::path::Path::new(path);
154 if p.is_absolute() || path.starts_with('/') {
157 return path.to_string();
158 }
159 match here.as_deref() {
162 Some(dir) => crate::core::command_cwd::join_in(dir, path)
163 .to_string_lossy()
164 .into_owned(),
165 None => path.to_string(),
166 }
167 };
168 let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
169 let Some(first) = tokens.first() else {
170 continue;
171 };
172 let base = first.rsplit('/').next().unwrap_or(first);
173 match base {
174 "curl" => {
175 let tokens_slice = &tokens[1..];
176 for (i, tok) in tokens_slice.iter().enumerate() {
177 let target: Option<&str> = if tok == "--output" {
178 tokens_slice.get(i + 1).map(String::as_str)
179 } else if let Some(val) = tok.strip_prefix("--output=") {
180 Some(val)
181 } else if tok == "--output-dir" {
182 tokens_slice.get(i + 1).map(String::as_str)
183 } else if let Some(val) = tok.strip_prefix("--output-dir=") {
184 Some(val)
185 } else if tok.starts_with('-')
186 && !tok.starts_with("--")
187 && tok[1..].contains('o')
188 {
189 tokens_slice.get(i + 1).map(String::as_str)
191 } else if tok == "--remote-name"
192 || tok == "--remote-name-all"
193 || (tok.starts_with('-')
194 && !tok.starts_with("--")
195 && tok[1..].contains('O'))
196 {
197 Some(".")
198 } else {
199 None
200 };
201 if let Some(path) = target {
202 if is_scratch_path(&resolve(path)) {
203 continue;
204 }
205 return Some(format!("curl {tok}"));
206 }
207 }
208 }
209 "wget" => {
210 let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
212 tok == "--output-document=-"
213 || tok == "-O-"
214 || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
215 || ((tok == "-O" || tok == "--output-document")
216 && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
217 || tok == "--spider"
218 });
219 if !to_stdout {
220 return Some(
221 "wget downloads to a file by default; use wget -qO- <url> for stdout"
222 .to_string(),
223 );
224 }
225 }
226 "dd" => {
227 for tok in &tokens[1..] {
228 if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
229 return Some(format!("dd {tok}"));
230 }
231 }
232 }
233 _ => {}
234 }
235 }
236 None
237}
238
239fn is_heredoc_file_write(
242 command: &str,
243 write_allow_paths: &[String],
244 project_root: Option<&str>,
245) -> bool {
246 let has_heredoc = command.contains("<<");
247 if !has_heredoc {
248 return false;
249 }
250 let cmd_lower = command.to_lowercase();
251 let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
252 let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
253 if !has_known_heredoc {
254 return false;
255 }
256 let stripped = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
259 disallowed_write_redirect_target(&stripped, write_allow_paths, project_root).is_some()
260}
261
262pub fn is_temp_redirect_target(target: &str) -> bool {
272 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
273 is_write_allowed_redirect_target(target, &write_allow_paths, None)
274}
275
276fn is_write_allowed_redirect_target(
277 target: &str,
278 write_allow_paths: &[String],
279 project_root: Option<&str>,
280) -> bool {
281 let t = target.trim_start_matches(['>', '&', '|']);
283 let t = t.trim_matches(['"', '\'']);
286 if t.starts_with('$') || t.starts_with("${") {
287 return true;
289 }
290
291 if is_unix_scratch_prefix(t) {
296 return true;
297 }
298
299 let path = std::path::Path::new(t);
300 if !path.is_absolute() {
301 return false;
302 }
303 let resolved = resolve_path_for_comparison(path);
304 if project_root.is_some_and(|root| {
305 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
306 }) {
307 return false;
308 }
309 write_allow_paths.iter().any(|allowed| {
310 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
311 })
312}
313
314fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
315 use std::path::{Component, PathBuf};
316
317 let mut normalized = PathBuf::new();
318 for component in path.components() {
319 match component {
320 Component::CurDir => {}
321 Component::ParentDir => {
322 normalized.pop();
323 }
324 other => normalized.push(other.as_os_str()),
325 }
326 }
327
328 let mut unresolved = Vec::new();
329 let mut existing = normalized.clone();
330 while !existing.exists() {
331 let Some(name) = existing.file_name() else {
332 break;
333 };
334 unresolved.push(name.to_os_string());
335 if !existing.pop() {
336 break;
337 }
338 }
339 let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
340 for component in unresolved.iter().rev() {
341 resolved.push(component);
342 }
343 resolved
344}
345
346fn tee_targets(command: &str) -> Vec<String> {
347 crate::core::shell_allowlist::extract_all_commands_pub(command)
348 .into_iter()
349 .filter_map(|segment| {
350 let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
351 let first = tokens.first()?;
352 if first.rsplit('/').next().unwrap_or(first) != "tee" {
353 return None;
354 }
355 let mut after_separator = false;
356 Some(
357 tokens
358 .iter()
359 .skip(1)
360 .find(|token| {
361 if *token == "--" {
362 after_separator = true;
363 return false;
364 }
365 after_separator || !token.starts_with('-')
366 })
367 .cloned()
368 .unwrap_or_default(),
369 )
370 })
371 .collect()
372}
373
374fn disallowed_tee_target(
381 command: &str,
382 write_allow_paths: &[String],
383 project_root: Option<&str>,
384) -> Option<String> {
385 tee_targets(command).into_iter().find(|target| {
386 !target.is_empty()
387 && !is_write_allowed_redirect_target(target, write_allow_paths, project_root)
388 })
389}
390
391#[cfg(test)]
398fn has_file_write_redirect(
399 command: &str,
400 write_allow_paths: &[String],
401 project_root: Option<&str>,
402) -> bool {
403 disallowed_write_redirect_target(command, write_allow_paths, project_root).is_some()
404}
405
406fn disallowed_write_redirect_target(
415 command: &str,
416 write_allow_paths: &[String],
417 project_root: Option<&str>,
418) -> Option<String> {
419 let bytes = command.as_bytes();
420 let len = bytes.len();
421 let mut i = 0;
422 let mut in_single_quote = false;
423 let mut in_double_quote = false;
424
425 while i < len {
426 let c = bytes[i];
427 if c == b'\\' && !in_single_quote {
428 i += 2;
434 continue;
435 }
436 if c == b'\'' && !in_double_quote {
437 in_single_quote = !in_single_quote;
438 } else if c == b'"' && !in_single_quote {
439 in_double_quote = !in_double_quote;
440 } else if c == b'>' && !in_single_quote && !in_double_quote {
441 if i > 0 && bytes[i - 1] == b'2' {
442 i += 1;
443 continue;
444 }
445 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
446 i + 2
447 } else {
448 i + 1
449 };
450 let rest = command[target_start..].trim_start();
455 let (rest, fd_dup) = match rest.strip_prefix('|') {
456 Some(r) => (r, false),
457 None => match rest.strip_prefix('&') {
458 Some(r) => (r, true),
459 None => (rest, false),
460 },
461 };
462 let word: String = rest
475 .chars()
476 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
477 .collect();
478 let target = if fd_dup { format!("&{word}") } else { word };
479 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
480 i += 1;
481 continue;
482 }
483 if let Some(fd) = target.strip_prefix('&')
486 && !fd.is_empty()
487 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
488 {
489 i += 1;
490 continue;
491 }
492 if is_write_allowed_redirect_target(&target, write_allow_paths, project_root) {
495 i += 1;
496 continue;
497 }
498 if !target.is_empty() {
499 return Some(target);
500 }
501 }
502 i += 1;
503 }
504 None
505}
506
507pub fn normalize_command_for_shell(command: &str) -> String {
510 if !cfg!(windows) {
511 return command.to_string();
512 }
513 let (_, flag) = crate::shell::shell_and_flag();
514 if flag != "/C" {
515 return command.to_string();
516 }
517 let bytes = command.as_bytes();
518 let mut result = Vec::with_capacity(bytes.len() + 16);
519 let mut in_single = false;
520 let mut in_double = false;
521 for (i, &b) in bytes.iter().enumerate() {
522 if b == b'\'' && !in_double {
523 in_single = !in_single;
524 } else if b == b'"' && !in_single {
525 in_double = !in_double;
526 } else if b == b';' && !in_single && !in_double {
527 result.extend_from_slice(b" && ");
528 continue;
529 }
530 result.push(b);
531 let _ = i;
532 }
533 String::from_utf8(result).unwrap_or_else(|_| command.to_string())
534}
535
536pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
541 crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
542}
543
544pub fn handle_with_context(
545 command: &str,
546 output: &str,
547 exit_code: i32,
548 crp_mode: CrpMode,
549 project_root: Option<&str>,
550) -> String {
551 let mut result = handle(command, output, exit_code, crp_mode);
552
553 {
554 if let Some(root) = project_root {
555 let estimated_tokens = result.len() / 4;
556 if estimated_tokens > 500 {
557 let kernel_budget = 100;
558 if let Some(enrichment) =
559 crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
560 && !enrichment.blocks.is_empty()
561 {
562 result.push_str("\n--- kernel context ---\n");
563 result.push_str(&enrichment.blocks);
564 }
565 }
566 }
567 }
568
569 result
570}
571
572#[cfg(test)]
573mod kernel_tests {
574 use super::handle_with_context;
575 use crate::tools::CrpMode;
576
577 #[test]
578 fn handle_with_context_does_not_panic_on_short_output() {
579 let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
580 assert!(!result.is_empty());
581 }
582}
583
584#[cfg(test)]
585fn is_search_command(command: &str) -> bool {
586 let cmd = command.trim_start();
587 cmd.starts_with("grep ")
588 || cmd.starts_with("rg ")
589 || cmd.starts_with("find ")
590 || cmd.starts_with("fd ")
591 || cmd.starts_with("ag ")
592 || cmd.starts_with("ack ")
593}
594
595#[cfg(test)]
596fn generic_compress(output: &str) -> String {
597 let output = crate::core::compressor::strip_ansi(output);
598 let lines: Vec<&str> = output
599 .lines()
600 .filter(|l| {
601 let t = l.trim();
602 !t.is_empty()
603 })
604 .collect();
605
606 if lines.len() <= 20 {
607 return lines.join("\n");
608 }
609
610 let show_count = (lines.len() / 3).min(30);
611 let half = show_count / 2;
612 let first = &lines[..half];
613 let last = &lines[lines.len() - half..];
614 let omitted = lines.len() - (half * 2);
615 format!(
616 "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
617 first.join("\n"),
618 half * 2,
619 lines.len(),
620 omitted,
621 last.join("\n")
622 )
623}
624
625pub fn contains_auth_flow(output: &str) -> bool {
629 let lower = output.to_lowercase();
630
631 const STRONG_SIGNALS: &[&str] = &[
632 "devicelogin",
633 "deviceauth",
634 "device_code",
635 "device code",
636 "device-code",
637 "verification_uri",
638 "user_code",
639 "one-time code",
640 ];
641
642 if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
643 return true;
644 }
645
646 const WEAK_SIGNALS: &[&str] = &[
647 "enter the code",
648 "enter this code",
649 "enter code:",
650 "use the code",
651 "use a web browser to open",
652 "open the page",
653 "authenticate by visiting",
654 "sign in with the code",
655 "sign in using a code",
656 "verification code",
657 "authorize this device",
658 "waiting for authentication",
659 "waiting for login",
660 "waiting for you to authenticate",
661 "open your browser",
662 "open in your browser",
663 ];
664
665 let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
666 if !has_weak_signal {
667 return false;
668 }
669
670 lower.contains("http://") || lower.contains("https://")
671}
672
673#[cfg(test)]
674mod tests;