Skip to main content

adk_surface/
rules.rs

1//! What each surface may decide (spec 3.3 §7.2) and the rules on every surface (§7.4),
2//! enforced by the engine rather than left to renderers.
3//!
4//! | Surface (row) | Allow once | Always allow | Edit | Deny | High risk |
5//! |---|---|---|---|---|---|
6//! | Web home | Yes | Yes | Yes | Yes | Yes, after confirming it is you |
7//! | Terminal | Yes | Yes | Yes | Yes | Yes, on a paired local terminal |
8//! | Phone | Yes | Yes | Yes | Yes | Yes, after confirming it is you |
9//! | Desktop tray | Yes | No (opens the home) | No | Yes | No (opens the home) |
10//! | Chat | Yes, low and medium risk | No | No | Yes | No (links to the home) |
11//! | Voice | Yes, low and medium risk, with a cancel window | No | No | Yes | No |
12//!
13//! The row comes from how the input was given before the surface it arrived on: a spoken
14//! answer in the web home follows the voice row, a chat message the chat row, and an agent's
15//! request decides nothing at all (§7.4 rule 6). A call that spends money follows the
16//! high-risk column and is never allowed "always" (rule 4). The high-risk column is about
17//! approving: Deny stays on the tray and in voice for every decision, since saying no is
18//! always safe, and only chat, where a high-risk decision never resolves (S-I6), loses it. A
19//! call shown truncated cannot be approved until it was expanded (§7.1).
20//!
21//! A change on the person's screens (feature `verb-ui`, spec 3.3 §2 item 7) follows the same
22//! table: an agent's request is an ordinary decision, low risk, whose card never offers
23//! "always", and a person takes a screen action from the web home, the phone, a terminal or by
24//! voice, never from chat or the tray. No screen action answers a decision.
25//!
26//! Agent-drawn UI never decides (rule 5): a drawing with a decision's words or controls is
27//! refused before any surface shows it ([`genui::Validator`](crate::genui)), and a form's
28//! Send only asks for a call, which waits for the person whatever the agent's mode, standing
29//! rules or earlier approvals, on a card that never offers "Always allow".
30
31use adk_core::ApprovalAction;
32use schemars::JsonSchema;
33use serde::{Deserialize, Serialize};
34
35use crate::origin::{Caller, Origin, SurfaceKind};
36use crate::words;
37
38/// How long a spoken "allow once" waits before it takes effect, so the person can cancel it
39/// on screen (spec 3.3 §5.6, §7.2).
40pub const VOICE_CANCEL_WINDOW_SECS: u32 = 5;
41
42/// An answer to a decision (spec 3.3 §8.2).
43///
44/// # Example
45///
46/// ```rust
47/// use adk_surface::Answer;
48///
49/// assert_eq!(serde_json::to_value(Answer::AllowOnce).unwrap(), "allowOnce");
50/// ```
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
52#[serde(rename_all = "camelCase")]
53pub enum Answer {
54    /// Run this one call.
55    AllowOnce,
56    /// Run it and allow the same call from now on, scoped.
57    AlwaysAllow,
58    /// Change the arguments, then allow.
59    Edit,
60    /// Refuse.
61    Deny,
62}
63
64/// How much harm a call can do, as approvers see it (spec 3.3 §7.1).
65#[derive(
66    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
67)]
68#[serde(rename_all = "camelCase")]
69pub enum Risk {
70    /// Routine.
71    Low,
72    /// Needs a look.
73    Medium,
74    /// Needs a careful look.
75    High,
76}
77
78impl Risk {
79    /// The words: `"Low risk"`, `"Medium risk"`, `"High risk"`.
80    pub fn words(self) -> &'static str {
81        match self {
82            Self::Low => words::LOW_RISK,
83            Self::Medium => words::MEDIUM_RISK,
84            Self::High => words::HIGH_RISK,
85        }
86    }
87}
88
89impl From<adk_core::ApprovalRisk> for Risk {
90    fn from(risk: adk_core::ApprovalRisk) -> Self {
91        match risk {
92            adk_core::ApprovalRisk::Low => Self::Low,
93            adk_core::ApprovalRisk::Medium => Self::Medium,
94            // A critical call needs at least the care of a high-risk one.
95            adk_core::ApprovalRisk::High | adk_core::ApprovalRisk::Critical => Self::High,
96        }
97    }
98}
99
100/// The row of the §7.2 table that applies to a caller.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
102#[serde(rename_all = "camelCase")]
103pub enum Row {
104    /// The web home.
105    Web,
106    /// The terminal.
107    Terminal,
108    /// The phone.
109    Phone,
110    /// The desktop tray.
111    Tray,
112    /// A chat channel.
113    Chat,
114    /// Voice.
115    Voice,
116    /// An agent: decides nothing (§7.4 rule 6).
117    Agent,
118}
119
120/// The row that applies to `caller`: the way the input was given first, then the surface.
121///
122/// # Example
123///
124/// ```rust
125/// use adk_surface::{Caller, Origin, SurfaceKind};
126/// use adk_surface::rules::{Row, row};
127///
128/// let spoken = Caller::human("ana", SurfaceKind::Web, Origin::Voice);
129/// assert_eq!(row(&spoken), Row::Voice);
130/// let typed = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
131/// assert_eq!(row(&typed), Row::Terminal);
132/// ```
133pub fn row(caller: &Caller) -> Row {
134    match &caller.origin {
135        Origin::Agent { .. } => Row::Agent,
136        Origin::Voice => Row::Voice,
137        Origin::Chat { .. } => Row::Chat,
138        Origin::Keyboard | Origin::Pointer | Origin::Touch => match caller.surface {
139            SurfaceKind::Web => Row::Web,
140            SurfaceKind::Terminal => Row::Terminal,
141            SurfaceKind::Phone => Row::Phone,
142            SurfaceKind::Tray => Row::Tray,
143            SurfaceKind::Chat => Row::Chat,
144            SurfaceKind::Voice => Row::Voice,
145        },
146    }
147}
148
149/// What the engine knows about a decision when it computes the answers (spec 3.3 §7.1).
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct DecisionFacts {
152    /// The risk the inbox entry carries.
153    pub risk: Risk,
154    /// The call spends money: never "always", never approved from chat, voice or the tray
155    /// (§7.4 rule 4).
156    pub money: bool,
157    /// The call is shown truncated and must be expanded before it is approved (§7.1).
158    pub truncated: bool,
159    /// What the inbox entry allows.
160    pub allows: Vec<ApprovalAction>,
161    /// The label of "Always allow" when the source can create the standing rule, such as
162    /// "Always allow for this person"; `None` when it cannot.
163    pub always_label: Option<String>,
164    /// The decision adds an agent a person was suggested (`kernel:agent.create`): it follows
165    /// the "Always allow" column, with **Add this agent** and **Don't add** (spec 3.3 §5.7,
166    /// §7.2).
167    pub adds_agent: bool,
168    /// The call sends, keeps or acts on images held as evidence (spec 3.7 §8.2): what a
169    /// surface may answer then depends on whether it can show them and whether anything is
170    /// left to send. `None` for a call without images.
171    pub image: Option<ImageGate>,
172    /// The card decides a whole screen plan with one answer (spec 3.7 Q8): **Allow** and
173    /// **Deny** only, never **Always allow** or **Edit**, and **Allow** only where the whole
174    /// plan can be shown — the web home, the phone and the terminal.
175    pub plan: bool,
176}
177
178/// What the rules need to know about a decision with images (spec 3.7 §8.2).
179///
180/// | Situation | Answers |
181/// |---|---|
182/// | Nothing to send: an image is deleted, or every pixel is covered | Deny only, on every surface (board choices A13, A15) |
183/// | Voice | Deny only: it cannot show the image, so it cannot say yes to sending it (A18) |
184/// | Chat and the tray | Deny and "Open in home": a person cannot approve an image they cannot see (A17) |
185/// | The web home, the phone, a terminal | As for any decision, but never **Always allow**: the egress rules decide each host and data class, and a standing rule made from a card would not change them |
186///
187/// # Example
188///
189/// ```rust
190/// use adk_surface::rules::ImageGate;
191///
192/// let gate = ImageGate { sendable: true, holds_again: true };
193/// assert!(gate.sendable);
194/// ```
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct ImageGate {
197    /// Something can be sent: every image is kept and not wholly covered.
198    pub sendable: bool,
199    /// The source holds the call again when its arguments change, so **Edit** can be offered:
200    /// a changed call has a changed image, which a person must see before it leaves (V-I5).
201    pub holds_again: bool,
202}
203
204/// One answer a surface may offer, with its label (spec 3.3 §8.2).
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206#[serde(rename_all = "camelCase")]
207pub struct AnswerOption {
208    /// The answer.
209    pub answer: Answer,
210    /// The button's words.
211    pub label: String,
212    /// The person must confirm it is them first (high risk on the web home and the phone).
213    pub needs_presence: bool,
214    /// The call must be expanded first: it is shown truncated.
215    pub needs_expanded: bool,
216}
217
218/// The answers a surface may give one decision (spec 3.3 §7.2).
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
220#[serde(rename_all = "camelCase")]
221pub struct Allowed {
222    /// The answers, in the order of §7.1: allow once, always allow, edit, deny.
223    pub options: Vec<AnswerOption>,
224    /// Some answers are only in the home: show "Open in home".
225    pub open_in_home: bool,
226    /// A spoken "allow once" takes effect after this many seconds unless cancelled.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub cancel_window_secs: Option<u32>,
229    /// Why this surface cannot approve, in plain words, when it cannot.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub note: Option<String>,
232}
233
234impl Allowed {
235    /// The option for `answer`, when this surface offers it.
236    pub fn option(&self, answer: Answer) -> Option<&AnswerOption> {
237        self.options.iter().find(|option| option.answer == answer)
238    }
239}
240
241/// The answers `caller` may give a decision with `facts` (spec 3.3 §7.2, §7.4).
242///
243/// # Example
244///
245/// ```rust
246/// use adk_core::ApprovalAction;
247/// use adk_surface::{Answer, Caller, Origin, SurfaceKind};
248/// use adk_surface::rules::{DecisionFacts, Risk, allowed_answers};
249///
250/// let facts = DecisionFacts {
251///     risk: Risk::Medium,
252///     money: false,
253///     truncated: false,
254///     allows: ApprovalAction::ALL.to_vec(),
255///     always_label: Some("Always allow for this person".into()),
256///     adds_agent: false,
257///     image: None,
258///     plan: false,
259/// };
260/// let chat = Caller::human("ana", SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() });
261/// let answers: Vec<Answer> = allowed_answers(&chat, &facts).options.iter().map(|o| o.answer).collect();
262/// assert_eq!(answers, vec![Answer::AllowOnce, Answer::Deny]);
263///
264/// let high = DecisionFacts { risk: Risk::High, ..facts };
265/// assert!(allowed_answers(&chat, &high).options.is_empty());
266/// ```
267pub fn allowed_answers(caller: &Caller, facts: &DecisionFacts) -> Allowed {
268    let row = row(caller);
269    if facts.adds_agent {
270        return agent_answers(row, caller, facts);
271    }
272    let consequential = facts.risk == Risk::High || facts.money;
273    let can = |action: ApprovalAction| facts.allows.contains(&action);
274    let mut allowed =
275        Allowed { options: Vec::new(), open_in_home: false, cancel_window_secs: None, note: None };
276    let push = |allowed: &mut Allowed, answer: Answer, label: &str, needs_presence: bool| {
277        let needs_expanded = facts.truncated && answer != Answer::Deny;
278        allowed.options.push(AnswerOption {
279            answer,
280            label: label.to_string(),
281            needs_presence,
282            needs_expanded,
283        });
284    };
285    match row {
286        Row::Agent => {
287            allowed.note = Some(words::NEEDS_A_SCREEN.to_string());
288        }
289        Row::Web | Row::Phone | Row::Terminal => {
290            // High risk: after confirming it is you (web home, phone), or on a paired local
291            // terminal; a terminal that is neither sends the person to the home.
292            let high_ok = !consequential || row != Row::Terminal || caller.paired_local;
293            let needs_presence = consequential && row != Row::Terminal;
294            if high_ok && can(ApprovalAction::Approve) {
295                let label = if needs_presence {
296                    words::CONFIRM_ITS_YOU_AND_APPROVE
297                } else {
298                    words::ALLOW_ONCE
299                };
300                push(&mut allowed, Answer::AllowOnce, label, needs_presence);
301            }
302            if !consequential
303                && can(ApprovalAction::Approve)
304                && let Some(label) = &facts.always_label
305            {
306                push(&mut allowed, Answer::AlwaysAllow, label, false);
307            }
308            if high_ok && can(ApprovalAction::Edit) {
309                push(&mut allowed, Answer::Edit, words::EDIT, needs_presence);
310            }
311            if can(ApprovalAction::Reject) {
312                push(&mut allowed, Answer::Deny, words::DENY, false);
313            }
314            if !high_ok {
315                allowed.open_in_home = true;
316                allowed.note = Some(words::APPROVE_IN_THE_HOME.to_string());
317            }
318        }
319        Row::Tray | Row::Chat | Row::Voice => {
320            if consequential {
321                // Saying no is always safe, so the tray and voice keep Deny; a high-risk
322                // decision never resolves in chat (S-I6), and chat never touches money (§7.4
323                // rule 4).
324                if row != Row::Chat && can(ApprovalAction::Reject) {
325                    push(&mut allowed, Answer::Deny, words::DENY, false);
326                }
327                allowed.open_in_home = row != Row::Voice;
328                allowed.note = Some(
329                    match row {
330                        Row::Tray => words::APPROVE_IN_THE_HOME,
331                        _ => words::NEEDS_A_SCREEN,
332                    }
333                    .to_string(),
334                );
335            } else {
336                if can(ApprovalAction::Approve) {
337                    push(&mut allowed, Answer::AllowOnce, words::ALLOW_ONCE, false);
338                }
339                if can(ApprovalAction::Reject) {
340                    push(&mut allowed, Answer::Deny, words::DENY, false);
341                }
342                // Always allow and edit live in the home (the tray opens it, chat links it).
343                allowed.open_in_home = row != Row::Voice;
344                if row == Row::Voice {
345                    allowed.cancel_window_secs = Some(VOICE_CANCEL_WINDOW_SECS);
346                }
347            }
348        }
349    }
350    if let Some(gate) = facts.image {
351        image_answers(row, gate, &mut allowed);
352    }
353    if facts.plan {
354        plan_answers(row, &mut allowed);
355    }
356    allowed
357}
358
359/// Narrows `allowed` for a screen plan's card (spec 3.7 Q8): one answer for every step, never
360/// a standing rule and never edited, and approved only by a person who can see the whole plan.
361pub(crate) fn plan_answers(row: Row, allowed: &mut Allowed) {
362    allowed.options.retain(|option| matches!(option.answer, Answer::AllowOnce | Answer::Deny));
363    for option in &mut allowed.options {
364        if option.answer == Answer::AllowOnce && !option.needs_presence {
365            option.label = words::ALLOW_THIS_PLAN.to_string();
366        }
367    }
368    match row {
369        Row::Chat | Row::Tray | Row::Voice => {
370            allowed.options.retain(|option| option.answer == Answer::Deny);
371            allowed.cancel_window_secs = None;
372            allowed.open_in_home = row != Row::Voice;
373            allowed.note = Some(words::LOOK_AT_THE_PLAN_IN_THE_HOME.to_string());
374        }
375        Row::Web | Row::Phone | Row::Terminal | Row::Agent => {}
376    }
377}
378
379/// Narrows `allowed` for a decision with images (spec 3.7 §8.2): see [`ImageGate`].
380pub(crate) fn image_answers(row: Row, gate: ImageGate, allowed: &mut Allowed) {
381    allowed.options.retain(|option| option.answer != Answer::AlwaysAllow);
382    if !gate.sendable {
383        allowed.options.retain(|option| option.answer == Answer::Deny);
384        allowed.cancel_window_secs = None;
385        return;
386    }
387    if !gate.holds_again {
388        allowed.options.retain(|option| option.answer != Answer::Edit);
389    }
390    match row {
391        Row::Voice => {
392            allowed.options.retain(|option| option.answer == Answer::Deny);
393            allowed.cancel_window_secs = None;
394            allowed.note = Some(words::LOOK_AT_THE_IMAGE_ON_A_SCREEN.to_string());
395        }
396        Row::Chat | Row::Tray => {
397            allowed.options.retain(|option| option.answer == Answer::Deny);
398            allowed.open_in_home = true;
399            allowed.note = Some(words::SHOW_THE_IMAGE_IN_THE_HOME.to_string());
400        }
401        Row::Web | Row::Phone | Row::Terminal | Row::Agent => {}
402    }
403}
404
405/// The answers to a suggested agent (spec 3.3 §5.7, §7.2 "Add an agent, or let one do
406/// more"): adding is a standing change, so it follows "Always allow" — the web home, the phone
407/// and the terminal, at high risk after confirming it is you or on a paired local terminal —
408/// with no Always allow and no Edit; **Don't add** is the Deny column, on every surface.
409fn agent_answers(row: Row, caller: &Caller, facts: &DecisionFacts) -> Allowed {
410    use crate::agents::words as agent_words;
411    let consequential = facts.risk == Risk::High || facts.money;
412    let can = |action: ApprovalAction| facts.allows.contains(&action);
413    let mut allowed =
414        Allowed { options: Vec::new(), open_in_home: false, cancel_window_secs: None, note: None };
415    let option = |answer: Answer, label: &str, needs_presence: bool| AnswerOption {
416        answer,
417        label: label.to_string(),
418        needs_presence,
419        needs_expanded: facts.truncated && answer != Answer::Deny,
420    };
421    match row {
422        Row::Agent => allowed.note = Some(words::NEEDS_A_SCREEN.to_string()),
423        Row::Web | Row::Phone | Row::Terminal => {
424            let high_ok = !consequential || row != Row::Terminal || caller.paired_local;
425            let needs_presence = consequential && row != Row::Terminal;
426            if high_ok && can(ApprovalAction::Approve) {
427                let label = if needs_presence {
428                    agent_words::CONFIRM_ITS_YOU_AND_ADD
429                } else {
430                    agent_words::ADD_THIS_AGENT
431                };
432                allowed.options.push(option(Answer::AllowOnce, label, needs_presence));
433            }
434            if can(ApprovalAction::Reject) {
435                allowed.options.push(option(Answer::Deny, agent_words::DONT_ADD, false));
436            }
437            if !high_ok {
438                allowed.open_in_home = true;
439                allowed.note = Some(words::APPROVE_IN_THE_HOME.to_string());
440            }
441        }
442        Row::Tray | Row::Chat | Row::Voice => {
443            if can(ApprovalAction::Reject) {
444                allowed.options.push(option(Answer::Deny, agent_words::DONT_ADD, false));
445            }
446            allowed.open_in_home = row != Row::Voice;
447            allowed.note = Some(
448                match row {
449                    Row::Voice => words::NEEDS_A_SCREEN,
450                    _ => words::APPROVE_IN_THE_HOME,
451                }
452                .to_string(),
453            );
454        }
455    }
456    allowed
457}
458
459/// Why the engine refused an answer (spec 3.3 §7.2, §7.4).
460#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
461pub enum RuleViolation {
462    /// The surface may not give this answer to this decision.
463    #[error("this answer is not available here; open the decision in the home app to answer it")]
464    NotOffered,
465    /// The answer needs the person to confirm it is them first.
466    #[error(
467        "confirm it's you first: high-risk calls are approved only after a passkey or device check"
468    )]
469    PresenceRequired,
470    /// The call was shown truncated and was not expanded.
471    #[error("expand the call first: a truncated call cannot be approved until it is shown in full")]
472    NotExpanded,
473}
474
475impl RuleViolation {
476    /// The error code the engine reports.
477    pub fn code(&self) -> &'static str {
478        match self {
479            Self::NotOffered => "surface.answer_not_allowed",
480            Self::PresenceRequired => "surface.confirm_presence",
481            Self::NotExpanded => "surface.call_not_expanded",
482        }
483    }
484}
485
486/// Checks that `caller` may give `answer` to a decision with `facts`, `expanded` saying
487/// whether the surface showed the call in full (spec 3.3 §7.1, §7.2, §7.4).
488///
489/// # Errors
490///
491/// Returns the [`RuleViolation`] that refuses the answer.
492///
493/// # Example
494///
495/// ```rust
496/// use adk_core::ApprovalAction;
497/// use adk_surface::{Answer, Caller, Origin, SurfaceKind};
498/// use adk_surface::rules::{DecisionFacts, Risk, RuleViolation, check};
499///
500/// let facts = DecisionFacts {
501///     risk: Risk::High,
502///     money: false,
503///     truncated: false,
504///     allows: ApprovalAction::ALL.to_vec(),
505///     always_label: None,
506///     adds_agent: false,
507///     image: None,
508///     plan: false,
509/// };
510/// let web = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
511/// assert_eq!(check(&web, &facts, Answer::AllowOnce, true), Err(RuleViolation::PresenceRequired));
512/// assert!(check(&web.with_presence_confirmed(), &facts, Answer::AllowOnce, true).is_ok());
513/// ```
514pub fn check(
515    caller: &Caller,
516    facts: &DecisionFacts,
517    answer: Answer,
518    expanded: bool,
519) -> Result<(), RuleViolation> {
520    let allowed = allowed_answers(caller, facts);
521    let option = allowed.option(answer).ok_or(RuleViolation::NotOffered)?;
522    if option.needs_presence && !caller.presence_confirmed {
523        return Err(RuleViolation::PresenceRequired);
524    }
525    if option.needs_expanded && !expanded {
526        return Err(RuleViolation::NotExpanded);
527    }
528    Ok(())
529}
530
531/// Whether `caller` may resume after a stop: only the web home or a paired local terminal,
532/// with a person's own hands (spec 3.3 §8.2, §11 S-I10).
533///
534/// # Example
535///
536/// ```rust
537/// use adk_surface::{Caller, Origin, SurfaceKind};
538/// use adk_surface::rules::may_resume;
539///
540/// assert!(may_resume(&Caller::human("ana", SurfaceKind::Web, Origin::Pointer)));
541/// assert!(!may_resume(&Caller::human("ana", SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() })));
542/// assert!(!may_resume(&Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard)));
543/// ```
544pub fn may_resume(caller: &Caller) -> bool {
545    match row(caller) {
546        Row::Web => true,
547        Row::Terminal => caller.paired_local,
548        Row::Phone | Row::Tray | Row::Chat | Row::Voice | Row::Agent => false,
549    }
550}
551
552/// Whether `caller` may make agents act more on their own (a looser mode), which is a
553/// standing permission and so follows "Always allow" (spec 3.3 §7.2, §7.4 rule 4): the web
554/// home, the phone and the terminal. Any surface may tighten.
555///
556/// # Example
557///
558/// ```rust
559/// use adk_surface::{Caller, Origin, SurfaceKind};
560/// use adk_surface::rules::may_loosen_mode;
561///
562/// assert!(may_loosen_mode(&Caller::human("ana", SurfaceKind::Phone, Origin::Touch)));
563/// assert!(!may_loosen_mode(&Caller::human("ana", SurfaceKind::Web, Origin::Voice)));
564/// ```
565pub fn may_loosen_mode(caller: &Caller) -> bool {
566    matches!(row(caller), Row::Web | Row::Phone | Row::Terminal)
567}
568
569/// Whether `caller` may add, change, pause or remove an agent here (spec 3.3 §5.7, §7.2): a
570/// person at the web home or the terminal. The phone answers suggestions only (decision 16).
571///
572/// # Example
573///
574/// ```rust
575/// use adk_surface::{Caller, Origin, SurfaceKind};
576/// use adk_surface::rules::may_change_agents;
577///
578/// assert!(may_change_agents(&Caller::human("ana", SurfaceKind::Web, Origin::Pointer)));
579/// assert!(may_change_agents(&Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard)));
580/// assert!(!may_change_agents(&Caller::human("ana", SurfaceKind::Phone, Origin::Touch)));
581/// ```
582pub fn may_change_agents(caller: &Caller) -> bool {
583    matches!(row(caller), Row::Web | Row::Terminal) && caller.device.is_none()
584}
585
586/// Whether `caller` may resume one agent paused by hand: where Resume all may be given (spec
587/// 3.3 §5.7, S-I10).
588///
589/// # Example
590///
591/// ```rust
592/// use adk_surface::{Caller, Origin, SurfaceKind};
593/// use adk_surface::rules::may_resume_agent;
594///
595/// assert!(may_resume_agent(&Caller::human("ana", SurfaceKind::Web, Origin::Pointer)));
596/// assert!(!may_resume_agent(&Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard)));
597/// ```
598pub fn may_resume_agent(caller: &Caller) -> bool {
599    may_resume(caller)
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    fn facts(risk: Risk) -> DecisionFacts {
607        DecisionFacts {
608            risk,
609            money: false,
610            truncated: false,
611            allows: ApprovalAction::ALL.to_vec(),
612            always_label: Some(words::ALWAYS_ALLOW_FOR_THIS_PERSON.into()),
613            adds_agent: false,
614            image: None,
615            plan: false,
616        }
617    }
618
619    fn answers(caller: &Caller, facts: &DecisionFacts) -> Vec<Answer> {
620        allowed_answers(caller, facts).options.iter().map(|option| option.answer).collect()
621    }
622
623    fn caller(surface: SurfaceKind, origin: Origin) -> Caller {
624        Caller::human("ana", surface, origin)
625    }
626
627    fn telegram() -> Origin {
628        Origin::Chat { channel: "Telegram".into() }
629    }
630
631    use Answer::{AllowOnce, AlwaysAllow, Deny, Edit};
632
633    /// The §7.2 table, row by row, for low/medium and high risk.
634    #[test]
635    fn the_table_of_section_7_2() {
636        let everyday = facts(Risk::Medium);
637        let high = facts(Risk::High);
638        let web = caller(SurfaceKind::Web, Origin::Pointer);
639        let phone = caller(SurfaceKind::Phone, Origin::Touch);
640        let terminal = caller(SurfaceKind::Terminal, Origin::Keyboard);
641        let paired = caller(SurfaceKind::Terminal, Origin::Keyboard).with_paired_local();
642        let tray = caller(SurfaceKind::Tray, Origin::Pointer);
643        let chat = caller(SurfaceKind::Chat, telegram());
644        let voice = caller(SurfaceKind::Voice, Origin::Voice);
645        let agent = caller(SurfaceKind::Web, Origin::Agent { agent: "finance".into() });
646
647        for full in [&web, &phone, &terminal] {
648            assert_eq!(answers(full, &everyday), vec![AllowOnce, AlwaysAllow, Edit, Deny]);
649        }
650        assert_eq!(answers(&tray, &everyday), vec![AllowOnce, Deny]);
651        assert_eq!(answers(&chat, &everyday), vec![AllowOnce, Deny]);
652        assert_eq!(answers(&voice, &everyday), vec![AllowOnce, Deny]);
653        assert!(answers(&agent, &everyday).is_empty());
654
655        // High risk: never "always"; web and phone after confirming it is you; a paired local
656        // terminal; nothing but the home elsewhere.
657        for screen in [&web, &phone] {
658            let allowed = allowed_answers(screen, &high);
659            assert_eq!(answers(screen, &high), vec![AllowOnce, Edit, Deny]);
660            assert_eq!(allowed.options[0].label, words::CONFIRM_ITS_YOU_AND_APPROVE);
661            assert!(allowed.options[0].needs_presence && allowed.options[1].needs_presence);
662        }
663        assert_eq!(answers(&paired, &high), vec![AllowOnce, Edit, Deny]);
664        assert_eq!(answers(&terminal, &high), vec![Deny]);
665        let unpaired = allowed_answers(&terminal, &high);
666        assert!(unpaired.open_in_home);
667        // An unpaired terminal says where the call can be approved; it is at a screen already.
668        assert_eq!(unpaired.note.as_deref(), Some(words::APPROVE_IN_THE_HOME));
669        // Deny is always safe: the tray and voice keep it on every decision; chat never
670        // resolves a high-risk one (S-I6).
671        assert_eq!(answers(&tray, &high), vec![Deny]);
672        assert_eq!(answers(&voice, &high), vec![Deny]);
673        assert!(answers(&chat, &high).is_empty());
674        assert!(allowed_answers(&tray, &high).open_in_home);
675        assert!(allowed_answers(&chat, &high).open_in_home);
676        assert!(!allowed_answers(&voice, &high).open_in_home);
677        assert_eq!(allowed_answers(&voice, &high).note.as_deref(), Some(words::NEEDS_A_SCREEN));
678        assert_eq!(allowed_answers(&voice, &high).cancel_window_secs, None);
679        assert_eq!(allowed_answers(&voice, &everyday).cancel_window_secs, Some(5));
680    }
681
682    #[test]
683    fn money_is_never_always_and_never_approved_from_chat_or_voice() {
684        let money = DecisionFacts { money: true, ..facts(Risk::Low) };
685        let web = caller(SurfaceKind::Web, Origin::Pointer);
686        assert_eq!(answers(&web, &money), vec![AllowOnce, Edit, Deny]);
687        assert!(answers(&caller(SurfaceKind::Chat, telegram()), &money).is_empty());
688        assert_eq!(answers(&caller(SurfaceKind::Web, Origin::Voice), &money), vec![Deny]);
689    }
690
691    #[test]
692    fn a_truncated_call_is_approved_only_once_expanded() {
693        let truncated = DecisionFacts { truncated: true, ..facts(Risk::Low) };
694        let web = caller(SurfaceKind::Web, Origin::Pointer);
695        assert_eq!(check(&web, &truncated, AllowOnce, false), Err(RuleViolation::NotExpanded));
696        assert_eq!(check(&web, &truncated, AllowOnce, true), Ok(()));
697        assert_eq!(check(&web, &truncated, Deny, false), Ok(()));
698    }
699
700    /// A screen plan's card (spec 3.7 Q8): allow and deny where the plan can be shown, deny
701    /// elsewhere, never always or edit, and allow only once the plan was shown in full.
702    #[test]
703    fn a_screen_plan_is_allowed_or_denied_where_it_can_be_seen() {
704        let plan = DecisionFacts { plan: true, ..facts(Risk::Medium) };
705        let web = caller(SurfaceKind::Web, Origin::Pointer);
706        assert_eq!(answers(&web, &plan), vec![AllowOnce, Deny]);
707        assert_eq!(allowed_answers(&web, &plan).options[0].label, words::ALLOW_THIS_PLAN);
708        assert_eq!(
709            answers(&caller(SurfaceKind::Phone, Origin::Touch), &plan),
710            vec![AllowOnce, Deny]
711        );
712        assert_eq!(
713            answers(&caller(SurfaceKind::Terminal, Origin::Keyboard), &plan),
714            vec![AllowOnce, Deny]
715        );
716        for row in [
717            caller(SurfaceKind::Chat, telegram()),
718            caller(SurfaceKind::Tray, Origin::Pointer),
719            caller(SurfaceKind::Web, Origin::Voice),
720        ] {
721            let allowed = allowed_answers(&row, &plan);
722            assert_eq!(answers(&row, &plan), vec![Deny], "{row:?}");
723            assert_eq!(allowed.note.as_deref(), Some(words::LOOK_AT_THE_PLAN_IN_THE_HOME));
724            assert_eq!(allowed.cancel_window_secs, None);
725        }
726        assert_eq!(check(&web, &plan, AlwaysAllow, true), Err(RuleViolation::NotOffered));
727        assert_eq!(check(&web, &plan, Edit, true), Err(RuleViolation::NotOffered));
728        let long = DecisionFacts { truncated: true, ..plan };
729        assert_eq!(check(&web, &long, AllowOnce, false), Err(RuleViolation::NotExpanded));
730        assert_eq!(check(&web, &long, AllowOnce, true), Ok(()));
731        assert_eq!(check(&web, &long, Deny, false), Ok(()));
732    }
733
734    #[test]
735    fn the_request_limits_the_answers() {
736        let no_edit = DecisionFacts {
737            allows: vec![ApprovalAction::Approve, ApprovalAction::Reject],
738            always_label: None,
739            ..facts(Risk::Low)
740        };
741        assert_eq!(
742            answers(&caller(SurfaceKind::Web, Origin::Pointer), &no_edit),
743            vec![AllowOnce, Deny]
744        );
745    }
746
747    #[test]
748    fn resuming_is_the_home_or_a_paired_local_terminal() {
749        assert!(may_resume(&caller(SurfaceKind::Web, Origin::Keyboard)));
750        assert!(may_resume(&caller(SurfaceKind::Terminal, Origin::Keyboard).with_paired_local()));
751        for other in [
752            caller(SurfaceKind::Phone, Origin::Touch),
753            caller(SurfaceKind::Tray, Origin::Pointer),
754            caller(SurfaceKind::Chat, telegram()),
755            caller(SurfaceKind::Web, Origin::Voice),
756            caller(SurfaceKind::Web, Origin::Agent { agent: "a".into() }),
757        ] {
758            assert!(!may_resume(&other), "{other:?}");
759        }
760    }
761
762    /// The §7.2 column "Add an agent, or let one do more" over every row (spec 3.3 §5.7).
763    #[test]
764    fn a_suggested_agent_follows_the_always_allow_column() {
765        use crate::agents::words::{ADD_THIS_AGENT, CONFIRM_ITS_YOU_AND_ADD, DONT_ADD};
766        let agent_facts =
767            |risk| DecisionFacts { adds_agent: true, always_label: None, ..facts(risk) };
768        let labels = |caller: &Caller, facts: &DecisionFacts| -> Vec<(Answer, String, bool)> {
769            allowed_answers(caller, facts)
770                .options
771                .into_iter()
772                .map(|option| (option.answer, option.label, option.needs_presence))
773                .collect()
774        };
775        let web = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
776        let phone = Caller::human("ana", SurfaceKind::Phone, Origin::Touch);
777        let terminal = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
778        let local = terminal.clone().with_paired_local();
779        let tray = Caller::human("ana", SurfaceKind::Tray, Origin::Pointer);
780        let chat =
781            Caller::human("ana", SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() });
782        let voice = Caller::human("ana", SurfaceKind::Web, Origin::Voice);
783        let agent =
784            Caller::human("ana", SurfaceKind::Web, Origin::Agent { agent: "finance".into() });
785        let add = (Answer::AllowOnce, ADD_THIS_AGENT.to_string(), false);
786        let confirm = (Answer::AllowOnce, CONFIRM_ITS_YOU_AND_ADD.to_string(), true);
787        let dont = (Answer::Deny, DONT_ADD.to_string(), false);
788        let medium = agent_facts(Risk::Medium);
789        let high = agent_facts(Risk::High);
790        // No Always allow and no Edit anywhere.
791        for caller in [&web, &phone, &terminal] {
792            assert_eq!(labels(caller, &medium), [add.clone(), dont.clone()], "{caller:?}");
793        }
794        assert_eq!(labels(&web, &high), [confirm.clone(), dont.clone()]);
795        assert_eq!(labels(&phone, &high), [confirm, dont.clone()]);
796        assert_eq!(labels(&terminal, &high), std::slice::from_ref(&dont));
797        assert!(allowed_answers(&terminal, &high).open_in_home);
798        assert_eq!(labels(&local, &high), [add, dont.clone()]);
799        for caller in [&tray, &chat, &voice] {
800            for facts in [&medium, &high] {
801                assert_eq!(labels(caller, facts), std::slice::from_ref(&dont), "{caller:?}");
802            }
803        }
804        assert!(allowed_answers(&chat, &medium).open_in_home);
805        assert!(labels(&agent, &medium).is_empty());
806        // Money is high risk too.
807        let money = DecisionFacts { money: true, ..agent_facts(Risk::Low) };
808        assert_eq!(labels(&terminal, &money), [dont]);
809    }
810}