1use adk_core::ApprovalAction;
32use schemars::JsonSchema;
33use serde::{Deserialize, Serialize};
34
35use crate::origin::{Caller, Origin, SurfaceKind};
36use crate::words;
37
38pub const VOICE_CANCEL_WINDOW_SECS: u32 = 5;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
52#[serde(rename_all = "camelCase")]
53pub enum Answer {
54 AllowOnce,
56 AlwaysAllow,
58 Edit,
60 Deny,
62}
63
64#[derive(
66 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
67)]
68#[serde(rename_all = "camelCase")]
69pub enum Risk {
70 Low,
72 Medium,
74 High,
76}
77
78impl Risk {
79 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 adk_core::ApprovalRisk::High | adk_core::ApprovalRisk::Critical => Self::High,
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
102#[serde(rename_all = "camelCase")]
103pub enum Row {
104 Web,
106 Terminal,
108 Phone,
110 Tray,
112 Chat,
114 Voice,
116 Agent,
118}
119
120pub 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#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct DecisionFacts {
152 pub risk: Risk,
154 pub money: bool,
157 pub truncated: bool,
159 pub allows: Vec<ApprovalAction>,
161 pub always_label: Option<String>,
164 pub adds_agent: bool,
168 pub image: Option<ImageGate>,
172 pub plan: bool,
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct ImageGate {
197 pub sendable: bool,
199 pub holds_again: bool,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206#[serde(rename_all = "camelCase")]
207pub struct AnswerOption {
208 pub answer: Answer,
210 pub label: String,
212 pub needs_presence: bool,
214 pub needs_expanded: bool,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
220#[serde(rename_all = "camelCase")]
221pub struct Allowed {
222 pub options: Vec<AnswerOption>,
224 pub open_in_home: bool,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub cancel_window_secs: Option<u32>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub note: Option<String>,
232}
233
234impl Allowed {
235 pub fn option(&self, answer: Answer) -> Option<&AnswerOption> {
237 self.options.iter().find(|option| option.answer == answer)
238 }
239}
240
241pub 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 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 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 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
359pub(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
379pub(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
405fn 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
461pub enum RuleViolation {
462 #[error("this answer is not available here; open the decision in the home app to answer it")]
464 NotOffered,
465 #[error(
467 "confirm it's you first: high-risk calls are approved only after a passkey or device check"
468 )]
469 PresenceRequired,
470 #[error("expand the call first: a truncated call cannot be approved until it is shown in full")]
472 NotExpanded,
473}
474
475impl RuleViolation {
476 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
486pub 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
531pub 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
552pub fn may_loosen_mode(caller: &Caller) -> bool {
566 matches!(row(caller), Row::Web | Row::Phone | Row::Terminal)
567}
568
569pub fn may_change_agents(caller: &Caller) -> bool {
583 matches!(row(caller), Row::Web | Row::Terminal) && caller.device.is_none()
584}
585
586pub 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 #[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 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 assert_eq!(unpaired.note.as_deref(), Some(words::APPROVE_IN_THE_HOME));
669 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 #[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 #[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 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 let money = DecisionFacts { money: true, ..agent_facts(Risk::Low) };
808 assert_eq!(labels(&terminal, &money), [dont]);
809 }
810}