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