edgecrab-tools 0.2.3

Tool registry, ToolHandler trait, and 50+ tool implementations
Documentation
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
//! macOS-specific permission preflight checks.
//!
//! WHY this exists: heuristic command matching is enough to identify commands
//! that may trigger macOS consent prompts, but on macOS we can do better for a
//! subset of permissions by asking the OS directly before execution.
//!
//! Public macOS APIs are uneven:
//! - Accessibility: `AXIsProcessTrusted()` gives a direct yes/no answer.
//! - Apple Events / Automation: `AEDeterminePermissionToAutomateTarget()`
//!   reports granted / denied / would-prompt, but only for already-running
//!   target applications.
//! - Full Disk Access has no equivalent public preflight API, so protected-path
//!   access still relies on capability probing and output rewriting.

use std::sync::OnceLock;

use regex::Regex;

use crate::shell_syntax::parse_heredoc_marker;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacosConsentState {
    Granted,
    Denied,
    WouldPrompt,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MacosPermissionPreflight {
    pub automation_target: Option<String>,
    pub automation_state: Option<MacosConsentState>,
    pub accessibility_state: Option<MacosConsentState>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AutomationTarget {
    label: String,
    bundle_id: String,
}

fn applescript_target_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r#"(?is)tell\s+application(?:\s+id)?\s+["']([^"']+)["']"#)
            .expect("valid AppleScript target regex")
    })
}

fn accessibility_ui_scripting_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(
            r#"(?is)\bosascript\b.*(?:system\s+events|keystroke\b|key\s+code\b|click\s+(?:button|menu|menu item))"#,
        )
        .expect("valid accessibility regex")
    })
}

fn shortcuts_run_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"(?i)\bshortcuts\s+run\b").expect("valid shortcuts regex"))
}

fn memo_notes_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"(?i)\bmemo\s+notes\b").expect("valid memo notes regex"))
}

fn known_bundle_id(app_name: &str) -> Option<&'static str> {
    match app_name.trim().to_ascii_lowercase().as_str() {
        "notes" => Some("com.apple.Notes"),
        "system events" => Some("com.apple.systemevents"),
        "shortcuts" => Some("com.apple.shortcuts"),
        "finder" => Some("com.apple.finder"),
        "terminal" => Some("com.apple.Terminal"),
        "safari" => Some("com.apple.Safari"),
        "mail" => Some("com.apple.mail"),
        _ => None,
    }
}

fn automation_target_from_applescript(script: &str) -> Option<AutomationTarget> {
    let captures = applescript_target_regex().captures(script)?;
    let raw_target = captures.get(1)?.as_str().trim();
    if raw_target.starts_with("com.") {
        return Some(AutomationTarget {
            label: raw_target.into(),
            bundle_id: raw_target.into(),
        });
    }

    let bundle_id = known_bundle_id(raw_target)?;
    Some(AutomationTarget {
        label: raw_target.into(),
        bundle_id: bundle_id.into(),
    })
}

fn join_non_empty(parts: Vec<String>) -> Option<String> {
    let parts = parts
        .into_iter()
        .map(|part| part.trim().to_string())
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>();
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("\n"))
    }
}

fn extract_inline_osascript(command: &str) -> Option<String> {
    let tokens = shell_words::split(command).ok()?;
    let mut expressions = Vec::new();
    let mut idx = 0usize;

    while idx < tokens.len() {
        let token = &tokens[idx];
        let command_name = token.rsplit('/').next().unwrap_or(token);
        if command_name != "osascript" {
            idx += 1;
            continue;
        }

        idx += 1;
        while idx < tokens.len() {
            match tokens[idx].as_str() {
                "-e" => {
                    let expr = tokens.get(idx + 1)?;
                    expressions.push(expr.clone());
                    idx += 2;
                }
                "|" | "||" | "&&" | ";" => break,
                _ => idx += 1,
            }
        }
    }

    join_non_empty(expressions)
}

fn extract_osascript_heredoc(command: &str) -> Option<String> {
    let opener = command.lines().next()?.trim();
    if !opener.contains("<<") {
        return None;
    }

    let opens_osascript = opener.contains("osascript");
    let pipes_to_osascript = opener.contains("| osascript") || opener.contains("|osascript");
    if !opens_osascript && !pipes_to_osascript {
        return None;
    }

    let marker = parse_heredoc_marker(opener)?;
    let allows_tab_indented_terminator = opener.contains("<<-");
    let mut body_lines = Vec::new();
    for line in command.lines().skip(1) {
        let terminator = if allows_tab_indented_terminator {
            line.trim_start_matches('\t')
        } else {
            line
        };
        if terminator == marker {
            break;
        }
        body_lines.push(line);
    }
    let body = body_lines.join("\n");
    let body = body.trim();
    if body.is_empty() {
        return None;
    }
    Some(body.to_string())
}

fn extract_piped_literal_osascript(command: &str) -> Option<String> {
    let tokens = shell_words::split(command).ok()?;
    let pipe_idx = tokens.iter().position(|token| token == "|")?;
    let rhs = tokens.get(pipe_idx + 1)?;
    if rhs.rsplit('/').next().unwrap_or(rhs) != "osascript" {
        return None;
    }

    let lhs = &tokens[..pipe_idx];
    match lhs {
        [cmd, script] if cmd == "echo" => Some(script.clone()),
        [cmd, format, script] if cmd == "printf" && format.contains("%s") => Some(script.clone()),
        [cmd, format, first, second]
            if cmd == "printf" && format.contains("%s") && format.contains("\\n") =>
        {
            Some(format!("{first}\n{second}"))
        }
        _ => None,
    }
}

fn extract_literal_applescript(command: &str) -> Option<String> {
    extract_inline_osascript(command)
        .or_else(|| extract_osascript_heredoc(command))
        .or_else(|| extract_piped_literal_osascript(command))
}

fn automation_target_from_command(command: &str) -> Option<AutomationTarget> {
    if memo_notes_regex().is_match(command) {
        return Some(AutomationTarget {
            label: "Notes".into(),
            bundle_id: "com.apple.Notes".into(),
        });
    }
    if shortcuts_run_regex().is_match(command) {
        return Some(AutomationTarget {
            label: "Shortcuts".into(),
            bundle_id: "com.apple.shortcuts".into(),
        });
    }

    extract_literal_applescript(command)
        .and_then(|script| automation_target_from_applescript(&script))
        .or_else(|| automation_target_from_applescript(command))
}

fn command_needs_accessibility(command: &str) -> bool {
    accessibility_ui_scripting_regex().is_match(command)
}

#[cfg(target_os = "macos")]
fn macos_preflight(command: &str) -> MacosPermissionPreflight {
    let automation_target = automation_target_from_command(command);
    let automation_state = automation_target
        .as_ref()
        .map(|target| automation_consent_state(&target.bundle_id));
    let accessibility_state =
        command_needs_accessibility(command).then(accessibility_consent_state);
    MacosPermissionPreflight {
        automation_target: automation_target.map(|target| target.label),
        automation_state,
        accessibility_state,
    }
}

#[cfg(not(target_os = "macos"))]
fn macos_preflight(_command: &str) -> MacosPermissionPreflight {
    MacosPermissionPreflight::default()
}

pub fn preflight_command_permissions(command: &str) -> MacosPermissionPreflight {
    macos_preflight(command)
}

#[cfg(target_os = "macos")]
fn accessibility_consent_state() -> MacosConsentState {
    if unsafe { AXIsProcessTrusted() } != 0 {
        MacosConsentState::Granted
    } else {
        MacosConsentState::Denied
    }
}

#[cfg(target_os = "macos")]
fn automation_consent_state(bundle_id: &str) -> MacosConsentState {
    let Some(status) = automation_consent_status(bundle_id) else {
        return MacosConsentState::Unknown;
    };

    match status {
        0 => MacosConsentState::Granted,
        -1743 => MacosConsentState::Denied,
        -1744 => MacosConsentState::WouldPrompt,
        -600 => MacosConsentState::Unknown,
        _ => MacosConsentState::Unknown,
    }
}

#[cfg(target_os = "macos")]
fn automation_consent_status(bundle_id: &str) -> Option<i32> {
    let mut desc = AEDesc {
        descriptor_type: 0,
        data_handle: std::ptr::null_mut(),
    };
    let status = unsafe {
        AECreateDesc(
            four_char_code(*b"bund"),
            bundle_id.as_ptr().cast(),
            i32::try_from(bundle_id.len()).ok()?,
            &mut desc,
        )
    };
    if status != 0 {
        return None;
    }

    let permission_status = unsafe {
        AEDeterminePermissionToAutomateTarget(
            &desc,
            four_char_code(*b"****"),
            four_char_code(*b"****"),
            0,
        )
    };
    let _ = unsafe { AEDisposeDesc(&mut desc) };
    Some(permission_status)
}

#[cfg(target_os = "macos")]
const fn four_char_code(code: [u8; 4]) -> u32 {
    u32::from_be_bytes(code)
}

#[cfg(target_os = "macos")]
type Boolean = u8;

#[cfg(target_os = "macos")]
#[repr(C)]
struct AEDesc {
    descriptor_type: u32,
    data_handle: *mut std::ffi::c_void,
}

#[cfg(target_os = "macos")]
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
    fn AXIsProcessTrusted() -> Boolean;
}

#[cfg(target_os = "macos")]
#[link(name = "CoreServices", kind = "framework")]
unsafe extern "C" {
    fn AECreateDesc(
        type_code: u32,
        data_ptr: *const std::ffi::c_void,
        data_size: i32,
        result: *mut AEDesc,
    ) -> i32;
    fn AEDisposeDesc(desc: *mut AEDesc) -> i32;
    fn AEDeterminePermissionToAutomateTarget(
        target: *const AEDesc,
        event_class: u32,
        event_id: u32,
        ask_user_if_needed: Boolean,
    ) -> i32;
}

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

    #[test]
    fn detects_notes_target_from_memo() {
        let preflight = preflight_command_permissions("memo notes -s 'Title'");
        assert_eq!(preflight.automation_target.as_deref(), Some("Notes"));
        assert!(preflight.automation_state.is_some() || !cfg!(target_os = "macos"));
    }

    #[test]
    fn detects_accessibility_ui_scripting() {
        let preflight = preflight_command_permissions(
            "osascript -e 'tell application \"System Events\" to keystroke \"v\"'",
        );
        assert_eq!(
            preflight.automation_target.as_deref(),
            Some("System Events")
        );
        assert!(preflight.accessibility_state.is_some() || !cfg!(target_os = "macos"));
    }

    #[test]
    fn plain_osascript_delay_has_no_probe() {
        let preflight = preflight_command_permissions("osascript -e 'delay 1'");
        assert_eq!(preflight.automation_target, None);
        assert_eq!(preflight.automation_state, None);
        assert_eq!(preflight.accessibility_state, None);
    }

    #[test]
    fn detects_target_from_multiple_inline_e_segments() {
        let preflight = preflight_command_permissions(
            "osascript -e 'tell application \"Notes\"' -e 'activate'",
        );
        assert_eq!(preflight.automation_target.as_deref(), Some("Notes"));
    }

    #[test]
    fn detects_target_from_osascript_heredoc() {
        let preflight = preflight_command_permissions(
            "osascript <<'APPLESCRIPT'\ntell application \"Notes\" to activate\nAPPLESCRIPT",
        );
        assert_eq!(preflight.automation_target.as_deref(), Some("Notes"));
    }

    #[test]
    fn detects_target_from_piped_heredoc() {
        let preflight = preflight_command_permissions(
            "cat <<'APPLESCRIPT' | osascript\ntell application id \"com.apple.Notes\" to activate\nAPPLESCRIPT",
        );
        assert_eq!(
            preflight.automation_target.as_deref(),
            Some("com.apple.Notes")
        );
    }

    #[test]
    fn detects_target_from_printf_pipe() {
        let preflight = preflight_command_permissions(
            "printf '%s' 'tell application \"Notes\" to activate' | osascript",
        );
        assert_eq!(preflight.automation_target.as_deref(), Some("Notes"));
    }

    #[test]
    fn detects_target_from_tab_stripped_heredoc() {
        let preflight = preflight_command_permissions(
            "osascript <<-APPLESCRIPT\n\ttell application \"Notes\" to activate\n\tAPPLESCRIPT",
        );
        assert_eq!(preflight.automation_target.as_deref(), Some("Notes"));
    }
}