rightkit-control 0.1.5

Background native input, accessibility reads, and a WebDriver bridge for driving real desktop apps without stealing focus.
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
//! EFF-001 effect admission: every effectful control request traverses one
//! authority, validate → (policy) → approval → execute → settle, and a denial
//! is final before any side effect.
//!
//! Contract (CodeRight `docs/canon/daemon-master-canon-atoms.md`, EFF-001):
//! effects "converge on one semantic validate → transform → normalize → policy
//! → approval → resource → execute → verify → settle authority"; acceptance:
//! "denied path never executes". Stage names and order mirror CodeRight's
//! `EffectAdmissionStage`. A surface may skip a stage that does not apply but
//! may never reorder them or reach `Execute` after a denial. This crate
//! traverses `Validate`, `Approval`, `Execute`, `Settle`; transform/normalize/
//! policy/resource/verify belong to the caller (its hook can implement policy).
//!
//! The executor is a closure handed to [`EffectGate::admit`]; it is only ever
//! invoked after the host's [`AdmissionHook`] returned
//! [`AdmissionDecision::Allow`] and the cancellation token was still clear.
use std::collections::VecDeque;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use crate::events::{emit, ControlEvent, EventSink};

/// EFF-001 admission stages in canonical order (identical to CodeRight's
/// `EffectAdmissionStage`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EffectAdmissionStage {
    Validate,
    Transform,
    Normalize,
    Policy,
    Approval,
    Resource,
    Execute,
    Verify,
    Settle,
}

impl EffectAdmissionStage {
    pub fn label(self) -> &'static str {
        match self {
            Self::Validate => "validate",
            Self::Transform => "transform",
            Self::Normalize => "normalize",
            Self::Policy => "policy",
            Self::Approval => "approval",
            Self::Resource => "resource",
            Self::Execute => "execute",
            Self::Verify => "verify",
            Self::Settle => "settle",
        }
    }
}

/// What kind of effect a request produces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EffectKind {
    /// Load a URL / move to another document.
    Navigate,
    /// Pointer, wheel, key or text input delivered to a target.
    Input,
    /// Semantic action on an element (AX press, select, focus).
    Action,
    /// Run script inside the target (e.g. webview `eval`).
    Script,
    /// Capture pixels/state to a file or buffer.
    Capture,
    /// Launch or terminate a process/window.
    Process,
    /// An app-registered typed command.
    Command,
}

impl EffectKind {
    pub fn label(self) -> &'static str {
        match self {
            Self::Navigate => "navigate",
            Self::Input => "input",
            Self::Action => "action",
            Self::Script => "script",
            Self::Capture => "capture",
            Self::Process => "process",
            Self::Command => "command",
        }
    }
}

/// A typed effect request presented to the admission hook.
///
/// `params` is the opaque request payload (usually JSON) so the hook can bind
/// its approval to the exact payload; it is never copied into events or
/// settlement records.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectRequest {
    /// Assigned by [`EffectGate::admit`]; any caller value is overwritten.
    pub id: u64,
    pub kind: EffectKind,
    /// Method / verb name, e.g. `click`, `type`, `eval`.
    pub method: String,
    /// Target identity, e.g. window label, `pid:1234`, element id.
    pub target: String,
    /// Opaque payload for payload-bound approval. Never emitted.
    pub params: String,
}

impl EffectRequest {
    pub fn new(kind: EffectKind, method: impl Into<String>, target: impl Into<String>) -> Self {
        Self {
            id: 0,
            kind,
            method: method.into(),
            target: target.into(),
            params: String::new(),
        }
    }
    pub fn with_params(mut self, params: impl Into<String>) -> Self {
        self.params = params.into();
        self
    }
}

/// Host decision at the approval stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdmissionDecision {
    Allow,
    Deny { reason: String },
}

impl AdmissionDecision {
    pub fn deny(reason: impl Into<String>) -> Self {
        Self::Deny {
            reason: reason.into(),
        }
    }
}

/// Host-supplied admission authority. Closures
/// `Fn(&EffectRequest) -> AdmissionDecision` implement it.
///
/// A panic in either method fails closed (the request is denied).
pub trait AdmissionHook: Send + Sync {
    /// Structural validation before approval. Default accepts.
    fn validate(&self, _request: &EffectRequest) -> Result<(), String> {
        Ok(())
    }
    /// Approve or deny. Called only after validation passed.
    fn approve(&self, request: &EffectRequest) -> AdmissionDecision;
}

impl<F> AdmissionHook for F
where
    F: Fn(&EffectRequest) -> AdmissionDecision + Send + Sync,
{
    fn approve(&self, request: &EffectRequest) -> AdmissionDecision {
        self(request)
    }
}

/// Explicit allow-all hook. This is what a host gets when it configures no
/// hook, preserving pre-0.1.1 behaviour while still settling every effect.
#[derive(Debug, Clone, Copy, Default)]
pub struct AllowAll;

impl AdmissionHook for AllowAll {
    fn approve(&self, _: &EffectRequest) -> AdmissionDecision {
        AdmissionDecision::Allow
    }
}

/// Cooperative cancellation shared between caller and executor.
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);

impl CancelToken {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn cancel(&self) {
        self.0.store(true, Ordering::SeqCst);
    }
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::SeqCst)
    }
}

/// Why an executor did not succeed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecError {
    Failed(String),
    /// The executor observed cancellation and stopped.
    Cancelled,
}

impl From<String> for ExecError {
    fn from(s: String) -> Self {
        Self::Failed(s)
    }
}
impl From<&str> for ExecError {
    fn from(s: &str) -> Self {
        Self::Failed(s.into())
    }
}

/// Terminal state recorded at the settle stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SettleOutcome {
    Ok,
    Denied,
    Failed,
    Cancelled,
}

impl SettleOutcome {
    pub fn label(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Denied => "denied",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }
}

/// Content-free settlement record (no params, no executor output).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settlement {
    pub id: u64,
    pub kind: EffectKind,
    pub method: String,
    pub target: String,
    pub outcome: SettleOutcome,
    /// Stages traversed, canonical order, always ending in `Settle`.
    pub stages: Vec<EffectAdmissionStage>,
    /// True iff the executor was invoked (false for every denial).
    pub executed: bool,
    /// True iff the executor panicked (outcome is then `Failed`).
    pub crashed: bool,
    /// Denial / failure reason. Hook- or executor-authored text.
    pub reason: Option<String>,
}

/// Result of [`EffectGate::admit`]: the settlement plus the executor's value
/// when the outcome is `Ok`.
#[derive(Debug)]
pub struct Effect<T> {
    pub settlement: Settlement,
    pub value: Option<T>,
}

impl<T> Effect<T> {
    pub fn is_ok(&self) -> bool {
        self.settlement.outcome == SettleOutcome::Ok
    }
    /// `Ok(value)` or `Err(reason)` with an outcome prefix (`denied: ...`).
    pub fn into_result(self) -> Result<T, String> {
        match self.value {
            Some(v) if self.settlement.outcome == SettleOutcome::Ok => Ok(v),
            _ => Err(format!(
                "{}: {}",
                self.settlement.outcome.label(),
                self.settlement.reason.unwrap_or_default()
            )),
        }
    }
}

/// Default number of settlements retained by [`EffectGate::settlements`].
pub const DEFAULT_JOURNAL_CAPACITY: usize = 1024;

/// The single admission authority for one control surface. Cheap to share
/// behind an `Arc`; `admit` is safe to call concurrently.
pub struct EffectGate {
    hook: Arc<dyn AdmissionHook>,
    events: Option<EventSink>,
    next_id: AtomicU64,
    journal: Mutex<VecDeque<Settlement>>,
    capacity: usize,
}

impl std::fmt::Debug for EffectGate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EffectGate")
            .field("next_id", &self.next_id.load(Ordering::SeqCst))
            .field("capacity", &self.capacity)
            .finish_non_exhaustive()
    }
}

impl Default for EffectGate {
    fn default() -> Self {
        Self::allow_all()
    }
}

impl EffectGate {
    pub fn new(hook: impl AdmissionHook + 'static) -> Self {
        Self::from_arc(Arc::new(hook))
    }
    pub fn from_arc(hook: Arc<dyn AdmissionHook>) -> Self {
        Self {
            hook,
            events: None,
            next_id: AtomicU64::new(1),
            journal: Mutex::new(VecDeque::new()),
            capacity: DEFAULT_JOURNAL_CAPACITY,
        }
    }
    /// Gate with [`AllowAll`]: still validates, settles and emits events.
    pub fn allow_all() -> Self {
        Self::new(AllowAll)
    }
    pub fn with_events(mut self, sink: EventSink) -> Self {
        self.events = Some(sink);
        self
    }
    /// Bound on retained settlements (oldest dropped first). `0` keeps none.
    pub fn with_journal_capacity(mut self, capacity: usize) -> Self {
        self.capacity = capacity;
        self
    }

    /// Snapshot of retained settlements, oldest first.
    pub fn settlements(&self) -> Vec<Settlement> {
        lock(&self.journal).iter().cloned().collect()
    }

    /// Run `request` through validate → approval → execute → settle.
    ///
    /// `execute` is invoked at most once, and only when validation and the
    /// hook both admit the request and `cancel` is not yet set. Every path
    /// settles exactly once (recorded and returned) and emits lifecycle
    /// events. Executor panics are contained and settled as `Failed`.
    pub fn admit<T>(
        &self,
        mut request: EffectRequest,
        cancel: &CancelToken,
        execute: impl FnOnce(&CancelToken) -> Result<T, ExecError>,
    ) -> Effect<T> {
        request.id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let mut stages = vec![EffectAdmissionStage::Validate];

        // Validate (crate structural checks, then the host's).
        let validated = if request.method.trim().is_empty() {
            Err("effect method is empty".to_string())
        } else {
            guarded(|| self.hook.validate(&request))
                .unwrap_or_else(|| Err("admission hook panicked during validate".into()))
        };
        if let Err(reason) = validated {
            return self.deny(request, stages, EffectAdmissionStage::Validate, reason);
        }

        // Approval.
        stages.push(EffectAdmissionStage::Approval);
        let decision = guarded(|| self.hook.approve(&request))
            .unwrap_or_else(|| AdmissionDecision::deny("admission hook panicked during approval"));
        if let AdmissionDecision::Deny { reason } = decision {
            return self.deny(request, stages, EffectAdmissionStage::Approval, reason);
        }

        // Cancelled after approval but before any side effect.
        if cancel.is_cancelled() {
            return self.settle(
                request,
                stages,
                SettleOutcome::Cancelled,
                false,
                false,
                Some("cancelled before execute".into()),
                None,
            );
        }

        // Execute.
        stages.push(EffectAdmissionStage::Execute);
        emit(
            &self.events,
            ControlEvent::EffectStarted {
                id: request.id,
                kind: request.kind,
                method: request.method.clone(),
            },
        );
        match catch_unwind(AssertUnwindSafe(|| execute(cancel))) {
            Ok(Ok(v)) => self.settle(
                request,
                stages,
                SettleOutcome::Ok,
                true,
                false,
                None,
                Some(v),
            ),
            Ok(Err(ExecError::Cancelled)) => self.settle(
                request,
                stages,
                SettleOutcome::Cancelled,
                true,
                false,
                Some("cancelled during execute".into()),
                None,
            ),
            Ok(Err(ExecError::Failed(reason))) => self.settle(
                request,
                stages,
                SettleOutcome::Failed,
                true,
                false,
                Some(reason),
                None,
            ),
            Err(panic) => {
                let reason = panic_text(&panic);
                self.settle(
                    request,
                    stages,
                    SettleOutcome::Failed,
                    true,
                    true,
                    Some(reason),
                    None,
                )
            }
        }
    }

    fn deny<T>(
        &self,
        request: EffectRequest,
        stages: Vec<EffectAdmissionStage>,
        stage: EffectAdmissionStage,
        reason: String,
    ) -> Effect<T> {
        self.settle_with(
            request,
            stages,
            SettleOutcome::Denied,
            false,
            false,
            Some(reason),
            None,
            Some(stage),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn settle<T>(
        &self,
        request: EffectRequest,
        stages: Vec<EffectAdmissionStage>,
        outcome: SettleOutcome,
        executed: bool,
        crashed: bool,
        reason: Option<String>,
        value: Option<T>,
    ) -> Effect<T> {
        self.settle_with(
            request, stages, outcome, executed, crashed, reason, value, None,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn settle_with<T>(
        &self,
        request: EffectRequest,
        mut stages: Vec<EffectAdmissionStage>,
        outcome: SettleOutcome,
        executed: bool,
        crashed: bool,
        reason: Option<String>,
        value: Option<T>,
        denied_at: Option<EffectAdmissionStage>,
    ) -> Effect<T> {
        stages.push(EffectAdmissionStage::Settle);
        let settlement = Settlement {
            id: request.id,
            kind: request.kind,
            method: request.method,
            target: request.target,
            outcome,
            stages,
            executed,
            crashed,
            reason,
        };
        if self.capacity > 0 {
            let mut j = lock(&self.journal);
            while j.len() >= self.capacity {
                j.pop_front();
            }
            j.push_back(settlement.clone());
        }
        let (id, kind, method) = (settlement.id, settlement.kind, settlement.method.clone());
        let event = match (denied_at, crashed) {
            (Some(stage), _) => ControlEvent::EffectDenied {
                id,
                kind,
                method,
                stage,
                reason: settlement.reason.clone().unwrap_or_default(),
            },
            (None, true) => ControlEvent::EffectCrashed { id, kind, method },
            (None, false) => ControlEvent::EffectStopped {
                id,
                kind,
                method,
                outcome,
                executed,
            },
        };
        emit(&self.events, event);
        Effect { settlement, value }
    }
}

fn guarded<R>(f: impl FnOnce() -> R) -> Option<R> {
    catch_unwind(AssertUnwindSafe(f)).ok()
}

fn panic_text(p: &Box<dyn std::any::Any + Send>) -> String {
    let msg = p
        .downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| p.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "non-string panic".into());
    format!("executor panicked: {msg}")
}

pub(crate) fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}