argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! What a direct turn's CLI asks you, as Claude Code asks it: a question per edit, command, or
//! other tool, answered Yes, Yes and don't ask again, or No. What you already allowed is answered
//! here without one.

use argonauts_core::asking::AskReply;
use argonauts_core::events::approval::AnswerOption;
use serde_json::Value;

use crate::choices::{choose, option};

/// Claude Code's tools that change a file.
const EDIT_TOOLS: &[&str] = &["Edit", "Write", "MultiEdit", "NotebookEdit"];

/// Claude Code's shell tool.
const COMMAND_TOOL: &str = "Bash";

/// A folder outside your checkout, as OpenCode asks for it (`external_directory`). Never
/// allowed without asking, and never for good.
pub(crate) const OUTSIDE_TOOL: &str = "ExternalDirectory";

/// Body rows shown at most; the question says how many more there are.
const MAX_ROWS: usize = 12;

/// What "don't ask again" would cover.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Grant {
    /// Every edit, for the rest of the conversation.
    Edits,
    /// Commands that start with this, saved to `approvals.allow_commands`.
    Commands(String),
    /// Every call of this tool, saved to `approvals.allow_commands` by its name.
    Tool(String),
    /// Nothing: this question is asked every time.
    Never,
}

/// One question, ready to show.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Question {
    pub title: String,
    pub body: Vec<String>,
    pub grant: Grant,
    /// What it asks about, as the closed question says it: "the edit to notes.txt".
    pub about: String,
}

impl Question {
    pub(crate) fn of(tool: &str, input: &Value) -> Self {
        if EDIT_TOOLS.contains(&tool) {
            let file = text(input, &["file_path", "notebook_path", "path"]);
            let file = if file.is_empty() { "a file" } else { &file };
            return Self {
                title: format!("Make this edit to {file}?"),
                body: edit_rows(input),
                grant: Grant::Edits,
                about: format!("the edit to {file}"),
            };
        }
        if tool == COMMAND_TOOL {
            let command = text(input, &["command"]);
            let mut body: Vec<String> = command.lines().map(str::to_owned).collect();
            let description = text(input, &["description"]);
            if !description.is_empty() {
                body.push(description);
            }
            let first = command.lines().next().unwrap_or_default().trim();
            let mut body = capped(body);
            // Claude Code asks about these every time, so nothing can be allowed for good.
            let grant = match super::rm::always_asked(&command) {
                Some(why) => {
                    body.push(format!("Claude Code always asks about this one: {why}."));
                    Grant::Never
                }
                None => Grant::Commands(command_prefix(&command)),
            };
            return Self {
                title: "Run this command?".to_owned(),
                body,
                grant,
                about: crate::controller::recap::title_from_request(first),
            };
        }
        if tool == OUTSIDE_TOOL {
            let folder = text(input, &["path"]);
            return Self {
                title: format!("Work outside your folder, in {folder}?"),
                about: format!("working in {folder}"),
                body: vec![folder],
                grant: Grant::Never,
            };
        }
        let shown = serde_json::to_string_pretty(input).unwrap_or_default();
        Self {
            title: String::new(),
            body: capped(shown.lines().map(str::to_owned).collect()),
            grant: Grant::Tool(tool.to_owned()),
            about: tool.to_owned(),
        }
    }

    /// The question's title, naming the CLI where the tool is its own.
    pub(crate) fn title(&self, cli: &str, tool: &str) -> String {
        if self.title.is_empty() {
            format!("Let {cli} use {tool}?")
        } else {
            self.title.clone()
        }
    }

    /// Yes `y`, Yes and don't ask again `a`, No `n`, as Claude Code words them.
    pub(crate) fn options(&self, cli: &str) -> Vec<AnswerOption> {
        let again = match &self.grant {
            Grant::Edits => {
                Some("Yes, and allow edits for the rest of this conversation".to_owned())
            }
            Grant::Commands(prefix) => Some(format!(
                "Yes, and don't ask again for {prefix} in this project"
            )),
            Grant::Tool(tool) => Some(format!(
                "Yes, and don't ask again for {tool} in this project"
            )),
            Grant::Never => None,
        };
        let mut options = vec![option('y', "Yes", choose("yes"), true)];
        options.extend(again.map(|again| option('a', &again, choose("always"), false)));
        options.push(option(
            'n',
            &format!("No, and tell {cli} what to do instead (esc)"),
            choose("no"),
            false,
        ));
        options
    }
}

/// Whether your earlier answers already allow this call.
pub(crate) fn allowed(tool: &str, input: &Value, edits_allowed: bool, patterns: &[String]) -> bool {
    if tool == OUTSIDE_TOOL {
        return false;
    }
    if EDIT_TOOLS.contains(&tool) {
        // Argonauts Code's own files change through a setup you pick a place for, never through an
        // edit you allowed for the code, so such an edit always asks.
        let file = text(input, &["file_path", "notebook_path", "path"]);
        return edits_allowed && !in_setup_folder(&file);
    }
    if tool == COMMAND_TOOL {
        // A command that reaches into Argonauts Code's own files asks each time, as their edits do.
        let command = text(input, &["command"]);
        return !names_setup_folder(&command)
            && patterns
                .iter()
                .any(|pattern| command_matches(pattern, &command));
    }
    patterns.iter().any(|pattern| pattern == tool)
}

/// The pattern "don't ask again" saves for a command: its prefix, then ` *`.
pub(crate) fn command_pattern(prefix: &str) -> String {
    format!("{prefix} *")
}

/// A pattern ending in ` *` covers the command it names and any that go on from it; any other
/// pattern covers itself. A command that chains, pipes, or redirects is never covered, since
/// its prefix says nothing of the rest.
pub(crate) fn command_matches(pattern: &str, command: &str) -> bool {
    let command = command.trim();
    if command.is_empty() || has_shell_operators(command) {
        return false;
    }
    match pattern.strip_suffix(" *") {
        Some(base) => command == base || command.starts_with(&format!("{base} ")),
        None => command == pattern,
    }
}

/// The words a command starts with that say what it runs, such as `python -m pytest` or
/// `cargo test`: up to three, stopping at a flag (but for `-m`), a path, or anything the shell
/// reads.
pub(crate) fn command_prefix(command: &str) -> String {
    let mut words = Vec::new();
    let mut takes_module = false;
    for word in command.split_whitespace() {
        if words.len() == 3 || has_shell_operators(word) {
            break;
        }
        if takes_module {
            words.push(word);
            takes_module = false;
            continue;
        }
        if word == "-m" {
            words.push(word);
            takes_module = true;
            continue;
        }
        if word.starts_with('-') || word.contains('/') || word.contains('=') {
            break;
        }
        words.push(word);
    }
    if words.is_empty() {
        command.trim().to_owned()
    } else {
        words.join(" ")
    }
}

fn has_shell_operators(text: &str) -> bool {
    ["&&", "||", ";", "|", ">", "<", "`", "$(", "\n", "&"]
        .iter()
        .any(|operator| text.contains(operator))
}

/// What No says to the CLI, which then stops, as Claude Code does when you answer no.
pub(crate) fn no() -> AskReply {
    AskReply::deny("The user said no to this. Stop, and wait for what they say next.")
}

/// Whether autopilot says yes with nobody there. A turn started on autopilot never asks, so
/// whatever "don't ask again" could cover is a yes. What is asked about every time isn't: a
/// removal Claude Code always asks about, a folder outside yours, and Argonauts Code's own
/// files.
pub(crate) fn autopilot_allows(tool: &str, input: &Value) -> bool {
    if Question::of(tool, input).grant == Grant::Never {
        return false;
    }
    if EDIT_TOOLS.contains(&tool) {
        return !in_setup_folder(&text(input, &["file_path", "notebook_path", "path"]));
    }
    tool != COMMAND_TOOL || !names_setup_folder(&text(input, &["command"]))
}

/// What autopilot's no says to the CLI, which skips the call and carries on.
pub(crate) fn not_on_autopilot() -> AskReply {
    AskReply::deny(
        "Nobody is at the terminal: the user is on autopilot, and this is asked about every \
         time. Carry on without it, and say in your answer what you left undone.",
    )
}

/// An edit as `-` and `+` rows, or a new file's first lines.
fn edit_rows(input: &Value) -> Vec<String> {
    let mut rows = Vec::new();
    let mut pair = |old: &str, new: &str| {
        rows.extend(old.lines().map(|line| format!("- {line}")));
        rows.extend(new.lines().map(|line| format!("+ {line}")));
    };
    // An ACP agent's edit comes as a unified diff.
    if let Some(diff) = input.get("diff").and_then(Value::as_str) {
        let changed = diff
            .lines()
            .filter(|line| !line.starts_with("+++") && !line.starts_with("---"))
            .filter_map(|line| match line.split_at_checked(1) {
                Some(("+", rest)) => Some(format!("+ {rest}")),
                Some(("-", rest)) => Some(format!("- {rest}")),
                _ => None,
            });
        return capped(changed.collect());
    }
    if let Some(edits) = input.get("edits").and_then(Value::as_array) {
        for edit in edits {
            pair(&text(edit, &["old_string"]), &text(edit, &["new_string"]));
        }
    } else if input.get("old_string").is_some() {
        pair(&text(input, &["old_string"]), &text(input, &["new_string"]));
    } else {
        pair("", &text(input, &["content", "new_source"]));
    }
    capped(rows)
}

fn capped(mut rows: Vec<String>) -> Vec<String> {
    if rows.len() > MAX_ROWS {
        let hidden = rows.len() - (MAX_ROWS - 1);
        rows.truncate(MAX_ROWS - 1);
        rows.push(format!("… +{hidden} lines"));
    }
    rows
}

/// Whether a shell command names a `.argonauts` folder anywhere in it.
pub(crate) fn names_setup_folder(command: &str) -> bool {
    command.contains(".argonauts")
}

/// A path in a `.argonauts` folder, the project's or yours.
pub(crate) fn in_setup_folder(path: &str) -> bool {
    std::path::Path::new(path)
        .components()
        .any(|part| part.as_os_str() == ".argonauts")
}

fn text(value: &Value, keys: &[&str]) -> String {
    keys.iter()
        .find_map(|key| value.get(*key).and_then(Value::as_str))
        .unwrap_or_default()
        .to_owned()
}

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

    /// OpenCode asking to reach a folder outside yours (live, 1.18.34) gets a question of its own,
    /// answered Yes or No, and nothing you allowed before covers it.
    #[test]
    fn a_folder_outside_yours_is_asked_about_every_time() {
        let input = json!({"path": "/"});
        let question = Question::of(OUTSIDE_TOOL, &input);
        assert_eq!(
            question.title("OpenCode", OUTSIDE_TOOL),
            "Work outside your folder, in /?"
        );
        let keys: Vec<char> = question
            .options("OpenCode")
            .iter()
            .map(|option| option.key)
            .collect();
        assert_eq!(keys, ['y', 'n']);
        let everything = [OUTSIDE_TOOL.to_owned(), "* *".to_owned()];
        assert!(!allowed(OUTSIDE_TOOL, &input, true, &everything));
    }

    #[test]
    fn each_tool_gets_claude_codes_question() {
        let edit = Question::of(
            "Edit",
            &json!({"file_path": "invoice/money.py", "old_string": "sign = 1", "new_string": "negative = True"}),
        );
        assert_eq!(
            edit.title("Claude Code", "Edit"),
            "Make this edit to invoice/money.py?"
        );
        assert_eq!(edit.body, ["- sign = 1", "+ negative = True"]);
        let labels: Vec<_> = edit
            .options("Claude Code")
            .into_iter()
            .map(|option| option.label)
            .collect();
        assert_eq!(
            labels,
            [
                "Yes",
                "Yes, and allow edits for the rest of this conversation",
                "No, and tell Claude Code what to do instead (esc)"
            ]
        );

        let bash = Question::of("Bash", &json!({"command": "python -m pytest -q"}));
        assert_eq!(bash.title("Claude Code", "Bash"), "Run this command?");
        assert_eq!(bash.grant, Grant::Commands("python -m pytest".into()));

        // A flagged rm says why it's asked, and offers no "don't ask again".
        let rm = Question::of("Bash", &json!({"command": r#"rm -rf "$BUILD_DIR/tmp""#}));
        assert_eq!(rm.grant, Grant::Never);
        assert_eq!(
            rm.body,
            [
                r#"rm -rf "$BUILD_DIR/tmp""#,
                "Claude Code always asks about this one: if BUILD_DIR were empty, it would \
                 remove /tmp."
            ]
        );
        let labels: Vec<_> = rm
            .options("Claude Code")
            .into_iter()
            .map(|option| option.label)
            .collect();
        assert_eq!(
            labels,
            ["Yes", "No, and tell Claude Code what to do instead (esc)"]
        );

        let fetch = Question::of("WebFetch", &json!({"url": "https://example.com"}));
        assert_eq!(
            fetch.title("Claude Code", "WebFetch"),
            "Let Claude Code use WebFetch?"
        );
        assert_eq!(fetch.grant, Grant::Tool("WebFetch".into()));
    }

    #[test]
    fn a_saved_pattern_covers_its_commands_and_nothing_chained() {
        let pattern = command_pattern(&command_prefix("cargo test --workspace"));
        assert_eq!(pattern, "cargo test *");
        assert!(command_matches(&pattern, "cargo test"));
        assert!(command_matches(&pattern, "cargo test -p app"));
        assert!(!command_matches(&pattern, "cargo testify"));
        assert!(!command_matches(&pattern, "cargo test && rm -rf x"));
        assert!(!command_matches(&pattern, "cargo test > out.txt"));
        assert_eq!(command_prefix("echo hi > shell.txt"), "echo hi");
        assert_eq!(command_prefix("./run.sh"), "./run.sh");

        let patterns = vec![pattern, "WebFetch".to_owned()];
        assert!(allowed(
            "Bash",
            &json!({"command": "cargo test"}),
            false,
            &patterns
        ));
        assert!(!allowed(
            "Bash",
            &json!({"command": "ls"}),
            false,
            &patterns
        ));
        // A command into Argonauts Code's own files asks each time, whatever was allowed before.
        let into_settings = json!({"command": "cargo test --manifest-path .argonauts/x.toml"});
        assert!(!allowed("Bash", &into_settings, true, &patterns));
        assert!(allowed("WebFetch", &json!({}), false, &patterns));
        assert!(!allowed("Edit", &json!({}), false, &patterns));
        assert!(allowed("Write", &json!({}), true, &patterns));
        // Edits allowed for the code never reach Argonauts Code's own files.
        let settings = json!({"file_path": "/repo/.argonauts/config.toml"});
        assert!(!allowed("Write", &settings, true, &patterns));
        let role = json!({"file_path": ".argonauts/roles/reviewer.md"});
        assert!(!allowed("Edit", &role, true, &patterns));
        assert!(allowed(
            "Edit",
            &json!({"file_path": "src/app.rs"}),
            true,
            &patterns
        ));
    }
}