instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! Codex "code mode" runs shell commands inside a JavaScript cell: a `custom_tool_call` named `exec` whose `input`
//! is code such as `const r = await tools.exec_command({cmd: "git status", workdir: "/repo"}); text(r.output)`.
//! This reads those cells without running anything: it finds each `exec_command(...)` call and takes the literal
//! `cmd` and `workdir` values. A template literal keeps its `${...}` interpolations as written; a value that is not a
//! literal (a variable, a concatenation) gives no command for that call.

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct ExecCall {
    pub(crate) cmd: String,
    pub(crate) workdir: Option<String>,
}

/// Every `exec_command` call with a literal command in the cell, in source order.
pub(crate) fn exec_calls(js: &str) -> Vec<ExecCall> {
    let b: Vec<char> = js.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            '/' if b.get(i + 1) == Some(&'/') => i = skip_line(&b, i),
            '/' if b.get(i + 1) == Some(&'*') => i = skip_block(&b, i),
            '"' | '\'' | '`' => i = literal(&b, i).1,
            c if is_ident(c) => {
                let start = i;
                while i < b.len() && is_ident(b[i]) {
                    i += 1;
                }
                let word: String = b[start..i].iter().collect();
                if word == "exec_command" {
                    let j = skip_space(&b, i);
                    if b.get(j) == Some(&'(') {
                        let (call, end) = arguments(&b, skip_space(&b, j + 1));
                        if let Some(call) = call {
                            out.push(call);
                        }
                        i = end.max(i);
                    }
                }
            }
            _ => i += 1,
        }
    }
    out
}

fn is_ident(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '$'
}

fn skip_space(b: &[char], mut i: usize) -> usize {
    loop {
        while i < b.len() && b[i].is_whitespace() {
            i += 1;
        }
        if b.get(i) == Some(&'/') && b.get(i + 1) == Some(&'/') {
            i = skip_line(b, i);
        } else if b.get(i) == Some(&'/') && b.get(i + 1) == Some(&'*') {
            i = skip_block(b, i);
        } else {
            return i;
        }
    }
}

fn skip_line(b: &[char], mut i: usize) -> usize {
    while i < b.len() && b[i] != '\n' {
        i += 1;
    }
    i
}

fn skip_block(b: &[char], mut i: usize) -> usize {
    i += 2;
    while i < b.len() && !(b[i] == '*' && b.get(i + 1) == Some(&'/')) {
        i += 1;
    }
    (i + 2).min(b.len())
}

/// Decodes the string or template literal starting at `i` (its opening quote); returns the value and the index just
/// past the closing quote. An unterminated literal runs to the end.
fn literal(b: &[char], i: usize) -> (String, usize) {
    let quote = b[i];
    let mut out = String::new();
    let mut j = i + 1;
    while j < b.len() {
        let c = b[j];
        if c == quote {
            return (out, j + 1);
        }
        if c == '\\' {
            j += 1;
            let Some(&e) = b.get(j) else { break };
            match e {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                'r' => out.push('\r'),
                'b' => out.push('\u{8}'),
                'f' => out.push('\u{c}'),
                'v' => out.push('\u{b}'),
                '0' if !b.get(j + 1).is_some_and(|d| d.is_ascii_digit()) => out.push('\0'),
                '\n' => {}
                'x' => {
                    let hex: String = b.iter().skip(j + 1).take(2).collect();
                    match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
                        Some(ch) if hex.len() == 2 => {
                            out.push(ch);
                            j += 2;
                        }
                        _ => out.push('x'),
                    }
                }
                'u' => {
                    let (code, used) = if b.get(j + 1) == Some(&'{') {
                        let hex: String = b.iter().skip(j + 2).take_while(|d| **d != '}').collect();
                        (u32::from_str_radix(&hex, 16).ok(), hex.chars().count() + 2)
                    } else {
                        let hex: String = b.iter().skip(j + 1).take(4).collect();
                        (u32::from_str_radix(&hex, 16).ok().filter(|_| hex.chars().count() == 4), 4)
                    };
                    match code.and_then(char::from_u32) {
                        Some(ch) => {
                            out.push(ch);
                            j += used;
                        }
                        None => out.push('u'),
                    }
                }
                other => out.push(other),
            }
            j += 1;
            continue;
        }
        if quote == '`' && c == '$' && b.get(j + 1) == Some(&'{') {
            // an interpolation stays as written, braces and nested literals included
            let end = interpolation_end(b, j + 2);
            out.extend(&b[j..end]);
            j = end;
            continue;
        }
        out.push(c);
        j += 1;
    }
    (out, b.len())
}

/// A String.raw template: backslashes stay as written, `${...}` stays as written. `i` is the opening backtick.
fn raw_template(b: &[char], i: usize) -> (String, usize) {
    let mut out = String::new();
    let mut j = i + 1;
    while j < b.len() {
        match b[j] {
            '`' => return (out, j + 1),
            '\\' => {
                out.push('\\');
                if let Some(&n) = b.get(j + 1) {
                    out.push(n);
                }
                j += 2;
            }
            '$' if b.get(j + 1) == Some(&'{') => {
                let end = interpolation_end(b, j + 2);
                out.extend(&b[j..end]);
                j = end;
            }
            c => {
                out.push(c);
                j += 1;
            }
        }
    }
    (out, b.len())
}

/// The literal value at `j`, if it is one: a quoted string, a template, or `String.raw` followed by a template.
fn value_literal(b: &[char], j: usize) -> Option<(String, usize)> {
    match b.get(j) {
        Some('"' | '\'' | '`') => Some(literal(b, j)),
        Some('S') => {
            let word: String = b[j..].iter().take(10).collect();
            if word != "String.raw" {
                return None;
            }
            let k = skip_space(b, j + 10);
            (b.get(k) == Some(&'`')).then(|| raw_template(b, k))
        }
        _ => None,
    }
}

/// Index just past the `}` that closes an interpolation whose body starts at `i`.
fn interpolation_end(b: &[char], mut i: usize) -> usize {
    let mut depth = 1;
    while i < b.len() {
        match b[i] {
            '"' | '\'' | '`' => i = literal(b, i).1,
            '{' => {
                depth += 1;
                i += 1;
            }
            '}' => {
                depth -= 1;
                i += 1;
                if depth == 0 {
                    return i;
                }
            }
            _ => i += 1,
        }
    }
    b.len()
}

/// Skips one expression up to a top-level `,` or the closing bracket of the enclosing group.
fn skip_value(b: &[char], mut i: usize) -> usize {
    let mut depth = 0usize;
    while i < b.len() {
        match b[i] {
            '"' | '\'' | '`' => i = literal(b, i).1,
            '/' if b.get(i + 1) == Some(&'/') => i = skip_line(b, i),
            '/' if b.get(i + 1) == Some(&'*') => i = skip_block(b, i),
            '(' | '[' | '{' => {
                depth += 1;
                i += 1;
            }
            ')' | ']' | '}' => {
                if depth == 0 {
                    return i;
                }
                depth -= 1;
                i += 1;
            }
            ',' if depth == 0 => return i,
            _ => i += 1,
        }
    }
    i
}

/// The argument of one `exec_command(` call, starting after the parenthesis: a string, or an object literal.
fn arguments(b: &[char], i: usize) -> (Option<ExecCall>, usize) {
    match b.get(i) {
        Some('"' | '\'' | '`') => {
            let (cmd, end) = literal(b, i);
            let after = skip_space(b, end);
            // only a lone literal argument is the command itself
            let alone = matches!(b.get(after), Some(')' | ','));
            (alone.then_some(ExecCall { cmd, workdir: None }), end)
        }
        Some('{') => {
            let mut j = i + 1;
            let (mut cmd, mut workdir) = (None, None);
            loop {
                j = skip_space(b, j);
                match b.get(j) {
                    None => return (None, b.len()),
                    Some('}') => {
                        j += 1;
                        break;
                    }
                    Some(',') => {
                        j += 1;
                        continue;
                    }
                    _ => {}
                }
                let key = match b[j] {
                    '"' | '\'' | '`' => {
                        let (k, end) = literal(b, j);
                        j = end;
                        k
                    }
                    c if is_ident(c) => {
                        let s = j;
                        while j < b.len() && is_ident(b[j]) {
                            j += 1;
                        }
                        b[s..j].iter().collect()
                    }
                    _ => {
                        j = skip_value(b, j);
                        continue;
                    }
                };
                j = skip_space(b, j);
                if b.get(j) != Some(&':') {
                    // shorthand `{cmd}` or a method: nothing literal to read
                    j = skip_value(b, j);
                    continue;
                }
                j = skip_space(b, j + 1);
                let parsed = value_literal(b, j);
                let literal_value = parsed.is_some();
                let end = parsed.as_ref().map_or_else(|| skip_value(b, j), |p| p.1);
                // a literal that opens a concatenation ("a" + x) keeps its leading text; any other trailing expression drops it
                let (alone, leads) = {
                    let k = skip_space(b, end);
                    (matches!(b.get(k), Some(',' | '}')), b.get(k) == Some(&'+'))
                };
                if literal_value && (alone || leads) {
                    let v = parsed.map(|p| p.0).unwrap_or_default();
                    match key.as_str() {
                        "cmd" => cmd = Some(v),
                        "workdir" => workdir = Some(v),
                        _ => {}
                    }
                } else if !literal_value {
                    // a variable or expression: the call has no literal value for this key
                    if key == "cmd" {
                        cmd = None;
                    }
                }
                j = if literal_value && !alone { skip_value(b, j) } else { end };
            }
            (cmd.map(|cmd| ExecCall { cmd, workdir }), j)
        }
        _ => (None, i),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn calls(js: &str) -> Vec<(String, Option<String>)> {
        exec_calls(js).into_iter().map(|c| (c.cmd, c.workdir)).collect()
    }

    #[test]
    fn reads_a_quoted_cmd_and_workdir() {
        let js = r#"const r=await tools.exec_command({cmd:"pwd; git status --short",workdir:"/home/yin/repo",max_output_tokens:2600});text(r.output)"#;
        assert_eq!(calls(js), vec![("pwd; git status --short".into(), Some("/home/yin/repo".into()))]);
    }

    #[test]
    fn decodes_escapes_in_double_single_and_template_strings() {
        let js = "await tools.exec_command({cmd:\"rg -n 'a|b\\\\(' src; echo \\\"x\\\"\\ndone\"});\
                  await tools.exec_command({cmd:'echo \\'hi\\' \\u0041\\x42'});";
        assert_eq!(calls(js), vec![("rg -n 'a|b\\(' src; echo \"x\"\ndone".into(), None), ("echo 'hi' AB".into(), None)]);
    }

    #[test]
    fn a_cell_with_two_calls_keeps_both_and_the_interpolation_as_written() {
        let js = "const a = await tools.exec_command({workdir: \"/w\", cmd: `git -C ${dir} status`});\n\
                  const b = await tools.exec_command({cmd: `echo ${ {x:`}`}.x } && ls`, workdir: `/w2`});";
        assert_eq!(
            calls(js),
            vec![("git -C ${dir} status".into(), Some("/w".into())), ("echo ${ {x:`}`}.x } && ls".into(), Some("/w2".into()))]
        );
    }

    #[test]
    fn a_string_argument_is_the_command() {
        assert_eq!(calls("await tools.exec_command('ls -la')"), vec![("ls -la".into(), None)]);
        assert_eq!(calls("await tools.exec_command(\"a\" + b)"), vec![]);
    }

    #[test]
    fn other_cells_and_non_literals_give_nothing() {
        assert!(calls("const r = await tools.apply_patch({input: patch}); text(r)").is_empty());
        assert!(calls("const c = 'ls'; await tools.exec_command({cmd: c})").is_empty());
        assert!(calls("await tools.exec_command({cmd: base + ' -la'})").is_empty());
        // the name inside a string or a comment is not a call
        assert!(calls("text(\"tools.exec_command({cmd:'rm -rf /'})\"); // tools.exec_command({cmd:'x'})").is_empty());
    }


    #[test]
    fn a_concatenated_cmd_keeps_its_leading_literal() {
        let js = "await tools.exec_command({cmd:\"sed -n '1,9p' '\"+p+\"'\",max_output_tokens:6000})";
        assert_eq!(calls(js), vec![("sed -n '1,9p' '".into(), None)]);
    }

    #[test]
    fn string_raw_keeps_backslashes_and_interpolations() {
        let js = "text(await tools.exec_command({cmd:String.raw`printf '%s\\n' \"a\\\\b\" ${x}`, workdir:\"/w\"}))";
        assert_eq!(calls(js), vec![("printf '%s\\n' \"a\\\\b\" ${x}".into(), Some("/w".into()))]);
    }
    #[test]
    fn a_literal_cmd_survives_other_keys_that_are_expressions() {
        let js = "await tools.exec_command({yield_time_ms: 1000 * 2, cmd: \"make\", env: {A: 'b,c'}, workdir: \"/x\"})";
        assert_eq!(calls(js), vec![("make".into(), Some("/x".into()))]);
    }
}