selfware 0.6.0

Your personal AI workshop — software you own, software that lasts
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
//! Keyboard control for desktop automation.
//!
//! Provides programmatic typing, key presses, and key combinations.
//! On Linux, uses xdotool for actual input. When running under WSL2 without
//! xdotool, falls back to PowerShell `SendKeys` via `powershell.exe`.
//! On other platforms, stubs with logging.

#[cfg(all(target_os = "linux", not(test)))]
use anyhow::Context;
use anyhow::{bail, Result};

use std::sync::OnceLock;
use tracing::{debug, warn};

use super::{is_blocked_combo, ActionRateLimiter, TypingProfile};

/// Backend used for keyboard input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KeyboardBackend {
    Xdotool,
    WindowsWsl,
}

impl KeyboardBackend {
    #[allow(dead_code)]
    pub(crate) fn doctor_name(self) -> &'static str {
        match self {
            Self::Xdotool => "xdotool",
            Self::WindowsWsl => "windows_wsl",
        }
    }

    #[allow(dead_code)]
    pub(crate) fn doctor_message(self) -> &'static str {
        match self {
            Self::Xdotool => "Keyboard control available via xdotool",
            Self::WindowsWsl => "Keyboard control available via Windows fallback (WSL)",
        }
    }
}

/// Detect the keyboard backend once and cache it.
fn detect_backend() -> Option<KeyboardBackend> {
    static BACKEND: OnceLock<Option<KeyboardBackend>> = OnceLock::new();
    *BACKEND.get_or_init(|| {
        if xdotool_available() {
            Some(KeyboardBackend::Xdotool)
        } else if can_use_wsl_powershell() {
            Some(KeyboardBackend::WindowsWsl)
        } else {
            None
        }
    })
}

fn xdotool_available() -> bool {
    std::process::Command::new("which")
        .arg("xdotool")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn can_use_wsl_powershell() -> bool {
    is_wsl_environment()
        && std::process::Command::new("powershell.exe")
            .args(["-NoProfile", "-Command", "Write-Output ok"])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
}

fn is_wsl_environment() -> bool {
    std::env::var_os("WSL_INTEROP").is_some()
        || std::env::var_os("WSL_DISTRO_NAME").is_some()
        || std::fs::read_to_string("/proc/sys/kernel/osrelease")
            .map(|r| r.to_ascii_lowercase().contains("microsoft"))
            .unwrap_or(false)
}

/// Return the available keyboard backend (public for doctor checks).
#[allow(dead_code)]
pub(crate) fn available_backend() -> Option<KeyboardBackend> {
    detect_backend()
}

/// Keyboard controller with rate limiting and typing profiles.
pub struct KeyboardController {
    rate_limiter: ActionRateLimiter,
    typing_profile: TypingProfile,
}

/// Map common key names to xdotool key names.
fn map_key_name(key: &str) -> &str {
    match key.to_lowercase().as_str() {
        "enter" | "return" => "Return",
        "tab" => "Tab",
        "escape" | "esc" => "Escape",
        "backspace" => "BackSpace",
        "delete" | "del" => "Delete",
        "space" => "space",
        "up" => "Up",
        "down" => "Down",
        "left" => "Left",
        "right" => "Right",
        "home" => "Home",
        "end" => "End",
        "pageup" | "page_up" => "Prior",
        "pagedown" | "page_down" => "Next",
        "insert" => "Insert",
        "f1" => "F1",
        "f2" => "F2",
        "f3" => "F3",
        "f4" => "F4",
        "f5" => "F5",
        "f6" => "F6",
        "f7" => "F7",
        "f8" => "F8",
        "f9" => "F9",
        "f10" => "F10",
        "f11" => "F11",
        "f12" => "F12",
        "shift" => "shift",
        "ctrl" | "control" => "ctrl",
        "alt" => "alt",
        "super" | "meta" | "cmd" | "command" => "super",
        _ => key,
    }
}

/// Build the xdotool key string for a combo like "ctrl+shift+t".
fn build_xdotool_combo(combo: &str) -> String {
    combo
        .split('+')
        .map(|part| map_key_name(part.trim()))
        .collect::<Vec<_>>()
        .join("+")
}

/// Build the command args for an xdotool invocation.
/// Returns (program, args) tuple for testability.
#[allow(dead_code)]
fn build_xdotool_type_cmd(text: &str) -> (&'static str, Vec<String>) {
    (
        "xdotool",
        vec![
            "type".to_string(),
            "--clearmodifiers".to_string(),
            "--".to_string(),
            text.to_string(),
        ],
    )
}

#[allow(dead_code)]
fn build_xdotool_key_cmd(key: &str) -> (&'static str, Vec<String>) {
    ("xdotool", vec!["key".to_string(), key.to_string()])
}

#[allow(dead_code)]
fn build_xdotool_keydown_cmd(key: &str) -> (&'static str, Vec<String>) {
    ("xdotool", vec!["keydown".to_string(), key.to_string()])
}

#[allow(dead_code)]
fn build_xdotool_keyup_cmd(key: &str) -> (&'static str, Vec<String>) {
    ("xdotool", vec!["keyup".to_string(), key.to_string()])
}

/// Map a key name to the PowerShell `SendKeys` notation.
#[allow(dead_code)]
fn map_key_to_sendkeys(key: &str) -> String {
    match key.to_lowercase().as_str() {
        "enter" | "return" => "{ENTER}".to_string(),
        "tab" => "{TAB}".to_string(),
        "escape" | "esc" => "{ESC}".to_string(),
        "backspace" => "{BACKSPACE}".to_string(),
        "delete" | "del" => "{DELETE}".to_string(),
        "space" => " ".to_string(),
        "up" => "{UP}".to_string(),
        "down" => "{DOWN}".to_string(),
        "left" => "{LEFT}".to_string(),
        "right" => "{RIGHT}".to_string(),
        "home" => "{HOME}".to_string(),
        "end" => "{END}".to_string(),
        "pageup" | "page_up" | "prior" => "{PGUP}".to_string(),
        "pagedown" | "page_down" | "next" => "{PGDN}".to_string(),
        "insert" => "{INSERT}".to_string(),
        "f1" => "{F1}".to_string(),
        "f2" => "{F2}".to_string(),
        "f3" => "{F3}".to_string(),
        "f4" => "{F4}".to_string(),
        "f5" => "{F5}".to_string(),
        "f6" => "{F6}".to_string(),
        "f7" => "{F7}".to_string(),
        "f8" => "{F8}".to_string(),
        "f9" => "{F9}".to_string(),
        "f10" => "{F10}".to_string(),
        "f11" => "{F11}".to_string(),
        "f12" => "{F12}".to_string(),
        // Single printable characters go through as-is but must be escaped
        // if they are special SendKeys characters.
        other => escape_sendkeys_char(other),
    }
}

/// Escape characters that have special meaning in SendKeys.
#[allow(dead_code)]
fn escape_sendkeys_char(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for ch in s.chars() {
        match ch {
            '+' | '^' | '%' | '~' | '(' | ')' | '{' | '}' | '[' | ']' => {
                out.push('{');
                out.push(ch);
                out.push('}');
            }
            _ => out.push(ch),
        }
    }
    out
}

/// Escape text for SendKeys (batch of printable characters).
#[allow(dead_code)]
fn escape_sendkeys_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 16);
    for ch in text.chars() {
        match ch {
            '+' | '^' | '%' | '~' | '(' | ')' | '{' | '}' | '[' | ']' => {
                out.push('{');
                out.push(ch);
                out.push('}');
            }
            '\n' => out.push_str("{ENTER}"),
            '\t' => out.push_str("{TAB}"),
            _ => out.push(ch),
        }
    }
    out
}

/// Build a PowerShell SendKeys combo string from "ctrl+shift+t" style input.
/// SendKeys modifiers: ^ = Ctrl, % = Alt, + = Shift.
#[allow(dead_code)]
fn build_sendkeys_combo(combo: &str) -> String {
    let mut prefix = String::new();
    let mut key_part = String::new();

    for part in combo.split('+') {
        let trimmed = part.trim();
        match trimmed.to_lowercase().as_str() {
            "ctrl" | "control" => prefix.push('^'),
            "alt" => prefix.push('%'),
            "shift" => prefix.push('+'),
            "super" | "meta" | "cmd" | "command" => prefix.push('^'), // best-effort: map super to ctrl on Windows
            _ => key_part = map_key_to_sendkeys(trimmed),
        }
    }

    format!("{}{}", prefix, key_part)
}

/// Run a PowerShell SendKeys command via powershell.exe.
#[cfg(all(target_os = "linux", not(test)))]
async fn run_powershell_sendkeys(sendkeys_sequence: &str) -> Result<()> {
    use tokio::process::Command;

    let script = format!(
        "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('{}')",
        sendkeys_sequence.replace('\'', "''")
    );

    let output = Command::new("powershell.exe")
        .args(["-NoProfile", "-Command", &script])
        .output()
        .await
        .context("Failed to execute powershell.exe for keyboard input")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "PowerShell SendKeys failed (exit {}): {}",
            output.status,
            stderr.trim()
        );
    }

    Ok(())
}

/// No-op PowerShell stub for tests.
#[cfg(all(target_os = "linux", test))]
async fn run_powershell_sendkeys(_sendkeys_sequence: &str) -> Result<()> {
    Ok(())
}

/// Execute an xdotool command. Returns error if xdotool is not available.
#[cfg(all(target_os = "linux", not(test)))]
async fn run_xdotool(args: &[String]) -> Result<()> {
    use tokio::process::Command;

    // If no input backend was detected, fail with a clear message instead of
    // shelling out to a missing xdotool binary (which produces a raw ENOENT).
    if detect_backend().is_none() {
        bail!(
            "no input backend available: install xdotool (Linux X11) or run \
             under a supported environment"
        );
    }

    let output = Command::new("xdotool")
        .args(args)
        .output()
        .await
        .context("Failed to execute xdotool. Is xdotool installed? (apt install xdotool)")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("xdotool failed (exit {}): {}", output.status, stderr.trim());
    }

    Ok(())
}

/// No-op xdotool stub for tests (avoids requiring xdotool in CI).
#[cfg(all(target_os = "linux", test))]
async fn run_xdotool(_args: &[String]) -> Result<()> {
    Ok(())
}

impl KeyboardController {
    pub fn new() -> Self {
        Self {
            rate_limiter: ActionRateLimiter::default(),
            typing_profile: TypingProfile::default(),
        }
    }

    pub fn with_typing_profile(mut self, profile: TypingProfile) -> Self {
        self.typing_profile = profile;
        self
    }

    /// Type a string character by character.
    pub async fn type_text(&self, text: &str) -> Result<()> {
        if !self.rate_limiter.check() {
            bail!("Keyboard action rate limit exceeded");
        }

        // Validate text length to prevent abuse
        if text.len() > 10_000 {
            bail!(
                "Text too long for keyboard typing ({} chars, max 10000)",
                text.len()
            );
        }

        debug!("Keyboard type: {} chars", text.len());

        #[cfg(target_os = "linux")]
        {
            if text.is_empty() {
                return Ok(());
            }

            let backend = detect_backend();

            if self.typing_profile.base_delay_ms > 0 {
                // Human-like typing: type char by char with delays
                for ch in text.chars() {
                    let delay = self.typing_profile.base_delay_ms;
                    let char_str = ch.to_string();
                    match backend {
                        Some(KeyboardBackend::Xdotool) | None => {
                            let (_, args) = build_xdotool_type_cmd(&char_str);
                            run_xdotool(&args).await?;
                        }
                        Some(KeyboardBackend::WindowsWsl) => {
                            let escaped = escape_sendkeys_text(&char_str);
                            run_powershell_sendkeys(&escaped).await?;
                        }
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                }
            } else {
                // Instant typing
                match backend {
                    Some(KeyboardBackend::Xdotool) | None => {
                        let (_, args) = build_xdotool_type_cmd(text);
                        run_xdotool(&args).await?;
                    }
                    Some(KeyboardBackend::WindowsWsl) => {
                        let escaped = escape_sendkeys_text(text);
                        run_powershell_sendkeys(&escaped).await?;
                    }
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            if !text.is_empty() {
                let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
                let script = format!(
                    "tell application \"System Events\" to keystroke \"{}\"",
                    escaped
                );
                let _ = tokio::process::Command::new("osascript")
                    .arg("-e")
                    .arg(&script)
                    .output()
                    .await;
            }
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            if self.typing_profile.base_delay_ms > 0 {
                for ch in text.chars() {
                    let delay = self.typing_profile.base_delay_ms;
                    tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                    debug!("Typed: '{}'", ch);
                }
            } else {
                debug!(
                    "Typed {} chars instantly (stub — no keyboard backend on this platform)",
                    text.len()
                );
            }
        }

        Ok(())
    }

    /// Press a single key.
    pub async fn press_key(&self, key: &str) -> Result<()> {
        if !self.rate_limiter.check() {
            bail!("Keyboard action rate limit exceeded");
        }

        let mapped = map_key_name(key);
        debug!("Key press: {} (mapped: {})", key, mapped);

        #[cfg(target_os = "linux")]
        {
            match detect_backend() {
                Some(KeyboardBackend::Xdotool) | None => {
                    let (_, args) = build_xdotool_key_cmd(mapped);
                    run_xdotool(&args).await?;
                }
                Some(KeyboardBackend::WindowsWsl) => {
                    let sendkeys = map_key_to_sendkeys(key);
                    run_powershell_sendkeys(&sendkeys).await?;
                }
            }
        }

        Ok(())
    }

    /// Execute a key combination (e.g., "ctrl+c", "cmd+v").
    pub async fn key_combo(&self, combo: &str) -> Result<()> {
        if !self.rate_limiter.check() {
            bail!("Keyboard action rate limit exceeded");
        }

        // Safety check for dangerous combos
        if is_blocked_combo(combo) {
            bail!(
                "Key combo '{}' is blocked for safety. Blocked combos cannot be executed.",
                combo
            );
        }

        let xdotool_combo = build_xdotool_combo(combo);
        debug!("Key combo: {} (xdotool: {})", combo, xdotool_combo);

        #[cfg(target_os = "linux")]
        {
            match detect_backend() {
                Some(KeyboardBackend::Xdotool) | None => {
                    let (_, args) = build_xdotool_key_cmd(&xdotool_combo);
                    run_xdotool(&args).await?;
                }
                Some(KeyboardBackend::WindowsWsl) => {
                    let sendkeys = build_sendkeys_combo(combo);
                    debug!("Key combo via SendKeys: {}", sendkeys);
                    run_powershell_sendkeys(&sendkeys).await?;
                }
            }
        }

        Ok(())
    }

    /// Press and hold a key.
    pub async fn key_down(&self, key: &str) -> Result<()> {
        if !self.rate_limiter.check() {
            bail!("Keyboard action rate limit exceeded");
        }

        let mapped = map_key_name(key);
        debug!("Key down: {} (mapped: {})", key, mapped);

        #[cfg(target_os = "linux")]
        {
            match detect_backend() {
                Some(KeyboardBackend::Xdotool) | None => {
                    let (_, args) = build_xdotool_keydown_cmd(mapped);
                    run_xdotool(&args).await?;
                }
                Some(KeyboardBackend::WindowsWsl) => {
                    // SendKeys does not support hold-down semantics; log a warning
                    // and send a single key press as best-effort.
                    warn!(
                        "key_down('{}') via WSL PowerShell has no hold semantics; \
                         sending a single key press instead",
                        key
                    );
                    let sendkeys = map_key_to_sendkeys(key);
                    run_powershell_sendkeys(&sendkeys).await?;
                }
            }
        }

        Ok(())
    }

    /// Release a held key.
    pub async fn key_up(&self, key: &str) -> Result<()> {
        if !self.rate_limiter.check() {
            bail!("Keyboard action rate limit exceeded");
        }

        let mapped = map_key_name(key);
        debug!("Key up: {} (mapped: {})", key, mapped);

        #[cfg(target_os = "linux")]
        {
            match detect_backend() {
                Some(KeyboardBackend::Xdotool) | None => {
                    let (_, args) = build_xdotool_keyup_cmd(mapped);
                    run_xdotool(&args).await?;
                }
                Some(KeyboardBackend::WindowsWsl) => {
                    // SendKeys does not support key-up; this is a no-op on WSL.
                    warn!(
                        "key_up('{}') via WSL PowerShell is a no-op (SendKeys has no hold semantics)",
                        key
                    );
                }
            }
        }

        Ok(())
    }
}

impl Default for KeyboardController {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[path = "../../tests/unit/computer/keyboard/keyboard_test.rs"]
mod tests;