aidaemon 0.11.10

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! macOS Accessibility + screen capture backend for `computer_use`.
#![allow(dead_code, clippy::too_many_arguments)]

use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use async_trait::async_trait;
use axuielement::ax_action::AX_PRESS_ACTION;
use axuielement::ax_attribute::attributes::{
    AX_DESCRIPTION_ATTRIBUTE, AX_ENABLED_ATTRIBUTE, AX_FOCUSED_ATTRIBUTE, AX_MAIN_ATTRIBUTE,
    AX_POSITION_ATTRIBUTE, AX_ROLE_ATTRIBUTE, AX_SIZE_ATTRIBUTE, AX_SUBROLE_ATTRIBUTE,
    AX_TITLE_ATTRIBUTE, AX_VALUE_ATTRIBUTE, AX_WINDOWS_ATTRIBUTE,
};
use axuielement::AXUIElement;
use axuielement::{is_process_trusted, is_process_trusted_with_prompt};
use enigo::{Button, Coordinate, Direction, Enigo, Key, Keyboard, Mouse, Settings};
use xcap::image::imageops::FilterType;
use xcap::image::RgbaImage;
use xcap::Window;

use crate::config::ComputerUseConfig;

use super::cache::{SnapshotCache, SnapshotKey};
use super::harness::{ComputerHarness, HarnessRequestContext};
use super::policy::is_prohibited_bundle;
use super::types::{AppInfo, AppSnapshot, AxWalkLimits, ElementBounds, IndexedElement};

const ACCESSIBILITY_HELP: &str = "Accessibility permission is required. \
Grant it in System Settings → Privacy & Security → Accessibility for aidaemon, then retry.";
const SCREEN_RECORDING_HELP: &str = "Screen Recording permission is required. \
Grant it in System Settings → Privacy & Security → Screen Recording for aidaemon. \
This permission only takes effect after the daemon is restarted.";

// CoreGraphics screen-capture authorization (macOS 10.15+). Preflight is a
// non-prompting probe; Request triggers the system prompt and registers the
// app in the Screen Recording pane so the user has something to toggle.
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
    fn CGPreflightScreenCaptureAccess() -> bool;
    fn CGRequestScreenCaptureAccess() -> bool;
}

pub struct MacOsHarness {
    config: ComputerUseConfig,
}

impl MacOsHarness {
    pub fn new(config: ComputerUseConfig) -> Self {
        Self { config }
    }
}

#[async_trait]
impl ComputerHarness for MacOsHarness {
    fn check_permissions(&self) -> Result<(), String> {
        // Accessibility — needed for the AX tree walk and AX/enigo input.
        if !is_process_trusted() {
            // On the first failed check, ask macOS to show the grant dialog —
            // this also registers aidaemon in the Accessibility pane so the user
            // can toggle it on instead of hunting for it with the "+" button.
            static AX_PROMPTED: AtomicBool = AtomicBool::new(false);
            if !AX_PROMPTED.swap(true, Ordering::SeqCst) {
                let _ = is_process_trusted_with_prompt();
            }
            return Err(ACCESSIBILITY_HELP.to_string());
        }
        // Screen Recording — needed for window capture. Check it explicitly so
        // the model gets an accurate, actionable error instead of a downstream
        // "no capturable window" from the capture backend.
        // SAFETY: both are simple C predicates with no arguments.
        if !unsafe { CGPreflightScreenCaptureAccess() } {
            static SCREEN_PROMPTED: AtomicBool = AtomicBool::new(false);
            if !SCREEN_PROMPTED.swap(true, Ordering::SeqCst) {
                // Triggers the system prompt and registers aidaemon in the
                // Screen Recording pane. The grant only applies after restart.
                unsafe { CGRequestScreenCaptureAccess() };
            }
            return Err(SCREEN_RECORDING_HELP.to_string());
        }
        Ok(())
    }

    async fn list_apps(&self) -> Result<Vec<AppInfo>, String> {
        self.check_permissions()?;
        list_running_apps()
    }

    async fn get_app_state(
        &self,
        app: &str,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<AppSnapshot, String> {
        self.check_permissions()?;
        let resolved = resolve_app(app)?;
        if is_prohibited_bundle(&resolved.bundle_id) {
            return Err(format!(
                "App '{}' ({}) is blocked by computer_use policy",
                resolved.name, resolved.bundle_id
            ));
        }
        capture_app(resolved, &self.config, cache, ctx)
    }

    async fn activate_app(
        &self,
        app: &str,
        generation: Option<u64>,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<AppSnapshot, String> {
        let resolved = resolve_app(app)?;
        let key = snapshot_key(resolved.bundle_id.clone(), ctx);
        if let Some(generation) = generation {
            cache.validate_generation(&key, generation)?;
        }
        activate_app(&resolved)?;
        capture_app(resolved, &self.config, cache, ctx)
    }

    async fn click(
        &self,
        app: &str,
        generation: u64,
        element_index: Option<u32>,
        x: Option<f64>,
        y: Option<f64>,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<(AppSnapshot, Option<u32>, &'static str), String> {
        let resolved = resolve_app(app)?;
        let key = snapshot_key(resolved.bundle_id.clone(), ctx);
        cache.validate_generation(&key, generation)?;

        if let Some(index) = element_index {
            let element = cache.element_by_index(&key, generation, index)?.clone();
            // Prefer an AX press: it activates the control directly without
            // moving the real cursor or requiring the app to be frontmost, so a
            // GUI task works even while the user is looking at another window.
            // Only fall back to a synthetic cursor click (which needs the app in
            // the foreground) if the control can't be AX-pressed.
            if press_element_via_ax(resolved.pid, index, &self.config)? {
                let refreshed = capture_app(resolved, &self.config, cache, ctx)?;
                return Ok((refreshed, Some(index), "ax_press"));
            }
            verify_foreground(&resolved)?;
            click_element(&element)?;
            let refreshed = capture_app(resolved, &self.config, cache, ctx)?;
            return Ok((refreshed, Some(index), "cursor"));
        }

        // Raw coordinate clicks can only go through the synthetic cursor, which
        // requires the target app to be frontmost.
        let (px, py) = match (x, y) {
            (Some(x), Some(y)) => (x, y),
            _ => return Err("click requires element_index or both x and y coordinates".to_string()),
        };
        verify_foreground(&resolved)?;
        click_global_point(px, py)?;
        Ok((
            capture_app(resolved, &self.config, cache, ctx)?,
            None,
            "coordinate",
        ))
    }

    async fn type_text(
        &self,
        app: &str,
        generation: u64,
        text: &str,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<AppSnapshot, String> {
        let resolved = resolve_app(app)?;
        let key = snapshot_key(resolved.bundle_id.clone(), ctx);
        cache.validate_generation(&key, generation)?;
        verify_foreground(&resolved)?;
        let mut enigo = Enigo::new(&Settings::default()).map_err(|e| e.to_string())?;
        enigo
            .text(text)
            .map_err(|e| format!("Failed to type text: {e}"))?;
        capture_app(resolved, &self.config, cache, ctx)
    }

    async fn press_key(
        &self,
        app: &str,
        generation: u64,
        key: &str,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<AppSnapshot, String> {
        let resolved = resolve_app(app)?;
        let key_id = snapshot_key(resolved.bundle_id.clone(), ctx);
        cache.validate_generation(&key_id, generation)?;
        verify_foreground(&resolved)?;
        press_key_combo(key)?;
        capture_app(resolved, &self.config, cache, ctx)
    }

    async fn scroll(
        &self,
        app: &str,
        generation: u64,
        element_index: u32,
        direction: &str,
        pages: f64,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<(AppSnapshot, u32), String> {
        let resolved = resolve_app(app)?;
        let key = snapshot_key(resolved.bundle_id.clone(), ctx);
        let _element = cache.element_by_index(&key, generation, element_index)?;
        verify_foreground(&resolved)?;
        scroll_direction(direction, pages)?;
        Ok((
            capture_app(resolved, &self.config, cache, ctx)?,
            element_index,
        ))
    }

    async fn set_value(
        &self,
        app: &str,
        generation: u64,
        element_index: u32,
        value: &str,
        ctx: &HarnessRequestContext,
        cache: &mut SnapshotCache,
    ) -> Result<(AppSnapshot, u32), String> {
        let resolved = resolve_app(app)?;
        let key = snapshot_key(resolved.bundle_id.clone(), ctx);
        let element = cache
            .element_by_index(&key, generation, element_index)?
            .clone();
        verify_foreground(&resolved)?;
        click_element(&element)?;
        let mut enigo = Enigo::new(&Settings::default()).map_err(|e| e.to_string())?;
        enigo.text(value).map_err(|e| e.to_string())?;
        Ok((
            capture_app(resolved, &self.config, cache, ctx)?,
            element_index,
        ))
    }
}

fn snapshot_key(bundle_id: String, ctx: &HarnessRequestContext) -> SnapshotKey {
    SnapshotKey {
        task_id: ctx.task_id.clone(),
        session_id: ctx.session_id.clone(),
        bundle_id,
    }
}

fn capture_app(
    app: AppInfo,
    config: &ComputerUseConfig,
    cache: &mut SnapshotCache,
    ctx: &HarnessRequestContext,
) -> Result<AppSnapshot, String> {
    let app_element = AXUIElement::from_pid(app.pid)
        .ok_or_else(|| format!("No AX element for pid {}", app.pid))?;
    let window = focused_or_main_window(&app_element)?;
    let window_title =
        optional_string_attr(&window, AX_TITLE_ATTRIBUTE).unwrap_or_else(|| app.name.clone());
    let limits = AxWalkLimits::from_config(config);
    let (elements, truncated) = walk_tree(&window, limits);
    let png = capture_window_png(app.pid, &app.name, config)?;
    let snapshot = AppSnapshot {
        generation: 0,
        bundle_id: app.bundle_id,
        app_name: app.name,
        pid: app.pid,
        window_id: 1,
        window_title,
        elements,
        truncated,
        png,
    };
    let key = snapshot_key(snapshot.bundle_id.clone(), ctx);
    Ok(cache.store(key, snapshot))
}

fn list_running_apps() -> Result<Vec<AppInfo>, String> {
    // System Events' process list can mutate while AppleScript iterates it (an
    // app launches or quits mid-loop), which throws a transient
    // "Invalid index" error. Snapshot the process list into a local variable
    // first, wrap each process's property reads in `try` so one stale entry
    // can't abort the whole enumeration, and retry the whole call a few times.
    const SCRIPT: &str = r#"
set output to ""
tell application "System Events"
  set procList to (every application process whose background only is false)
  repeat with proc in procList
    try
      set procName to name of proc
      set procPid to unix id of proc
      set procBundle to ""
      try
        set procBundle to bundle identifier of proc
      end try
      set output to output & procName & tab & procPid & tab & procBundle & linefeed
    end try
  end repeat
end tell
return output
"#;
    let mut last_err = String::new();
    let mut stdout = String::new();
    for attempt in 0..3 {
        let out = Command::new("/usr/bin/osascript")
            .arg("-e")
            .arg(SCRIPT)
            .output()
            .map_err(|e| format!("Failed to list apps: {e}"))?;
        if out.status.success() {
            stdout = String::from_utf8_lossy(&out.stdout).into_owned();
            last_err.clear();
            break;
        }
        last_err = String::from_utf8_lossy(&out.stderr).trim().to_string();
        // Brief backoff lets the process table settle before retrying.
        if attempt < 2 {
            std::thread::sleep(std::time::Duration::from_millis(150));
        }
    }
    if !last_err.is_empty() {
        return Err(format!("Failed to list apps: {last_err}"));
    }
    let mut apps = Vec::new();
    for line in stdout.lines() {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() < 2 {
            continue;
        }
        let name = parts[0].trim();
        let pid: i32 = parts[1].trim().parse().unwrap_or(-1);
        if pid <= 0 || name.is_empty() {
            continue;
        }
        let bundle_id = parts.get(2).copied().unwrap_or("").trim();
        let bundle_id = if bundle_id.is_empty() {
            bundle_id_for_pid(pid).unwrap_or_default()
        } else {
            bundle_id.to_string()
        };
        apps.push(AppInfo {
            name: name.to_string(),
            bundle_id,
            pid,
        });
    }
    apps.sort_by(|a, b| {
        a.name
            .to_ascii_lowercase()
            .cmp(&b.name.to_ascii_lowercase())
    });
    apps.dedup_by(|a, b| a.pid == b.pid);
    Ok(apps)
}

fn resolve_app(app: &str) -> Result<AppInfo, String> {
    let apps = list_running_apps()?;
    let needle = app.trim();
    if let Some(found) = apps
        .iter()
        .find(|a| a.bundle_id.eq_ignore_ascii_case(needle) || a.name.eq_ignore_ascii_case(needle))
    {
        return Ok(found.clone());
    }
    if let Some(found) = apps.iter().find(|a| {
        a.name
            .to_ascii_lowercase()
            .contains(&needle.to_ascii_lowercase())
    }) {
        return Ok(found.clone());
    }
    Err(format!("No running app matching '{app}'"))
}

fn bundle_id_for_pid(pid: i32) -> Option<String> {
    let script = format!(
        r#"tell application "System Events" to get bundle identifier of first application process whose unix id is {pid}"#
    );
    let out = Command::new("/usr/bin/osascript")
        .arg("-e")
        .arg(script)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!value.is_empty()).then_some(value)
}

fn focused_or_main_window(app: &AXUIElement) -> Result<AXUIElement, String> {
    let windows = windows_for_app(app)?;
    for window in &windows {
        if optional_bool_attr(window, AX_FOCUSED_ATTRIBUTE).unwrap_or(false)
            || optional_bool_attr(window, AX_MAIN_ATTRIBUTE).unwrap_or(false)
        {
            return Ok(window.clone());
        }
    }
    windows
        .into_iter()
        .next()
        .ok_or_else(|| "No accessible window found for app".to_string())
}

fn windows_for_app(app: &AXUIElement) -> Result<Vec<AXUIElement>, String> {
    let value = app
        .attribute(AX_WINDOWS_ATTRIBUTE)
        .map_err(|e| e.to_string())?;
    let Some(value) = value else {
        return Ok(Vec::new());
    };
    let Some(items) = value.as_array() else {
        return Ok(Vec::new());
    };
    Ok(items.iter().filter_map(|item| item.as_element()).collect())
}

struct WalkState {
    next_index: u32,
    nodes: u32,
    truncated: bool,
    started: Instant,
    limits: AxWalkLimits,
    elements: Vec<IndexedElement>,
    max_depth_seen: u32,
}

fn walk_tree(root: &AXUIElement, limits: AxWalkLimits) -> (Vec<IndexedElement>, bool) {
    let mut state = WalkState {
        // Incremented before assignment, so the first interactive element is 1.
        next_index: 0,
        nodes: 0,
        truncated: false,
        started: Instant::now(),
        limits,
        elements: Vec::new(),
        max_depth_seen: 0,
    };
    walk_node(root, 0, &mut state);
    if state.truncated && state.elements.is_empty() {
        // No interactive controls before the limit. The root role distinguishes
        // the real failure modes: a degraded/no-access tree shows the app
        // recursing into itself ("AXWindow" never appears), whereas a genuinely
        // deep app needs a higher depth/node budget.
        let root_role = optional_string_attr(root, AX_ROLE_ATTRIBUTE).unwrap_or_default();
        tracing::warn!(
            nodes = state.nodes,
            max_depth_seen = state.max_depth_seen,
            root_role,
            "computer_use AX walk truncated with no elements (check Accessibility permission / app depth)"
        );
    }
    (state.elements, state.truncated)
}

fn walk_node(element: &AXUIElement, depth: u32, state: &mut WalkState) {
    state.max_depth_seen = state.max_depth_seen.max(depth);
    if state.started.elapsed() > state.limits.max_duration
        || state.nodes >= state.limits.max_nodes
        || depth > state.limits.max_depth
    {
        state.truncated = true;
        return;
    }

    let role = optional_string_attr(element, AX_ROLE_ATTRIBUTE).unwrap_or_default();
    let title = pick_label(element);
    let enabled = optional_bool_attr(element, AX_ENABLED_ATTRIBUTE).unwrap_or(true);
    let subrole = optional_string_attr(element, AX_SUBROLE_ATTRIBUTE);
    let bounds = element_bounds(element);

    let interactive = is_interactive_role(&role);
    let context = !title.is_empty() && is_context_role(&role);
    if interactive || context {
        // Only interactive elements get a stable number the model can target;
        // context labels/value displays carry index 0 so they never shift the
        // button numbering when they appear/disappear (e.g. a result display).
        let index = if interactive {
            state.next_index = state.next_index.saturating_add(1);
            state.next_index
        } else {
            0
        };
        state.elements.push(IndexedElement {
            index,
            role,
            title,
            enabled,
            bounds,
            subrole,
            interactive,
        });
        state.nodes = state.nodes.saturating_add(1);
    }

    let children = match element.children() {
        Ok(children) => collapse_passthrough(element, children),
        Err(_) => return,
    };
    for child in children {
        walk_node(&child, depth.saturating_add(1), state);
        if state.truncated {
            return;
        }
    }
}

fn collapse_passthrough(parent: &AXUIElement, children: Vec<AXUIElement>) -> Vec<AXUIElement> {
    if children.len() != 1 {
        return children;
    }
    let role = optional_string_attr(parent, AX_ROLE_ATTRIBUTE).unwrap_or_default();
    // Use the *structural* label (title/description only, NOT AXValue): a wrapper
    // group that merely carries a value is still structurally empty and should be
    // collapsed, otherwise value-bearing groups exhaust the depth budget before
    // the real controls are reached.
    let title = structural_label(parent);
    if title.is_empty() && role.contains("Group") {
        if let Ok(grandchildren) = children[0].children() {
            return collapse_passthrough(&children[0], grandchildren);
        }
    }
    children
}

fn is_interactive_role(role: &str) -> bool {
    matches!(
        role,
        "AXButton"
            | "AXCheckBox"
            | "AXRadioButton"
            | "AXPopUpButton"
            | "AXMenuItem"
            | "AXTextField"
            | "AXTextArea"
            | "AXSlider"
            | "AXIncrementor"
            | "AXLink"
            | "AXComboBox"
            | "AXCell"
    ) || role.ends_with("Button")
}

fn is_context_role(role: &str) -> bool {
    role.contains("StaticText") || role.contains("Heading") || role.contains("Label")
}

fn pick_label(element: &AXUIElement) -> String {
    // Fall back to AXValue last so value-bearing displays (e.g. a calculator's
    // result field, a read-only text label) surface their content — these often
    // have an empty title/description but a meaningful value the model needs to
    // read back the outcome of an action.
    if let Some(label) = structural_label_opt(element) {
        return label;
    }
    optional_string_attr(element, AX_VALUE_ATTRIBUTE).unwrap_or_default()
}

/// Title/description label only (no AXValue). Used where a value must not count
/// as a meaningful label — notably passthrough-group collapsing.
fn structural_label(element: &AXUIElement) -> String {
    structural_label_opt(element).unwrap_or_default()
}

fn structural_label_opt(element: &AXUIElement) -> Option<String> {
    for attr in [AX_TITLE_ATTRIBUTE, AX_DESCRIPTION_ATTRIBUTE] {
        if let Some(value) = optional_string_attr(element, attr) {
            if !value.is_empty() {
                return Some(value);
            }
        }
    }
    None
}

fn optional_string_attr(element: &AXUIElement, name: &str) -> Option<String> {
    element.attribute(name).ok()?.and_then(|v| v.as_string())
}

fn optional_bool_attr(element: &AXUIElement, name: &str) -> Option<bool> {
    element.attribute(name).ok()?.and_then(|v| v.as_bool())
}

fn element_bounds(element: &AXUIElement) -> Option<ElementBounds> {
    let pos = element
        .attribute(AX_POSITION_ATTRIBUTE)
        .ok()?
        .and_then(|v| v.as_point())?;
    let size = element
        .attribute(AX_SIZE_ATTRIBUTE)
        .ok()?
        .and_then(|v| v.as_size())?;
    Some(ElementBounds {
        x: pos.x,
        y: pos.y,
        width: size.width,
        height: size.height,
    })
}

fn capture_window_png(
    pid: i32,
    app_name: &str,
    config: &ComputerUseConfig,
) -> Result<Vec<u8>, String> {
    let windows = Window::all().map_err(|e| e.to_string())?;
    let window = windows
        .into_iter()
        .find(|w| {
            w.pid().ok() == Some(pid as u32) || w.app_name().ok().as_deref() == Some(app_name)
        })
        .ok_or_else(|| format!("No capturable window for {app_name}"))?;
    let image = window.capture_image().map_err(|e| e.to_string())?;
    encode_png(resize_image(image, config)?, config)
}

fn resize_image(image: RgbaImage, config: &ComputerUseConfig) -> Result<RgbaImage, String> {
    let (w, h) = (image.width(), image.height());
    let max_w = config.screenshot_max_width.max(1);
    let max_h = config.screenshot_max_height.max(1);
    if w <= max_w && h <= max_h {
        return Ok(image);
    }
    let scale = (max_w as f32 / w as f32).min(max_h as f32 / h as f32);
    let nw = ((w as f32 * scale).round() as u32).max(1);
    let nh = ((h as f32 * scale).round() as u32).max(1);
    Ok(xcap::image::imageops::resize(
        &image,
        nw,
        nh,
        FilterType::Triangle,
    ))
}

fn encode_png(image: RgbaImage, config: &ComputerUseConfig) -> Result<Vec<u8>, String> {
    let mut buf = Vec::new();
    let mut cursor = std::io::Cursor::new(&mut buf);
    image
        .write_to(&mut cursor, xcap::image::ImageFormat::Png)
        .map_err(|e| e.to_string())?;
    if buf.len() as u64 > config.screenshot_max_bytes {
        return Err(format!(
            "Screenshot exceeds screenshot_max_bytes ({})",
            config.screenshot_max_bytes
        ));
    }
    Ok(buf)
}

fn verify_foreground(app: &AppInfo) -> Result<(), String> {
    let system = axuielement::system_wide()
        .ok_or_else(|| "AX system-wide element unavailable".to_string())?;
    let focused_app = system
        .focused_application()
        .map_err(|e| e.to_string())?
        .ok_or_else(|| "No focused application".to_string())?;
    let focused_pid = focused_app.pid().map_err(|e| e.to_string())?;
    if focused_pid != app.pid {
        return Err(format!(
            "Foreground target mismatch — expected {} (pid {}). Activate the app first.",
            app.name, app.pid
        ));
    }
    Ok(())
}

fn activate_app(app: &AppInfo) -> Result<(), String> {
    // Activate by PID, not by name: the name could legitimately contain quotes
    // or other AppleScript metacharacters, so interpolating it into a script is
    // an injection risk. A PID is an integer with no escaping concerns.
    let script = format!(
        r#"tell application "System Events" to set frontmost of (first process whose unix id is {}) to true"#,
        app.pid
    );
    let out = Command::new("/usr/bin/osascript")
        .arg("-e")
        .arg(script)
        .output()
        .map_err(|e| e.to_string())?;
    if out.status.success() {
        Ok(())
    } else {
        Err(format!(
            "Failed to activate app '{}': {}",
            app.name,
            String::from_utf8_lossy(&out.stderr)
        ))
    }
}

/// Try to activate the `target_index`-th interactive control via an AX press
/// (no cursor movement, no foreground requirement). Returns `Ok(true)` if the
/// control was pressed, `Ok(false)` if it can't be found or doesn't support a
/// press (caller falls back to a synthetic cursor click).
fn press_element_via_ax(
    pid: i32,
    target_index: u32,
    config: &ComputerUseConfig,
) -> Result<bool, String> {
    let app_element =
        AXUIElement::from_pid(pid).ok_or_else(|| format!("No AX element for pid {pid}"))?;
    let window = focused_or_main_window(&app_element)?;
    let limits = AxWalkLimits::from_config(config);
    let started = Instant::now();
    let mut counter = 0u32;
    let Some(live) =
        find_live_interactive(&window, 0, &limits, &started, &mut counter, target_index)
    else {
        return Ok(false);
    };
    Ok(live.perform_action(AX_PRESS_ACTION).is_ok())
}

/// Re-resolve the live `AXUIElement` for the `target`-th interactive control,
/// numbered identically to the snapshot walk (only interactive roles counted,
/// same depth-first order and passthrough collapsing).
fn find_live_interactive(
    element: &AXUIElement,
    depth: u32,
    limits: &AxWalkLimits,
    started: &Instant,
    counter: &mut u32,
    target: u32,
) -> Option<AXUIElement> {
    if started.elapsed() > limits.max_duration || depth > limits.max_depth {
        return None;
    }
    let role = optional_string_attr(element, AX_ROLE_ATTRIBUTE).unwrap_or_default();
    if is_interactive_role(&role) {
        *counter = counter.saturating_add(1);
        if *counter == target {
            return Some(element.clone());
        }
    }
    let children = match element.children() {
        Ok(children) => collapse_passthrough(element, children),
        Err(_) => return None,
    };
    for child in children {
        if let Some(found) = find_live_interactive(
            &child,
            depth.saturating_add(1),
            limits,
            started,
            counter,
            target,
        ) {
            return Some(found);
        }
    }
    None
}

fn click_element(element: &IndexedElement) -> Result<(), String> {
    let bounds = element
        .bounds
        .ok_or_else(|| format!("Element {} has no bounds for click", element.index))?;
    let cx = bounds.x + bounds.width / 2.0;
    let cy = bounds.y + bounds.height / 2.0;
    click_global_point(cx, cy)
}

fn click_global_point(x: f64, y: f64) -> Result<(), String> {
    let target_x = x.round() as i32;
    let target_y = y.round() as i32;
    let mut enigo = Enigo::new(&Settings::default()).map_err(|e| e.to_string())?;
    enigo
        .move_mouse(target_x, target_y, Coordinate::Abs)
        .map_err(|e| e.to_string())?;
    if let Ok((cursor_x, cursor_y)) = read_mouse_position() {
        const CURSOR_TOLERANCE: i32 = 8;
        if (cursor_x - target_x).abs() > CURSOR_TOLERANCE
            || (cursor_y - target_y).abs() > CURSOR_TOLERANCE
        {
            return Err(
                "Cursor moved after positioning — aborting click to avoid hitting an unintended target"
                    .to_string(),
            );
        }
    }
    enigo
        .button(Button::Left, Direction::Click)
        .map_err(|e| e.to_string())?;
    Ok(())
}

fn read_mouse_position() -> Result<(i32, i32), String> {
    let output = Command::new("swift")
        .args([
            "-e",
            r#"import Cocoa
let p = NSEvent.mouseLocation
let screen = NSScreen.screens?.first?.frame.height ?? 0
print("\(Int(p.x)),\(Int(screen - p.y))")"#,
        ])
        .output()
        .map_err(|e| e.to_string())?;
    if !output.status.success() {
        return Err(String::from_utf8_lossy(&output.stderr).to_string());
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let mut parts = text.trim().split(',');
    let x: i32 = parts
        .next()
        .ok_or_else(|| "missing cursor x".to_string())?
        .trim()
        .parse()
        .map_err(|e| format!("invalid cursor x: {e}"))?;
    let y: i32 = parts
        .next()
        .ok_or_else(|| "missing cursor y".to_string())?
        .trim()
        .parse()
        .map_err(|e| format!("invalid cursor y: {e}"))?;
    Ok((x, y))
}

fn press_key_combo(raw: &str) -> Result<(), String> {
    let mut enigo = Enigo::new(&Settings::default()).map_err(|e| e.to_string())?;
    for part in raw.split('+').map(str::trim).filter(|s| !s.is_empty()) {
        let key = match part.to_ascii_lowercase().as_str() {
            "return" | "enter" => Key::Return,
            "tab" => Key::Tab,
            "escape" | "esc" => Key::Escape,
            "command" | "cmd" => Key::Meta,
            "shift" => Key::Shift,
            "control" | "ctrl" => Key::Control,
            "option" | "alt" => Key::Alt,
            other if other.len() == 1 => Key::Unicode(other.chars().next().unwrap()),
            other => return Err(format!("Unsupported key token '{other}'")),
        };
        enigo
            .key(key, Direction::Click)
            .map_err(|e| e.to_string())?;
    }
    Ok(())
}

fn scroll_direction(direction: &str, pages: f64) -> Result<(), String> {
    let mut enigo = Enigo::new(&Settings::default()).map_err(|e| e.to_string())?;
    let amount = (pages.abs() * 120.0).round() as i32;
    let delta = match direction.to_ascii_lowercase().as_str() {
        "up" => amount,
        "down" => -amount,
        "left" => amount,
        "right" => -amount,
        other => return Err(format!("Invalid scroll direction '{other}'")),
    };
    enigo
        .scroll(delta, enigo::Axis::Vertical)
        .map_err(|e| e.to_string())?;
    Ok(())
}