use crate::tools::CrpMode;
const MAX_COMMAND_BYTES: usize = 8192;
pub fn validate_command(command: &str) -> Option<String> {
let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
let project_root = crate::core::config::Config::find_project_root();
validate_command_with_write_allow_paths(command, &write_allow_paths, project_root.as_deref())
}
pub(crate) fn validate_command_with_write_allow_paths(
command: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
) -> Option<String> {
validate_command_in_cwd(command, write_allow_paths, project_root, None)
}
const CAPTURE_RULE: &str = "The rule: output capture (`>`, `>>`, `| tee`) may go to the \
session's project, a directory in `allow_paths` / `extra_roots`, a directory listed in \
`write_allow_paths` in config.toml, or a scratch path (/tmp, /var/tmp, $TMPDIR). Every \
other destination is refused. Commands that do not capture output are not restricted.";
pub(crate) fn capture_roots(
project_root: &str,
session_extra_roots: &[String],
cfg: &crate::core::config::Config,
) -> Vec<String> {
std::iter::once(project_root.to_string())
.chain(session_extra_roots.iter().cloned())
.chain(cfg.allow_paths.iter().cloned())
.chain(cfg.extra_roots.iter().cloned())
.filter(|raw| !raw.trim().is_empty())
.map(|raw| crate::core::pathjail::expand_user_path(&raw))
.filter(|path| {
let contains_home = dirs::home_dir().is_some_and(|home| home.starts_with(path));
path.is_absolute()
&& !contains_home
&& !crate::core::pathutil::is_broad_or_unsafe_root(path)
&& !crate::core::pathjail::is_read_only_path(path)
})
.map(|path| path.to_string_lossy().into_owned())
.collect()
}
const WRITE_REASON: &str = "Files you keep are written with ctx_patch or the native Write/Edit \
tool, so the read-before-write gate and the edit checks apply to them; ctx_shell does not \
write them through output capture. This is unconditional: the redirect itself is not \
compressed, so a smaller command or `raw=true` does not change the verdict.";
pub(crate) fn validate_command_in_cwd(
command: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
cwd: Option<&str>,
) -> Option<String> {
if command.len() > MAX_COMMAND_BYTES {
return Some(format!(
"ERROR: Command too large ({} bytes, limit {}). \
If you're writing file content, use the native Write/Edit tool instead. \
ctx_shell is for reading command output only (git, cargo, npm, etc.).",
command.len(),
MAX_COMMAND_BYTES
));
}
let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
if let Some(target) = segments.iter().find_map(|(segment, here)| {
disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
}) {
return Some(format!(
"ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
not the size or content of the output. {WRITE_REASON} {CAPTURE_RULE} \
Write the file with ctx_patch or the native Write tool, or capture to a scratch \
path.{}",
relative_target_note(&target)
));
}
if let Some(target) = segments.iter().find_map(|(segment, here)| {
disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
}) {
return Some(format!(
"ERROR: ctx_shell refuses `tee {target}`. Piping makes no difference: the \
destination decides. {WRITE_REASON} {CAPTURE_RULE} \
Write the file with ctx_patch or the native Write tool, or tee to a scratch \
path.{}",
relative_target_note(&target)
));
}
if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
return Some(format!(
"ERROR: ctx_shell detected a heredoc writing to a file. {WRITE_REASON} \
Create the file with ctx_patch (op=create) or the native Write tool. \
Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
));
}
if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
return Some(format!(
"ERROR: ctx_shell detected a file download/write ({reason}). \
Download flags write a file without a redirect, so the capture rule applies \
to them as well (GH #391). \
For text, fetch to stdout: curl <url> / wget -qO- <url>. \
For a binary (image, PDF, archive) neither stdout nor the editor's Write \
tool can carry the bytes — download to an absolute scratch path instead, \
e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661). \
The target must be a literal path, $TMPDIR, or a variable this same command \
set to a literal earlier (D=/tmp/x; curl -o $D/f); any other variable cannot \
be resolved here and is refused."
));
}
None
}
fn relative_target_note(target: &str) -> &'static str {
let t = target
.trim_start_matches(['>', '&', '|'])
.trim_matches(['"', '\'']);
if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
return "";
}
" A relative target is placed in the directory its own command runs in: the call's \
`cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
run — a relative target is refused; give an absolute path."
}
fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
let base = cwd
.filter(|c| !c.trim().is_empty())
.map(std::path::Path::new);
crate::core::command_cwd::segments_with_cwd(command, base)
.into_iter()
.map(|s| {
let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
(s.segment, here)
})
.collect()
}
fn is_unix_scratch_prefix(path: &str) -> bool {
for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
if path == prefix || path.starts_with(&format!("{prefix}/")) {
return true;
}
}
false
}
fn is_scratch_path(path: &str) -> bool {
if is_unix_scratch_prefix(path) {
return true;
}
if let Ok(tmpdir) = std::env::var("TMPDIR")
&& !tmpdir.is_empty()
&& std::path::Path::new(path).starts_with(tmpdir.as_str())
{
return true;
}
let tmp = std::env::temp_dir();
if std::path::Path::new(path).starts_with(&tmp) {
return true;
}
false
}
fn download_to_file_reason(command: &str) -> Option<String> {
let segments = crate::core::command_cwd::segments_with_cwd(command, None);
let known_vars = literal_assignments_before_each_segment(command, segments.len());
for (index, seg_cwd) in segments.into_iter().enumerate() {
let seg = seg_cwd.segment;
let here = seg_cwd.cwd;
let vars = &known_vars[index];
let resolve = |path: &str| -> String {
let expanded = expand_leading_variable(path, vars);
let path = expanded.as_deref().unwrap_or(path);
let p = std::path::Path::new(path);
if p.is_absolute() || path.starts_with('/') {
return path.to_string();
}
match here.as_deref() {
Some(dir) => crate::core::command_cwd::join_in(dir, path)
.to_string_lossy()
.into_owned(),
None => path.to_string(),
}
};
let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
let Some(first) = tokens.first() else {
continue;
};
let base = first.rsplit('/').next().unwrap_or(first);
match base {
"curl" => {
let tokens_slice = &tokens[1..];
for (i, tok) in tokens_slice.iter().enumerate() {
let target: Option<&str> = if tok == "--output" {
tokens_slice.get(i + 1).map(String::as_str)
} else if let Some(val) = tok.strip_prefix("--output=") {
Some(val)
} else if tok == "--output-dir" {
tokens_slice.get(i + 1).map(String::as_str)
} else if let Some(val) = tok.strip_prefix("--output-dir=") {
Some(val)
} else if tok.starts_with('-')
&& !tok.starts_with("--")
&& tok[1..].contains('o')
{
tokens_slice.get(i + 1).map(String::as_str)
} else if tok == "--remote-name"
|| tok == "--remote-name-all"
|| (tok.starts_with('-')
&& !tok.starts_with("--")
&& tok[1..].contains('O'))
{
Some(".")
} else {
None
};
if let Some(path) = target {
if is_scratch_path(&resolve(path)) {
continue;
}
return Some(format!("curl {tok}"));
}
}
}
"wget" => {
let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
tok == "--output-document=-"
|| tok == "-O-"
|| (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
|| ((tok == "-O" || tok == "--output-document")
&& tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
|| tok == "--spider"
});
if !to_stdout {
return Some(
"wget downloads to a file by default; use wget -qO- <url> for stdout"
.to_string(),
);
}
}
"dd" => {
for tok in &tokens[1..] {
if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
return Some(format!("dd {tok}"));
}
}
}
_ => {}
}
}
None
}
fn literal_assignments_before_each_segment(
command: &str,
segment_count: usize,
) -> Vec<std::collections::HashMap<String, String>> {
use crate::core::shell_allowlist::Separator;
let separated = crate::core::shell_allowlist::segments_with_separators(command);
if separated.len() != segment_count {
return vec![std::collections::HashMap::new(); segment_count];
}
let mut known = std::collections::HashMap::new();
let mut prev: Option<Separator> = None;
let mut before_each = Vec::with_capacity(segment_count);
for (segment, sep) in separated {
before_each.push(known.clone());
let tokens = crate::core::shell_allowlist::shell_tokenize(&segment);
let words: &[String] = match tokens.first().map(String::as_str) {
Some("export") => &tokens[1..],
_ => &tokens,
};
let assignments: Option<Vec<(&str, &str)>> = words
.iter()
.map(|word| {
let (name, value) = word.split_once('=')?;
let valid_name = name
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
valid_name.then_some((name, value))
})
.collect();
match assignments {
Some(pairs) if !pairs.is_empty() => {
let in_current_shell = matches!(prev, None | Some(Separator::Sequence))
&& matches!(sep, None | Some(Separator::Sequence | Separator::And));
for (name, value) in pairs {
let literal = !value.contains(['$', '`']) && !value.starts_with('~');
if in_current_shell && literal {
known.insert(name.to_string(), value.to_string());
} else {
known.remove(name);
}
}
}
_ => {
let rebinds = matches!(
tokens.first().map(String::as_str),
Some(
"read"
| "for"
| "select"
| "eval"
| "source"
| "."
| "unset"
| "declare"
| "typeset"
| "local"
| "readonly"
| "export"
| "mapfile"
| "readarray"
| "getopts"
| "printf"
)
);
if rebinds {
known.clear();
}
}
}
prev = sep;
}
before_each
}
fn expand_leading_variable(
path: &str,
known: &std::collections::HashMap<String, String>,
) -> Option<String> {
let rest = path.strip_prefix('$')?;
let (name, tail) = if let Some(braced) = rest.strip_prefix('{') {
let (name, tail) = braced.split_once('}')?;
(name, tail)
} else {
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
rest.split_at(end)
};
if name.is_empty() || !(tail.is_empty() || tail.starts_with('/')) {
return None;
}
let value = match known.get(name) {
Some(value) => value.clone(),
None if name == "TMPDIR" => std::env::var("TMPDIR").ok().filter(|v| !v.is_empty())?,
None => return None,
};
Some(format!("{value}{tail}"))
}
fn is_heredoc_file_write(
command: &str,
segments: &[(String, Option<String>)],
write_allow_paths: &[String],
project_root: Option<&str>,
) -> bool {
let has_heredoc = command.contains("<<");
if !has_heredoc {
return false;
}
let cmd_lower = command.to_lowercase();
let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
if !has_known_heredoc {
return false;
}
segments.iter().any(|(segment, here)| {
disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
.is_some()
})
}
pub fn is_temp_redirect_target(target: &str) -> bool {
let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
}
fn is_write_allowed_redirect_target(
target: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
cwd: Option<&str>,
) -> bool {
let t = target.trim_start_matches(['>', '&', '|']);
let t = t.trim_matches(['"', '\'']);
if t.starts_with('$') || t.starts_with("${") {
return true;
}
if is_unix_scratch_prefix(t) {
return true;
}
let path = std::path::Path::new(t);
let resolved_input;
let path = if path.is_absolute() {
path
} else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
resolved_input = std::path::Path::new(base).join(path);
resolved_input.as_path()
} else {
return false;
};
let resolved = resolve_path_for_comparison(path);
if project_root.is_some_and(|root| {
resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
}) {
return false;
}
write_allow_paths.iter().any(|allowed| {
resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
})
}
fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
use std::path::{Component, PathBuf};
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
normalized.pop();
}
other => normalized.push(other.as_os_str()),
}
}
let mut unresolved = Vec::new();
let mut existing = normalized.clone();
while !existing.exists() {
let Some(name) = existing.file_name() else {
break;
};
unresolved.push(name.to_os_string());
if !existing.pop() {
break;
}
}
let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
for component in unresolved.iter().rev() {
resolved.push(component);
}
resolved
}
fn tee_targets(command: &str) -> Vec<String> {
crate::core::shell_allowlist::extract_all_commands_pub(command)
.into_iter()
.filter_map(|segment| {
let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
let first = tokens.first()?;
if first.rsplit('/').next().unwrap_or(first) != "tee" {
return None;
}
let mut after_separator = false;
Some(
tokens
.iter()
.skip(1)
.find(|token| {
if *token == "--" {
after_separator = true;
return false;
}
after_separator || !token.starts_with('-')
})
.cloned()
.unwrap_or_default(),
)
})
.collect()
}
fn disallowed_tee_target(
command: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
cwd: Option<&str>,
) -> Option<String> {
tee_targets(command).into_iter().find(|target| {
!target.is_empty()
&& !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
})
}
#[cfg(test)]
fn has_file_write_redirect(
command: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
) -> bool {
disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
}
fn disallowed_write_redirect_target(
command: &str,
write_allow_paths: &[String],
project_root: Option<&str>,
cwd: Option<&str>,
) -> Option<String> {
let bytes = command.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut in_single_quote = false;
let mut in_double_quote = false;
while i < len {
let c = bytes[i];
if c == b'\\' && !in_single_quote {
i += 2;
continue;
}
if c == b'\'' && !in_double_quote {
in_single_quote = !in_single_quote;
} else if c == b'"' && !in_single_quote {
in_double_quote = !in_double_quote;
} else if c == b'>' && !in_single_quote && !in_double_quote {
if i > 0 && bytes[i - 1] == b'2' {
i += 1;
continue;
}
let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
i + 2
} else {
i + 1
};
let rest = command[target_start..].trim_start();
let (rest, fd_dup) = match rest.strip_prefix('|') {
Some(r) => (r, false),
None => match rest.strip_prefix('&') {
Some(r) => (r, true),
None => (rest, false),
},
};
let word: String = rest
.chars()
.take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
.collect();
let target = if fd_dup { format!("&{word}") } else { word };
if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
i += 1;
continue;
}
if let Some(fd) = target.strip_prefix('&')
&& !fd.is_empty()
&& (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
{
i += 1;
continue;
}
if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
i += 1;
continue;
}
if !target.is_empty() {
return Some(target);
}
}
i += 1;
}
None
}
pub fn normalize_command_for_shell(command: &str) -> String {
if !cfg!(windows) {
return command.to_string();
}
let (_, flag) = crate::shell::shell_and_flag();
if flag != "/C" {
return command.to_string();
}
let bytes = command.as_bytes();
let mut result = Vec::with_capacity(bytes.len() + 16);
let mut in_single = false;
let mut in_double = false;
for (i, &b) in bytes.iter().enumerate() {
if b == b'\'' && !in_double {
in_single = !in_single;
} else if b == b'"' && !in_single {
in_double = !in_double;
} else if b == b';' && !in_single && !in_double {
result.extend_from_slice(b" && ");
continue;
}
result.push(b);
let _ = i;
}
String::from_utf8(result).unwrap_or_else(|_| command.to_string())
}
pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
}
pub fn handle_with_context(
command: &str,
output: &str,
exit_code: i32,
crp_mode: CrpMode,
project_root: Option<&str>,
) -> String {
let mut result = handle(command, output, exit_code, crp_mode);
{
if let Some(root) = project_root {
let estimated_tokens = result.len() / 4;
if estimated_tokens > 500 {
let kernel_budget = 100;
if let Some(enrichment) =
crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
&& !enrichment.blocks.is_empty()
{
result.push_str("\n--- kernel context ---\n");
result.push_str(&enrichment.blocks);
}
}
}
}
result
}
#[cfg(test)]
mod kernel_tests {
use super::handle_with_context;
use crate::tools::CrpMode;
#[test]
fn handle_with_context_does_not_panic_on_short_output() {
let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
assert!(!result.is_empty());
}
}
#[cfg(test)]
fn is_search_command(command: &str) -> bool {
let cmd = command.trim_start();
cmd.starts_with("grep ")
|| cmd.starts_with("rg ")
|| cmd.starts_with("find ")
|| cmd.starts_with("fd ")
|| cmd.starts_with("ag ")
|| cmd.starts_with("ack ")
}
#[cfg(test)]
fn generic_compress(output: &str) -> String {
let output = crate::core::compressor::strip_ansi(output);
let lines: Vec<&str> = output
.lines()
.filter(|l| {
let t = l.trim();
!t.is_empty()
})
.collect();
if lines.len() <= 20 {
return lines.join("\n");
}
let show_count = (lines.len() / 3).min(30);
let half = show_count / 2;
let first = &lines[..half];
let last = &lines[lines.len() - half..];
let omitted = lines.len() - (half * 2);
format!(
"{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
first.join("\n"),
half * 2,
lines.len(),
omitted,
last.join("\n")
)
}
pub fn contains_auth_flow(output: &str) -> bool {
let lower = output.to_lowercase();
const STRONG_SIGNALS: &[&str] = &[
"devicelogin",
"deviceauth",
"device_code",
"device code",
"device-code",
"verification_uri",
"user_code",
"one-time code",
];
if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
return true;
}
const WEAK_SIGNALS: &[&str] = &[
"enter the code",
"enter this code",
"enter code:",
"use the code",
"use a web browser to open",
"open the page",
"authenticate by visiting",
"sign in with the code",
"sign in using a code",
"verification code",
"authorize this device",
"waiting for authentication",
"waiting for login",
"waiting for you to authenticate",
"open your browser",
"open in your browser",
];
let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
if !has_weak_signal {
return false;
}
lower.contains("http://") || lower.contains("https://")
}
#[cfg(test)]
mod tests;