use crate::tools::command_args::{
command_words_after_environment_prefix, has_unsafe_readonly_options, shell_command_text_with_args,
};
use crate::tools::output_spooler::SpooledOutputReference;
use serde_json::Value;
use std::path::Path;
const READONLY_UNIFIED_EXEC_COMMANDS: &[&str] = &[
"rg", "ls", "cat", "diff", "find", "wc", "grep", "egrep", "fgrep", "head", "tail", "sort", "uniq", "bat", "sed",
"awk", "cut", "tr", "echo", "pwd", "printf", "true", "false", "test", "cd", "fd", "tree", "which", "stat", "file",
"du", "df", "realpath", "basename", "dirname", "nl", "column", "jq", "date", "whoami", "uname",
];
pub fn is_readonly_base_command(command: &str) -> bool {
READONLY_UNIFIED_EXEC_COMMANDS.contains(&command)
}
fn is_readonly_subcommand(first: &str, second: Option<&str>, third: Option<&str>) -> bool {
match first {
"git" => matches!(
second,
Some(
"status"
| "log"
| "diff"
| "show"
| "blame"
| "ls-files"
| "rev-parse"
| "describe"
| "shortlog"
| "grep"
| "rev-list"
| "ls-tree"
| "cat-file"
| "diff-tree"
| "merge-base"
| "range-diff"
| "whatchanged"
| "count-objects"
| "var"
| "version"
| "help"
)
),
"cargo" => match second {
Some("check" | "test" | "metadata" | "tree" | "clippy") => true,
Some("nextest") => matches!(third, Some("run" | "list")),
_ => false,
},
"npm" | "pnpm" | "yarn" => match second {
Some("test") => true,
Some("run") => matches!(third, Some("test")),
_ => false,
},
_ => false,
}
}
fn is_readonly_flag_shaped_git_subcommand(
subcommand: Option<&str>,
operand: Option<&str>,
command_words: &[String],
sub_index: usize,
) -> bool {
if subcommand == Some("branch") {
let mutates = command_words.iter().skip(sub_index + 1).any(|word| {
matches!(word.as_str(), "--set-upstream" | "--unset-upstream" | "--edit-description")
|| word.starts_with("--set-upstream-to")
|| word.starts_with("-u")
|| word.starts_with("-m")
|| word.starts_with("-M")
|| word.starts_with("-c")
|| word.starts_with("-C")
});
if mutates {
return false;
}
}
matches!(
(subcommand, operand),
(Some("tag") | Some("branch"), None)
| (Some("reflog"), None | Some("show"))
| (Some("remote"), None | Some("show") | Some("get-url"))
| (Some("stash"), Some("list") | Some("show"))
| (Some("worktree"), Some("list"))
)
}
fn is_version_or_help_probe(command_words: &[String]) -> bool {
fn is_probe_flag(word: &str) -> bool {
matches!(word, "-h" | "--help" | "-V" | "--version")
}
let mut flags = command_words.iter().skip(1);
flags.next().is_some_and(|word| is_probe_flag(word)) && flags.all(|word| is_probe_flag(word))
}
pub(crate) fn static_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
let sanitized = sanitize_static_shell_command(command)?;
parse_shell_command_words(&sanitized)
}
pub(crate) fn static_shell_command_words_with_output_plumbing(command: &str) -> Option<Vec<Vec<String>>> {
if !crate::command_safety::shell_parser::has_only_output_redirections(command) {
return None;
}
parse_shell_command_words(command)
}
pub(super) fn parse_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
let commands = crate::command_safety::shell_parser::parse_shell_commands_tree_sitter(command).ok()?;
if commands.is_empty() {
return None;
}
commands
.into_iter()
.map(|command| {
let mut words = Vec::new();
for word in command {
let tokens = shell_words::split(&word).ok()?;
words.extend(tokens);
}
(!words.is_empty()).then_some(words)
})
.collect()
}
fn readonly_command_head(words: &[String]) -> Option<(&[String], String)> {
let command_words = command_words_after_environment_prefix(words);
let first = command_words
.first()
.and_then(|word| Path::new(word).file_name())
.and_then(|name| name.to_str())
.map(str::to_ascii_lowercase)?;
if has_unsafe_readonly_options(words) {
return None;
}
Some((command_words, first))
}
pub(crate) fn command_words_are_readonly(words: &[String]) -> bool {
let Some((command_words, first)) = readonly_command_head(words) else {
return false;
};
if first == "command" {
return matches!(command_words.get(1).map(String::as_str), Some("-v" | "-V"))
&& command_words.len() > 2
&& command_words
.iter()
.skip(2)
.all(|word| !word.starts_with('-') && !word.is_empty());
}
if is_readonly_base_command(&first)
|| is_version_or_help_probe(command_words)
|| is_known_readonly_dry_run(command_words, &first)
{
return true;
}
let lowered = command_words
.iter()
.filter(|word| !word.starts_with('-') && !word.contains('='))
.take(3)
.map(|word| word.to_ascii_lowercase())
.collect::<Vec<_>>();
if first != "git" {
let (second, third) = (lowered.get(1).map(String::as_str), lowered.get(2).map(String::as_str));
return is_readonly_subcommand(&first, second, third);
}
let Some((sub_index, operand)) = git_subcommand_and_operand(command_words) else {
return false;
};
let subcommand = command_words.get(sub_index).map(String::as_str);
is_readonly_subcommand("git", subcommand, None)
|| is_readonly_flag_shaped_git_subcommand(subcommand, operand, command_words, sub_index)
}
fn git_subcommand_and_operand(command_words: &[String]) -> Option<(usize, Option<&str>)> {
const GLOBAL_OPTIONS_WITH_VALUE: &[&str] = &[
"-C",
"-c",
"--git-dir",
"--work-tree",
"--namespace",
"--super-prefix",
"--exec-path",
"--config-env",
"--shallow-file",
"--attr-source",
];
const GLOBAL_OPTIONS_FLAG_ONLY: &[&str] = &[
"-p",
"--paginate",
"--no-pager",
"--bare",
"--literal-pathspecs",
"--no-replace-objects",
"--no-optional-locks",
"--end-of-options",
"--version",
"--help",
"--html-path",
];
let mut index = 1;
while let Some(word) = command_words.get(index) {
if !word.starts_with('-') {
let operand = command_words
.iter()
.skip(index + 1)
.find(|candidate| !candidate.starts_with('-'))
.map(String::as_str);
return Some((index, operand));
}
if GLOBAL_OPTIONS_WITH_VALUE.contains(&word.as_str()) {
index += 2; continue;
}
if GLOBAL_OPTIONS_FLAG_ONLY.contains(&word.as_str()) {
index += 1;
continue;
}
return None;
}
None
}
fn command_words_are_parallel_safe(words: &[String]) -> bool {
let Some((command_words, first)) = readonly_command_head(words) else {
return false;
};
if is_readonly_base_command(&first) {
return true;
}
if is_version_or_help_probe(command_words) {
return true;
}
if first != "git" {
return false;
}
let subcommand = command_words
.iter()
.skip(1)
.find(|word| !word.starts_with('-') && !word.contains('='))
.map(|word| word.to_ascii_lowercase());
is_readonly_subcommand("git", subcommand.as_deref(), None)
}
fn is_known_readonly_dry_run(words: &[String], program: &str) -> bool {
if !matches!(program, "npm" | "pnpm" | "yarn") {
return false;
}
let Some(subcommand) = words.iter().skip(1).find(|word| !word.starts_with('-') && !word.contains('=')) else {
return false;
};
subcommand == "install" && words.iter().any(|word| word == "--dry-run")
}
fn matches_at(chars: &[char], index: usize, pattern: &[char]) -> bool {
chars
.get(index..index.saturating_add(pattern.len()))
.is_some_and(|candidate| candidate == pattern)
}
fn sanitize_static_shell_command(command: &str) -> Option<String> {
if crate::command_safety::shell_parser::contains_dynamic_shell_syntax(command) {
return None;
}
let chars = command.chars().collect::<Vec<_>>();
let mut sanitized = String::with_capacity(command.len());
let mut index = 0;
let mut in_single_quote = false;
let mut in_double_quote = false;
while index < chars.len() {
let character = chars[index];
if character == '\'' && !in_double_quote {
in_single_quote.toggle();
sanitized.push(character);
index += 1;
continue;
}
if character == '"' && !in_single_quote {
in_double_quote.toggle();
sanitized.push(character);
index += 1;
continue;
}
if in_single_quote || in_double_quote {
sanitized.push(character);
index += 1;
continue;
}
let preceded_by_boundary = index == 0
|| chars
.get(index.saturating_sub(1))
.is_some_and(|previous| previous.is_whitespace() || matches!(previous, '|' | '&' | ';'));
if preceded_by_boundary && matches_at(&chars, index, &['2', '>', '&', '1']) {
index += 4;
continue;
}
if cfg!(unix)
&& preceded_by_boundary
&& matches_at(&chars, index, &['2', '>', '/', 'd', 'e', 'v', '/', 'n', 'u', 'l', 'l'])
{
index += 11;
continue;
}
match character {
'<' | '>' => return None,
'&' if matches_at(&chars, index, &['&', '&']) => {
sanitized.push('&');
sanitized.push('&');
index += 2;
}
'&' => return None,
_ => {
sanitized.push(character);
index += 1;
}
}
}
(!sanitized.trim().is_empty()).then_some(sanitized)
}
fn parsed_session_commands(args: &Value) -> Option<Vec<Vec<String>>> {
let raw = shell_command_text_with_args(args)?;
static_shell_command_words(&raw)
}
fn all_commands_readonly(commands: &[Vec<String>]) -> bool {
commands.iter().all(|words| command_words_are_readonly(words))
}
pub fn is_readonly_command_session_command(args: &Value) -> bool {
let Some(commands) = parsed_session_commands(args) else {
return false;
};
all_commands_readonly(&commands)
}
pub(crate) fn is_parallel_safe_command_session_command(args: &Value) -> bool {
if args.get("session_id").is_some()
|| args.get("chars").is_some()
|| args.get("input").is_some()
|| args.get("tty").and_then(Value::as_bool) == Some(true)
|| args
.get("sandbox_permissions")
.and_then(Value::as_str)
.is_some_and(|value| value != "use_default")
{
return false;
}
let Some(commands) = parsed_session_commands(args) else {
return false;
};
commands.len() == 1 && command_words_are_parallel_safe(&commands[0])
}
pub fn is_spool_file_read_command(tool_name: &str, args: &Value) -> bool {
if super::classify::canonical_command_session_tool_name(tool_name).is_none() {
return false;
}
let Some(commands) = parsed_session_commands(args) else {
return false;
};
if !all_commands_readonly(&commands) {
return false;
}
commands
.iter()
.flatten()
.any(|word| SpooledOutputReference::recognizes_path(Path::new(word)))
}
#[cfg(test)]
mod tests;