Skip to main content

adk_surface/
hints.rs

1//! Card hints (spec 3.3 §7.1, §7.2): what a feature knows about the decisions its own tools
2//! ask, which a card cannot read from the call alone.
3//!
4//! A feature that publishes tools under its own [`ToolOrigin`](adk_core::ToolOrigin) — a
5//! workflow's governed nodes, a form an agent drew, a change on the person's screens — tells
6//! its decisions apart by [`ApprovalRequest::origin`], never by the tool's name, and gives
7//! the engine a [`CardHint`] for each. Hints are registered with
8//! [`SurfaceEngineBuilder::card_hints`](crate::SurfaceEngineBuilder::card_hints) in order, and
9//! the engine reads them wherever it draws a card: Decisions, a session's decisions, the
10//! feed, and the cards of the phone, voice, chat and the tray.
11//!
12//! | Field | What it changes | When several hints set it |
13//! |---|---|---|
14//! | `heading` | The heading, in place of the one made from the tool and its main argument | The first hint that sets it |
15//! | `chat_heading` | The heading of a chat card | The first hint that sets it |
16//! | `money` | `Some(true)` marks the call as spending money: the high-risk column, never **Always allow** (§7.4 rule 4) | Any hint that marks it |
17//! | `reversibility` | "Can't be undone", "You can change it back", … | The first hint that sets it |
18//! | `offer_always` | `Some(false)` removes **Always allow** | Any hint that removes it |
19//! | `first_step` | A step of "How it got here" before "Asked at 10:02" | The first hint that sets it |
20//! | `detail` | A line under the details, with an optional link into the home | The first hint that sets it |
21//! | `media` | Where a call's images go, what they are, what they cost and what they were cut from (spec 3.7 §8.2) | Each fact from the first hint that sets it |
22//!
23//! A hint may only make a card stricter or add words. It never adds an answer, never lowers
24//! the risk and never changes it: the risk stays the inbox entry's, set when the call was
25//! held, so chat, voice and the kernel's own routes agree (spec 3.3 §7.2). The kernel's own
26//! routes, its chat gateway among them, read no hints: a feature whose hint marks money also
27//! rates the call high through its approval router, as the workflow observer does. `money: Some(false)`
28//! and `offer_always: Some(true)` change nothing. The engine's
29//! [`heading`](crate::SurfaceEngineBuilder::heading), [`money`](crate::SurfaceEngineBuilder::money)
30//! and [`reversibility`](crate::SurfaceEngineBuilder::reversibility) stay the fallback for a
31//! field no hint sets.
32//!
33//! A hint reads only the inbox entry it is given and the provider's own kernel-side data,
34//! never text an agent wrote (§7.1: every surface draws a decision from the inbox entry, never
35//! from agent output).
36//!
37//! A feature can also name what its call acts on, as the person knows it ([`CardHints::names`]):
38//! the record of an answer then carries that name and the card's summary, so "What your agents
39//! did" says "Finance asked to snooze News digest; you said no" whichever answer was given
40//! (spec 3.3 §8, §11).
41
42use std::sync::Arc;
43
44use adk_core::ApprovalRequest;
45use async_trait::async_trait;
46
47use crate::model::{CardDetail, Reversibility};
48
49/// What a feature says about one of its decisions (spec 3.3 §7.1). Every field is optional.
50/// When several hints answer the same decision, the first that sets a wording field wins, and
51/// any of them can mark money or remove **Always allow**.
52///
53/// # Example
54///
55/// ```rust
56/// use adk_surface::{CardDetail, CardHint, Reversibility};
57///
58/// let hint = CardHint::new()
59///     .with_heading("Move News digest to 19:00")
60///     .with_chat_heading("Snooze something in Coming up")
61///     .with_reversibility(Reversibility::CanBeChangedBack)
62///     .without_always_allow()
63///     .with_first_step("Finance read 1 web page (example.com)");
64/// assert_eq!(hint.offer_always, Some(false));
65///
66/// let workflow = CardHint::new()
67///     .spends_money()
68///     .with_detail(CardDetail::new("From the invoice-run workflow").with_link("Open in Runs", "/ui/runs/r-1"));
69/// assert_eq!(workflow.money, Some(true));
70/// ```
71#[derive(Debug, Clone, Default, PartialEq, Eq)]
72pub struct CardHint {
73    /// What will happen, in plain words, in place of the heading made from the call.
74    pub heading: Option<String>,
75    /// The heading of a chat card, which carries no arguments (S-I5): "Snooze something in
76    /// Coming up".
77    pub chat_heading: Option<String>,
78    /// `Some(true)` marks the call as spending money. `Some(false)` changes nothing.
79    pub money: Option<bool>,
80    /// Whether the call can be taken back.
81    pub reversibility: Option<Reversibility>,
82    /// `Some(false)` removes **Always allow**. `Some(true)` changes nothing: whether it is
83    /// offered stays the source's and the rules' (§7.2).
84    pub offer_always: Option<bool>,
85    /// A step of "How it got here" before "Asked at 10:02", such as "Finance read 1 web page
86    /// (example.com)".
87    pub first_step: Option<String>,
88    /// A line under the details, such as "From the invoice-run workflow · Open in Runs". Never
89    /// on a chat card (S-I5).
90    pub detail: Option<CardDetail>,
91    /// What the feature knows about the images the call holds as evidence: where they go,
92    /// what they are, the estimated cost and what they were cut from (spec 3.7 §8.2).
93    pub media: Option<crate::evidence::MediaFacts>,
94}
95
96impl CardHint {
97    /// A hint that changes nothing.
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Heads the card with `heading`.
103    #[must_use]
104    pub fn with_heading(mut self, heading: impl Into<String>) -> Self {
105        self.heading = Some(heading.into());
106        self
107    }
108
109    /// Heads a chat card with `heading`.
110    #[must_use]
111    pub fn with_chat_heading(mut self, heading: impl Into<String>) -> Self {
112        self.chat_heading = Some(heading.into());
113        self
114    }
115
116    /// Marks the call as spending money: the high-risk column, never **Always allow**.
117    #[must_use]
118    pub fn spends_money(mut self) -> Self {
119        self.money = Some(true);
120        self
121    }
122
123    /// Says whether the call can be taken back.
124    #[must_use]
125    pub fn with_reversibility(mut self, reversibility: Reversibility) -> Self {
126        self.reversibility = Some(reversibility);
127        self
128    }
129
130    /// Removes **Always allow** from the card on every surface.
131    #[must_use]
132    pub fn without_always_allow(mut self) -> Self {
133        self.offer_always = Some(false);
134        self
135    }
136
137    /// Adds `step` to "How it got here", before "Asked at 10:02".
138    #[must_use]
139    pub fn with_first_step(mut self, step: impl Into<String>) -> Self {
140        self.first_step = Some(step.into());
141        self
142    }
143
144    /// Adds the line `detail` under the details.
145    #[must_use]
146    pub fn with_detail(mut self, detail: CardDetail) -> Self {
147        self.detail = Some(detail);
148        self
149    }
150
151    /// Says what the call's images are and where they go (spec 3.7 §8.2).
152    #[must_use]
153    pub fn with_media(mut self, media: crate::evidence::MediaFacts) -> Self {
154        self.media = Some(media);
155        self
156    }
157
158    /// This hint with `later`'s fields where this one sets none, keeping the stricter value of
159    /// `money` and `offer_always`.
160    pub(crate) fn then(self, later: Self) -> Self {
161        let money = (self.marks_money() || later.marks_money()).then_some(true);
162        let offer_always = (self.removes_always() || later.removes_always()).then_some(false);
163        Self {
164            heading: self.heading.or(later.heading),
165            chat_heading: self.chat_heading.or(later.chat_heading),
166            money,
167            reversibility: self.reversibility.or(later.reversibility),
168            offer_always,
169            first_step: self.first_step.or(later.first_step),
170            detail: self.detail.or(later.detail),
171            media: match (self.media, later.media) {
172                (Some(first), Some(second)) => Some(first.then(second)),
173                (first, second) => first.or(second),
174            },
175        }
176    }
177
178    /// The call spends money, as this hint says.
179    pub(crate) fn marks_money(&self) -> bool {
180        self.money == Some(true)
181    }
182
183    /// **Always allow** is not offered, as this hint says.
184    pub(crate) fn removes_always(&self) -> bool {
185        self.offer_always == Some(false)
186    }
187}
188
189/// A feature's hints for the decisions its tools ask (spec 3.3 §7.1), read by the engine
190/// wherever it draws a card.
191///
192/// Return `None` for every request that is not the feature's own, told by
193/// [`ApprovalRequest::origin`]. Read only `request` and the feature's own kernel-side data,
194/// never text an agent wrote; a failure to read that data is logged and answered with `None`
195/// or a hint that says less, since the card is shown either way.
196///
197/// # Example
198///
199/// ```rust
200/// use std::sync::Arc;
201/// use adk_core::ApprovalRequest;
202/// use adk_surface::{CardHint, CardHints, LocalSource, Reversibility, SurfaceEngine};
203///
204/// /// The cards of tools published as `verbs:adk-rust`.
205/// struct Verbs;
206///
207/// #[async_trait::async_trait]
208/// impl CardHints for Verbs {
209///     async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
210///         let origin = request.origin.as_ref()?;
211///         (origin.source == "verbs:adk-rust").then(|| {
212///             CardHint::new()
213///                 .with_chat_heading("Snooze something in Coming up")
214///                 .with_reversibility(Reversibility::CanBeChangedBack)
215///                 .without_always_allow()
216///         })
217///     }
218/// }
219///
220/// # fn example(source: LocalSource) {
221/// let engine = SurfaceEngine::builder(Arc::new(source)).card_hints(Arc::new(Verbs)).build();
222/// # let _ = engine;
223/// # }
224/// ```
225#[async_trait]
226pub trait CardHints: Send + Sync {
227    /// The hint for `request`, or `None` when it is not this feature's.
228    async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint>;
229
230    /// What `request`'s call acts on, as the person knows it — "News digest" — which the
231    /// record of an answer to it names beside the card's summary (spec 3.3 §8, §11). `None`,
232    /// the default, for a call that names nothing a person knows or that is not this
233    /// feature's.
234    async fn names(&self, _request: &ApprovalRequest) -> Option<String> {
235        None
236    }
237}
238
239/// What `request`'s call acts on, as the first of `hints` that names it says, or for a decision
240/// the kernel itself asks, what it is about: the agent to add, the agenda item, the driver
241/// (spec 3.3 §8).
242pub(crate) async fn named(
243    hints: &[Arc<dyn CardHints>],
244    request: &ApprovalRequest,
245) -> Option<String> {
246    for hints in hints {
247        if let Some(name) = hints.names(request).await {
248            return Some(name);
249        }
250    }
251    crate::project::kernel_name(request)
252}
253
254#[cfg(test)]
255mod tests {
256    use adk_core::{
257        ApprovalPolicy, ApprovalRisk, ApprovalScope, ApproverSelector, ToolConfirmationRequest,
258    };
259    use chrono::FixedOffset;
260    use proptest::prelude::*;
261    use serde_json::json;
262
263    use super::*;
264    use crate::origin::{Caller, Origin, SurfaceKind};
265    use crate::project::Projector;
266    use crate::rules::{Answer, allowed_answers};
267
268    fn words() -> impl Strategy<Value = Option<String>> {
269        proptest::option::of("[A-Za-z ]{1,12}")
270    }
271
272    fn reversibility() -> impl Strategy<Value = Option<Reversibility>> {
273        proptest::option::of(prop_oneof![
274            Just(Reversibility::CantBeUnsent),
275            Just(Reversibility::CantBeUndone),
276            Just(Reversibility::CanBeRemoved),
277            Just(Reversibility::CanBeChangedBack),
278        ])
279    }
280
281    fn hint() -> impl Strategy<Value = CardHint> {
282        (
283            (words(), words(), any::<Option<bool>>()),
284            (reversibility(), any::<Option<bool>>(), words(), words()),
285        )
286            .prop_map(
287                |((heading, chat_heading, money), (reversibility, offer_always, step, detail))| {
288                    CardHint {
289                        heading,
290                        chat_heading,
291                        money,
292                        reversibility,
293                        offer_always,
294                        first_step: step,
295                        detail: detail.map(CardDetail::new),
296                        media: None,
297                    }
298                },
299            )
300    }
301
302    fn caller(row: usize) -> Caller {
303        let (surface, origin) = match row {
304            0 => (SurfaceKind::Web, Origin::Pointer),
305            1 => (SurfaceKind::Terminal, Origin::Keyboard),
306            2 => (SurfaceKind::Phone, Origin::Touch),
307            3 => (SurfaceKind::Tray, Origin::Pointer),
308            4 => (SurfaceKind::Chat, Origin::Chat { channel: "Telegram".into() }),
309            _ => (SurfaceKind::Web, Origin::Voice),
310        };
311        let caller = Caller::human("ana", surface, origin);
312        if row == 1 { caller.with_paired_local() } else { caller }
313    }
314
315    proptest! {
316        #![proptest_config(ProptestConfig::with_cases(256))]
317
318        /// Spec 3.3 §7.1: the first hint that sets a field wins; money and Always allow keep
319        /// the stricter value any hint gives.
320        #[test]
321        fn hints_merge_first_wins_and_stricter_counts(hints in proptest::collection::vec(hint(), 0..5)) {
322            let merged = hints.iter().cloned().fold(CardHint::new(), CardHint::then);
323            let first = |field: fn(&CardHint) -> Option<String>| hints.iter().find_map(field);
324            prop_assert_eq!(merged.heading.clone(), first(|hint| hint.heading.clone()));
325            prop_assert_eq!(merged.chat_heading.clone(), first(|hint| hint.chat_heading.clone()));
326            prop_assert_eq!(merged.first_step.clone(), first(|hint| hint.first_step.clone()));
327            prop_assert_eq!(
328                merged.detail.clone(),
329                hints.iter().find_map(|hint| hint.detail.clone())
330            );
331            prop_assert_eq!(merged.reversibility, hints.iter().find_map(|hint| hint.reversibility));
332            prop_assert_eq!(merged.marks_money(), hints.iter().any(CardHint::marks_money));
333            prop_assert_eq!(merged.removes_always(), hints.iter().any(CardHint::removes_always));
334        }
335
336        /// Spec 3.3 §7.2: whatever a hint says, every surface may give no answer it could not
337        /// give without it, the risk is the inbox entry's, and money is never unmarked.
338        #[test]
339        fn a_hint_never_adds_an_answer_or_changes_the_risk(
340            hints in proptest::collection::vec(hint(), 0..4),
341            risk in prop_oneof![
342                Just(ApprovalRisk::Low),
343                Just(ApprovalRisk::Medium),
344                Just(ApprovalRisk::High),
345                Just(ApprovalRisk::Critical),
346            ],
347            tool in prop_oneof![Just("payments_charge"), Just("send_email"), Just("verb_snooze")],
348            always in any::<bool>(),
349            row in 0usize..6,
350        ) {
351            let merged = hints.into_iter().fold(CardHint::new(), CardHint::then);
352            let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
353            let call = ToolConfirmationRequest::new(tool, json!({ "to": "[client email]" }));
354            let request = adk_core::ApprovalRequest::new(
355                "apr-1",
356                ApprovalScope::new("adk-rust", "ana", "s1"),
357                &call,
358                ApprovalPolicy::new([ApproverSelector::human("ana")]),
359            )
360            .with_risk(risk);
361            let label = always.then(|| "Always allow for this person".to_string());
362            let plain = projector.facts(&request, label.clone(), &CardHint::new());
363            let hinted = projector.facts(&request, label, &merged);
364            prop_assert_eq!(hinted.risk, plain.risk);
365            prop_assert_eq!(&hinted.allows, &plain.allows);
366            prop_assert!(hinted.money || !plain.money);
367            let caller = caller(row);
368            let answers = |facts| -> Vec<Answer> {
369                allowed_answers(&caller, facts).options.iter().map(|option| option.answer).collect()
370            };
371            let (before, after) = (answers(&plain), answers(&hinted));
372            prop_assert!(after.iter().all(|answer| before.contains(answer)), "{before:?} → {after:?}");
373        }
374    }
375}