Skip to main content

vtcode_core/tools/command_args/
mod.rs

1//! Shared helpers for command-style tool arguments.
2
3use std::path::Path;
4
5use serde_json::Value;
6
7use crate::tools::tool_intent::{command_session_action, command_session_action_in, command_session_action_is};
8
9const INDEXED_COMMAND_TYPE_ERROR: &str = "command array must contain only strings";
10const COMMAND_VALUE_TYPE_ERROR: &str = "command must be a string or array of strings";
11
12mod text_tools;
13use text_tools::{has_unsafe_awk_options, has_unsafe_sed_options};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub(crate) enum WriteStdinDispatch {
17    Write,
18    Poll,
19    Wait,
20    Inspect,
21    Terminate,
22    Close,
23}
24
25impl WriteStdinDispatch {
26    #[must_use]
27    pub(crate) const fn command_session_action(self) -> &'static str {
28        match self {
29            Self::Write => "write",
30            Self::Poll => "poll",
31            Self::Wait => "wait",
32            Self::Inspect => "inspect",
33            Self::Terminate => "terminate",
34            Self::Close => "close",
35        }
36    }
37}
38
39pub(crate) fn write_stdin_dispatch(args: &Value) -> Result<WriteStdinDispatch, &'static str> {
40    let payload = args.as_object().ok_or("write_stdin requires a JSON object")?;
41    if let Some(action) = payload.get("action") {
42        let action = action.as_str().ok_or("write_stdin action must be a string")?;
43        // Zero-alloc ASCII case-insensitive match: identical verdicts to the
44        // old `to_ascii_lowercase()` + `match` (both fold ASCII only), but
45        // without heap-allocating the lowered action on this hot path.
46        if action.eq_ignore_ascii_case("wait") {
47            return Ok(WriteStdinDispatch::Wait);
48        }
49        if action.eq_ignore_ascii_case("inspect") {
50            return Ok(WriteStdinDispatch::Inspect);
51        }
52        if action.eq_ignore_ascii_case("terminate") {
53            return Ok(WriteStdinDispatch::Terminate);
54        }
55        if action.eq_ignore_ascii_case("close") {
56            return Ok(WriteStdinDispatch::Close);
57        }
58        if action.eq_ignore_ascii_case("poll") {
59            if payload.get("chars").is_some_and(|chars| chars.as_str() != Some("")) {
60                return Err("write_stdin poll cannot send chars");
61            }
62            return Ok(WriteStdinDispatch::Poll);
63        }
64        if !action.eq_ignore_ascii_case("write") {
65            return Err("write_stdin action must be write, poll, wait, inspect, terminate, or close");
66        }
67    }
68    let chars = payload
69        .get("chars")
70        .and_then(Value::as_str)
71        .ok_or("write_stdin requires string chars")?;
72
73    if chars.is_empty() {
74        Ok(WriteStdinDispatch::Poll)
75    } else {
76        Ok(WriteStdinDispatch::Write)
77    }
78}
79
80fn collect_indexed_command_parts(
81    payload: &serde_json::Map<String, Value>,
82    start_index: usize,
83) -> Result<Vec<String>, &'static str> {
84    let mut parts = Vec::new();
85    let mut index = start_index;
86    while let Some(value) = payload.get(&format!("command.{index}")) {
87        let Some(part) = value.as_str() else {
88            return Err(INDEXED_COMMAND_TYPE_ERROR);
89        };
90        parts.push(part.to_string());
91        index += 1;
92    }
93    Ok(parts)
94}
95
96// Canonical probe lives in `vtcode-commons::tool_intent` so transcript
97// surfaces share it; re-exported here so existing import paths keep working.
98pub use vtcode_commons::tool_intent::has_indexed_command_parts;
99
100pub fn parse_indexed_command_parts(
101    payload: &serde_json::Map<String, Value>,
102) -> Result<Option<Vec<String>>, &'static str> {
103    let zero_based = collect_indexed_command_parts(payload, 0)?;
104    if !zero_based.is_empty() {
105        return Ok(Some(zero_based));
106    }
107
108    let one_based = collect_indexed_command_parts(payload, 1)?;
109    if one_based.is_empty() {
110        Ok(None)
111    } else {
112        Ok(Some(one_based))
113    }
114}
115
116pub fn normalize_indexed_command_args(args: &Value) -> Result<Option<Value>, &'static str> {
117    let Some(payload) = args.as_object() else {
118        return Ok(None);
119    };
120    if payload.get("command").is_some() {
121        return Ok(None);
122    }
123
124    let Some(parts) = parse_indexed_command_parts(payload)? else {
125        return Ok(None);
126    };
127
128    let mut normalized = payload.clone();
129    normalized.insert("command".to_string(), Value::String(shell_words::join(parts.iter().map(String::as_str))));
130    Ok(Some(Value::Object(normalized)))
131}
132
133pub fn normalized_command_value(args: &Value) -> Result<Option<Value>, &'static str> {
134    if let Some(command) = args
135        .get("command")
136        .or_else(|| args.get("cmd"))
137        .or_else(|| args.get("raw_command"))
138    {
139        return Ok(Some(command.clone()));
140    }
141
142    Ok(normalize_indexed_command_args(args)?.and_then(|normalized| normalized.get("command").cloned()))
143}
144
145pub fn command_words(args: &Value) -> Result<Option<Vec<String>>, &'static str> {
146    let Some(command) = normalized_command_value(args)? else {
147        return Ok(None);
148    };
149
150    let mut parts = match command {
151        Value::String(command) => shell_words::split(&command).map_err(|_e| COMMAND_VALUE_TYPE_ERROR)?,
152        Value::Array(values) => values
153            .iter()
154            .map(|value| value.as_str().map(ToOwned::to_owned).ok_or(COMMAND_VALUE_TYPE_ERROR))
155            .collect::<Result<Vec<_>, _>>()?,
156        _ => return Err(COMMAND_VALUE_TYPE_ERROR),
157    };
158
159    if let Some(extra_args) = args.get("args").and_then(Value::as_array) {
160        for value in extra_args {
161            let Some(part) = value.as_str() else {
162                return Err(COMMAND_VALUE_TYPE_ERROR);
163            };
164            parts.push(part.to_string());
165        }
166    }
167
168    if parts.is_empty() { Ok(None) } else { Ok(Some(parts)) }
169}
170
171pub fn command_text(args: &Value) -> Result<Option<String>, &'static str> {
172    let Some(parts) = command_words(args)? else {
173        return Ok(None);
174    };
175    Ok(Some(shell_words::join(parts.iter().map(String::as_str))))
176}
177
178/// Ordered argument keys that may carry a shell command string for display.
179///
180/// Canonical display precedence shared by the binary's tool summaries so
181/// headline and detail extraction can never drift. Safety classification must
182/// keep using [`raw_command_text`]/[`command_words`], which re-parse via
183/// `shell_words` and intentionally exclude the legacy display-only
184/// `bash_command` key that core handlers never execute.
185pub const DISPLAY_COMMAND_KEYS: &[&str] = &["command", "raw_command", "bash_command", "cmd"];
186
187/// Display-only extraction of a shell command string plus the key it came from.
188///
189/// Unlike [`raw_command_text`], array commands are joined with plain spaces
190/// (no quoting) because the result is rendered, never executed or re-parsed:
191/// `["bash", "-lc", "ls -R"]` displays as `bash -lc ls -R`. The `command` key
192/// trims before the emptiness check while other keys use raw emptiness,
193/// preserving historical per-key behavior. Indexed `command.N` parts are
194/// handled by [`command_words`]'s primary path, not here.
195///
196/// Returns `None` when no key carries a non-empty command.
197pub fn extract_command_text_with_key(args: &Value) -> Option<(String, &'static str)> {
198    if let Some(array) = args.get("command").and_then(Value::as_array) {
199        let joined: String = array
200            .iter()
201            .filter_map(|value| value.as_str())
202            .filter(|segment| !segment.is_empty())
203            .collect::<Vec<_>>()
204            .join(" ");
205        if !joined.is_empty() {
206            return Some((joined, "command"));
207        }
208    }
209    for &key in DISPLAY_COMMAND_KEYS {
210        let Some(value) = args.get(key).and_then(Value::as_str) else {
211            continue;
212        };
213        // The `command` key trims before the emptiness check; the others do not,
214        // matching historical per-key behavior.
215        let (text, ok) = if key == "command" {
216            let trimmed = value.trim();
217            (trimmed.to_string(), !trimmed.is_empty())
218        } else {
219            (value.to_string(), !value.is_empty())
220        };
221        if ok {
222            return Some((text, key));
223        }
224    }
225    None
226}
227
228fn has_nonempty_string_field(args: &Value, key: &str) -> bool {
229    args.get(key)
230        .and_then(Value::as_str)
231        .map(str::trim)
232        .is_some_and(|value| !value.is_empty())
233}
234
235pub fn interactive_input_text(args: &Value) -> Option<&str> {
236    args.get("input")
237        .and_then(Value::as_str)
238        .or_else(|| args.get("chars").and_then(Value::as_str))
239        .or_else(|| args.get("text").and_then(Value::as_str))
240        .filter(|value| !value.is_empty())
241}
242
243pub fn session_id_text_from_payload(payload: &serde_json::Map<String, Value>) -> Option<&str> {
244    payload
245        .get("session_id")
246        .or_else(|| payload.get("s"))
247        .and_then(Value::as_str)
248        .map(str::trim)
249        .filter(|value| !value.is_empty())
250}
251
252pub fn session_id_text(args: &Value) -> Option<&str> {
253    args.as_object().and_then(session_id_text_from_payload)
254}
255
256pub fn command_session_missing_required_args(args: &Value) -> Vec<&'static str> {
257    if command_session_action(args).is_none() {
258        return Vec::new();
259    }
260
261    let mut missing = Vec::new();
262    if command_session_action_is(args, "run") {
263        if command_text(args).ok().flatten().is_none() {
264            missing.push("command");
265        }
266    } else if command_session_action_is(args, "write") {
267        if session_id_text(args).is_none() {
268            missing.push("session_id");
269        }
270        if interactive_input_text(args).is_none() {
271            missing.push("input or chars or text");
272        }
273    } else if command_session_action_in(args, &["poll", "wait", "continue", "close"]) {
274        if session_id_text(args).is_none() {
275            missing.push("session_id");
276        }
277    } else if command_session_action_is(args, "inspect") {
278        let has_session_id = session_id_text(args).is_some();
279        let has_spool_path = has_nonempty_string_field(args, "spool_path");
280        if !has_session_id && !has_spool_path {
281            missing.push("session_id or spool_path");
282        }
283    } else if command_session_action_is(args, "code") {
284        let has_code = has_nonempty_string_field(args, "code") || has_nonempty_string_field(args, "command");
285        if !has_code {
286            missing.push("code or command");
287        }
288    }
289
290    missing
291}
292
293pub fn command_session_requires_command_safety(args: &Value) -> bool {
294    command_session_action_is(args, "run")
295}
296
297pub fn working_dir_text_from_payload(payload: &serde_json::Map<String, Value>) -> Option<&str> {
298    payload
299        .get("working_dir")
300        .or_else(|| payload.get("cwd"))
301        .or_else(|| payload.get("workdir"))
302        .and_then(Value::as_str)
303        .map(str::trim)
304        .filter(|value| !value.is_empty())
305}
306
307pub fn working_dir_text(args: &Value) -> Option<&str> {
308    args.as_object().and_then(working_dir_text_from_payload)
309}
310
311/// Extract the raw command string from command_session-style arguments without
312/// splitting it into words. This is useful for checking shell syntax that
313/// would be lost after `shell_words::split`, such as redirections and pipes.
314pub fn raw_command_text(args: &Value) -> Option<String> {
315    let payload = args.as_object()?;
316
317    if let Some(command) = payload
318        .get("command")
319        .or_else(|| payload.get("cmd"))
320        .or_else(|| payload.get("raw_command"))
321    {
322        match command {
323            Value::String(text) => return Some(text.clone()),
324            Value::Array(values) => {
325                let parts: Option<Vec<&str>> = values.iter().map(|v| v.as_str()).collect();
326                return parts.map(shell_words::join);
327            }
328            _ => return None,
329        }
330    }
331
332    let indexed = parse_indexed_command_parts(payload).ok().flatten()?;
333    Some(shell_words::join(indexed.iter().map(String::as_str)))
334}
335
336/// Complete static-classification candidate, including the quoted argv suffix
337/// that execution appends to shell text. Conflicting raw overrides cannot prove
338/// one invocation, so callers must fail closed instead of treating it as a read
339/// or verifier. Dynamic syntax and command options still need normal validation.
340pub(crate) fn shell_command_text_with_args(args: &Value) -> Option<String> {
341    let mut command = raw_command_text(args)?;
342    if args
343        .get("raw_command")
344        .and_then(Value::as_str)
345        .is_some_and(|raw| raw != command)
346    {
347        return None;
348    }
349    if let Some(arguments) = args.get("args") {
350        let arguments = arguments.as_array()?;
351        let suffix_words = arguments.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
352        if !suffix_words.is_empty() {
353            command.push(' ');
354            command.push_str(&shell_words::join(suffix_words));
355        }
356    }
357    Some(command)
358}
359
360/// Returns whether a shell command contains syntax whose meaning depends on
361/// shell expansion rather than the literal argument text.
362///
363/// Read-only classification and approval-family learning must only operate on
364/// static command shapes. Parameter expansion, command substitution, brace
365/// expansion, globbing, and unquoted backslash escapes can otherwise turn a
366/// harmless-looking token into a different executable argument at runtime.
367pub fn contains_dynamic_shell_syntax(command: &str) -> bool {
368    crate::command_safety::shell_parser::contains_dynamic_shell_syntax(command)
369}
370
371/// Single-walk result for an `env` / leading-assignment prefix.
372///
373/// `stripped_start` is the index of the executable that will actually run;
374/// `has_injection` reports whether the skipped prefix sets a known
375/// config/loader-injection key or uses `env -S` (which re-parses at runtime
376/// and cannot be audited). One walk produces both so safety checks never
377/// re-scan the same prefix twice and the `env`-flag table cannot drift
378/// between the stripping and injection paths.
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380struct EnvPrefixScan {
381    stripped_start: usize,
382    has_injection: bool,
383}
384
385fn is_env_split_string_flag(word: &str) -> bool {
386    word == "-S" || word == "--split-string" || word.starts_with("-S") || word.starts_with("--split-string=")
387}
388
389fn env_flag_consumes_next(word: &str) -> bool {
390    matches!(word, "-u" | "--unset" | "-C" | "--chdir")
391}
392
393/// Walk an optional `env` prefix plus leading `KEY=value` assignments once.
394///
395/// Shared by [`command_words_after_environment_prefix`] (stripping) and
396/// [`environment_prefix_has_injection_keys`] (injection audit) so both paths
397/// inspect the same command shape. Fail-closed notes:
398///
399/// - `env -S`/`--split-string` re-parses the rest at runtime: reported as
400///   injection with an empty remainder, matching both historical paths.
401/// - Words with an empty key (`=foo`) are NOT assignments: scanning stops and
402///   they are kept as the program (unknown, therefore mutating). The old
403///   stripping path skipped them via a broad `contains('=')` test; stopping is
404///   strictly fail-closed and the injection path is unchanged.
405fn scan_environment_prefix(words: &[String]) -> EnvPrefixScan {
406    let mut start = 0;
407    let mut has_injection = false;
408    loop {
409        if words.get(start).is_some_and(|word| word == "env") {
410            start += 1;
411            while let Some(word) = words.get(start) {
412                if word == "--" {
413                    start += 1;
414                    break;
415                }
416                if is_env_split_string_flag(word) {
417                    // Split-string re-parses the rest at runtime; cannot audit
418                    // assignments. Treat as unsafe with no auditable remainder.
419                    return EnvPrefixScan { stripped_start: words.len(), has_injection: true };
420                }
421                let consumes_next = env_flag_consumes_next(word);
422                start += 1;
423                if consumes_next {
424                    // `-u/--unset` removes a key; `-C/--chdir` takes a path.
425                    if words.get(start).is_some() {
426                        start += 1;
427                    }
428                    continue;
429                }
430                if let Some(key) = env_assignment_key(word) {
431                    if is_env_injection_key(key) {
432                        has_injection = true;
433                    }
434                    continue;
435                }
436                if word.starts_with('-') {
437                    continue;
438                }
439                start -= 1;
440                break;
441            }
442            continue;
443        }
444        if let Some(key) = words.get(start).and_then(|word| env_assignment_key(word)) {
445            if is_env_injection_key(key) {
446                has_injection = true;
447            }
448            start += 1;
449            continue;
450        }
451        break;
452    }
453    EnvPrefixScan { stripped_start: start, has_injection }
454}
455
456/// Skip an optional `env` prefix and leading shell environment assignments.
457///
458/// The returned slice starts at the executable that will actually run. Keep
459/// this helper shared by intent and activity classification so both paths
460/// inspect the same command shape.
461pub fn command_words_after_environment_prefix(words: &[String]) -> &[String] {
462    let scan = scan_environment_prefix(words);
463    &words[scan.stripped_start..]
464}
465
466/// Exact environment keys that can inject config, load foreign code, or launch
467/// helpers into an otherwise read-only program.
468const ENV_INJECTION_KEYS: &[&str] = &[
469    "GIT_CONFIG_COUNT",
470    "GIT_CONFIG_GLOBAL",
471    "GIT_CONFIG_SYSTEM",
472    "GIT_CONFIG_NOSYSTEM",
473    "GIT_EXTERNAL_DIFF",
474    "GIT_TEXTCONV",
475    "GIT_DIFF_OPTS",
476    "GIT_EDITOR",
477    "GIT_SEQUENCE_EDITOR",
478    "GIT_SSH",
479    "GIT_SSH_COMMAND",
480    "GIT_EXEC_PATH",
481    "LD_PRELOAD",
482    "LD_AUDIT",
483    "LD_LIBRARY_PATH",
484    "DYLD_INSERT_LIBRARIES",
485    "DYLD_LIBRARY_PATH",
486    "DYLD_FRAMEWORK_PATH",
487    "DYLD_FALLBACK_LIBRARY_PATH",
488    "BASH_ENV",
489    "ENV",
490    "SHELLOPTS",
491    "PERL5OPT",
492    "PYTHONSTARTUP",
493    "NODE_OPTIONS",
494    "RUBYOPT",
495    "EDITOR",
496    "VISUAL",
497    "PAGER",
498];
499
500/// Prefix families that always carry injection payload (`GIT_CONFIG_KEY_n` /
501/// `GIT_CONFIG_VALUE_n` pair with `GIT_CONFIG_COUNT`).
502const ENV_INJECTION_KEY_PREFIXES: &[&str] = &["GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_"];
503
504fn env_assignment_key(word: &str) -> Option<&str> {
505    if word.starts_with('-') {
506        return None;
507    }
508    let (key, _) = word.split_once('=')?;
509    if key.is_empty() {
510        return None;
511    }
512    Some(key)
513}
514
515fn is_env_injection_key(key: &str) -> bool {
516    ENV_INJECTION_KEYS.contains(&key) || ENV_INJECTION_KEY_PREFIXES.iter().any(|prefix| key.starts_with(prefix))
517}
518
519/// Returns whether an `env` / leading-assignment prefix sets a known
520/// config-injection or loader-injection key.
521///
522/// `command_words_after_environment_prefix` strips these assignments so the
523/// executable can be classified; the values themselves must still be checked.
524/// Unset (`env -u KEY`) is not an assignment. Unknown keys stay allowed so
525/// ordinary exploration (`LANG=C rg …`) keeps working.
526pub fn environment_prefix_has_injection_keys(words: &[String]) -> bool {
527    scan_environment_prefix(words).has_injection
528}
529
530/// Resolve the executable behind the supported flag-only `uv run` prefix.
531/// Unknown/value-taking wrapper options remain unclassified.
532pub(crate) fn uv_run_command_words(words: &[String]) -> Option<&[String]> {
533    if words.get(1).map(String::as_str) != Some("run") {
534        return None;
535    }
536    let index = words
537        .iter()
538        .enumerate()
539        .skip(2)
540        .find(|(_, word)| {
541            !matches!(
542                word.as_str(),
543                "--frozen" | "--locked" | "--no-sync" | "--offline" | "--no-project" | "--quiet" | "-q"
544            )
545        })?
546        .0;
547    (!words.get(index)?.starts_with('-')).then(|| &words[index..])
548}
549
550/// Explicit source repair modes cannot serve as completion verifiers, even
551/// when declared by a tracker. Command admission remains policy-owned.
552pub(crate) fn command_uses_source_repair(words: &[String]) -> bool {
553    let words = command_words_after_environment_prefix(words);
554    let Some(program) = words
555        .first()
556        .and_then(|word| Path::new(word).file_name())
557        .and_then(|name| name.to_str())
558    else {
559        return false;
560    };
561    let program = program.to_ascii_lowercase();
562    match program.as_str() {
563        "cargo" => {
564            let mut arguments = words.iter().skip(1).take_while(|word| word.as_str() != "--");
565            arguments.clone().any(|word| word.split('=').next() == Some("--fix"))
566                || arguments
567                    .find(|word| !word.starts_with(['-', '+']))
568                    .is_some_and(|word| word == "fix")
569        }
570        "ruff" => {
571            words.iter().skip(1).take_while(|word| word.as_str() != "--").any(|word| {
572                // `--unsafe-fixes` enables rewriting fixes, `-o`/`--output-file`
573                // writes the report, and `--add-noqa`/`--add-ignore` edit
574                // sources. `-o` also matches attached values (`-oFILE`); no
575                // other ruff short flag starts with `-o`, and `--output-*`
576                // long flags start with `--`, never `-o`.
577                word.split('=').next().is_some_and(|flag| {
578                    matches!(
579                        flag,
580                        "--fix" | "--fix-only" | "--unsafe-fixes" | "--output-file" | "--add-noqa" | "--add-ignore"
581                    ) || flag.starts_with("-o")
582                })
583            })
584        }
585        "uv" => uv_run_command_words(words).is_some_and(command_uses_source_repair),
586        _ => false,
587    }
588}
589
590/// Return whether a parsed command uses an option or environment assignment
591/// that can turn an otherwise read-only inspection program into a writer or
592/// command launcher.
593///
594/// This is deliberately option/env focused; the read-only executable/subcommand
595/// allow-list remains in `tool_intent::readonly`. Keeping the unsafe option
596/// rules here lets raw argument validation and activity classification share
597/// the same token-aware guard without searching quoted text.
598pub(crate) fn has_unsafe_readonly_options(words: &[String]) -> bool {
599    if command_uses_source_repair(words) {
600        return true;
601    }
602    // Single prefix walk: the scan yields both the injection verdict and the
603    // stripped executable offset, replacing the historical two-walk sequence
604    // (`environment_prefix_has_injection_keys` then
605    // `command_words_after_environment_prefix`).
606    let scan = scan_environment_prefix(words);
607    if scan.has_injection {
608        return true;
609    }
610    let command_words = &words[scan.stripped_start..];
611    let Some(program) = command_words
612        .first()
613        .and_then(|word| Path::new(word).file_name())
614        .and_then(|name| name.to_str())
615    else {
616        return false;
617    };
618    let program = program.to_ascii_lowercase();
619
620    match program.as_str() {
621        "rustc" => command_words.iter().enumerate().skip(1).any(|(index, word)| {
622            word.starts_with("-o")
623                || word.split('=').next() == Some("--out-dir")
624                || ["--print", "--emit"].iter().any(|option| {
625                    let value = if word == option {
626                        command_words.get(index + 1).map(String::as_str)
627                    } else {
628                        word.strip_prefix(option).and_then(|suffix| suffix.strip_prefix('='))
629                    };
630                    value.is_some_and(|value| value.contains('='))
631                })
632        }),
633        "pytest" | "python" | "python3" | "uv" => command_words.iter().skip(1).any(|word| {
634            matches!(
635                word.split('=').next(),
636                Some("--junitxml" | "--junit-xml" | "--log-file" | "--basetemp" | "--output-file")
637            )
638        }),
639        "ruff" => command_words
640            .iter()
641            .skip(1)
642            .any(|word| word.split('=').next() == Some("--output-file")),
643        "git" => command_words.iter().skip(1).any(|word| {
644            // `-C <dir>` (bare or inline `-C<dir>`) only redirects which
645            // repository is read; the subcommand allow-list still gates every
646            // git call, so it cannot turn an inspection into a writer. `-c
647            // key=value` stays prompt-requiring: config injection is a
648            // command-execution vector (fsmonitor/pager hooks).
649            let is_dir_redirect = word == "-C" || (word.starts_with("-C") && word.len() > 2);
650            (!is_dir_redirect && crate::command_safety::git_global_option_requires_prompt(word))
651                || word == "--ext-diff"
652                || word == "--textconv"
653                || word == "-o"
654                || word.starts_with("-o")
655                || word == "--output"
656                || word.starts_with("--output=")
657        }),
658        "sed" => has_unsafe_sed_options(&command_words[1..]),
659        "find" => command_words.iter().skip(1).any(|word| {
660            matches!(
661                word.as_str(),
662                "-delete" | "-exec" | "-execdir" | "-ok" | "-okdir" | "-fls" | "-fprint" | "-fprint0" | "-fprintf"
663            )
664        }),
665        "sort" => command_words.iter().skip(1).any(|word| {
666            word == "-o"
667                || word.starts_with("-o")
668                || word == "--output"
669                || word.starts_with("--output=")
670                || word == "--compress-program"
671                || word.starts_with("--compress-program=")
672        }),
673        "date" => command_words
674            .iter()
675            .skip(1)
676            .any(|word| word == "-s" || word.starts_with("-s") || word == "--set" || word.starts_with("--set=")),
677        "rg" => command_words.iter().skip(1).any(|word| {
678            matches!(word.as_str(), "--pre" | "--hostname-bin" | "--search-zip" | "-z")
679                || word.starts_with("--pre=")
680                || word.starts_with("--hostname-bin=")
681        }),
682        "fd" => command_words
683            .iter()
684            .skip(1)
685            .any(|word| word == "-x" || word == "--exec" || word == "--exec-batch" || word.starts_with("--exec=")),
686        "tree" => command_words
687            .iter()
688            .skip(1)
689            .any(|word| word == "-o" || word.starts_with("-o") || word == "--output" || word.starts_with("--output=")),
690        // `awk` stays on the read-only allow-list, but its program text can
691        // write (`print > file`), pipe into commands (`print | "cmd"`),
692        // execute them (`system()`), call them indirectly (`@func()`), or
693        // load code (`@include`, `@load`), and its options can edit in place
694        // (`-i inplace`), load external code (`-l`), or write profiles
695        // (`-p`). `has_unsafe_awk_options` fails closed on all of those; only
696        // data-only options (`-v`, `-F`) and a write-free program pass.
697        "awk" => has_unsafe_awk_options(&command_words[1..]),
698        // `bat` stays on the read-only allow-list, but `--pager <command>`
699        // selects the program bat spawns to page its output. bat only pages
700        // on a terminal, so under the PTY backend (which sets a controlling
701        // terminal) that program runs, which turns a read-only inspection
702        // into a command launcher.
703        "bat" => command_words.iter().skip(1).any(|word| {
704            word == "-p"
705                || word == "--pager"
706                || word.starts_with("--pager=")
707                || word == "--paging"
708                || word.starts_with("--paging=")
709        }),
710        _ => false,
711    }
712}
713
714pub fn normalize_shell_args(args: &Value) -> Result<Value, &'static str> {
715    let mut normalized = match normalize_indexed_command_args(args)? {
716        Some(value) => value,
717        None => args.clone(),
718    };
719
720    let Some(payload) = normalized.as_object_mut() else {
721        return Ok(normalized);
722    };
723
724    if payload.get("command").is_none() {
725        if let Some(command) = payload.get("cmd").cloned() {
726            payload.insert("command".to_string(), command);
727        } else if let Some(command) = payload.get("raw_command").cloned() {
728            payload.insert("command".to_string(), command);
729        }
730    }
731
732    if payload.get("input").is_none() {
733        if let Some(input) = payload.get("chars").cloned() {
734            payload.insert("input".to_string(), input);
735        } else if let Some(input) = payload.get("text").cloned() {
736            payload.insert("input".to_string(), input);
737        }
738    }
739
740    if payload.get("session_id").is_none()
741        && let Some(session_id) = payload.get("s").cloned()
742    {
743        payload.insert("session_id".to_string(), session_id);
744    }
745
746    if payload.get("max_tokens").is_none()
747        && let Some(max_output_tokens) = payload.get("max_output_tokens").cloned()
748    {
749        payload.insert("max_tokens".to_string(), max_output_tokens);
750    }
751
752    if payload.get("max_output_tokens").is_none()
753        && let Some(max_tokens) = payload.get("max_tokens").cloned()
754    {
755        payload.insert("max_output_tokens".to_string(), max_tokens);
756    }
757
758    Ok(normalized)
759}
760
761#[cfg(test)]
762mod tests;