actl-core 0.1.7

Protocol layer: JSON envelope, error codes, ref semantics (platform-free)
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
//! Task consent is volatile: restart, external input, or expiry revokes it.
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Approval {
    #[default]
    Expiring,
    OncePerRun,
}
/// 误触自动恢复(pardon):授权被外部输入撤销后,若撤销源与后续输入均为
/// "良性"(纯鼠标移动,无任何按键/点击/滚轮),静默窗内无新输入且前台未变,
/// 显示端可自动重新授权,预算内不需要用户点击。任何键盘事件永久不赦免。
/// 流程可在 handoff.pardon_input 覆盖全局默认(逐流程优先)。
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct PardonPolicy {
    pub enabled: bool,
    /// 静默窗:最后一次外部输入后需安静的毫秒数(1000..=10000)。
    pub quiet_ms: u64,
    /// 每任务自动恢复次数(1..=5);耗尽后回到显式确认。
    pub budget: u32,
    /// 恢复前要求前台窗口与出卡时一致。
    pub require_foreground: bool,
    /// 仅当待执行动作非键盘通道时赦免(type/press 等注入键盘的动作永不自动恢复)。
    pub keyboard_safe_only: bool,
}
impl Default for PardonPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            quiet_ms: 4000,
            budget: 2,
            require_foreground: true,
            keyboard_safe_only: true,
        }
    }
}
impl PardonPolicy {
    pub fn valid(&self) -> bool {
        (1000..=10000).contains(&self.quiet_ms) && (1..=5).contains(&self.budget)
    }
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PardonInputs {
    pub now_ms: u64,
    /// 撤销授权的那次输入是否为按键/点击/滚轮(硬输入)。
    pub revoker_hard: bool,
    /// 最后一次外部输入时间;无输入则 None。
    pub last_input_ms: Option<u64>,
    /// 撤销之后是否出现过硬输入;有则永不赦免。
    pub hard_input_after_revoke: bool,
    /// 前台窗口与出卡时是否一致。
    pub foreground_same: bool,
    /// 待执行动作是否为键盘通道。
    pub keyboard_action: bool,
    pub budget_left: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PardonDecision {
    /// 条件满足,自动重新授权。
    Pardon,
    /// 条件未满足但可继续等待(静默窗未满等)。
    Wait,
    /// 结构性不满足:出卡等显式确认,本任务不再自动恢复。
    Never,
}
pub fn pardon_decision(inputs: PardonInputs, policy: &PardonPolicy) -> PardonDecision {
    if !policy.enabled || inputs.revoker_hard || inputs.hard_input_after_revoke {
        return PardonDecision::Never;
    }
    if policy.keyboard_safe_only && inputs.keyboard_action {
        return PardonDecision::Never;
    }
    if inputs.budget_left == 0 {
        return PardonDecision::Never;
    }
    if policy.require_foreground && !inputs.foreground_same {
        return PardonDecision::Never;
    }
    match inputs.last_input_ms {
        None => PardonDecision::Wait,
        Some(last) if inputs.now_ms.saturating_sub(last) < policy.quiet_ms => PardonDecision::Wait,
        Some(_) => PardonDecision::Pardon,
    }
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Policy {
    pub approval: Approval,
    #[serde(default, skip_serializing_if = "PardonPolicy::is_default")]
    pub pardon_input: PardonPolicy,
}
thread_local! { static POLICY: std::cell::Cell<Approval> = const { std::cell::Cell::new(Approval::Expiring) }; }
pub fn configure(policy: Approval) {
    POLICY.with(|p| p.set(policy));
}
pub fn configured() -> Approval {
    POLICY.with(|p| p.get())
}

pub const INPUT_TAG: usize = 0x4143544c;
pub const REQUEST_MESSAGE: u32 = 0x8000 + 46;
pub const CHECK_MESSAGE: u32 = 0x8000 + 47;
pub const RECOVER_MESSAGE: u32 = 0x8000 + 48;
pub const FOREGROUND_MESSAGE: u32 = 0x8000 + 51;
pub const PENDING: usize = 1;
pub const ALLOWED: usize = 2;
pub const DEFERRED: usize = 3;
pub const YIELDED: usize = 4;
pub const PANEL_UNAVAILABLE: usize = 5;
pub const MONITOR_UNAVAILABLE: usize = 6;
pub const USER_PAUSED: usize = 7;
pub const CANCELLED: usize = 8;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Request {
    pub approval: Approval,
    pub generation: String,
    pub call: String,
    pub task: String,
    pub target: String,
    pub ts_ms: u64,
    /// 动作种类(click/type/press…);旧执行器请求缺失时按未知处理。
    #[serde(default)]
    pub action: String,
}
impl Request {
    pub fn fresh(&self, now: u64) -> bool {
        self.ts_ms <= now
            && now - self.ts_ms < 2000
            && !self.call.is_empty()
            && !self.task.is_empty()
            && !self.generation.is_empty()
    }
}

#[derive(Default)]
pub struct Consent {
    grant: Option<(String, u64, u64, u64)>,
    approval: Approval,
    reason: Option<&'static str>,
}
/// 授权动作自身余韵的宽限窗:授权(点击"开始"或快捷键)后的物理输入在
/// 此窗内视为 settle(按键/鼠标抬起、手部余动),刷新基线而非撤销。
/// 没有它,严格相等判定会让授权点击自己的 mouse-up 必然杀死授权
/// (实测:human_takeover_or_grant_expired 于授权后第一次 check 即现)。
pub const GRACE_MS: u64 = 750;
impl Consent {
    /// Called only by the companion's explicit user Start/Continue action
    /// (button click or Ctrl+Alt+Y hotkey).
    pub fn allow(&mut self, task: &str, input_seq: u64, now: u64) {
        self.allow_with_policy(task, input_seq, now, Approval::Expiring);
    }
    pub fn allow_with_policy(&mut self, task: &str, input_seq: u64, now: u64, approval: Approval) {
        self.approval = approval;
        self.grant = Some((task.into(), input_seq, now, now));
        self.reason = Some("allowed");
    }
    pub fn revoke(&mut self) {
        self.revoke_with_reason("revoked");
    }
    pub fn revoke_with_reason(&mut self, reason: &'static str) {
        if self.grant.take().is_some() || self.reason.is_none() {
            self.reason = Some(reason);
        }
    }
    pub fn reason(&self) -> &'static str {
        self.reason.unwrap_or("no_grant")
    }
    pub fn check(&mut self, task: &str, input_seq: u64, now: u64) -> bool {
        let Some((owner, seq, started, touched)) = self.grant.as_mut() else {
            return false;
        };
        let expired = if now < *touched {
            Some("clock_reversed")
        } else if self.approval == Approval::Expiring && now - *started >= 600_000 {
            Some("duration_expired")
        } else if self.approval == Approval::Expiring && now - *touched >= 60_000 {
            Some("idle_expired")
        } else {
            None
        };
        if let Some(reason) = expired {
            self.revoke_with_reason(reason);
            return false;
        }
        if *seq != input_seq {
            if now - *started < GRACE_MS {
                // 宽限窗内:授权动作的余韵,重设基线继续放行
                *seq = input_seq;
            } else {
                self.revoke_with_reason("external_input");
                return false;
            }
        }
        if owner != task {
            self.reason = Some("different_task");
            return false;
        }
        *touched = now;
        true
    }
    pub fn check_policy(
        &mut self,
        task: &str,
        input_seq: u64,
        now: u64,
        approval: Approval,
    ) -> bool {
        if self.grant.is_some() && self.approval != approval {
            self.reason = Some("policy_changed");
            return false;
        }
        self.check(task, input_seq, now)
    }
}

/// Ignore only events tagged by this injector and marked injected by Windows.
pub fn external_input(injected: bool, tag: usize) -> bool {
    !injected || tag != INPUT_TAG
}

pub fn error(reason: &str) -> crate::CtlError {
    crate::CtlError::with_evidence(
        crate::ErrorCode::NotActionable,
        "desktop handoff required; user must choose Start/Continue in actl, then re-observe before retrying interrupted work",
        serde_json::json!({"stage":"handoff", "reason":reason, "retry_input":false}),
    )
}

pub fn foreground_error(expected: &str, actual: &str) -> crate::CtlError {
    crate::CtlError::with_evidence(
        crate::ErrorCode::NotActionable,
        "physical foreground does not match the target; re-observe the window before retrying",
        serde_json::json!({"stage":"foreground_verify", "reason":"foreground_mismatch", "expected":expected, "actual":actual}),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn injected_events_from_other_tools_still_yield() {
        assert!(!external_input(true, INPUT_TAG));
        assert!(external_input(false, INPUT_TAG));
        assert!(external_input(false, 0));
        assert!(external_input(true, 0));
    }
    #[test]
    fn foreground_mismatch_never_recommends_elevation() {
        let e = foreground_error("target", "");
        assert_eq!(e.code, crate::ErrorCode::NotActionable);
        assert!(!e.code.recovery_hint().contains("elevated"));
    }
    #[test]
    fn consent_is_explicit_and_task_scoped() {
        let mut c = Consent::default();
        assert!(!c.check("a", 10, 100));
        c.allow("a", 10, 100);
        assert!(c.check("a", 10, 101));
        assert!(!c.check("b", 10, 102));
        assert!(c.check("a", 10, 103));
    }
    #[test]
    fn same_field_input_revokes_even_without_focus_change() {
        let mut c = Consent::default();
        c.allow("a", 10, 10_000); // 宽限窗之外的时间原点
        assert!(!c.check("a", 11, 10_000 + GRACE_MS + 1));
        assert!(!c.check("a", 10, 10_000 + GRACE_MS + 2));
        c.allow("a", 12, 10_000 + GRACE_MS + 3);
        assert!(c.check("a", 12, 10_000 + GRACE_MS + 4));
    }

    #[test]
    fn grant_settle_grace_absorbs_then_goes_strict() {
        let mut c = Consent::default();
        c.allow("a", 10, 1_000);
        // 授权 mouse-up 与手部余动(宽限窗内):刷新基线,不撤销
        assert!(c.check("a", 12, 1_050));
        assert!(c.check("a", 15, 1_700));
        // 窗外的新输入 = 外部接管,撤销
        assert!(!c.check("a", 16, 1_000 + GRACE_MS + 5));
        // 撤销后不可复活
        assert!(!c.check("a", 16, 1_000 + GRACE_MS + 10));
    }

    #[test]
    fn grace_does_not_change_task_scope_or_expiry() {
        let mut c = Consent::default();
        c.allow("a", 10, 1_000);
        assert!(!c.check("b", 11, 1_100), "余韵不改任务归属");
        assert!(c.check("a", 11, 1_100));
        // idle/expiry 上限照旧
        assert!(!c.check("a", 11, 1_100 + 60_000));
    }
    #[test]
    fn expiry_restart_and_clock_reversal_fail_closed() {
        let mut c = Consent::default();
        c.allow("a", 0, 100);
        assert!(!c.check("a", 0, 60_100));
        c.allow("a", 0, 100);
        assert!(!c.check("a", 0, 99));
        c.allow("a", 0, 100);
        for t in (101..600_100).step_by(1000) {
            assert!(c.check("a", 0, t));
        }
        assert!(!c.check("a", 0, 600_100));
        assert!(!Consent::default().check("a", 0, 101));
    }

    fn inputs(now: u64, last: Option<u64>) -> PardonInputs {
        PardonInputs {
            now_ms: now,
            revoker_hard: false,
            last_input_ms: last,
            hard_input_after_revoke: false,
            foreground_same: true,
            keyboard_action: false,
            budget_left: 2,
        }
    }
    #[test]
    fn pardon_waits_for_quiet_then_recovers_within_budget() {
        let policy = PardonPolicy::default();
        assert_eq!(
            pardon_decision(inputs(10_000, Some(9_000)), &policy),
            PardonDecision::Wait
        );
        assert_eq!(
            pardon_decision(inputs(10_000, Some(10_000 - policy.quiet_ms)), &policy),
            PardonDecision::Pardon
        );
        let drained = PardonInputs {
            budget_left: 0,
            ..inputs(10_000, Some(0))
        };
        assert_eq!(pardon_decision(drained, &policy), PardonDecision::Never);
    }
    #[test]
    fn hard_input_keyboards_and_focus_change_never_pardon() {
        let policy = PardonPolicy::default();
        let hard_revoker = PardonInputs {
            revoker_hard: true,
            ..inputs(10_000, Some(0))
        };
        assert_eq!(
            pardon_decision(hard_revoker, &policy),
            PardonDecision::Never
        );
        let hard_after = PardonInputs {
            hard_input_after_revoke: true,
            ..inputs(10_000, Some(0))
        };
        assert_eq!(pardon_decision(hard_after, &policy), PardonDecision::Never);
        let typing = PardonInputs {
            keyboard_action: true,
            ..inputs(10_000, Some(0))
        };
        assert_eq!(pardon_decision(typing, &policy), PardonDecision::Never);
        let moved_focus = PardonInputs {
            foreground_same: false,
            ..inputs(10_000, Some(0))
        };
        assert_eq!(pardon_decision(moved_focus, &policy), PardonDecision::Never);
        let relaxed = PardonPolicy {
            require_foreground: false,
            keyboard_safe_only: false,
            ..policy
        };
        assert_eq!(
            pardon_decision(
                PardonInputs {
                    keyboard_action: true,
                    foreground_same: false,
                    ..inputs(10_000, Some(0))
                },
                &relaxed
            ),
            PardonDecision::Pardon
        );
    }
    #[test]
    fn disabled_policy_and_unknown_ranges_fail_closed() {
        assert!(
            !PardonPolicy {
                quiet_ms: 999,
                ..PardonPolicy::default()
            }
            .valid()
        );
        assert!(
            !PardonPolicy {
                budget: 0,
                ..PardonPolicy::default()
            }
            .valid()
        );
        let off = PardonPolicy {
            enabled: false,
            ..PardonPolicy::default()
        };
        assert_eq!(
            pardon_decision(inputs(10_000, Some(0)), &off),
            PardonDecision::Never
        );
        assert_eq!(
            serde_json::from_str::<Policy>("{\"approval\":\"once_per_run\"}").unwrap(),
            Policy {
                approval: Approval::OncePerRun,
                pardon_input: PardonPolicy::default()
            }
        );
    }
}