claux 20260416.0.1

Terminal AI coding assistant with tool execution
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
428
429
430
431
432
use serde::{Deserialize, Serialize};

use crate::utils::diff::generate_diff;

/// How permissions are handled.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum PermissionMode {
    /// Prompt for write operations, auto-allow reads
    #[default]
    Default,
    /// Auto-allow file edits, still prompt for bash
    AcceptEdits,
    /// Allow everything without prompting
    Bypass,
    /// Deny all write operations
    Plan,
}

/// Result of a permission check.
pub enum PermissionResult {
    Allow,
    Deny(String),
    Ask {
        message: String,
        diff: Option<String>,
    },
}

/// User's response to a permission prompt.
#[derive(Debug, Clone, PartialEq)]
pub enum PermissionResponse {
    /// Allow this one time
    Allow,
    /// Deny this one time
    Deny,
    /// Always allow this tool for the rest of the session
    AlwaysAllow,
    /// Always allow this specific command (for Bash tool only)
    AlwaysAllowCommand(String),
}

pub struct PermissionChecker {
    mode: PermissionMode,
    /// Tools the user has "always allowed" this session
    session_allows: std::collections::HashSet<String>,
    /// Specific bash commands the user has "always allowed" this session
    bash_command_allows: std::collections::HashSet<String>,
}

impl PermissionChecker {
    pub fn new(mode: PermissionMode) -> Self {
        Self {
            mode,
            session_allows: std::collections::HashSet::new(),
            bash_command_allows: std::collections::HashSet::new(),
        }
    }

    /// Record that the user chose "always allow" for a tool.
    pub fn always_allow(&mut self, tool_name: &str) {
        self.session_allows.insert(tool_name.to_string());
    }

    /// Record that the user chose "always allow" for a specific bash command.
    pub fn always_allow_command(&mut self, cmd: &str) {
        self.bash_command_allows.insert(cmd.to_string());
    }

    /// Check if a specific bash command is always allowed.
    pub fn is_command_allowed(&self, cmd: &str) -> bool {
        self.bash_command_allows.contains(cmd)
    }

    /// Check whether a tool invocation should be allowed.
    pub fn check(
        &self,
        tool_name: &str,
        input: &serde_json::Value,
        is_read_only: bool,
    ) -> PermissionResult {
        // Session-level always-allow overrides
        if self.session_allows.contains(tool_name) {
            return PermissionResult::Allow;
        }

        // Command-specific allows for Bash
        if tool_name == "Bash" {
            if let Some(cmd) = input["command"].as_str() {
                if self.bash_command_allows.contains(cmd) {
                    return PermissionResult::Allow;
                }
            }
        }

        match self.mode {
            PermissionMode::Bypass => PermissionResult::Allow,

            PermissionMode::Plan => {
                if is_read_only {
                    PermissionResult::Allow
                } else {
                    PermissionResult::Deny("Plan mode: write operations are disabled".to_string())
                }
            }

            PermissionMode::AcceptEdits => {
                if is_read_only || tool_name == "Write" || tool_name == "Edit" {
                    PermissionResult::Allow
                } else if tool_name == "Bash" {
                    let cmd = input["command"].as_str().unwrap_or("");
                    PermissionResult::Ask {
                        message: format!("Allow bash: {}?", truncate(cmd, 80)),
                        diff: None,
                    }
                } else {
                    PermissionResult::Allow
                }
            }

            PermissionMode::Default => {
                if is_read_only {
                    // Follow Claude Code's lead: prompt for Read and Grep, auto-allow Glob
                    match tool_name {
                        "Read" => {
                            let path = input["file_path"].as_str().unwrap_or("?");
                            PermissionResult::Ask {
                                message: format!("read: {path}"),
                                diff: None,
                            }
                        }
                        "Grep" => {
                            let pattern = input["pattern"].as_str().unwrap_or("?");
                            let path = input["path"].as_str().unwrap_or("");
                            let msg = if path.is_empty() {
                                format!("grep: \"{pattern}\"")
                            } else {
                                format!("grep: \"{pattern}\" in {path}")
                            };
                            PermissionResult::Ask {
                                message: msg,
                                diff: None,
                            }
                        }
                        "Glob" => PermissionResult::Allow,
                        "WebFetch" => {
                            let url = input["url"].as_str().unwrap_or("?");
                            PermissionResult::Ask {
                                message: format!("fetch: {url}"),
                                diff: None,
                            }
                        }
                        _ => PermissionResult::Allow,
                    }
                } else {
                    match tool_name {
                        "Bash" => {
                            let cmd = input["command"].as_str().unwrap_or("");
                            PermissionResult::Ask {
                                message: format!("bash: {}", truncate(cmd, 80)),
                                diff: None,
                            }
                        }
                        "Write" => {
                            let path = input["file_path"].as_str().unwrap_or("?");
                            PermissionResult::Ask {
                                message: format!("write: {path}"),
                                diff: None,
                            }
                        }
                        "Edit" => {
                            let path = input["file_path"].as_str().unwrap_or("?");
                            let old_string = input["old_string"].as_str().unwrap_or("");
                            let new_string = input["new_string"].as_str().unwrap_or("");

                            let diff = if !old_string.is_empty() && !new_string.is_empty() {
                                Some(generate_diff(old_string, new_string, path))
                            } else {
                                None
                            };

                            PermissionResult::Ask {
                                message: format!("edit: {path}"),
                                diff,
                            }
                        }
                        _ => PermissionResult::Ask {
                            message: tool_name.to_string(),
                            diff: None,
                        },
                    }
                }
            }
        }
    }
}

fn truncate(s: &str, max: usize) -> &str {
    if s.len() <= max {
        s
    } else {
        &s[..max]
    }
}

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

    #[test]
    fn bypass_allows_everything() {
        let checker = PermissionChecker::new(PermissionMode::Bypass);
        let input = json!({"command": "rm -rf /"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn plan_denies_writes() {
        let checker = PermissionChecker::new(PermissionMode::Plan);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Deny(_)
        ));
    }

    #[test]
    fn plan_allows_reads() {
        let checker = PermissionChecker::new(PermissionMode::Plan);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Read", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_allows_read_only() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "*.rs"});
        assert!(matches!(
            checker.check("Glob", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_asks_for_bash() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn default_asks_for_write() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "/tmp/test", "content": "hello"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn accept_edits_allows_write_and_edit() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Edit", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn accept_edits_asks_for_bash() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"command": "rm -rf /"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn always_allow_overrides_mode() {
        let mut checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});

        // First call should ask
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));

        // After always_allow, should allow
        checker.always_allow("Bash");
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn always_allow_is_tool_specific() {
        let mut checker = PermissionChecker::new(PermissionMode::Default);
        checker.always_allow("Bash");

        let input = json!({"file_path": "/tmp/test"});
        // Write should still ask
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn ask_summary_contains_command() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});
        if let PermissionResult::Ask { message, diff: _ } = checker.check("Bash", &input, false) {
            assert!(message.contains("cargo test"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn ask_summary_contains_file_path() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "/home/ducks/important.rs"});
        if let PermissionResult::Ask { message, diff: _ } = checker.check("Edit", &input, false) {
            assert!(message.contains("important.rs"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn edit_permission_includes_diff_when_fields_present() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({
            "file_path": "src/main.rs",
            "old_string": "let x = 1",
            "new_string": "let x = 2"
        });

        if let PermissionResult::Ask { message, diff } = checker.check("Edit", &input, false) {
            assert!(message.contains("src/main.rs"));
            assert!(diff.is_some(), "Diff should be generated when old_string and new_string are provided");
            let diff_content = diff.unwrap();
            assert!(diff_content.contains("src/main.rs"));
            assert!(diff_content.contains("-let x = 1"));
            assert!(diff_content.contains("+let x = 2"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn edit_permission_no_diff_when_fields_missing() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "src/main.rs"});

        if let PermissionResult::Ask { message, diff } = checker.check("Edit", &input, false) {
            assert!(message.contains("src/main.rs"));
            assert!(diff.is_none(), "Diff should be None when old_string/new_string are missing");
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn default_prompts_for_read_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "src/secret.rs"});

        if let PermissionResult::Ask { message, diff } = checker.check("Read", &input, true) {
            assert!(message.contains("src/secret.rs"));
            assert!(diff.is_none());
        } else {
            panic!("expected Ask for Read tool");
        }
    }

    #[test]
    fn default_prompts_for_grep_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "SECRET_KEY", "path": "src/"});

        if let PermissionResult::Ask { message, diff } = checker.check("Grep", &input, true) {
            assert!(message.contains("src/"));
            assert!(diff.is_none());
        } else {
            panic!("expected Ask for Grep tool");
        }
    }

    #[test]
    fn default_auto_allows_glob_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "*.rs"});

        assert!(matches!(
            checker.check("Glob", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_prompts_for_webfetch_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"url": "https://example.com/api"});

        if let PermissionResult::Ask { message, diff } = checker.check("WebFetch", &input, true) {
            assert!(message.contains("https://example.com/api"));
            assert!(diff.is_none());
        } else {
            panic!("expected Ask for WebFetch tool");
        }
    }
}