use adk_core::ApprovalAction;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::origin::{Caller, Origin, SurfaceKind};
use crate::words;
pub const VOICE_CANCEL_WINDOW_SECS: u32 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum Answer {
AllowOnce,
AlwaysAllow,
Edit,
Deny,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub enum Risk {
Low,
Medium,
High,
}
impl Risk {
pub fn words(self) -> &'static str {
match self {
Self::Low => words::LOW_RISK,
Self::Medium => words::MEDIUM_RISK,
Self::High => words::HIGH_RISK,
}
}
}
impl From<adk_core::ApprovalRisk> for Risk {
fn from(risk: adk_core::ApprovalRisk) -> Self {
match risk {
adk_core::ApprovalRisk::Low => Self::Low,
adk_core::ApprovalRisk::Medium => Self::Medium,
adk_core::ApprovalRisk::High | adk_core::ApprovalRisk::Critical => Self::High,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum Row {
Web,
Terminal,
Phone,
Tray,
Chat,
Voice,
Agent,
}
pub fn row(caller: &Caller) -> Row {
match &caller.origin {
Origin::Agent { .. } => Row::Agent,
Origin::Voice => Row::Voice,
Origin::Chat { .. } => Row::Chat,
Origin::Keyboard | Origin::Pointer | Origin::Touch => match caller.surface {
SurfaceKind::Web => Row::Web,
SurfaceKind::Terminal => Row::Terminal,
SurfaceKind::Phone => Row::Phone,
SurfaceKind::Tray => Row::Tray,
SurfaceKind::Chat => Row::Chat,
SurfaceKind::Voice => Row::Voice,
},
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecisionFacts {
pub risk: Risk,
pub money: bool,
pub truncated: bool,
pub allows: Vec<ApprovalAction>,
pub always_label: Option<String>,
pub adds_agent: bool,
pub image: Option<ImageGate>,
pub plan: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageGate {
pub sendable: bool,
pub holds_again: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AnswerOption {
pub answer: Answer,
pub label: String,
pub needs_presence: bool,
pub needs_expanded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Allowed {
pub options: Vec<AnswerOption>,
pub open_in_home: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cancel_window_secs: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl Allowed {
pub fn option(&self, answer: Answer) -> Option<&AnswerOption> {
self.options.iter().find(|option| option.answer == answer)
}
}
pub fn allowed_answers(caller: &Caller, facts: &DecisionFacts) -> Allowed {
let row = row(caller);
if facts.adds_agent {
return agent_answers(row, caller, facts);
}
let consequential = facts.risk == Risk::High || facts.money;
let can = |action: ApprovalAction| facts.allows.contains(&action);
let mut allowed =
Allowed { options: Vec::new(), open_in_home: false, cancel_window_secs: None, note: None };
let push = |allowed: &mut Allowed, answer: Answer, label: &str, needs_presence: bool| {
let needs_expanded = facts.truncated && answer != Answer::Deny;
allowed.options.push(AnswerOption {
answer,
label: label.to_string(),
needs_presence,
needs_expanded,
});
};
match row {
Row::Agent => {
allowed.note = Some(words::NEEDS_A_SCREEN.to_string());
}
Row::Web | Row::Phone | Row::Terminal => {
let high_ok = !consequential || row != Row::Terminal || caller.paired_local;
let needs_presence = consequential && row != Row::Terminal;
if high_ok && can(ApprovalAction::Approve) {
let label = if needs_presence {
words::CONFIRM_ITS_YOU_AND_APPROVE
} else {
words::ALLOW_ONCE
};
push(&mut allowed, Answer::AllowOnce, label, needs_presence);
}
if !consequential
&& can(ApprovalAction::Approve)
&& let Some(label) = &facts.always_label
{
push(&mut allowed, Answer::AlwaysAllow, label, false);
}
if high_ok && can(ApprovalAction::Edit) {
push(&mut allowed, Answer::Edit, words::EDIT, needs_presence);
}
if can(ApprovalAction::Reject) {
push(&mut allowed, Answer::Deny, words::DENY, false);
}
if !high_ok {
allowed.open_in_home = true;
allowed.note = Some(words::APPROVE_IN_THE_HOME.to_string());
}
}
Row::Tray | Row::Chat | Row::Voice => {
if consequential {
if row != Row::Chat && can(ApprovalAction::Reject) {
push(&mut allowed, Answer::Deny, words::DENY, false);
}
allowed.open_in_home = row != Row::Voice;
allowed.note = Some(
match row {
Row::Tray => words::APPROVE_IN_THE_HOME,
_ => words::NEEDS_A_SCREEN,
}
.to_string(),
);
} else {
if can(ApprovalAction::Approve) {
push(&mut allowed, Answer::AllowOnce, words::ALLOW_ONCE, false);
}
if can(ApprovalAction::Reject) {
push(&mut allowed, Answer::Deny, words::DENY, false);
}
allowed.open_in_home = row != Row::Voice;
if row == Row::Voice {
allowed.cancel_window_secs = Some(VOICE_CANCEL_WINDOW_SECS);
}
}
}
}
if let Some(gate) = facts.image {
image_answers(row, gate, &mut allowed);
}
if facts.plan {
plan_answers(row, &mut allowed);
}
allowed
}
pub(crate) fn plan_answers(row: Row, allowed: &mut Allowed) {
allowed.options.retain(|option| matches!(option.answer, Answer::AllowOnce | Answer::Deny));
for option in &mut allowed.options {
if option.answer == Answer::AllowOnce && !option.needs_presence {
option.label = words::ALLOW_THIS_PLAN.to_string();
}
}
match row {
Row::Chat | Row::Tray | Row::Voice => {
allowed.options.retain(|option| option.answer == Answer::Deny);
allowed.cancel_window_secs = None;
allowed.open_in_home = row != Row::Voice;
allowed.note = Some(words::LOOK_AT_THE_PLAN_IN_THE_HOME.to_string());
}
Row::Web | Row::Phone | Row::Terminal | Row::Agent => {}
}
}
pub(crate) fn image_answers(row: Row, gate: ImageGate, allowed: &mut Allowed) {
allowed.options.retain(|option| option.answer != Answer::AlwaysAllow);
if !gate.sendable {
allowed.options.retain(|option| option.answer == Answer::Deny);
allowed.cancel_window_secs = None;
return;
}
if !gate.holds_again {
allowed.options.retain(|option| option.answer != Answer::Edit);
}
match row {
Row::Voice => {
allowed.options.retain(|option| option.answer == Answer::Deny);
allowed.cancel_window_secs = None;
allowed.note = Some(words::LOOK_AT_THE_IMAGE_ON_A_SCREEN.to_string());
}
Row::Chat | Row::Tray => {
allowed.options.retain(|option| option.answer == Answer::Deny);
allowed.open_in_home = true;
allowed.note = Some(words::SHOW_THE_IMAGE_IN_THE_HOME.to_string());
}
Row::Web | Row::Phone | Row::Terminal | Row::Agent => {}
}
}
fn agent_answers(row: Row, caller: &Caller, facts: &DecisionFacts) -> Allowed {
use crate::agents::words as agent_words;
let consequential = facts.risk == Risk::High || facts.money;
let can = |action: ApprovalAction| facts.allows.contains(&action);
let mut allowed =
Allowed { options: Vec::new(), open_in_home: false, cancel_window_secs: None, note: None };
let option = |answer: Answer, label: &str, needs_presence: bool| AnswerOption {
answer,
label: label.to_string(),
needs_presence,
needs_expanded: facts.truncated && answer != Answer::Deny,
};
match row {
Row::Agent => allowed.note = Some(words::NEEDS_A_SCREEN.to_string()),
Row::Web | Row::Phone | Row::Terminal => {
let high_ok = !consequential || row != Row::Terminal || caller.paired_local;
let needs_presence = consequential && row != Row::Terminal;
if high_ok && can(ApprovalAction::Approve) {
let label = if needs_presence {
agent_words::CONFIRM_ITS_YOU_AND_ADD
} else {
agent_words::ADD_THIS_AGENT
};
allowed.options.push(option(Answer::AllowOnce, label, needs_presence));
}
if can(ApprovalAction::Reject) {
allowed.options.push(option(Answer::Deny, agent_words::DONT_ADD, false));
}
if !high_ok {
allowed.open_in_home = true;
allowed.note = Some(words::APPROVE_IN_THE_HOME.to_string());
}
}
Row::Tray | Row::Chat | Row::Voice => {
if can(ApprovalAction::Reject) {
allowed.options.push(option(Answer::Deny, agent_words::DONT_ADD, false));
}
allowed.open_in_home = row != Row::Voice;
allowed.note = Some(
match row {
Row::Voice => words::NEEDS_A_SCREEN,
_ => words::APPROVE_IN_THE_HOME,
}
.to_string(),
);
}
}
allowed
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RuleViolation {
#[error("this answer is not available here; open the decision in the home app to answer it")]
NotOffered,
#[error(
"confirm it's you first: high-risk calls are approved only after a passkey or device check"
)]
PresenceRequired,
#[error("expand the call first: a truncated call cannot be approved until it is shown in full")]
NotExpanded,
}
impl RuleViolation {
pub fn code(&self) -> &'static str {
match self {
Self::NotOffered => "surface.answer_not_allowed",
Self::PresenceRequired => "surface.confirm_presence",
Self::NotExpanded => "surface.call_not_expanded",
}
}
}
pub fn check(
caller: &Caller,
facts: &DecisionFacts,
answer: Answer,
expanded: bool,
) -> Result<(), RuleViolation> {
let allowed = allowed_answers(caller, facts);
let option = allowed.option(answer).ok_or(RuleViolation::NotOffered)?;
if option.needs_presence && !caller.presence_confirmed {
return Err(RuleViolation::PresenceRequired);
}
if option.needs_expanded && !expanded {
return Err(RuleViolation::NotExpanded);
}
Ok(())
}
pub fn may_resume(caller: &Caller) -> bool {
match row(caller) {
Row::Web => true,
Row::Terminal => caller.paired_local,
Row::Phone | Row::Tray | Row::Chat | Row::Voice | Row::Agent => false,
}
}
pub fn may_loosen_mode(caller: &Caller) -> bool {
matches!(row(caller), Row::Web | Row::Phone | Row::Terminal)
}
pub fn may_change_agents(caller: &Caller) -> bool {
matches!(row(caller), Row::Web | Row::Terminal) && caller.device.is_none()
}
pub fn may_resume_agent(caller: &Caller) -> bool {
may_resume(caller)
}
#[cfg(test)]
mod tests {
use super::*;
fn facts(risk: Risk) -> DecisionFacts {
DecisionFacts {
risk,
money: false,
truncated: false,
allows: ApprovalAction::ALL.to_vec(),
always_label: Some(words::ALWAYS_ALLOW_FOR_THIS_PERSON.into()),
adds_agent: false,
image: None,
plan: false,
}
}
fn answers(caller: &Caller, facts: &DecisionFacts) -> Vec<Answer> {
allowed_answers(caller, facts).options.iter().map(|option| option.answer).collect()
}
fn caller(surface: SurfaceKind, origin: Origin) -> Caller {
Caller::human("ana", surface, origin)
}
fn telegram() -> Origin {
Origin::Chat { channel: "Telegram".into() }
}
use Answer::{AllowOnce, AlwaysAllow, Deny, Edit};
#[test]
fn the_table_of_section_7_2() {
let everyday = facts(Risk::Medium);
let high = facts(Risk::High);
let web = caller(SurfaceKind::Web, Origin::Pointer);
let phone = caller(SurfaceKind::Phone, Origin::Touch);
let terminal = caller(SurfaceKind::Terminal, Origin::Keyboard);
let paired = caller(SurfaceKind::Terminal, Origin::Keyboard).with_paired_local();
let tray = caller(SurfaceKind::Tray, Origin::Pointer);
let chat = caller(SurfaceKind::Chat, telegram());
let voice = caller(SurfaceKind::Voice, Origin::Voice);
let agent = caller(SurfaceKind::Web, Origin::Agent { agent: "finance".into() });
for full in [&web, &phone, &terminal] {
assert_eq!(answers(full, &everyday), vec![AllowOnce, AlwaysAllow, Edit, Deny]);
}
assert_eq!(answers(&tray, &everyday), vec![AllowOnce, Deny]);
assert_eq!(answers(&chat, &everyday), vec![AllowOnce, Deny]);
assert_eq!(answers(&voice, &everyday), vec![AllowOnce, Deny]);
assert!(answers(&agent, &everyday).is_empty());
for screen in [&web, &phone] {
let allowed = allowed_answers(screen, &high);
assert_eq!(answers(screen, &high), vec![AllowOnce, Edit, Deny]);
assert_eq!(allowed.options[0].label, words::CONFIRM_ITS_YOU_AND_APPROVE);
assert!(allowed.options[0].needs_presence && allowed.options[1].needs_presence);
}
assert_eq!(answers(&paired, &high), vec![AllowOnce, Edit, Deny]);
assert_eq!(answers(&terminal, &high), vec![Deny]);
let unpaired = allowed_answers(&terminal, &high);
assert!(unpaired.open_in_home);
assert_eq!(unpaired.note.as_deref(), Some(words::APPROVE_IN_THE_HOME));
assert_eq!(answers(&tray, &high), vec![Deny]);
assert_eq!(answers(&voice, &high), vec![Deny]);
assert!(answers(&chat, &high).is_empty());
assert!(allowed_answers(&tray, &high).open_in_home);
assert!(allowed_answers(&chat, &high).open_in_home);
assert!(!allowed_answers(&voice, &high).open_in_home);
assert_eq!(allowed_answers(&voice, &high).note.as_deref(), Some(words::NEEDS_A_SCREEN));
assert_eq!(allowed_answers(&voice, &high).cancel_window_secs, None);
assert_eq!(allowed_answers(&voice, &everyday).cancel_window_secs, Some(5));
}
#[test]
fn money_is_never_always_and_never_approved_from_chat_or_voice() {
let money = DecisionFacts { money: true, ..facts(Risk::Low) };
let web = caller(SurfaceKind::Web, Origin::Pointer);
assert_eq!(answers(&web, &money), vec![AllowOnce, Edit, Deny]);
assert!(answers(&caller(SurfaceKind::Chat, telegram()), &money).is_empty());
assert_eq!(answers(&caller(SurfaceKind::Web, Origin::Voice), &money), vec![Deny]);
}
#[test]
fn a_truncated_call_is_approved_only_once_expanded() {
let truncated = DecisionFacts { truncated: true, ..facts(Risk::Low) };
let web = caller(SurfaceKind::Web, Origin::Pointer);
assert_eq!(check(&web, &truncated, AllowOnce, false), Err(RuleViolation::NotExpanded));
assert_eq!(check(&web, &truncated, AllowOnce, true), Ok(()));
assert_eq!(check(&web, &truncated, Deny, false), Ok(()));
}
#[test]
fn a_screen_plan_is_allowed_or_denied_where_it_can_be_seen() {
let plan = DecisionFacts { plan: true, ..facts(Risk::Medium) };
let web = caller(SurfaceKind::Web, Origin::Pointer);
assert_eq!(answers(&web, &plan), vec![AllowOnce, Deny]);
assert_eq!(allowed_answers(&web, &plan).options[0].label, words::ALLOW_THIS_PLAN);
assert_eq!(
answers(&caller(SurfaceKind::Phone, Origin::Touch), &plan),
vec![AllowOnce, Deny]
);
assert_eq!(
answers(&caller(SurfaceKind::Terminal, Origin::Keyboard), &plan),
vec![AllowOnce, Deny]
);
for row in [
caller(SurfaceKind::Chat, telegram()),
caller(SurfaceKind::Tray, Origin::Pointer),
caller(SurfaceKind::Web, Origin::Voice),
] {
let allowed = allowed_answers(&row, &plan);
assert_eq!(answers(&row, &plan), vec![Deny], "{row:?}");
assert_eq!(allowed.note.as_deref(), Some(words::LOOK_AT_THE_PLAN_IN_THE_HOME));
assert_eq!(allowed.cancel_window_secs, None);
}
assert_eq!(check(&web, &plan, AlwaysAllow, true), Err(RuleViolation::NotOffered));
assert_eq!(check(&web, &plan, Edit, true), Err(RuleViolation::NotOffered));
let long = DecisionFacts { truncated: true, ..plan };
assert_eq!(check(&web, &long, AllowOnce, false), Err(RuleViolation::NotExpanded));
assert_eq!(check(&web, &long, AllowOnce, true), Ok(()));
assert_eq!(check(&web, &long, Deny, false), Ok(()));
}
#[test]
fn the_request_limits_the_answers() {
let no_edit = DecisionFacts {
allows: vec![ApprovalAction::Approve, ApprovalAction::Reject],
always_label: None,
..facts(Risk::Low)
};
assert_eq!(
answers(&caller(SurfaceKind::Web, Origin::Pointer), &no_edit),
vec![AllowOnce, Deny]
);
}
#[test]
fn resuming_is_the_home_or_a_paired_local_terminal() {
assert!(may_resume(&caller(SurfaceKind::Web, Origin::Keyboard)));
assert!(may_resume(&caller(SurfaceKind::Terminal, Origin::Keyboard).with_paired_local()));
for other in [
caller(SurfaceKind::Phone, Origin::Touch),
caller(SurfaceKind::Tray, Origin::Pointer),
caller(SurfaceKind::Chat, telegram()),
caller(SurfaceKind::Web, Origin::Voice),
caller(SurfaceKind::Web, Origin::Agent { agent: "a".into() }),
] {
assert!(!may_resume(&other), "{other:?}");
}
}
#[test]
fn a_suggested_agent_follows_the_always_allow_column() {
use crate::agents::words::{ADD_THIS_AGENT, CONFIRM_ITS_YOU_AND_ADD, DONT_ADD};
let agent_facts =
|risk| DecisionFacts { adds_agent: true, always_label: None, ..facts(risk) };
let labels = |caller: &Caller, facts: &DecisionFacts| -> Vec<(Answer, String, bool)> {
allowed_answers(caller, facts)
.options
.into_iter()
.map(|option| (option.answer, option.label, option.needs_presence))
.collect()
};
let web = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
let phone = Caller::human("ana", SurfaceKind::Phone, Origin::Touch);
let terminal = Caller::human("ana", SurfaceKind::Terminal, Origin::Keyboard);
let local = terminal.clone().with_paired_local();
let tray = Caller::human("ana", SurfaceKind::Tray, Origin::Pointer);
let chat =
Caller::human("ana", SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() });
let voice = Caller::human("ana", SurfaceKind::Web, Origin::Voice);
let agent =
Caller::human("ana", SurfaceKind::Web, Origin::Agent { agent: "finance".into() });
let add = (Answer::AllowOnce, ADD_THIS_AGENT.to_string(), false);
let confirm = (Answer::AllowOnce, CONFIRM_ITS_YOU_AND_ADD.to_string(), true);
let dont = (Answer::Deny, DONT_ADD.to_string(), false);
let medium = agent_facts(Risk::Medium);
let high = agent_facts(Risk::High);
for caller in [&web, &phone, &terminal] {
assert_eq!(labels(caller, &medium), [add.clone(), dont.clone()], "{caller:?}");
}
assert_eq!(labels(&web, &high), [confirm.clone(), dont.clone()]);
assert_eq!(labels(&phone, &high), [confirm, dont.clone()]);
assert_eq!(labels(&terminal, &high), std::slice::from_ref(&dont));
assert!(allowed_answers(&terminal, &high).open_in_home);
assert_eq!(labels(&local, &high), [add, dont.clone()]);
for caller in [&tray, &chat, &voice] {
for facts in [&medium, &high] {
assert_eq!(labels(caller, facts), std::slice::from_ref(&dont), "{caller:?}");
}
}
assert!(allowed_answers(&chat, &medium).open_in_home);
assert!(labels(&agent, &medium).is_empty());
let money = DecisionFacts { money: true, ..agent_facts(Risk::Low) };
assert_eq!(labels(&terminal, &money), [dont]);
}
}