vtcode_core/tools/tool_intent/readonly/
mod.rs1use crate::tools::command_args::{
2 command_words_after_environment_prefix, has_unsafe_readonly_options, shell_command_text_with_args,
3};
4use crate::tools::output_spooler::SpooledOutputReference;
5use serde_json::Value;
6use std::path::Path;
7
8const READONLY_UNIFIED_EXEC_COMMANDS: &[&str] = &[
26 "rg", "ls", "cat", "diff", "find", "wc", "grep", "egrep", "fgrep", "head", "tail", "sort", "uniq", "bat", "sed",
27 "awk", "cut", "tr", "echo", "pwd", "printf", "true", "false", "test", "cd", "fd", "tree", "which", "stat", "file",
28 "du", "df", "realpath", "basename", "dirname", "nl", "column", "jq", "date", "whoami", "uname",
29];
30
31pub fn is_readonly_base_command(command: &str) -> bool {
32 READONLY_UNIFIED_EXEC_COMMANDS.contains(&command)
33}
34
35fn is_readonly_subcommand(first: &str, second: Option<&str>, third: Option<&str>) -> bool {
45 match first {
46 "git" => matches!(
47 second,
48 Some(
49 "status"
50 | "log"
51 | "diff"
52 | "show"
53 | "blame"
54 | "ls-files"
55 | "rev-parse"
56 | "describe"
57 | "shortlog"
58 | "grep"
59 | "rev-list"
60 | "ls-tree"
61 | "cat-file"
62 | "diff-tree"
63 | "merge-base"
64 | "range-diff"
65 | "whatchanged"
66 | "count-objects"
67 | "var"
68 | "version"
69 | "help"
70 )
71 ),
72 "cargo" => match second {
73 Some("check" | "test" | "metadata" | "tree" | "clippy") => true,
74 Some("nextest") => matches!(third, Some("run" | "list")),
75 _ => false,
76 },
77 "npm" | "pnpm" | "yarn" => match second {
78 Some("test") => true,
79 Some("run") => matches!(third, Some("test")),
80 _ => false,
81 },
82 _ => false,
83 }
84}
85
86fn is_readonly_flag_shaped_git_subcommand(
104 subcommand: Option<&str>,
105 operand: Option<&str>,
106 command_words: &[String],
107 sub_index: usize,
108) -> bool {
109 if subcommand == Some("branch") {
110 let mutates = command_words.iter().skip(sub_index + 1).any(|word| {
111 matches!(word.as_str(), "--set-upstream" | "--unset-upstream" | "--edit-description")
112 || word.starts_with("--set-upstream-to")
113 || word.starts_with("-u")
114 || word.starts_with("-m")
115 || word.starts_with("-M")
116 || word.starts_with("-c")
117 || word.starts_with("-C")
118 });
119 if mutates {
120 return false;
121 }
122 }
123
124 matches!(
125 (subcommand, operand),
126 (Some("tag") | Some("branch"), None)
127 | (Some("reflog"), None | Some("show"))
128 | (Some("remote"), None | Some("show") | Some("get-url"))
129 | (Some("stash"), Some("list") | Some("show"))
130 | (Some("worktree"), Some("list"))
131 )
132}
133
134fn is_version_or_help_probe(command_words: &[String]) -> bool {
144 fn is_probe_flag(word: &str) -> bool {
145 matches!(word, "-h" | "--help" | "-V" | "--version")
146 }
147
148 let mut flags = command_words.iter().skip(1);
149 flags.next().is_some_and(|word| is_probe_flag(word)) && flags.all(|word| is_probe_flag(word))
150}
151
152pub(crate) fn static_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
160 let sanitized = sanitize_static_shell_command(command)?;
161 parse_shell_command_words(&sanitized)
162}
163
164pub(crate) fn static_shell_command_words_with_output_plumbing(command: &str) -> Option<Vec<Vec<String>>> {
170 if !crate::command_safety::shell_parser::has_only_output_redirections(command) {
171 return None;
172 }
173 parse_shell_command_words(command)
174}
175
176pub(super) fn parse_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
180 let commands = crate::command_safety::shell_parser::parse_shell_commands_tree_sitter(command).ok()?;
181 if commands.is_empty() {
182 return None;
183 }
184
185 commands
186 .into_iter()
187 .map(|command| {
188 let mut words = Vec::new();
189 for word in command {
190 let tokens = shell_words::split(&word).ok()?;
191 words.extend(tokens);
192 }
193 (!words.is_empty()).then_some(words)
194 })
195 .collect()
196}
197
198fn readonly_command_head(words: &[String]) -> Option<(&[String], String)> {
208 let command_words = command_words_after_environment_prefix(words);
209 let first = command_words
210 .first()
211 .and_then(|word| Path::new(word).file_name())
212 .and_then(|name| name.to_str())
213 .map(str::to_ascii_lowercase)?;
214 if has_unsafe_readonly_options(words) {
215 return None;
216 }
217 Some((command_words, first))
218}
219
220pub(crate) fn command_words_are_readonly(words: &[String]) -> bool {
224 let Some((command_words, first)) = readonly_command_head(words) else {
225 return false;
226 };
227 if first == "command" {
228 return matches!(command_words.get(1).map(String::as_str), Some("-v" | "-V"))
229 && command_words.len() > 2
230 && command_words
231 .iter()
232 .skip(2)
233 .all(|word| !word.starts_with('-') && !word.is_empty());
234 }
235
236 if is_readonly_base_command(&first)
237 || is_version_or_help_probe(command_words)
238 || is_known_readonly_dry_run(command_words, &first)
239 {
240 return true;
241 }
242
243 let lowered = command_words
244 .iter()
245 .filter(|word| !word.starts_with('-') && !word.contains('='))
246 .take(3)
247 .map(|word| word.to_ascii_lowercase())
248 .collect::<Vec<_>>();
249 if first != "git" {
250 let (second, third) = (lowered.get(1).map(String::as_str), lowered.get(2).map(String::as_str));
251 return is_readonly_subcommand(&first, second, third);
252 }
253
254 let Some((sub_index, operand)) = git_subcommand_and_operand(command_words) else {
255 return false;
256 };
257 let subcommand = command_words.get(sub_index).map(String::as_str);
258 is_readonly_subcommand("git", subcommand, None)
259 || is_readonly_flag_shaped_git_subcommand(subcommand, operand, command_words, sub_index)
260}
261
262fn git_subcommand_and_operand(command_words: &[String]) -> Option<(usize, Option<&str>)> {
281 const GLOBAL_OPTIONS_WITH_VALUE: &[&str] = &[
282 "-C",
283 "-c",
284 "--git-dir",
285 "--work-tree",
286 "--namespace",
287 "--super-prefix",
288 "--exec-path",
289 "--config-env",
290 "--shallow-file",
291 "--attr-source",
292 ];
293 const GLOBAL_OPTIONS_FLAG_ONLY: &[&str] = &[
294 "-p",
295 "--paginate",
296 "--no-pager",
297 "--bare",
298 "--literal-pathspecs",
299 "--no-replace-objects",
300 "--no-optional-locks",
301 "--end-of-options",
302 "--version",
303 "--help",
304 "--html-path",
305 ];
306
307 let mut index = 1;
308 while let Some(word) = command_words.get(index) {
309 if !word.starts_with('-') {
310 let operand = command_words
311 .iter()
312 .skip(index + 1)
313 .find(|candidate| !candidate.starts_with('-'))
314 .map(String::as_str);
315 return Some((index, operand));
316 }
317 if GLOBAL_OPTIONS_WITH_VALUE.contains(&word.as_str()) {
318 index += 2; continue;
320 }
321 if GLOBAL_OPTIONS_FLAG_ONLY.contains(&word.as_str()) {
322 index += 1;
323 continue;
324 }
325 return None;
329 }
330 None
331}
332
333fn command_words_are_parallel_safe(words: &[String]) -> bool {
338 let Some((command_words, first)) = readonly_command_head(words) else {
339 return false;
340 };
341
342 if is_readonly_base_command(&first) {
343 return true;
344 }
345 if is_version_or_help_probe(command_words) {
347 return true;
348 }
349 if first != "git" {
350 return false;
351 }
352
353 let subcommand = command_words
354 .iter()
355 .skip(1)
356 .find(|word| !word.starts_with('-') && !word.contains('='))
357 .map(|word| word.to_ascii_lowercase());
358 is_readonly_subcommand("git", subcommand.as_deref(), None)
359}
360
361fn is_known_readonly_dry_run(words: &[String], program: &str) -> bool {
362 if !matches!(program, "npm" | "pnpm" | "yarn") {
363 return false;
364 }
365
366 let Some(subcommand) = words.iter().skip(1).find(|word| !word.starts_with('-') && !word.contains('=')) else {
367 return false;
368 };
369
370 subcommand == "install" && words.iter().any(|word| word == "--dry-run")
371}
372
373fn matches_at(chars: &[char], index: usize, pattern: &[char]) -> bool {
374 chars
375 .get(index..index.saturating_add(pattern.len()))
376 .is_some_and(|candidate| candidate == pattern)
377}
378
379fn sanitize_static_shell_command(command: &str) -> Option<String> {
383 if crate::command_safety::shell_parser::contains_dynamic_shell_syntax(command) {
384 return None;
385 }
386
387 let chars = command.chars().collect::<Vec<_>>();
388 let mut sanitized = String::with_capacity(command.len());
389 let mut index = 0;
390 let mut in_single_quote = false;
391 let mut in_double_quote = false;
392
393 while index < chars.len() {
394 let character = chars[index];
395 if character == '\'' && !in_double_quote {
396 in_single_quote.toggle();
397 sanitized.push(character);
398 index += 1;
399 continue;
400 }
401 if character == '"' && !in_single_quote {
402 in_double_quote.toggle();
403 sanitized.push(character);
404 index += 1;
405 continue;
406 }
407 if in_single_quote || in_double_quote {
408 sanitized.push(character);
409 index += 1;
410 continue;
411 }
412
413 let preceded_by_boundary = index == 0
414 || chars
415 .get(index.saturating_sub(1))
416 .is_some_and(|previous| previous.is_whitespace() || matches!(previous, '|' | '&' | ';'));
417 if preceded_by_boundary && matches_at(&chars, index, &['2', '>', '&', '1']) {
418 index += 4;
419 continue;
420 }
421 if cfg!(unix)
422 && preceded_by_boundary
423 && matches_at(&chars, index, &['2', '>', '/', 'd', 'e', 'v', '/', 'n', 'u', 'l', 'l'])
424 {
425 index += 11;
426 continue;
427 }
428
429 match character {
430 '<' | '>' => return None,
431 '&' if matches_at(&chars, index, &['&', '&']) => {
432 sanitized.push('&');
433 sanitized.push('&');
434 index += 2;
435 }
436 '&' => return None,
437 _ => {
438 sanitized.push(character);
439 index += 1;
440 }
441 }
442 }
443
444 (!sanitized.trim().is_empty()).then_some(sanitized)
445}
446
447fn parsed_session_commands(args: &Value) -> Option<Vec<Vec<String>>> {
455 let raw = shell_command_text_with_args(args)?;
456 static_shell_command_words(&raw)
457}
458
459fn all_commands_readonly(commands: &[Vec<String>]) -> bool {
464 commands.iter().all(|words| command_words_are_readonly(words))
465}
466
467pub fn is_readonly_command_session_command(args: &Value) -> bool {
468 let Some(commands) = parsed_session_commands(args) else {
469 return false;
470 };
471
472 all_commands_readonly(&commands)
473}
474
475pub(crate) fn is_parallel_safe_command_session_command(args: &Value) -> bool {
478 if args.get("session_id").is_some()
479 || args.get("chars").is_some()
480 || args.get("input").is_some()
481 || args.get("tty").and_then(Value::as_bool) == Some(true)
482 || args
483 .get("sandbox_permissions")
484 .and_then(Value::as_str)
485 .is_some_and(|value| value != "use_default")
486 {
487 return false;
488 }
489 let Some(commands) = parsed_session_commands(args) else {
490 return false;
491 };
492 commands.len() == 1 && command_words_are_parallel_safe(&commands[0])
493}
494
495pub fn is_spool_file_read_command(tool_name: &str, args: &Value) -> bool {
499 if super::classify::canonical_command_session_tool_name(tool_name).is_none() {
500 return false;
501 }
502
503 let Some(commands) = parsed_session_commands(args) else {
508 return false;
509 };
510 if !all_commands_readonly(&commands) {
511 return false;
512 }
513 commands
514 .iter()
515 .flatten()
516 .any(|word| SpooledOutputReference::recognizes_path(Path::new(word)))
517}
518
519#[cfg(test)]
520mod tests;