Skip to main content

host/
bash_notes.rs

1//! Result conventions of the model's `bash` (wave 38, from Mirror's tools/bash_tool.rs):
2//!
3//! - exit code 1 from a read-only comparison command (`grep`, `rg`, `diff`, `cmp`, `test`, ...) reports a result,
4//!   not a failure. When the command is a simple pipeline whose last command is one of those, the result carries an
5//!   `exit_note` ("No matches found"); runtime.py then shows `[No matches found (exit code 1)]` instead of the
6//!   failure line `[exit code 1]`. `exit_code` stays 1 (and `.ok`, a clean exit 0, stays false);
7//! - a failed command whose output shows the sandbox refused it carries a `sandbox_note` (`sandbox::refusal`), a
8//!   line runtime.py prints after the output, saying what was blocked and what is allowed.
9
10use serde_json::Value;
11
12/// Commands whose exit code 1 reports a result, and the note shown in place of the failure line.
13pub const NON_ERROR_EXIT_1: &[(&str, &str)] = &[
14    ("grep", "No matches found"),
15    ("egrep", "No matches found"),
16    ("fgrep", "No matches found"),
17    ("rg", "No matches found"),
18    ("diff", "Files differ"),
19    ("cmp", "Files differ"),
20    ("test", "Condition is false"),
21    ("[", "Condition is false"),
22];
23
24/// The note for `exit_code` of `command`: exit code 1 of a simple pipeline (commands joined by `|` or `|&`, nothing
25/// else) whose last command is one of [`NON_ERROR_EXIT_1`]. Anything else (`;`, `&&`, `||`, `&`, a newline, a
26/// subshell or command substitution, a `!` negation) may have taken its status from another command: no note.
27pub fn exit_note(command: &str, exit_code: Option<i32>) -> Option<&'static str> {
28    if exit_code != Some(1) {
29        return None;
30    }
31    let last = pipeline_commands(command)?.pop()?;
32    let program = program_of(&last)?;
33    let name = program.rsplit('/').next().unwrap_or(&program);
34    NON_ERROR_EXIT_1
35        .iter()
36        .find(|(candidate, _)| *candidate == name)
37        .map(|(_, note)| *note)
38}
39
40/// The commands of a simple pipeline, split on `|` outside quotes; None when `command` is anything more.
41fn pipeline_commands(command: &str) -> Option<Vec<String>> {
42    let mut parts = Vec::new();
43    let mut current = String::new();
44    let (mut in_single, mut in_double) = (false, false);
45    let mut characters = command.trim().chars().peekable();
46    while let Some(character) = characters.next() {
47        if in_single {
48            in_single = character != '\'';
49            current.push(character);
50            continue;
51        }
52        match character {
53            '\\' => {
54                current.push(character);
55                current.push(characters.next()?);
56            }
57            '\'' if !in_double => {
58                in_single = true;
59                current.push(character);
60            }
61            '"' => {
62                in_double = !in_double;
63                current.push(character);
64            }
65            // Substitutions run commands of their own, inside quotes too.
66            '`' => return None,
67            '$' if characters.peek() == Some(&'(') => return None,
68            _ if in_double => current.push(character),
69            // `2>&1`, `>&2`, `&>file`: redirections, not a background `&` or `&&`.
70            '&' if current.ends_with(['>', '<']) || characters.peek() == Some(&'>') => current.push(character),
71            // A comment starts at a word's beginning; elsewhere `#` is part of the word.
72            '#' if !(current.is_empty() || current.ends_with(char::is_whitespace)) => current.push(character),
73            ';' | '&' | '\n' | '(' | ')' | '{' | '}' | '#' => return None,
74            '|' => {
75                match characters.peek() {
76                    Some('|') => return None,
77                    Some('&') => {
78                        characters.next();
79                    }
80                    _ => {}
81                }
82                parts.push(std::mem::take(&mut current));
83            }
84            _ => current.push(character),
85        }
86    }
87    if in_single || in_double {
88        return None;
89    }
90    parts.push(current);
91    parts.iter().all(|part| !part.trim().is_empty()).then_some(parts)
92}
93
94/// The program a simple command runs: its first word after `NAME=value` assignments, unquoted (a `!` negation,
95/// where exit code 1 means the command succeeded, is a word of its own and no comparison command).
96fn program_of(command: &str) -> Option<String> {
97    let program = command.split_whitespace().find(|word| !is_assignment(word))?;
98    Some(program.trim_matches(|c| c == '\'' || c == '"').to_string())
99}
100
101fn is_assignment(word: &str) -> bool {
102    word.split_once('=').is_some_and(|(name, _)| {
103        !name.is_empty()
104            && !name.starts_with(|c: char| c.is_ascii_digit())
105            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
106    })
107}
108
109/// Adds the notes to a `bash` result (`output`) or a job snapshot (`text`) of `command`: `exit_note` when the
110/// command ended with a non-error exit 1, `sandbox_note` when it failed and `policy` (the sandbox in use, if any)
111/// refused it. A result still running, stopped or without an exit code gets neither.
112pub fn annotate(result: &mut Value, command: &str, policy: Option<&sandbox::Policy>) {
113    let Some(object) = result.as_object_mut() else {
114        return;
115    };
116    let flag = |key: &str| object.get(key).and_then(Value::as_bool) == Some(true);
117    if flag("running") || flag("cancelled") || flag("timed_out") {
118        return;
119    }
120    if object
121        .get("status")
122        .and_then(Value::as_str)
123        .is_some_and(|status| status != "completed")
124    {
125        return;
126    }
127    let exit_code = object
128        .get("exit_code")
129        .and_then(Value::as_i64)
130        .and_then(|code| i32::try_from(code).ok());
131    if let Some(note) = exit_note(command, exit_code) {
132        object.insert("exit_note".into(), note.into());
133    }
134    let Some(policy) = policy.filter(|_| exit_code.is_some_and(|code| code != 0)) else {
135        return;
136    };
137    let output = ["output", "text"]
138        .iter()
139        .find_map(|key| object.get(*key).and_then(Value::as_str))
140        .unwrap_or_default();
141    if let Some(note) = sandbox::refusal::refusal_note(policy, output) {
142        object.insert("sandbox_note".into(), note.into());
143    }
144}